Skip to content

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

Go

feat(wecom): report a failed run to the chat that asked (#7952)

Xichang(Seacen) Zhao03b597dd8a1b
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
index c8e98d02b2..f732c7b522 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -33,6 +33,7 @@ import (
"errors"
"fmt"
"log/slog"
+ "strings"
"sync"
"time"
@@ -136,6 +137,12 @@ func NewOutbound(q outboundQueries, senders *sendersRegistry, logger *slog.Logge
// Register subscribes to the chat-done event on the bus.
func (o *Outbound) Register(bus *events.Bus) {
bus.Subscribe(protocol.EventChatDone, o.handleEvent)
+ // A failed run ends the turn just as a reply does, and it goes out on the
+ // same route: task delivery row, origin gate, installation, socket. Until
+ // this subscription a failed run in WeCom said nothing and logged nothing,
+ // because no handler ran; DingTalk, Lark, Slack and Telegram all handle it.
+ bus.Subscribe(protocol.EventTaskFailed, o.handleEvent)
+ bus.Subscribe(protocol.EventTaskCancelled, o.handleTaskCancelled)
// Inbox notifications delivered through the smart bot: when the
// recipient member has a WeCom binding with a live connection, their
// inbox:new items are pushed to the aibot as a markdown card.
@@ -170,7 +177,7 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
// agent produced a file and said nothing about it: the platform writes an
// assistant message for exactly that case, and returning now would throw
// the work away.
- content := chatDoneContent(e.Payload)
+ content := deliverableContent(e)
if content == "" && !o.mayCarryAttachments(e) {
o.skipped(ctx, e, skipNothingToSay)
return nil
@@ -311,6 +318,47 @@ func wecomBindingFromTaskDelivery(delivery db.ChannelTaskDelivery) db.ChannelCha
// envelope's TaskID is preferred, with the payload as the fallback —
// service.broadcastChatDone sets ChatDonePayload.TaskID and leaves the
// envelope's empty, so in practice the fallback is the live path.
+// taskFailedPrefix marks a failure notice apart from a reply in the chat, the
+// way DingTalk's and Lark's do.
+const taskFailedPrefix = "⚠️ "
+
+// deliverableContent is what this event has to say in the chat.
+//
+// chat:done carries the agent's reply. task:failed carries the platform's own
+// redacted failure text in `error` — the same text the web transcript shows —
+// and nothing while an auto-retry is pending: the retry attempt reports its
+// own outcome, and announcing a failure the next attempt may undo would be
+// noise. Empty means the turn ends silently, exactly as an empty reply does.
+func deliverableContent(e events.Event) string {
+ if e.Type == protocol.EventTaskFailed {
+ return taskFailedContent(e.Payload)
+ }
+ return chatDoneContent(e.Payload)
+}
+
+func taskFailedContent(payload any) string {
+ p, ok := payload.(map[string]any)
+ if !ok {
+ return ""
+ }
+ if pending, _ := p["retry_pending"].(bool); pending {
+ return ""
+ }
+ msg, _ := p["error"].(string)
+ if strings.TrimSpace(msg) == "" {
+ return ""
+ }
+ return taskFailedPrefix + msg
+}
+
+// handleTaskCancelled is subscribed for the log line and nothing else: a
+// cancellation ends the run without an answer, and WeCom has nothing to take
+// back — no typing badge, no placeholder. Lark makes the same choice.
+func (o *Outbound) handleTaskCancelled(e events.Event) {
+ o.logger.DebugContext(context.Background(), "wecom outbound: run cancelled, nothing to send",
+ "chat_session_id", e.ChatSessionID, "task_id", e.TaskID)
+}
+
func chatDoneTaskID(e events.Event) (pgtype.UUID, bool) {
raw := e.TaskID
if raw == "" {
diff --git a/server/internal/integrations/wecom/task_failed_db_test.go b/server/internal/integrations/wecom/task_failed_db_test.go
new file mode 100644
index 0000000000..930f227987
--- /dev/null
+++ b/server/internal/integrations/wecom/task_failed_db_test.go
@@ -0,0 +1,41 @@
+package wecom
+
+// task_failed_db_test.go — the same failed run, answered by the real query
+// layer: the task delivery row, the channel_ingested stamp on the user's
+// message and the installation's status all come from Postgres, and the
+// event travels through a real bus into the real subscriber.
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func TestTaskFailed_ReachesTheChatThroughTheRealQueryLayer(t *testing.T) {
+ pool := twoReplicaDB(t)
+ turn := seedBoundTurn(t, pool)
+ r := newReplica(t, pool, turn.instID, true)
+
+ r.bus.Publish(events.Event{
+ Type: protocol.EventTaskFailed,
+ ActorType: "system",
+ ChatSessionID: turn.sessionID,
+ TaskID: turn.taskID,
+ Payload: map[string]any{
+ "task_id": turn.taskID,
+ "chat_session_id": turn.sessionID,
+ "status": "failed",
+ "retry_pending": false,
+ "error": "上下文超出模型限制",
+ },
+ })
+
+ got := sentTexts(t, r.conn)
+ if len(got) != 1 || got[0] != "⚠️ 上下文超出模型限制" {
+ t.Fatalf("sent %q, want exactly the failure notice", got)
+ }
+ if n := r.mx.get("outbound_delivered"); n != 1 {
+ t.Errorf("outbound_delivered = %d, want 1", n)
+ }
+}
diff --git a/server/internal/integrations/wecom/task_failed_test.go b/server/internal/integrations/wecom/task_failed_test.go
new file mode 100644
index 0000000000..00fa42ac96
--- /dev/null
+++ b/server/internal/integrations/wecom/task_failed_test.go
@@ -0,0 +1,135 @@
+package wecom
+
+// task_failed_test.go — a failed run reaches the chat that asked, on the same
+// route a reply takes; a retry-pending attempt and a web-UI run's failure do
+// not; a cancellation sends nothing.
+//
+// REVERSE VERIFICATION: with the two bus.Subscribe lines for task:failed and
+// task:cancelled removed from Register, TestRegister_AFailedRunReachesTheChat
+// fails (no frame); with deliverableContent reverted to chatDoneContent, the
+// processEvent tests fail (no frame).
+
+import (
+ "context"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func taskFailedEvent(taskID, errText string, retryPending bool) events.Event {
+ payload := map[string]any{
+ "task_id": taskID,
+ "status": "failed",
+ "retry_pending": retryPending,
+ }
+ if errText != "" {
+ payload["error"] = errText
+ }
+ return events.Event{
+ Type: protocol.EventTaskFailed,
+ ActorType: "system",
+ ChatSessionID: "22222222-2222-2222-2222-222222222222",
+ TaskID: taskID,
+ Payload: payload,
+ }
+}
+
+func failedRunRig(t *testing.T, origin *bool) (*Outbound, *recordingConn) {
+ t.Helper()
+ q := &fakeOutboundQueries{
+ sessionBinding: db.ChannelChatSessionBinding{ChannelChatID: "CHAT_1", ChatType: "group"},
+ installation: db.ChannelInstallation{Status: string(InstallationActive)},
+ channelIngested: origin,
+ }
+ q.fileTask(t, "33333333-3333-3333-3333-333333333333")
+ o, instID, conn := newOutboundWithConn(t, q)
+ q.sessionBinding.InstallationID = instID
+ q.installation.ID = instID
+ return o, conn
+}
+
+func TestProcessEvent_AFailedRunIsReportedToTheChatThatAsked(t *testing.T) {
+ t.Parallel()
+ o, conn := failedRunRig(t, askedOverWecom())
+ err := o.processEvent(context.Background(), taskFailedEvent("33333333-3333-3333-3333-333333333333", "上下文超出模型限制", false))
+ if err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ body := conn.sendBody(t, 0)
+ if body["chatid"] != "CHAT_1" {
+ t.Errorf("chatid = %v, want CHAT_1", body["chatid"])
+ }
+ md, _ := body["markdown"].(map[string]any)
+ if md == nil || md["content"] != "⚠️ 上下文超出模型限制" {
+ t.Errorf("content = %v, want the failure text behind the warning mark", body["markdown"])
+ }
+ if n := conn.frameCount(); n != 1 {
+ t.Errorf("%d frames, want exactly one", n)
+ }
+}
+
+func TestProcessEvent_ARetryPendingFailureSaysNothing(t *testing.T) {
+ t.Parallel()
+ o, conn := failedRunRig(t, askedOverWecom())
+ if err := o.processEvent(context.Background(), taskFailedEvent("33333333-3333-3333-3333-333333333333", "transient", true)); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if n := conn.frameCount(); n != 0 {
+ t.Fatalf("%d frames for an attempt the platform is already retrying, want 0", n)
+ }
+}
+
+func TestProcessEvent_AFailureWithNoTextSaysNothing(t *testing.T) {
+ t.Parallel()
+ o, conn := failedRunRig(t, askedOverWecom())
+ if err := o.processEvent(context.Background(), taskFailedEvent("33333333-3333-3333-3333-333333333333", "", false)); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if n := conn.frameCount(); n != 0 {
+ t.Fatalf("%d frames for a failure with no text, want 0", n)
+ }
+}
+
+// The origin gate is the same one the reply path has: a run started from the
+// web UI on a session that also lives in a WeCom group must not report its
+// failure into the room.
+func TestProcessEvent_AWebRunsFailureStaysOutOfTheRoom(t *testing.T) {
+ t.Parallel()
+ o, conn := failedRunRig(t, askedInTheWebUI())
+ if err := o.processEvent(context.Background(), taskFailedEvent("33333333-3333-3333-3333-333333333333", "boom", false)); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+ if n := conn.frameCount(); n != 0 {
+ t.Fatalf("%d frames for a web-UI run's failure, want 0", n)
+ }
+}
+
+// The wiring, through a real bus: task:failed is subscribed, task:cancelled
+// is subscribed and sends nothing.
+func TestRegister_AFailedRunReachesTheChatAndACancelledOneDoesNot(t *testing.T) {
+ t.Parallel()
+ o, conn := failedRunRig(t, askedOverWecom())
+ bus := events.New()
+ o.Register(bus)
+
+ bus.Publish(events.Event{
+ Type: protocol.EventTaskCancelled,
+ ChatSessionID: "22222222-2222-2222-2222-222222222222",
+ TaskID: "33333333-3333-3333-3333-333333333333",
+ Payload: map[string]any{"task_id": "33333333-3333-3333-3333-333333333333", "status": "cancelled"},
+ })
+ if n := conn.frameCount(); n != 0 {
+ t.Fatalf("%d frames for a cancellation, want 0", n)
+ }
+
+ bus.Publish(taskFailedEvent("33333333-3333-3333-3333-333333333333", "boom", false))
+ if n := conn.frameCount(); n != 1 {
+ t.Fatalf("%d frames after a published task:failed, want 1 — is the bus subscription there?", n)
+ }
+ md, _ := conn.sendBody(t, 0)["markdown"].(map[string]any)
+ if md == nil || md["content"] != "⚠️ boom" {
+ t.Errorf("content = %v, want ⚠️ boom", md)
+ }
+}