Skip to content

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

Go

fix(lark): isolate topic-group sessions by thread (#5061)

beastfd813f2569a7
diff --git a/server/internal/integrations/lark/channel_store.go b/server/internal/integrations/lark/channel_store.go
index ddc267360f..74dd07bc04 100644
--- a/server/internal/integrations/lark/channel_store.go
+++ b/server/internal/integrations/lark/channel_store.go
@@ -315,23 +315,6 @@ func (s *ChannelStore) GetLarkChatSessionBindingBySession(ctx context.Context, c
return chatSessionBindingFromRow(row), nil
}
-func (s *ChannelStore) CreateLarkChatSessionBinding(ctx context.Context, arg CreateChatSessionBindingParams) (ChatSessionBinding, error) {
- row, err := s.Queries.CreateChannelChatSessionBinding(ctx, db.CreateChannelChatSessionBindingParams{
- ChatSessionID: arg.ChatSessionID,
- InstallationID: arg.InstallationID,
- ChannelType: channelTypeFeishu,
- ChannelChatID: arg.ChannelChatID,
- ChatType: arg.ChatType,
- // Feishu's channel_chat_id is the real chat id, so the key alone routes
- // outbound; config stays the empty object (the column is NOT NULL).
- Config: []byte("{}"),
- })
- if err != nil {
- return ChatSessionBinding{}, err
- }
- return chatSessionBindingFromRow(row), nil
-}
-
func (s *ChannelStore) UpdateLarkChatSessionBindingReplyTarget(ctx context.Context, arg UpdateChatSessionBindingReplyTargetParams) error {
return s.Queries.UpdateChannelChatSessionBindingReplyTarget(ctx, db.UpdateChannelChatSessionBindingReplyTargetParams{
ChatSessionID: arg.ChatSessionID,
diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.go
index 8ef9c64e7c..297fe26425 100644
--- a/server/internal/integrations/lark/feishu_resolvers.go
+++ b/server/internal/integrations/lark/feishu_resolvers.go
@@ -161,16 +161,40 @@ type chatSession interface {
type feishuSessionBinder struct{ session chatSession }
+// larkBindingConfig is the opaque outbound routing persisted on the chat
+// binding's config when the binding key is a composite (Lark topic): the real
+// chat id lives here so the outbound path can post back.
+type larkBindingConfig struct {
+ ChatID string `json:"chat_id"`
+}
+
+// larkSessionRouting derives the session-isolation key (stored as
+// channel_chat_id) and the outbound config from one inbound Feishu message.
+// A p2p or plain group chat is one continuous session per chat, so the key is
+// the chat id and the key alone routes outbound (no config). A message inside
+// a Lark topic (话题, thread_id present) is isolated by topic — key =
+// "chat:thread" — so two @bot topics in one group are two sessions (the same
+// model as Slack's channel:threadRoot; see engine.EnsureSessionInput). Pure
+// function so the isolation contract is unit-tested without a DB.
+func larkSessionRouting(msg channel.InboundMessage) (bindingKey string, config []byte) {
+ chatID := msg.Source.ChatID
+ if msg.Source.ChatType != channel.ChatTypeGroup || msg.Source.ThreadID == "" {
+ return chatID, nil
+ }
+ cfg, _ := json.Marshal(larkBindingConfig{ChatID: chatID})
+ return chatID + ":" + msg.Source.ThreadID, cfg
+}
+
func (r *feishuSessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
+ bindingKey, config := larkSessionRouting(p.Message)
return r.session.EnsureSession(ctx, engine.EnsureSessionInput{
WorkspaceID: p.Installation.WorkspaceID,
AgentID: p.Installation.AgentID,
InstallationID: p.Installation.ID,
Sender: p.Sender,
- // Feishu's chat id is the session-isolation key (one session per chat),
- // and channel_chat_id IS the real outbound chat, so no BindingConfig.
- BindingKey: p.Message.Source.ChatID,
- ChatType: p.Message.Source.ChatType,
+ BindingKey: bindingKey,
+ BindingConfig: config,
+ ChatType: p.Message.Source.ChatType,
})
}
diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.go
index b8922fb948..9b376a9cc0 100644
--- a/server/internal/integrations/lark/feishu_resolvers_test.go
+++ b/server/internal/integrations/lark/feishu_resolvers_test.go
@@ -49,10 +49,10 @@ func TestFeishuSessionBinder_EnsureSessionMapping(t *testing.T) {
got := f.ensureIn
if got.BindingKey != "oc_chat" {
- t.Errorf("BindingKey = %q, want the chat id (Feishu: one session per chat)", got.BindingKey)
+ t.Errorf("BindingKey = %q, want the chat id (plain group: one session per chat)", got.BindingKey)
}
if len(got.BindingConfig) != 0 {
- t.Errorf("Feishu must not set BindingConfig (chat id is the real chat): %q", got.BindingConfig)
+ t.Errorf("plain group must not set BindingConfig (chat id is the real chat): %q", got.BindingConfig)
}
if got.WorkspaceID != binderUUID(2) || got.AgentID != binderUUID(3) || got.InstallationID != binderUUID(1) ||
got.Sender != binderUUID(7) || got.ChatType != channel.ChatTypeGroup {
@@ -60,6 +60,62 @@ func TestFeishuSessionBinder_EnsureSessionMapping(t *testing.T) {
}
}
+// TestFeishuSessionBinder_TopicMessageIsolatesByThread pins the topic-group
+// session-isolation contract (the Slack channel:threadRoot model): a message
+// inside a Lark topic (thread_id present) keys the session by chat+thread so
+// two @bot topics in one group do not collapse into one transcript, and the
+// real chat id rides the binding config for the outbound path.
+func TestFeishuSessionBinder_TopicMessageIsolatesByThread(t *testing.T) {
+ f := &fakeChatSession{}
+ b := &feishuSessionBinder{session: f}
+
+ if _, err := b.EnsureSession(context.Background(), engine.EnsureSessionParams{
+ Installation: engine.ResolvedInstallation{ID: binderUUID(1), WorkspaceID: binderUUID(2), AgentID: binderUUID(3)},
+ Sender: binderUUID(7),
+ Message: channel.InboundMessage{Source: channel.Source{
+ ChatID: "oc_chat", ChatType: channel.ChatTypeGroup, ThreadID: "omt_topic1",
+ }},
+ }); err != nil {
+ t.Fatalf("EnsureSession: %v", err)
+ }
+
+ got := f.ensureIn
+ if got.BindingKey != "oc_chat:omt_topic1" {
+ t.Errorf("BindingKey = %q, want chat:thread composite (topic isolation)", got.BindingKey)
+ }
+ var cfg larkBindingConfig
+ if err := json.Unmarshal(got.BindingConfig, &cfg); err != nil || cfg.ChatID != "oc_chat" {
+ t.Errorf("BindingConfig must carry the real chat id, got %q (err=%v)", got.BindingConfig, err)
+ }
+}
+
+// TestLarkSessionRouting unit-tests the pure key-derivation contract.
+func TestLarkSessionRouting(t *testing.T) {
+ cases := []struct {
+ name string
+ src channel.Source
+ wantKey string
+ wantConfig bool
+ }{
+ {"p2p", channel.Source{ChatID: "oc_dm", ChatType: channel.ChatTypeP2P}, "oc_dm", false},
+ // p2p never has topics; a stray thread id must not split the DM session.
+ {"p2p with stray thread", channel.Source{ChatID: "oc_dm", ChatType: channel.ChatTypeP2P, ThreadID: "omt_x"}, "oc_dm", false},
+ {"plain group", channel.Source{ChatID: "oc_g", ChatType: channel.ChatTypeGroup}, "oc_g", false},
+ {"topic group", channel.Source{ChatID: "oc_g", ChatType: channel.ChatTypeGroup, ThreadID: "omt_1"}, "oc_g:omt_1", true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ key, config := larkSessionRouting(channel.InboundMessage{Source: tc.src})
+ if key != tc.wantKey {
+ t.Errorf("bindingKey = %q, want %q", key, tc.wantKey)
+ }
+ if tc.wantConfig != (len(config) > 0) {
+ t.Errorf("config presence = %v, want %v (%q)", len(config) > 0, tc.wantConfig, config)
+ }
+ })
+ }
+}
+
func TestFeishuSessionBinder_AppendUsesUnenrichedCommandBody(t *testing.T) {
f := &fakeChatSession{}
b := &feishuSessionBinder{session: f}
diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.go
index 1c60504911..f84036aa87 100644
--- a/server/internal/integrations/lark/outbound.go
+++ b/server/internal/integrations/lark/outbound.go
@@ -364,7 +364,7 @@ func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentia
return sendWithThreadFallback(p.cfg.Logger, "send markdown card", target, func(t ReplyTarget) error {
_, err := p.client.SendMarkdownCard(ctx, SendMarkdownCardParams{
InstallationID: creds,
- ChatID: ChatID(binding.ChannelChatID),
+ ChatID: outboundChatID(binding),
Markdown: content,
ReplyTarget: t,
})
@@ -374,7 +374,7 @@ func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentia
return sendWithThreadFallback(p.cfg.Logger, "send text message", target, func(t ReplyTarget) error {
_, err := p.client.SendTextMessage(ctx, SendTextParams{
InstallationID: creds,
- ChatID: ChatID(binding.ChannelChatID),
+ ChatID: outboundChatID(binding),
Text: content,
ReplyTarget: t,
})
@@ -382,6 +382,21 @@ func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentia
})
}
+// outboundChatID recovers the real Lark chat id from the chat binding. The
+// channel_chat_id may be a composite "chat:thread" topic-isolation key, so
+// the real chat id is read from the binding config (larkBindingConfig);
+// pre-topic rows (config "{}") route by the key itself, which for them IS the
+// real chat id.
+func outboundChatID(b ChatSessionBinding) ChatID {
+ if len(b.Config) > 0 {
+ var cfg larkBindingConfig
+ if err := json.Unmarshal(b.Config, &cfg); err == nil && cfg.ChatID != "" {
+ return ChatID(cfg.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
@@ -473,7 +488,7 @@ func (p *Patcher) fail(ctx context.Context, creds InstallationCredentials, bindi
return sendWithThreadFallback(p.cfg.Logger, "send error card", threadReplyTarget(binding), func(t ReplyTarget) error {
_, err := p.client.SendInteractiveCard(ctx, SendCardParams{
InstallationID: creds,
- ChatID: ChatID(binding.ChannelChatID),
+ ChatID: outboundChatID(binding),
CardJSON: render.JSON,
ReplyTarget: t,
})
diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.go
index a6cbf53076..c03a8a260e 100644
--- a/server/internal/integrations/lark/outbound_test.go
+++ b/server/internal/integrations/lark/outbound_test.go
@@ -517,6 +517,65 @@ func TestPatcherRepliesInThreadWhenTriggerWasInThread(t *testing.T) {
}
}
+// TestPatcherTopicSessionSendsToRealChatID pins the composite-key outbound
+// contract: a per-topic session stores "chat:thread" as channel_chat_id (the
+// isolation key), so the send target MUST come from the binding config's real
+// chat id — the raw key is not a valid Lark chat id.
+func TestPatcherTopicSessionSendsToRealChatID(t *testing.T) {
+ p, q, api := newTestPatcher(t)
+ q.binding.ChannelChatID = "oc_test_chat:omt_topic1"
+ q.binding.Config = []byte(`{"chat_id":"oc_test_chat"}`)
+ q.binding.ChatType = "group"
+ q.binding.LastMessageID = pgtype.Text{String: "om_trigger", Valid: true}
+ q.binding.LastThreadID = pgtype.Text{String: "omt_topic1", Valid: true}
+ taskID := uuidFromString(t, "eeaaaaaa-eeaa-eeaa-eeaa-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "topic 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]
+ if got.ChatID != "oc_test_chat" {
+ t.Errorf("chat_id = %q, want the real chat id from binding config", got.ChatID)
+ }
+ if got.ReplyTarget.MessageID != "om_trigger" || !got.ReplyTarget.InThread {
+ t.Errorf("expected thread reply target {om_trigger, InThread:true}; got %+v", got.ReplyTarget)
+ }
+}
+
+// TestPatcherLegacyBindingFallsBackToKey pins backward compatibility: rows
+// created before topic isolation have the raw chat id as the key and "{}" as
+// config — the send target must stay the key itself.
+func TestPatcherLegacyBindingFallsBackToKey(t *testing.T) {
+ p, q, api := newTestPatcher(t)
+ q.binding.Config = []byte(`{}`)
+ taskID := uuidFromString(t, "eebbbbbb-eebb-eebb-eebb-eeeeeeeeeeee")
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{Content: "legacy 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].ChatID; got != "oc_test_chat" {
+ t.Errorf("chat_id = %q, want the raw binding key for legacy rows", got)
+ }
+}
+
// 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
diff --git a/server/internal/integrations/lark/params.go b/server/internal/integrations/lark/params.go
index b058a52d93..03818bc69d 100644
--- a/server/internal/integrations/lark/params.go
+++ b/server/internal/integrations/lark/params.go
@@ -74,14 +74,6 @@ type GetChatSessionBindingParams struct {
ChannelChatID string
}
-// CreateChatSessionBindingParams binds a chat_session to a channel chat.
-type CreateChatSessionBindingParams struct {
- ChatSessionID pgtype.UUID
- InstallationID pgtype.UUID
- ChannelChatID string
- ChatType string
-}
-
// UpdateChatSessionBindingReplyTargetParams records the latest inbound trigger
// message + thread so the outbound patcher can thread its reply.
type UpdateChatSessionBindingReplyTargetParams struct {
diff --git a/server/internal/integrations/lark/store.go b/server/internal/integrations/lark/store.go
index fce84d12ce..cb918a71bc 100644
--- a/server/internal/integrations/lark/store.go
+++ b/server/internal/integrations/lark/store.go
@@ -71,17 +71,18 @@ type UserBinding struct {
}
// ChatSessionBinding is the flat view of a channel_chat_session_binding row.
-// Every field is a flat column (config is unused for feishu today), so this is
-// a pure copy with no JSON involved.
type ChatSessionBinding struct {
ID pgtype.UUID
ChatSessionID pgtype.UUID
InstallationID pgtype.UUID
ChannelChatID string
ChatType string
- CreatedAt pgtype.Timestamptz
- LastMessageID pgtype.Text
- LastThreadID pgtype.Text
+ // Config carries the real chat id (larkBindingConfig) when ChannelChatID
+ // is a composite "chat:thread" topic-isolation key; "{}" otherwise.
+ Config []byte
+ CreatedAt pgtype.Timestamptz
+ LastMessageID pgtype.Text
+ LastThreadID pgtype.Text
}
// InboundMessageDedup is the flat view of a channel_inbound_message_dedup row.
@@ -215,7 +216,7 @@ func encodeBindingConfig(b UserBinding) ([]byte, error) {
}
// chatSessionBindingFromRow copies a channel_chat_session_binding row into the
-// flat domain struct. No JSON: every feishu field is already a flat column.
+// flat domain struct. Config stays raw bytes; outboundChatID decodes it.
func chatSessionBindingFromRow(row db.ChannelChatSessionBinding) ChatSessionBinding {
return ChatSessionBinding{
ID: row.ID,
@@ -223,6 +224,7 @@ func chatSessionBindingFromRow(row db.ChannelChatSessionBinding) ChatSessionBind
InstallationID: row.InstallationID,
ChannelChatID: row.ChannelChatID,
ChatType: row.ChatType,
+ Config: row.Config,
CreatedAt: row.CreatedAt,
LastMessageID: row.LastMessageID,
LastThreadID: row.LastThreadID,