Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): report task usage before cancel check (#1180)
joyanup4c1fd6021521
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 99e09fddac..a81b5a8e9e 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -26,6 +26,20 @@ import (// server refresh.var ErrRepoNotConfigured = errors.New("repo is not configured for this workspace")+// taskRunner executes a single agent task and returns the result.+// Extracted as an interface so tests can inject a fake without spawning real+// agent processes, while keeping test scaffolding out of the production struct.+type taskRunner interface {+ run(ctx context.Context, task Task, provider string, slot int, log *slog.Logger) (TaskResult, error)+}++// taskRunnerFunc adapts a plain function to the taskRunner interface.+type taskRunnerFunc func(context.Context, Task, string, int, *slog.Logger) (TaskResult, error)++func (f taskRunnerFunc) run(ctx context.Context, task Task, provider string, slot int, log *slog.Logger) (TaskResult, error) {+ return f(ctx, task, provider, slot, log)+}+var (isBrewInstall = cli.IsBrewInstallgetBrewPrefix = cli.GetBrewPrefix@@ -107,6 +121,9 @@ type Daemon struct {// goroutine can race against t.TempDir cleanup, leaving a partially// deleted bare clone and an unrelated `not empty` cleanup failure.bgSyncs sync.WaitGroup++ runner taskRunner // executes agent tasks; set to d.runTask by New(), overridable in tests+ cancelPollInterval time.Duration // how often handleTask polls for server-side cancellation; overridable in tests}// New creates a new Daemon instance.@@ -116,7 +133,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {// Tag every daemon HTTP request with the daemon's CLI version so the// server can split logs/metrics by client version (parallel to the CLI).client.SetVersion(cfg.CLIVersion)- return &Daemon{+ d := &Daemon{cfg: cfg,client: client,repoCache: repocache.New(cacheRoot, logger),@@ -130,7 +147,10 @@ func New(cfg Config, logger *slog.Logger) *Daemon {runtimeGoneInflight: make(map[string]struct{}),reregisterNextAttempt: make(map[string]time.Time),reregisterLastCompletedAt: make(map[string]time.Time),+ cancelPollInterval: 5 * time.Second,}+ d.runner = taskRunnerFunc(d.runTask)+ return d}// setAgentVersion records the detected CLI version for an agent provider so@@ -1848,7 +1868,14 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {runCtx, runCancel := context.WithCancel(ctx)defer runCancel()- cancelledByPoll := d.watchTaskCancellation(runCtx, task.ID, 5*time.Second, taskLog)+ // Poll interval is d.cancelPollInterval (5s in production, reduced in tests+ // via direct field override). Guard against zero so a misconfigured daemon+ // doesn't panic time.NewTicker.+ pollInterval := d.cancelPollInterval+ if pollInterval == 0 {+ pollInterval = 5 * time.Second+ }+ cancelledByPoll := d.watchTaskCancellation(runCtx, task.ID, pollInterval, taskLog)go func() {select {case <-cancelledByPoll:@@ -1857,7 +1884,18 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {}}()- result, err := d.runTask(runCtx, task, provider, slot, taskLog)+ result, err := d.runner.run(runCtx, task, provider, slot, taskLog)++ // Report usage before any early return — the agent accumulates tokens+ // whether the task completes, errors, or is cancelled mid-run by the poll+ // goroutine. Both claude.go and codex.go populate result.Usage even when+ // runCtx is cancelled, so dropping this on the cancelled path silently+ // under-reports billing.+ if len(result.Usage) > 0 {+ if usageErr := d.client.ReportTaskUsage(ctx, task.ID, result.Usage); usageErr != nil {+ taskLog.Warn("report task usage failed", "error", usageErr)+ }+ }// Check if we were cancelled by the polling goroutine.select {@@ -1888,13 +1926,6 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {return}- // Report usage independently so it's captured even for failed/blocked tasks.- if len(result.Usage) > 0 {- if err := d.client.ReportTaskUsage(ctx, task.ID, result.Usage); err != nil {- taskLog.Warn("report task usage failed", "error", err)- }- }-d.reportTaskResult(ctx, task.ID, result, taskLog)// Write GC metadata after the task finishes so the periodic GC loopdiff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 3b02c6a434..97030685ba 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -1513,3 +1513,202 @@ func TestReportTaskResult_NonCompletedHitsFailEndpoint(t *testing.T) {})}}++// TestHandleTask_ReportsUsageBeforeCancel verifies that ReportTaskUsage is called+// even when the server marks the task as cancelled during the post-run status+// check. Regression test for the ordering bug where the cancel check ran before+// usage was reported, silently discarding accumulated tokens.+func TestHandleTask_ReportsUsageBeforeCancel(t *testing.T) {+ t.Parallel()++ var callOrder []string+ var mu sync.Mutex+ recordCall := func(name string) {+ mu.Lock()+ callOrder = append(callOrder, name)+ mu.Unlock()+ }++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/start"):+ recordCall("start")+ w.WriteHeader(http.StatusOK)+ case strings.HasSuffix(r.URL.Path, "/progress"):+ w.WriteHeader(http.StatusOK)+ case strings.HasSuffix(r.URL.Path, "/usage"):+ recordCall("usage")+ w.WriteHeader(http.StatusOK)+ case strings.HasSuffix(r.URL.Path, "/status"):+ recordCall("status")+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"status":"cancelled"}`))+ default:+ w.WriteHeader(http.StatusOK)+ }+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ workspaces: make(map[string]*workspaceState),+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "claude"}},+ cancelPollInterval: time.Hour, // effectively disable poll-cancel path; we want the post-run status check+ }++ // Inject a fake runner that returns a result with usage tokens, bypassing+ // real agent process execution.+ d.runner = taskRunnerFunc(func(_ context.Context, _ Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {+ return TaskResult{+ Status: "completed",+ Usage: []TaskUsageEntry{+ {Provider: "anthropic", Model: "claude-opus-4-6", InputTokens: 100, OutputTokens: 50},+ },+ }, nil+ })++ task := Task{+ ID: "task-abc",+ RuntimeID: "rt-1",+ IssueID: "issue-xyz",+ Agent: &AgentData{Name: "test-agent"},+ }++ d.handleTask(context.Background(), task, 0)++ mu.Lock()+ order := make([]string, len(callOrder))+ copy(order, callOrder)+ mu.Unlock()++ // usage must appear before status in the call order.+ usageIdx, statusIdx := -1, -1+ for i, name := range order {+ switch name {+ case "usage":+ usageIdx = i+ case "status":+ statusIdx = i+ }+ }++ if usageIdx == -1 {+ t.Fatal("ReportTaskUsage was never called — usage is lost for cancelled tasks")+ }+ if statusIdx == -1 {+ t.Fatal("GetTaskStatus was never called")+ }+ if usageIdx > statusIdx {+ t.Fatalf("usage was reported AFTER status check (order: %v) — regression", order)+ }+}++// TestHandleTask_ReportsUsageWhenCancelledByPoll verifies that ReportTaskUsage is+// called even when the task is cancelled mid-execution by the poll goroutine.+// Regression test for the cancelledByPoll early-return path that previously+// discarded accumulated usage before calling ReportTaskUsage.+func TestHandleTask_ReportsUsageWhenCancelledByPoll(t *testing.T) {+ t.Parallel()++ var callOrder []string+ var mu sync.Mutex+ recordCall := func(name string) {+ mu.Lock()+ callOrder = append(callOrder, name)+ mu.Unlock()+ }++ // statusCallCount lets the poll goroutine return "cancelled" on first call+ // while still handling later calls from the post-run status check.+ var statusCallCount atomic.Int64++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/start"):+ w.WriteHeader(http.StatusOK)+ case strings.HasSuffix(r.URL.Path, "/progress"):+ w.WriteHeader(http.StatusOK)+ case strings.HasSuffix(r.URL.Path, "/usage"):+ recordCall("usage")+ w.WriteHeader(http.StatusOK)+ case strings.HasSuffix(r.URL.Path, "/status"):+ // First call is from the poll goroutine — return "cancelled" to+ // trigger runCancel() and close(cancelledByPoll).+ if statusCallCount.Add(1) == 1 {+ recordCall("poll-status")+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"status":"cancelled"}`))+ } else {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"status":"running"}`))+ }+ default:+ w.WriteHeader(http.StatusOK)+ }+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ workspaces: make(map[string]*workspaceState),+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "claude"}},+ cancelPollInterval: 10 * time.Millisecond, // fire quickly so test is fast+ }++ // Inject a runner that blocks until runCtx is cancelled (simulating a real+ // agent being interrupted), then returns usage tokens as claude.go does.+ d.runner = taskRunnerFunc(func(runCtx context.Context, _ Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {+ <-runCtx.Done()+ return TaskResult{+ Status: "aborted",+ Usage: []TaskUsageEntry{+ {Provider: "anthropic", Model: "claude-opus-4-6", InputTokens: 200, OutputTokens: 80},+ },+ }, nil+ })++ task := Task{+ ID: "task-poll",+ RuntimeID: "rt-1",+ IssueID: "issue-poll",+ Agent: &AgentData{Name: "test-agent"},+ }++ d.handleTask(context.Background(), task, 0)++ mu.Lock()+ order := make([]string, len(callOrder))+ copy(order, callOrder)+ mu.Unlock()++ // Verify the poll goroutine actually fired — without this assertion the test+ // could pass via the post-run GetTaskStatus check without ever taking the+ // cancelledByPoll path, making it a vacuous regression guard.+ pollStatusIdx := -1+ usageIdx := -1+ for i, name := range order {+ switch name {+ case "poll-status":+ pollStatusIdx = i+ case "usage":+ usageIdx = i+ }+ }+ if pollStatusIdx == -1 {+ t.Fatalf("poll goroutine never fired (order: %v) — cancelledByPoll path not exercised", order)+ }+ if usageIdx == -1 {+ t.Fatalf("ReportTaskUsage was never called on poll-cancelled path (order: %v) — tokens lost", order)+ }+ // poll-status must precede usage: poll fires → runCtx cancelled → runner unblocks → usage flushed.+ // If usage comes first, usage was reported before the runner was interrupted, which is impossible+ // given that the runner blocks on runCtx.Done().+ if usageIdx < pollStatusIdx {+ t.Fatalf("usage reported before poll-status (order: %v) — poll-status must come first", order)+ }+}