diff --git a/internal/gateway/claude_output_drain_test.go b/internal/gateway/claude_output_drain_test.go index e9afb33d0..4e18c0bdb 100644 --- a/internal/gateway/claude_output_drain_test.go +++ b/internal/gateway/claude_output_drain_test.go @@ -88,4 +88,14 @@ func TestClaudeEndedBeforeItsInputSaysWhy(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "ended by magpie") || strings.Contains(err.Error(), "signal") { t.Errorf("a write after magpie ended Claude Code: %v", err) } + // at once, before Claude Code has been reaped (red on ubuntu CI, where + // the write went into a pipe still open and nothing was said) + run, _, err := s.subscription.start(context.Background(), req, "claude-sonnet-5", "", "", nil) + if err != nil { + t.Fatal(err) + } + run.abort() + if err := run.setEffort("high"); err == nil || !strings.Contains(err.Error(), "ended by magpie") { + t.Errorf("a write right after magpie ended Claude Code: %v", err) + } } diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index c0af0d1b8..8d390af52 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -2884,6 +2884,14 @@ func (r *subscriptionRun) launch() error { // how it ended, or that magpie ended it, and the last it wrote to stderr — // the cause comes last, after any warnings before it. func (r *subscriptionRun) tell(line []byte) error { + // one magpie ended is not written to: until Wait has reaped it, its + // input still takes a write, which no one will read + r.mu.Lock() + killed := r.killed + r.mu.Unlock() + if killed { + return r.whyEnded() + } _, err := r.stdin.Write(append(line, '\n')) if err == nil { return nil @@ -2899,6 +2907,12 @@ func (r *subscriptionRun) tell(line []byte) error { case <-time.After(outputDrain + time.Second): return err } + return r.whyEnded() +} + +// whyEnded says how the run's Claude Code ended, or that magpie ended it, +// and the last it wrote to stderr. +func (r *subscriptionRun) whyEnded() error { r.mu.Lock() defer r.mu.Unlock() why := "exited before it read its input"