Skip to content

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

Go

MUL-7209 fix(lark): reply natively and mention the asker in ordinary groups (#8238)

Bohan Jiang091d3ce5de65
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index e79ac91128..daa7f727db 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -74,6 +74,7 @@ type SessionQueries interface {
ResolveChannelChatContextHistoryStart(ctx context.Context, arg db.ResolveChannelChatContextHistoryStartParams) error
SetChannelChatContextInitiator(ctx context.Context, arg db.SetChannelChatContextInitiatorParams) (pgtype.UUID, error)
UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) error
+ SetChannelChatContextReplyTarget(ctx context.Context, arg db.SetChannelChatContextReplyTargetParams) error
MarkChannelInboundDedupProcessed(ctx context.Context, arg db.MarkChannelInboundDedupProcessedParams) (int64, error)
}
@@ -205,6 +206,9 @@ func (a dbSessionQueries) SetChannelChatContextInitiator(ctx context.Context, ar
func (a dbSessionQueries) UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) error {
return a.q.UpdateChannelChatSessionBindingReplyTarget(ctx, arg)
}
+func (a dbSessionQueries) SetChannelChatContextReplyTarget(ctx context.Context, arg db.SetChannelChatContextReplyTargetParams) error {
+ return a.q.SetChannelChatContextReplyTarget(ctx, arg)
+}
func (a dbSessionQueries) MarkChannelInboundDedupProcessed(ctx context.Context, arg db.MarkChannelInboundDedupProcessedParams) (int64, error) {
return a.q.MarkChannelInboundDedupProcessed(ctx, arg)
}
@@ -379,14 +383,20 @@ func (s *ChatSession) createSessionAndBinding(ctx context.Context, in EnsureSess
// its own binding row, recording the real thread here per session does not clash
// across sibling threads.
type AppendInput struct {
- SessionID pgtype.UUID
- Sender pgtype.UUID
- InstallationID pgtype.UUID
- Body string
- CommandText string
- MessageID string
- DedupMessageID string
- ThreadID string
+ SessionID pgtype.UUID
+ Sender pgtype.UUID
+ InstallationID pgtype.UUID
+ Body string
+ CommandText string
+ MessageID string
+ DedupMessageID string
+ ThreadID string
+ // SenderChannelID is the platform-native id of whoever sent THIS message
+ // (Lark open_id, Slack user id, ...). Sender above is the Multica user it
+ // resolved to; both are recorded because the outbound side needs the
+ // platform id to render a native @-mention, and a Multica user can hold
+ // more than one platform identity on the same installation.
+ SenderChannelID string
ClaimToken pgtype.UUID
MediaPendingSeconds float64
ForceFresh bool
@@ -407,10 +417,12 @@ type StartSessionInput struct {
// CommandText is the current member-authored instruction before adapter
// context enrichment. It is used only for the initial Chat title; Body
// remains the canonical persisted/agent-visible content.
- CommandText string
- MessageID string
- DedupMessageID string
- ThreadID string
+ CommandText string
+ MessageID string
+ DedupMessageID string
+ ThreadID string
+ // SenderChannelID mirrors AppendInput.SenderChannelID.
+ SenderChannelID string
ClaimToken pgtype.UUID
MediaPendingSeconds float64
PersistMessage bool
@@ -544,6 +556,17 @@ func (s *ChatSession) StartSession(ctx context.Context, in StartSessionInput) (S
}); err != nil {
return StartSessionResult{}, fmt.Errorf("set started chat reply target: %w", err)
}
+ // A started session opens at revision 1, and the message that started
+ // it is that generation's trigger.
+ if err := qtx.SetChannelChatContextReplyTarget(ctx, db.SetChannelChatContextReplyTargetParams{
+ ChatSessionID: session.ID,
+ Revision: 1,
+ LastMessageID: textOrNull(in.MessageID),
+ LastThreadID: textOrNull(in.ThreadID),
+ LastSenderID: textOrNull(in.SenderChannelID),
+ }); err != nil {
+ return StartSessionResult{}, fmt.Errorf("snapshot started chat reply target: %w", err)
+ }
}
dedupMessageID := in.DedupMessageID
if dedupMessageID == "" {
@@ -704,6 +727,21 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
}); err != nil {
return AppendResult{}, fmt.Errorf("snapshot channel context initiator: %w", err)
}
+ // The trigger an outbound reply answers, snapshotted on the same
+ // generation and under the same command guard as the initiator above:
+ // a message excluded from agent input is not the question being
+ // answered, so it must not become the message the answer quotes.
+ if in.MessageID != "" {
+ if err := qtx.SetChannelChatContextReplyTarget(ctx, db.SetChannelChatContextReplyTargetParams{
+ ChatSessionID: in.SessionID,
+ Revision: contextRevision,
+ LastMessageID: textOrNull(in.MessageID),
+ LastThreadID: textOrNull(in.ThreadID),
+ LastSenderID: textOrNull(in.SenderChannelID),
+ }); err != nil {
+ return AppendResult{}, fmt.Errorf("snapshot channel context reply target: %w", err)
+ }
+ }
}
// channel_ingested is the immutable provenance the cancel path gates on:
// it must be stamped in the same transaction as the message so no later
@@ -729,8 +767,10 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
return AppendResult{}, fmt.Errorf("touch chat session: %w", err)
}
- // Record the latest trigger so the decoupled outbound patcher can thread
- // its reply back into the originating topic.
+ // Advance the session's latest-trigger cursor, which the history-boundary
+ // bookkeeping reads. The outbound reply target is NOT taken from here — it
+ // is frozen per generation above, because this cursor belongs to the
+ // session and a debounced run answers one generation of it.
if in.MessageID != "" {
if err := qtx.UpdateChannelChatSessionBindingReplyTarget(ctx, db.UpdateChannelChatSessionBindingReplyTargetParams{
ReplyChatSessionID: in.SessionID,
diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.go
index 0c3e9539d7..c8ae3a5f29 100644
--- a/server/internal/integrations/channel/engine/session_db_test.go
+++ b/server/internal/integrations/channel/engine/session_db_test.go
@@ -16,6 +16,7 @@ import (
"github.com/multica-ai/multica/server/internal/channelmedia"
"github.com/multica-ai/multica/server/internal/integrations/channel"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
)
func sessionPersistenceTestDB(t *testing.T) *pgxpool.Pool {
@@ -1166,3 +1167,360 @@ func TestAppendUserMessage_MediaDeadlineUsesDatabaseClock(t *testing.T) {
t.Fatalf("deadline remaining = %.2fs (DB clock), want ~60s budget", remaining)
}
}
+
+// TestChannelTaskDeliveryFreezesTriggerPerGeneration is the regression for the
+// cross-generation mis-attribution #8234 has to survive.
+//
+// The debouncer keys its timers on (chat_session, context revision), so a run
+// batched in revision 1 can be enqueued AFTER a /clear has opened revision 2
+// and revision 2's own message has already committed. If the delivery snapshot
+// read the session's latest trigger, A's answer would quote and @-mention B —
+// and the ordering here is the ordinary one, not a rare interleaving: it only
+// needs B's append to commit before A's flush fires, which is what a 3s
+// debounce window invites.
+//
+// Both generations are appended first, with NO delivery created in between,
+// and only then are the two tasks enqueued. That is what distinguishes this
+// from "a created delivery is immutable" — the value has to be correct at
+// creation time, not merely stable afterwards.
+func TestChannelTaskDeliveryFreezesTriggerPerGeneration(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ f := seedSessionPersistenceFixture(t, pool)
+ ctx := context.Background()
+ q := db.New(pool)
+
+ recordGeneration := func(revision int64, messageID, senderID string) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ VALUES ($1, $2)
+ ON CONFLICT DO NOTHING
+ `, f.sessionID, revision); err != nil {
+ t.Fatalf("create generation %d: %v", revision, err)
+ }
+ if err := q.SetChannelChatContextReplyTarget(ctx, db.SetChannelChatContextReplyTargetParams{
+ ChatSessionID: f.sessionID, Revision: revision,
+ LastMessageID: pgtype.Text{String: messageID, Valid: true},
+ LastSenderID: pgtype.Text{String: senderID, Valid: true},
+ }); err != nil {
+ t.Fatalf("snapshot generation %d reply target: %v", revision, err)
+ }
+ // Every inbound turn also advances the session-wide cursor, which is
+ // exactly the value that must NOT reach the delivery rows below.
+ if err := q.UpdateChannelChatSessionBindingReplyTarget(ctx, db.UpdateChannelChatSessionBindingReplyTargetParams{
+ ReplyChatSessionID: f.sessionID,
+ LastMessageID: pgtype.Text{String: messageID, Valid: true},
+ }); err != nil {
+ t.Fatalf("advance session cursor for %d: %v", revision, err)
+ }
+ }
+
+ // A asks in revision 1; before its debounce fires, B's /clear opens
+ // revision 2 and B's question lands there. The session cursor now reads B.
+ recordGeneration(1, "om_from_alice", "ou_alice")
+ recordGeneration(2, "om_from_bob", "ou_bob")
+
+ // Pin the hazard this test exists for: the session-wide cursor now reads
+ // B, so sourcing the delivery from the binding — what this code did before
+ // #8234 — would hand revision 1 B's message and B's sender.
+ binding, err := q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
+ ChatSessionID: f.sessionID, ChannelType: "lark",
+ })
+ if err != nil {
+ t.Fatalf("read binding cursor: %v", err)
+ }
+ if binding.LastMessageID.String != "om_from_bob" {
+ t.Fatalf("precondition: session cursor = %q, want om_from_bob so the wrong answer is genuinely reachable",
+ binding.LastMessageID.String)
+ }
+
+ for _, tc := range []struct {
+ name string
+ revision int64
+ wantMessage string
+ wantSender string
+ }{
+ {"revision 1 (A)", 1, "om_from_alice", "ou_alice"},
+ {"revision 2 (B)", 2, "om_from_bob", "ou_bob"},
+ } {
+ taskID := newDeliveryTaskID(t, pool)
+ delivery, err := q.CreateChannelTaskDeliveryFromSession(ctx, db.CreateChannelTaskDeliveryFromSessionParams{
+ TaskID: taskID, ChatSessionID: f.sessionID, ContextRevision: tc.revision,
+ })
+ if err != nil {
+ t.Fatalf("%s: create delivery: %v", tc.name, err)
+ }
+ if delivery.ChannelMessageID.String != tc.wantMessage {
+ t.Errorf("%s: message = %q, want %q — the delivery must freeze its OWN generation's trigger",
+ tc.name, delivery.ChannelMessageID.String, tc.wantMessage)
+ }
+ if delivery.ChannelSenderID.String != tc.wantSender {
+ t.Errorf("%s: sender = %q, want %q", tc.name, delivery.ChannelSenderID.String, tc.wantSender)
+ }
+ // The route still comes from the binding, which is per-session.
+ if delivery.ChannelChatID != f.channelChatID {
+ t.Errorf("%s: chat id = %q, want the session's route %q",
+ tc.name, delivery.ChannelChatID, f.channelChatID)
+ }
+ }
+}
+
+// TestChannelTaskDeliveryFreezesThreadPerGeneration is the Slack-DM shape,
+// and the reason the reply thread is trigger data rather than route data.
+//
+// It is tempting to call the thread "route" and read it from the binding: for
+// a thread-ISOLATED session (Lark topic, Slack channel thread) there is one
+// binding per thread, so the two coincide. Slack DMs break that. Per
+// slackSessionRouting, a DM keeps ONE binding for the whole channel while
+// replying into whichever thread the member used, so the binding cursor names
+// the thread that spoke LAST — not the one this run answers.
+//
+// Here revision 1 is asked inside thread T1 and revision 2 at top level, both
+// appended before either delivery exists. Each delivery must keep its own
+// thread; the binding cursor at that point holds revision 2's.
+func TestChannelTaskDeliveryFreezesThreadPerGeneration(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ f := seedSessionPersistenceFixture(t, pool)
+ ctx := context.Background()
+ q := db.New(pool)
+
+ record := func(revision int64, messageID, threadID, senderID string) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ VALUES ($1, $2) ON CONFLICT DO NOTHING
+ `, f.sessionID, revision); err != nil {
+ t.Fatalf("create generation %d: %v", revision, err)
+ }
+ if err := q.SetChannelChatContextReplyTarget(ctx, db.SetChannelChatContextReplyTargetParams{
+ ChatSessionID: f.sessionID, Revision: revision,
+ LastMessageID: pgtype.Text{String: messageID, Valid: true},
+ LastThreadID: pgtype.Text{String: threadID, Valid: threadID != ""},
+ LastSenderID: pgtype.Text{String: senderID, Valid: true},
+ }); err != nil {
+ t.Fatalf("snapshot generation %d: %v", revision, err)
+ }
+ if err := q.UpdateChannelChatSessionBindingReplyTarget(ctx, db.UpdateChannelChatSessionBindingReplyTargetParams{
+ ReplyChatSessionID: f.sessionID,
+ LastMessageID: pgtype.Text{String: messageID, Valid: true},
+ LastThreadID: pgtype.Text{String: threadID, Valid: threadID != ""},
+ }); err != nil {
+ t.Fatalf("advance session cursor for %d: %v", revision, err)
+ }
+ }
+
+ recordGeneration := record
+ recordGeneration(1, "om_in_thread", "thread_T1", "U_alice")
+ recordGeneration(2, "om_top_level", "", "U_bob")
+
+ // The wrong answer is reachable: the binding cursor no longer has T1.
+ binding, err := q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
+ ChatSessionID: f.sessionID, ChannelType: "lark",
+ })
+ if err != nil {
+ t.Fatalf("read binding cursor: %v", err)
+ }
+ if binding.LastThreadID.Valid {
+ t.Fatalf("precondition: session cursor thread = %+v, want cleared by revision 2", binding.LastThreadID)
+ }
+
+ for _, tc := range []struct {
+ name string
+ revision int64
+ wantThread string
+ }{
+ {"revision 1, asked inside T1", 1, "thread_T1"},
+ {"revision 2, asked at top level", 2, ""},
+ } {
+ taskID := newDeliveryTaskID(t, pool)
+ delivery, err := q.CreateChannelTaskDeliveryFromSession(ctx, db.CreateChannelTaskDeliveryFromSessionParams{
+ TaskID: taskID, ChatSessionID: f.sessionID, ContextRevision: tc.revision,
+ })
+ if err != nil {
+ t.Fatalf("%s: create delivery: %v", tc.name, err)
+ }
+ if delivery.ChannelThreadID.String != tc.wantThread {
+ t.Errorf("%s: thread = %q, want %q — the reply thread belongs to the generation, not the session cursor",
+ tc.name, delivery.ChannelThreadID.String, tc.wantThread)
+ }
+ }
+}
+
+// TestChannelTaskDeliveryRecoversThreadForIsolatedBinding covers the shape
+// migration 460 leaves behind on every thread-isolated channel: a generation
+// with no trigger at all, recovered after deploy.
+//
+// The trigger is legitimately unknown there. The THREAD is not: a Slack
+// channel thread, Telegram forum topic or Lark topic keeps one binding per
+// thread, so its last_thread_id is a stable property of the session rather
+// than a moving cursor. Dropping it would put a recovered run's answer in the
+// parent channel — the same relocation this PR already closed once for the
+// live path.
+//
+// Both consumers read delivery.channel_thread_id directly
+// (slackBindingFromTaskDelivery -> outboundTarget, telegramBindingFromTaskDelivery
+// -> outboundTarget), so this column is the canonical layer for the guarantee.
+// Lark also needs a trigger MESSAGE to enter a topic and declines to send
+// without one; see topicSendWithoutTrigger.
+func TestChannelTaskDeliveryRecoversThreadForIsolatedBinding(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ ctx := context.Background()
+ q := db.New(pool)
+
+ for _, tc := range []struct {
+ name string
+ bindingKey func(chatID string) string
+ config string
+ wantThread string
+ }{
+ {
+ // Composite key + a config naming the real channel: the marker every
+ // adapter writes for a thread-isolated session.
+ name: "isolated binding recovers its thread",
+ bindingKey: func(chatID string) string { return chatID + ":thread_T1" },
+ config: `{"channel_id":%q}`,
+ wantThread: "thread_T1",
+ },
+ {
+ // A DM/plain chat: the key IS the chat, so last_thread_id is only
+ // ever "whoever spoke last" and must not be borrowed.
+ name: "non-isolated binding recovers nothing",
+ bindingKey: func(chatID string) string { return chatID },
+ config: `{"channel_id":%q}`,
+ wantThread: "",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := seedIsolatedBindingFixture(t, pool, tc.bindingKey, tc.config)
+ // Pre-460 generation: no trigger recorded at all.
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ VALUES ($1, 1) ON CONFLICT DO NOTHING
+ `, f.sessionID); err != nil {
+ t.Fatalf("create generation: %v", err)
+ }
+ // The session cursor still remembers the thread, as it always has.
+ if err := q.UpdateChannelChatSessionBindingReplyTarget(ctx, db.UpdateChannelChatSessionBindingReplyTargetParams{
+ ReplyChatSessionID: f.sessionID,
+ LastMessageID: pgtype.Text{String: "om_before_deploy", Valid: true},
+ LastThreadID: pgtype.Text{String: "thread_T1", Valid: true},
+ }); err != nil {
+ t.Fatalf("seed session cursor: %v", err)
+ }
+
+ taskID := newDeliveryTaskID(t, pool)
+ delivery, err := q.CreateChannelTaskDeliveryFromSession(ctx, db.CreateChannelTaskDeliveryFromSessionParams{
+ TaskID: taskID, ChatSessionID: f.sessionID, ContextRevision: 1,
+ })
+ if err != nil {
+ t.Fatalf("create delivery: %v", err)
+ }
+ if delivery.ChannelThreadID.String != tc.wantThread {
+ t.Errorf("thread = %q, want %q", delivery.ChannelThreadID.String, tc.wantThread)
+ }
+ // The trigger stays unknown either way — recovering the route must
+ // not smuggle in an attribution.
+ if delivery.ChannelMessageID.Valid || delivery.ChannelSenderID.Valid {
+ t.Errorf("trigger = message %+v sender %+v, want both NULL",
+ delivery.ChannelMessageID, delivery.ChannelSenderID)
+ }
+ })
+ }
+}
+
+// seedIsolatedBindingFixture builds a session whose binding key and config the
+// caller controls, so a test can express a genuinely thread-isolated binding
+// rather than hand-inserting a thread onto a plain one.
+func seedIsolatedBindingFixture(t *testing.T, pool *pgxpool.Pool, key func(string) string, configFmt string) sessionPersistenceFixture {
+ t.Helper()
+ f := seedSessionPersistenceFixtureWithoutChannel(t, pool)
+ ctx := context.Background()
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO channel_installation (
+ workspace_id, agent_id, channel_type, config, status, installer_user_id
+ ) VALUES ($1, $2, 'lark', '{}'::jsonb, 'active', $3)
+ RETURNING id
+ `, f.workspaceID, f.agentID, f.userID).Scan(&f.installationID); err != nil {
+ t.Fatalf("create channel installation: %v", err)
+ }
+ realChatID := "chat-" + fmt.Sprint(time.Now().UnixNano())
+ f.channelChatID = key(realChatID)
+ if _, err := db.New(pool).CreateChannelChatSessionBinding(ctx, db.CreateChannelChatSessionBindingParams{
+ ChatSessionID: f.sessionID, InstallationID: f.installationID, ChannelType: "lark",
+ ChannelChatID: f.channelChatID, ChatType: "group",
+ Config: []byte(fmt.Sprintf(configFmt, realChatID)),
+ }); err != nil {
+ t.Fatalf("create channel binding: %v", err)
+ }
+ t.Cleanup(func() {
+ cleanupCtx := context.Background()
+ _, _ = pool.Exec(cleanupCtx, `
+ DELETE FROM channel_chat_context_generation
+ WHERE chat_session_id IN (
+ SELECT chat_session_id FROM channel_chat_session_binding WHERE installation_id = $1
+ )
+ `, f.installationID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, f.installationID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_installation WHERE id = $1`, f.installationID)
+ })
+ return f
+}
+
+// TestChannelTaskDeliveryIsImmutableAfterCreation covers the other half: once
+// a task's delivery row exists, later inbound turns on the same generation
+// must not move it.
+func TestChannelTaskDeliveryIsImmutableAfterCreation(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ f := seedSessionPersistenceFixture(t, pool)
+ ctx := context.Background()
+ q := db.New(pool)
+
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ VALUES ($1, 1) ON CONFLICT DO NOTHING
+ `, f.sessionID); err != nil {
+ t.Fatalf("create generation: %v", err)
+ }
+ setTrigger := func(messageID, senderID string) {
+ t.Helper()
+ if err := q.SetChannelChatContextReplyTarget(ctx, db.SetChannelChatContextReplyTargetParams{
+ ChatSessionID: f.sessionID, Revision: 1,
+ LastMessageID: pgtype.Text{String: messageID, Valid: true},
+ LastSenderID: pgtype.Text{String: senderID, Valid: true},
+ }); err != nil {
+ t.Fatalf("snapshot reply target: %v", err)
+ }
+ }
+
+ setTrigger("om_from_alice", "ou_alice")
+ taskID := newDeliveryTaskID(t, pool)
+ if _, err := q.CreateChannelTaskDeliveryFromSession(ctx, db.CreateChannelTaskDeliveryFromSessionParams{
+ TaskID: taskID, ChatSessionID: f.sessionID, ContextRevision: 1,
+ }); err != nil {
+ t.Fatalf("create delivery: %v", err)
+ }
+
+ // B speaks into the same generation while A's run is still working.
+ setTrigger("om_from_bob", "ou_bob")
+
+ reread, err := q.GetChannelTaskDelivery(ctx, taskID)
+ if err != nil {
+ t.Fatalf("re-read delivery: %v", err)
+ }
+ if reread.ChannelSenderID.String != "ou_alice" || reread.ChannelMessageID.String != "om_from_alice" {
+ t.Errorf("delivery = sender %q message %q after B spoke, want alice's trigger frozen",
+ reread.ChannelSenderID.String, reread.ChannelMessageID.String)
+ }
+}
+
+// newDeliveryTaskID mints a task id to hang a channel_task_delivery off.
+// channel_task_delivery carries no foreign keys (MUL-3515 §4), so the row
+// under test needs no agent_task_queue peer — only its own cleanup.
+func newDeliveryTaskID(t *testing.T, pool *pgxpool.Pool) pgtype.UUID {
+ t.Helper()
+ taskID := dbid.NewV7()
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_task_delivery WHERE task_id = $1`, taskID)
+ })
+ return taskID
+}
diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.go
index a2ef6e7c11..3d6431a209 100644
--- a/server/internal/integrations/channel/engine/session_test.go
+++ b/server/internal/integrations/channel/engine/session_test.go
@@ -89,6 +89,9 @@ type fakeSessionQueries struct {
lastCreate db.CreateChatMessageParams
touched int
replyTargets int
+ lastReplyTarget db.UpdateChannelChatSessionBindingReplyTargetParams
+ contextReplyTargets int
+ lastContextReply db.SetChannelChatContextReplyTargetParams
lockedWorkspace int // count of LockWorkspaceForChatSessionCreate calls
lastConfig []byte // config of the most recent CreateChannelChatSessionBinding
attachments []db.CreateAttachmentParams
@@ -352,8 +355,15 @@ func (f *fakeSessionQueries) SetChannelChatContextInitiator(_ context.Context, a
return arg.InitiatorUserID, nil
}
-func (f *fakeSessionQueries) UpdateChannelChatSessionBindingReplyTarget(context.Context, db.UpdateChannelChatSessionBindingReplyTargetParams) error {
+func (f *fakeSessionQueries) UpdateChannelChatSessionBindingReplyTarget(_ context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) error {
f.replyTargets++
+ f.lastReplyTarget = arg
+ return nil
+}
+
+func (f *fakeSessionQueries) SetChannelChatContextReplyTarget(_ context.Context, arg db.SetChannelChatContextReplyTargetParams) error {
+ f.contextReplyTargets++
+ f.lastContextReply = arg
return nil
}
@@ -1353,3 +1363,52 @@ func TestAppendUserMessage_ClaimLost(t *testing.T) {
t.Errorf("zero Mark rows must return ErrClaimLost, got %v", err)
}
}
+
+// TestAppendUserMessage_ReplyTargetCarriesSender pins that the trigger's
+// channel-native sender is recorded in the SAME write as its message and
+// thread ids. They have to move together: the outbound side reads all three
+// as one snapshot, so a sender written by a different turn than the message
+// it accompanies would let a reply to one member carry another's @-mention.
+func TestAppendUserMessage_ReplyTargetCarriesSender(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ if _, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Body: "hi", MessageID: "om_1", ThreadID: "omt_1", SenderChannelID: "ou_sender",
+ }); err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ got := f.lastContextReply
+ if got.LastMessageID.String != "om_1" {
+ t.Fatalf("context reply target = %+v, want the trigger message", got)
+ }
+ // The thread is NOT recorded here: it is route, carried by the binding,
+ // so that a generation with no trigger still routes into its topic.
+ if f.lastReplyTarget.LastThreadID.String != "omt_1" {
+ t.Errorf("binding cursor thread = %+v, want the route to stay on the binding",
+ f.lastReplyTarget.LastThreadID)
+ }
+ if !got.LastSenderID.Valid || got.LastSenderID.String != "ou_sender" {
+ t.Errorf("last_sender_id = %+v, want ou_sender recorded alongside the message", got.LastSenderID)
+ }
+ if got.Revision != f.contextRevision {
+ t.Errorf("snapshot revision = %d, want the generation this message belongs to (%d)",
+ got.Revision, f.contextRevision)
+ }
+}
+
+// TestAppendUserMessage_ReplyTargetSenderNullWhenAbsent covers adapters that
+// do not supply a channel-native sender (every channel but Lark today): the
+// column goes NULL rather than empty string, so the outbound side reads it as
+// "no identity" and sends without a mention.
+func TestAppendUserMessage_ReplyTargetSenderNullWhenAbsent(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ if _, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Body: "hi", MessageID: "om_1",
+ }); err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if f.lastContextReply.LastSenderID.Valid {
+ t.Errorf("absent sender must be NULL; got %+v", f.lastContextReply.LastSenderID)
+ }
+}
diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.go
index 7d1ebbf2be..6bd001ba5f 100644
--- a/server/internal/integrations/lark/feishu_resolvers.go
+++ b/server/internal/integrations/lark/feishu_resolvers.go
@@ -175,7 +175,8 @@ func (r *feishuSessionBinder) StartSession(ctx context.Context, p engine.StartSe
},
Initiator: p.Sender,
Body: p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID, ThreadID: p.Message.Source.ThreadID,
- ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
+ SenderChannelID: p.Message.Source.SenderID,
+ ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,
BeforeCommit: p.BeforeCommit,
})
@@ -238,6 +239,7 @@ func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.Append
CommandText: commandText,
MessageID: p.Message.MessageID,
ThreadID: p.Message.Source.ThreadID,
+ SenderChannelID: p.Message.Source.SenderID,
ClaimToken: p.ClaimToken,
MediaPendingSeconds: p.MediaPendingSeconds,
ForceFresh: p.Message.ForceFresh,
diff --git a/server/internal/integrations/lark/mention.go b/server/internal/integrations/lark/mention.go
new file mode 100644
index 0000000000..509efd959d
--- /dev/null
+++ b/server/internal/integrations/lark/mention.go
@@ -0,0 +1,64 @@
+package lark
+
+import "strings"
+
+// Native Feishu @-mentions, the outbound half of #8234. An agent's answer
+// that opens with a literal "@Wang" is plain black text: it neither links to
+// the member nor rings their phone, so in a busy group the person who asked
+// never learns the answer arrived. A mention the platform recognises is the
+// only construct that notifies.
+//
+// The mention is built from the open_id we persisted for the task's
+// initiator, NEVER by pattern-matching an "@name" the model wrote. Display
+// names are ambiguous (duplicates, nicknames, and a model that simply
+// guesses wrong), and a mis-resolved name pings the wrong colleague — the
+// exact failure #8234 asks us to avoid. Identity flows from the DB or the
+// message goes out unmentioned.
+//
+// The two outbound wire shapes spell mentions differently, and using the
+// wrong spelling leaves visible markup in the transcript:
+//
+// - msg_type=text → <at user_id="ou_x"></at>
+// - schema-2.0 card markdown → <at id=ou_x></at>
+//
+// Both render the member's current display name from the id, so the element
+// body is left empty rather than carrying a name that could go stale.
+
+// mentionSeparator trails the mention so the agent's first word does not
+// collide with the rendered name. A trailing space (not a newline) keeps a
+// one-line answer on one line.
+const mentionSeparator = " "
+
+// safeMentionOpenID guards the open_id before it is interpolated into text
+// content or card JSON. Real Feishu ids are "ou_" + hex, so anything
+// carrying quotes, angle brackets, or whitespace is not an id we should be
+// embedding — returning "" makes the caller send without a mention instead
+// of emitting broken markup or malformed card JSON.
+func safeMentionOpenID(openID string) string {
+ if openID == "" || strings.ContainsAny(openID, "<>\"'`\\ \t\r\n") {
+ return ""
+ }
+ return openID
+}
+
+// prependTextMention returns body with a native mention of openID in front,
+// for the msg_type=text path. An empty or unsafe openID returns body
+// unchanged — an unmentioned answer is the correct degradation, a wrong or
+// broken mention is not.
+func prependTextMention(openID, body string) string {
+ id := safeMentionOpenID(openID)
+ if id == "" {
+ return body
+ }
+ return `<at user_id="` + id + `"></at>` + mentionSeparator + body
+}
+
+// prependMarkdownMention is prependTextMention for the schema-2.0 card
+// markdown element, which spells the same mention with `id=` and no quotes.
+func prependMarkdownMention(openID, body string) string {
+ id := safeMentionOpenID(openID)
+ if id == "" {
+ return body
+ }
+ return `<at id=` + id + `></at>` + mentionSeparator + body
+}
diff --git a/server/internal/integrations/lark/mention_test.go b/server/internal/integrations/lark/mention_test.go
new file mode 100644
index 0000000000..55589b3423
--- /dev/null
+++ b/server/internal/integrations/lark/mention_test.go
@@ -0,0 +1,57 @@
+package lark
+
+import "testing"
+
+// TestPrependMentionWireShapes pins the two spellings apart. They are easy
+// to swap by accident and the failure is silent-ish: the wrong one renders
+// as literal `<at ...>` markup in the user's transcript instead of a
+// mention, so the member still gets no notification — the bug #8234
+// reported, with extra noise on top.
+func TestPrependMentionWireShapes(t *testing.T) {
+ t.Parallel()
+ if got, want := prependTextMention("ou_x", "hi"), `<at user_id="ou_x"></at> hi`; got != want {
+ t.Errorf("text mention = %q, want %q", got, want)
+ }
+ if got, want := prependMarkdownMention("ou_x", "hi"), "<at id=ou_x></at> hi"; got != want {
+ t.Errorf("markdown mention = %q, want %q", got, want)
+ }
+}
+
+// TestPrependMentionDegradesWithoutIdentity is the "never guess" contract:
+// with no usable open_id the body goes out verbatim. A reply that lost its
+// mention is a small regression; a reply that mentions the wrong colleague
+// is the failure the issue explicitly asked us to avoid, and a malformed id
+// would corrupt the card JSON envelope it is interpolated into.
+func TestPrependMentionDegradesWithoutIdentity(t *testing.T) {
+ t.Parallel()
+ // Anything that could break out of the attribute or the card JSON is
+ // treated as "no identity" rather than escaped — real Feishu ids are
+ // "ou_" + hex, so a value like this is a bug upstream, not a name.
+ for _, openID := range []string{
+ "",
+ `ou_x" onclick="`,
+ "ou_x<br>",
+ "ou_x ou_y",
+ "ou_x\nou_y",
+ `ou_x\`,
+ } {
+ if got := prependTextMention(openID, "hi"); got != "hi" {
+ t.Errorf("prependTextMention(%q) = %q, want the body unchanged", openID, got)
+ }
+ if got := prependMarkdownMention(openID, "hi"); got != "hi" {
+ t.Errorf("prependMarkdownMention(%q) = %q, want the body unchanged", openID, got)
+ }
+ }
+}
+
+// TestPrependMentionKeepsBodyIntact guards the seam: the agent's answer is
+// forwarded byte-for-byte after the separator, including leading markdown
+// that the caller already used to pick the wire shape.
+func TestPrependMentionKeepsBodyIntact(t *testing.T) {
+ t.Parallel()
+ body := "# heading\n- bullet\n\n```go\nfmt.Println()\n```"
+ got := prependMarkdownMention("ou_x", body)
+ if want := "<at id=ou_x></at> " + body; got != want {
+ t.Errorf("markdown mention = %q, want %q", got, want)
+ }
+}
diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.go
index 52f380aaeb..5194435949 100644
--- a/server/internal/integrations/lark/outbound.go
+++ b/server/internal/integrations/lark/outbound.go
@@ -353,6 +353,7 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {
ID: delivery.BindingID, InstallationID: delivery.InstallationID,
ChannelChatID: delivery.ChannelChatID, ChatType: delivery.ChatType, Config: delivery.Config,
LastMessageID: delivery.ChannelMessageID, LastThreadID: delivery.ChannelThreadID,
+ LastSenderID: delivery.ChannelSenderID,
}
// Only bound sessions reach here, so classify the task origin before
@@ -401,13 +402,43 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {
switch e.Type {
case protocol.EventChatDone:
- return p.sendChatReply(ctx, creds, binding, e.Payload)
+ return p.sendChatReply(ctx, creds, binding, mentionOpenID(binding), e.Payload)
case protocol.EventTaskFailed:
return p.fail(ctx, creds, binding, taskID, agentName, e.Payload)
}
return nil
}
+// mentionOpenID returns the Feishu open_id to @-mention on this reply, or ""
+// for "send without a mention".
+//
+// It reads the sender frozen onto this task's delivery row — the same
+// per-task snapshot the reply target comes from, recorded together with it on
+// the inbound turn. Two properties follow, and both matter:
+//
+// - The mention names the account that sent THIS trigger, not whoever
+// messaged the chat most recently, so a slow answer cannot mention a
+// later speaker.
+//
+// - It is the exact platform identity, not one re-derived from the Multica
+// member. channel_user_binding is unique on (installation_id,
+// channel_user_id) only, so one member can hold several open_ids on a
+// single installation; a member-keyed reverse lookup would then be free
+// to name whichever it found first, and a reply to one account could
+// mention another.
+//
+// Group chats only. A p2p reply already lands in a 1:1 conversation that
+// notifies on its own, so a mention there is pure noise.
+//
+// Pre-migration deliveries carry no sender and mention nobody, which is the
+// same degradation as an unresolvable one — the answer still goes out.
+func mentionOpenID(binding ChatSessionBinding) string {
+ if ChatType(binding.ChatType) != ChatTypeGroup || !binding.LastSenderID.Valid {
+ return ""
+ }
+ return binding.LastSenderID.String
+}
+
// sendChatReply turns ChatDonePayload.Content into a Lark message.
// The wire shape is chosen per-reply based on whether the body
// contains any markdown syntax:
@@ -430,28 +461,41 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {
// the task without producing visible output, which only happens for
// edge cases like a chat task that just acknowledged a system event;
// not emitting a message there is the right product call.
-func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentials, binding ChatSessionBinding, payload any) error {
+//
+// mentionOpenID, when non-empty, prefixes the body with a native mention of
+// that member (see mention.go). The wire shape is chosen from the agent's own
+// content BEFORE the mention is attached, so a mention can never flip a plain
+// prose answer onto the card path.
+func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentials, binding ChatSessionBinding, mentionOpenID string, payload any) error {
content := chatDoneContent(payload)
if content == "" {
return nil
}
+ if topicSendWithoutTrigger(binding) {
+ p.cfg.Logger.Warn("lark: no trigger for a topic-isolated session; skipping reply rather than posting it to the parent group",
+ "chat_session_id", uuidString(binding.ChatSessionID),
+ "channel_chat_id", binding.ChannelChatID)
+ return nil
+ }
target := threadReplyTarget(binding)
if containsMarkdown(content) {
- return sendWithThreadFallback(p.cfg.Logger, "send markdown card", target, func(t ReplyTarget) error {
+ markdown := prependMarkdownMention(mentionOpenID, content)
+ return sendWithReplyFallback(p.cfg.Logger, "send markdown card", target, func(t ReplyTarget) error {
_, err := p.client.SendMarkdownCard(ctx, SendMarkdownCardParams{
InstallationID: creds,
ChatID: outboundChatID(binding),
- Markdown: content,
+ Markdown: markdown,
ReplyTarget: t,
})
return err
})
}
- return sendWithThreadFallback(p.cfg.Logger, "send text message", target, func(t ReplyTarget) error {
+ text := prependTextMention(mentionOpenID, content)
+ return sendWithReplyFallback(p.cfg.Logger, "send text message", target, func(t ReplyTarget) error {
_, err := p.client.SendTextMessage(ctx, SendTextParams{
InstallationID: creds,
ChatID: outboundChatID(binding),
- Text: content,
+ Text: text,
ReplyTarget: t,
})
return err
@@ -473,27 +517,87 @@ func outboundChatID(b ChatSessionBinding) ChatID {
return ChatID(b.ChannelChatID)
}
-// threadReplyTarget derives the outbound reply target from the chat
-// binding's most-recent inbound trigger. We thread the reply ONLY when
-// that trigger was itself inside a Lark topic (last_lark_thread_id
-// present): normal group / p2p chats keep the unchanged chat-level send
-// path, and only an @-mention that happened inside a thread gets a
-// threaded reply (replying to last_lark_message_id with reply_in_thread).
-// The zero ReplyTarget means "send at the chat level".
+// threadReplyTarget derives the outbound reply target from the trigger
+// snapshot the delivery row froze for THIS task. Three cases:
+//
+// - Trigger inside a Lark topic (last_lark_thread_id present) → reply
+// with reply_in_thread so the answer stays in the 话题 rather than
+// leaking into the main group chat. Unchanged.
+//
+// - Trigger in an ordinary group → reply to that message natively
+// (#8234). A standalone message in a busy group loses which of the
+// several questions in flight it answers; the native reply is what
+// restores that attribution.
+//
+// - Anything else (p2p, or no trigger message id recorded) → the
+// chat-level send, unchanged. A 1:1 conversation has no ambiguity
+// for a quote to resolve, so quoting every DM turn would be chrome
+// without a reader.
+//
+// isTopicIsolated reports whether this binding is one Lark topic (话题) rather
+// than a whole chat. larkSessionRouting writes a config only for topic
+// sessions — key "chat:thread", config {"chat_id": real} — so a decoded
+// chat_id IS the isolation marker. Pre-topic rows carry "{}" and plain chats
+// carry no config, both of which read as not isolated.
+func isTopicIsolated(b ChatSessionBinding) bool {
+ if len(b.Config) == 0 {
+ return false
+ }
+ var cfg larkBindingConfig
+ if err := json.Unmarshal(b.Config, &cfg); err != nil {
+ return false
+ }
+ return cfg.ChatID != "" && cfg.ChatID != b.ChannelChatID
+}
+
+// topicSendWithoutTrigger reports that this task belongs to a topic-isolated
+// session but carries no trigger message to reply to.
+//
+// It is the one combination Lark cannot serve. Slack and Telegram can place a
+// message in a thread from the thread id alone (thread_ts,
+// message_thread_id); Lark's only route into a topic is replying to a message
+// inside it, so with no trigger the send would fall through to
+// outboundChatID, which resolves the composite key to the whole chat. The
+// answer to a question asked in one topic would then appear in the main group
+// — not a confidentiality break (group members can open the topic either way)
+// but the wrong place, and the session isolation that topic routing exists to
+// provide would be silently undone.
+//
+// So we decline to send. The member can ask again, the answer is still in
+// Multica, and this is a one-time window: it is reachable only for
+// generations predating migration 460 that are recovered after deploy without
+// a new inbound turn, since every turn after deploy records a trigger before
+// its task is enqueued.
+//
+// Deliberately narrower than sendWithReplyFallback's chat-level retry, which
+// fires only when Lark reports the topic itself cannot receive the reply. The
+// topic is unusable there, so delivering beats losing the reply; here the
+// topic is fine and only our own bookkeeping is missing.
+func topicSendWithoutTrigger(b ChatSessionBinding) bool {
+ hasTrigger := b.LastMessageID.Valid && b.LastMessageID.String != ""
+ return isTopicIsolated(b) && !hasTrigger
+}
+
func threadReplyTarget(binding ChatSessionBinding) ReplyTarget {
- if binding.LastThreadID.Valid && binding.LastThreadID.String != "" &&
- binding.LastMessageID.Valid && binding.LastMessageID.String != "" {
+ if !binding.LastMessageID.Valid || binding.LastMessageID.String == "" {
+ return ReplyTarget{}
+ }
+ if binding.LastThreadID.Valid && binding.LastThreadID.String != "" {
return ReplyTarget{MessageID: binding.LastMessageID.String, InThread: true}
}
- return ReplyTarget{}
+ if ChatType(binding.ChatType) != ChatTypeGroup {
+ return ReplyTarget{}
+ }
+ return ReplyTarget{MessageID: binding.LastMessageID.String}
}
-// sendWithThreadFallback runs send with the thread reply target and,
-// ONLY when the threaded attempt fails with a Lark error that means the
-// topic reply legitimately cannot land (trigger message recalled, topic
-// gone, topics disabled, aggregated message — see
-// threadReplyUnsupportedCodes), retries once at the chat level so the
-// reply is not silently lost. Any other failure — transport error,
+// sendWithReplyFallback runs send against the reply target and, ONLY
+// when the attempt fails with a Lark error that means this specific
+// trigger message legitimately cannot receive a reply (message
+// recalled, invisible to the operator, self-destructing; plus the
+// topic-only cases: topic gone, topics disabled, aggregated message —
+// see threadReplyUnsupportedCodes), retries once at the chat level so
+// the reply is not silently lost. Any other failure — transport error,
// 5xx, timeout, rate limit, or an ambiguous "the server may have
// received it" error — is logged and returned as a failure rather than
// retried: a blind chat-level retry could duplicate the reply or leak a
@@ -503,22 +607,22 @@ func threadReplyTarget(binding ChatSessionBinding) ReplyTarget {
// It is a package-level function (rather than a Patcher method) so the
// event-driven Patcher and the immediate OutcomeReplier share one
// classified fallback path.
-func sendWithThreadFallback(log *slog.Logger, op string, target ReplyTarget, send func(ReplyTarget) error) error {
+func sendWithReplyFallback(log *slog.Logger, op string, target ReplyTarget, send func(ReplyTarget) error) error {
err := send(target)
if err == nil {
return nil
}
if target.IsSet() && isThreadReplyUnsupported(err) {
- log.Warn("lark: thread reply unsupported for target, retrying at chat level",
- "op", op, "reply_message_id", target.MessageID, "error", err)
+ log.Warn("lark: reply target unusable, retrying at chat level",
+ "op", op, "reply_message_id", target.MessageID, "in_thread", target.InThread, "error", err)
if fallbackErr := send(ReplyTarget{}); fallbackErr != nil {
- return fmt.Errorf("%s (chat-level fallback after thread-unsupported reply: %v): %w", op, err, fallbackErr)
+ return fmt.Errorf("%s (chat-level fallback after unusable reply target: %v): %w", op, err, fallbackErr)
}
return nil
}
if target.IsSet() {
- log.Warn("lark: thread reply failed; not falling back (non-classified error)",
- "op", op, "reply_message_id", target.MessageID, "error", err)
+ log.Warn("lark: reply failed; not falling back (non-classified error)",
+ "op", op, "reply_message_id", target.MessageID, "in_thread", target.InThread, "error", err)
}
return fmt.Errorf("%s: %w", op, err)
}
@@ -552,6 +656,12 @@ func (p *Patcher) installationCredentials(inst Installation) (InstallationCreden
// time we'd just send a second card, which is fine — failure is
// usually a single terminal event.
func (p *Patcher) fail(ctx context.Context, creds InstallationCredentials, binding ChatSessionBinding, taskID pgtype.UUID, agentName string, payload any) error {
+ if topicSendWithoutTrigger(binding) {
+ p.cfg.Logger.Warn("lark: no trigger for a topic-isolated session; skipping error card rather than posting it to the parent group",
+ "chat_session_id", uuidString(binding.ChatSessionID),
+ "channel_chat_id", binding.ChannelChatID)
+ return nil
+ }
render, err := p.cfg.Renderer.Render(RenderInput{
Kind: CardKindError,
AgentName: agentName,
@@ -561,7 +671,7 @@ func (p *Patcher) fail(ctx context.Context, creds InstallationCredentials, bindi
if err != nil {
return fmt.Errorf("render error card: %w", err)
}
- return sendWithThreadFallback(p.cfg.Logger, "send error card", threadReplyTarget(binding), func(t ReplyTarget) error {
+ return sendWithReplyFallback(p.cfg.Logger, "send error card", threadReplyTarget(binding), func(t ReplyTarget) error {
_, err := p.client.SendInteractiveCard(ctx, SendCardParams{
InstallationID: creds,
ChatID: outboundChatID(binding),
diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.go
index 4efb6a523f..de445fdebd 100644
--- a/server/internal/integrations/lark/outbound_test.go
+++ b/server/internal/integrations/lark/outbound_test.go
@@ -34,25 +34,38 @@ type fakePatcherQueries struct {
created []CreateOutboundCardMessageParams
createReturn OutboundCardMessage
statusUpdates []UpdateOutboundCardStatusParams
+ // deliveriesByTask overrides the derived delivery row per task_id, so a
+ // test can give two concurrent runs different frozen trigger snapshots.
+ // Empty falls back to the binding-derived row below.
+ deliveriesByTask map[string]db.ChannelTaskDelivery
+ // tasksByID overrides `task` per task_id; empty falls back to `task`.
+ tasksByID map[string]db.AgentTaskQueue
}
func (f *fakePatcherQueries) GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error) {
+ if task, ok := f.tasksByID[uuidString(id)]; ok {
+ return task, f.taskErr
+ }
return f.task, f.taskErr
}
func (f *fakePatcherQueries) TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error) {
return f.taskChannelIngested, nil
}
-func (f *fakePatcherQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {
+func (f *fakePatcherQueries) GetChannelTaskDelivery(_ context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error) {
if f.bindingErr != nil {
return db.ChannelTaskDelivery{}, f.bindingErr
}
+ if delivery, ok := f.deliveriesByTask[uuidString(taskID)]; ok {
+ return delivery, f.deliveryErr
+ }
if f.delivery.ChannelType == "" && f.binding.InstallationID.Valid {
return db.ChannelTaskDelivery{
BindingID: f.binding.ID, InstallationID: f.binding.InstallationID,
ChannelType: channelTypeFeishu, ChannelChatID: f.binding.ChannelChatID,
ChatType: f.binding.ChatType,
ChannelMessageID: f.binding.LastMessageID, ChannelThreadID: f.binding.LastThreadID,
- Config: f.binding.Config,
+ ChannelSenderID: f.binding.LastSenderID,
+ Config: f.binding.Config,
}, f.deliveryErr
}
return f.delivery, f.deliveryErr
@@ -676,14 +689,14 @@ func TestPatcherLegacyBindingFallsBackToKey(t *testing.T) {
}
}
-// TestPatcherSendsToChatWhenNoThread verifies that a non-thread trigger
-// (no last_lark_thread_id on the binding) keeps the historical
-// chat-level send: ReplyTarget stays empty so SendTextMessage targets
-// the chat by chat_id. This is the no-behavior-change guarantee for
-// normal group / p2p chats.
-func TestPatcherSendsToChatWhenNoThread(t *testing.T) {
+// TestPatcherRepliesNativelyInOrdinaryGroup pins the #8234 fix: an
+// ordinary group trigger (last_lark_message_id present, NO
+// last_lark_thread_id) now replies natively to that message instead of
+// posting a standalone chat-level message — but reply_in_thread stays
+// false, because there is no topic to stay inside.
+func TestPatcherRepliesNativelyInOrdinaryGroup(t *testing.T) {
p, q, api := newTestPatcher(t)
- // binding has a message id but NO thread id → must not thread.
+ q.binding.ChatType = string(ChatTypeGroup)
q.binding.LastMessageID = pgtype.Text{String: "om_trigger", Valid: true}
taskID := uuidFromString(t, "ee777777-ee77-ee77-ee77-eeeeeeeeeeee")
@@ -694,15 +707,51 @@ func TestPatcherSendsToChatWhenNoThread(t *testing.T) {
Payload: protocol.ChatDonePayload{Content: "plain reply"},
})
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.textSent) != 1 {
+ t.Fatalf("expected one text send; got %d", len(api.textSent))
+ }
+ got := api.textSent[0].ReplyTarget
+ if got.MessageID != "om_trigger" {
+ t.Errorf("ordinary group reply must target the trigger message; got %+v", got)
+ }
+ if got.InThread {
+ t.Errorf("no thread id on the trigger, so reply_in_thread must be false; got %+v", got)
+ }
+}
+
+// TestPatcherSendsToChatWithoutTriggerMessage covers the one case that
+// still has nothing to reply to: a binding with no last_lark_message_id
+// at all (pre-#8234 rows, or a session whose trigger was never
+// recorded). ReplyTarget stays empty and the send goes to the chat by
+// chat_id.
+func TestPatcherSendsToChatWithoutTriggerMessage(t *testing.T) {
+ p, q, api := newTestPatcher(t)
+ q.binding.ChatType = string(ChatTypeGroup)
+ q.binding.LastMessageID = pgtype.Text{}
+ q.binding.LastThreadID = pgtype.Text{}
+ taskID := uuidFromString(t, "ee779999-ee77-ee77-ee77-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "plain reply"},
+ })
+
api.mu.Lock()
defer api.mu.Unlock()
if len(api.textSent) != 1 {
t.Fatalf("expected one text send; got %d", len(api.textSent))
}
if api.textSent[0].ReplyTarget.IsSet() {
- t.Errorf("non-thread trigger must NOT route through the reply endpoint; got %+v",
+ t.Errorf("no trigger message id means chat-level send; got %+v",
api.textSent[0].ReplyTarget)
}
+ if api.textSent[0].ChatID != "oc_test_chat" {
+ t.Errorf("chat_id = %q, want the binding chat", api.textSent[0].ChatID)
+ }
}
// TestPatcherThreadReplyMarkdownRoutesToThread verifies the markdown
@@ -918,3 +967,309 @@ func TestPatcherClearsTypingAfterSessionDeleteRemovedTheBinding(t *testing.T) {
len(api.sent), len(api.textSent), len(api.patched))
}
}
+
+// ---- native @-mention of the triggering member (#8234) ----
+
+// groupPatcherWithSender wires the shared setup for the mention tests: a
+// group binding, a trigger message to reply to, and the channel-native
+// sender frozen alongside it.
+func groupPatcherWithSender(t *testing.T, senderOpenID string) (*Patcher, *fakePatcherQueries, *fakeAPIClient) {
+ t.Helper()
+ p, q, api := newTestPatcher(t)
+ q.binding.ChatType = string(ChatTypeGroup)
+ q.binding.LastMessageID = pgtype.Text{String: "om_trigger", Valid: true}
+ if senderOpenID != "" {
+ q.binding.LastSenderID = pgtype.Text{String: senderOpenID, Valid: true}
+ }
+ return p, q, api
+}
+
+// TestPatcherMentionsSenderInTextReply is the core of the mention half of
+// #8234: the member who @-mentioned the bot is rendered as a native Feishu
+// mention (which notifies them), built from the open_id frozen with the
+// trigger — never from an "@name" in the agent's prose.
+func TestPatcherMentionsSenderInTextReply(t *testing.T) {
+ p, q, api := groupPatcherWithSender(t, "ou_member_1")
+ taskID := uuidFromString(t, "ee991111-ee99-ee99-ee99-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "plain reply"},
+ })
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.textSent) != 1 {
+ t.Fatalf("expected one text send; got %d", len(api.textSent))
+ }
+ want := `<at user_id="ou_member_1"></at> plain reply`
+ if got := api.textSent[0].Text; got != want {
+ t.Errorf("text = %q, want %q", got, want)
+ }
+ if api.textSent[0].ReplyTarget.MessageID != "om_trigger" {
+ t.Errorf("reply target = %+v, want the trigger message", api.textSent[0].ReplyTarget)
+ }
+}
+
+// TestPatcherMentionsSenderInMarkdownCard pins the second wire shape: a
+// markdown answer goes out as a schema-2.0 card, where the same mention is
+// spelled `<at id=...>`. Using the text spelling here would leave raw markup
+// visible in the card.
+func TestPatcherMentionsSenderInMarkdownCard(t *testing.T) {
+ p, q, api := groupPatcherWithSender(t, "ou_member_2")
+ taskID := uuidFromString(t, "ee992222-ee99-ee99-ee99-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "# heading\n- bullet"},
+ })
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.mdCardSent) != 1 {
+ t.Fatalf("expected one markdown card send; got %d", len(api.mdCardSent))
+ }
+ want := "<at id=ou_member_2></at> # heading\n- bullet"
+ if got := api.mdCardSent[0].Markdown; got != want {
+ t.Errorf("markdown = %q, want %q", got, want)
+ }
+}
+
+// TestPatcherSendsWithoutMentionWhenSenderUnknown covers the degradation the
+// issue asks for explicitly, and the pre-migration rows that carry no frozen
+// sender: the answer still goes out, just unmentioned. It must never fall
+// back to guessing some other member.
+func TestPatcherSendsWithoutMentionWhenSenderUnknown(t *testing.T) {
+ p, q, api := groupPatcherWithSender(t, "")
+ taskID := uuidFromString(t, "ee993333-ee99-ee99-ee99-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "plain reply"},
+ })
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.textSent) != 1 {
+ t.Fatalf("expected one text send; got %d", len(api.textSent))
+ }
+ if got := api.textSent[0].Text; got != "plain reply" {
+ t.Errorf("unknown sender must send the body unchanged; got %q", got)
+ }
+}
+
+// TestPatcherDoesNotMentionInP2P keeps 1:1 chats quiet: the member is the
+// only other participant and already gets a normal message notification, so
+// a mention there is noise.
+func TestPatcherDoesNotMentionInP2P(t *testing.T) {
+ p, q, api := groupPatcherWithSender(t, "ou_member_5")
+ q.binding.ChatType = string(ChatTypeP2P)
+ taskID := uuidFromString(t, "ee995555-ee99-ee99-ee99-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "plain reply"},
+ })
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if got := api.textSent[0].Text; got != "plain reply" {
+ t.Errorf("p2p reply must carry no mention; got %q", got)
+ }
+}
+
+// deliveryWithTrigger builds the frozen per-task snapshot the Patcher reads:
+// one task's own trigger message and the account that sent it.
+func deliveryWithTrigger(binding ChatSessionBinding, messageID, senderOpenID string) db.ChannelTaskDelivery {
+ return db.ChannelTaskDelivery{
+ BindingID: binding.ID, InstallationID: binding.InstallationID,
+ ChannelType: channelTypeFeishu, ChannelChatID: binding.ChannelChatID,
+ ChatType: binding.ChatType,
+ ChannelMessageID: pgtype.Text{String: messageID, Valid: true},
+ ChannelSenderID: pgtype.Text{String: senderOpenID, Valid: true},
+ Config: binding.Config,
+ }
+}
+
+// TestPatcherMentionsEachTaskOwnSender is the cross-mention guard. Two
+// members each trigger a run in the same group and the runs finish in the
+// reverse order. Because both the reply target and the mention come from the
+// snapshot frozen on each task — not from whoever spoke in the chat most
+// recently — each answer quotes and mentions the member who actually asked.
+func TestPatcherMentionsEachTaskOwnSender(t *testing.T) {
+ p, q, api := groupPatcherWithSender(t, "ou_alice")
+ aliceTask := uuidFromString(t, "ee996666-ee99-ee99-ee99-eeeeeeeeeeee")
+ bobTask := uuidFromString(t, "ee997777-ee99-ee99-ee99-eeeeeeeeeeee")
+ q.deliveriesByTask = map[string]db.ChannelTaskDelivery{
+ uuidString(aliceTask): deliveryWithTrigger(q.binding, "om_alice_msg", "ou_alice"),
+ uuidString(bobTask): deliveryWithTrigger(q.binding, "om_bob_msg", "ou_bob"),
+ }
+
+ // Bob asked second but his run finishes first.
+ for _, taskID := range []pgtype.UUID{bobTask, aliceTask} {
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "answer"},
+ })
+ }
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.textSent) != 2 {
+ t.Fatalf("expected two text sends; got %d", len(api.textSent))
+ }
+ wantText := []string{`<at user_id="ou_bob"></at> answer`, `<at user_id="ou_alice"></at> answer`}
+ wantReplyTo := []string{"om_bob_msg", "om_alice_msg"}
+ for i := range wantText {
+ if got := api.textSent[i].Text; got != wantText[i] {
+ t.Errorf("send[%d] text = %q, want %q", i, got, wantText[i])
+ }
+ if got := api.textSent[i].ReplyTarget.MessageID; got != wantReplyTo[i] {
+ t.Errorf("send[%d] reply target = %q, want %q", i, got, wantReplyTo[i])
+ }
+ }
+}
+
+// TestPatcherMentionsTriggeringAccountNotSiblingIdentity is the regression
+// for the identity bug the first cut of #8234 shipped with. That version
+// resolved the mention by looking the sender back up from the task's Multica
+// member, which is unsound: channel_user_binding is unique on
+// (installation_id, channel_user_id) but NOT on (installation_id,
+// multica_user_id), so one member can legitimately hold two open_ids on one
+// installation — the redeem path plain-INSERTs the second — and a
+// member-keyed lookup is then free to return either.
+//
+// Here both accounts belong to the same Multica member and the SECOND one
+// triggers the run. The reply must mention the account that sent the
+// message, not its sibling identity. Reading the frozen sender is what makes
+// the member's other open_id unreachable from this path.
+func TestPatcherMentionsTriggeringAccountNotSiblingIdentity(t *testing.T) {
+ member := uuidFromString(t, "dddd8888-dddd-dddd-dddd-dddddddddddd")
+ p, q, api := groupPatcherWithSender(t, "ou_personal_account")
+ taskID := uuidFromString(t, "ee998888-ee99-ee99-ee99-eeeeeeeeeeee")
+
+ // One member, two bound Feishu accounts on this installation. The task
+ // records only the shared Multica user, so the member alone cannot say
+ // which account spoke.
+ q.task = db.AgentTaskQueue{InitiatorUserID: member}
+ q.deliveriesByTask = map[string]db.ChannelTaskDelivery{
+ uuidString(taskID): deliveryWithTrigger(q.binding, "om_trigger", "ou_work_account"),
+ }
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "answer"},
+ })
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.textSent) != 1 {
+ t.Fatalf("expected one text send; got %d", len(api.textSent))
+ }
+ want := `<at user_id="ou_work_account"></at> answer`
+ if got := api.textSent[0].Text; got != want {
+ t.Errorf("text = %q, want %q — the mention must name the account that sent the trigger", got, want)
+ }
+}
+
+// TestPatcherSkipsTopicReplyWithoutTrigger is the leak guard. A
+// topic-isolated session whose task carries no trigger message has no way
+// into the topic — Lark can only reply into one — and outboundChatID would
+// resolve the composite key to the PARENT group. Posting there is not a
+// degraded reply, it is the member's topic conversation appearing in front
+// of the whole group, so the Patcher must send nothing at all.
+func TestPatcherSkipsTopicReplyWithoutTrigger(t *testing.T) {
+ p, q, api := newTestPatcher(t)
+ q.binding.ChatType = string(ChatTypeGroup)
+ q.binding.ChannelChatID = "oc_test_chat:omt_topic1"
+ q.binding.Config = []byte(`{"chat_id":"oc_test_chat"}`)
+ // Pre-migration generation: the trigger snapshot is empty, so there is no
+ // message to reply into the topic with.
+ q.binding.LastMessageID = pgtype.Text{}
+ q.binding.LastThreadID = pgtype.Text{}
+ taskID := uuidFromString(t, "eeccdddd-eecc-eecc-eecc-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "answer for the topic"},
+ })
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.textSent) != 0 || len(api.mdCardSent) != 0 || len(api.sent) != 0 {
+ t.Errorf("a topic reply with no trigger must not reach the parent group; text=%d md=%d card=%d",
+ len(api.textSent), len(api.mdCardSent), len(api.sent))
+ }
+}
+
+// TestPatcherSkipsTopicErrorCardWithoutTrigger covers the same leak on the
+// failure path: an error card names the run and its agent, so it must not
+// surface in the parent group either.
+func TestPatcherSkipsTopicErrorCardWithoutTrigger(t *testing.T) {
+ p, q, api := newTestPatcher(t)
+ q.binding.ChatType = string(ChatTypeGroup)
+ q.binding.ChannelChatID = "oc_test_chat:omt_topic1"
+ q.binding.Config = []byte(`{"chat_id":"oc_test_chat"}`)
+ q.binding.LastMessageID = pgtype.Text{}
+ q.binding.LastThreadID = pgtype.Text{}
+ taskID := uuidFromString(t, "eecceeee-eecc-eecc-eecc-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventTaskFailed,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: map[string]any{"error": "boom"},
+ })
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.sent) != 0 || len(api.textSent) != 0 {
+ t.Errorf("a topic error card with no trigger must not reach the parent group; card=%d text=%d",
+ len(api.sent), len(api.textSent))
+ }
+}
+
+// TestPatcherStillRepliesInOrdinaryGroupWithoutTrigger is the boundary: the
+// guard is about topics only. An ordinary group has no isolation to breach —
+// the chat-level send lands in the very chat the session belongs to — so a
+// missing trigger degrades to an unquoted, unmentioned reply, not silence.
+func TestPatcherStillRepliesInOrdinaryGroupWithoutTrigger(t *testing.T) {
+ p, q, api := newTestPatcher(t)
+ q.binding.ChatType = string(ChatTypeGroup)
+ q.binding.LastMessageID = pgtype.Text{}
+ q.binding.LastThreadID = pgtype.Text{}
+ taskID := uuidFromString(t, "eeccffff-eecc-eecc-eecc-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "plain reply"},
+ })
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.textSent) != 1 {
+ t.Fatalf("expected one text send; got %d", len(api.textSent))
+ }
+ if api.textSent[0].ChatID != "oc_test_chat" {
+ t.Errorf("chat_id = %q, want the session's own chat", api.textSent[0].ChatID)
+ }
+ if got := api.textSent[0].Text; got != "plain reply" {
+ t.Errorf("text = %q, want the body unchanged", got)
+ }
+}
diff --git a/server/internal/integrations/lark/outcome_replier.go b/server/internal/integrations/lark/outcome_replier.go
index 5b919f1a18..aee33c0404 100644
--- a/server/internal/integrations/lark/outcome_replier.go
+++ b/server/internal/integrations/lark/outcome_replier.go
@@ -279,7 +279,7 @@ func (r *LarkOutcomeReplier) sendIssueOutcome(ctx context.Context, inst Installa
// topics disabled, aggregated message) falls back to a chat-level
// 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 outcome text", inboundReplyTarget(msg), func(t ReplyTarget) error {
+ return sendWithReplyFallback(r.log, "send issue outcome text", inboundReplyTarget(msg), func(t ReplyTarget) error {
_, err := r.client.SendTextMessage(ctx, SendTextParams{
InstallationID: creds,
ChatID: msg.ChatID,
@@ -290,17 +290,24 @@ func (r *LarkOutcomeReplier) sendIssueOutcome(ctx context.Context, inst Installa
})
}
-// inboundReplyTarget threads an outbound reply off the inbound trigger
-// message when that message lived inside a Lark topic (话题). It mirrors
-// threadReplyTarget (used by the event-driven Patcher) but reads the
-// live InboundMessage the replier already holds, so it needs no DB
-// round-trip. An empty thread_id yields the zero ReplyTarget — a
-// chat-level send, i.e. the unchanged behavior for non-thread messages.
+// inboundReplyTarget mirrors threadReplyTarget (used by the event-driven
+// Patcher) case for case — topic trigger threads, ordinary group trigger
+// replies natively, p2p and untriggered sends stay chat-level — but
+// reads the live InboundMessage the replier already holds, so it needs
+// no DB round-trip. Keep the two in lockstep: a user cannot tell whether
+// an answer came from the synchronous replier or the task patcher, so
+// they must not place their replies differently.
func inboundReplyTarget(msg InboundMessage) ReplyTarget {
- if msg.ThreadID != "" && msg.MessageID != "" {
+ if msg.MessageID == "" {
+ return ReplyTarget{}
+ }
+ if msg.ThreadID != "" {
return ReplyTarget{MessageID: msg.MessageID, InThread: true}
}
- return ReplyTarget{}
+ if msg.ChatType != ChatTypeGroup {
+ return ReplyTarget{}
+ }
+ return ReplyTarget{MessageID: msg.MessageID}
}
// issueCreatedText composes the user-facing confirmation. Identifier
@@ -367,7 +374,7 @@ func (r *LarkOutcomeReplier) sendChatNotice(ctx context.Context, inst Installati
// 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 {
+ return sendWithReplyFallback(r.log, "send notice card", inboundReplyTarget(msg), func(t ReplyTarget) error {
_, err := r.client.SendInteractiveCard(ctx, SendCardParams{
InstallationID: creds,
ChatID: msg.ChatID,
diff --git a/server/internal/integrations/lark/outcome_replier_test.go b/server/internal/integrations/lark/outcome_replier_test.go
index 6379f1ce58..d92d981bb2 100644
--- a/server/internal/integrations/lark/outcome_replier_test.go
+++ b/server/internal/integrations/lark/outcome_replier_test.go
@@ -899,3 +899,79 @@ func mustUUID(s string) pgtype.UUID {
// silence the unused import warnings for the dependencies we keep
// reaching for via reflection in future test cases.
var _ = pgx.ErrNoRows
+
+// TestLarkOutcomeReplierRepliesNativelyInOrdinaryGroup is the outcome
+// replier's half of #8234: the /issue confirmation now attaches to the
+// message that asked for it even outside a topic. reply_in_thread stays
+// false — there is no topic to stay inside — so the reply lands in the
+// group as a native quote-reply rather than a standalone message.
+func TestLarkOutcomeReplierRepliesNativelyInOrdinaryGroup(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,
+ })
+
+ rep.Reply(context.Background(), Installation{AppID: "cli_x"},
+ InboundMessage{ChatID: "oc_chat_42", ChatType: ChatTypeGroup, MessageID: "om_trigger", SenderOpenID: "ou_user"},
+ DispatchResult{
+ Outcome: OutcomeIngested,
+ IssueID: mustUUID("22222222-2222-2222-2222-222222222222"),
+ IssueNumber: 42,
+ IssueIdentifier: "MUL-42",
+ })
+
+ stub.mu.Lock()
+ defer stub.mu.Unlock()
+ if len(stub.textOut) != 1 {
+ t.Fatalf("expected one send; got %d", len(stub.textOut))
+ }
+ got := stub.textOut[0].ReplyTarget
+ if got.MessageID != "om_trigger" {
+ t.Errorf("ordinary group confirmation must reply to the trigger; got %+v", got)
+ }
+ if got.InThread {
+ t.Errorf("no thread id, so reply_in_thread must be false; got %+v", got)
+ }
+}
+
+// TestLarkOutcomeReplierSendsToChatWithoutTriggerMessage keeps the only
+// remaining chat-level case honest: with no inbound message id there is
+// nothing to reply to.
+func TestLarkOutcomeReplierSendsToChatWithoutTriggerMessage(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,
+ })
+
+ rep.Reply(context.Background(), Installation{AppID: "cli_x"},
+ InboundMessage{ChatID: "oc_chat_42", SenderOpenID: "ou_user"},
+ DispatchResult{
+ Outcome: OutcomeIngested,
+ IssueID: mustUUID("22222222-2222-2222-2222-222222222222"),
+ IssueNumber: 42,
+ IssueIdentifier: "MUL-42",
+ })
+
+ stub.mu.Lock()
+ defer stub.mu.Unlock()
+ if len(stub.textOut) != 1 {
+ t.Fatalf("expected one send; got %d", len(stub.textOut))
+ }
+ if stub.textOut[0].ReplyTarget.IsSet() {
+ t.Errorf("no trigger message id means chat-level send; got %+v", stub.textOut[0].ReplyTarget)
+ }
+}
diff --git a/server/internal/integrations/lark/store.go b/server/internal/integrations/lark/store.go
index cb918a71bc..20809b2f0e 100644
--- a/server/internal/integrations/lark/store.go
+++ b/server/internal/integrations/lark/store.go
@@ -83,6 +83,12 @@ type ChatSessionBinding struct {
CreatedAt pgtype.Timestamptz
LastMessageID pgtype.Text
LastThreadID pgtype.Text
+ // LastSenderID is the channel-native id (open_id) of whoever sent the
+ // trigger LastMessageID refers to — the account an outbound reply
+ // @-mentions. Frozen per task via channel_task_delivery, never re-derived
+ // from the Multica member: one member can hold several open_ids on one
+ // installation, so a member-keyed lookup could name the wrong account.
+ LastSenderID pgtype.Text
}
// InboundMessageDedup is the flat view of a channel_inbound_message_dedup row.
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 36711856b6..782fe2bcca 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2049,6 +2049,7 @@ func (s *TaskService) enqueueChatTaskTx(
if _, err := qtx.CreateChannelTaskDeliveryFromSession(
ctx, db.CreateChannelTaskDeliveryFromSessionParams{
TaskID: task.ID, ChatSessionID: chatSession.ID,
+ ContextRevision: contextRevision,
},
); err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("snapshot channel task delivery: %w", err)
diff --git a/server/migrations/460_channel_trigger_snapshot.down.sql b/server/migrations/460_channel_trigger_snapshot.down.sql
new file mode 100644
index 0000000000..18643270ca
--- /dev/null
+++ b/server/migrations/460_channel_trigger_snapshot.down.sql
@@ -0,0 +1,7 @@
+ALTER TABLE channel_task_delivery
+ DROP COLUMN IF EXISTS channel_sender_id;
+
+ALTER TABLE channel_chat_context_generation
+ DROP COLUMN IF EXISTS last_message_id,
+ DROP COLUMN IF EXISTS last_thread_id,
+ DROP COLUMN IF EXISTS last_sender_id;
diff --git a/server/migrations/460_channel_trigger_snapshot.up.sql b/server/migrations/460_channel_trigger_snapshot.up.sql
new file mode 100644
index 0000000000..59bd5d7361
--- /dev/null
+++ b/server/migrations/460_channel_trigger_snapshot.up.sql
@@ -0,0 +1,80 @@
+-- Freeze each trigger's reply target AND its channel-native sender per context
+-- generation, so an outbound reply answers exactly the message that asked and
+-- @-mentions exactly the account that sent it (#8234).
+--
+-- Two earlier shapes were wrong, both for the same underlying reason — the
+-- identity was read from something coarser than "this trigger":
+--
+-- * Resolving the open_id at send time from the task's initiator_user_id.
+-- channel_user_binding is unique on (installation_id, channel_user_id) and
+-- NOT on (installation_id, multica_user_id), so a member who binds a
+-- second Feishu account on one installation has two rows and the reverse
+-- lookup could name either.
+--
+-- * Recording the trigger on channel_chat_session_binding, which holds one
+-- row per chat_session and therefore only ever remembers the LATEST
+-- trigger. A run debounced in revision 1 has its delivery row created
+-- after a /clear opened revision 2, so it would freeze the newer
+-- generation's message and sender: reply to A's question, quote and
+-- mention B.
+--
+-- channel_chat_context_generation is keyed (chat_session_id, revision) and
+-- already snapshots initiator_user_id for exactly this reason — see
+-- SetChannelChatContextInitiator, whose comment names the same hazard for
+-- crash recovery. The trigger belongs beside it. channel_task_delivery then
+-- freezes the generation's values per task.
+--
+-- The thread belongs here too, with the message and sender. It is tempting to
+-- call the thread "route" and read it from the binding, but that only holds
+-- for thread-ISOLATED sessions. Slack DMs are the counterexample the repo
+-- already encodes: slackSessionRouting keeps one binding per DM channel while
+-- carrying a per-message reply thread, so the binding's cursor names whichever
+-- thread spoke last. Reading it there would hand a debounced revision-1 run
+-- the thread of a later revision — the same cross-generation hazard this
+-- snapshot exists to close for the message and sender.
+--
+-- The binding keeps its own last_message_id / last_thread_id for the
+-- history-boundary bookkeeping (history_start_message_id,
+-- history_end_message_id). That cursor is deliberately NOT interchangeable
+-- with the trigger here: it advances for channel commands (/issue) too,
+-- whereas the trigger is written only for messages that are actually agent
+-- input.
+--
+-- No index: every read here goes through an existing key (chat_session_id +
+-- revision, or task_id).
+ALTER TABLE channel_chat_context_generation
+ ADD COLUMN IF NOT EXISTS last_message_id TEXT,
+ ADD COLUMN IF NOT EXISTS last_thread_id TEXT,
+ ADD COLUMN IF NOT EXISTS last_sender_id TEXT;
+
+ALTER TABLE channel_task_delivery
+ ADD COLUMN IF NOT EXISTS channel_sender_id TEXT;
+
+-- Existing generations intentionally keep a NULL trigger — no backfill, in
+-- line with 451_agent_task_comment_thread's "pre-migration rows drain without
+-- rewriting historical data".
+--
+-- Nothing needs one. The trigger is recorded during AppendUserMessage, which
+-- commits before the debounced flush that enqueues the task and creates its
+-- delivery row, so the first inbound turn after deploy already supplies a
+-- correct value for that generation. Only a generation enqueued with NO
+-- post-deploy append can read NULL here — the recovered-run path — and that is
+-- exactly the case a backfill cannot serve: the binding cursor it would copy
+-- from has already advanced past that generation, so seeding would supply a
+-- confidently wrong message and sender rather than no answer.
+--
+-- What a NULL trigger costs depends on where the answer is going, and
+-- CreateChannelTaskDeliveryFromSession is written around that:
+--
+-- * Ordinary chat, p2p, Slack DM — a chat-level send lands in the very
+-- conversation the session belongs to. No quote, no mention, right place.
+--
+-- * Thread-isolated session (Lark topic, Slack channel thread, Telegram
+-- forum topic) — the thread is recovered from the binding, which for these
+-- bindings is a stable property of the session rather than a cursor. The
+-- answer still reaches its thread.
+--
+-- * Lark topic specifically — Lark can only enter a topic by replying to a
+-- message inside it, so a recovered thread is not enough. The Patcher
+-- declines to send rather than posting into the parent group; see
+-- topicSendWithoutTrigger.
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index 56cf7c504c..2e06350ec6 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -77,9 +77,9 @@ WITH closed AS (
NOT $4::boolean,
TRUE
FROM advanced
- RETURNING chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at
+ RETURNING chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at, last_message_id, last_thread_id, last_sender_id
)
-SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at FROM opened
+SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at, last_message_id, last_thread_id, last_sender_id FROM opened
`
type AdvanceChannelChatContextGenerationParams struct {
@@ -98,6 +98,9 @@ type AdvanceChannelChatContextGenerationRow struct {
PendingFresh bool `json:"pending_fresh"`
InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
+ LastMessageID pgtype.Text `json:"last_message_id"`
+ LastThreadID pgtype.Text `json:"last_thread_id"`
+ LastSenderID pgtype.Text `json:"last_sender_id"`
}
// Opens a new agent-visible context while retaining the same Multica Chat.
@@ -120,6 +123,9 @@ func (q *Queries) AdvanceChannelChatContextGeneration(ctx context.Context, arg A
&i.PendingFresh,
&i.InitiatorUserID,
&i.CreatedAt,
+ &i.LastMessageID,
+ &i.LastThreadID,
+ &i.LastSenderID,
)
return i, err
}
@@ -388,11 +394,11 @@ func (q *Queries) ConsumeChannelBindingToken(ctx context.Context, tokenHash stri
const copyChannelTaskDelivery = `-- name: CopyChannelTaskDelivery :exec
INSERT INTO channel_task_delivery (
task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
- channel_message_id, channel_thread_id, route_revision, config
+ channel_message_id, channel_thread_id, channel_sender_id, route_revision, config
)
SELECT
$1, delivery.binding_id, delivery.installation_id, delivery.channel_type, delivery.channel_chat_id, delivery.chat_type,
- delivery.channel_message_id, delivery.channel_thread_id, delivery.route_revision, delivery.config
+ delivery.channel_message_id, delivery.channel_thread_id, delivery.channel_sender_id, delivery.route_revision, delivery.config
FROM channel_task_delivery AS delivery
WHERE delivery.task_id = $2
`
@@ -696,27 +702,79 @@ const createChannelTaskDeliveryFromSession = `-- name: CreateChannelTaskDelivery
INSERT INTO channel_task_delivery (
task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
- channel_message_id, channel_thread_id, route_revision, config
+ channel_message_id, channel_thread_id, channel_sender_id, route_revision, config
)
SELECT
$1, binding.id, binding.installation_id, binding.channel_type,
- binding.channel_chat_id, binding.chat_type, binding.last_message_id, binding.last_thread_id,
+ binding.channel_chat_id, binding.chat_type,
+ generation.last_message_id,
+ CASE
+ -- This generation recorded a trigger, so its thread is authoritative —
+ -- including when it is legitimately empty, which is how a Slack DM
+ -- answered at top level is distinguished from one answered inside a
+ -- thread.
+ WHEN generation.last_message_id IS NOT NULL THEN generation.last_thread_id
+ -- No trigger: pre-migration, or a generation whose only messages were
+ -- channel commands. Recover the thread ONLY for a thread-isolated
+ -- binding, where it is a stable property of the session rather than a
+ -- moving cursor. Such a binding is exactly the one whose key is the
+ -- composite "chat:thread", which is why it carries the real chat id in
+ -- its config — the marker every adapter writes (larkSessionRouting,
+ -- slackSessionRouting, telegramSessionRouting). Without this, a
+ -- recovered pre-migration run in a Slack channel thread or a Telegram
+ -- forum topic would answer in the parent conversation.
+ WHEN COALESCE(binding.config ->> 'chat_id', binding.config ->> 'channel_id', '')
+ NOT IN ('', binding.channel_chat_id) THEN binding.last_thread_id
+ -- A non-isolated binding's cursor names whichever thread spoke last,
+ -- which is not this run's. Nothing we can justify.
+ ELSE NULL
+ END,
+ generation.last_sender_id,
binding.route_revision, binding.config
FROM channel_chat_session_binding AS binding
-WHERE binding.chat_session_id = $2
-RETURNING task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, channel_message_id, channel_thread_id, route_revision, config, created_at
+JOIN channel_chat_context_generation AS generation
+ ON generation.chat_session_id = binding.chat_session_id
+ AND generation.revision = $2
+WHERE binding.chat_session_id = $3
+RETURNING task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, channel_message_id, channel_thread_id, route_revision, config, created_at, channel_sender_id
`
type CreateChannelTaskDeliveryFromSessionParams struct {
- TaskID pgtype.UUID `json:"task_id"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ TaskID pgtype.UUID `json:"task_id"`
+ ContextRevision int64 `json:"context_revision"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
}
// =====================
// channel_task_delivery
// =====================
+// Freezes one task's outbound delivery, from two different sources on purpose.
+//
+// ROUTE — chat, type, config, revision — comes from the session binding. It is
+// a property of the session and does not vary by generation.
+//
+// TRIGGER — the message an answer quotes, the thread it replies into, and the
+// account it @-mentions — comes from the generation this task answers, NOT
+// from the binding's latest-trigger cursor, which a newer generation may
+// already have advanced past.
+//
+// The thread sits with the trigger rather than the route deliberately. For a
+// thread-isolated session (Lark topic, Slack channel thread) the two coincide,
+// so it is easy to mistake the thread for route data — but Slack DMs keep ONE
+// binding per channel while replying into whichever thread the member used
+// (slackSessionRouting), so the binding cursor there names the latest thread,
+// not this run's. Taking it from the generation is correct for both shapes.
+//
+// The one exception is the CASE below: when a generation recorded no trigger
+// at all, a thread-isolated binding can still say which thread the session
+// lives in, and must, or the answer surfaces in the parent channel.
+//
+// A NULL trigger means "we cannot attribute this run": callers reply without a
+// quote or mention rather than inventing one. INNER JOIN on the generation: a
+// task whose generation row is missing entirely has no context to deliver
+// against at all.
func (q *Queries) CreateChannelTaskDeliveryFromSession(ctx context.Context, arg CreateChannelTaskDeliveryFromSessionParams) (ChannelTaskDelivery, error) {
- row := q.db.QueryRow(ctx, createChannelTaskDeliveryFromSession, arg.TaskID, arg.ChatSessionID)
+ row := q.db.QueryRow(ctx, createChannelTaskDeliveryFromSession, arg.TaskID, arg.ContextRevision, arg.ChatSessionID)
var i ChannelTaskDelivery
err := row.Scan(
&i.TaskID,
@@ -730,6 +788,7 @@ func (q *Queries) CreateChannelTaskDeliveryFromSession(ctx context.Context, arg
&i.RouteRevision,
&i.Config,
&i.CreatedAt,
+ &i.ChannelSenderID,
)
return i, err
}
@@ -1179,7 +1238,7 @@ func (q *Queries) FindReusableChannelUserBinding(ctx context.Context, arg FindRe
}
const getChannelChatContextGeneration = `-- name: GetChannelChatContextGeneration :one
-SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at FROM channel_chat_context_generation
+SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at, last_message_id, last_thread_id, last_sender_id FROM channel_chat_context_generation
WHERE chat_session_id = $1
AND revision = $2
`
@@ -1201,6 +1260,9 @@ func (q *Queries) GetChannelChatContextGeneration(ctx context.Context, arg GetCh
&i.PendingFresh,
&i.InitiatorUserID,
&i.CreatedAt,
+ &i.LastMessageID,
+ &i.LastThreadID,
+ &i.LastSenderID,
)
return i, err
}
@@ -1544,7 +1606,7 @@ func (q *Queries) GetChannelOutboundCardByTask(ctx context.Context, arg GetChann
}
const getChannelTaskDelivery = `-- name: GetChannelTaskDelivery :one
-SELECT task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, channel_message_id, channel_thread_id, route_revision, config, created_at FROM channel_task_delivery WHERE task_id = $1
+SELECT task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, channel_message_id, channel_thread_id, route_revision, config, created_at, channel_sender_id FROM channel_task_delivery WHERE task_id = $1
`
func (q *Queries) GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (ChannelTaskDelivery, error) {
@@ -1562,6 +1624,7 @@ func (q *Queries) GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID
&i.RouteRevision,
&i.Config,
&i.CreatedAt,
+ &i.ChannelSenderID,
)
return i, err
}
@@ -1903,7 +1966,7 @@ func (q *Queries) ListChannelOutboundMessagesByIDs(ctx context.Context, arg List
}
const lockChannelChatContextGenerationByRevision = `-- name: LockChannelChatContextGenerationByRevision :one
-SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at FROM channel_chat_context_generation
+SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at, last_message_id, last_thread_id, last_sender_id FROM channel_chat_context_generation
WHERE chat_session_id = $1
AND revision = $2
FOR UPDATE
@@ -1926,6 +1989,9 @@ func (q *Queries) LockChannelChatContextGenerationByRevision(ctx context.Context
&i.PendingFresh,
&i.InitiatorUserID,
&i.CreatedAt,
+ &i.LastMessageID,
+ &i.LastThreadID,
+ &i.LastSenderID,
)
return i, err
}
@@ -2584,6 +2650,44 @@ func (q *Queries) SetChannelChatContextInitiator(ctx context.Context, arg SetCha
return initiator_user_id, err
}
+const setChannelChatContextReplyTarget = `-- name: SetChannelChatContextReplyTarget :exec
+UPDATE channel_chat_context_generation
+SET last_message_id = $1,
+ last_thread_id = $2,
+ last_sender_id = $3
+WHERE chat_session_id = $4
+ AND revision = $5
+`
+
+type SetChannelChatContextReplyTargetParams struct {
+ LastMessageID pgtype.Text `json:"last_message_id"`
+ LastThreadID pgtype.Text `json:"last_thread_id"`
+ LastSenderID pgtype.Text `json:"last_sender_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Revision int64 `json:"revision"`
+}
+
+// Snapshots the trigger this generation will be answered on: the message an
+// outbound reply targets, its thread, and the channel-native id of whoever
+// sent it. The sibling of SetChannelChatContextInitiator, and load-bearing for
+// the same reason — a debounced run flushes against ITS generation, which may
+// no longer be the session's newest, so reading the trigger from the session
+// would answer one member's question quoting and @-mentioning another's.
+//
+// All three move together in one statement: a sender or thread that described
+// a different message than the reply targets is precisely the cross-attribution
+// this exists to prevent.
+func (q *Queries) SetChannelChatContextReplyTarget(ctx context.Context, arg SetChannelChatContextReplyTargetParams) error {
+ _, err := q.db.Exec(ctx, setChannelChatContextReplyTarget,
+ arg.LastMessageID,
+ arg.LastThreadID,
+ arg.LastSenderID,
+ arg.ChatSessionID,
+ arg.Revision,
+ )
+ return err
+}
+
const setChannelInstallationConfig = `-- name: SetChannelInstallationConfig :exec
UPDATE channel_installation
SET config = $2, updated_at = now()
@@ -2712,8 +2816,11 @@ type UpdateChannelChatSessionBindingReplyTargetParams struct {
ReplyChatSessionID pgtype.UUID `json:"reply_chat_session_id"`
}
-// Records the most recent inbound trigger message + thread so the decoupled
-// outbound patcher can thread its reply back into the originating topic.
+// Advances the session's latest-trigger cursor, which drives the history
+// boundary bookkeeping below. NOT the outbound reply target: that is frozen
+// per context generation (SetChannelChatContextReplyTarget), because this row
+// only ever remembers the newest trigger and a debounced run can be enqueued
+// after a later generation has already moved it.
func (q *Queries) UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg UpdateChannelChatSessionBindingReplyTargetParams) error {
_, err := q.db.Exec(ctx, updateChannelChatSessionBindingReplyTarget, arg.LastMessageID, arg.LastThreadID, arg.ReplyChatSessionID)
return err
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index b15e113619..c3067c09d5 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -337,6 +337,9 @@ type ChannelChatContextGeneration struct {
PendingFresh bool `json:"pending_fresh"`
InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
+ LastMessageID pgtype.Text `json:"last_message_id"`
+ LastThreadID pgtype.Text `json:"last_thread_id"`
+ LastSenderID pgtype.Text `json:"last_sender_id"`
}
type ChannelChatSessionBinding struct {
@@ -445,6 +448,7 @@ type ChannelTaskDelivery struct {
RouteRevision int64 `json:"route_revision"`
Config []byte `json:"config"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ChannelSenderID pgtype.Text `json:"channel_sender_id"`
}
type ChannelUserBinding struct {
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index b9d600086e..f7b2ac9c4f 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -635,8 +635,11 @@ SELECT * FROM channel_chat_session_binding
WHERE chat_session_id = ANY(@chat_session_ids::uuid[]);
-- name: UpdateChannelChatSessionBindingReplyTarget :exec
--- Records the most recent inbound trigger message + thread so the decoupled
--- outbound patcher can thread its reply back into the originating topic.
+-- Advances the session's latest-trigger cursor, which drives the history
+-- boundary bookkeeping below. NOT the outbound reply target: that is frozen
+-- per context generation (SetChannelChatContextReplyTarget), because this row
+-- only ever remembers the newest trigger and a debounced run can be enqueued
+-- after a later generation has already moved it.
WITH current_route AS (
SELECT current_binding.*
FROM channel_chat_session_binding AS current_binding
@@ -763,6 +766,24 @@ WHERE chat_session_id = @chat_session_id
AND revision = @revision
RETURNING initiator_user_id;
+-- name: SetChannelChatContextReplyTarget :exec
+-- Snapshots the trigger this generation will be answered on: the message an
+-- outbound reply targets, its thread, and the channel-native id of whoever
+-- sent it. The sibling of SetChannelChatContextInitiator, and load-bearing for
+-- the same reason — a debounced run flushes against ITS generation, which may
+-- no longer be the session's newest, so reading the trigger from the session
+-- would answer one member's question quoting and @-mentioning another's.
+--
+-- All three move together in one statement: a sender or thread that described
+-- a different message than the reply targets is precisely the cross-attribution
+-- this exists to prevent.
+UPDATE channel_chat_context_generation
+SET last_message_id = sqlc.narg('last_message_id'),
+ last_thread_id = sqlc.narg('last_thread_id'),
+ last_sender_id = sqlc.narg('last_sender_id')
+WHERE chat_session_id = @chat_session_id
+ AND revision = @revision;
+
-- name: ClearChannelChatContextPendingFresh :exec
UPDATE channel_chat_context_generation
SET pending_fresh = FALSE
@@ -819,15 +840,66 @@ WHERE binding.installation_id = sqlc.arg('installation_id')
-- =====================
-- name: CreateChannelTaskDeliveryFromSession :one
+-- Freezes one task's outbound delivery, from two different sources on purpose.
+--
+-- ROUTE — chat, type, config, revision — comes from the session binding. It is
+-- a property of the session and does not vary by generation.
+--
+-- TRIGGER — the message an answer quotes, the thread it replies into, and the
+-- account it @-mentions — comes from the generation this task answers, NOT
+-- from the binding's latest-trigger cursor, which a newer generation may
+-- already have advanced past.
+--
+-- The thread sits with the trigger rather than the route deliberately. For a
+-- thread-isolated session (Lark topic, Slack channel thread) the two coincide,
+-- so it is easy to mistake the thread for route data — but Slack DMs keep ONE
+-- binding per channel while replying into whichever thread the member used
+-- (slackSessionRouting), so the binding cursor there names the latest thread,
+-- not this run's. Taking it from the generation is correct for both shapes.
+--
+-- The one exception is the CASE below: when a generation recorded no trigger
+-- at all, a thread-isolated binding can still say which thread the session
+-- lives in, and must, or the answer surfaces in the parent channel.
+--
+-- A NULL trigger means "we cannot attribute this run": callers reply without a
+-- quote or mention rather than inventing one. INNER JOIN on the generation: a
+-- task whose generation row is missing entirely has no context to deliver
+-- against at all.
INSERT INTO channel_task_delivery (
task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
- channel_message_id, channel_thread_id, route_revision, config
+ channel_message_id, channel_thread_id, channel_sender_id, route_revision, config
)
SELECT
@task_id, binding.id, binding.installation_id, binding.channel_type,
- binding.channel_chat_id, binding.chat_type, binding.last_message_id, binding.last_thread_id,
+ binding.channel_chat_id, binding.chat_type,
+ generation.last_message_id,
+ CASE
+ -- This generation recorded a trigger, so its thread is authoritative —
+ -- including when it is legitimately empty, which is how a Slack DM
+ -- answered at top level is distinguished from one answered inside a
+ -- thread.
+ WHEN generation.last_message_id IS NOT NULL THEN generation.last_thread_id
+ -- No trigger: pre-migration, or a generation whose only messages were
+ -- channel commands. Recover the thread ONLY for a thread-isolated
+ -- binding, where it is a stable property of the session rather than a
+ -- moving cursor. Such a binding is exactly the one whose key is the
+ -- composite "chat:thread", which is why it carries the real chat id in
+ -- its config — the marker every adapter writes (larkSessionRouting,
+ -- slackSessionRouting, telegramSessionRouting). Without this, a
+ -- recovered pre-migration run in a Slack channel thread or a Telegram
+ -- forum topic would answer in the parent conversation.
+ WHEN COALESCE(binding.config ->> 'chat_id', binding.config ->> 'channel_id', '')
+ NOT IN ('', binding.channel_chat_id) THEN binding.last_thread_id
+ -- A non-isolated binding's cursor names whichever thread spoke last,
+ -- which is not this run's. Nothing we can justify.
+ ELSE NULL
+ END,
+ generation.last_sender_id,
binding.route_revision, binding.config
FROM channel_chat_session_binding AS binding
+JOIN channel_chat_context_generation AS generation
+ ON generation.chat_session_id = binding.chat_session_id
+ AND generation.revision = @context_revision
WHERE binding.chat_session_id = @chat_session_id
RETURNING *;
@@ -837,11 +909,11 @@ SELECT * FROM channel_task_delivery WHERE task_id = $1;
-- name: CopyChannelTaskDelivery :exec
INSERT INTO channel_task_delivery (
task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
- channel_message_id, channel_thread_id, route_revision, config
+ channel_message_id, channel_thread_id, channel_sender_id, route_revision, config
)
SELECT
@child_task_id, delivery.binding_id, delivery.installation_id, delivery.channel_type, delivery.channel_chat_id, delivery.chat_type,
- delivery.channel_message_id, delivery.channel_thread_id, delivery.route_revision, delivery.config
+ delivery.channel_message_id, delivery.channel_thread_id, delivery.channel_sender_id, delivery.route_revision, delivery.config
FROM channel_task_delivery AS delivery
WHERE delivery.task_id = @parent_task_id;