Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5966 fix(channels): skip media for duplicate issue commands (#6688)
YYClawd317eb3f461c
diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 96053cccdf..af53f354d6 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -448,10 +448,12 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channeres.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.+ // failure and not a chat prompt. Finalize the durable chat message's+ // media state without resolving it. There is no new issue to consume+ // the media, so downloading and persisting attachments would only+ // create unused resources.if resolveMedia {- r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, duplicate, pgtype.Text{}, "", pgtype.UUID{}, localMediaDeadline)+ r.enqueueMediaFinalization(set, inst, identity, appendRes.MessageID, msg, sessionID, localMediaDeadline)}return res, postAppendFinalize, nil}@@ -506,6 +508,32 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// task service defers a task to the persisted media deadline, then media// completion promotes it early.func (r *Router) enqueueMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueDescriptionBase pgtype.Text, issueCommandText string, issueTaskID pgtype.UUID, deadline time.Time) {+ r.enqueueMediaJob(set, inst, identity, chatMessageID, msg, sessionID, issue, issueDescriptionBase, issueCommandText, issueTaskID, true, deadline)+}++// enqueueMediaFinalization clears the durable media-pending marker without+// invoking the platform resolver. Duplicate /issue commands use this because+// neither the existing issue nor the hidden command message should gain a new+// copy of media that no newly-created issue will consume.+func (r *Router) enqueueMediaFinalization(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, deadline time.Time) {+ r.mediaQueueMu.Lock()+ if r.stopping {+ r.mediaQueueMu.Unlock()+ return+ }+ r.mediaWg.Add(1)+ r.mediaQueueMu.Unlock()++ go func() {+ defer r.mediaWg.Done()+ // A channel_command message cannot join or gate a chat task's input+ // batch, so clearing its own pending marker need not wait behind the+ // session's ordered remote-media queue.+ r.resolveAndBindMedia(set, inst, identity, chatMessageID, msg, sessionID, db.Issue{}, pgtype.Text{}, "", pgtype.UUID{}, false, deadline)+ }()+}++func (r *Router) enqueueMediaJob(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueDescriptionBase pgtype.Text, issueCommandText string, issueTaskID pgtype.UUID, resolveRemote bool, deadline time.Time) {key := keyForSession(sessionID)done := make(chan struct{})@@ -546,7 +574,7 @@ func (r *Router) enqueueMedia(set ResolverSet, inst ResolvedInstallation, identiexpired = true}}- if !expired {+ if !expired && resolveRemote {select {case r.mediaSem <- struct{}{}:defer func() { <-r.mediaSem }()@@ -560,18 +588,20 @@ func (r *Router) enqueueMedia(set ResolverSet, inst ResolvedInstallation, identi// sees the dead deadline and runs only the empty finalize.}}- r.resolveAndBindMedia(set, inst, identity, chatMessageID, msg, sessionID, issue, issueDescriptionBase, issueCommandText, issueTaskID, deadline)+ r.resolveAndBindMedia(set, inst, identity, chatMessageID, msg, sessionID, issue, issueDescriptionBase, issueCommandText, issueTaskID, resolveRemote, deadline)}()}const mediaFinalizeTimeout = 5 * time.Second-func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueDescriptionBase pgtype.Text, issueCommandText string, issueTaskID pgtype.UUID, deadline time.Time) {+func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueDescriptionBase pgtype.Text, issueCommandText string, issueTaskID pgtype.UUID, resolveRemote bool, deadline time.Time) {ctx, cancel := context.WithDeadline(r.mediaCtx, deadline)defer cancel()resolved := msg- if ctx.Err() == nil {+ if !resolveRemote {+ resolved.MediaRefs = nil+ } else if ctx.Err() == nil {// Skipped entirely when the budget expired while queued (or on// shutdown): resolving on a dead context would only churn through// intent writes that immediately fail.@@ -579,7 +609,7 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,}finalizeCtx, finalizeCancel := context.WithTimeout(context.Background(), mediaFinalizeTimeout)defer finalizeCancel()- if err := ctx.Err(); err != nil {+ if err := ctx.Err(); resolveRemote && err != nil {// Refs resolved before the deadline already sit in object storage but// will not gain an attachment row. Nothing is deleted here — their// intent-ledger rows were written before the uploads, and thediff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex 50ad9e73bf..7fd5661f04 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -1,8 +1,10 @@package engineimport (+ "bytes""context""errors"+ "log/slog""sync""sync/atomic""testing"@@ -898,11 +900,20 @@ func TestRouter_IssueCommand_ActiveDuplicateIsTerminalProductOutcome(t *testing.}) {t.Fatalf("duplicate result was not delivered to replier: %+v", h.replier.calls())}- if !waitFor(time.Second, func() bool { return len(h.binder.boundMedia().MediaRefs) == 1 }) {+ if !waitFor(time.Second, func() bool { return h.binder.boundMedia().MessageID.Valid }) {t.Fatalf("duplicate media was not finalized: %+v", h.binder.boundMedia())}- if got := h.binder.boundMedia().IssueID; got != duplicate.ID {- t.Fatalf("duplicate media target = %v, want %v", got, duplicate.ID)+ if h.media.calls() != 0 {+ t.Fatalf("duplicate media unexpectedly invoked resolver, calls=%d", h.media.calls())+ }+ if got := h.binder.boundMedia().MediaRefs; len(got) != 0 {+ t.Fatalf("duplicate media unexpectedly persisted refs: %+v", got)+ }+ if got := h.binder.boundMedia().IssueID; got.Valid {+ t.Fatalf("duplicate media unexpectedly targeted existing issue %v", got)+ }+ if h.issues.attachmentsChanged.Load() != 0 {+ t.Fatalf("duplicate media published issue attachment changes = %d, want 0", h.issues.attachmentsChanged.Load())}h.tasks.mu.Lock()issuePromotions := len(h.tasks.issueTaskPromotions)@@ -912,6 +923,100 @@ func TestRouter_IssueCommand_ActiveDuplicateIsTerminalProductOutcome(t *testing.}}+func TestRouter_IssueCommand_ActiveDuplicateFinalizesWithoutWaitingForSessionMedia(t *testing.T) {+ h := newHarness(t)+ firstStarted := make(chan struct{})+ releaseFirst := make(chan struct{})+ var releaseOnce sync.Once+ t.Cleanup(func() { releaseOnce.Do(func() { close(releaseFirst) }) })+ h.media.resolve = func(_ context.Context, msg channel.InboundMessage) channel.InboundMessage {+ if msg.MessageID == "om-first" {+ close(firstStarted)+ <-releaseFirst+ }+ return msg+ }++ first := p2pMessage(t)+ first.MessageID = "om-first"+ if err := h.router.Handle(context.Background(), first); err != nil {+ t.Fatalf("first Handle: %v", err)+ }+ select {+ case <-firstStarted:+ case <-time.After(time.Second):+ t.Fatal("first session media job did not start")+ }++ duplicateMessageID := uuidFromString(t, "77777777-7777-4777-8777-777777777777")+ h.binder.appendResult = AppendResult{+ MessageID: duplicateMessageID,+ 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++ second := p2pMessage(t)+ second.MessageID = "om-duplicate"+ if err := h.router.Handle(context.Background(), second); err != nil {+ t.Fatalf("duplicate Handle: %v", err)+ }+ if !waitFor(time.Second, func() bool { return h.binder.boundMedia().MessageID == duplicateMessageID }) {+ t.Fatal("duplicate finalization waited behind the session's active media resolver")+ }+ if h.media.calls() != 1 {+ t.Fatalf("duplicate finalization invoked media resolver, calls=%d", h.media.calls())+ }+ if got := h.binder.boundMedia(); len(got.MediaRefs) != 0 || got.IssueID.Valid {+ t.Fatalf("duplicate finalization persisted media or targeted the issue: %+v", got)+ }++ releaseOnce.Do(func() { close(releaseFirst) })+ if !waitFor(time.Second, func() bool { return h.tasks.promotionCalls() == 2 }) {+ t.Fatalf("session media job did not finish after release, promotions=%d", h.tasks.promotionCalls())+ }+}++func TestRouter_MediaFinalizationExpiredDeadlineDoesNotLogResolutionFailure(t *testing.T) {+ h := newHarness(t)+ var logs bytes.Buffer+ h.router.logger = slog.New(slog.NewTextHandler(&logs, nil))+ messageID := uuidFromString(t, "77777777-7777-4777-8777-777777777777")++ h.router.resolveAndBindMedia(+ ResolverSet{Session: h.binder, Media: h.media},+ h.inst.inst,+ h.ident.id,+ messageID,+ p2pMessage(t),+ h.binder.ensureID,+ db.Issue{},+ pgtype.Text{},+ "",+ pgtype.UUID{},+ false,+ time.Now().Add(-time.Second),+ )++ if got := h.binder.boundMedia(); got.MessageID != messageID || len(got.MediaRefs) != 0 {+ t.Fatalf("expired finalize-only bind = %+v", got)+ }+ if h.media.calls() != 0 {+ t.Fatalf("finalize-only path invoked media resolver, calls=%d", h.media.calls())+ }+ if bytes.Contains(logs.Bytes(), []byte("media resolution incomplete")) {+ t.Fatalf("finalize-only path logged a media resolution failure: %s", logs.String())+ }+}+func TestRouter_IssueCommand_InfrastructureFailureRemainsError(t *testing.T) {h := newHarness(t)h.binder.appendResult = AppendResult{diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.goindex 5e282e2b64..52ecfa6332 100644--- a/server/internal/integrations/channel/engine/session_db_test.go+++ b/server/internal/integrations/channel/engine/session_db_test.go@@ -295,6 +295,72 @@ func TestBindMediaRefs_IssueAttachmentSurvivesChatSessionDeletion(t *testing.T)}}+func TestBindMediaRefs_EmptyRefsCreateNoAttachmentAndClearPending(t *testing.T) {+ pool := sessionPersistenceTestDB(t)+ fixture := seedSessionPersistenceFixture(t, pool)+ session := NewChatSession(db.New(pool), pool, channel.Type("dingtalk"), SessionTitles{})+ ctx := context.Background()++ var issueID pgtype.UUID+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, number)+ VALUES ($1, 'Existing issue', 'todo', 'none', 'member', $2, 1)+ RETURNING id+ `, fixture.workspaceID, fixture.userID).Scan(&issueID); err != nil {+ t.Fatalf("create existing issue: %v", err)+ }+ if _, err := pool.Exec(ctx, `+ INSERT INTO attachment (+ workspace_id, issue_id, uploader_type, uploader_id,+ filename, url, content_type, size_bytes+ ) VALUES ($1, $2, 'member', $3, 'original.png',+ 'https://cdn.example.test/original-issue-image', 'image/png', 3)+ `, fixture.workspaceID, issueID, fixture.userID); err != nil {+ t.Fatalf("create original issue attachment: %v", err)+ }+ appendRes, err := session.AppendUserMessage(ctx, AppendInput{+ SessionID: fixture.sessionID,+ Sender: fixture.userID,+ Body: "/issue Existing issue\n[Image]",+ CommandText: "/issue Existing issue",+ MediaPendingSeconds: 60,+ })+ if err != nil {+ t.Fatalf("append duplicate issue command: %v", err)+ }++ if err := session.BindMediaRefs(ctx, BindMediaInput{+ MessageID: appendRes.MessageID,+ SessionID: fixture.sessionID,+ WorkspaceID: fixture.workspaceID,+ Sender: fixture.userID,+ Body: "/issue Existing issue\n[Image]",+ }); err != nil {+ t.Fatalf("finalize duplicate issue media: %v", err)+ }++ var issueAttachmentCount, workspaceAttachmentCount int+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM attachment WHERE issue_id = $1`, issueID).Scan(&issueAttachmentCount); err != nil {+ t.Fatalf("count existing issue attachments: %v", err)+ }+ if issueAttachmentCount != 1 {+ t.Fatalf("existing issue attachment rows = %d, want unchanged count 1", issueAttachmentCount)+ }+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM attachment WHERE workspace_id = $1`, fixture.workspaceID).Scan(&workspaceAttachmentCount); err != nil {+ t.Fatalf("count workspace attachments: %v", err)+ }+ if workspaceAttachmentCount != 1 {+ t.Fatalf("workspace attachment rows = %d, want no new rows beyond the original", workspaceAttachmentCount)+ }+ var mediaPendingUntil pgtype.Timestamptz+ if err := pool.QueryRow(ctx, `SELECT channel_media_pending_until FROM chat_message WHERE id = $1`, appendRes.MessageID).Scan(&mediaPendingUntil); err != nil {+ t.Fatalf("load duplicate command media marker: %v", err)+ }+ if mediaPendingUntil.Valid {+ t.Fatalf("duplicate command kept media pending until %v", mediaPendingUntil.Time)+ }+}+func TestBindMediaRefs_MaterializesIssueImagesInOriginalRichTextOrder(t *testing.T) {pool := sessionPersistenceTestDB(t)fixture := seedSessionPersistenceFixture(t, pool)