diff --git a/internal/claude/claude.go b/internal/claude/claude.go index 6ef01238..59b66db1 100644 --- a/internal/claude/claude.go +++ b/internal/claude/claude.go @@ -474,14 +474,39 @@ func (s *session) emit(frame protocol.ChatEventFrame) { targets = append(targets, ch) } s.mu.Unlock() + lifecycle := frameIsLifecycle(frame) for _, ch := range targets { select { case ch <- frame: + continue default: } + if !lifecycle { + continue + } + // A full watcher may lose a delta (the hub repairs text from + // history), but never a step start or end: a lost end leaves the + // turn "working" forever. Wait, bounded, for the watcher to drain. + timer := time.NewTimer(lifecycleDeliveryTimeout) + select { + case ch <- frame: + case <-timer.C: + log.Printf("claude session %s: a watcher did not accept the %s frame within %s; it was dropped", s.id, frame.Kind, lifecycleDeliveryTimeout) + } + timer.Stop() } } +// lifecycleDeliveryTimeout bounds how long emit waits for a full watcher to +// accept a turn lifecycle frame before it gives up on that watcher. +var lifecycleDeliveryTimeout = 5 * time.Second + +// frameIsLifecycle reports whether a frame changes the turn's state, so it +// must reach every watcher even when that watcher's buffer is full. +func frameIsLifecycle(frame protocol.ChatEventFrame) bool { + return frame.Kind == protocol.ChatEventStep || frame.Kind == protocol.ChatEventResync +} + func (s *session) subscribe() chan protocol.ChatEventFrame { ch := make(chan protocol.ChatEventFrame, 256) s.mu.Lock() diff --git a/internal/claude/emit_lifecycle_test.go b/internal/claude/emit_lifecycle_test.go new file mode 100644 index 00000000..6577e5c3 --- /dev/null +++ b/internal/claude/emit_lifecycle_test.go @@ -0,0 +1,61 @@ +package claude + +import ( + "context" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// A watcher whose buffer is full of streamed text may lose a delta, but never +// the turn's end: a lost end left the chat "working" forever. +func TestEmitDeliversTheTurnEndToAFullWatcher(t *testing.T) { + c := newChat(context.Background()) + t.Cleanup(c.cancel) + s := c.sessionFor("ses_full", t.TempDir()) + ch := s.subscribe() + defer s.unsubscribe(ch) + for len(ch) < cap(ch) { + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}}) + } + emitted := make(chan struct{}) + go func() { + defer close(emitted) + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}) + }() + // The watcher is slow, not gone: it drains only after the end was emitted. + time.Sleep(100 * time.Millisecond) + deadline := time.After(3 * time.Second) + for { + select { + case frame := <-ch: + if frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded { + <-emitted + return + } + case <-deadline: + t.Fatal("the turn end never reached the full watcher") + } + } +} + +// A watcher that never drains does not hold the CLI reader forever. +func TestEmitGivesUpOnAStuckWatcher(t *testing.T) { + prior := lifecycleDeliveryTimeout + lifecycleDeliveryTimeout = 50 * time.Millisecond + t.Cleanup(func() { lifecycleDeliveryTimeout = prior }) + c := newChat(context.Background()) + t.Cleanup(c.cancel) + s := c.sessionFor("ses_stuck", t.TempDir()) + ch := s.subscribe() + defer s.unsubscribe(ch) + for len(ch) < cap(ch) { + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}}) + } + start := time.Now() + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}) + if waited := time.Since(start); waited > 2*time.Second { + t.Fatalf("emit blocked %s on a stuck watcher", waited) + } +} diff --git a/internal/server/chat_lost_end_test.go b/internal/server/chat_lost_end_test.go new file mode 100644 index 00000000..99db772e --- /dev/null +++ b/internal/server/chat_lost_end_test.go @@ -0,0 +1,90 @@ +package server + +import ( + "context" + "path/filepath" + "sync" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// reportingChat is an observedChat that also reports its turn state without +// I/O, as Claude Code does. +type reportingChat struct { + *observedChat + rmu sync.Mutex + running bool +} + +func (c *reportingChat) TurnRunning(string) bool { + c.rmu.Lock() + defer c.rmu.Unlock() + return c.running +} + +// Prompt starts a turn, as Claude Code's does before it returns. +func (c *reportingChat) Prompt(ctx context.Context, sessionID, text string) error { + if err := c.observedChat.Prompt(ctx, sessionID, text); err != nil { + return err + } + c.setRunning(true) + return nil +} + +func (c *reportingChat) setRunning(running bool) { + c.rmu.Lock() + c.running = running + c.rmu.Unlock() +} + +// The live incident: a Claude turn's end frame was dropped on the way (a full +// watcher buffer), so the room's own turn stayed "working" forever and every +// later prompt queued behind it. Once the harness reports itself idle for the +// settle period and its probe agrees, the turn is ended, the client told to +// resync, and the queued prompt delivered. While it reports running, it waits. +func TestChatRunnerEndsItsTurnWhoseEndFrameWasLost(t *testing.T) { + fastUnattended(t) + fastStaleTurnSettle(t) + t.Setenv("PIPELINES_NTFY_URL", "") + store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db")) + broker := &reportingChat{observedChat: newObservedChat()} + server := startQueueServer(t, broker, store) + conn := dialChatConn(t, server.ctx, server.srv) + broker.setProbe(true) + sendPrompt(t, server.ctx, conn, "p1", "build it", "op-1") + waitFor(t, "first prompt", func() bool { return broker.promptCount() == 1 }) + broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_1")) + waitStepFrame(t, server.ctx, conn, protocol.ChatStepStarted, "turn_1") + if ack := sendPrompt(t, server.ctx, conn, "p2", "continue", "op-2"); !ack.ChatQueued { + t.Fatalf("second prompt was not queued behind the running turn: %+v", ack) + } + time.Sleep(4 * chatQueueStaleTurnSettle) + if n := broker.promptCount(); n != 1 { + t.Fatalf("prompt delivered while the harness reports its turn running: %v", broker.promptTexts()) + } + // The turn ends in the harness, but its end frame never arrives. + broker.setRunning(false) + broker.setProbe(false) + sawResync := false + for { + message := readChatMessage(t, server.ctx, conn) + if message.Type != protocol.ChatEvent || message.ChatEvent == nil { + continue + } + if message.ChatEvent.Kind == protocol.ChatEventResync { + sawResync = true + } + if step := message.ChatEvent.Step; step != nil && step.Status == protocol.ChatStepEnded && step.TurnID == "turn_1" { + break + } + } + if !sawResync { + t.Fatal("the client was not told to resync after the lost end") + } + waitFor(t, "queued prompt delivered after the lost end", func() bool { return broker.promptCount() == 2 }) + if texts := broker.promptTexts(); texts[1] != "continue" { + t.Fatalf("delivered = %v", texts) + } +} diff --git a/internal/server/chat_manager.go b/internal/server/chat_manager.go index 533d5d9a..d5340735 100644 --- a/internal/server/chat_manager.go +++ b/internal/server/chat_manager.go @@ -834,6 +834,20 @@ func (m *chatManager) TurnRunning(sessionID string) bool { return ok && reporter.TurnRunning(sessionID) } +// TracksTurnState reports whether the routed harness reports its own turn +// state through TurnRunning (Claude Code does; OpenCode and Codex are probed). +func (m *chatManager) TracksTurnState(sessionID string) bool { + m.mu.Lock() + backend := m.cache[sessionID] + m.mu.Unlock() + adapter := m.opencode + if backend != "" && backend != "opencode" { + adapter = m.attached(backend) + } + _, ok := adapter.(chatTurnReporter) + return ok +} + // ProbeTurn asks the session's own harness whether a turn is in flight. It is // the server-start probe (chat_unattended.go): a harness that can be asked // (OpenCode, Codex) is asked; otherwise its in-memory state is used, which for diff --git a/internal/server/chat_queue.go b/internal/server/chat_queue.go index 2f5d26a6..1a266e7c 100644 --- a/internal/server/chat_queue.go +++ b/internal/server/chat_queue.go @@ -190,6 +190,22 @@ func errChatQueueFull(sessionID string) error { return errors.New("session " + sessionID + " already has the maximum number of prompts queued") } +// chatTurnTracker is implemented by a broker that routes to several harnesses +// and knows whether the one serving a session reports its own turn state. +type chatTurnTracker interface { + TracksTurnState(sessionID string) bool +} + +// brokerTracksTurns reports whether brokerTurnRunning's answer for sessionID +// comes from a harness that tracks its turn, rather than a constant false. +func brokerTracksTurns(broker chatBroker, sessionID string) bool { + if tracker, ok := broker.(chatTurnTracker); ok { + return tracker.TracksTurnState(sessionID) + } + _, ok := broker.(chatTurnReporter) + return ok +} + // brokerTurnRunning asks a harness that knows its own turn state without I/O. func brokerTurnRunning(broker chatBroker, sessionID string) bool { reporter, ok := broker.(chatTurnReporter) diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 85a69615..a6459c59 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -925,10 +925,96 @@ func (h *chatHub) runTurn(room *chatRoom, p *chatQueuedPrompt, done chan struct{ // 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.startRoomPoller(room, broker) - select { - case <-done: - case <-room.ctx.Done(): + h.awaitTurnEnd(room, broker, done) +} + +// awaitTurnEnd waits for the turn runner's turn to end. Its end normally +// arrives as a step frame; the safety net covers an end that was lost on the +// way (a full watcher buffer, a stream that reconnected): once a harness that +// tracks its own turn state has reported itself idle for the settle period +// (chatQueueStaleTurnSettle) and its own probe confirms no turn is in flight, +// the turn is ended here and attached clients re-read the history. A harness +// that cannot report or be probed is never second-guessed. +func (h *chatHub) awaitTurnEnd(room *chatRoom, broker chatBroker, done chan struct{}) { + prober, probes := broker.(chatTurnProber) + if !probes || !brokerTracksTurns(broker, room.sessionID) { + select { + case <-done: + case <-room.ctx.Done(): + } + return } + settle := h.unattended.staleTurn + if settle <= 0 { + settle = 10 * time.Second + } + ticker := time.NewTicker(min(chatQueueBusyPoll, settle/4)) + defer ticker.Stop() + var idleSince time.Time + for { + select { + case <-done: + return + case <-room.ctx.Done(): + return + case <-ticker.C: + } + if brokerTurnRunning(broker, room.sessionID) { + idleSince = time.Time{} + continue + } + now := h.clock() + if idleSince.IsZero() { + idleSince = now + } + if now.Sub(idleSince) < settle { + continue + } + probeCtx, cancel := context.WithTimeout(room.ctx, 5*time.Second) + busy, err := prober.ProbeTurn(probeCtx, room.sessionID) + cancel() + if err != nil || busy { + // Look again only after another settle period. + idleSince = h.clock() + continue + } + if h.endLostTurn(room, done, now.Sub(idleSince)) { + return + } + } +} + +// endLostTurn ends the runner's turn whose end frame never arrived, exactly +// as that frame would have, and asks attached clients to resync. It reports +// false when the turn already ended (or the room was released) meanwhile. +func (h *chatHub) endLostTurn(room *chatRoom, done chan struct{}, idle time.Duration) bool { + h.mu.Lock() + if h.rooms[room.sessionID] != room || room.ctx.Err() != nil || room.turnDone != done { + h.mu.Unlock() + return true + } + log.Printf("chat session %s: the harness reports no turn running for %s but the turn %q never reported its end; ending it", + room.sessionID, idle.Round(time.Second), room.nativeTurnID) + end := protocol.ChatEventFrame{SessionID: room.sessionID, NativeTurnID: room.nativeTurnID, Kind: protocol.ChatEventStep, + Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: room.nativeTurnID}} + priorStep := h.turnLocked(room.sessionID).step + h.applyLocked(end) + h.noteTurnDiffLocked(room, end) + h.noteReplyAttentionLocked(priorStep, end) + h.finishTurnLocked(room) + resync := protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventResync} + var slow []*chatSub + for _, sub := range room.subs { + if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) || + !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) { + slow = append(slow, sub) + } + } + h.mu.Unlock() + for _, sub := range slow { + sub.close() + } + return true } // endRoomTurn releases the turn slot after a prompt that never entered flight,