Skip to content

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

Go

feat(slack): Socket Mode channel.Channel adapter (MUL-3516) (#4523)

Bohan Jiangcb6616f5304a
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 42af180f29..eac8867b55 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -26,6 +26,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
"github.com/multica-ai/multica/server/internal/integrations/lark"
+ "github.com/multica-ai/multica/server/internal/integrations/slack"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -275,14 +276,20 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
patcher.SetTypingIndicatorManager(typingIndicator)
// Inbound pipeline seams: lark_inbound_audit logger and the
- // channel-aware ChatSessionService. They back the Feishu
- // ResolverSet that the channel-agnostic engine.Router runs
- // through, sharing the same IssueService + TaskService that
- // back HTTP, so /issue-created issues share counter, dup
- // guard, project boundary, broadcast, analytics and
- // agent-enqueue with the rest of the product.
+ // shared channel-agnostic chat-session service. They back the
+ // Feishu ResolverSet that the engine.Router runs through,
+ // sharing the same IssueService + TaskService that back HTTP, so
+ // /issue-created issues share counter, dup guard, project
+ // boundary, broadcast, analytics and agent-enqueue with the rest
+ // of the product. Feishu is just another consumer of the shared
+ // engine.ChatSession (channel_type-keyed); the Lark session
+ // titles preserve the pre-cutover wording.
auditLogger := lark.NewAuditLogger(queries)
- chatSvc := lark.NewChatSessionService(queries, pool)
+ feishuSession := engine.NewChatSession(queries, pool, channel.TypeFeishu, engine.SessionTitles{
+ Group: "Lark group chat",
+ Direct: "Lark direct message",
+ Fallback: "Lark chat",
+ })
// OutcomeReplier wires the outbound side: NeedsBinding /
// AgentOffline / AgentArchived / issue-created translate to a
@@ -327,7 +334,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
Logger: slog.Default(),
})
channelRouter.Register(channel.TypeFeishu, lark.NewFeishuResolverSet(
- cs, chatSvc, auditLogger, resolverReplier, typingIndicator,
+ cs, feishuSession, auditLogger, resolverReplier, typingIndicator,
))
slog.Info("lark inbound pipeline wired", "connector", connectorLabel)
@@ -389,6 +396,32 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
} else {
slog.Info("lark integration disabled (MULTICA_LARK_SECRET_KEY not set)")
}
+
+ // Slack integration (MUL-3516). Gated by MULTICA_SLACK_SECRET_KEY — the key
+ // that decrypts the bot/app tokens stored on the channel_installation row.
+ // When unset the whole block is skipped, so existing deployments are
+ // unaffected; an operator opts in by setting the key and creating a
+ // channel_type='slack' installation (config: app_id=team_id, bot_user_id,
+ // bot_token_encrypted, app_token_encrypted). Registering the Factory
+ // (Socket Mode connect/send) + ResolverSet (inbound pipeline) + the outbound
+ // subscriber (agent reply -> Slack) is all it takes — no engine or core edit,
+ // and Feishu is untouched. The Slack ResolverSet/Outbound share the same
+ // engine.ChatSession, channel_* tables, IssueService and TaskService as
+ // Feishu, so /issue, dedup, and run-triggering behave identically.
+ if slackKey, err := secretbox.LoadKey("MULTICA_SLACK_SECRET_KEY"); err == nil {
+ box, err := secretbox.New(slackKey)
+ if err != nil {
+ slog.Error("slack: secretbox.New failed; slack integration disabled", "error", err)
+ } else {
+ slack.RegisterSlack(channelRegistry, slack.SlackChannelDeps{Decrypt: box.Open, Logger: slog.Default()})
+ channelRouter.Register(slack.TypeSlack, slack.NewSlackResolverSet(queries, pool))
+ slack.NewOutbound(queries, box.Open, slog.Default()).Register(bus)
+ slog.Info("slack integration enabled")
+ }
+ } else {
+ slog.Info("slack integration disabled (MULTICA_SLACK_SECRET_KEY not set)")
+ }
+
if opts.HeartbeatScheduler != nil {
h.HeartbeatScheduler = opts.HeartbeatScheduler
}
diff --git a/server/go.mod b/server/go.mod
index 0554c307d0..7d9933c038 100644
--- a/server/go.mod
+++ b/server/go.mod
@@ -23,7 +23,9 @@ require (
github.com/redis/go-redis/v9 v9.18.0
github.com/resend/resend-go/v2 v2.28.0
github.com/robfig/cron/v3 v3.0.1
+ github.com/slack-go/slack v0.26.0
github.com/spf13/cobra v1.10.2
+ github.com/spf13/pflag v1.0.9
golang.org/x/sync v0.20.0
google.golang.org/protobuf v1.36.8
gopkg.in/yaml.v3 v3.0.1
@@ -57,7 +59,6 @@ require (
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.16.1 // indirect
- github.com/spf13/pflag v1.0.9 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/sys v0.35.0 // indirect
diff --git a/server/go.sum b/server/go.sum
index 635fc359c9..c5cb11eaf5 100644
--- a/server/go.sum
+++ b/server/go.sum
@@ -57,6 +57,8 @@ github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
+github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=
+github.com/go-test/deep v1.1.1/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -115,6 +117,8 @@ github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzG
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/slack-go/slack v0.26.0 h1:hx5Iy1t89tSw2zLEHu5YFFTDDFGmvhYCUh73ptHQ2Ls=
+github.com/slack-go/slack v0.26.0/go.mod h1:UEe+jmo9WLlwHB04qsOrTDvqM7Aa4rQL3O5wF3n0hx4=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
diff --git a/server/internal/integrations/channel/engine/issue_command.go b/server/internal/integrations/channel/engine/issue_command.go
new file mode 100644
index 0000000000..1f7f67e370
--- /dev/null
+++ b/server/internal/integrations/channel/engine/issue_command.go
@@ -0,0 +1,75 @@
+package engine
+
+import "strings"
+
+// issueCommandPrefix is the literal command token. We match exactly —
+// `/Issue` or `/ISSUE` do NOT trigger creation. The case sensitivity is
+// product-intentional: it avoids accidentally promoting messages that mention
+// "/issue" inline in a sentence. This is cross-platform product behavior, so it
+// lives in the shared engine rather than in any one adapter.
+const issueCommandPrefix = "/issue"
+
+// ParseIssueCommand extracts an /issue command from a chat-message body. It
+// returns (cmd, true) when the message qualifies and the caller should dispatch
+// to IssueService.Create; (nil, false) otherwise. Recognized shapes:
+//
+// - `/issue <title>` → Title = "<title>", Description = ""
+// - `/issue <title>\n<rest...>` → Title = "<title>", Description = "<rest>"
+// - `/issue` (alone, no title) → Title = "", Description = ""
+// (the caller falls back to the previous user message; the parser does not
+// do that lookup itself because it has no DB access)
+//
+// Only the first non-empty line is considered: a body that begins with blank
+// lines and then `/issue ...` still qualifies. A body whose first non-empty
+// line is anything other than the literal prefix is not an issue command, even
+// if `/issue` appears later. `/issue` must be a whole token, not a prefix of
+// one ("/issuetracker" does not match).
+func ParseIssueCommand(body string) (*IssueCommand, bool) {
+ lines := strings.Split(body, "\n")
+
+ firstIdx := -1
+ for i, line := range lines {
+ if strings.TrimSpace(line) != "" {
+ firstIdx = i
+ break
+ }
+ }
+ if firstIdx == -1 {
+ return nil, false
+ }
+
+ trimmed := strings.TrimLeft(lines[firstIdx], " \t")
+ if !strings.HasPrefix(trimmed, issueCommandPrefix) {
+ return nil, false
+ }
+
+ rest := trimmed[len(issueCommandPrefix):]
+ if rest != "" {
+ if r0 := rest[0]; r0 != ' ' && r0 != '\t' {
+ return nil, false
+ }
+ }
+
+ title := strings.TrimSpace(rest)
+ description := ""
+ if firstIdx+1 < len(lines) {
+ description = strings.TrimRight(strings.Join(lines[firstIdx+1:], "\n"), " \t\n")
+ }
+ return &IssueCommand{Title: title, Description: description}, true
+}
+
+// titleFromPreviousMessage derives a title from a prior chat message, used for
+// the bare `/issue` fallback. The previous message may itself be an `/issue …`
+// invocation (two commands in a row), in which case stripping the prefix yields
+// the real intent; otherwise the first non-empty line is the title.
+func titleFromPreviousMessage(body string) string {
+ if cmd, ok := ParseIssueCommand(body); ok {
+ return cmd.Title
+ }
+ for _, line := range strings.Split(body, "\n") {
+ if t := strings.TrimSpace(line); t != "" {
+ return t
+ }
+ }
+ return ""
+}
diff --git a/server/internal/integrations/channel/engine/issue_command_test.go b/server/internal/integrations/channel/engine/issue_command_test.go
new file mode 100644
index 0000000000..6592dd02c0
--- /dev/null
+++ b/server/internal/integrations/channel/engine/issue_command_test.go
@@ -0,0 +1,54 @@
+package engine
+
+import "testing"
+
+func TestParseIssueCommand(t *testing.T) {
+ cases := []struct {
+ name string
+ body string
+ wantOK bool
+ wantTitle string
+ wantDesc string
+ }{
+ {"title only", "/issue Fix the login bug", true, "Fix the login bug", ""},
+ {"title + description", "/issue Fix login\nIt 500s on submit\nsince Tuesday", true, "Fix login", "It 500s on submit\nsince Tuesday"},
+ {"bare command", "/issue", true, "", ""},
+ {"bare command with trailing space", "/issue ", true, "", ""},
+ {"leading blank lines", "\n\n/issue Title", true, "Title", ""},
+ {"tab separator", "/issue\tTabbed", true, "Tabbed", ""},
+ {"not a token", "/issuetracker do thing", false, "", ""},
+ {"prefix mid-sentence", "hey /issue not a command", false, "", ""},
+ {"case sensitive", "/Issue Title", false, "", ""},
+ {"empty", "", false, "", ""},
+ {"only whitespace", " \n ", false, "", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ cmd, ok := ParseIssueCommand(tc.body)
+ if ok != tc.wantOK {
+ t.Fatalf("ok = %v, want %v", ok, tc.wantOK)
+ }
+ if !tc.wantOK {
+ if cmd != nil {
+ t.Errorf("cmd = %+v, want nil", cmd)
+ }
+ return
+ }
+ if cmd.Title != tc.wantTitle || cmd.Description != tc.wantDesc {
+ t.Errorf("cmd = {%q, %q}, want {%q, %q}", cmd.Title, cmd.Description, tc.wantTitle, tc.wantDesc)
+ }
+ })
+ }
+}
+
+func TestTitleFromPreviousMessage(t *testing.T) {
+ if got := titleFromPreviousMessage("/issue Real title"); got != "Real title" {
+ t.Errorf("prev /issue should strip prefix: %q", got)
+ }
+ if got := titleFromPreviousMessage("\n first line\nsecond"); got != "first line" {
+ t.Errorf("prev plain should take first non-empty line: %q", got)
+ }
+ if got := titleFromPreviousMessage(" \n "); got != "" {
+ t.Errorf("blank prev → empty: %q", got)
+ }
+}
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
new file mode 100644
index 0000000000..84fad9b874
--- /dev/null
+++ b/server/internal/integrations/channel/engine/session.go
@@ -0,0 +1,332 @@
+package engine
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// This file is the SHARED, channel-agnostic chat-session service every IM
+// adapter reuses (MUL-3516). It was lifted out of the Feishu-specific
+// lark.chatSessionService so that adding an IM never re-implements the
+// session/append/`/issue` machinery — the platform adapter contributes only a
+// channel_type, its session titles, and (because enrichment is
+// platform-specific) the command-parse source. The logic — find-or-create
+// session + binding, append message + touch + reply-target + in-tx dedup mark,
+// `/issue` parse — is identical across platforms and carries the channel_type
+// discriminator through the generalized channel_* tables.
+
+const pgSQLStateUniqueViolation = "23505"
+
+// TxStarter abstracts transaction creation. Satisfied by *pgxpool.Pool. Kept
+// local to the engine so the integration layer never back-references
+// internal/service.
+type TxStarter interface {
+ Begin(ctx context.Context) (pgx.Tx, error)
+}
+
+// SessionQueries is the narrow slice of the generated queries the ChatSession
+// service needs. *db.Queries satisfies it through the dbSessionQueries adapter
+// (whose WithTx returns the interface type); tests supply an in-memory fake.
+type SessionQueries interface {
+ WithTx(tx pgx.Tx) SessionQueries
+ GetChannelChatSessionBinding(ctx context.Context, arg db.GetChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)
+ CreateChatSession(ctx context.Context, arg db.CreateChatSessionParams) (db.ChatSession, error)
+ CreateChannelChatSessionBinding(ctx context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)
+ CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error)
+ TouchChatSession(ctx context.Context, id pgtype.UUID) error
+ GetMostRecentUserChatMessage(ctx context.Context, chatSessionID pgtype.UUID) (db.ChatMessage, error)
+ UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) error
+ MarkChannelInboundDedupProcessed(ctx context.Context, arg db.MarkChannelInboundDedupProcessedParams) (int64, error)
+}
+
+// dbSessionQueries adapts *db.Queries to SessionQueries — the only purpose is
+// to give WithTx an interface return type so the transactional path stays
+// behind SessionQueries.
+type dbSessionQueries struct{ q *db.Queries }
+
+func (a dbSessionQueries) WithTx(tx pgx.Tx) SessionQueries {
+ return dbSessionQueries{q: a.q.WithTx(tx)}
+}
+func (a dbSessionQueries) GetChannelChatSessionBinding(ctx context.Context, arg db.GetChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
+ return a.q.GetChannelChatSessionBinding(ctx, arg)
+}
+func (a dbSessionQueries) CreateChatSession(ctx context.Context, arg db.CreateChatSessionParams) (db.ChatSession, error) {
+ return a.q.CreateChatSession(ctx, arg)
+}
+func (a dbSessionQueries) CreateChannelChatSessionBinding(ctx context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
+ return a.q.CreateChannelChatSessionBinding(ctx, arg)
+}
+func (a dbSessionQueries) CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
+ return a.q.CreateChatMessage(ctx, arg)
+}
+func (a dbSessionQueries) TouchChatSession(ctx context.Context, id pgtype.UUID) error {
+ return a.q.TouchChatSession(ctx, id)
+}
+func (a dbSessionQueries) GetMostRecentUserChatMessage(ctx context.Context, chatSessionID pgtype.UUID) (db.ChatMessage, error) {
+ return a.q.GetMostRecentUserChatMessage(ctx, chatSessionID)
+}
+func (a dbSessionQueries) UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) error {
+ return a.q.UpdateChannelChatSessionBindingReplyTarget(ctx, arg)
+}
+func (a dbSessionQueries) MarkChannelInboundDedupProcessed(ctx context.Context, arg db.MarkChannelInboundDedupProcessedParams) (int64, error) {
+ return a.q.MarkChannelInboundDedupProcessed(ctx, arg)
+}
+
+// SessionTitles are the per-platform display titles a freshly created
+// chat_session gets (the first message has not been appended yet, so the title
+// cannot be derived from content). The adapter supplies its own wording.
+type SessionTitles struct {
+ Group string
+ Direct string
+ Fallback string
+}
+
+func (t SessionTitles) forType(ct channel.ChatType) string {
+ switch ct {
+ case channel.ChatTypeGroup:
+ return t.Group
+ case channel.ChatTypeP2P:
+ return t.Direct
+ default:
+ return t.Fallback
+ }
+}
+
+// ChatSession is the shared chat-session service. One instance is built per
+// channel_type (so the binding rows carry the right discriminator); the logic
+// is otherwise platform-neutral.
+type ChatSession struct {
+ q SessionQueries
+ tx TxStarter
+ channelType channel.Type
+ titles SessionTitles
+}
+
+// NewChatSession builds the shared service over the generated queries. tx is
+// required: AppendUserMessage runs the dedup Mark inside the chat_message
+// transaction so the durable write and the Mark commit (or roll back) together.
+func NewChatSession(q *db.Queries, tx TxStarter, channelType channel.Type, titles SessionTitles) *ChatSession {
+ return &ChatSession{q: dbSessionQueries{q: q}, tx: tx, channelType: channelType, titles: titles}
+}
+
+// newChatSessionWith is the test seam: it accepts a SessionQueries directly so
+// an in-memory fake can stand in for *db.Queries.
+func newChatSessionWith(q SessionQueries, tx TxStarter, channelType channel.Type, titles SessionTitles) *ChatSession {
+ return &ChatSession{q: q, tx: tx, channelType: channelType, titles: titles}
+}
+
+// EnsureSessionInput is the channel-agnostic input for EnsureSession.
+//
+// BindingKey is the SESSION-ISOLATION key (stored as channel_chat_id; one
+// chat_session per (installation_id, BindingKey)). It is intentionally NOT the
+// same thing as "the chat to reply into": the adapter composes it so that
+// distinct conversations get distinct sessions — Feishu passes the chat id;
+// Slack passes the channel id for a DM, and the channel id PLUS the thread root
+// for a channel/thread, so two @bot threads in one Slack channel do not collapse
+// into one transcript (the Hermes model: IM-independent, Slack groups isolated
+// by thread root). A raw platform chat id must never be passed straight through
+// as the key for a threaded platform.
+//
+// BindingConfig is opaque platform routing the key alone cannot carry — e.g.
+// Slack's real channel_id when BindingKey is a composite — persisted on the
+// binding's config for the outbound path to read back. nil means "{}".
+//
+// Sender is the already-resolved Multica user (the session creator: the sole
+// human for p2p, the installer for group chats — the caller decides which).
+type EnsureSessionInput struct {
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ InstallationID pgtype.UUID
+ Sender pgtype.UUID
+ BindingKey string
+ BindingConfig []byte
+ ChatType channel.ChatType
+}
+
+// EnsureSession returns the chat_session.id bound to (installation, BindingKey),
+// creating it (with its channel_chat_session_binding) on first contact. The
+// race between two concurrent first messages is resolved by the
+// UNIQUE (installation_id, channel_chat_id) constraint: the loser re-reads the
+// winner's row.
+func (s *ChatSession) EnsureSession(ctx context.Context, in EnsureSessionInput) (pgtype.UUID, error) {
+ lookup := db.GetChannelChatSessionBindingParams{InstallationID: in.InstallationID, ChannelChatID: in.BindingKey}
+
+ existing, err := s.q.GetChannelChatSessionBinding(ctx, lookup)
+ if err == nil {
+ return existing.ChatSessionID, nil
+ }
+ if !errors.Is(err, pgx.ErrNoRows) {
+ return pgtype.UUID{}, fmt.Errorf("lookup chat session binding: %w", err)
+ }
+
+ id, err := s.createSessionAndBinding(ctx, in)
+ if err == nil {
+ return id, nil
+ }
+ if isUniqueViolation(err) {
+ existing, lookupErr := s.q.GetChannelChatSessionBinding(ctx, lookup)
+ if lookupErr == nil {
+ return existing.ChatSessionID, nil
+ }
+ return pgtype.UUID{}, fmt.Errorf("race re-read after unique violation: %w", lookupErr)
+ }
+ return pgtype.UUID{}, err
+}
+
+func (s *ChatSession) createSessionAndBinding(ctx context.Context, in EnsureSessionInput) (pgtype.UUID, error) {
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return pgtype.UUID{}, fmt.Errorf("begin tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := s.q.WithTx(tx)
+
+ session, err := qtx.CreateChatSession(ctx, db.CreateChatSessionParams{
+ WorkspaceID: in.WorkspaceID,
+ AgentID: in.AgentID,
+ CreatorID: in.Sender,
+ Title: s.titles.forType(in.ChatType),
+ })
+ if err != nil {
+ return pgtype.UUID{}, fmt.Errorf("create chat session: %w", err)
+ }
+ bindingConfig := in.BindingConfig
+ if len(bindingConfig) == 0 {
+ bindingConfig = []byte("{}")
+ }
+ if _, err := qtx.CreateChannelChatSessionBinding(ctx, db.CreateChannelChatSessionBindingParams{
+ ChatSessionID: session.ID,
+ InstallationID: in.InstallationID,
+ ChannelType: string(s.channelType),
+ ChannelChatID: in.BindingKey,
+ ChatType: string(in.ChatType),
+ Config: bindingConfig,
+ }); err != nil {
+ return pgtype.UUID{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return pgtype.UUID{}, fmt.Errorf("commit: %w", err)
+ }
+ return session.ID, nil
+}
+
+// AppendInput is the channel-agnostic input for AppendUserMessage. Body is the
+// full stored text (including any platform enrichment); CommandText is the
+// user's OWN typed text used for `/issue` parsing (empty falls back to Body) —
+// the adapter supplies it because enrichment is platform-specific. ClaimToken
+// is the dedup owner-fence: when valid, the Mark runs inside this method's tx.
+//
+// MessageID and ThreadID are the REAL platform message id and thread id of this
+// trigger — the outbound reply target recorded on the binding (last_message_id /
+// last_thread_id), NOT the session BindingKey. Because each isolated session has
+// 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
+ ThreadID string
+ ClaimToken pgtype.UUID
+}
+
+// AppendUserMessage writes the user message into the chat_session (touching it
+// and recording the reply target), runs the in-tx dedup Mark when a claim token
+// is supplied, and returns the parsed `/issue` command when present. Returns
+// ErrClaimLost when a concurrent reclaim rotated the dedup token mid-flight, in
+// which case the whole transaction rolls back (no chat_message lands).
+func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (AppendResult, error) {
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return AppendResult{}, fmt.Errorf("begin tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := s.q.WithTx(tx)
+
+ // Parse before the insert so the bare-`/issue` previous-message fallback
+ // queries the message set that does NOT yet include this message.
+ commandSource := in.CommandText
+ if commandSource == "" {
+ commandSource = in.Body
+ }
+ cmd, _ := ParseIssueCommand(commandSource)
+ if cmd != nil && cmd.Title == "" {
+ prev, err := qtx.GetMostRecentUserChatMessage(ctx, in.SessionID)
+ if err == nil {
+ cmd.Title = titleFromPreviousMessage(prev.Content)
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return AppendResult{}, fmt.Errorf("previous message lookup: %w", err)
+ }
+ }
+
+ if _, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ChatSessionID: in.SessionID,
+ Role: "user",
+ Content: in.Body,
+ }); err != nil {
+ return AppendResult{}, fmt.Errorf("create chat message: %w", err)
+ }
+ if err := qtx.TouchChatSession(ctx, in.SessionID); err != nil {
+ 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.
+ if in.MessageID != "" {
+ if err := qtx.UpdateChannelChatSessionBindingReplyTarget(ctx, db.UpdateChannelChatSessionBindingReplyTargetParams{
+ ChatSessionID: in.SessionID,
+ LastMessageID: textOrNull(in.MessageID),
+ LastThreadID: textOrNull(in.ThreadID),
+ }); err != nil {
+ return AppendResult{}, fmt.Errorf("update reply target: %w", err)
+ }
+ }
+
+ markedInTx := false
+ if in.ClaimToken.Valid && in.MessageID != "" {
+ rows, err := qtx.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
+ InstallationID: in.InstallationID,
+ MessageID: in.MessageID,
+ ClaimToken: in.ClaimToken,
+ })
+ if err != nil {
+ return AppendResult{}, fmt.Errorf("mark dedup processed: %w", err)
+ }
+ if rows == 0 {
+ // Another worker re-claimed the dedup row; roll back via the
+ // deferred Rollback so no second chat_message lands.
+ return AppendResult{}, ErrClaimLost
+ }
+ markedInTx = true
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ return AppendResult{}, fmt.Errorf("commit: %w", err)
+ }
+ return AppendResult{IssueCommand: cmd, DedupMarked: markedInTx}, nil
+}
+
+func isUniqueViolation(err error) bool {
+ var pg *pgconn.PgError
+ if errors.As(err, &pg) {
+ return pg.Code == pgSQLStateUniqueViolation
+ }
+ return false
+}
+
+func textOrNull(s string) pgtype.Text {
+ if s == "" {
+ return pgtype.Text{}
+ }
+ return pgtype.Text{String: s, Valid: true}
+}
diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.go
new file mode 100644
index 0000000000..d9b3d6ce66
--- /dev/null
+++ b/server/internal/integrations/channel/engine/session_test.go
@@ -0,0 +1,322 @@
+package engine
+
+import (
+ "context"
+ "fmt"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// uid builds a deterministic, valid pgtype.UUID from a single byte so tests can
+// compare ids by equality.
+func uid(b byte) pgtype.UUID {
+ var u pgtype.UUID
+ u.Bytes[0] = b
+ u.Valid = true
+ return u
+}
+
+// fakeTx satisfies pgx.Tx by embedding the (nil) interface; the ChatSession
+// service only calls Commit/Rollback, which we override as no-ops.
+type fakeTx struct{ pgx.Tx }
+
+func (fakeTx) Commit(context.Context) error { return nil }
+func (fakeTx) Rollback(context.Context) error { return nil }
+
+type fakeTxStarter struct{}
+
+func (fakeTxStarter) Begin(context.Context) (pgx.Tx, error) { return fakeTx{}, nil }
+
+// fakeSessionQueries is an in-memory SessionQueries for unit tests.
+type fakeSessionQueries struct {
+ bindings map[string]pgtype.UUID
+ nextSession byte
+ createdSessions int
+ messages []string
+ touched int
+ replyTargets int
+ lastConfig []byte // config of the most recent CreateChannelChatSessionBinding
+
+ prevMessage *string // GetMostRecentUserChatMessage result; nil → ErrNoRows
+ markRows int64 // MarkChannelInboundDedupProcessed result
+ createBindingErr error // simulate a unique violation on create
+ raceWinner pgtype.UUID
+}
+
+func newFake() *fakeSessionQueries {
+ return &fakeSessionQueries{bindings: map[string]pgtype.UUID{}, markRows: 1}
+}
+
+func bindKey(inst pgtype.UUID, chat string) string { return fmt.Sprintf("%x|%s", inst.Bytes, chat) }
+
+func (f *fakeSessionQueries) WithTx(tx pgx.Tx) SessionQueries { return f }
+
+func (f *fakeSessionQueries) GetChannelChatSessionBinding(_ context.Context, arg db.GetChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
+ if id, ok := f.bindings[bindKey(arg.InstallationID, arg.ChannelChatID)]; ok {
+ return db.ChannelChatSessionBinding{ChatSessionID: id}, nil
+ }
+ return db.ChannelChatSessionBinding{}, pgx.ErrNoRows
+}
+
+func (f *fakeSessionQueries) CreateChatSession(_ context.Context, _ db.CreateChatSessionParams) (db.ChatSession, error) {
+ f.nextSession++
+ f.createdSessions++
+ return db.ChatSession{ID: uid(f.nextSession)}, nil
+}
+
+func (f *fakeSessionQueries) CreateChannelChatSessionBinding(_ context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
+ f.lastConfig = arg.Config
+ if f.createBindingErr != nil {
+ // Simulate the race winner having committed its binding first.
+ f.bindings[bindKey(arg.InstallationID, arg.ChannelChatID)] = f.raceWinner
+ return db.ChannelChatSessionBinding{}, f.createBindingErr
+ }
+ f.bindings[bindKey(arg.InstallationID, arg.ChannelChatID)] = arg.ChatSessionID
+ return db.ChannelChatSessionBinding{ChatSessionID: arg.ChatSessionID}, nil
+}
+
+func (f *fakeSessionQueries) CreateChatMessage(_ context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
+ f.messages = append(f.messages, arg.Content)
+ return db.ChatMessage{}, nil
+}
+
+func (f *fakeSessionQueries) TouchChatSession(context.Context, pgtype.UUID) error {
+ f.touched++
+ return nil
+}
+
+func (f *fakeSessionQueries) GetMostRecentUserChatMessage(context.Context, pgtype.UUID) (db.ChatMessage, error) {
+ if f.prevMessage != nil {
+ return db.ChatMessage{Content: *f.prevMessage}, nil
+ }
+ return db.ChatMessage{}, pgx.ErrNoRows
+}
+
+func (f *fakeSessionQueries) UpdateChannelChatSessionBindingReplyTarget(context.Context, db.UpdateChannelChatSessionBindingReplyTargetParams) error {
+ f.replyTargets++
+ return nil
+}
+
+func (f *fakeSessionQueries) MarkChannelInboundDedupProcessed(context.Context, db.MarkChannelInboundDedupProcessedParams) (int64, error) {
+ return f.markRows, nil
+}
+
+func newTestSession(f SessionQueries) *ChatSession {
+ return newChatSessionWith(f, fakeTxStarter{}, channel.TypeFeishu, SessionTitles{Group: "G", Direct: "D", Fallback: "F"})
+}
+
+func TestEnsureSession_CreateThenReuse(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ in := EnsureSessionInput{InstallationID: uid(1), BindingKey: "chatA", ChatType: channel.ChatTypeP2P, Sender: uid(7)}
+
+ id1, err := s.EnsureSession(context.Background(), in)
+ if err != nil {
+ t.Fatalf("first EnsureSession: %v", err)
+ }
+ if f.createdSessions != 1 {
+ t.Fatalf("createdSessions = %d, want 1", f.createdSessions)
+ }
+
+ id2, err := s.EnsureSession(context.Background(), in)
+ if err != nil {
+ t.Fatalf("second EnsureSession: %v", err)
+ }
+ if f.createdSessions != 1 {
+ t.Errorf("second call must reuse the binding, not create: createdSessions = %d", f.createdSessions)
+ }
+ if id1 != id2 {
+ t.Errorf("ids differ: %v vs %v", id1, id2)
+ }
+}
+
+func TestEnsureSession_RaceUniqueViolation(t *testing.T) {
+ f := newFake()
+ f.createBindingErr = &pgconn.PgError{Code: "23505"}
+ f.raceWinner = uid(99)
+ s := newTestSession(f)
+
+ id, err := s.EnsureSession(context.Background(), EnsureSessionInput{InstallationID: uid(1), BindingKey: "chatA", ChatType: channel.ChatTypeGroup})
+ if err != nil {
+ t.Fatalf("EnsureSession on race: %v", err)
+ }
+ if id != uid(99) {
+ t.Errorf("lost-race re-read should return the winner's session: %v", id)
+ }
+}
+
+// TestEnsureSession_ThreadRootIsolation is the regression guard for Elon's
+// must-fix: two @bot threads in the SAME Slack channel must NOT collapse into
+// one chat_session. The Slack resolver composes BindingKey = channel + thread
+// root, so distinct thread roots map to distinct sessions while a follow-up in
+// the same thread reuses its session.
+func TestEnsureSession_ThreadRootIsolation(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ mk := func(key string) pgtype.UUID {
+ id, err := s.EnsureSession(context.Background(), EnsureSessionInput{
+ InstallationID: uid(1), BindingKey: key, ChatType: channel.ChatTypeGroup,
+ })
+ if err != nil {
+ t.Fatalf("EnsureSession(%q): %v", key, err)
+ }
+ return id
+ }
+
+ thread1 := mk("C123:1111.0001")
+ thread2 := mk("C123:2222.0002") // same channel, different thread root
+ if thread1 == thread2 {
+ t.Fatal("distinct thread roots in one channel must get distinct sessions")
+ }
+ if f.createdSessions != 2 {
+ t.Fatalf("createdSessions = %d, want 2", f.createdSessions)
+ }
+
+ again := mk("C123:1111.0001") // a follow-up in thread 1
+ if again != thread1 {
+ t.Error("same thread root must reuse its session")
+ }
+ if f.createdSessions != 2 {
+ t.Errorf("a thread follow-up must not create a new session: createdSessions = %d", f.createdSessions)
+ }
+}
+
+func TestEnsureSession_StoresBindingConfig(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ if _, err := s.EnsureSession(context.Background(), EnsureSessionInput{
+ InstallationID: uid(1), BindingKey: "C123:1111.0001", ChatType: channel.ChatTypeGroup,
+ BindingConfig: []byte(`{"channel_id":"C123"}`),
+ }); err != nil {
+ t.Fatalf("EnsureSession: %v", err)
+ }
+ if string(f.lastConfig) != `{"channel_id":"C123"}` {
+ t.Errorf("opaque outbound routing must be persisted on the binding: %q", f.lastConfig)
+ }
+
+ // Empty BindingConfig defaults to the "{}" object (the column is NOT NULL).
+ f2 := newFake()
+ if _, err := newTestSession(f2).EnsureSession(context.Background(), EnsureSessionInput{
+ InstallationID: uid(1), BindingKey: "chatA", ChatType: channel.ChatTypeP2P,
+ }); err != nil {
+ t.Fatalf("EnsureSession: %v", err)
+ }
+ if string(f2.lastConfig) != "{}" {
+ t.Errorf("empty BindingConfig should default to {}: %q", f2.lastConfig)
+ }
+}
+
+func TestAppendUserMessage_PlainText(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ res, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Sender: uid(7), Body: "hello there", MessageID: "m1",
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if res.IssueCommand != nil {
+ t.Errorf("plain text should not parse as /issue: %+v", res.IssueCommand)
+ }
+ if len(f.messages) != 1 || f.messages[0] != "hello there" {
+ t.Errorf("messages = %v", f.messages)
+ }
+ if f.touched != 1 || f.replyTargets != 1 {
+ t.Errorf("touched=%d replyTargets=%d, want 1/1", f.touched, f.replyTargets)
+ }
+}
+
+func TestAppendUserMessage_NoReplyTargetWithoutMessageID(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ if _, err := s.AppendUserMessage(context.Background(), AppendInput{SessionID: uid(1), Body: "hi"}); err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if f.replyTargets != 0 {
+ t.Errorf("no MessageID → no reply-target update, got %d", f.replyTargets)
+ }
+}
+
+func TestAppendUserMessage_IssueCommand(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ res, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Body: "/issue Fix bug\nsteps to repro", MessageID: "m1",
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if res.IssueCommand == nil || res.IssueCommand.Title != "Fix bug" || res.IssueCommand.Description != "steps to repro" {
+ t.Errorf("IssueCommand = %+v", res.IssueCommand)
+ }
+}
+
+func TestAppendUserMessage_CommandTextOverridesEnrichedBody(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ // Body is enriched (quoted context prepended) so /issue is NOT on the first
+ // line; CommandText carries the user's own text and must win.
+ res, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1),
+ Body: "> quoted context from another message\n/issue Real intent",
+ CommandText: "/issue Real intent",
+ MessageID: "m1",
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if res.IssueCommand == nil || res.IssueCommand.Title != "Real intent" {
+ t.Errorf("CommandText should drive /issue parsing: %+v", res.IssueCommand)
+ }
+ // The stored message is still the full (enriched) body.
+ if f.messages[0] != "> quoted context from another message\n/issue Real intent" {
+ t.Errorf("stored body should be the enriched Body: %q", f.messages[0])
+ }
+}
+
+func TestAppendUserMessage_BareIssueUsesPreviousMessage(t *testing.T) {
+ f := newFake()
+ prev := "Make the export button work"
+ f.prevMessage = &prev
+ s := newTestSession(f)
+ res, err := s.AppendUserMessage(context.Background(), AppendInput{SessionID: uid(1), Body: "/issue", MessageID: "m2"})
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if res.IssueCommand == nil || res.IssueCommand.Title != "Make the export button work" {
+ t.Errorf("bare /issue should fall back to previous message title: %+v", res.IssueCommand)
+ }
+}
+
+func TestAppendUserMessage_DedupMark(t *testing.T) {
+ f := newFake()
+ f.markRows = 1
+ s := newTestSession(f)
+ res, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Body: "hi", MessageID: "m1", InstallationID: uid(1), ClaimToken: uid(5),
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if !res.DedupMarked {
+ t.Error("a successful in-tx Mark should set DedupMarked")
+ }
+}
+
+func TestAppendUserMessage_ClaimLost(t *testing.T) {
+ f := newFake()
+ f.markRows = 0 // a concurrent reclaim rotated the token
+ s := newTestSession(f)
+ _, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Body: "hi", MessageID: "m1", InstallationID: uid(1), ClaimToken: uid(5),
+ })
+ if err != ErrClaimLost {
+ t.Errorf("zero Mark rows must return ErrClaimLost, got %v", err)
+ }
+}
diff --git a/server/internal/integrations/lark/channel_store.go b/server/internal/integrations/lark/channel_store.go
index e030179a3b..4afb246c62 100644
--- a/server/internal/integrations/lark/channel_store.go
+++ b/server/internal/integrations/lark/channel_store.go
@@ -265,6 +265,9 @@ func (s *ChannelStore) CreateLarkChatSessionBinding(ctx context.Context, arg Cre
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
diff --git a/server/internal/integrations/lark/chat.go b/server/internal/integrations/lark/chat.go
index a693521a4b..21c8119ed0 100644
--- a/server/internal/integrations/lark/chat.go
+++ b/server/internal/integrations/lark/chat.go
@@ -6,121 +6,15 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
-// ChatSessionService is the channel-aware chat-session entry point for
-// Lark. It exists deliberately apart from the HTTP `SendChatMessage`
-// handler because that handler's single-creator semantics
-// (chat_session.creator_id == request user_id) make sense for the
-// browser/desktop client — one human, one session — but break for
-// group chat_sessions where many Lark users converse with one Bot.
-//
-// Concrete implementation lands in a follow-up PR (MUL-2671). The
-// interface is declared here so the migration + service boundary PR
-// can establish the architectural cut without dragging in OAuth, WS,
-// and card-patching code.
-//
-// Inbound contract (enforced by the implementation):
-//
-// - EnsureChatSession is the ONLY way Lark code creates / looks up a
-// chat_session. Identity check MUST run before this call — the
-// service treats every successful return as "the sender is a
-// verified, workspace-bound user".
-//
-// - AppendUserMessage trusts that the caller has gated the message
-// through identity + group-mention filters. Unbound users and
-// non-addressed group messages do NOT come through here; they go
-// to AuditDrop instead.
-type ChatSessionService interface {
- // EnsureChatSession returns the chat_session bound to the given
- // (installation, lark_chat_id) pair, creating it on first contact.
- // `sender` must already be a verified lark_user_binding row — see
- // the contract note above. The returned UUID is the
- // chat_session.id; callers persist no other state.
- EnsureChatSession(ctx context.Context, p EnsureChatSessionParams) (pgtype.UUID, error)
-
- // AppendUserMessage appends the message to chat_session, dedups
- // via lark_inbound_message_dedup, and (when the message starts
- // with `/issue`) returns the parsed command so the caller can
- // dispatch through service.IssueService.Create.
- AppendUserMessage(ctx context.Context, p AppendUserMessageParams) (AppendResult, error)
-}
-
-// EnsureChatSessionParams carries the inputs for ChatSessionService.EnsureChatSession.
-// Note `Sender` is the resolved Multica user UUID — the caller has
-// already mapped lark_open_id → user via lark_user_binding.
-type EnsureChatSessionParams struct {
- WorkspaceID pgtype.UUID
- InstallationID pgtype.UUID
- AgentID pgtype.UUID
- ChatID ChatID
- ChatType ChatType
- Sender pgtype.UUID
-}
-
-// AppendUserMessageParams carries the inputs for ChatSessionService.AppendUserMessage.
-// Body is the (already-decoded) user-facing text. LarkMessageID is the
-// Lark-side message id used for idempotency dedup.
-//
-// ClaimToken is the owner-fencing token returned by the dispatcher's
-// ClaimLarkInboundDedup call. When ClaimToken.Valid is true,
-// AppendUserMessage runs MarkLarkInboundDedupProcessed INSIDE its own
-// chat_message+session transaction, gated on this token. A mismatched
-// token (another worker re-claimed the row while we were running)
-// returns ErrClaimLost and rolls back the entire transaction, so no
-// second chat_message can land for the same Lark message_id. Pass an
-// invalid (zero) UUID to skip the in-tx Mark — useful for tests and
-// for callers that have already finalized dedup outside the
-// transaction.
-type AppendUserMessageParams struct {
- ChatSessionID pgtype.UUID
- Sender pgtype.UUID
- // Body is the full text stored as the chat_message — including any
- // quoted-reply / forwarded context the enricher inlined.
- Body string
- // CommandBody is the user's own typed text, used as the `/issue`
- // command source. It is the un-enriched Body; when empty (callers
- // that don't set it), `/issue` parsing falls back to Body so
- // behavior is unchanged for the non-enriched path.
- CommandBody string
- InstallationID pgtype.UUID
- LarkMessageID string
- // LarkThreadID is the Lark topic (话题) id of the trigger message, or
- // empty for a normal chat message. AppendUserMessage records it (with
- // LarkMessageID) on the chat binding so the outbound patcher can
- // thread its reply back into the originating topic.
- LarkThreadID string
- ClaimToken pgtype.UUID
-}
-
-// AppendResult reports what AppendUserMessage decided.
-//
-// Dedup is enforced by the Dispatcher's top-level dedup gate before
-// AppendUserMessage runs, so a returned AppendResult always
-// represents a freshly-stored message. Callers may safely act on
-// IssueCommand without re-checking idempotency.
-type AppendResult struct {
- // IssueCommand is non-nil when the first non-empty line begins
- // with `/issue`. The caller passes this to
- // service.IssueService.Create.
- IssueCommand *IssueCommand
- // DedupMarked is true when AppendUserMessage finalized the dedup
- // claim in its own transaction (i.e. ClaimToken was supplied and
- // the Mark succeeded). The dispatcher uses this to skip the
- // post-pipeline finalize, since the row is already in its
- // terminal state.
- DedupMarked bool
-}
-
-// IssueCommand is the parsed shape of a user-typed `/issue ...`
-// command. Title is required; Description is the joined remainder of
-// the message body (empty when only a title was given).
-type IssueCommand struct {
- Title string
- Description string
-}
-
-// AuditLogger records dropped inbound events to lark_inbound_audit.
-// The interface deliberately does not accept a message body — see the
-// drop-audit policy in MUL-2671 §4.7.
+// The chat-session ensure/append/`/issue` machinery that used to live here (and
+// in chat_service.go) has moved to the channel-agnostic engine.ChatSession
+// (MUL-3516), which Feishu now consumes via NewFeishuResolverSet — there is no
+// Feishu-specific session service anymore. What remains is the inbound drop
+// audit seam, still Feishu-shaped.
+
+// AuditLogger records dropped inbound events to lark_inbound_audit. The
+// interface deliberately does not accept a message body — see the drop-audit
+// policy in MUL-2671 §4.7.
type AuditLogger interface {
RecordDrop(ctx context.Context, p AuditDropParams) error
}
diff --git a/server/internal/integrations/lark/chat_service.go b/server/internal/integrations/lark/chat_service.go
deleted file mode 100644
index 37626fdce1..0000000000
--- a/server/internal/integrations/lark/chat_service.go
+++ /dev/null
@@ -1,327 +0,0 @@
-package lark
-
-import (
- "context"
- "errors"
- "fmt"
- "strings"
-
- "github.com/jackc/pgx/v5"
- "github.com/jackc/pgx/v5/pgconn"
- "github.com/jackc/pgx/v5/pgtype"
- db "github.com/multica-ai/multica/server/pkg/db/generated"
-)
-
-// pgSQLStateUniqueViolation is the Postgres SQLSTATE for unique
-// constraint violations. Spelled out as a literal rather than imported
-// from pgerrcode to avoid pulling in another dependency for a single
-// constant. See https://www.postgresql.org/docs/current/errcodes-appendix.html
-const pgSQLStateUniqueViolation = "23505"
-
-// ErrClaimLost signals that AppendUserMessage's in-tx dedup Mark
-// matched zero rows — another worker re-claimed the lark_inbound_-
-// message_dedup row while we were running (stale-reclaim race). The
-// transaction is rolled back, no chat_message lands, and the
-// Dispatcher treats this as a duplicate drop: the other worker is the
-// sole writer for this Lark message_id.
-var ErrClaimLost = errors.New("lark dedup claim lost to a concurrent reclaim")
-
-// isUniqueViolation reports whether err is a Postgres unique-violation
-// (SQLSTATE 23505). The lark_chat_session_binding
-// UNIQUE (installation_id, lark_chat_id) constraint surfaces this
-// code when two concurrent first messages on the same Lark chat race
-// to create the binding row.
-func isUniqueViolation(err error) bool {
- var pg *pgconn.PgError
- if errors.As(err, &pg) {
- return pg.Code == pgSQLStateUniqueViolation
- }
- return false
-}
-
-// TxStarter abstracts transaction creation. Re-declared in this
-// package (rather than depending on internal/service) so the
-// integrations layer does not back-reference into service — a circular
-// dependency we want to avoid as both packages grow. Satisfied by
-// *pgxpool.Pool.
-type TxStarter interface {
- Begin(ctx context.Context) (pgx.Tx, error)
-}
-
-// chatSessionService is the concrete ChatSessionService. It enforces
-// the architectural rules from doc.go:
-//
-// - EnsureChatSession only creates / looks up rows; identity must
-// already be resolved by the caller (the sender argument is a
-// trusted Multica user UUID).
-//
-// - AppendUserMessage runs message-write + session-touch in a single
-// transaction so a session that has received a message has its
-// `updated_at` advanced atomically. Per-Lark-message-id idempotency
-// is enforced by the Dispatcher's two-phase dedup gate
-// (ClaimLarkInboundDedup + Mark/Release) BEFORE AppendUserMessage
-// runs — see Dispatcher.Handle. AppendUserMessage trusts the
-// dispatcher's claim and does not re-check dedup itself; this is
-// what lets the dispatcher safely Release the claim on infra
-// failure (rolled-back tx → no chat_message → next replay
-// re-processes).
-type chatSessionService struct {
- queries *ChannelStore
- txStarter TxStarter
-}
-
-// NewChatSessionService constructs a ChatSessionService backed by the
-// supplied queries and tx starter. The tx starter is required;
-// without it, AppendUserMessage cannot run dedup + insert atomically.
-// queries is wrapped in a ChannelStore so the lark_* calls resolve to
-// channel_* rows (MUL-3515).
-func NewChatSessionService(queries *db.Queries, tx TxStarter) ChatSessionService {
- return &chatSessionService{queries: NewChannelStore(queries), txStarter: tx}
-}
-
-// EnsureChatSession returns the chat_session.id bound to the given
-// Lark chat. The implementation is the two-phase find-or-create
-// expected by the interface contract:
-//
-// 1. Look up the existing lark_chat_session_binding.
-// 2. If found, return its chat_session_id.
-// 3. Otherwise, in one transaction: create chat_session +
-// lark_chat_session_binding. Commit.
-//
-// The race between two concurrent first messages on the same Lark
-// chat is resolved by the UNIQUE (installation_id, lark_chat_id)
-// constraint on lark_chat_session_binding: the loser of the race
-// catches the unique violation, re-reads the existing row, and
-// returns its chat_session_id.
-func (s *chatSessionService) EnsureChatSession(ctx context.Context, p EnsureChatSessionParams) (pgtype.UUID, error) {
- // Fast path: existing binding.
- existing, err := s.queries.GetLarkChatSessionBinding(ctx, GetChatSessionBindingParams{
- InstallationID: p.InstallationID,
- ChannelChatID: string(p.ChatID),
- })
- if err == nil {
- return existing.ChatSessionID, nil
- }
- if !errors.Is(err, pgx.ErrNoRows) {
- return pgtype.UUID{}, fmt.Errorf("lookup chat session binding: %w", err)
- }
-
- // Create path: chat_session + binding atomically.
- id, err := s.createSessionAndBinding(ctx, p)
- if err == nil {
- return id, nil
- }
-
- // Lost the race: another goroutine created the binding between our
- // lookup and our insert. Re-read and return the winner's session.
- if isUniqueViolation(err) {
- existing, lookupErr := s.queries.GetLarkChatSessionBinding(ctx, GetChatSessionBindingParams{
- InstallationID: p.InstallationID,
- ChannelChatID: string(p.ChatID),
- })
- if lookupErr == nil {
- return existing.ChatSessionID, nil
- }
- return pgtype.UUID{}, fmt.Errorf("race re-read after unique violation: %w", lookupErr)
- }
- return pgtype.UUID{}, err
-}
-
-func (s *chatSessionService) createSessionAndBinding(ctx context.Context, p EnsureChatSessionParams) (pgtype.UUID, error) {
- tx, err := s.txStarter.Begin(ctx)
- if err != nil {
- return pgtype.UUID{}, fmt.Errorf("begin tx: %w", err)
- }
- defer tx.Rollback(ctx)
- qtx := s.queries.WithTx(tx)
-
- session, err := qtx.CreateChatSession(ctx, db.CreateChatSessionParams{
- WorkspaceID: p.WorkspaceID,
- AgentID: p.AgentID,
- CreatorID: p.Sender,
- Title: defaultSessionTitle(p.ChatType),
- })
- if err != nil {
- return pgtype.UUID{}, fmt.Errorf("create chat session: %w", err)
- }
-
- if _, err := qtx.CreateLarkChatSessionBinding(ctx, CreateChatSessionBindingParams{
- ChatSessionID: session.ID,
- InstallationID: p.InstallationID,
- ChannelChatID: string(p.ChatID),
- ChatType: string(p.ChatType),
- }); err != nil {
- return pgtype.UUID{}, err
- }
-
- if err := tx.Commit(ctx); err != nil {
- return pgtype.UUID{}, fmt.Errorf("commit: %w", err)
- }
- return session.ID, nil
-}
-
-// AppendUserMessage writes the user message into chat_session and
-// (when the body parses as `/issue …`) returns the parsed command so
-// the caller can dispatch through IssueService.
-//
-// Idempotency is enforced as a two-step contract with the Dispatcher's
-// ClaimLarkInboundDedup gate:
-//
-// 1. BEFORE this method is called, the Dispatcher claims an in-flight
-// row in lark_inbound_message_dedup and gets back a `claim_token`.
-// A replay whose previous attempt reached a durable outcome —
-// processed_at IS NOT NULL — is dropped at that gate and never
-// reaches AppendUserMessage at all.
-//
-// 2. INSIDE this method's chat_message+session transaction, when
-// ClaimToken is supplied, we run MarkLarkInboundDedupProcessed
-// gated on (message_id, claim_token, processed_at IS NULL). If
-// another worker re-claimed the dedup row in the meantime — e.g.
-// because we ran slowly past the 60-second staleness TTL — the
-// row's claim_token has rotated, our UPDATE matches zero rows,
-// and we return ErrClaimLost. The deferred Rollback then unwinds
-// the chat_message + session writes, so no second chat_message
-// lands for the same Lark message_id.
-//
-// Together these close the two windows that staleness-TTL alone left
-// open (stale-reclaim race + Mark-window crash): the durable write
-// and the dedup Mark commit (or roll back) atomically.
-//
-// Callers that pass an invalid (zero) ClaimToken get the legacy
-// behavior — just write the message — and are responsible for
-// finalizing the dedup row themselves. The dispatcher always passes
-// the live token; tests use the zero value when they want to exercise
-// the write path without modelling dedup.
-func (s *chatSessionService) AppendUserMessage(ctx context.Context, p AppendUserMessageParams) (AppendResult, error) {
- tx, err := s.txStarter.Begin(ctx)
- if err != nil {
- return AppendResult{}, fmt.Errorf("begin tx: %w", err)
- }
- defer tx.Rollback(ctx)
- qtx := s.queries.WithTx(tx)
-
- // Parse the command from the user's OWN typed text (CommandBody),
- // not the stored Body: the enricher prepends quoted / forwarded
- // context to Body, which would push a `/issue …` off the first line
- // and silently stop creating the issue (parseIssueCommand only
- // inspects the first non-empty line). Fall back to Body when
- // CommandBody is unset so non-enriched callers are unaffected.
- //
- // Parse BEFORE the insert so the "/issue alone → use previous user
- // message" fallback queries from the message set that does NOT yet
- // include the message currently being appended; otherwise the
- // previous-message lookup would self-reference.
- commandSource := p.CommandBody
- if commandSource == "" {
- commandSource = p.Body
- }
- cmd, _ := parseIssueCommand(commandSource)
- if cmd != nil && cmd.Title == "" {
- prev, err := qtx.GetMostRecentUserChatMessage(ctx, p.ChatSessionID)
- if err == nil {
- cmd.Title = titleFromPreviousMessage(prev.Content)
- } else if !errors.Is(err, pgx.ErrNoRows) {
- return AppendResult{}, fmt.Errorf("previous message lookup: %w", err)
- }
- }
-
- if _, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
- ChatSessionID: p.ChatSessionID,
- Role: "user",
- Content: p.Body,
- }); err != nil {
- return AppendResult{}, fmt.Errorf("create chat message: %w", err)
- }
-
- if err := qtx.TouchChatSession(ctx, p.ChatSessionID); err != nil {
- return AppendResult{}, fmt.Errorf("touch chat session: %w", err)
- }
-
- // Record this message as the chat binding's most-recent reply
- // target. The outbound patcher is event-driven and disconnected from
- // the inbound message, so it cannot otherwise know which message /
- // thread to reply into. We persist the latest trigger here (in the
- // same tx as the chat_message write) so EventChatDone can thread the
- // reply back into the originating Lark topic. last_lark_thread_id is
- // NULL for non-thread messages, which keeps the outbound on the
- // chat-level send path. Skipped when there is no Lark message_id
- // (defensive: every real inbound carries one).
- if p.LarkMessageID != "" {
- if err := qtx.UpdateLarkChatSessionBindingReplyTarget(ctx, UpdateChatSessionBindingReplyTargetParams{
- ChatSessionID: p.ChatSessionID,
- LastMessageID: textOrNull(p.LarkMessageID),
- LastThreadID: textOrNull(p.LarkThreadID),
- }); err != nil {
- return AppendResult{}, fmt.Errorf("update reply target: %w", err)
- }
- }
-
- // In-tx dedup Mark, gated on the supplied claim token. The whole
- // point of doing this here — rather than after Commit — is that
- // the chat_message write and the Mark either commit atomically or
- // roll back atomically. A stale-reclaim by another worker rotated
- // claim_token, so our UPDATE matches zero rows; deferring to the
- // post-method Mark path would leave the chat_message in place
- // while another worker also wrote one.
- markedInTx := false
- if p.ClaimToken.Valid && p.LarkMessageID != "" {
- rows, err := qtx.MarkLarkInboundDedupProcessed(ctx, MarkInboundDedupProcessedParams{
- InstallationID: p.InstallationID,
- MessageID: p.LarkMessageID,
- ClaimToken: p.ClaimToken,
- })
- if err != nil {
- return AppendResult{}, fmt.Errorf("mark dedup processed: %w", err)
- }
- if rows == 0 {
- // Another worker holds (or already finalized) this
- // claim. Roll back via the deferred Rollback — the
- // chat_message insert never commits.
- return AppendResult{}, ErrClaimLost
- }
- markedInTx = true
- }
-
- if err := tx.Commit(ctx); err != nil {
- return AppendResult{}, fmt.Errorf("commit: %w", err)
- }
-
- return AppendResult{IssueCommand: cmd, DedupMarked: markedInTx}, nil
-}
-
-// titleFromPreviousMessage extracts a sensible title from a prior
-// chat message. The spec says the previous "user message" is the
-// fallback; in practice the previous message itself might also be an
-// `/issue ...` invocation (the user typed two commands in a row), in
-// which case stripping the prefix yields the real intent.
-func titleFromPreviousMessage(body string) string {
- if cmd, ok := parseIssueCommand(body); ok {
- return cmd.Title
- }
- // First non-empty line, trimmed. Multi-line free text "becomes"
- // the title via its first line; description fallback for the
- // previous-message path is out of scope (the user's intent was a
- // title alone).
- for _, line := range strings.Split(body, "\n") {
- t := strings.TrimSpace(line)
- if t != "" {
- return t
- }
- }
- return ""
-}
-
-// defaultSessionTitle gives a freshly created chat_session a
-// reasonable display title. We do not derive from message content —
-// the first message hasn't been appended yet — so we use a stable
-// per-chat-type label that the front-end can localize later.
-func defaultSessionTitle(t ChatType) string {
- switch t {
- case ChatTypeGroup:
- return "Lark group chat"
- case ChatTypeP2P:
- return "Lark direct message"
- default:
- return "Lark chat"
- }
-}
diff --git a/server/internal/integrations/lark/doc.go b/server/internal/integrations/lark/doc.go
index 07483b73a2..031309ead9 100644
--- a/server/internal/integrations/lark/doc.go
+++ b/server/internal/integrations/lark/doc.go
@@ -7,8 +7,9 @@
// 2. InstallationService (encrypted app_secret, workspace-scoped lookups)
// 3. BindingTokenService (15-minute single-use, transactional redeem
// that rejects cross-user rebinds in-DB)
-// 4. ChatSessionService (channel-aware chat_session ensure / append
-// with /issue command parsing)
+// 4. Feishu ResolverSet (feishu_resolvers.go) feeding the shared,
+// channel-agnostic engine.ChatSession (chat_session ensure / append,
+// /issue parsing) — no Feishu-specific session service remains
// 5. Dispatcher (inbound pipeline: installation route → top-level
// message_id dedup → group filter → identity check → ensure
// session → append → /issue → enqueue chat task; typed outcomes
@@ -28,14 +29,14 @@
// SDK — bootstrap via POST /callback/ws/endpoint, app-layer
// ping/pong, ACK responses on every data frame, ctx cancel breaks
// blocking ReadMessage via a watchdog goroutine for §4.4)
-// 10. Patcher (subscribes to task / chat-done events; keeps the
+// 10. Patcher (subscribes to task / chat-done events; keeps the
// per-task Lark interactive card in sync; throttled patches +
// final/error bypass)
-// 11. OutcomeReplier (outbound side of the EventEmitter contract:
+// 11. OutcomeReplier (outbound side of the EventEmitter contract:
// NeedsBinding mints a token + sends the binding prompt;
// AgentOffline / AgentArchived push status notice cards into the
// chat; Ingested is owned by the Patcher; Dropped is silent)
-// 12. RegistrationService (RFC 8628 device-flow scan-to-install: opens
+// 12. RegistrationService (RFC 8628 device-flow scan-to-install: opens
// a session against accounts.feishu.cn, polls in the background,
// and on success writes through InstallationService + auto-binds
// the installer via InstallerBinder so §2.1 "scan to bind, you're
@@ -45,8 +46,8 @@
//
// 1. Issue creation goes through internal/service.IssueService.Create —
// this package never calls qtx.CreateIssue directly.
-// 2. Inbound message ingestion uses ChatSessionService here, NOT the
-// HTTP `SendChatMessage` handler. Group chat_sessions have multi-
+// 2. Inbound message ingestion uses the shared engine.ChatSession, NOT
+// the HTTP `SendChatMessage` handler. Group chat_sessions have multi-
// member creator semantics that the HTTP handler's single-creator
// guard rejects on purpose.
// 3. Outbound card-message mapping lives in `lark_outbound_card_message`
diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.go
index 9ac29d9743..fdc5aedf44 100644
--- a/server/internal/integrations/lark/feishu_resolvers.go
+++ b/server/internal/integrations/lark/feishu_resolvers.go
@@ -40,14 +40,16 @@ func larkMsgFromRaw(msg channel.InboundMessage) (InboundMessage, error) {
return lm, nil
}
-// NewFeishuResolverSet assembles the Feishu ResolverSet from the store, chat
-// service, audit logger, and (optional) outbound replier + typing indicator.
-func NewFeishuResolverSet(store *ChannelStore, chat ChatSessionService, audit AuditLogger, replier OutcomeReplier, typing *TypingIndicatorManager) engine.ResolverSet {
+// NewFeishuResolverSet assembles the Feishu ResolverSet from the store, the
+// shared session service, audit logger, and (optional) outbound replier +
+// typing indicator. Feishu is just another consumer of the channel-agnostic
+// engine.ChatSession — there is no Feishu-specific session implementation.
+func NewFeishuResolverSet(store *ChannelStore, session *engine.ChatSession, audit AuditLogger, replier OutcomeReplier, typing *TypingIndicatorManager) engine.ResolverSet {
set := engine.ResolverSet{
Installation: &feishuInstallationResolver{store: store},
Identity: &feishuIdentityResolver{store: store},
Dedup: &feishuDeduper{store: store},
- Session: &feishuSessionBinder{chat: chat},
+ Session: &feishuSessionBinder{session: session},
Audit: &feishuAuditor{audit: audit},
OriginType: originFeishuChat,
}
@@ -149,48 +151,47 @@ func (r *feishuDeduper) Release(ctx context.Context, installationID pgtype.UUID,
// ---- session bind / append ----
-type feishuSessionBinder struct{ chat ChatSessionService }
+// chatSession is the slice of engine.ChatSession the Feishu binder drives.
+// Declared as an interface so the (platform-specific) param mapping can be
+// unit-tested with a fake; *engine.ChatSession is the production value.
+type chatSession interface {
+ EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
+ AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
+}
+
+type feishuSessionBinder struct{ session chatSession }
func (r *feishuSessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
- return r.chat.EnsureChatSession(ctx, EnsureChatSessionParams{
+ return r.session.EnsureSession(ctx, engine.EnsureSessionInput{
WorkspaceID: p.Installation.WorkspaceID,
- InstallationID: p.Installation.ID,
AgentID: p.Installation.AgentID,
- ChatID: ChatID(p.Message.Source.ChatID),
- ChatType: ChatType(p.Message.Source.ChatType),
+ 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,
})
}
func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
+ // CommandText is the user's OWN typed text: the Feishu enricher inlines
+ // quoted/forwarded context into Body, so /issue parsing must use the
+ // un-enriched command body stashed in Raw, not Body.
lm, err := larkMsgFromRaw(p.Message)
if err != nil {
return engine.AppendResult{}, err
}
- res, err := r.chat.AppendUserMessage(ctx, AppendUserMessageParams{
- ChatSessionID: p.SessionID,
+ return r.session.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: p.SessionID,
Sender: p.Sender,
- Body: p.Message.Text,
- CommandBody: lm.CommandBody,
InstallationID: p.InstallationID,
- LarkMessageID: p.Message.MessageID,
- LarkThreadID: p.Message.Source.ThreadID,
+ Body: p.Message.Text,
+ CommandText: lm.CommandBody,
+ MessageID: p.Message.MessageID,
+ ThreadID: p.Message.Source.ThreadID,
ClaimToken: p.ClaimToken,
})
- if err != nil {
- if errors.Is(err, ErrClaimLost) {
- return engine.AppendResult{}, engine.ErrClaimLost
- }
- return engine.AppendResult{}, err
- }
- out := engine.AppendResult{DedupMarked: res.DedupMarked}
- if res.IssueCommand != nil {
- out.IssueCommand = &engine.IssueCommand{
- Title: res.IssueCommand.Title,
- Description: res.IssueCommand.Description,
- }
- }
- return out, nil
}
// ---- audit ----
diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.go
new file mode 100644
index 0000000000..b8922fb948
--- /dev/null
+++ b/server/internal/integrations/lark/feishu_resolvers_test.go
@@ -0,0 +1,96 @@
+package lark
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+func binderUUID(b byte) pgtype.UUID {
+ var u pgtype.UUID
+ u.Bytes[0] = b
+ u.Valid = true
+ return u
+}
+
+// fakeChatSession records the inputs the Feishu binder maps onto the shared
+// engine.ChatSession, so the (platform-specific) mapping is unit-tested.
+type fakeChatSession struct {
+ ensureIn engine.EnsureSessionInput
+ appendIn engine.AppendInput
+}
+
+func (f *fakeChatSession) EnsureSession(_ context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error) {
+ f.ensureIn = in
+ return binderUUID(42), nil
+}
+
+func (f *fakeChatSession) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
+ f.appendIn = in
+ return engine.AppendResult{}, nil
+}
+
+func TestFeishuSessionBinder_EnsureSessionMapping(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}},
+ }); err != nil {
+ t.Fatalf("EnsureSession: %v", err)
+ }
+
+ got := f.ensureIn
+ if got.BindingKey != "oc_chat" {
+ t.Errorf("BindingKey = %q, want the chat id (Feishu: 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)
+ }
+ if got.WorkspaceID != binderUUID(2) || got.AgentID != binderUUID(3) || got.InstallationID != binderUUID(1) ||
+ got.Sender != binderUUID(7) || got.ChatType != channel.ChatTypeGroup {
+ t.Errorf("ensure mapping wrong: %+v", got)
+ }
+}
+
+func TestFeishuSessionBinder_AppendUsesUnenrichedCommandBody(t *testing.T) {
+ f := &fakeChatSession{}
+ b := &feishuSessionBinder{session: f}
+
+ // Raw carries the original lark InboundMessage; CommandBody is the user's
+ // un-enriched text used for /issue parsing (Body has quoted context inlined).
+ raw, _ := json.Marshal(InboundMessage{CommandBody: "/issue Real intent"})
+ if _, err := b.AppendMessage(context.Background(), engine.AppendParams{
+ SessionID: binderUUID(1),
+ Sender: binderUUID(7),
+ InstallationID: binderUUID(2),
+ ClaimToken: binderUUID(9),
+ Message: channel.InboundMessage{
+ MessageID: "om_1",
+ Text: "> quoted context\n/issue Real intent",
+ Source: channel.Source{ChatID: "oc", ThreadID: "th_1"},
+ Raw: raw,
+ },
+ }); err != nil {
+ t.Fatalf("AppendMessage: %v", err)
+ }
+
+ got := f.appendIn
+ if got.CommandText != "/issue Real intent" {
+ t.Errorf("CommandText must be the un-enriched CommandBody from Raw, got %q", got.CommandText)
+ }
+ if got.Body != "> quoted context\n/issue Real intent" {
+ t.Errorf("Body must be the (enriched) Message.Text, got %q", got.Body)
+ }
+ if got.MessageID != "om_1" || got.ThreadID != "th_1" || got.SessionID != binderUUID(1) ||
+ got.Sender != binderUUID(7) || got.InstallationID != binderUUID(2) || got.ClaimToken != binderUUID(9) {
+ t.Errorf("append mapping wrong: %+v", got)
+ }
+}
diff --git a/server/internal/integrations/lark/inbound_enricher_test.go b/server/internal/integrations/lark/inbound_enricher_test.go
index 0a60e47dda..fa0966791d 100644
--- a/server/internal/integrations/lark/inbound_enricher_test.go
+++ b/server/internal/integrations/lark/inbound_enricher_test.go
@@ -5,6 +5,8 @@ import (
"errors"
"strings"
"testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
)
// enricherFakeClient is a programmable APIClient for enricher tests. It
@@ -398,11 +400,11 @@ func TestEnrichPreservesCommandBodyForIssueParsing(t *testing.T) {
out := enrich(t, fake, in, InboundEnricherConfig{})
// Enriched Body now starts with the quoted block → no longer a command.
- if _, ok := parseIssueCommand(out.Body); ok {
+ if _, ok := engine.ParseIssueCommand(out.Body); ok {
t.Errorf("enriched Body should not parse as /issue (it is prefixed): %q", out.Body)
}
// CommandBody is untouched and still parses with the right title.
- cmd, ok := parseIssueCommand(out.CommandBody)
+ cmd, ok := engine.ParseIssueCommand(out.CommandBody)
if !ok || cmd.Title != "删除 issue 按钮" {
t.Errorf("CommandBody should still parse /issue: cmd=%+v ok=%v", cmd, ok)
}
diff --git a/server/internal/integrations/lark/issue_command.go b/server/internal/integrations/lark/issue_command.go
deleted file mode 100644
index 840ed60732..0000000000
--- a/server/internal/integrations/lark/issue_command.go
+++ /dev/null
@@ -1,75 +0,0 @@
-package lark
-
-import "strings"
-
-// issueCommandPrefix is the literal command token. We match exactly —
-// `/Issue` or `/ISSUE` do NOT trigger creation. The case sensitivity
-// is product-intentional: it avoids accidentally promoting messages
-// that mention "/issue" inline in a sentence.
-const issueCommandPrefix = "/issue"
-
-// parseIssueCommand extracts an /issue command from a chat-message body.
-// It returns (cmd, true) when the message qualifies and the caller
-// should dispatch to IssueService.Create; (nil, false) when the body
-// is not an issue command. The bool is redundant when cmd != nil but
-// makes call sites easier to read.
-//
-// Recognized shapes (matching MUL-2671 §2.3):
-//
-// - `/issue <title>` → Title = "<title>", Description = ""
-// - `/issue <title>\n<rest...>` → Title = "<title>", Description = "<rest>"
-// (multi-line: first line is title, the
-// remainder, joined back with newlines,
-// becomes description)
-// - `/issue` (alone, no title) → Title = "", Description = ""
-// (the caller is expected to fall back
-// to the previous user message; the
-// parser does not do that lookup
-// itself because it has no DB access)
-//
-// Only the first non-empty line is considered: a message body that
-// begins with blank lines and then `/issue ...` still qualifies. A
-// body whose first non-empty line is anything other than the literal
-// prefix is not an issue command, even if `/issue` appears later.
-func parseIssueCommand(body string) (*IssueCommand, bool) {
- lines := strings.Split(body, "\n")
-
- // Skip leading blank lines to find the first content line. A user
- // who copy-pastes from a doc and ends up with a leading newline
- // should not have their command silently ignored.
- firstIdx := -1
- for i, line := range lines {
- if strings.TrimSpace(line) != "" {
- firstIdx = i
- break
- }
- }
- if firstIdx == -1 {
- return nil, false
- }
-
- first := lines[firstIdx]
- trimmed := strings.TrimLeft(first, " \t")
- if !strings.HasPrefix(trimmed, issueCommandPrefix) {
- return nil, false
- }
-
- // What follows the prefix on the same line must be either the end
- // of the line or a whitespace character. This rejects words like
- // "/issuetracker" — `/issue` must be a token, not a prefix of one.
- rest := trimmed[len(issueCommandPrefix):]
- if rest != "" {
- r0 := rest[0]
- if r0 != ' ' && r0 != '\t' {
- return nil, false
- }
- }
-
- title := strings.TrimSpace(rest)
- description := ""
- if firstIdx+1 < len(lines) {
- description = strings.TrimRight(strings.Join(lines[firstIdx+1:], "\n"), " \t\n")
- }
-
- return &IssueCommand{Title: title, Description: description}, true
-}
diff --git a/server/internal/integrations/lark/issue_command_test.go b/server/internal/integrations/lark/issue_command_test.go
deleted file mode 100644
index 1212378b5c..0000000000
--- a/server/internal/integrations/lark/issue_command_test.go
+++ /dev/null
@@ -1,137 +0,0 @@
-package lark
-
-import "testing"
-
-func TestParseIssueCommand(t *testing.T) {
- tests := []struct {
- name string
- body string
- wantMatch bool
- wantTitle string
- wantDescrip string
- }{
- {
- name: "non command body",
- body: "hello world",
- wantMatch: false,
- },
- {
- name: "empty body",
- body: "",
- wantMatch: false,
- },
- {
- name: "issue mentioned mid-sentence does not match",
- body: "please use /issue to file a ticket",
- wantMatch: false,
- },
- {
- name: "wrong case rejected",
- body: "/Issue something",
- wantMatch: false,
- },
- {
- name: "prefix-of-token rejected",
- body: "/issuetracker my title",
- wantMatch: false,
- },
- {
- name: "title only",
- body: "/issue fix login redirect",
- wantMatch: true,
- wantTitle: "fix login redirect",
- },
- {
- name: "title and description",
- body: "/issue fix login redirect\nuser is bounced back to landing",
- wantMatch: true,
- wantTitle: "fix login redirect",
- wantDescrip: "user is bounced back to landing",
- },
- {
- name: "multi-line description preserved",
- body: "/issue title\nline one\nline two",
- wantMatch: true,
- wantTitle: "title",
- wantDescrip: "line one\nline two",
- },
- {
- name: "leading blank lines tolerated",
- body: "\n\n/issue lazy formatter",
- wantMatch: true,
- wantTitle: "lazy formatter",
- },
- {
- name: "command alone has no title",
- body: "/issue",
- wantMatch: true,
- wantTitle: "",
- },
- {
- name: "command with trailing whitespace alone has no title",
- body: "/issue ",
- wantMatch: true,
- wantTitle: "",
- },
- {
- name: "tab separator accepted",
- body: "/issue\ttabby",
- wantMatch: true,
- wantTitle: "tabby",
- },
- {
- name: "trailing blank lines trimmed from description",
- body: "/issue title\nbody\n\n\n",
- wantMatch: true,
- wantTitle: "title",
- wantDescrip: "body",
- },
- {
- name: "lines after a non-command first line are not parsed",
- body: "hello\n/issue not here",
- wantMatch: false,
- },
- }
-
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- cmd, ok := parseIssueCommand(tc.body)
- if ok != tc.wantMatch {
- t.Fatalf("match=%v want %v (cmd=%+v)", ok, tc.wantMatch, cmd)
- }
- if !tc.wantMatch {
- if cmd != nil {
- t.Fatalf("expected nil command, got %+v", cmd)
- }
- return
- }
- if cmd.Title != tc.wantTitle {
- t.Errorf("title=%q want %q", cmd.Title, tc.wantTitle)
- }
- if cmd.Description != tc.wantDescrip {
- t.Errorf("description=%q want %q", cmd.Description, tc.wantDescrip)
- }
- })
- }
-}
-
-func TestTitleFromPreviousMessage(t *testing.T) {
- tests := []struct {
- name string
- body string
- want string
- }{
- {name: "plain message", body: "fix the bug", want: "fix the bug"},
- {name: "previous was /issue command, use its title", body: "/issue prior title", want: "prior title"},
- {name: "multi-line plain takes first line", body: "first line\nsecond line", want: "first line"},
- {name: "blank lines skipped", body: "\n\nactual line", want: "actual line"},
- {name: "all whitespace returns empty", body: " \n\t\n", want: ""},
- }
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- if got := titleFromPreviousMessage(tc.body); got != tc.want {
- t.Errorf("titleFromPreviousMessage(%q) = %q, want %q", tc.body, got, tc.want)
- }
- })
- }
-}
diff --git a/server/internal/integrations/lark/tx.go b/server/internal/integrations/lark/tx.go
new file mode 100644
index 0000000000..08b10e6bac
--- /dev/null
+++ b/server/internal/integrations/lark/tx.go
@@ -0,0 +1,15 @@
+package lark
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5"
+)
+
+// TxStarter abstracts transaction creation. Re-declared in this package (rather
+// than depending on internal/service) so the integrations layer does not
+// back-reference into service — a circular dependency we want to avoid as both
+// packages grow. Satisfied by *pgxpool.Pool.
+type TxStarter interface {
+ Begin(ctx context.Context) (pgx.Tx, error)
+}
diff --git a/server/internal/integrations/slack/channel.go b/server/internal/integrations/slack/channel.go
new file mode 100644
index 0000000000..a7ee847a36
--- /dev/null
+++ b/server/internal/integrations/slack/channel.go
@@ -0,0 +1,452 @@
+package slack
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "regexp"
+ "strings"
+
+ "github.com/slack-go/slack"
+ "github.com/slack-go/slack/slackevents"
+ "github.com/slack-go/slack/socketmode"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// TypeSlack is the channel discriminator for the Slack adapter. It is defined
+// here (not in the channel core package) on purpose: registering a new platform
+// must not require editing the core, so the Type value lives with its adapter.
+const TypeSlack channel.Type = "slack"
+
+// maxMessageRunes caps a single outbound chat.postMessage body. Slack hard-caps
+// a message around 40k characters; we chunk below that with headroom.
+const maxMessageRunes = 38000
+
+// slackChannel is the Slack implementation of channel.Channel. One instance is
+// built per channel_installation by the registered Factory. It holds only what
+// Connect/Send need (the decoded credentials + an API client); the installation
+// identity is resolved per message by the Router, so it is absent here — the
+// same split the Feishu adapter uses.
+type slackChannel struct {
+ creds credentials
+ api *slack.Client
+ handler channel.InboundHandler
+ logger *slog.Logger
+ mentionRe *regexp.Regexp
+}
+
+var _ channel.Channel = (*slackChannel)(nil)
+
+func (c *slackChannel) Type() channel.Type { return TypeSlack }
+
+// Connect opens the Slack Socket Mode WebSocket and runs the receive loop,
+// blocking until ctx is cancelled or the connection drops — the contract
+// engine.Supervisor relies on to tie lease renewal to connection liveness
+// (matching feishuChannel.Connect). Each decoded Events API message is
+// normalized to a channel.InboundMessage and handed to the engine handler. The
+// envelope is ACKed immediately on receipt (Slack expires un-ACKed envelopes in
+// ~3s) so the handler's slower DB work never races the ACK.
+func (c *slackChannel) Connect(ctx context.Context) error {
+ if c.handler == nil {
+ return errors.New("slack: inbound handler not configured")
+ }
+ if c.api == nil {
+ return errors.New("slack: api client not configured")
+ }
+ sm := socketmode.New(c.api)
+
+ runErr := make(chan error, 1)
+ go func() { runErr <- sm.RunContext(ctx) }()
+
+ for {
+ select {
+ case <-ctx.Done():
+ // Graceful teardown: the Supervisor cancelled the run context.
+ return nil
+ case err := <-runErr:
+ // The managed connection loop ended. On ctx cancellation this is a
+ // graceful stop; otherwise it is a real failure the Supervisor
+ // retries under backoff.
+ if ctx.Err() != nil {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ return errors.New("slack: socket mode connection closed")
+ case evt, ok := <-sm.Events:
+ if !ok {
+ if ctx.Err() != nil {
+ return nil
+ }
+ return errors.New("slack: socket mode event stream closed")
+ }
+ if err := c.handleSocketEvent(ctx, sm, evt); err != nil {
+ // A handler error is an infrastructure failure (InboundHandler
+ // contract): surface it so the Supervisor tears the connection
+ // down and reconnects under backoff, instead of silently
+ // dropping every subsequent event. ctx cancellation is a
+ // graceful stop, not a failure.
+ if ctx.Err() != nil {
+ return nil
+ }
+ return err
+ }
+ }
+ }
+}
+
+// Disconnect is a no-op: the Socket Mode loop is torn down by ctx cancellation
+// (the Supervisor cancels the run context), mirroring feishuChannel.Disconnect.
+func (c *slackChannel) Disconnect(ctx context.Context) error { return nil }
+
+// Send delivers a minimal text reply via chat.postMessage, threading into
+// out.ThreadID when set so a decoupled reply lands back in the originating
+// thread. Long bodies are chunked under Slack's per-message cap; the returned
+// SendResult carries the timestamp of the LAST posted chunk.
+func (c *slackChannel) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ if c.api == nil {
+ return channel.SendResult{}, errors.New("slack: api client not configured")
+ }
+ threadTS := outboundThreadTS(out)
+ var lastTS string
+ // Convert the agent's standard Markdown to Slack mrkdwn before posting so
+ // bold/headers/links render instead of showing literal markup.
+ for _, chunk := range chunkMessage(formatMrkdwn(out.Text), maxMessageRunes) {
+ opts := []slack.MsgOption{
+ slack.MsgOptionText(chunk, false),
+ slack.MsgOptionDisableLinkUnfurl(),
+ }
+ if threadTS != "" {
+ opts = append(opts, slack.MsgOptionTS(threadTS))
+ }
+ _, ts, err := c.api.PostMessageContext(ctx, out.ChatID, opts...)
+ if err != nil {
+ return channel.SendResult{}, fmt.Errorf("slack: chat.postMessage: %w", err)
+ }
+ lastTS = ts
+ }
+ return channel.SendResult{MessageID: lastTS}, nil
+}
+
+// Capabilities declares what the Slack adapter supports TODAY. Declaration
+// only — the engine performs no degradation, and callers pick a rendering from
+// these bits, so declaring a capability the Send path cannot fulfil would
+// mislead them. The minimal Send delivers text into a chat or thread, so only
+// CapText | CapThreadReply are declared. Block Kit (CapRichCard), file
+// attachments (CapAttachment) and chat.update edits (CapMessageEdit) are
+// deferred until those paths are actually wired.
+func (c *slackChannel) Capabilities() channel.Capability {
+ return channel.CapText | channel.CapThreadReply
+}
+
+// ---- inbound ----
+
+func (c *slackChannel) handleSocketEvent(ctx context.Context, sm *socketmode.Client, evt socketmode.Event) error {
+ switch evt.Type {
+ case socketmode.EventTypeEventsAPI:
+ eventsAPI, ok := evt.Data.(slackevents.EventsAPIEvent)
+ if !ok {
+ return nil
+ }
+ // ACK first: Slack expires un-ACKed envelopes in ~3s, far below the
+ // handler's DB work. The ACK is independent of the handler outcome —
+ // a handler error is surfaced to the Supervisor (reconnect/backoff),
+ // not retried through the un-ACK path.
+ if evt.Request != nil {
+ if err := sm.Ack(*evt.Request); err != nil {
+ c.logger.WarnContext(ctx, "slack: ack failed", "error", err)
+ }
+ }
+ return c.dispatchEventsAPI(ctx, eventsAPI)
+ case socketmode.EventTypeConnecting, socketmode.EventTypeConnected, socketmode.EventTypeHello:
+ c.logger.DebugContext(ctx, "slack: socket mode", "event", evt.Type)
+ case socketmode.EventTypeIncomingError, socketmode.EventTypeErrorBadMessage:
+ c.logger.WarnContext(ctx, "slack: socket mode error", "event", evt.Type)
+ default:
+ // Interactive / slash-command / other events are out of scope for the
+ // minimal adapter; ACK so Slack does not retry, then ignore.
+ if evt.Request != nil {
+ _ = sm.Ack(*evt.Request)
+ }
+ }
+ return nil
+}
+
+func (c *slackChannel) dispatchEventsAPI(ctx context.Context, e slackevents.EventsAPIEvent) error {
+ var (
+ msg channel.InboundMessage
+ ok bool
+ )
+ switch inner := e.InnerEvent.Data.(type) {
+ case *slackevents.AppMentionEvent:
+ msg, ok = c.inboundFromAppMention(e, inner)
+ case *slackevents.MessageEvent:
+ msg, ok = c.inboundFromMessage(e, inner)
+ default:
+ return nil
+ }
+ if !ok {
+ return nil
+ }
+ // A non-nil handler error is an infrastructure failure; propagate it so the
+ // Supervisor reconnects (InboundHandler contract). A legitimate product
+ // drop (dedup hit / unbound sender / group filter) returns nil — not an
+ // error — so it does not tear the connection down.
+ return c.handler(ctx, msg)
+}
+
+// inboundFromMessage normalizes a Slack message event. It returns ok=false for
+// events that must not reach the core: the bot's own messages and other bots'
+// messages (loop guard), and edits/deletes/joins and similar subtyped system
+// messages (only brand-new user messages are ingested).
+//
+// Group addressing policy (v1, deliberate): a group message is addressed to the
+// bot only when it carries an explicit <@bot> mention. Mention-free follow-ups
+// inside a thread the bot is already engaged in are NOT auto-addressed here:
+// "reply to a bot message" is session state, so it belongs in the session-aware
+// shared service / resolver layer (which can detect an existing bound session
+// for the thread and survive reconnects) rather than in per-connection adapter
+// memory. Until that lands, channel/thread continuation requires re-mentioning
+// the bot. P2P (DM) ingests every message, unchanged.
+func (c *slackChannel) inboundFromMessage(e slackevents.EventsAPIEvent, m *slackevents.MessageEvent) (channel.InboundMessage, bool) {
+ if m.BotID != "" || m.SubType == "bot_message" {
+ return channel.InboundMessage{}, false
+ }
+ if m.User == "" || (c.creds.BotUserID != "" && m.User == c.creds.BotUserID) {
+ return channel.InboundMessage{}, false
+ }
+ if !isIngestableSubtype(m.SubType) {
+ return channel.InboundMessage{}, false
+ }
+
+ chatType := slackChatType(m.Channel, m.ChannelType)
+ addressed := chatType == channel.ChatTypeP2P || c.mentionsBot(m.Text)
+ return c.buildInbound(e, buildInboundParams{
+ eventType: "message",
+ subType: m.SubType,
+ channelID: m.Channel,
+ userID: m.User,
+ text: m.Text,
+ ts: m.TimeStamp,
+ threadTS: m.ThreadTimeStamp,
+ chatType: chatType,
+ addressed: addressed,
+ }), true
+}
+
+// inboundFromAppMention normalizes an app_mention event. An app_mention is, by
+// definition, addressed to the bot and occurs in a channel (group). The same
+// channel @mention also arrives as a message event with the identical ts, so
+// the engine's (installation, message_id=ts) dedup collapses the pair — no
+// special-casing needed here.
+func (c *slackChannel) inboundFromAppMention(e slackevents.EventsAPIEvent, m *slackevents.AppMentionEvent) (channel.InboundMessage, bool) {
+ if m.BotID != "" || m.User == "" || (c.creds.BotUserID != "" && m.User == c.creds.BotUserID) {
+ return channel.InboundMessage{}, false
+ }
+ return c.buildInbound(e, buildInboundParams{
+ eventType: "app_mention",
+ channelID: m.Channel,
+ userID: m.User,
+ text: m.Text,
+ ts: m.TimeStamp,
+ threadTS: m.ThreadTimeStamp,
+ chatType: channel.ChatTypeGroup,
+ addressed: true,
+ }), true
+}
+
+type buildInboundParams struct {
+ eventType string
+ subType string
+ channelID string
+ userID string
+ text string
+ ts string
+ threadTS string
+ chatType channel.ChatType
+ addressed bool
+}
+
+func (c *slackChannel) buildInbound(e slackevents.EventsAPIEvent, p buildInboundParams) channel.InboundMessage {
+ teamID := e.TeamID
+ if teamID == "" {
+ teamID = c.creds.TeamID
+ }
+ raw, _ := json.Marshal(slackRawEvent{
+ TeamID: teamID,
+ APIAppID: e.APIAppID,
+ EventType: p.eventType,
+ SubType: p.subType,
+ ChannelType: string(p.chatType),
+ })
+ var reply *channel.ReplyCtx
+ if p.threadTS != "" && p.threadTS != p.ts {
+ reply = &channel.ReplyCtx{MessageID: p.threadTS, RootID: p.threadTS}
+ }
+ return channel.InboundMessage{
+ EventID: p.ts,
+ MessageID: p.ts,
+ Type: channel.MsgTypeText,
+ Text: c.cleanText(p.text),
+ ReplyTo: reply,
+ AddressedToBot: p.addressed,
+ Source: channel.Source{
+ ChannelType: TypeSlack,
+ ChatID: p.channelID,
+ ChatType: p.chatType,
+ SenderID: p.userID,
+ ThreadID: p.threadTS,
+ },
+ Raw: raw,
+ }
+}
+
+// slackRawEvent carries the Slack-specific fields the cross-platform envelope
+// does not — read back only inside the Slack resolvers (team_id routes the
+// installation; the core never reads Raw).
+type slackRawEvent struct {
+ TeamID string `json:"team_id"`
+ APIAppID string `json:"api_app_id,omitempty"`
+ EventType string `json:"event_type"`
+ SubType string `json:"subtype,omitempty"`
+ ChannelType string `json:"channel_type,omitempty"`
+}
+
+// cleanText strips a leading/embedded bot mention token and trims surrounding
+// whitespace so the core sees the user's actual prompt, not "<@U123> hi".
+func (c *slackChannel) cleanText(text string) string {
+ if c.mentionRe != nil {
+ text = c.mentionRe.ReplaceAllString(text, "")
+ }
+ return strings.TrimSpace(text)
+}
+
+// mentionsBot reports whether text contains an @-mention of this bot. Slack
+// renders a mention as <@U123> or <@U123|name>.
+func (c *slackChannel) mentionsBot(text string) bool {
+ return c.mentionRe != nil && c.mentionRe.MatchString(text)
+}
+
+// ---- helpers ----
+
+// slackChatType maps a Slack channel id / channel_type to the normalized
+// ChatType. Only a 1:1 direct message ("im", or a "D…" channel id) is p2p;
+// everything else — public/private channels AND multi-party DMs ("mpim", which
+// are multi-person conversations) — is a group. A group routes through the
+// engine's "must address the bot" filter, so plain chatter in a multi-party DM
+// is not mistaken for a prompt to the bot.
+func slackChatType(channelID, channelType string) channel.ChatType {
+ switch channelType {
+ case "im":
+ return channel.ChatTypeP2P
+ case "mpim", "channel", "group", "private_channel":
+ return channel.ChatTypeGroup
+ }
+ if strings.HasPrefix(channelID, "D") {
+ return channel.ChatTypeP2P
+ }
+ return channel.ChatTypeGroup
+}
+
+// isIngestableSubtype reports whether a message subtype is a brand-new user
+// message the core should ingest. Empty subtype is the normal case;
+// thread_broadcast and file_share are real user messages; everything else
+// (message_changed, message_deleted, channel_join, …) is a system/edit event.
+func isIngestableSubtype(subType string) bool {
+ switch subType {
+ case "", "thread_broadcast", "file_share":
+ return true
+ default:
+ return false
+ }
+}
+
+// outboundThreadTS picks the Slack thread_ts for an outbound reply: an explicit
+// quote target wins, else the thread the inbound message belonged to.
+func outboundThreadTS(out channel.OutboundMessage) string {
+ if out.ReplyTo != "" {
+ return out.ReplyTo
+ }
+ return out.ThreadID
+}
+
+// chunkMessage splits text into <=maxRunes-rune pieces on rune boundaries so a
+// long agent reply does not exceed Slack's per-message cap. An empty body
+// yields a single empty chunk (Slack rejects truly empty text, but the caller
+// guards against that upstream).
+func chunkMessage(text string, maxRunes int) []string {
+ if maxRunes <= 0 || len([]rune(text)) <= maxRunes {
+ return []string{text}
+ }
+ runes := []rune(text)
+ var chunks []string
+ for len(runes) > 0 {
+ n := maxRunes
+ if n > len(runes) {
+ n = len(runes)
+ }
+ chunks = append(chunks, string(runes[:n]))
+ runes = runes[n:]
+ }
+ return chunks
+}
+
+// ---- registration ----
+
+// SlackChannelDeps bundles the shared dependencies the Slack Factory closes
+// over. The inbound handler is supplied per-build by the engine via
+// channel.Config.Handler, mirroring FeishuChannelDeps.
+type SlackChannelDeps struct {
+ // Decrypt turns the stored bot/app token ciphertext into plaintext. A nil
+ // Decrypter treats stored tokens as plaintext (tests / un-encrypted dev).
+ Decrypt Decrypter
+ Logger *slog.Logger
+}
+
+// RegisterSlack registers the Slack Factory on reg under TypeSlack so the
+// engine.Supervisor can build a slackChannel per installation. "Adding a
+// channel" is this call plus the adapter — no engine edit.
+func RegisterSlack(reg *channel.Registry, deps SlackChannelDeps) {
+ reg.Register(TypeSlack, newSlackFactory(deps))
+}
+
+func newSlackFactory(deps SlackChannelDeps) channel.Factory {
+ logger := deps.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return func(cfg channel.Config) (channel.Channel, error) {
+ creds, err := decodeCredentials(cfg.Raw, deps.Decrypt)
+ if err != nil {
+ return nil, err
+ }
+ if creds.BotToken == "" || creds.AppToken == "" {
+ return nil, errors.New("slack: installation config missing bot or app token")
+ }
+ return newSlackChannel(creds, slack.New(creds.BotToken, slack.OptionAppLevelToken(creds.AppToken)), cfg.Handler, logger), nil
+ }
+}
+
+// newSlackChannel builds a slackChannel from decoded credentials and a
+// configured API client. Kept separate from the Factory so tests can inject a
+// client pointed at an httptest server.
+func newSlackChannel(creds credentials, api *slack.Client, handler channel.InboundHandler, logger *slog.Logger) *slackChannel {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ var mentionRe *regexp.Regexp
+ if creds.BotUserID != "" {
+ mentionRe = regexp.MustCompile(`<@` + regexp.QuoteMeta(creds.BotUserID) + `(\|[^>]*)?>`)
+ }
+ return &slackChannel{
+ creds: creds,
+ api: api,
+ handler: handler,
+ logger: logger,
+ mentionRe: mentionRe,
+ }
+}
diff --git a/server/internal/integrations/slack/channel_test.go b/server/internal/integrations/slack/channel_test.go
new file mode 100644
index 0000000000..1ede0a7293
--- /dev/null
+++ b/server/internal/integrations/slack/channel_test.go
@@ -0,0 +1,370 @@
+package slack
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+
+ "github.com/slack-go/slack"
+ "github.com/slack-go/slack/slackevents"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+func testChannel(botUserID string) *slackChannel {
+ return newSlackChannel(credentials{TeamID: "T1", BotUserID: botUserID}, nil, nil, nil)
+}
+
+func eventsAPI(inner any) slackevents.EventsAPIEvent {
+ return slackevents.EventsAPIEvent{
+ TeamID: "T1",
+ APIAppID: "A1",
+ InnerEvent: slackevents.EventsAPIInnerEvent{
+ Data: inner,
+ },
+ }
+}
+
+func TestInboundFromMessage_DM(t *testing.T) {
+ c := testChannel("UBOT")
+ e := eventsAPI(nil)
+ msg, ok := c.inboundFromMessage(e, &slackevents.MessageEvent{
+ User: "UALICE",
+ Text: "hello bot",
+ Channel: "D123",
+ ChannelType: "im",
+ TimeStamp: "1700000000.000100",
+ })
+ if !ok {
+ t.Fatal("expected DM message to be ingestable")
+ }
+ if msg.Source.ChatType != channel.ChatTypeP2P {
+ t.Errorf("ChatType = %q, want p2p", msg.Source.ChatType)
+ }
+ if !msg.AddressedToBot {
+ t.Error("DM should always be addressed to bot")
+ }
+ if msg.Source.ChannelType != TypeSlack {
+ t.Errorf("ChannelType = %q, want slack", msg.Source.ChannelType)
+ }
+ if msg.MessageID != "1700000000.000100" || msg.EventID != msg.MessageID {
+ t.Errorf("MessageID/EventID = %q/%q, want the ts", msg.MessageID, msg.EventID)
+ }
+ if msg.Source.SenderID != "UALICE" || msg.Source.ChatID != "D123" {
+ t.Errorf("sender/chat = %q/%q", msg.Source.SenderID, msg.Source.ChatID)
+ }
+ if msg.Text != "hello bot" {
+ t.Errorf("Text = %q", msg.Text)
+ }
+ // team_id must be in Raw so the installation resolver can route.
+ var raw slackRawEvent
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil {
+ t.Fatalf("decode raw: %v", err)
+ }
+ if raw.TeamID != "T1" || raw.EventType != "message" {
+ t.Errorf("raw = %+v", raw)
+ }
+}
+
+func TestInboundFromMessage_ChannelMention(t *testing.T) {
+ c := testChannel("UBOT")
+ msg, ok := c.inboundFromMessage(eventsAPI(nil), &slackevents.MessageEvent{
+ User: "UALICE",
+ Text: "<@UBOT> create an issue",
+ Channel: "C123",
+ ChannelType: "channel",
+ TimeStamp: "1700000000.000200",
+ })
+ if !ok {
+ t.Fatal("expected channel message to be ingestable")
+ }
+ if msg.Source.ChatType != channel.ChatTypeGroup {
+ t.Errorf("ChatType = %q, want group", msg.Source.ChatType)
+ }
+ if !msg.AddressedToBot {
+ t.Error("channel message mentioning the bot should be addressed to bot")
+ }
+ if msg.Text != "create an issue" {
+ t.Errorf("Text = %q, want mention stripped", msg.Text)
+ }
+}
+
+func TestInboundFromMessage_ChannelNoMention(t *testing.T) {
+ c := testChannel("UBOT")
+ msg, ok := c.inboundFromMessage(eventsAPI(nil), &slackevents.MessageEvent{
+ User: "UALICE",
+ Text: "just chatting with the team",
+ Channel: "C123",
+ ChannelType: "channel",
+ TimeStamp: "1700000000.000300",
+ })
+ if !ok {
+ t.Fatal("a non-mention channel message is still ingested; the engine group filter drops it")
+ }
+ if msg.AddressedToBot {
+ t.Error("channel message without a mention must not be addressed to bot")
+ }
+}
+
+func TestInboundFromMessage_ThreadReply(t *testing.T) {
+ c := testChannel("UBOT")
+ msg, ok := c.inboundFromMessage(eventsAPI(nil), &slackevents.MessageEvent{
+ User: "UALICE",
+ Text: "<@UBOT> follow up",
+ Channel: "C123",
+ ChannelType: "channel",
+ TimeStamp: "1700000000.000500",
+ ThreadTimeStamp: "1700000000.000400",
+ })
+ if !ok {
+ t.Fatal("thread reply should be ingestable")
+ }
+ if msg.Source.ThreadID != "1700000000.000400" {
+ t.Errorf("ThreadID = %q", msg.Source.ThreadID)
+ }
+ if msg.ReplyTo == nil || msg.ReplyTo.MessageID != "1700000000.000400" {
+ t.Errorf("ReplyTo = %+v, want the thread root", msg.ReplyTo)
+ }
+}
+
+func TestInboundFromMessage_SkipsBotAndOwnAndEdits(t *testing.T) {
+ c := testChannel("UBOT")
+ cases := []struct {
+ name string
+ m *slackevents.MessageEvent
+ }{
+ {"own message", &slackevents.MessageEvent{User: "UBOT", Text: "hi", Channel: "D1", ChannelType: "im", TimeStamp: "1.1"}},
+ {"other bot", &slackevents.MessageEvent{User: "UX", BotID: "B1", Text: "hi", Channel: "C1", TimeStamp: "1.2"}},
+ {"bot_message subtype", &slackevents.MessageEvent{SubType: "bot_message", Text: "hi", Channel: "C1", TimeStamp: "1.3"}},
+ {"edit", &slackevents.MessageEvent{User: "UALICE", SubType: "message_changed", Text: "hi", Channel: "C1", TimeStamp: "1.4"}},
+ {"delete", &slackevents.MessageEvent{User: "UALICE", SubType: "message_deleted", Channel: "C1", TimeStamp: "1.5"}},
+ {"empty user", &slackevents.MessageEvent{Text: "hi", Channel: "C1", TimeStamp: "1.6"}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if _, ok := c.inboundFromMessage(eventsAPI(nil), tc.m); ok {
+ t.Errorf("%s should not be ingested", tc.name)
+ }
+ })
+ }
+}
+
+func TestInboundFromAppMention(t *testing.T) {
+ c := testChannel("UBOT")
+ msg, ok := c.inboundFromAppMention(eventsAPI(nil), &slackevents.AppMentionEvent{
+ User: "UALICE",
+ Text: "<@UBOT> hi",
+ Channel: "C123",
+ TimeStamp: "1700000000.000700",
+ })
+ if !ok {
+ t.Fatal("app_mention should be ingestable")
+ }
+ if msg.Source.ChatType != channel.ChatTypeGroup || !msg.AddressedToBot {
+ t.Errorf("app_mention must be a group message addressed to bot: %+v", msg.Source)
+ }
+ if msg.Text != "hi" {
+ t.Errorf("Text = %q, want mention stripped", msg.Text)
+ }
+ // The bot's own app_mention echo (BotID set) must be skipped.
+ if _, ok := c.inboundFromAppMention(eventsAPI(nil), &slackevents.AppMentionEvent{User: "UBOT", Channel: "C1", TimeStamp: "1.9"}); ok {
+ t.Error("bot's own mention should be skipped")
+ }
+}
+
+func TestCapabilitiesAndType(t *testing.T) {
+ c := testChannel("UBOT")
+ if c.Type() != TypeSlack {
+ t.Errorf("Type = %q", c.Type())
+ }
+ caps := c.Capabilities()
+ if !caps.Has(channel.CapText) || !caps.Has(channel.CapThreadReply) {
+ t.Errorf("capabilities = %s, want text + thread_reply", caps)
+ }
+ // Capabilities the Send path cannot fulfil yet must NOT be declared.
+ for _, cap := range []channel.Capability{channel.CapRichCard, channel.CapAttachment, channel.CapMessageEdit} {
+ if caps.Has(cap) {
+ t.Errorf("capability %s must not be declared until implemented", cap)
+ }
+ }
+}
+
+func TestSlackChatType(t *testing.T) {
+ cases := []struct {
+ channelID, channelType string
+ want channel.ChatType
+ }{
+ {"D123", "im", channel.ChatTypeP2P},
+ {"G123", "mpim", channel.ChatTypeGroup}, // multi-party DM is a group
+ {"C123", "channel", channel.ChatTypeGroup},
+ {"C123", "private_channel", channel.ChatTypeGroup},
+ {"D999", "", channel.ChatTypeP2P}, // fallback by id prefix
+ {"C999", "", channel.ChatTypeGroup},
+ }
+ for _, tc := range cases {
+ if got := slackChatType(tc.channelID, tc.channelType); got != tc.want {
+ t.Errorf("slackChatType(%q,%q) = %q, want %q", tc.channelID, tc.channelType, got, tc.want)
+ }
+ }
+}
+
+func TestMpimRequiresMention(t *testing.T) {
+ c := testChannel("UBOT")
+ // A multi-party DM is a group: plain chatter must NOT be addressed to bot.
+ msg, ok := c.inboundFromMessage(eventsAPI(nil), &slackevents.MessageEvent{
+ User: "UALICE", Text: "team lunch?", Channel: "G123", ChannelType: "mpim", TimeStamp: "1.1",
+ })
+ if !ok {
+ t.Fatal("mpim message should still be ingested (engine group filter decides)")
+ }
+ if msg.Source.ChatType != channel.ChatTypeGroup {
+ t.Errorf("mpim ChatType = %q, want group", msg.Source.ChatType)
+ }
+ if msg.AddressedToBot {
+ t.Error("plain mpim chatter must not be addressed to bot")
+ }
+}
+
+func TestDispatchEventsAPI_PropagatesHandlerError(t *testing.T) {
+ wantErr := errors.New("db down")
+ calls := 0
+ c := newSlackChannel(credentials{TeamID: "T1", BotUserID: "UBOT"}, nil, func(_ context.Context, _ channel.InboundMessage) error {
+ calls++
+ return wantErr
+ }, nil)
+
+ e := eventsAPI(&slackevents.MessageEvent{User: "UALICE", Text: "hi", Channel: "D1", ChannelType: "im", TimeStamp: "1.1"})
+ if err := c.dispatchEventsAPI(context.Background(), e); !errors.Is(err, wantErr) {
+ t.Errorf("dispatchEventsAPI error = %v, want %v (infra error must propagate to Connect→Supervisor)", err, wantErr)
+ }
+ if calls != 1 {
+ t.Errorf("handler called %d times, want 1", calls)
+ }
+
+ // A non-ingestable event (the bot's own message) must not reach the handler
+ // and must not error.
+ calls = 0
+ skip := eventsAPI(&slackevents.MessageEvent{User: "UBOT", Text: "echo", Channel: "D1", ChannelType: "im", TimeStamp: "1.2"})
+ if err := c.dispatchEventsAPI(context.Background(), skip); err != nil {
+ t.Errorf("skipped event should not error: %v", err)
+ }
+ if calls != 0 {
+ t.Errorf("handler called %d times for skipped event, want 0", calls)
+ }
+}
+
+func TestDecodeCredentials(t *testing.T) {
+ // app_id holds the team_id routing key; tokens stored as base64 plaintext
+ // here (nil Decrypter = identity).
+ raw := json.RawMessage(`{
+ "app_id": "T1",
+ "bot_user_id": "UBOT",
+ "bot_token_encrypted": "eG94Yi1ib3Q=",
+ "app_token_encrypted": "eGFwcC1hcHA="
+ }`)
+ creds, err := decodeCredentials(raw, nil)
+ if err != nil {
+ t.Fatalf("decodeCredentials: %v", err)
+ }
+ if creds.TeamID != "T1" || creds.BotUserID != "UBOT" {
+ t.Errorf("creds = %+v", creds)
+ }
+ if creds.BotToken != "xoxb-bot" || creds.AppToken != "xapp-app" {
+ t.Errorf("tokens = %q / %q", creds.BotToken, creds.AppToken)
+ }
+ if _, err := decodeCredentials(nil, nil); err == nil {
+ t.Error("empty config should error")
+ }
+}
+
+func TestChunkMessage(t *testing.T) {
+ if got := chunkMessage("short", 100); len(got) != 1 || got[0] != "short" {
+ t.Errorf("short message should be one chunk: %v", got)
+ }
+ long := make([]rune, 250)
+ for i := range long {
+ long[i] = 'a'
+ }
+ chunks := chunkMessage(string(long), 100)
+ if len(chunks) != 3 {
+ t.Fatalf("250 runes / 100 = 3 chunks, got %d", len(chunks))
+ }
+ if len([]rune(chunks[0])) != 100 || len([]rune(chunks[2])) != 50 {
+ t.Errorf("chunk sizes wrong: %d / %d", len([]rune(chunks[0])), len([]rune(chunks[2])))
+ }
+}
+
+func TestSend(t *testing.T) {
+ var gotForm url.Values
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _ = r.ParseForm()
+ gotForm = r.PostForm
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"channel":"C123","ts":"1700000000.111111"}`))
+ }))
+ defer srv.Close()
+
+ api := slack.New("xoxb-test", slack.OptionAPIURL(srv.URL+"/"))
+ c := newSlackChannel(credentials{TeamID: "T1"}, api, nil, nil)
+
+ res, err := c.Send(context.Background(), channel.OutboundMessage{
+ ChatID: "C123",
+ Text: "reply body",
+ ThreadID: "1700000000.000400",
+ })
+ if err != nil {
+ t.Fatalf("Send: %v", err)
+ }
+ if res.MessageID != "1700000000.111111" {
+ t.Errorf("MessageID = %q", res.MessageID)
+ }
+ if gotForm.Get("channel") != "C123" || gotForm.Get("text") != "reply body" {
+ t.Errorf("posted channel/text = %q / %q", gotForm.Get("channel"), gotForm.Get("text"))
+ }
+ if gotForm.Get("thread_ts") != "1700000000.000400" {
+ t.Errorf("thread_ts = %q, want the inbound thread", gotForm.Get("thread_ts"))
+ }
+}
+
+// TestSend_AppliesMrkdwn guards the wiring: Send must run the agent's Markdown
+// through formatMrkdwn before posting, so Slack renders it instead of showing
+// literal markup. (The converter itself is covered in mrkdwn_test.go.)
+func TestSend_AppliesMrkdwn(t *testing.T) {
+ var gotText string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _ = r.ParseForm()
+ gotText = r.PostForm.Get("text")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"channel":"C1","ts":"1.1"}`))
+ }))
+ defer srv.Close()
+
+ api := slack.New("xoxb-test", slack.OptionAPIURL(srv.URL+"/"))
+ c := newSlackChannel(credentials{TeamID: "T1"}, api, nil, nil)
+
+ if _, err := c.Send(context.Background(), channel.OutboundMessage{
+ ChatID: "C1",
+ Text: "**bold** see [docs](http://x.com)",
+ }); err != nil {
+ t.Fatalf("Send: %v", err)
+ }
+ if gotText != "*bold* see <http://x.com|docs>" {
+ t.Errorf("Send must convert Markdown to mrkdwn before posting, got %q", gotText)
+ }
+}
+
+func TestOutboundThreadTS(t *testing.T) {
+ if got := outboundThreadTS(channel.OutboundMessage{ReplyTo: "111.1", ThreadID: "222.2"}); got != "111.1" {
+ t.Errorf("explicit ReplyTo should win: %q", got)
+ }
+ if got := outboundThreadTS(channel.OutboundMessage{ThreadID: "222.2"}); got != "222.2" {
+ t.Errorf("thread fallback: %q", got)
+ }
+ if got := outboundThreadTS(channel.OutboundMessage{}); got != "" {
+ t.Errorf("top-level send has no thread: %q", got)
+ }
+}
diff --git a/server/internal/integrations/slack/config.go b/server/internal/integrations/slack/config.go
new file mode 100644
index 0000000000..f8a78bf9b3
--- /dev/null
+++ b/server/internal/integrations/slack/config.go
@@ -0,0 +1,125 @@
+// Package slack is the Slack implementation of channel.Channel — the second
+// adapter driven by the channel-agnostic engine (MUL-3516), proving the
+// MUL-3506 thesis that adding an IM is "implement Channel + register" with no
+// engine, core, or channel_* schema change. It mirrors the Feishu reference
+// adapter (server/internal/integrations/lark/feishu_channel.go): Connect runs
+// the platform receive loop (here Slack Socket Mode, an outbound WebSocket
+// long-conn that needs no public inbound URL) and hands every decoded event to
+// the engine's shared inbound handler as a normalized channel.InboundMessage;
+// Send posts a text reply via chat.postMessage. The design references the
+// proven Slack adapter in Nous Research's Hermes Agent.
+package slack
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+)
+
+// installConfig is the JSON shape stored in channel_installation.config for a
+// Slack installation. The cross-platform columns stay flat; everything
+// Slack-specific lives in this opaque blob (the documented config boundary).
+//
+// app_id holds the Slack team_id — the per-installation routing key — so the
+// generic GetChannelInstallationByAppID query (which reads config->>'app_id')
+// and the (channel_type, config->>'app_id') unique index route Slack inbound
+// events with NO new query and NO schema change. team_id is also kept as its
+// own field for readability; the two carry the same value.
+//
+// Tokens are stored as base64-encoded secretbox ciphertext (never plaintext),
+// mirroring Feishu's app_secret_encrypted. The bot token (xoxb-…) authorizes
+// Web API calls (chat.postMessage); the app-level token (xapp-…) authorizes the
+// Socket Mode connection.
+type installConfig struct {
+ AppID string `json:"app_id"`
+ TeamID string `json:"team_id,omitempty"`
+ BotUserID string `json:"bot_user_id,omitempty"`
+ BotTokenEncrypted string `json:"bot_token_encrypted"`
+ AppTokenEncrypted string `json:"app_token_encrypted"`
+}
+
+// credentials is the decoded, decrypted form the adapter runs on. The
+// installation IDENTITY (workspace / agent / installer) is deliberately absent:
+// it is resolved per message by the Router's InstallationResolver, exactly as
+// the Feishu adapter does.
+type credentials struct {
+ TeamID string
+ BotUserID string
+ BotToken string
+ AppToken string
+}
+
+// Decrypter turns stored ciphertext into plaintext. The wiring injects a
+// secretbox-backed implementation; tests inject an identity decrypter (or nil,
+// which treats the stored bytes as plaintext).
+type Decrypter func(ciphertext []byte) (plaintext []byte, err error)
+
+// decodeCredentials parses the per-installation config blob and decrypts the
+// stored tokens. It is the single place the Slack config JSON is interpreted.
+func decodeCredentials(raw json.RawMessage, decrypt Decrypter) (credentials, error) {
+ if len(raw) == 0 {
+ return credentials{}, errors.New("slack: empty installation config")
+ }
+ var cfg installConfig
+ if err := json.Unmarshal(raw, &cfg); err != nil {
+ return credentials{}, fmt.Errorf("decode slack installation config: %w", err)
+ }
+ botToken, err := decryptToken(cfg.BotTokenEncrypted, decrypt)
+ if err != nil {
+ return credentials{}, fmt.Errorf("decrypt bot token: %w", err)
+ }
+ appToken, err := decryptToken(cfg.AppTokenEncrypted, decrypt)
+ if err != nil {
+ return credentials{}, fmt.Errorf("decrypt app token: %w", err)
+ }
+ teamID := cfg.TeamID
+ if teamID == "" {
+ teamID = cfg.AppID
+ }
+ return credentials{
+ TeamID: teamID,
+ BotUserID: cfg.BotUserID,
+ BotToken: botToken,
+ AppToken: appToken,
+ }, nil
+}
+
+// decryptToken base64-decodes the stored ciphertext (tolerating the MIME
+// newline wrapping PostgreSQL's encode(...,'base64') emits) and runs it through
+// the injected Decrypter. An empty stored value decodes to an empty token; a
+// nil Decrypter treats the decoded bytes as plaintext (test convenience).
+func decryptToken(enc string, decrypt Decrypter) (string, error) {
+ if enc == "" {
+ return "", nil
+ }
+ ciphertext, err := base64.StdEncoding.DecodeString(stripWhitespace(enc))
+ if err != nil {
+ return "", fmt.Errorf("base64 decode: %w", err)
+ }
+ if decrypt == nil {
+ return string(ciphertext), nil
+ }
+ plaintext, err := decrypt(ciphertext)
+ if err != nil {
+ return "", err
+ }
+ return string(plaintext), nil
+}
+
+// stripWhitespace removes ASCII whitespace so a MIME-wrapped base64 string
+// (newlines every 64 chars) and an unwrapped one decode identically.
+func stripWhitespace(s string) string {
+ var b strings.Builder
+ b.Grow(len(s))
+ for _, r := range s {
+ switch r {
+ case ' ', '\t', '\n', '\r':
+ continue
+ default:
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
diff --git a/server/internal/integrations/slack/mrkdwn.go b/server/internal/integrations/slack/mrkdwn.go
new file mode 100644
index 0000000000..cc7c648434
--- /dev/null
+++ b/server/internal/integrations/slack/mrkdwn.go
@@ -0,0 +1,134 @@
+// The formatMrkdwn function below is a Go port of the Markdown-to-mrkdwn
+// converter (format_message) from Nous Research's Hermes Agent, used under the
+// MIT License. Source:
+// https://github.com/NousResearch/hermes-agent/blob/main/plugins/platforms/slack/adapter.py
+//
+// Copyright (c) 2025 Nous Research
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+
+package slack
+
+import (
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+// Slack renders its own "mrkdwn" dialect, not standard Markdown: bold is *one*
+// star (not two), italic is _underscore_, links are <url|label>, headers and
+// ~~strike~~ are not supported. The agent emits standard Markdown, so an
+// unconverted reply shows literal `**`, `##`, and `[text](url)` in Slack. This
+// converter is a faithful Go port of Hermes Agent's slack `format_message`
+// (MIT; see the license notice at the top of this file): protected regions
+// (code, converted links, existing Slack
+// entities) are stashed behind NUL-delimited placeholders so later passes never
+// mangle them, then restored last in reverse order so nested placeholders
+// resolve.
+var (
+ reFenced = regexp.MustCompile("(?s)(```(?:[^\\n]*\\n)?.*?```)")
+ reInlineCode = regexp.MustCompile("(`[^`]+`)")
+ reMdLink = regexp.MustCompile(`(!?)\[([^\]]+)\]\(([^()]*(?:\([^()]*\)[^()]*)*)\)`)
+ reSlackEntity = regexp.MustCompile(`(<(?:[@#!]|(?:https?|mailto|tel):)[^>\n]+>)`)
+ reBlockquote = regexp.MustCompile(`(?m)^(>+\s)`)
+ reHeader = regexp.MustCompile(`(?m)^#{1,6}\s+(.+)$`)
+ reInnerBold = regexp.MustCompile(`\*\*(.+?)\*\*`)
+ reBoldItalic = regexp.MustCompile(`\*\*\*(.+?)\*\*\*`)
+ reBold = regexp.MustCompile(`\*\*(.+?)\*\*`)
+ reItalic = regexp.MustCompile(`\*(\S(?:[^*\n]*?\S)?)\*`)
+ reStrike = regexp.MustCompile(`~~(.+?)~~`)
+)
+
+// formatMrkdwn converts standard Markdown to Slack mrkdwn.
+func formatMrkdwn(content string) string {
+ if content == "" {
+ return content
+ }
+ p := &mrkdwnPlaceholders{values: map[string]string{}}
+ text := content
+
+ // 1) Protect fenced code blocks, then 2) inline code.
+ text = reFenced.ReplaceAllStringFunc(text, p.stash)
+ text = reInlineCode.ReplaceAllStringFunc(text, p.stash)
+
+ // 3) Markdown links [text](url) -> <url|text>; image links (![..]) are left
+ // untouched (Slack does not render inline images from markdown).
+ text = reMdLink.ReplaceAllStringFunc(text, func(m string) string {
+ sub := reMdLink.FindStringSubmatch(m)
+ if sub[1] == "!" {
+ return m
+ }
+ url := strings.TrimSpace(sub[3])
+ if strings.HasPrefix(url, "<") && strings.HasSuffix(url, ">") {
+ url = strings.TrimSpace(url[1 : len(url)-1])
+ }
+ return p.stash("<" + url + "|" + sub[2] + ">")
+ })
+
+ // 4) Protect existing Slack entities / manual links, 5) blockquote markers.
+ text = reSlackEntity.ReplaceAllStringFunc(text, p.stash)
+ text = reBlockquote.ReplaceAllStringFunc(text, p.stash)
+
+ // 6) Escape Slack control chars (unescape first so input isn't double-escaped).
+ text = strings.NewReplacer("&amp;", "&", "&lt;", "<", "&gt;", ">").Replace(text)
+ text = strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;").Replace(text)
+
+ // 7) Headers (## Title) -> *Title* (strip redundant bold inside).
+ text = reHeader.ReplaceAllStringFunc(text, func(m string) string {
+ inner := strings.TrimSpace(reHeader.FindStringSubmatch(m)[1])
+ inner = reInnerBold.ReplaceAllString(inner, "$1")
+ return p.stash("*" + inner + "*")
+ })
+
+ // 8) ***bold italic*** -> *_text_*, 9) **bold** -> *bold*,
+ // 10) *italic* -> _italic_, 11) ~~strike~~ -> ~strike~.
+ text = reBoldItalic.ReplaceAllStringFunc(text, func(m string) string {
+ return p.stash("*_" + reBoldItalic.FindStringSubmatch(m)[1] + "_*")
+ })
+ text = reBold.ReplaceAllStringFunc(text, func(m string) string {
+ return p.stash("*" + reBold.FindStringSubmatch(m)[1] + "*")
+ })
+ text = reItalic.ReplaceAllStringFunc(text, func(m string) string {
+ return p.stash("_" + reItalic.FindStringSubmatch(m)[1] + "_")
+ })
+ text = reStrike.ReplaceAllStringFunc(text, func(m string) string {
+ return p.stash("~" + reStrike.FindStringSubmatch(m)[1] + "~")
+ })
+
+ // 13) Restore placeholders in reverse insertion order (nested ones resolve).
+ for i := len(p.order) - 1; i >= 0; i-- {
+ k := p.order[i]
+ text = strings.ReplaceAll(text, k, p.values[k])
+ }
+ return text
+}
+
+type mrkdwnPlaceholders struct {
+ values map[string]string
+ order []string
+ n int
+}
+
+func (p *mrkdwnPlaceholders) stash(v string) string {
+ key := "\x00SL" + strconv.Itoa(p.n) + "\x00"
+ p.n++
+ p.values[key] = v
+ p.order = append(p.order, key)
+ return key
+}
diff --git a/server/internal/integrations/slack/mrkdwn_test.go b/server/internal/integrations/slack/mrkdwn_test.go
new file mode 100644
index 0000000000..2a750cfe0b
--- /dev/null
+++ b/server/internal/integrations/slack/mrkdwn_test.go
@@ -0,0 +1,52 @@
+package slack
+
+import "testing"
+
+func TestFormatMrkdwn(t *testing.T) {
+ cases := []struct {
+ name string
+ in string
+ want string
+ }{
+ {"plain unchanged", "just a reply", "just a reply"},
+ {"empty", "", ""},
+ {"bold", "**bold**", "*bold*"},
+ {"italic star to underscore", "*italic*", "_italic_"},
+ {"underscore italic kept", "_italic_", "_italic_"},
+ {"bold italic", "***both***", "*_both_*"},
+ {"strikethrough", "~~gone~~", "~gone~"},
+ {"header to bold", "## Title", "*Title*"},
+ {"header strips inner bold", "### **Big**", "*Big*"},
+ {"markdown link", "see [docs](https://x.com/a)", "see <https://x.com/a|docs>"},
+ {"image link untouched", "![alt](https://x.com/i.png)", "![alt](https://x.com/i.png)"},
+ {"inline code protected", "use `**not bold**` here", "use `**not bold**` here"},
+ {"existing slack mention untouched", "hi <@U123>", "hi <@U123>"},
+ {"ampersand and angles escaped", "a & b < c > d", "a &amp; b &lt; c &gt; d"},
+ {"blockquote preserved", "> quoted line", "> quoted line"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := formatMrkdwn(tc.in); got != tc.want {
+ t.Errorf("formatMrkdwn(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestFormatMrkdwn_FencedCodeProtected(t *testing.T) {
+ in := "before\n```\n**stars** and [x](y) stay literal\n```\nafter **bold**"
+ got := formatMrkdwn(in)
+ want := "before\n```\n**stars** and [x](y) stay literal\n```\nafter *bold*"
+ if got != want {
+ t.Errorf("fenced code must be protected while outside text converts:\n got=%q\nwant=%q", got, want)
+ }
+}
+
+func TestFormatMrkdwn_LinkInsideBold(t *testing.T) {
+ // A link nested in bold: the link converts and survives the bold pass.
+ got := formatMrkdwn("**see [docs](https://x.com)**")
+ want := "*see <https://x.com|docs>*"
+ if got != want {
+ t.Errorf("formatMrkdwn nested link+bold = %q, want %q", got, want)
+ }
+}
diff --git a/server/internal/integrations/slack/outbound.go b/server/internal/integrations/slack/outbound.go
new file mode 100644
index 0000000000..24234884e5
--- /dev/null
+++ b/server/internal/integrations/slack/outbound.go
@@ -0,0 +1,153 @@
+package slack
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/slack-go/slack"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// outboundQueries is the slice of generated queries the Slack outbound
+// subscriber needs. *db.Queries satisfies it.
+type outboundQueries interface {
+ GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
+ GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
+}
+
+// replySender posts one reply. Satisfied by *slackChannel, so the outbound path
+// reuses Send's Markdown->mrkdwn conversion, chunking, and threading.
+type replySender interface {
+ Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error)
+}
+
+// Outbound delivers an agent's chat reply back to Slack — the outbound half of
+// the round trip. It mirrors the Feishu Patcher: on EventChatDone it finds the
+// Slack chat binding for the finished task's session and posts the reply into
+// the originating channel/thread. Sessions with no Slack binding are ignored,
+// so it coexists with the Feishu Patcher on the shared event bus. It is only
+// registered when Slack is configured.
+type Outbound struct {
+ q outboundQueries
+ decrypt Decrypter
+ logger *slog.Logger
+ newSender func(creds credentials) replySender
+}
+
+// NewOutbound builds the Slack outbound subscriber over the generated queries
+// and the bot/app-token decrypter.
+func NewOutbound(q outboundQueries, decrypt Decrypter, logger *slog.Logger) *Outbound {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ o := &Outbound{q: q, decrypt: decrypt, logger: logger}
+ o.newSender = func(c credentials) replySender {
+ // Only the bot token is needed to post; the app token is a Socket Mode
+ // (inbound) credential.
+ return newSlackChannel(c, slack.New(c.BotToken), nil, logger)
+ }
+ return o
+}
+
+// Register subscribes to the chat-done event on the bus.
+func (o *Outbound) Register(bus *events.Bus) {
+ bus.Subscribe(protocol.EventChatDone, o.handleEvent)
+}
+
+func (o *Outbound) handleEvent(e events.Event) {
+ // Bus delivery is synchronous, so a stuck Slack HTTP call must not wedge the
+ // publish call site: use a fresh ctx with a tight timeout.
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := o.processEvent(ctx, e); err != nil {
+ o.logger.WarnContext(ctx, "slack outbound: reply delivery failed",
+ "error", err, "chat_session_id", e.ChatSessionID)
+ }
+}
+
+func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
+ sessionID, err := util.ParseUUID(e.ChatSessionID)
+ if err != nil || !sessionID.Valid {
+ // Issue / autopilot tasks carry no chat_session.
+ return nil
+ }
+ binding, err := o.q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
+ ChatSessionID: sessionID,
+ ChannelType: string(TypeSlack),
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil // not a Slack session (Feishu / web-only)
+ }
+ return fmt.Errorf("lookup slack chat binding: %w", err)
+ }
+ content := chatDoneContent(e.Payload)
+ if content == "" {
+ return nil // nothing to say (empty completion)
+ }
+ inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
+ ID: binding.InstallationID,
+ ChannelType: string(TypeSlack),
+ })
+ if err != nil {
+ return fmt.Errorf("load slack installation: %w", err)
+ }
+ if inst.Status != "active" {
+ return nil // revoked between trigger and reply
+ }
+ creds, err := decodeCredentials(inst.Config, o.decrypt)
+ if err != nil {
+ return fmt.Errorf("decode slack credentials: %w", err)
+ }
+ channelID, threadTS := outboundTarget(binding)
+ if _, err := o.newSender(creds).Send(ctx, channel.OutboundMessage{
+ ChatID: channelID,
+ Text: content,
+ ThreadID: threadTS,
+ }); err != nil {
+ return fmt.Errorf("post slack reply: %w", err)
+ }
+ return nil
+}
+
+// outboundTarget recovers the real send target from the chat binding. The
+// channel_chat_id may be a composite "channel:threadRoot" isolation key, so the
+// real channel id is read from the binding config (slackBindingConfig); the
+// reply thread is the recorded last_thread_id.
+func outboundTarget(b db.ChannelChatSessionBinding) (channelID, threadTS string) {
+ channelID = b.ChannelChatID
+ if len(b.Config) > 0 {
+ var cfg slackBindingConfig
+ if err := json.Unmarshal(b.Config, &cfg); err == nil && cfg.ChannelID != "" {
+ channelID = cfg.ChannelID
+ }
+ }
+ if b.LastThreadID.Valid {
+ threadTS = b.LastThreadID.String
+ }
+ return channelID, threadTS
+}
+
+// chatDoneContent extracts the reply text from an EventChatDone payload (the
+// typed payload, or its map form after a serialization round trip).
+func chatDoneContent(payload any) string {
+ switch p := payload.(type) {
+ case protocol.ChatDonePayload:
+ return p.Content
+ case map[string]any:
+ if s, ok := p["content"].(string); ok {
+ return s
+ }
+ }
+ return ""
+}
diff --git a/server/internal/integrations/slack/outbound_test.go b/server/internal/integrations/slack/outbound_test.go
new file mode 100644
index 0000000000..95a6ae6ad2
--- /dev/null
+++ b/server/internal/integrations/slack/outbound_test.go
@@ -0,0 +1,148 @@
+package slack
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "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/protocol"
+)
+
+func uid(b byte) pgtype.UUID {
+ var u pgtype.UUID
+ u.Bytes[0] = b
+ u.Valid = true
+ return u
+}
+
+type fakeOutboundQueries struct {
+ binding db.ChannelChatSessionBinding
+ bindingErr error
+ inst db.ChannelInstallation
+ instErr error
+}
+
+func (f *fakeOutboundQueries) GetChannelChatSessionBindingBySession(context.Context, db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
+ return f.binding, f.bindingErr
+}
+
+func (f *fakeOutboundQueries) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {
+ return f.inst, f.instErr
+}
+
+type fakeSender struct {
+ called int
+ got channel.OutboundMessage
+}
+
+func (f *fakeSender) Send(_ context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ f.called++
+ f.got = out
+ return channel.SendResult{MessageID: "1.1"}, nil
+}
+
+// slackInstallConfigJSON builds an installation config blob with base64 tokens
+// (a nil Decrypter treats the decoded bytes as plaintext).
+func slackInstallConfigJSON() []byte {
+ b, _ := json.Marshal(map[string]string{
+ "app_id": "T1",
+ "bot_user_id": "UBOT",
+ "bot_token_encrypted": base64.StdEncoding.EncodeToString([]byte("xoxb-test")),
+ "app_token_encrypted": base64.StdEncoding.EncodeToString([]byte("xapp-test")),
+ })
+ return b
+}
+
+func newTestOutbound(q outboundQueries, fs *fakeSender) *Outbound {
+ o := NewOutbound(q, nil, nil)
+ o.newSender = func(credentials) replySender { return fs }
+ return o
+}
+
+func chatDoneEvent(sessionID string, content string) events.Event {
+ return events.Event{
+ Type: protocol.EventChatDone,
+ ChatSessionID: sessionID,
+ Payload: protocol.ChatDonePayload{Content: content},
+ }
+}
+
+func TestOutbound_PostsReplyToBoundSlackChannel(t *testing.T) {
+ q := &fakeOutboundQueries{
+ // Composite isolation key; real channel + reply thread come from config /
+ // last_thread_id.
+ binding: db.ChannelChatSessionBinding{
+ InstallationID: uid(1),
+ ChannelChatID: "C123:1111.0",
+ Config: []byte(`{"channel_id":"C123"}`),
+ LastThreadID: pgtype.Text{String: "1111.0", Valid: true},
+ },
+ inst: db.ChannelInstallation{ID: uid(1), Status: "active", Config: slackInstallConfigJSON()},
+ }
+ fs := &fakeSender{}
+ o := newTestOutbound(q, fs)
+
+ o.handleEvent(chatDoneEvent("00000000-0000-0000-0000-000000000001", "**all done**"))
+
+ if fs.called != 1 {
+ t.Fatalf("sender called %d times, want 1", fs.called)
+ }
+ if fs.got.ChatID != "C123" {
+ t.Errorf("ChatID = %q, want the real channel from config (not the composite key)", fs.got.ChatID)
+ }
+ if fs.got.ThreadID != "1111.0" {
+ t.Errorf("ThreadID = %q, want the recorded reply thread", fs.got.ThreadID)
+ }
+ if fs.got.Text != "**all done**" {
+ t.Errorf("Text = %q, want the raw content (Send applies mrkdwn)", fs.got.Text)
+ }
+}
+
+func TestOutbound_IgnoresNonSlackAndEmptyAndRevoked(t *testing.T) {
+ const sid = "00000000-0000-0000-0000-000000000001"
+ activeInst := db.ChannelInstallation{ID: uid(1), Status: "active", Config: slackInstallConfigJSON()}
+ boundBinding := db.ChannelChatSessionBinding{InstallationID: uid(1), ChannelChatID: "C1", Config: []byte(`{"channel_id":"C1"}`)}
+
+ cases := []struct {
+ name string
+ q *fakeOutboundQueries
+ evt events.Event
+ }{
+ {
+ name: "no slack binding (Feishu / web session)",
+ q: &fakeOutboundQueries{bindingErr: pgx.ErrNoRows},
+ evt: chatDoneEvent(sid, "hi"),
+ },
+ {
+ name: "empty completion content",
+ q: &fakeOutboundQueries{binding: boundBinding, inst: activeInst},
+ evt: chatDoneEvent(sid, ""),
+ },
+ {
+ name: "revoked installation",
+ q: &fakeOutboundQueries{binding: boundBinding, inst: db.ChannelInstallation{ID: uid(1), Status: "revoked", Config: slackInstallConfigJSON()}},
+ evt: chatDoneEvent(sid, "hi"),
+ },
+ {
+ name: "non-chat event (no session id)",
+ q: &fakeOutboundQueries{},
+ evt: chatDoneEvent("", "hi"),
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ fs := &fakeSender{}
+ newTestOutbound(tc.q, fs).handleEvent(tc.evt)
+ if fs.called != 0 {
+ t.Errorf("%s: sender must not be called, got %d", tc.name, fs.called)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.go
new file mode 100644
index 0000000000..3058668642
--- /dev/null
+++ b/server/internal/integrations/slack/resolvers.go
@@ -0,0 +1,248 @@
+package slack
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// This file is the Slack ResolverSet: the platform-specific seams the
+// channel-agnostic engine.Router runs the inbound pipeline through. It mirrors
+// the Feishu ResolverSet but is built entirely on the generic channel_* queries
+// (no new query, no schema change) plus the shared engine.ChatSession — so
+// "adding Slack" stays "implement Channel + register a ResolverSet".
+
+// originSlackChat is the issue.origin_type label for issues created via the
+// Slack /issue command.
+const originSlackChat = "slack_chat"
+
+// NewSlackResolverSet assembles the Slack ResolverSet over the generated
+// queries + a tx starter (for the shared session service). Replier/Typing are
+// left nil for now: the outbound binding-prompt / notice path is a later step
+// (the inbound pipeline — route, identity, dedup, session, /issue, run trigger
+// — is fully functional without them).
+func NewSlackResolverSet(q *db.Queries, tx engine.TxStarter) engine.ResolverSet {
+ return engine.ResolverSet{
+ Installation: &installationResolver{q: q},
+ Identity: &identityResolver{q: q},
+ Dedup: &deduper{q: q},
+ Session: &sessionBinder{session: engine.NewChatSession(q, tx, TypeSlack, engine.SessionTitles{
+ Group: "Slack channel",
+ Direct: "Slack direct message",
+ Fallback: "Slack chat",
+ })},
+ Audit: &auditor{q: q},
+ OriginType: originSlackChat,
+ }
+}
+
+var (
+ _ engine.InstallationResolver = (*installationResolver)(nil)
+ _ engine.IdentityResolver = (*identityResolver)(nil)
+ _ engine.Deduper = (*deduper)(nil)
+ _ engine.SessionBinder = (*sessionBinder)(nil)
+ _ engine.Auditor = (*auditor)(nil)
+)
+
+// slackBindingConfig is the opaque outbound routing persisted on the chat
+// binding's config. When the binding key is a composite (Slack channel thread),
+// the real channel id lives here so the outbound path can post back.
+type slackBindingConfig struct {
+ ChannelID string `json:"channel_id"`
+}
+
+// slackSessionRouting derives, from one inbound Slack message, the three things
+// the session layer needs kept distinct (Elon's round-2 must-fix):
+//
+// - bindingKey: the session-isolation key (stored as channel_chat_id). A DM is
+// one continuous session per channel, so the key is the channel id. A
+// channel/group message is isolated by THREAD ROOT — key = "channel:root" —
+// so two @bot threads in one channel are two sessions, matching Hermes. The
+// thread root is the inbound thread_ts when replying in a thread, else the
+// message ts (a top-level @mention starts a new root).
+// - config: the real channel id, so outbound works even when the key is
+// composite.
+// - replyThread: the thread_ts to reply into (the thread root for groups; the
+// inbound thread for DMs, which may be empty for a top-level send).
+//
+// It is a pure function so the isolation contract is unit-tested without a DB.
+func slackSessionRouting(msg channel.InboundMessage) (bindingKey string, config []byte, replyThread string) {
+ chatID := msg.Source.ChatID
+ cfg, _ := json.Marshal(slackBindingConfig{ChannelID: chatID})
+ if msg.Source.ChatType == channel.ChatTypeP2P {
+ return chatID, cfg, msg.Source.ThreadID
+ }
+ threadRoot := msg.Source.ThreadID
+ if threadRoot == "" {
+ threadRoot = msg.MessageID
+ }
+ return chatID + ":" + threadRoot, cfg, threadRoot
+}
+
+func decodeSlackRaw(msg channel.InboundMessage) (slackRawEvent, error) {
+ var raw slackRawEvent
+ if len(msg.Raw) == 0 {
+ return slackRawEvent{}, errors.New("slack: inbound message Raw is empty")
+ }
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil {
+ return slackRawEvent{}, fmt.Errorf("decode slack inbound raw: %w", err)
+ }
+ return raw, nil
+}
+
+func nullText(s string) pgtype.Text {
+ if s == "" {
+ return pgtype.Text{}
+ }
+ return pgtype.Text{String: s, Valid: true}
+}
+
+// ---- installation routing ----
+
+type installationResolver struct{ q *db.Queries }
+
+func (r *installationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
+ raw, err := decodeSlackRaw(msg)
+ if err != nil {
+ return engine.ResolvedInstallation{}, err
+ }
+ inst, err := r.q.GetChannelInstallationByAppID(ctx, db.GetChannelInstallationByAppIDParams{
+ ChannelType: string(TypeSlack),
+ AppID: raw.TeamID, // Slack team_id is stored in the routing-key slot
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedInstallation{}, engine.ErrInstallationNotFound
+ }
+ return engine.ResolvedInstallation{}, err
+ }
+ return engine.ResolvedInstallation{
+ ID: inst.ID,
+ WorkspaceID: inst.WorkspaceID,
+ AgentID: inst.AgentID,
+ InstallerUserID: inst.InstallerUserID,
+ Active: inst.Status == "active",
+ Platform: inst,
+ }, nil
+}
+
+// ---- identity ----
+
+type identityResolver struct{ q *db.Queries }
+
+func (r *identityResolver) ResolveSender(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) (engine.ResolvedIdentity, error) {
+ binding, err := r.q.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{
+ InstallationID: inst.ID,
+ ChannelUserID: msg.Source.SenderID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedIdentity{}, engine.ErrSenderUnbound
+ }
+ return engine.ResolvedIdentity{}, err
+ }
+ // Binding existence no longer proves membership (no FK); re-check.
+ if _, err := r.q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: binding.MulticaUserID,
+ WorkspaceID: inst.WorkspaceID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedIdentity{}, engine.ErrSenderNotMember
+ }
+ return engine.ResolvedIdentity{}, err
+ }
+ return engine.ResolvedIdentity{UserID: binding.MulticaUserID}, nil
+}
+
+// ---- dedup ----
+
+type deduper struct{ q *db.Queries }
+
+func (r *deduper) Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (pgtype.UUID, error) {
+ claim, err := r.q.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return pgtype.UUID{}, engine.ErrDuplicate
+ }
+ return pgtype.UUID{}, err
+ }
+ return claim.ClaimToken, nil
+}
+
+func (r *deduper) Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.q.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.q.ReleaseChannelInboundDedup(ctx, db.ReleaseChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+// ---- session bind / append ----
+
+type sessionBinder struct{ session *engine.ChatSession }
+
+func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
+ bindingKey, config, _ := slackSessionRouting(p.Message)
+ return r.session.EnsureSession(ctx, engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID,
+ AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID,
+ Sender: p.Sender,
+ BindingKey: bindingKey,
+ BindingConfig: config,
+ ChatType: p.Message.Source.ChatType,
+ })
+}
+
+func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
+ _, _, replyThread := slackSessionRouting(p.Message)
+ return r.session.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: p.SessionID,
+ Sender: p.Sender,
+ InstallationID: p.InstallationID,
+ Body: p.Message.Text,
+ // Slack text is not enriched, so the command source is the body itself.
+ CommandText: p.Message.Text,
+ MessageID: p.Message.MessageID,
+ ThreadID: replyThread,
+ ClaimToken: p.ClaimToken,
+ })
+}
+
+// ---- audit ----
+
+type auditor struct{ q *db.Queries }
+
+func (r *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
+ raw, _ := decodeSlackRaw(msg) // event_type is best-effort; a decode miss still audits the drop
+ return r.q.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ChannelType: string(TypeSlack),
+ EventType: raw.EventType,
+ DropReason: string(reason),
+ InstallationID: instID,
+ ChannelChatID: nullText(msg.Source.ChatID),
+ ChannelEventID: nullText(msg.EventID),
+ ChannelMessageID: nullText(msg.MessageID),
+ })
+}
diff --git a/server/internal/integrations/slack/resolvers_test.go b/server/internal/integrations/slack/resolvers_test.go
new file mode 100644
index 0000000000..f7b756dc76
--- /dev/null
+++ b/server/internal/integrations/slack/resolvers_test.go
@@ -0,0 +1,103 @@
+package slack
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+func inbound(chatType channel.ChatType, chatID, threadID, msgID string) channel.InboundMessage {
+ return channel.InboundMessage{
+ MessageID: msgID,
+ Source: channel.Source{
+ ChannelType: TypeSlack,
+ ChatID: chatID,
+ ChatType: chatType,
+ ThreadID: threadID,
+ },
+ }
+}
+
+func TestSlackSessionRouting(t *testing.T) {
+ cases := []struct {
+ name string
+ msg channel.InboundMessage
+ wantKey string
+ wantReplyThr string
+ wantChannelCfg string
+ }{
+ {
+ name: "DM top-level: one session per channel",
+ msg: inbound(channel.ChatTypeP2P, "D1", "", "111.0"),
+ wantKey: "D1",
+ wantReplyThr: "",
+ wantChannelCfg: "D1",
+ },
+ {
+ name: "DM in a thread: still one session per channel, reply into the thread",
+ msg: inbound(channel.ChatTypeP2P, "D1", "100.0", "111.0"),
+ wantKey: "D1",
+ wantReplyThr: "100.0",
+ wantChannelCfg: "D1",
+ },
+ {
+ name: "channel top-level @mention: new thread root = message ts",
+ msg: inbound(channel.ChatTypeGroup, "C1", "", "111.0"),
+ wantKey: "C1:111.0",
+ wantReplyThr: "111.0",
+ wantChannelCfg: "C1",
+ },
+ {
+ name: "channel thread reply: isolated by thread root",
+ msg: inbound(channel.ChatTypeGroup, "C1", "100.0", "222.0"),
+ wantKey: "C1:100.0",
+ wantReplyThr: "100.0",
+ wantChannelCfg: "C1",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ key, cfg, reply := slackSessionRouting(tc.msg)
+ if key != tc.wantKey {
+ t.Errorf("bindingKey = %q, want %q", key, tc.wantKey)
+ }
+ if reply != tc.wantReplyThr {
+ t.Errorf("replyThread = %q, want %q", reply, tc.wantReplyThr)
+ }
+ var got slackBindingConfig
+ if err := json.Unmarshal(cfg, &got); err != nil {
+ t.Fatalf("config not valid json: %v", err)
+ }
+ if got.ChannelID != tc.wantChannelCfg {
+ t.Errorf("config.channel_id = %q, want %q (real channel for outbound)", got.ChannelID, tc.wantChannelCfg)
+ }
+ })
+ }
+}
+
+// TestSlackThreadIsolation is the resolver-level guard Niko/Elon asked for: two
+// @bot threads in the SAME channel must derive DISTINCT session binding keys,
+// while a follow-up in the same thread derives the same key.
+func TestSlackThreadIsolation(t *testing.T) {
+ thread1Root, _, _ := slackSessionRouting(inbound(channel.ChatTypeGroup, "C1", "", "1111.0")) // @mention starts thread 1
+ thread2Root, _, _ := slackSessionRouting(inbound(channel.ChatTypeGroup, "C1", "", "2222.0")) // @mention starts thread 2
+ thread1Reply, _, _ := slackSessionRouting(inbound(channel.ChatTypeGroup, "C1", "1111.0", "3333.0")) // reply in thread 1
+
+ if thread1Root == thread2Root {
+ t.Errorf("two @bot threads in one channel must isolate: %q == %q", thread1Root, thread2Root)
+ }
+ if thread1Reply != thread1Root {
+ t.Errorf("a follow-up in thread 1 must reuse thread 1's key: %q != %q", thread1Reply, thread1Root)
+ }
+}
+
+func TestNewSlackResolverSet(t *testing.T) {
+ set := NewSlackResolverSet(nil, nil)
+ if set.Installation == nil || set.Identity == nil || set.Dedup == nil || set.Session == nil || set.Audit == nil {
+ t.Error("resolver set must populate all required resolvers")
+ }
+ if set.OriginType != "slack_chat" {
+ t.Errorf("OriginType = %q, want slack_chat", set.OriginType)
+ }
+}
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index 7f6f4634e3..7133c7ad72 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -191,9 +191,9 @@ func (q *Queries) CreateChannelBindingToken(ctx context.Context, arg CreateChann
const createChannelChatSessionBinding = `-- name: CreateChannelChatSessionBinding :one
INSERT INTO channel_chat_session_binding (
- chat_session_id, installation_id, channel_type, channel_chat_id, chat_type
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config
) VALUES (
- $1, $2, $3, $4, $5
+ $1, $2, $3, $4, $5, $6
)
RETURNING id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at
`
@@ -204,11 +204,18 @@ type CreateChannelChatSessionBindingParams struct {
ChannelType string `json:"channel_type"`
ChannelChatID string `json:"channel_chat_id"`
ChatType string `json:"chat_type"`
+ Config []byte `json:"config"`
}
// =====================
// channel_chat_session_binding
// =====================
+// channel_chat_id is the session-isolation key (one chat_session per
+// (installation_id, channel_chat_id)): Feishu passes the chat id; Slack passes
+// a stable key that, for channels, includes the thread root so each @bot thread
+// is its own session. config carries any platform-specific outbound routing the
+// key alone does not (e.g. Slack's real channel_id when the key is composite);
+// it is opaque to the shared session service.
func (q *Queries) CreateChannelChatSessionBinding(ctx context.Context, arg CreateChannelChatSessionBindingParams) (ChannelChatSessionBinding, error) {
row := q.db.QueryRow(ctx, createChannelChatSessionBinding,
arg.ChatSessionID,
@@ -216,6 +223,7 @@ func (q *Queries) CreateChannelChatSessionBinding(ctx context.Context, arg Creat
arg.ChannelType,
arg.ChannelChatID,
arg.ChatType,
+ arg.Config,
)
var i ChannelChatSessionBinding
err := row.Scan(
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index 5865d09746..fa9f0f7164 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -204,10 +204,16 @@ WHERE workspace_id = $1 AND multica_user_id = $2;
-- =====================
-- name: CreateChannelChatSessionBinding :one
+-- channel_chat_id is the session-isolation key (one chat_session per
+-- (installation_id, channel_chat_id)): Feishu passes the chat id; Slack passes
+-- a stable key that, for channels, includes the thread root so each @bot thread
+-- is its own session. config carries any platform-specific outbound routing the
+-- key alone does not (e.g. Slack's real channel_id when the key is composite);
+-- it is opaque to the shared session service.
INSERT INTO channel_chat_session_binding (
- chat_session_id, installation_id, channel_type, channel_chat_id, chat_type
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config
) VALUES (
- $1, $2, $3, $4, $5
+ $1, $2, $3, $4, $5, $6
)
RETURNING *;