Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
[MUL-5736] fix(channel): make issue commands terminal outcomes (#6398)
YYClawc1be369f6d3f
diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.goindex 7ba7b7ae7c..17b7556d22 100644--- a/server/internal/integrations/channel/engine/resolvers.go+++ b/server/internal/integrations/channel/engine/resolvers.go@@ -58,6 +58,10 @@ type Result struct {IssueNumber int32IssueIdentifier stringIssueTitle string+ // IssueDuplicate marks an /issue command that did not create a new issue+ // because the shared duplicate guard found the active IssueID above.+ // Repliers render this as a business conflict, never as an internal error.+ IssueDuplicate bool// runScheduled reports whether this ingest scheduled a normal chat run.// It is Router-internal state: repliers must continue to use Outcome.runScheduled booldiff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 9564e17124..408c811dc4 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -409,6 +409,21 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// chat reply's.prefix := r.issuePrefix(ctx, inst.WorkspaceID)issueRes, err := r.createIssue(ctx, inst, set.OriginType, identity.UserID, sessionID, *appendRes.IssueCommand, prefix)+ if errors.Is(err, service.ErrActiveDuplicate) && issueRes.DuplicateIssue != nil {+ duplicate := *issueRes.DuplicateIssue+ res.IssueID = duplicate.ID+ res.IssueNumber = duplicate.Number+ res.IssueTitle = duplicate.Title+ res.IssueIdentifier = service.IssueIdentifier(prefix, duplicate.Number)+ res.IssueDuplicate = true+ // A duplicate is a terminal product outcome, not an infrastructure+ // failure and not a chat prompt. Media binding remains independent,+ // exactly like the successful direct-create path below.+ if resolveMedia {+ r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, localMediaDeadline)+ }+ return res, postAppendFinalize, nil+ }if err != nil {return Result{}, postAppendFinalize, fmt.Errorf("create issue from command: %w", err)}@@ -418,6 +433,13 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// Same renderer the broadcast payload uses, so a degraded prefix can't// show the chat "#42" while the realtime list shows "-42".res.IssueIdentifier = service.IssueIdentifier(prefix, issueRes.Issue.Number)+ // IssueService.Create already enqueues the assigned agent's issue task.+ // Scheduling the command as a chat run too makes the agent execute the+ // same /issue input again. A synchronous issue command is terminal.+ if resolveMedia {+ r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, localMediaDeadline)+ }+ return res, postAppendFinalize, nil}// 8. Debounce the run trigger. The synchronous outcome is OutcomeIngesteddiff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex d3e77c8aa6..3c7205d708 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -784,6 +784,12 @@ func TestRouter_IssueCommand_Creates(t *testing.T) {if h.issues.params.OriginType.String != "lark_chat" {t.Fatalf("origin_type must come from the resolver set, got %q", h.issues.params.OriginType.String)}+ if h.tasks.calls() != 0 {+ t.Fatalf("direct issue create must not also enqueue a chat task, calls=%d", h.tasks.calls())+ }+ if h.typing.calls() != 0 {+ t.Fatalf("terminal issue command must not start a chat processing indicator, calls=%d", h.typing.calls())+ }if !waitFor(time.Second, func() bool {for _, r := range h.replier.calls() {if r.IssueIdentifier == "MUL-42" && r.IssueTitle == "Fix login" {@@ -796,6 +802,93 @@ func TestRouter_IssueCommand_Creates(t *testing.T) {}}+func TestRouter_IssueCommandWithMediaBindsWithoutChatRun(t *testing.T) {+ h := newHarness(t)+ h.binder.appendResult = AppendResult{+ MessageID: uuidFromString(t, "77777777-7777-4777-8777-777777777777"),+ DedupMarked: true,+ IssueCommand: &IssueCommand{+ Title: "Inspect image",+ },+ }+ h.issues.result = service.IssueCreateResult{Issue: db.Issue{+ ID: uuidFromString(t, "88888888-8888-4888-8888-888888888888"), Number: 43, Title: "Inspect image",+ }}+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ if !waitFor(time.Second, func() bool { return h.tasks.promotionCalls() == 1 }) {+ t.Fatal("issue command media did not finish binding")+ }+ if h.tasks.calls() != 0 {+ t.Fatalf("media completion must not enqueue a chat task, calls=%d", h.tasks.calls())+ }+ if got := h.binder.boundMedia(); len(got.MediaRefs) != 1 {+ t.Fatalf("bound media refs = %+v", got.MediaRefs)+ }+}++func TestRouter_IssueCommand_ActiveDuplicateIsTerminalProductOutcome(t *testing.T) {+ h := newHarness(t)+ h.binder.appendResult = AppendResult{+ MessageID: uuidFromString(t, "77777777-7777-4777-8777-777777777777"),+ DedupMarked: true,+ IssueCommand: &IssueCommand{+ Title: "Existing issue",+ },+ }+ duplicate := db.Issue{+ ID: uuidFromString(t, "88888888-8888-4888-8888-888888888888"),+ Number: 44,+ Title: "Existing issue",+ }+ h.issues.result = service.IssueCreateResult{DuplicateIssue: &duplicate}+ h.issues.err = service.ErrActiveDuplicate++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("duplicate issue must be a product outcome, got error: %v", err)+ }+ if h.tasks.calls() != 0 {+ t.Fatalf("duplicate command must not enqueue a chat task, calls=%d", h.tasks.calls())+ }+ if h.typing.calls() != 0 {+ t.Fatalf("duplicate command must not start a processing indicator, calls=%d", h.typing.calls())+ }+ if !waitFor(time.Second, func() bool {+ for _, result := range h.replier.calls() {+ if result.IssueDuplicate && result.IssueID == duplicate.ID && result.IssueIdentifier == "MUL-44" && result.IssueTitle == duplicate.Title {+ return true+ }+ }+ return false+ }) {+ t.Fatalf("duplicate result was not delivered to replier: %+v", h.replier.calls())+ }+}++func TestRouter_IssueCommand_InfrastructureFailureRemainsError(t *testing.T) {+ h := newHarness(t)+ h.binder.appendResult = AppendResult{+ DedupMarked: true,+ IssueCommand: &IssueCommand{+ Title: "Unavailable issue",+ },+ }+ issueErr := errors.New("database unavailable")+ h.issues.err = issueErr++ err := h.router.Handle(context.Background(), p2pMessage(t))+ if !errors.Is(err, issueErr) {+ t.Fatalf("infrastructure failure = %v", err)+ }+ if h.tasks.calls() != 0 {+ t.Fatalf("failed issue command must not enqueue a chat task, calls=%d", h.tasks.calls())+ }+ if len(h.replier.calls()) != 0 {+ t.Fatalf("failed issue command must not emit a success outcome: %+v", h.replier.calls())+ }+}+func TestRouter_GroupSessionCreatorIsInstaller(t *testing.T) {h := newHarness(t)msg := p2pMessage(t)diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.goindex 565b5f7016..219475c456 100644--- a/server/internal/integrations/channel/engine/session.go+++ b/server/internal/integrations/channel/engine/session.go@@ -281,6 +281,11 @@ type BindMediaInput struct {MediaRefs []channel.MediaRef}+// channelCommandMessageKind marks a visible user turn handled synchronously by+// Router. It remains an ordinary public message, but the task batch seal omits+// it so the agent cannot execute the command again on a later turn.+const channelCommandMessageKind = "channel_command"+// AppendUserMessage writes the user message into the chat_session (touching it// and recording the reply target), runs the in-tx dedup Mark when a claim token// is supplied, and returns the durable message id plus the parsed `/issue`@@ -318,6 +323,7 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (ApChatSessionID: in.SessionID,Role: "user",Content: in.Body,+ MessageKind: textOrNullIf(cmd != nil, channelCommandMessageKind),ChannelMediaPendingSecs: pgtype.Float8{Float64: in.MediaPendingSeconds, Valid: in.MediaPendingSeconds > 0},ChannelIngested: pgtype.Bool{Bool: true, Valid: true},})@@ -532,3 +538,7 @@ func textOrNull(s string) pgtype.Text {}return pgtype.Text{String: s, Valid: true}}++func textOrNullIf(valid bool, s string) pgtype.Text {+ return pgtype.Text{String: s, Valid: valid}+}diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.goindex 1b6018d4a0..fa26ce939a 100644--- a/server/internal/integrations/channel/engine/session_db_test.go+++ b/server/internal/integrations/channel/engine/session_db_test.go@@ -97,6 +97,64 @@ func seedSessionPersistenceFixture(t *testing.T, pool *pgxpool.Pool) sessionPersreturn f}+func TestChannelIssueCommandIsExcludedFromLaterChatTaskBatch(t *testing.T) {+ pool := sessionPersistenceTestDB(t)+ fixture := seedSessionPersistenceFixture(t, pool)+ session := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})++ command, err := session.AppendUserMessage(context.Background(), AppendInput{+ SessionID: fixture.sessionID, Sender: fixture.userID,+ Body: "/issue handled once", CommandText: "/issue handled once",+ })+ if err != nil {+ t.Fatalf("append command: %v", err)+ }+ ordinary, err := session.AppendUserMessage(context.Background(), AppendInput{+ SessionID: fixture.sessionID, Sender: fixture.userID,+ Body: "next question", CommandText: "next question",+ })+ if err != nil {+ t.Fatalf("append ordinary message: %v", err)+ }++ var agentID, runtimeID pgtype.UUID+ if err := pool.QueryRow(context.Background(), `+ SELECT cs.agent_id, a.runtime_id+ FROM chat_session cs+ JOIN agent a ON a.id = cs.agent_id+ WHERE cs.id = $1`, fixture.sessionID).Scan(&agentID, &runtimeID); err != nil {+ t.Fatalf("load task routing: %v", err)+ }+ var taskID pgtype.UUID+ if err := pool.QueryRow(context.Background(), `+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, completed_at)+ VALUES ($1, $2, $3, 'completed', now()) RETURNING id`, agentID, runtimeID, fixture.sessionID).Scan(&taskID); err != nil {+ t.Fatalf("create chat task: %v", err)+ }+ t.Cleanup(func() {+ _, _ = pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)+ })+ if err := db.New(pool).LinkUnownedChannelChatMessagesToTask(context.Background(), db.LinkUnownedChannelChatMessagesToTaskParams{+ TaskID: taskID, ChatSessionID: fixture.sessionID,+ }); err != nil {+ t.Fatalf("seal chat input: %v", err)+ }++ var commandOwner, ordinaryOwner pgtype.UUID+ if err := pool.QueryRow(context.Background(), `SELECT task_id FROM chat_message WHERE id = $1`, command.MessageID).Scan(&commandOwner); err != nil {+ t.Fatalf("load command owner: %v", err)+ }+ if err := pool.QueryRow(context.Background(), `SELECT task_id FROM chat_message WHERE id = $1`, ordinary.MessageID).Scan(&ordinaryOwner); err != nil {+ t.Fatalf("load ordinary owner: %v", err)+ }+ if commandOwner.Valid {+ t.Fatalf("handled command was linked to a later task: %v", commandOwner)+ }+ if ordinaryOwner != taskID {+ t.Fatalf("ordinary message owner = %v, want %v", ordinaryOwner, taskID)+ }+}+func TestBindMediaRefs_PersistsAndLinksAttachmentToDurableMessage(t *testing.T) {pool := sessionPersistenceTestDB(t)fixture := seedSessionPersistenceFixture(t, pool)diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.goindex ec69d872fe..f076d7a0d6 100644--- a/server/internal/integrations/channel/engine/session_test.go+++ b/server/internal/integrations/channel/engine/session_test.go@@ -315,12 +315,28 @@ func TestAppendUserMessage_CommandTextOverridesEnrichedBody(t *testing.T) {if res.IssueCommand == nil || res.IssueCommand.Title != "Real intent" {t.Errorf("CommandText should drive /issue parsing: %+v", res.IssueCommand)}+ if !f.lastCreate.MessageKind.Valid || f.lastCreate.MessageKind.String != channelCommandMessageKind {+ t.Errorf("handled command message kind = %+v", f.lastCreate.MessageKind)+ }// The stored message is still the full (enriched) body.if f.messages[0] != "> quoted context from another message\n/issue Real intent" {t.Errorf("stored body should be the enriched Body: %q", f.messages[0])}}+func TestAppendUserMessage_OrdinaryTurnKeepsDefaultMessageKind(t *testing.T) {+ f := newFake()+ s := newTestSession(f)+ if _, err := s.AppendUserMessage(context.Background(), AppendInput{+ SessionID: uid(1), Body: "hello", CommandText: "hello", MessageID: "m1",+ }); err != nil {+ t.Fatalf("AppendUserMessage: %v", err)+ }+ if f.lastCreate.MessageKind.Valid {+ t.Fatalf("ordinary message kind must use the database default: %+v", f.lastCreate.MessageKind)+ }+}+func TestBindMediaRefs_CreatesAndLinksChatAttachments(t *testing.T) {f := newFake()s := newTestSession(f)diff --git a/server/internal/integrations/lark/feishu_channel_test.go b/server/internal/integrations/lark/feishu_channel_test.goindex 64b14f146a..0b0b18f513 100644--- a/server/internal/integrations/lark/feishu_channel_test.go+++ b/server/internal/integrations/lark/feishu_channel_test.go@@ -768,6 +768,7 @@ func TestDispatchResultFromEngine(t *testing.T) {Outcome: engine.OutcomeNeedsBinding,Sender: "ou_user",IssueIdentifier: "MUL-7",+ IssueDuplicate: true,})if res.Outcome != OutcomeNeedsBinding {t.Fatalf("outcome not mapped: %q", res.Outcome)@@ -778,4 +779,7 @@ func TestDispatchResultFromEngine(t *testing.T) {if res.IssueIdentifier != "MUL-7" {t.Fatalf("issue identifier not mapped: %q", res.IssueIdentifier)}+ if !res.IssueDuplicate {+ t.Fatal("issue duplicate flag not mapped")+ }}diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.goindex b8f27ea7fd..9c8701c037 100644--- a/server/internal/integrations/lark/feishu_resolvers.go+++ b/server/internal/integrations/lark/feishu_resolvers.go@@ -274,6 +274,7 @@ func dispatchResultFromEngine(res engine.Result) DispatchResult {IssueNumber: res.IssueNumber,IssueIdentifier: res.IssueIdentifier,IssueTitle: res.IssueTitle,+ IssueDuplicate: res.IssueDuplicate,}}diff --git a/server/internal/integrations/lark/feishu_types.go b/server/internal/integrations/lark/feishu_types.goindex 9691542e7c..8ed36f13a7 100644--- a/server/internal/integrations/lark/feishu_types.go+++ b/server/internal/integrations/lark/feishu_types.go@@ -95,4 +95,7 @@ type DispatchResult struct {IssueIdentifier string// IssueTitle is the title supplied on /issue, echoed in the confirmation.IssueTitle string+ // IssueDuplicate distinguishes an active-issue conflict from a successful+ // create while carrying the existing issue fields above.+ IssueDuplicate bool}diff --git a/server/internal/integrations/lark/outcome_replier.go b/server/internal/integrations/lark/outcome_replier.goindex 2914a09a90..0d71858636 100644--- a/server/internal/integrations/lark/outcome_replier.go+++ b/server/internal/integrations/lark/outcome_replier.go@@ -181,18 +181,13 @@ func (r *LarkOutcomeReplier) Reply(ctx context.Context, inst Installation, msg I)}case OutcomeIngested:- // The agent's chat reply itself goes through the Patcher (text- // message on ChatDone). But /issue does NOT block on the- // agent — the user expects an immediate "Created [MUL-42]"- // confirmation as soon as the issue row commits, separate- // from whatever the agent eventually replies. Without this,- // the user types `/issue fix login bug` and just sees the- // agent's eventual response, with no clear signal that the- // command itself was understood. Gate on IssueID.Valid so a- // plain chat message (no /issue) stays silent here.+ // The agent's chat reply itself goes through the Patcher. An /issue+ // command gets an immediate product result: either the newly created+ // issue or the active duplicate that blocked it. Gate on IssueID.Valid+ // so a plain chat message stays silent here.if res.IssueID.Valid {- if err := r.sendIssueCreated(ctx, inst, msg, res); err != nil {- r.log.Warn("lark outcome replier: issue-created confirmation failed",+ if err := r.sendIssueOutcome(ctx, inst, msg, res); err != nil {+ r.log.Warn("lark outcome replier: issue outcome reply failed","installation_id", uuidString(inst.ID),"chat_id", string(msg.ChatID),"issue_id", uuidString(res.IssueID),@@ -228,14 +223,9 @@ func (r *LarkOutcomeReplier) sendBindingPrompt(ctx context.Context, inst Install})}-// sendIssueCreated posts the "Created [MUL-42] <title>" confirmation-// as a plain text message. We deliberately send text rather than an-// interactive card so the confirmation flows inline with the rest of-// the Lark conversation — consistent with how chat replies render-// after MUL-2671's plain-text refactor. The link to Multica is-// included on its own line so Lark's auto-linker turns it into a-// tappable URL.-func (r *LarkOutcomeReplier) sendIssueCreated(ctx context.Context, inst Installation, msg InboundMessage, res DispatchResult) error {+// sendIssueOutcome posts either the created confirmation or active-duplicate+// conflict as plain text, with a link to the relevant issue when configured.+func (r *LarkOutcomeReplier) sendIssueOutcome(ctx context.Context, inst Installation, msg InboundMessage, res DispatchResult) error {if msg.ChatID == "" {return errors.New("missing chat_id")}@@ -244,12 +234,15 @@ func (r *LarkOutcomeReplier) sendIssueCreated(ctx context.Context, inst Installareturn err}text := issueCreatedText(res, r.appURL)+ if res.IssueDuplicate {+ text = issueDuplicateText(res, r.appURL)+ }// Share the Patcher's classified fallback: a thread reply that// fails because the topic cannot receive it (recalled trigger,// topics disabled, aggregated message) falls back to a chat-level- // send so the confirmation is not lost; transport/5xx/rate-limit+ // send so the product result is not lost; transport/5xx/rate-limit// failures stay failures rather than leaking into the group chat.- return sendWithThreadFallback(r.log, "send issue-created text", inboundReplyTarget(msg), func(t ReplyTarget) error {+ return sendWithThreadFallback(r.log, "send issue outcome text", inboundReplyTarget(msg), func(t ReplyTarget) error {_, err := r.client.SendTextMessage(ctx, SendTextParams{InstallationID: creds,ChatID: msg.ChatID,@@ -296,6 +289,24 @@ func issueCreatedText(res DispatchResult, appURL string) string {return line + "\n" + strings.TrimRight(appURL, "/") + "/issues/" + identifier}+func issueDuplicateText(res DispatchResult, appURL string) string {+ identifier := res.IssueIdentifier+ if identifier == "" {+ identifier = fmt.Sprintf("#%d", res.IssueNumber)+ }+ title := strings.TrimSpace(res.IssueTitle)+ var line string+ if title == "" {+ line = fmt.Sprintf("Not created — active issue %s already exists.", identifier)+ } else {+ line = fmt.Sprintf("Not created — active issue %s already exists: %s", identifier, title)+ }+ if appURL == "" {+ return line+ }+ return line + "\n" + strings.TrimRight(appURL, "/") + "/issues/" + identifier+}+func (r *LarkOutcomeReplier) sendChatNotice(ctx context.Context, inst Installation, msg InboundMessage, body string) error {if msg.ChatID == "" {return errors.New("missing chat_id")@@ -312,7 +323,7 @@ func (r *LarkOutcomeReplier) sendChatNotice(ctx context.Context, inst Installatiif err != nil {return fmt.Errorf("render notice card: %w", err)}- // Same classified fallback as sendIssueCreated: only thread-reply+ // Same classified fallback as sendIssueOutcome: only thread-reply// failures that mean the topic cannot receive the message fall back// to a chat-level send; ambiguous/transport failures stay failures.return sendWithThreadFallback(r.log, "send notice card", inboundReplyTarget(msg), func(t ReplyTarget) error {diff --git a/server/internal/integrations/lark/outcome_replier_test.go b/server/internal/integrations/lark/outcome_replier_test.goindex 50ddc8f940..5dbe254070 100644--- a/server/internal/integrations/lark/outcome_replier_test.go+++ b/server/internal/integrations/lark/outcome_replier_test.go@@ -389,6 +389,44 @@ func TestLarkOutcomeReplierIssueCreatedSendsConfirmation(t *testing.T) {}}+func TestLarkOutcomeReplierIssueDuplicateSendsConflict(t *testing.T) {+ t.Parallel()+ log := slog.New(slog.NewTextHandler(io.Discard, nil))+ stub := &stubAPIClientWithRecorder{configured: true}+ rep := NewLarkOutcomeReplier(OutcomeReplierConfig{+ APIClient: stub,+ BindingSvc: &BindingTokenService{},+ Credentials: stubCredentialsResolver{secret: "s"},+ Queries: stubReplierQueries{},+ AppURL: "https://multica.test",+ Logger: log,+ })++ inst := Installation{AppID: "cli_x"}+ inst.ID = mustUUID("11111111-1111-1111-1111-111111111111")+ rep.Reply(context.Background(), inst, InboundMessage{ChatID: "oc_chat_42"}, DispatchResult{+ Outcome: OutcomeIngested,+ IssueID: mustUUID("22222222-2222-2222-2222-222222222222"),+ IssueNumber: 42,+ IssueIdentifier: "MUL-42",+ IssueTitle: "fix login bug",+ IssueDuplicate: true,+ })++ stub.mu.Lock()+ defer stub.mu.Unlock()+ if len(stub.textOut) != 1 {+ t.Fatalf("expected one duplicate reply, got %d", len(stub.textOut))+ }+ text := stub.textOut[0].Text+ if !strings.Contains(text, "Not created") || !strings.Contains(text, "MUL-42") || !strings.Contains(text, "fix login bug") {+ t.Fatalf("duplicate reply = %q", text)+ }+ if strings.Contains(text, "Created MUL-42") {+ t.Fatalf("duplicate reply falsely claimed creation: %q", text)+ }+}+// TestLarkOutcomeReplierOutcomeIngestedSilentWithoutIssue pins the// silent-by-default behaviour for plain chat messages. The "Created"// text is gated on IssueID.Valid; a chat that didn't include /issuediff --git a/server/internal/integrations/slack/replier.go b/server/internal/integrations/slack/replier.goindex 73e82355dc..391194dc1c 100644--- a/server/internal/integrations/slack/replier.go+++ b/server/internal/integrations/slack/replier.go@@ -118,11 +118,15 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall"installation_id", util.UUIDToString(inst.ID), "error", err)}case engine.OutcomeIngested:- // Only a /issue-created message warrants a confirmation; a plain chat- // message stays silent (the agent's own reply lands via EventChatDone).+ // Only an /issue product result warrants an immediate reply; a plain+ // chat message stays silent (the agent's own reply lands via ChatDone).if res.IssueID.Valid {- if err := r.post(ctx, inst, msg, issueCreatedText(res)); err != nil {- r.logger.WarnContext(ctx, "slack replier: issue-created confirmation failed",+ text := issueCreatedText(res)+ if res.IssueDuplicate {+ text = issueDuplicateText(res)+ }+ if err := r.post(ctx, inst, msg, text); err != nil {+ r.logger.WarnContext(ctx, "slack replier: issue outcome reply failed","installation_id", util.UUIDToString(inst.ID), "error", err)}}@@ -178,13 +182,26 @@ func (r *OutboundReplier) post(ctx context.Context, inst engine.ResolvedInstalla}func issueCreatedText(res engine.Result) string {- id := res.IssueIdentifier- if id == "" {- id = fmt.Sprintf("#%d", res.IssueNumber)- }+ id := issueResultIdentifier(res)title := strings.TrimSpace(res.IssueTitle)if title == "" {return "✅ Created " + id}return "✅ Created " + id + " — " + title}++func issueDuplicateText(res engine.Result) string {+ id := issueResultIdentifier(res)+ title := strings.TrimSpace(res.IssueTitle)+ if title == "" {+ return "⚠️ Not created — active issue " + id + " already exists."+ }+ return "⚠️ Not created — active issue " + id + " already exists: " + title+}++func issueResultIdentifier(res engine.Result) string {+ if res.IssueIdentifier != "" {+ return res.IssueIdentifier+ }+ return fmt.Sprintf("#%d", res.IssueNumber)+}diff --git a/server/internal/integrations/slack/replier_test.go b/server/internal/integrations/slack/replier_test.goindex 05d4b93918..965e88c08f 100644--- a/server/internal/integrations/slack/replier_test.go+++ b/server/internal/integrations/slack/replier_test.go@@ -142,6 +142,27 @@ func TestReply_IngestedWithIssue_Confirms(t *testing.T) {}}+func TestReply_IngestedWithDuplicateIssue_ReportsConflict(t *testing.T) {+ sender := &fakeReplySender{}+ r := newTestReplier(&fakeBindingMinter{}, sender)+ r.Reply(context.Background(), testResolvedInstallation(t), testInboundForReply(), engine.Result{+ Outcome: engine.OutcomeIngested,+ IssueID: mustUUID(t, "55555555-5555-5555-5555-555555555555"),+ IssueIdentifier: "MUL-42",+ IssueTitle: "Fix the thing",+ IssueDuplicate: true,+ })+ if sender.calls != 1 || sender.sent == nil {+ t.Fatalf("expected one duplicate reply, got %d", sender.calls)+ }+ if !strings.Contains(sender.sent.Text, "Not created") || !strings.Contains(sender.sent.Text, "MUL-42") {+ t.Fatalf("duplicate reply = %q", sender.sent.Text)+ }+ if strings.Contains(sender.sent.Text, "Created MUL-42") {+ t.Fatalf("duplicate reply falsely claimed creation: %q", sender.sent.Text)+ }+}+func TestReply_IngestedWithoutIssue_Silent(t *testing.T) {sender := &fakeReplySender{}r := newTestReplier(&fakeBindingMinter{}, sender)@@ -173,6 +194,15 @@ func TestIssueCreatedText(t *testing.T) {}}+func TestIssueDuplicateText(t *testing.T) {+ got := issueDuplicateText(engine.Result{+ IssueIdentifier: "MUL-7", IssueTitle: "Title", IssueDuplicate: true,+ })+ if got != "⚠️ Not created — active issue MUL-7 already exists: Title" {+ t.Fatalf("duplicate text = %q", got)+ }+}+func textOrEmpty(m *channel.OutboundMessage) string {if m == nil {return ""diff --git a/server/internal/service/task_channel_command_media_test.go b/server/internal/service/task_channel_command_media_test.gonew file mode 100644index 0000000000..34f9c73ba2--- /dev/null+++ b/server/internal/service/task_channel_command_media_test.go@@ -0,0 +1,152 @@+package service++import (+ "context"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"++ "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"+)++// seedChannelCommandSession creates the chat session these tests enqueue+// against and drops the rows they leave behind in it.+func seedChannelCommandSession(t *testing.T, pool *pgxpool.Pool, workspaceID, agentID, userID string) string {+ t.Helper()+ ctx := context.Background()+ 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)+ }+ t.Cleanup(func() {+ cleanupCtx := context.Background()+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM agent_task_queue WHERE chat_session_id = $1`, chatSessionID)+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM chat_message WHERE chat_session_id = $1`, chatSessionID)+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID)+ })+ return chatSessionID+}++// TestEnqueueChatTaskIgnoresHandledCommandMedia is the counterpart of+// TestEnqueueChatTaskDefersForChannelMediaAndPromotesWhenReady, which pins the+// ordinary case. A channel `/issue` turn is answered synchronously by the+// router and is deliberately excluded from every later input batch, so the+// media it carries gates nothing: the next, unrelated message must not wait for+// the command's attachments to bind — nor for the whole fallback budget on the+// create-failure path, where no binder ever runs to clear the marker.+func TestEnqueueChatTaskIgnoresHandledCommandMedia(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)+ chatSessionID := seedChannelCommandSession(t, pool, workspaceID, agentID, userID)++ var commandID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, message_kind, channel_media_pending_until)+ VALUES ($1, 'user', '/issue login is broken [Image]', 'channel_command', $2)+ RETURNING id`, chatSessionID, time.Now().Add(time.Minute)).Scan(&commandID); err != nil {+ t.Fatalf("seed handled command: %v", err)+ }+ // The message that arms this flush: plain text of its own, no media.+ var questionID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content)+ VALUES ($1, 'user', 'unrelated question') RETURNING id`, chatSessionID).Scan(&questionID); err != nil {+ t.Fatalf("seed ordinary message: %v", err)+ }++ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}+ task, err := svc.EnqueueChatTask(ctx, db.ChatSession{+ ID: util.MustParseUUID(chatSessionID),+ AgentID: util.MustParseUUID(agentID),+ }, util.MustParseUUID(userID), false)+ if err != nil {+ t.Fatalf("EnqueueChatTask: %v", err)+ }+ if task.Status != "queued" || task.FireAt.Valid {+ t.Fatalf("task = status %q fire_at %v, want queued at once: the handled command's media gates no batch",+ task.Status, task.FireAt)+ }++ var owner pgtype.UUID+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, commandID).Scan(&owner); err != nil {+ t.Fatalf("load command owner: %v", err)+ }+ if owner.Valid {+ t.Fatalf("handled command was sealed into a later task: %s", util.UUIDToString(owner))+ }+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, questionID).Scan(&owner); err != nil {+ t.Fatalf("load question owner: %v", err)+ }+ if !owner.Valid || owner.Bytes != task.ID.Bytes {+ t.Fatalf("question task_id = %s, want %s", util.UUIDToString(owner), util.UUIDToString(task.ID))+ }+}++// TestPromoteChannelChatTasksIgnoresHandledCommandMedia covers the second gate.+// A task deferred for its OWN media must be promoted as soon as that media+// binds, even when a command turn landed meanwhile and is still resolving its+// attachments: the command is not part of the deferred task's input.+func TestPromoteChannelChatTasksIgnoresHandledCommandMedia(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)+ chatSessionID := seedChannelCommandSession(t, pool, workspaceID, agentID, userID)++ var mediaMessageID string+ if err := pool.QueryRow(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, channel_media_pending_until)+ VALUES ($1, 'user', '[Image] what is this?', $2) RETURNING id`,+ chatSessionID, time.Now().Add(time.Minute)).Scan(&mediaMessageID); err != nil {+ t.Fatalf("seed pending media message: %v", err)+ }++ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}+ task, err := svc.EnqueueChatTask(ctx, db.ChatSession{+ ID: util.MustParseUUID(chatSessionID),+ AgentID: util.MustParseUUID(agentID),+ }, util.MustParseUUID(userID), false)+ if err != nil {+ t.Fatalf("EnqueueChatTask: %v", err)+ }+ if task.Status != "deferred" {+ t.Fatalf("task status = %q, want deferred behind its own media", task.Status)+ }++ // A `/issue` command arrives while the task waits, and starts resolving its+ // own attachments.+ if _, err := pool.Exec(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, message_kind, channel_media_pending_until)+ VALUES ($1, 'user', '/issue ship the fix [Image]', 'channel_command', $2)`,+ chatSessionID, time.Now().Add(time.Minute)); err != nil {+ t.Fatalf("seed handled command: %v", err)+ }+ // The deferred task's own media finishes.+ if err := q.ClearChatMessageChannelMediaPending(ctx, db.ClearChatMessageChannelMediaPendingParams{+ ID: util.MustParseUUID(mediaMessageID),+ ChatSessionID: util.MustParseUUID(chatSessionID),+ }); err != nil {+ t.Fatalf("clear pending media: %v", err)+ }+ if err := svc.PromoteChannelChatTasksIfMediaReady(ctx, util.MustParseUUID(chatSessionID)); err != nil {+ t.Fatalf("PromoteChannelChatTasksIfMediaReady: %v", err)+ }++ var status string+ var fireAt pgtype.Timestamptz+ if err := pool.QueryRow(ctx, `SELECT status, fire_at FROM agent_task_queue WHERE id = $1`, task.ID).+ Scan(&status, &fireAt); err != nil {+ t.Fatalf("load promoted task: %v", err)+ }+ if status != "queued" || fireAt.Valid {+ t.Fatalf("task = status %q fire_at %v, want queued once its own media bound", status, fireAt)+ }+}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex c0997ca819..fa5f221919 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -608,6 +608,7 @@ SELECT channel_media_pending_untilFROM chat_messageWHERE chat_session_id = $1AND role = 'user'+ AND message_kind != 'channel_command'AND channel_media_pending_until > now()ORDER BY channel_media_pending_until DESCLIMIT 1@@ -615,6 +616,10 @@ LIMIT 1// The latest unexpired media deadline gates a channel task. Using a durable// task fire_at means a process restart still produces the placeholder fallback.+// Only a turn that can join a task's input batch may gate one: channel_command+// turns are excluded from the seal below, so an unrelated later message would+// otherwise wait out a command's media (or its whole fallback budget, since a+// command whose create failed never runs the binder that clears the marker).func (q *Queries) GetChannelMediaPendingUntil(ctx context.Context, chatSessionID pgtype.UUID) (pgtype.Timestamptz, error) {row := q.db.QueryRow(ctx, getChannelMediaPendingUntil, chatSessionID)var channel_media_pending_until pgtype.Timestamptz@@ -999,6 +1004,7 @@ SET task_id = $1WHERE message.chat_session_id = $2AND message.role = 'user'AND message.task_id IS NULL+ AND message.message_kind != 'channel_command'AND NOT EXISTS (SELECT 1FROM chat_message AS prior@@ -1016,6 +1022,8 @@ type LinkUnownedChannelChatMessagesToTaskParams struct {// Seals the trailing channel-message batch to its task. The task row and these// links are committed together, so an older in-flight task cannot absorb a// newer media message and a later assistant row cannot hide that message.+// channel_command turns were already handled synchronously by Router; keeping+// them visible but unowned prevents both immediate and delayed re-execution.func (q *Queries) LinkUnownedChannelChatMessagesToTask(ctx context.Context, arg LinkUnownedChannelChatMessagesToTaskParams) error {_, err := q.db.Exec(ctx, linkUnownedChannelChatMessagesToTask, arg.TaskID, arg.ChatSessionID)return err@@ -1980,6 +1988,7 @@ WHERE task.chat_session_id = $1FROM chat_message AS messageWHERE message.chat_session_id = $1AND message.role = 'user'+ AND message.message_kind != 'channel_command'AND message.channel_media_pending_until > now())RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for@@ -1987,7 +1996,10 @@ RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, tas// Media completion may race with the 3s run batcher. Promote every original// channel task waiting for this session only after all unexpired media markers-// are gone; retry/escalation/direct-chat deferred tasks are excluded.+// are gone; retry/escalation/direct-chat deferred tasks are excluded. The+// marker scan uses the same population as GetChannelMediaPendingUntil and the+// seal: a channel_command turn belongs to no batch, so it must not hold a+// deferred task back either.func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatSessionID pgtype.UUID) ([]AgentTaskQueue, error) {rows, err := q.db.Query(ctx, promoteChannelChatTasksIfMediaReady, chatSessionID)if err != nil {diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex adb59a17e2..c4b59361be 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -379,10 +379,15 @@ SELECT EXISTS (-- name: GetChannelMediaPendingUntil :one-- The latest unexpired media deadline gates a channel task. Using a durable-- task fire_at means a process restart still produces the placeholder fallback.+-- Only a turn that can join a task's input batch may gate one: channel_command+-- turns are excluded from the seal below, so an unrelated later message would+-- otherwise wait out a command's media (or its whole fallback budget, since a+-- command whose create failed never runs the binder that clears the marker).SELECT channel_media_pending_untilFROM chat_messageWHERE chat_session_id = $1AND role = 'user'+ AND message_kind != 'channel_command'AND channel_media_pending_until > now()ORDER BY channel_media_pending_until DESCLIMIT 1;@@ -401,11 +406,14 @@ WHERE id = $1 AND role = 'user';-- Seals the trailing channel-message batch to its task. The task row and these-- links are committed together, so an older in-flight task cannot absorb a-- newer media message and a later assistant row cannot hide that message.+-- channel_command turns were already handled synchronously by Router; keeping+-- them visible but unowned prevents both immediate and delayed re-execution.UPDATE chat_message AS messageSET task_id = @task_idWHERE message.chat_session_id = @chat_session_idAND message.role = 'user'AND message.task_id IS NULL+ AND message.message_kind != 'channel_command'AND NOT EXISTS (SELECT 1FROM chat_message AS prior@@ -537,7 +545,10 @@ RETURNING *;-- name: PromoteChannelChatTasksIfMediaReady :many-- Media completion may race with the 3s run batcher. Promote every original-- channel task waiting for this session only after all unexpired media markers--- are gone; retry/escalation/direct-chat deferred tasks are excluded.+-- are gone; retry/escalation/direct-chat deferred tasks are excluded. The+-- marker scan uses the same population as GetChannelMediaPendingUntil and the+-- seal: a channel_command turn belongs to no batch, so it must not hold a+-- deferred task back either.UPDATE agent_task_queue AS taskSET status = 'queued', fire_at = NULLWHERE task.chat_session_id = @chat_session_id@@ -550,6 +561,7 @@ WHERE task.chat_session_id = @chat_session_idFROM chat_message AS messageWHERE message.chat_session_id = @chat_session_idAND message.role = 'user'+ AND message.message_kind != 'channel_command'AND message.channel_media_pending_until > now())RETURNING task.*;