Skip to content

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

Go

MUL-7085: fix(chat): publish cancellation events when archiving agents (#8073)

YYClaw940493409e03
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 7d40248f36..754c111d7e 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -2429,13 +2429,11 @@ func (h *Handler) ArchiveAgent(w http.ResponseWriter, r *http.Request) {
// Cancel all pending/active tasks for this agent. The cancel and its
// delegated-failure settlement commit together — a settlement issued after
- // the cancel committed could never be repaired. Per-task task:cancelled
- // events are still skipped: the agent:archived event below already triggers
- // a full active-tasks invalidation on every connected client.
- if cancelled, err := h.TaskService.CancelTasksForArchivedAgent(r.Context(), agent.ID); err != nil {
+ // the cancel committed could never be repaired. Chat tasks publish
+ // task:cancelled after commit for chat lifecycle consumers; the aggregate
+ // agent:archived event below remains unchanged.
+ if _, err := h.TaskService.CancelTasksForArchivedAgent(r.Context(), agent.ID); err != nil {
slog.Warn("cancel agent tasks on archive failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
- } else {
- h.TaskService.CaptureCancelledTasks(r.Context(), cancelled)
}
wsID := uuidToString(archived.WorkspaceID)
diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.go
index 8dc525e5c0..52f380aaeb 100644
--- a/server/internal/integrations/lark/outbound.go
+++ b/server/internal/integrations/lark/outbound.go
@@ -264,14 +264,12 @@ func (p *Patcher) SetTypingIndicatorManager(m *TypingIndicatorManager) {
// BroadcastCancelledTasks resolved each task's workspace through its
// chat_session, the same row its transaction had just deleted, and an
// event with no workspace is dropped before it reaches the bus. It now
-// takes the workspace from its caller. Two holes are left, neither of
-// them a missing subscription: archiving an agent stays silent by
-// choice — agent:archived invalidates every client's task list
-// instead — and no list refresh removes a Lark reaction; and an
-// ending that arrives while the reaction is still being added clears
+// takes the workspace from its caller. Archiving an agent also publishes
+// task:cancelled for chat tasks after commit, clearing their reactions
+// through this subscription. An ending during Add can still clear
// nothing, because Add records its state only after the Lark call
// returns, so the badge lands after the clear with nothing left to
-// take it off. That second one predates task:cancelled — chat-done
+// take it off. This race predates task:cancelled — chat-done
// and task-failed race the add the same way — and closing it needs a
// per-session generation the add can check when its call returns.
//
diff --git a/server/internal/integrations/slack/typing_indicator.go b/server/internal/integrations/slack/typing_indicator.go
index 67e4d8e768..a4faef3145 100644
--- a/server/internal/integrations/slack/typing_indicator.go
+++ b/server/internal/integrations/slack/typing_indicator.go
@@ -230,15 +230,10 @@ func (m *TypingIndicatorManager) apiForInstallation(ctx context.Context, id pgty
// just deleted, and an event with no workspace is dropped before it reaches the
// bus. It now takes the workspace from its caller.
//
-// Two holes are left, and neither is a missing subscription.
+// Archiving an agent also publishes task:cancelled for its chat tasks after
+// commit, so these reactions are cleared through the same subscription.
//
-// Archiving an agent cancels its tasks without broadcasting per row, on the
-// grounds that the agent:archived event already invalidates every client's task
-// list (handler/agent.go, ArchiveAgent). No client-side list refresh takes a
-// reaction off a Slack message, so archiving an agent mid-run leaves the 👀 in
-// place.
-//
-// And an ending that arrives while the reaction is still being added clears
+// An ending during Add can still clear
// nothing: Add records its state only after the Slack call returns, so Clear
// finds an empty map, and the reaction lands after it with nothing left to take
// it off. The Router adds on a detached goroutine, so a cancelled or very fast
diff --git a/server/internal/integrations/slack/typing_indicator_archive_test.go b/server/internal/integrations/slack/typing_indicator_archive_test.go
new file mode 100644
index 0000000000..776a5d418c
--- /dev/null
+++ b/server/internal/integrations/slack/typing_indicator_archive_test.go
@@ -0,0 +1,115 @@
+package slack
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/slack-go/slack"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/service"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// The task-state and transaction matrix lives in service/task_archive_cancel_test.go.
+// This regression follows one archive through the real bus subscriber and Slack
+// SDK, replacing only Slack's HTTP endpoint with a local server.
+func TestTypingIndicator_ArchiveRemovesSlackReaction(t *testing.T) {
+ databaseURL := os.Getenv("DATABASE_URL")
+ if databaseURL == "" {
+ t.Skip("DATABASE_URL not set")
+ }
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, databaseURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ f := testutil.New(pool, "", "")
+ suffix := fmt.Sprint(time.Now().UnixNano())
+ f.UserID = f.User(t, "Archive reaction test", "archive-reaction-"+suffix+"@example.test")
+ f.WorkspaceID = f.Workspace(t, "Archive reaction test", "archive-reaction-"+suffix)
+ f.Member(t, f.WorkspaceID, f.UserID, "owner")
+ runtimeID := f.Runtime(t, "Archive reaction test")
+ agentID := f.Agent(t, "Archive reaction test", runtimeID)
+ sessionID := f.ChatSession(t, agentID)
+ taskID := f.Task(t, agentID, testutil.Cols{
+ "chat_session_id": sessionID, "status": "running", "runtime_id": runtimeID,
+ })
+ installationID := f.Insert(t, "channel_installation", testutil.Cols{
+ "workspace_id": f.WorkspaceID, "agent_id": agentID, "channel_type": "slack",
+ "installer_user_id": f.UserID, "config": slackInstallConfigJSON(), "status": "active",
+ })
+ const channelID = "C_ARCHIVE_TEST"
+ ts := freshTS()
+ f.Insert(t, "channel_chat_session_binding", testutil.Cols{
+ "chat_session_id": sessionID, "installation_id": installationID, "channel_type": "slack",
+ "channel_chat_id": channelID, "chat_type": "group", "last_message_id": ts,
+ })
+ q := db.New(pool)
+ inst, err := q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
+ ID: util.MustParseUUID(installationID), ChannelType: "slack",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ type reactionCall struct{ path, channel, timestamp, name string }
+ var mu sync.Mutex
+ var calls []reactionCall
+ apiServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := r.ParseForm(); err != nil {
+ t.Error(err)
+ }
+ mu.Lock()
+ calls = append(calls, reactionCall{r.URL.Path, r.FormValue("channel"), r.FormValue("timestamp"), r.FormValue("name")})
+ mu.Unlock()
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true}`))
+ }))
+ t.Cleanup(apiServer.Close)
+ manager := NewTypingIndicatorManager(q, nil, nil)
+ manager.newAPI = func(c credentials) reactionAPI {
+ return slack.New(c.BotToken, slack.OptionAPIURL(apiServer.URL+"/"), slack.OptionHTTPClient(apiServer.Client()))
+ }
+ bus := events.New()
+ manager.Register(bus)
+ manager.Add(ctx, inst, util.MustParseUUID(sessionID), channelID, ts)
+ mu.Lock()
+ added := append([]reactionCall(nil), calls...)
+ mu.Unlock()
+ if len(added) != 1 || added[0] != (reactionCall{"/reactions.add", channelID, ts, typingEmoji}) {
+ t.Fatalf("fixture must add the processing reaction through Slack HTTP: %+v", added)
+ }
+
+ // ArchiveAgent commits before the handler calls CancelTasksForArchivedAgent.
+ if _, err := q.ArchiveAgent(ctx, db.ArchiveAgentParams{
+ ID: util.MustParseUUID(agentID), ArchivedBy: util.MustParseUUID(f.UserID),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ svc := &service.TaskService{Queries: q, TxStarter: pool, Bus: bus}
+ if _, err := svc.CancelTasksForArchivedAgent(ctx, util.MustParseUUID(agentID)); err != nil {
+ t.Fatal(err)
+ }
+ var status string
+ f.QueryRow(t, "SELECT status FROM agent_task_queue WHERE id=$1", taskID).Scan(&status)
+ if status != "cancelled" {
+ t.Fatalf("task status = %q, want cancelled", status)
+ }
+ mu.Lock()
+ got := append([]reactionCall(nil), calls...)
+ mu.Unlock()
+ if len(got) != 2 || got[1] != (reactionCall{"/reactions.remove", channelID, ts, typingEmoji}) {
+ t.Fatalf("archived task is cancelled, but Slack must remove its processing reaction: %+v", got)
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index c9bef30c39..a11ebf8781 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -5808,13 +5808,24 @@ func (s *TaskService) RecoverOrphanedTasksForRuntime(ctx context.Context, runtim
// CancelTasksForArchivedAgent cancels every active task belonging to an agent
// being archived and settles their recovery receipts in the same transaction.
//
-// Unlike CancelTasksForAgent it emits no per-task task:cancelled event: the
-// agent:archived event the caller publishes already invalidates every client's
-// active-task view, so per-row events would be redundant noise.
+// After commit, cancellation side effects are captured before chat tasks emit
+// task:cancelled so existing consumers can clear processing indicators, release
+// streams, and refresh chat state. The caller still publishes agent:archived;
+// non-chat tasks keep their existing behavior.
func (s *TaskService) CancelTasksForArchivedAgent(ctx context.Context, agentID pgtype.UUID) ([]db.AgentTaskQueue, error) {
- return s.terminateTasksInTx(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {
+ cancelled, err := s.terminateTasksInTx(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {
return qtx.CancelAgentTasksByAgent(ctx, agentID)
})
+ if err != nil {
+ return nil, err
+ }
+ s.CaptureCancelledTasks(ctx, cancelled)
+ for _, task := range cancelled {
+ if task.ChatSessionID.Valid {
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)
+ }
+ }
+ return cancelled, nil
}
func (s *TaskService) terminateTasksInTx(ctx context.Context, fail func(*db.Queries) ([]db.AgentTaskQueue, error)) ([]db.AgentTaskQueue, error) {
diff --git a/server/internal/service/task_archive_cancel_test.go b/server/internal/service/task_archive_cancel_test.go
new file mode 100644
index 0000000000..639d7aeac8
--- /dev/null
+++ b/server/internal/service/task_archive_cancel_test.go
@@ -0,0 +1,221 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func newArchiveCancelFixture(t *testing.T) (*testutil.Fixture, string, string) {
+ t.Helper()
+ fx := testutil.New(newCancelFinalizePool(t), "", "")
+ suffix := time.Now().UnixNano()
+ fx.UserID = fx.User(t, "Archive cancellation", fmt.Sprintf("archive-cancel-%[email protected]", suffix))
+ fx.WorkspaceID = fx.Workspace(t, "Archive cancellation", fmt.Sprintf("archive-cancel-%d", suffix))
+ fx.Member(t, fx.WorkspaceID, fx.UserID, "owner")
+ runtimeID := fx.Runtime(t, "Archive cancellation runtime")
+ agentID := fx.Agent(t, "Archived agent", runtimeID)
+ return fx, agentID, runtimeID
+}
+
+func TestCancelTasksForArchivedAgentPublishesCommittedChatCancellations(t *testing.T) {
+ ctx := context.Background()
+ fx, agentID, runtimeID := newArchiveCancelFixture(t)
+ chatByTask := make(map[string]string)
+ for _, status := range []string{"queued", "dispatched", "running", "waiting_local_directory", "deferred"} {
+ // No channel binding: the lifecycle notification applies to every chat.
+ chatID := fx.ChatSession(t, agentID)
+ taskID := fx.Task(t, agentID, testutil.Cols{
+ "chat_session_id": chatID,
+ "runtime_id": runtimeID,
+ "status": status,
+ })
+ chatByTask[taskID] = chatID
+ }
+ issueID := fx.Issue(t, "Issue task remains part of bulk cancellation")
+ issueTaskID := fx.Task(t, agentID, testutil.Cols{
+ "issue_id": issueID, "runtime_id": runtimeID, "status": "running",
+ })
+ unchanged := make(map[string]string)
+ for _, status := range []string{"completed", "failed", "cancelled"} {
+ unchanged[fx.Task(t, agentID, testutil.Cols{
+ "chat_session_id": fx.ChatSession(t, agentID),
+ "runtime_id": runtimeID,
+ "status": status,
+ })] = status
+ }
+ otherAgentID := fx.Agent(t, "Other agent", runtimeID)
+ unchanged[fx.Task(t, otherAgentID, testutil.Cols{
+ "chat_session_id": fx.ChatSession(t, otherAgentID),
+ "runtime_id": runtimeID,
+ "status": "running",
+ })] = "running"
+
+ // Hold a separate connection before cancellation starts, so the observer
+ // cannot reuse the transaction connection or see its uncommitted writes.
+ observer, err := fx.Pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire event observer: %v", err)
+ }
+ defer observer.Release()
+ bus := events.New()
+ seen := make(map[string]int)
+ bus.Subscribe(protocol.EventTaskCancelled, func(e events.Event) {
+ seen[e.TaskID]++
+ chatID, ok := chatByTask[e.TaskID]
+ if !ok {
+ t.Errorf("unexpected cancellation event for task %q", e.TaskID)
+ return
+ }
+ if e.WorkspaceID != fx.WorkspaceID || e.ChatSessionID != chatID || e.ActorType != "system" {
+ t.Errorf("task %s event scope = workspace %q chat %q actor %q", e.TaskID, e.WorkspaceID, e.ChatSessionID, e.ActorType)
+ }
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ t.Errorf("task %s payload type = %T, want map[string]any", e.TaskID, e.Payload)
+ return
+ }
+ for key, want := range map[string]any{
+ "task_id": e.TaskID, "agent_id": agentID, "chat_session_id": chatID,
+ "issue_id": "", "status": "cancelled",
+ } {
+ if got := payload[key]; got != want {
+ t.Errorf("task %s payload[%q] = %v, want %v", e.TaskID, key, got, want)
+ }
+ }
+ var status string
+ if err := observer.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, e.TaskID).Scan(&status); err != nil {
+ t.Errorf("read cancellation from event observer: %v", err)
+ } else if status != "cancelled" {
+ t.Errorf("task %s event arrived before cancellation committed: status = %q", e.TaskID, status)
+ }
+ })
+ svc := NewTaskService(db.New(fx.Pool), fx.Pool, nil, bus)
+ cancelled, err := svc.CancelTasksForArchivedAgent(ctx, util.MustParseUUID(agentID))
+ if err != nil {
+ t.Fatalf("cancel archived agent tasks: %v", err)
+ }
+ if len(cancelled) != len(chatByTask)+1 {
+ t.Errorf("cancelled rows = %d, want %d chat and issue tasks", len(cancelled), len(chatByTask)+1)
+ }
+ returned := make(map[string]int)
+ for _, task := range cancelled {
+ id := util.UUIDToString(task.ID)
+ returned[id]++
+ if _, ok := chatByTask[id]; !ok && id != issueTaskID {
+ t.Errorf("unexpected cancelled row %s", id)
+ }
+ if task.Status != "cancelled" {
+ t.Errorf("returned task %s status = %q, want cancelled", id, task.Status)
+ }
+ }
+ for taskID := range chatByTask {
+ if returned[taskID] != 1 || seen[taskID] != 1 {
+ t.Errorf("chat task %s: returned %d times, published %d times; want one each", taskID, returned[taskID], seen[taskID])
+ }
+ }
+ if returned[issueTaskID] != 1 || seen[issueTaskID] != 0 {
+ t.Errorf("issue task: returned %d times, published %d times; want one row and no task event", returned[issueTaskID], seen[issueTaskID])
+ }
+ if len(seen) != len(chatByTask) {
+ t.Errorf("distinct event tasks = %d, want %d", len(seen), len(chatByTask))
+ }
+ for taskID := range returned {
+ unchanged[taskID] = "cancelled"
+ }
+ for taskID, want := range unchanged {
+ var status string
+ if err := observer.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {
+ t.Fatalf("read task %s: %v", taskID, err)
+ }
+ if status != want {
+ t.Errorf("task %s persisted status = %q, want %q", taskID, status, want)
+ }
+ }
+
+ beforeRepeat := make(map[string]int, len(seen))
+ for taskID, count := range seen {
+ beforeRepeat[taskID] = count
+ }
+ cancelled, err = svc.CancelTasksForArchivedAgent(ctx, util.MustParseUUID(agentID))
+ if err != nil || len(cancelled) != 0 {
+ t.Fatalf("repeat cancellation: rows = %d, error = %v; want no rows and no error", len(cancelled), err)
+ }
+ if len(seen) != len(beforeRepeat) {
+ t.Error("repeat cancellation published events for additional tasks")
+ }
+ for taskID, count := range seen {
+ if count != beforeRepeat[taskID] {
+ t.Errorf("repeat cancellation published another event for task %s", taskID)
+ }
+ }
+}
+
+type archiveCancelRejectCommit struct {
+ pool *pgxpool.Pool
+ taskID string
+ err error
+ statusBeforeFail string
+}
+
+func (s *archiveCancelRejectCommit) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &archiveCancelRejectCommitTx{Tx: tx, starter: s}, nil
+}
+
+type archiveCancelRejectCommitTx struct {
+ pgx.Tx
+ starter *archiveCancelRejectCommit
+}
+
+func (tx *archiveCancelRejectCommitTx) Commit(ctx context.Context) error {
+ if err := tx.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, tx.starter.taskID).Scan(&tx.starter.statusBeforeFail); err != nil {
+ return err
+ }
+ if err := tx.Tx.Rollback(ctx); err != nil {
+ return err
+ }
+ return tx.starter.err
+}
+
+func TestCancelTasksForArchivedAgentCommitFailureDoesNotPublish(t *testing.T) {
+ ctx := context.Background()
+ fx, agentID, runtimeID := newArchiveCancelFixture(t)
+ taskID := fx.Task(t, agentID, testutil.Cols{
+ "chat_session_id": fx.ChatSession(t, agentID), "runtime_id": runtimeID, "status": "running",
+ })
+ injectedErr := errors.New("injected archive cancellation commit failure")
+ starter := &archiveCancelRejectCommit{pool: fx.Pool, taskID: taskID, err: injectedErr}
+ bus := events.New()
+ var published int
+ bus.Subscribe(protocol.EventTaskCancelled, func(events.Event) { published++ })
+ svc := NewTaskService(db.New(fx.Pool), starter, nil, bus)
+
+ cancelled, err := svc.CancelTasksForArchivedAgent(ctx, util.MustParseUUID(agentID))
+ if !errors.Is(err, injectedErr) || cancelled != nil {
+ t.Errorf("failed cancellation: rows = %v, error = %v; want nil rows and injected error", cancelled, err)
+ }
+ if starter.statusBeforeFail != "cancelled" {
+ t.Errorf("status inside failed transaction = %q, want cancelled", starter.statusBeforeFail)
+ }
+ var persistedStatus string
+ if err := fx.Pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&persistedStatus); err != nil {
+ t.Fatalf("read rolled-back task: %v", err)
+ }
+ if persistedStatus != "running" || published != 0 {
+ t.Errorf("failed cancellation: persisted status = %q, published = %d; want running and no events", persistedStatus, published)
+ }
+}