Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): cancel running agent when task is deleted server-side (#2107)
DimaSb1be9ed27fc2
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 9211d91ec7..2c63cc16fb 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -39,6 +39,22 @@ func isWorkspaceNotFoundError(err error) bool {return strings.Contains(strings.ToLower(reqErr.Body), "workspace not found")}+// isTaskNotFoundError returns true if the error is a 404 with "task not found"+// body. The daemon uses this to detect that a task was deleted server-side+// (issue removed, agent reassigned, ...) while the local agent was still+// running, so it can interrupt the agent rather than letting it keep+// emitting tool calls against a dead task.+func isTaskNotFoundError(err error) bool {+ var reqErr *requestError+ if !errors.As(err, &reqErr) {+ return false+ }+ if reqErr.StatusCode != http.StatusNotFound {+ return false+ }+ return strings.Contains(strings.ToLower(reqErr.Body), "task not found")+}+// Client handles HTTP communication with the Multica server daemon API.type Client struct {baseURL stringdiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex e57319d8a2..88aae699d2 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -1344,6 +1344,60 @@ func newTaskSlotSemaphore(maxConcurrentTasks int) chan int {return sem}+// shouldInterruptAgent decides whether the running agent should be cancelled+// based on the latest GetTaskStatus call. Pure function so the decision is+// trivially testable; the polling goroutine in watchTaskCancellation is just+// I/O around it.+//+// Two cases trigger cancellation:+//+// 1. status == "cancelled" — the server moved the task to cancelled+// (issue reassigned, user cancel, ...).+// 2. err is a 404 with "task not found" — the task row was deleted while+// the agent was running. Without this we'd let the local agent keep+// emitting tool calls against a dead task for its full timeout window.+//+// All other errors (transient network, 5xx, ...) intentionally do NOT+// trigger cancellation — the next tick will retry and we don't want a+// flaky link to kill an in-flight agent.+func shouldInterruptAgent(status string, err error) bool {+ if err != nil {+ return isTaskNotFoundError(err)+ }+ return status == "cancelled"+}++// watchTaskCancellation polls the server for the task's status on the given+// interval and returns a channel that is closed when the running agent+// should be interrupted. The polling goroutine stops when ctx is cancelled,+// so callers should pass the runCtx that was set up around the agent run.+func (d *Daemon) watchTaskCancellation(ctx context.Context, taskID string, pollInterval time.Duration, taskLog *slog.Logger) <-chan struct{} {+ cancelled := make(chan struct{})+ go func() {+ ticker := time.NewTicker(pollInterval)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ status, err := d.client.GetTaskStatus(ctx, taskID)+ if !shouldInterruptAgent(status, err) {+ continue+ }+ if err != nil {+ taskLog.Info("task gone server-side, interrupting agent", "error", err)+ } else {+ taskLog.Info("task cancelled by server, interrupting agent")+ }+ close(cancelled)+ return+ }+ }+ }()+ return cancelled+}+func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {d.mu.Lock()rt := d.runtimeIndex[task.RuntimeID]@@ -1373,27 +1427,17 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {_ = d.client.ReportProgress(ctx, task.ID, fmt.Sprintf("Launching %s", provider), 1, 2)// Create a cancellable context so we can interrupt the running agent- // when the server-side task status changes to 'cancelled'.+ // when the server signals the task should stop — either status moves+ // to "cancelled" or the task row is deleted (404).runCtx, runCancel := context.WithCancel(ctx)defer runCancel()- // Poll for cancellation every 5 seconds while the task is running.- cancelledByPoll := make(chan struct{})+ cancelledByPoll := d.watchTaskCancellation(runCtx, task.ID, 5*time.Second, taskLog)go func() {- ticker := time.NewTicker(5 * time.Second)- defer ticker.Stop()- for {- select {- case <-runCtx.Done():- return- case <-ticker.C:- if status, err := d.client.GetTaskStatus(ctx, task.ID); err == nil && status == "cancelled" {- taskLog.Info("task cancelled by server, interrupting agent")- runCancel()- close(cancelledByPoll)- return- }- }+ select {+ case <-cancelledByPoll:+ runCancel()+ case <-runCtx.Done():}}()diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 85ef99fc95..31d78018c8 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -303,6 +303,197 @@ func TestIsWorkspaceNotFoundError(t *testing.T) {}}+func TestIsTaskNotFoundError(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ err error+ want bool+ }{+ {+ name: "404 with task not found body",+ err: &requestError{+ Method: http.MethodPost,+ Path: "/api/daemon/tasks/abc/messages",+ StatusCode: http.StatusNotFound,+ Body: `{"error":"task not found"}`,+ },+ want: true,+ },+ {+ name: "404 with mixed-case body still matches",+ err: &requestError{+ StatusCode: http.StatusNotFound,+ Body: `{"error":"Task Not Found"}`,+ },+ want: true,+ },+ {+ name: "500 with same body is not task-not-found",+ err: &requestError{+ StatusCode: http.StatusInternalServerError,+ Body: `{"error":"task not found"}`,+ },+ want: false,+ },+ {+ name: "404 with workspace-not-found body is not task-not-found",+ err: &requestError{+ StatusCode: http.StatusNotFound,+ Body: `{"error":"workspace not found"}`,+ },+ want: false,+ },+ {+ name: "non-requestError",+ err: errors.New("network down"),+ want: false,+ },+ {+ name: "nil",+ err: nil,+ want: false,+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := isTaskNotFoundError(tc.err); got != tc.want {+ t.Fatalf("isTaskNotFoundError(%v) = %v, want %v", tc.err, got, tc.want)+ }+ })+ }+}++func TestShouldInterruptAgent(t *testing.T) {+ t.Parallel()++ notFound := &requestError{+ StatusCode: http.StatusNotFound,+ Body: `{"error":"task not found"}`,+ }+ transient := &requestError{+ StatusCode: http.StatusBadGateway,+ Body: `<html>...</html>`,+ }++ cases := []struct {+ name string+ status string+ err error+ want bool+ }{+ {name: "status cancelled", status: "cancelled", err: nil, want: true},+ {name: "task deleted (404)", status: "", err: notFound, want: true},+ {name: "running normally", status: "running", err: nil, want: false},+ {name: "transient 5xx is not a cancel signal", status: "", err: transient, want: false},+ {name: "no information yet", status: "", err: nil, want: false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := shouldInterruptAgent(tc.status, tc.err); got != tc.want {+ t.Fatalf("shouldInterruptAgent(%q, %v) = %v, want %v", tc.status, tc.err, got, tc.want)+ }+ })+ }+}++// TestWatchTaskCancellation_TaskDeleted reproduces the zombie-task bug:+// when the server deletes a task while it is running (issue removed,+// agent reassigned, etc.), GetTaskStatus starts returning 404. Before the+// fix the daemon kept polling and never interrupted the running agent —+// codex would keep emitting tool calls for minutes against a dead task.+//+// After the fix, watchTaskCancellation must close its channel within a+// few poll intervals so the caller can cancel the agent context.+func TestWatchTaskCancellation_TaskDeleted(t *testing.T) {+ t.Parallel()++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !strings.HasSuffix(r.URL.Path, "/status") {+ http.NotFound(w, r)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusNotFound)+ _, _ = w.Write([]byte(`{"error":"task not found"}`))+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{client: NewClient(srv.URL), logger: slog.Default()}+ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)++ cancelled := d.watchTaskCancellation(ctx, "task-deleted", 10*time.Millisecond, slog.Default())++ select {+ case <-cancelled:+ // Expected: the watcher detected the 404 and signalled cancellation.+ case <-time.After(2 * time.Second):+ t.Fatal("watchTaskCancellation did not signal cancellation when task was deleted (404)")+ }+}++// TestWatchTaskCancellation_StatusCancelled keeps the existing behaviour+// (server transitions task status to "cancelled") working alongside the+// new 404 path.+func TestWatchTaskCancellation_StatusCancelled(t *testing.T) {+ t.Parallel()++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !strings.HasSuffix(r.URL.Path, "/status") {+ http.NotFound(w, r)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"status":"cancelled"}`))+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{client: NewClient(srv.URL), logger: slog.Default()}+ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)++ cancelled := d.watchTaskCancellation(ctx, "task-cancelled", 10*time.Millisecond, slog.Default())++ select {+ case <-cancelled:+ case <-time.After(2 * time.Second):+ t.Fatal("watchTaskCancellation did not signal cancellation when status=cancelled")+ }+}++// TestWatchTaskCancellation_RunningTaskNotInterrupted ensures the watcher+// does NOT trigger on transient errors or while the task is still running.+func TestWatchTaskCancellation_RunningTaskNotInterrupted(t *testing.T) {+ t.Parallel()++ var calls atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls.Add(1)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"status":"running"}`))+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{client: NewClient(srv.URL), logger: slog.Default()}+ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)++ cancelled := d.watchTaskCancellation(ctx, "task-running", 10*time.Millisecond, slog.Default())++ select {+ case <-cancelled:+ t.Fatal("watchTaskCancellation should not signal cancellation while task is running")+ case <-time.After(150 * time.Millisecond):+ }+ if calls.Load() < 5 {+ t.Fatalf("expected the watcher to poll at least 5 times in 150ms, got %d", calls.Load())+ }+}+func TestMergeUsage(t *testing.T) {t.Parallel()