Skip to content

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

Go

fix(channels): deliver terminal task failure details (#6534)

YYClawd598e7a3e654
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 416bfd5872..5d0c4bb114 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -324,6 +324,8 @@ export interface TaskFailedPayload {
issue_id: string;
chat_session_id?: string;
status: string;
+ failure_reason?: string;
+ retry_pending?: boolean;
}
export interface TaskCancelledPayload {
diff --git a/server/cmd/server/issue_updated_projection_test.go b/server/cmd/server/issue_updated_projection_test.go
index 74f0051841..5a6673d260 100644
--- a/server/cmd/server/issue_updated_projection_test.go
+++ b/server/cmd/server/issue_updated_projection_test.go
@@ -150,6 +150,71 @@ func TestProjectOutbound_DoesNotMutateProducerPayload(t *testing.T) {
}
}
+func TestProjectOutbound_TaskFailedKeepsErrorInternal(t *testing.T) {
+ original := map[string]any{
+ "task_id": "task-1",
+ "failure_reason": "timeout",
+ "retry_pending": false,
+ "error": "task timed out",
+ }
+
+ projected, ok := projectOutbound(protocol.EventTaskFailed, original).(map[string]any)
+ if !ok {
+ t.Fatal("task:failed projection did not return a map")
+ }
+ if _, present := projected["error"]; present {
+ t.Fatal("task:failed error reached the workspace realtime payload")
+ }
+ if projected["failure_reason"] != "timeout" || projected["retry_pending"] != false {
+ t.Fatalf("safe task failure metadata was lost: %#v", projected)
+ }
+ if original["error"] != "task timed out" {
+ t.Fatal("task:failed projection mutated the in-process payload")
+ }
+}
+
+func TestTaskFailedBroadcast_DeliversErrorOnlyInProcess(t *testing.T) {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ payload := map[string]any{
+ "task_id": "task-1",
+ "failure_reason": "timeout",
+ "retry_pending": false,
+ "error": "task timed out",
+ }
+
+ var inProcessError string
+ bus.Subscribe(protocol.EventTaskFailed, func(e events.Event) {
+ m, _ := e.Payload.(map[string]any)
+ inProcessError, _ = m["error"].(string)
+ })
+ registerListeners(bus, fb)
+ bus.Publish(events.Event{
+ Type: protocol.EventTaskFailed,
+ WorkspaceID: "workspace-1",
+ Payload: payload,
+ })
+
+ if inProcessError != "task timed out" {
+ t.Fatalf("in-process channel listener error = %q, want task timed out", inProcessError)
+ }
+ if len(fb.workspaceCalls) != 1 {
+ t.Fatalf("workspace broadcasts = %d, want 1", len(fb.workspaceCalls))
+ }
+ var frame struct {
+ Payload map[string]any `json:"payload"`
+ }
+ if err := json.Unmarshal(fb.workspaceCalls[0].msg, &frame); err != nil {
+ t.Fatalf("unmarshal workspace frame: %v", err)
+ }
+ if _, present := frame.Payload["error"]; present {
+ t.Fatal("channel-only failure error reached the workspace broadcast")
+ }
+ if payload["error"] != "task timed out" {
+ t.Fatal("broadcast projection mutated the producer payload")
+ }
+}
+
// TestProjectOutbound_PassesThroughUnlistedEvents keeps the projection from
// becoming a general-purpose payload filter: an event type with no entry in the
// table must be forwarded byte-for-byte, and a non-map payload must survive.
diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.go
index 3ea90b3e97..a53f79ab64 100644
--- a/server/cmd/server/listeners.go
+++ b/server/cmd/server/listeners.go
@@ -36,6 +36,10 @@ import (
// internal/external payload boundary in one reviewable place.
var internalOnlyPayloadKeys = map[string][]string{
protocol.EventIssueUpdated: {"prev_description", "prev_title"},
+ // task:failed error text is consumed synchronously by channel outbounds.
+ // It may contain provider/runtime detail that belongs in the originating
+ // chat transcript, not in the workspace-wide realtime fanout.
+ protocol.EventTaskFailed: {"error"},
}
// projectOutbound returns payload with the event type's internal-only keys
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 941e01c13e..72dd757182 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -14,6 +14,7 @@ import (
"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"
+ "github.com/multica-ai/multica/server/pkg/redact"
)
const (
@@ -367,18 +368,29 @@ func broadcastFailedTasks(ctx context.Context, queries *db.Queries, taskSvc *ser
}
}
}
- bus.Publish(events.Event{
+ payload := map[string]any{
+ "task_id": util.UUIDToString(t.ID),
+ "agent_id": util.UUIDToString(t.AgentID),
+ "issue_id": util.UUIDToString(t.IssueID),
+ "status": "failed",
+ "failure_reason": failureReason,
+ "retry_pending": false,
+ }
+ if t.Error.Valid && t.Error.String != "" {
+ payload["error"] = redact.Text(t.Error.String)
+ }
+ e := events.Event{
Type: protocol.EventTaskFailed,
WorkspaceID: workspaceID,
ActorType: "system",
- Payload: map[string]any{
- "task_id": util.UUIDToString(t.ID),
- "agent_id": util.UUIDToString(t.AgentID),
- "issue_id": util.UUIDToString(t.IssueID),
- "status": "failed",
- "failure_reason": failureReason,
- },
- })
+ TaskID: util.UUIDToString(t.ID),
+ Payload: payload,
+ }
+ if t.ChatSessionID.Valid {
+ e.ChatSessionID = util.UUIDToString(t.ChatSessionID)
+ payload["chat_session_id"] = e.ChatSessionID
+ }
+ bus.Publish(e)
affectedAgents[util.UUIDToString(t.AgentID)] = t.AgentID
}
for _, agentID := range affectedAgents {
diff --git a/server/cmd/server/runtime_sweeper_test.go b/server/cmd/server/runtime_sweeper_test.go
index 050bd33e96..6c82ee33bb 100644
--- a/server/cmd/server/runtime_sweeper_test.go
+++ b/server/cmd/server/runtime_sweeper_test.go
@@ -215,6 +215,15 @@ func TestSweepStaleTasksBroadcastsWithWorkspaceID(t *testing.T) {
if e.WorkspaceID != testWorkspaceID {
t.Fatalf("expected WorkspaceID %s, got %s", testWorkspaceID, e.WorkspaceID)
}
+ if e.TaskID != taskID {
+ t.Fatalf("expected envelope TaskID %s, got %s", taskID, e.TaskID)
+ }
+ if payload["error"] != "task timed out" {
+ t.Fatalf("expected deliverable error %q, got %v", "task timed out", payload["error"])
+ }
+ if payload["failure_reason"] != "timeout" || payload["retry_pending"] != false {
+ t.Fatalf("unexpected failure metadata: reason=%v retry_pending=%v", payload["failure_reason"], payload["retry_pending"])
+ }
foundEvent = true
break
}
diff --git a/server/internal/integrations/dingtalk/outbound.go b/server/internal/integrations/dingtalk/outbound.go
index 62123b3bc7..a9b0602408 100644
--- a/server/internal/integrations/dingtalk/outbound.go
+++ b/server/internal/integrations/dingtalk/outbound.go
@@ -136,6 +136,9 @@ func eventContent(e events.Event) string {
return p.Content
case map[string]any:
if e.Type == protocol.EventTaskFailed {
+ if retryPending, _ := p["retry_pending"].(bool); retryPending {
+ return ""
+ }
if s, _ := p["error"].(string); s != "" {
return "⚠️ " + s
}
diff --git a/server/internal/integrations/dingtalk/outbound_test.go b/server/internal/integrations/dingtalk/outbound_test.go
index bdf2d3ec53..c0039dc7bc 100644
--- a/server/internal/integrations/dingtalk/outbound_test.go
+++ b/server/internal/integrations/dingtalk/outbound_test.go
@@ -23,11 +23,17 @@ func TestEventContent(t *testing.T) {
"⚠️ task timed out",
},
{
- // Failure broadcasts without an error text (a retry-pending
- // failure — the publisher omits `error` then — or the reaper
- // sweep) write no transcript message either — stay silent.
+ // Retry-pending failures stay silent even if a mixed-version
+ // publisher accidentally includes an error string.
+ "task failed with retry pending",
+ events.Event{Type: protocol.EventTaskFailed, Payload: map[string]any{"error": "task timed out", "failure_reason": "timeout", "retry_pending": true}},
+ "",
+ },
+ {
+ // Failure broadcasts without an error text have nothing safe to
+ // deliver and stay silent.
"task failed without error",
- events.Event{Type: protocol.EventTaskFailed, Payload: map[string]any{"failure_reason": "timeout", "retry_pending": true}},
+ events.Event{Type: protocol.EventTaskFailed, Payload: map[string]any{"failure_reason": "timeout", "retry_pending": false}},
"",
},
{
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index a245718bf0..1878f6b72b 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3979,8 +3979,10 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
// Reconcile agent status
s.ReconcileAgentStatus(ctx, task.AgentID)
- // Broadcast
- s.broadcastTaskEvent(ctx, protocol.EventTaskFailed, task)
+ // Broadcast. Channel subscribers need the same redacted failure text that
+ // was persisted in the chat transcript. A retry-pending attempt stays silent
+ // because its child reports the eventual terminal outcome.
+ s.broadcastTaskFailedEvent(ctx, task, errMsg, failureReason, retried != nil)
return &task, nil
}
@@ -4481,7 +4483,9 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTas
for _, t := range tasks {
// Auto-retry first so the issue stays in_progress rather than
// flapping todo → in_progress within a tick.
+ retryPending := false
if child, _ := s.MaybeRetryFailedTask(ctx, t); child != nil {
+ retryPending = true
retried++
if t.IssueID.Valid {
retriedIssues[util.UUIDToString(t.IssueID)] = true
@@ -4536,20 +4540,7 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTas
workspaceID = s.ResolveTaskWorkspaceID(ctx, t)
}
- if workspaceID != "" {
- s.Bus.Publish(events.Event{
- Type: protocol.EventTaskFailed,
- WorkspaceID: workspaceID,
- ActorType: "system",
- Payload: map[string]any{
- "task_id": util.UUIDToString(t.ID),
- "agent_id": util.UUIDToString(t.AgentID),
- "issue_id": util.UUIDToString(t.IssueID),
- "status": "failed",
- "failure_reason": failureReason,
- },
- })
- }
+ s.publishTaskFailedEvent(workspaceID, t, t.Error.String, failureReason, retryPending)
affectedAgents[util.UUIDToString(t.AgentID)] = t.AgentID
}
@@ -4895,27 +4886,73 @@ func (s *TaskService) broadcastTaskDispatch(ctx context.Context, task db.AgentTa
})
}
-func (s *TaskService) broadcastTaskEvent(ctx context.Context, eventType string, task db.AgentTaskQueue) {
- workspaceID := s.ResolveTaskWorkspaceID(ctx, task)
- if workspaceID == "" {
- return
- }
+// taskEvent builds the shared task-lifecycle event contract. Scope hints are
+// duplicated on the envelope intentionally: current listeners remain
+// compatible with the payload map, while the realtime layer can route without
+// decoding it once per-resource fanout is enabled.
+func taskEvent(eventType, workspaceID string, task db.AgentTaskQueue, extra ...map[string]any) events.Event {
payload := map[string]any{
"task_id": util.UUIDToString(task.ID),
"agent_id": util.UUIDToString(task.AgentID),
"issue_id": util.UUIDToString(task.IssueID),
"status": task.Status,
}
- if task.ChatSessionID.Valid {
- payload["chat_session_id"] = util.UUIDToString(task.ChatSessionID)
- }
- s.Bus.Publish(events.Event{
+ e := events.Event{
Type: eventType,
WorkspaceID: workspaceID,
ActorType: "system",
ActorID: "",
+ TaskID: util.UUIDToString(task.ID),
Payload: payload,
- })
+ }
+ if task.ChatSessionID.Valid {
+ chatSessionID := util.UUIDToString(task.ChatSessionID)
+ payload["chat_session_id"] = chatSessionID
+ e.ChatSessionID = chatSessionID
+ }
+ for _, fields := range extra {
+ for key, value := range fields {
+ payload[key] = value
+ }
+ }
+ return e
+}
+
+func (s *TaskService) publishTaskEvent(eventType, workspaceID string, task db.AgentTaskQueue, extra ...map[string]any) {
+ if workspaceID == "" {
+ return
+ }
+ s.Bus.Publish(taskEvent(eventType, workspaceID, task, extra...))
+}
+
+func (s *TaskService) broadcastTaskEvent(ctx context.Context, eventType string, task db.AgentTaskQueue, extra ...map[string]any) {
+ workspaceID := s.ResolveTaskWorkspaceID(ctx, task)
+ s.publishTaskEvent(eventType, workspaceID, task, extra...)
+}
+
+// taskFailedFields adds the terminal failure context required by channel
+// outbounds without changing the long-standing map payload used by existing
+// task event consumers. Error text is redacted and omitted while an automatic
+// retry is pending, so consumers can distinguish an intermediate failed
+// attempt from a user-visible terminal failure.
+func taskFailedFields(errMsg, failureReason string, retryPending bool) map[string]any {
+ fields := map[string]any{
+ "failure_reason": failureReason,
+ "retry_pending": retryPending,
+ }
+ if errMsg != "" && !retryPending {
+ fields["error"] = redact.Text(errMsg)
+ }
+ return fields
+}
+
+func (s *TaskService) publishTaskFailedEvent(workspaceID string, task db.AgentTaskQueue, errMsg, failureReason string, retryPending bool) {
+ s.publishTaskEvent(protocol.EventTaskFailed, workspaceID, task, taskFailedFields(errMsg, failureReason, retryPending))
+}
+
+func (s *TaskService) broadcastTaskFailedEvent(ctx context.Context, task db.AgentTaskQueue, errMsg, failureReason string, retryPending bool) {
+ workspaceID := s.ResolveTaskWorkspaceID(ctx, task)
+ s.publishTaskFailedEvent(workspaceID, task, errMsg, failureReason, retryPending)
}
// ResolveTaskWorkspaceID determines the workspace ID for a task.
diff --git a/server/internal/service/task_failure_event_test.go b/server/internal/service/task_failure_event_test.go
new file mode 100644
index 0000000000..b42865d189
--- /dev/null
+++ b/server/internal/service/task_failure_event_test.go
@@ -0,0 +1,143 @@
+package service
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "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 TestTaskFailedFieldsTerminalFailure(t *testing.T) {
+ secret := "sk-" + strings.Repeat("a", 24)
+ fields := taskFailedFields("provider rejected "+secret, "agent_error", false)
+
+ if fields["failure_reason"] != "agent_error" {
+ t.Fatalf("failure_reason = %v, want agent_error", fields["failure_reason"])
+ }
+ if fields["retry_pending"] != false {
+ t.Fatalf("retry_pending = %v, want false", fields["retry_pending"])
+ }
+ errorText, ok := fields["error"].(string)
+ if !ok || errorText == "" {
+ t.Fatal("terminal failure must include deliverable error text")
+ }
+ if strings.Contains(errorText, secret) {
+ t.Fatal("terminal failure payload leaked an API key")
+ }
+ if !strings.Contains(errorText, "[REDACTED API KEY]") {
+ t.Fatalf("terminal failure payload was not redacted: %q", errorText)
+ }
+}
+
+func TestTaskFailedFieldsRetryPendingOmitsError(t *testing.T) {
+ fields := taskFailedFields("task timed out", "timeout", true)
+
+ if fields["retry_pending"] != true {
+ t.Fatalf("retry_pending = %v, want true", fields["retry_pending"])
+ }
+ if _, present := fields["error"]; present {
+ t.Fatal("retry-pending failure must not expose a terminal error")
+ }
+}
+
+func TestTaskEventCarriesPayloadAndScopeHints(t *testing.T) {
+ task := db.AgentTaskQueue{
+ ID: testUUID(41),
+ AgentID: testUUID(42),
+ IssueID: testUUID(43),
+ ChatSessionID: testUUID(44),
+ Status: "failed",
+ }
+ e := taskEvent(protocol.EventTaskFailed, "workspace-1", task, map[string]any{
+ "failure_reason": "timeout",
+ "retry_pending": false,
+ })
+
+ if e.TaskID != util.UUIDToString(task.ID) {
+ t.Fatalf("event TaskID = %q, want %q", e.TaskID, util.UUIDToString(task.ID))
+ }
+ if e.ChatSessionID != util.UUIDToString(task.ChatSessionID) {
+ t.Fatalf("event ChatSessionID = %q, want %q", e.ChatSessionID, util.UUIDToString(task.ChatSessionID))
+ }
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ t.Fatalf("payload type = %T, want map[string]any", e.Payload)
+ }
+ for key, want := range map[string]any{
+ "task_id": util.UUIDToString(task.ID),
+ "agent_id": util.UUIDToString(task.AgentID),
+ "issue_id": util.UUIDToString(task.IssueID),
+ "chat_session_id": util.UUIDToString(task.ChatSessionID),
+ "status": "failed",
+ "failure_reason": "timeout",
+ "retry_pending": false,
+ } {
+ if got := payload[key]; got != want {
+ t.Errorf("payload[%q] = %v, want %v", key, got, want)
+ }
+ }
+}
+
+// TestFailTaskPublishesDeliverableChannelFailure walks the real persistence
+// path that previously emitted only the base task fields. The DingTalk
+// subscriber needs the redacted error and chat scope on this exact event to
+// replace its initial acknowledgement with a terminal failure notice.
+func TestFailTaskPublishesDeliverableChannelFailure(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var runtimeID string
+ if err := pool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {
+ t.Fatalf("load agent runtime: %v", err)
+ }
+ var chatSessionID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id)
+ VALUES ($1, $2, $3) RETURNING id`, workspaceID, agentID, userID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("seed chat session: %v", err)
+ }
+ var taskID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue
+ (agent_id, runtime_id, chat_session_id, status, priority, attempt, max_attempts)
+ VALUES ($1, $2, $3, 'running', 0, 1, 1)
+ RETURNING id`, agentID, runtimeID, chatSessionID).Scan(&taskID); err != nil {
+ t.Fatalf("seed running chat task: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM chat_message WHERE chat_session_id = $1`, chatSessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
+ })
+
+ bus := events.New()
+ var got events.Event
+ bus.Subscribe(protocol.EventTaskFailed, func(e events.Event) { got = e })
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: bus}
+ if _, err := svc.FailTask(ctx, util.MustParseUUID(taskID), "provider failed", "", "", "agent_error", false, ""); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+
+ if got.Type != protocol.EventTaskFailed {
+ t.Fatalf("event type = %q, want %q", got.Type, protocol.EventTaskFailed)
+ }
+ if got.WorkspaceID != workspaceID || got.TaskID != taskID || got.ChatSessionID != chatSessionID {
+ t.Fatalf("event scope = workspace %q task %q chat %q", got.WorkspaceID, got.TaskID, got.ChatSessionID)
+ }
+ payload, ok := got.Payload.(map[string]any)
+ if !ok {
+ t.Fatalf("payload type = %T, want map[string]any", got.Payload)
+ }
+ if payload["error"] != "provider failed" {
+ t.Fatalf("payload error = %v, want provider failed", payload["error"])
+ }
+ if payload["failure_reason"] != "agent_error" || payload["retry_pending"] != false {
+ t.Fatalf("failure metadata = reason %v retry %v", payload["failure_reason"], payload["retry_pending"])
+ }
+}