Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8346: fix(agent): handle Claude Code session and weekly limits (#9652)

inoisy828e0c927eb6
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index c6e57328c4..327fb86801 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -33,6 +33,24 @@ func claudeTerminateGrace() time.Duration {
return 5 * time.Second
}
+// claudeErrorResultGraceNanos optionally overrides, in nanoseconds, how long
+// claude may keep running after it reported an error result. Set via atomic
+// store in tests; zero keeps the default.
+var claudeErrorResultGraceNanos atomic.Int64
+
+// claudeErrorResultGrace bounds the wait for claude to exit after an error
+// result. With stdin closed the CLI still stays alive while any background
+// task it started is running, then opens a new turn when the task ends. After
+// an error result (a spent session limit, an API failure) that turn cannot
+// change the outcome, so the daemon stops waiting instead of holding the run
+// open for the task's lifetime.
+func claudeErrorResultGrace() time.Duration {
+ if n := claudeErrorResultGraceNanos.Load(); n > 0 {
+ return time.Duration(n)
+ }
+ return 10 * time.Second
+}
+
// claudeBackend implements Backend by spawning the Claude Code CLI
// with --output-format stream-json.
type claudeBackend struct {
@@ -210,6 +228,22 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
unreadableAssistantCount := 0
controlErrors := make(chan error, 1)
var controlWrites sync.WaitGroup
+ var stopAfterErrorResultOnce sync.Once
+ // stopAfterErrorResult terminates a claude that outlives its error
+ // result past the grace period, the same way cancellation does.
+ stopAfterErrorResult := func() {
+ select {
+ case <-procDone:
+ return
+ case <-time.After(claudeErrorResultGrace()):
+ }
+ b.cfg.Logger.Warn("claude still running after an error result; terminating process group", "pid", cmd.Process.Pid)
+ signalProcessGroup(cmd, syscall.SIGTERM)
+ if !waitProcessGroupGone(cmd, claudeTerminateGrace()) {
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ }
+ _ = stdout.Close()
+ }
// On cancellation / timeout, terminate claude (and every MCP server and
// tool subprocess it spawned) BEFORE unblocking the scanner. EOF stdin
@@ -304,6 +338,9 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
}
closeStdin()
+ if resultIsError || terminalReasonError != "" {
+ stopAfterErrorResultOnce.Do(func() { go stopAfterErrorResult() })
+ }
case "log":
if msg.Log != nil {
trySend(msgCh, Message{
diff --git a/server/pkg/agent/claude_cancel_unix_test.go b/server/pkg/agent/claude_cancel_unix_test.go
index 2ea076de3d..858561d5f8 100644
--- a/server/pkg/agent/claude_cancel_unix_test.go
+++ b/server/pkg/agent/claude_cancel_unix_test.go
@@ -6,6 +6,7 @@ import (
"context"
"log/slog"
"path/filepath"
+ "strings"
"testing"
"time"
)
@@ -144,3 +145,72 @@ func runClaudeCancellationTest(t *testing.T, script string) {
waitProcessGone(t, pid)
}
}
+
+// claudeErrorResultFakeScript impersonates claude after a spent session limit
+// while a background task is still running: it reports an error result, then
+// stays alive (as the CLI does until its background tasks end) with a
+// grandchild standing in for the never-ending background command.
+func claudeErrorResultFakeScript() string {
+ return "#!/bin/sh\n" + "trap 'exit 0' TERM\n" +
+ `( sleep 300 ) &
+child=$!
+if [ -n "$CLAUDE_PID_FILE" ]; then
+ printf '%s %s\n' "$$" "$child" > "$CLAUDE_PID_FILE"
+fi
+printf '{"type":"system","session_id":"ses_fake"}\n'
+printf '{"type":"result","subtype":"success","is_error":true,"result":"You'"'"'ve hit your session limit · resets 2pm (UTC)","session_id":"ses_fake"}\n'
+while true; do
+ sleep 0.1
+done
+`
+}
+
+// TestClaudeErrorResultTerminatesLingeringProcess verifies that a claude which
+// keeps running after an error result (it waits for a background task) is
+// stopped after the grace period: the run fails with the result's error
+// instead of hanging until the background task ends.
+func TestClaudeErrorResultTerminatesLingeringProcess(t *testing.T) {
+ claudeErrorResultGraceNanos.Store(int64(200 * time.Millisecond))
+ t.Cleanup(func() { claudeErrorResultGraceNanos.Store(0) })
+
+ tempDir := t.TempDir()
+ pidFile := filepath.Join(tempDir, "pids")
+ fakePath := filepath.Join(tempDir, "claude")
+ writeTestExecutable(t, fakePath, []byte(claudeErrorResultFakeScript()))
+
+ backend, err := New("claude", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.Default(),
+ Env: map[string]string{"CLAUDE_PID_FILE": pidFile},
+ })
+ if err != nil {
+ t.Fatalf("new claude backend: %v", err)
+ }
+
+ session, err := backend.Execute(context.Background(), "prompt-ignored", ExecOptions{Cwd: tempDir})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ pids := waitForPids(t, pidFile)
+
+ select {
+ case res := <-session.Result:
+ if res.Status != "failed" {
+ t.Errorf("status = %q, want failed", res.Status)
+ }
+ if !strings.Contains(res.Error, "hit your session limit") {
+ t.Errorf("error = %q, want the result's session limit text", res.Error)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("Execute did not return after an error result while claude kept running")
+ }
+
+ for _, pid := range pids {
+ waitProcessGone(t, pid)
+ }
+}
diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.go
index 4919c7f4dc..286fae4b9b 100644
--- a/server/pkg/taskfailure/classify.go
+++ b/server/pkg/taskfailure/classify.go
@@ -191,6 +191,12 @@ func Classify(rawError string) Reason {
// would not match the curly form either, so this is a small
// in-flight improvement on top of the SQL classifier.
"you\u2019ve hit your limit",
+ // Claude Code's subscription windows: "You've hit your session
+ // limit \u00b7 resets 2pm (UTC)" and "You've hit your weekly limit
+ // \u00b7 resets <date>". Matched without the apostrophe so both
+ // quote forms land here.
+ "hit your session limit",
+ "hit your weekly limit",
"credits",
"quota",
):
diff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.go
index a8b83a9072..91052d9b97 100644
--- a/server/pkg/taskfailure/classify_test.go
+++ b/server/pkg/taskfailure/classify_test.go
@@ -75,6 +75,9 @@ func TestClassifyRules(t *testing.T) {
{"usage limit", "Account exceeded the daily usage limit", ReasonAgentProviderQuotaLimit},
{"hit your limit ascii", "you've hit your limit; upgrade to continue", ReasonAgentProviderQuotaLimit},
{"hit your limit curly", "you\u2019ve hit your limit", ReasonAgentProviderQuotaLimit},
+ {"session limit ascii", "You've hit your session limit \u00b7 resets 2pm (UTC)", ReasonAgentProviderQuotaLimit},
+ {"session limit curly", "You\u2019ve hit your session limit \u00b7 resets 2pm (UTC)", ReasonAgentProviderQuotaLimit},
+ {"weekly limit", "You've hit your weekly limit \u00b7 resets Nov 3, 9am (UTC)", ReasonAgentProviderQuotaLimit},
{"credits", "Your account has 0 credits remaining", ReasonAgentProviderQuotaLimit},
{"quota", "quota exceeded for project foo", ReasonAgentProviderQuotaLimit},