Skip to content

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

Go

feat(channel): channel-agnostic engine (Supervisor + Router); Feishu as channel.Channel (MUL-3620) (#4512)

Bohan Jiang3e21e58df03c
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 09eba60206..53dee0ffc8 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -374,30 +374,33 @@ func main() {
go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())
go runDBStatsLogger(sweepCtx, pool)
- // Lark inbound supervisor: holds the §4.4 WS lease per installation
- // and runs the EventConnector for each. Nil when the Lark master
- // key is unset — self-host deployments that have not opted in to
- // Lark do not pay any goroutine cost. Lifecycle is bound to
- // sweepCtx so the Hub winds down alongside the other long-running
- // workers, AFTER the HTTP server has drained.
- // Cutover control (MUL-3515): MULTICA_LARK_HUB_DISABLED parks the Lark
- // inbound hub WITHOUT taking down the rest of the API — the process still
- // serves HTTP normally, it just never claims a WS lease or opens a Feishu
- // connection. The switch is generation-agnostic: in a pre-cutover build it
- // parks the OLD (lark_*) hub, in this build it parks the NEW (channel_*)
- // hub. The lark_*->channel_* rollout uses it twice — first to stop the old
- // hub on the current build so migration 124 takes a clean snapshot, then to
- // hold this build's new hub dormant until that migration has run and the old
- // pods have drained, so the two never double-process the same bot. Nil-ing
- // LarkHub here reuses the same "Lark not configured" path, so the shutdown
- // join below also skips it. The operator flips it off last to bring the new
- // hub up on channel_*. See migration 124's ROLLOUT note for the full order.
- if h.LarkHub != nil && os.Getenv("MULTICA_LARK_HUB_DISABLED") == "true" {
- slog.Warn("Lark inbound hub disabled via MULTICA_LARK_HUB_DISABLED; API serves normally but no Feishu WebSocket is opened")
- h.LarkHub = nil
- }
- if h.LarkHub != nil {
- go h.LarkHub.Run(sweepCtx)
+ // Channel inbound supervisor (MUL-3620): holds the §4.4 WS lease per
+ // installation and drives each channel.Channel. It is built
+ // unconditionally (it is channel-agnostic, not Lark-specific), so it
+ // always exists here; with no platform registered or no installation
+ // rows it simply idles. Lifecycle is bound to sweepCtx so it winds down
+ // alongside the other long-running workers, AFTER the HTTP server has
+ // drained.
+ // Cutover control (MUL-3515): MULTICA_LARK_HUB_DISABLED parks the inbound
+ // channel supervisor WITHOUT taking down the rest of the API — the process
+ // still serves HTTP normally, it just never claims a WS lease or opens a
+ // Feishu connection. The switch is generation-agnostic: in a pre-cutover
+ // build it parks the OLD (lark_*) hub, in this build it parks the NEW
+ // (channel_*) supervisor. The lark_*->channel_* rollout uses it twice —
+ // first to stop the old hub on the current build so migration 124 takes a
+ // clean snapshot, then to hold this build's new supervisor dormant until
+ // that migration has run and the old pods have drained, so the two never
+ // double-process the same bot. Nil-ing it here makes the start below and
+ // the shutdown join skip it. The operator flips it off last to bring the
+ // new supervisor up on channel_*. See migration 124's ROLLOUT note for the
+ // full order. The env var keeps its name for operator/runbook
+ // compatibility across the cutover.
+ if h.ChannelSupervisor != nil && os.Getenv("MULTICA_LARK_HUB_DISABLED") == "true" {
+ slog.Warn("Lark inbound supervisor disabled via MULTICA_LARK_HUB_DISABLED; API serves normally but no Feishu WebSocket is opened")
+ h.ChannelSupervisor = nil
+ }
+ if h.ChannelSupervisor != nil {
+ go h.ChannelSupervisor.Run(sweepCtx)
}
// MUL-2957: DB-backed execution scheduler. The scheduler turns the
@@ -472,20 +475,27 @@ func main() {
sweepCancel()
heartbeatScheduler.Stop()
- // Join the Lark Hub's per-installation supervisor goroutines so the
+ // Join the channel supervisor's per-installation goroutines so the
// lease renewer can issue a final release before process exit;
// otherwise the next replica would have to wait the full LeaseTTL
// before picking up the installation on the other side of the
// redeploy. The wait is bounded — if a supervisor is wedged (DB
- // pool stalled, a future real EventConnector ignoring ctx, etc.)
- // the fallback is the natural LeaseTTL expiry on the other side,
- // which is strictly better than holding shutdown open forever.
- if h.LarkHub != nil {
- if !h.LarkHub.WaitWithTimeout(h.LarkHub.ShutdownTimeout()) {
- slog.Warn("lark hub: supervisors did not exit within shutdown timeout; proceeding",
- "timeout", h.LarkHub.ShutdownTimeout().String(),
+ // pool stalled, a connector ignoring ctx, etc.) the fallback is the
+ // natural LeaseTTL expiry on the other side, which is strictly better
+ // than holding shutdown open forever. Then drain the Feishu runtime:
+ // the supervisors have stopped delivering inbound events, so flush the
+ // debounced run triggers and join any in-flight outbound replies
+ // (each bounded by ReplyTimeout) so a binding card / offline notice is
+ // not lost on shutdown.
+ if h.ChannelSupervisor != nil {
+ if !h.ChannelSupervisor.WaitWithTimeout(h.ChannelSupervisor.ShutdownTimeout()) {
+ slog.Warn("channel supervisor: connections did not exit within shutdown timeout; proceeding",
+ "timeout", h.ChannelSupervisor.ShutdownTimeout().String(),
)
}
+ if h.ChannelRouter != nil {
+ h.ChannelRouter.Drain()
+ }
}
if metricsServer != nil {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 9d995d1ae8..42af180f29 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -23,6 +23,8 @@ import (
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/featureflagdispatch"
"github.com/multica-ai/multica/server/internal/handler"
+ "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"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -188,13 +190,39 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
h.WebhookIPRateLimiter = handler.NewRedisWebhookIPRateLimiter(rdb, handler.DefaultWebhookIPRateLimit())
}
+ // Channel engine (MUL-3620): the platform-agnostic inbound runtime.
+ // Built UNCONDITIONALLY — it drives any channel.Channel, not just
+ // Feishu, so it must not depend on the Lark master key (a future
+ // Slack-only deployment has no Lark key). Platform adapters register a
+ // Factory + ResolverSet into it below; the Supervisor enumerates active
+ // installations across ALL channel types and routes each to its
+ // registered platform's Factory. With no platform registered the store
+ // still lists any active installation rows, but Registry.Build returns
+ // ErrUnknownType for them, so the supervisor logs and backs off without
+ // opening a connection (the normal state is simply that no rows exist
+ // for an unregistered platform). The Router is the single shared inbound
+ // handler injected into every Channel.
+ channelRegistry := channel.NewRegistry()
+ channelRouter := engine.NewRouter(h.IssueService, h.TaskService, queries, engine.RouterConfig{Logger: slog.Default()})
+ // Debounce the per-session run trigger so a burst of messages collapses
+ // into one agent run instead of one per message (MUL-2968).
+ channelRouter.EnableRunBatching(engine.DefaultChatRunBatchWindow)
+ h.ChannelRouter = channelRouter
+ h.ChannelSupervisor = engine.NewSupervisor(
+ lark.NewChannelInstallationStore(queries),
+ channelRegistry,
+ channelRouter.Handle,
+ engine.Config{},
+ )
+
// Lark integration. Only wired when MULTICA_LARK_SECRET_KEY is set:
// the InstallationService refuses to fall back to plaintext storage
// for app_secret, and the BindingTokenService cannot mint usable
// tokens without it either. When the key is absent the Lark
// handlers return 503 with a clear message; the rest of the server
// continues to start so self-host deployments that have not opted
- // in to Lark are unaffected.
+ // in to Lark are unaffected. Feishu registers its Factory + ResolverSet
+ // into the channel engine above.
if larkKey, err := secretbox.LoadKey("MULTICA_LARK_SECRET_KEY"); err == nil {
box, err := secretbox.New(larkKey)
if err != nil {
@@ -246,56 +274,23 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
typingIndicator := lark.NewTypingIndicatorManager(larkClient, installSvc, cs, slog.Default())
patcher.SetTypingIndicatorManager(typingIndicator)
- // Inbound pipeline: lark_inbound_audit logger,
- // channel-aware ChatSessionService, and the
- // Dispatcher that orders identity / dedup / append /
- // /issue / enqueue per §4.3. The Dispatcher depends
- // on the same IssueService + TaskService that back
- // HTTP, so /issue-created issues share counter, dup
+ // 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.
auditLogger := lark.NewAuditLogger(queries)
chatSvc := lark.NewChatSessionService(queries, pool)
- dispatcher := &lark.Dispatcher{
- Queries: cs,
- Chat: chatSvc,
- Audit: auditLogger,
- IssueService: h.IssueService,
- TaskService: h.TaskService,
- Logger: slog.Default(),
- }
- // Debounce the per-session run trigger so a burst of
- // messages (e.g. "forward a transcript, then type a note")
- // collapses into one agent run instead of one per message.
- // MUL-2968.
- dispatcher.EnableRunBatching(lark.DefaultChatRunBatchWindow)
-
- // WS Hub: lease + supervisor goroutines per installation.
- // The WSLongConnConnector talks Lark's long-conn protocol
- // over gorilla/websocket. The connector wraps every read
- // with a ctx-cancel watchdog so lease loss / shutdown
- // breaks the blocking ReadMessage in bounded time — the
- // invariant §4.4 leans on. If the endpoint fetcher fails
- // to initialize (bad MULTICA_LARK_CALLBACK_BASE_URL or
- // similar config error), buildLarkConnectorFactory logs
- // and falls back to the NoopConnector so the lease /
- // supervisor lifecycle still runs against real DB rows —
- // inbound messages will be silently dropped until the
- // config is fixed, with the boot log labelling the mode
- // "noop" so operators can spot it.
- connectorFactory, connectorLabel := buildLarkConnectorFactory(installSvc, larkClient)
- h.LarkHub = lark.NewHub(cs, connectorFactory, dispatcher, lark.HubConfig{})
- h.LarkHub.SetTypingIndicatorManager(typingIndicator)
-
- // OutcomeReplier wires the outbound side of the
- // EventEmitter contract: NeedsBinding / AgentOffline /
- // AgentArchived translate to a Lark-side reply card.
- // Requires the real APIClient (the stub returns
- // ErrAPIClientNotConfigured on every send) and the
- // binding token service. When either is missing, the
- // Hub falls back to the noop replier and the outcomes
- // get logged but not delivered — clearly visible in
- // boot output so operators understand the gap.
+
+ // OutcomeReplier wires the outbound side: NeedsBinding /
+ // AgentOffline / AgentArchived / issue-created translate to a
+ // Lark-side reply card. Requires the real APIClient and the
+ // binding token service; otherwise it falls back to the noop
+ // replier (outcomes logged, not delivered). We only register
+ // it on the ResolverSet when it can actually deliver, so a
+ // pre-outbound deployment pays no reply-goroutine cost.
replier := lark.NewLarkOutcomeReplier(lark.OutcomeReplierConfig{
APIClient: larkClient,
BindingSvc: h.LarkBindingTokens,
@@ -304,12 +299,36 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
PublicURL: signupConfig.PublicURL,
Logger: slog.Default(),
})
- h.LarkHub.SetOutcomeReplier(replier)
- // The agent-offline / agent-archived notice is now decided
- // at debounce-flush time rather than synchronously from
- // Handle, so the dispatcher drives that reply itself through
- // the same replier. MUL-2968.
- dispatcher.FlushReply = replier.Reply
+ var resolverReplier lark.OutcomeReplier
+ if larkClient.IsConfigured() {
+ resolverReplier = replier
+ }
+
+ // Feishu adapter (MUL-3620): the WSLongConnConnector talks
+ // Lark's long-conn protocol over gorilla/websocket and wraps
+ // every read with a ctx-cancel watchdog so lease loss /
+ // shutdown breaks the blocking ReadMessage in bounded time —
+ // the invariant §4.4 leans on. If the endpoint fetcher fails
+ // to initialize (bad MULTICA_LARK_CALLBACK_BASE_URL or
+ // similar), buildLarkConnector logs and falls back to the
+ // NoopConnector so the lease / supervisor lifecycle still runs
+ // against real DB rows — inbound messages are silently dropped
+ // until the config is fixed, with the boot log labelling the
+ // mode "noop".
+ //
+ // Registering the Factory (connect/send) + ResolverSet
+ // (inbound pipeline seams) is all it takes to add the platform
+ // to the engine — no engine edit.
+ connector, connectorLabel := buildLarkConnector(installSvc, larkClient)
+ lark.RegisterFeishu(channelRegistry, lark.FeishuChannelDeps{
+ Connector: connector,
+ APIClient: larkClient,
+ Credentials: installSvc,
+ Logger: slog.Default(),
+ })
+ channelRouter.Register(channel.TypeFeishu, lark.NewFeishuResolverSet(
+ cs, chatSvc, auditLogger, resolverReplier, typingIndicator,
+ ))
slog.Info("lark inbound pipeline wired", "connector", connectorLabel)
// One-shot union_id backfill for installations created
@@ -1021,11 +1040,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
return r, h
}
-// buildLarkConnectorFactory wires the real WS long-conn connector
-// that talks to /callback/ws/endpoint directly with app_id/app_secret.
-// The connector wraps every read with a ctx-cancel watchdog so lease
-// loss / shutdown breaks the blocking ReadMessage in bounded time —
-// the invariant §4.4 leans on.
+// buildLarkConnector wires the real WS long-conn connector that talks
+// to /callback/ws/endpoint directly with app_id/app_secret. The
+// connector wraps every read with a ctx-cancel watchdog so lease loss /
+// shutdown breaks the blocking ReadMessage in bounded time — the
+// invariant §4.4 leans on. A single connector instance serves every
+// installation; its Run is parameterized by the installation, so the
+// feishuChannel hands it the per-installation row.
//
// If the endpoint fetcher fails to initialize (typically a malformed
// MULTICA_LARK_CALLBACK_BASE_URL), we log and fall back to the
@@ -1034,16 +1055,16 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// the config is fixed; the boot log labels the mode "noop" so the
// degraded state is visible.
//
-// Returns the factory plus a short label for the boot log: "ws" in
-// the healthy case, "noop" in the fallback case.
-func buildLarkConnectorFactory(installSvc *lark.InstallationService, apiClient lark.APIClient) (lark.ConnectorFactory, string) {
+// Returns the connector plus a short label for the boot log:
+// "ws-long-conn" in the healthy case, "noop" in the fallback case.
+func buildLarkConnector(installSvc *lark.InstallationService, apiClient lark.APIClient) (lark.EventConnector, string) {
endpointFetcher, err := lark.NewHTTPConnectionTokenFetcher(lark.HTTPConnectionTokenConfig{
BaseURL: strings.TrimSpace(os.Getenv("MULTICA_LARK_CALLBACK_BASE_URL")),
Logger: slog.Default(),
})
if err != nil {
slog.Error("lark ws: endpoint fetcher init failed; falling back to noop", "error", err)
- return lark.NoopConnectorFactory(slog.Default()), "noop"
+ return lark.NewNoopConnector(slog.Default()), "noop"
}
decoder := lark.NewLarkJSONFrameDecoder()
dialer := lark.NewGorillaDialer()
@@ -1084,11 +1105,9 @@ func buildLarkConnectorFactory(installSvc *lark.InstallationService, apiClient l
})
if err != nil {
slog.Error("lark ws: connector init failed; falling back to noop", "error", err)
- return lark.NoopConnectorFactory(slog.Default()), "noop"
+ return lark.NewNoopConnector(slog.Default()), "noop"
}
- return func(_ lark.Installation) (lark.EventConnector, error) {
- return conn, nil
- }, "ws-long-conn"
+ return conn, "ws-long-conn"
}
// membershipChecker implements realtime.MembershipChecker using database queries.
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index c29ec1697f..2b06e7679a 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -21,6 +21,7 @@ import (
"github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/featureflagdispatch"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
"github.com/multica-ai/multica/server/internal/integrations/lark"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -151,18 +152,26 @@ type Handler struct {
// UI consults IsConfigured() to decide whether to surface install
// entry points.
LarkAPIClient lark.APIClient
- // LarkHub owns the per-installation supervisor goroutines that
- // hold the §4.4 WS lease and run the EventConnector. Nil only
- // when the master at-rest key (MULTICA_LARK_SECRET_KEY) is unset.
- // The router constructs the Hub but does NOT call Run on it; the
- // process owner (main.go) starts it under a long-running context
- // and joins via WaitWithTimeout (bounded wait, fenced by
- // ShutdownTimeout) during graceful shutdown so the lease renewer
- // can yield cleanly when the DB is healthy without blocking
- // process exit indefinitely if the pool is frozen — at worst the
- // next replica waits the full TTL.
- LarkHub *lark.Hub
- cfg Config
+ // ChannelSupervisor owns the per-installation supervisor goroutines
+ // that hold the §4.4 WS lease and drive each channel.Channel
+ // (MUL-3620 generalized the Feishu-only Hub into this channel-agnostic
+ // engine). The router constructs it UNCONDITIONALLY — it drives any
+ // channel type, not just Feishu, so it does not depend on the Lark
+ // master key; each platform registers its Factory only when configured
+ // (Feishu when MULTICA_LARK_SECRET_KEY is set). The router does NOT
+ // call Run; the process owner (main.go) starts it under a long-running
+ // context and joins via WaitWithTimeout (bounded, fenced by
+ // ShutdownTimeout) during graceful shutdown so the lease renewer yields
+ // cleanly when the DB is healthy without blocking process exit if the
+ // pool is frozen — at worst the next replica waits the full TTL.
+ ChannelSupervisor *engine.Supervisor
+ // ChannelRouter is the channel-agnostic inbound pipeline (the shared
+ // handler the Supervisor injects into every Channel). main.go calls
+ // Drain on it during shutdown, after the Supervisor has stopped
+ // delivering events, to flush debounced run triggers and join in-flight
+ // reply goroutines. Built unconditionally (even without Lark).
+ ChannelRouter *engine.Router
+ cfg Config
}
func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, store storage.Storage, cfSigner *auth.CloudFrontSigner, analyticsClient analytics.Client, cfg Config, daemonHubs ...*daemonws.Hub) *Handler {
diff --git a/server/internal/integrations/channel/channel.go b/server/internal/integrations/channel/channel.go
index c5731f703d..8fcc62dc24 100644
--- a/server/internal/integrations/channel/channel.go
+++ b/server/internal/integrations/channel/channel.go
@@ -36,11 +36,22 @@ type Channel interface {
Type() Type
// Connect establishes the platform link (e.g. dials the outbound
- // WebSocket long-conn, or starts the inbound HTTP listener). The
- // connection mode is the implementation's choice and invisible to
- // the core. Connect blocks only until the link is established (or
- // fails); the ongoing receive loop runs in the background and is
- // torn down by Disconnect or by ctx cancellation.
+ // WebSocket long-conn, or starts the inbound HTTP listener) and then
+ // BLOCKS, running the receive loop, until the link ends. The
+ // connection mode is the implementation's choice and invisible to the
+ // core. It returns:
+ //
+ // - nil when ctx is cancelled (graceful shutdown / lease loss);
+ // - a non-nil error when the link drops and cannot be recovered
+ // locally — the supervisor treats this as "this attempt failed"
+ // and reconnects under exponential backoff.
+ //
+ // While Connect runs, the adapter delivers each inbound message by
+ // invoking the InboundHandler it captured at construction
+ // (Config.Handler). Send may be called concurrently from another
+ // goroutine for the lifetime of the connection. Implementations MUST
+ // tolerate repeated Connect calls on different contexts: the
+ // supervisor may Connect, return, and Connect again after backoff.
Connect(ctx context.Context) error
// Disconnect tears the platform link down and releases its
@@ -72,6 +83,13 @@ type Channel interface {
type Config struct {
Type Type
Raw json.RawMessage
+
+ // Handler is the shared inbound entry point the engine injects so the
+ // built Channel can deliver normalized InboundMessage values into the
+ // core (see InboundHandler). A Factory captures it and invokes it from
+ // the Channel's receive loop. It may be nil when a Channel is built
+ // purely for its outbound Send path (no inbound delivery needed).
+ Handler InboundHandler
}
// Factory builds a Channel from its per-installation Config. Each adapter
diff --git a/server/internal/integrations/channel/engine/batcher.go b/server/internal/integrations/channel/engine/batcher.go
new file mode 100644
index 0000000000..6cdb156de5
--- /dev/null
+++ b/server/internal/integrations/channel/engine/batcher.go
@@ -0,0 +1,151 @@
+package engine
+
+import (
+ "sync"
+ "time"
+)
+
+// DefaultChatRunBatchWindow is the silence window the inbound debouncer waits
+// before triggering an agent run for a chat session. 3s (MUL-2968): long
+// enough to absorb a "forward a transcript, then type a note" burst into one
+// run, short enough that the bot's first reply is not perceptibly late.
+const DefaultChatRunBatchWindow = 3 * time.Second
+
+// stoppableTimer is the slice of *time.Timer the batcher depends on, pinned to
+// an interface so tests inject a manually-fired fake. *time.Timer satisfies it.
+type stoppableTimer interface {
+ Stop() bool
+}
+
+// pendingBatcher debounces the per-chat_session run trigger. Each inbound
+// message that lands in a session calls Schedule, which (re)arms a single
+// timer for that session; when the session goes quiet for the window the
+// latest flush runs exactly once. This collapses a burst into ONE agent run —
+// safe because the chat task reads the WHOLE session at run time. Only the run
+// TRIGGER is debounced; the chat_message rows, dedup, and frame ACK already
+// happened synchronously upstream.
+//
+// State is in-process, keyed by chat_session_id (a globally-unique UUID). The
+// WS lease guarantees a single active owner per installation, so a session is
+// debounced by one process. A hard crash inside the window drops the pending
+// trigger (messages are durable; they just do not fire a run until the next
+// message). Graceful shutdown calls FlushAll so that boundary is not hit on a
+// normal restart. Goroutine-safe; one instance is shared across supervisors.
+type pendingBatcher struct {
+ window time.Duration
+
+ // afterFunc builds a timer that invokes fn after d. Defaults to
+ // time.AfterFunc; tests substitute a fake for deterministic flushes.
+ afterFunc func(d time.Duration, fn func()) stoppableTimer
+
+ mu sync.Mutex
+ pending map[string]*pendingEntry
+ // seq mints a monotonic generation per (re)schedule. onFire carries the
+ // generation it was armed with and bails if a newer schedule superseded
+ // it — fencing the AfterFunc race where a timer fires concurrently with
+ // the Stop() meant to cancel it.
+ seq uint64
+ stopped bool
+ inflight sync.WaitGroup
+}
+
+type pendingEntry struct {
+ timer stoppableTimer
+ flush func()
+ gen uint64
+}
+
+// newPendingBatcher returns a batcher with the given silence window. A
+// non-positive window falls back to DefaultChatRunBatchWindow.
+func newPendingBatcher(window time.Duration) *pendingBatcher {
+ if window <= 0 {
+ window = DefaultChatRunBatchWindow
+ }
+ return &pendingBatcher{
+ window: window,
+ afterFunc: realAfterFunc,
+ pending: make(map[string]*pendingEntry),
+ }
+}
+
+func realAfterFunc(d time.Duration, fn func()) stoppableTimer {
+ return time.AfterFunc(d, fn)
+}
+
+// Schedule (re)arms the silence window for key. The most recent flush wins:
+// only session-level information is needed to fire a run, so keeping the latest
+// closure (which captures the latest installation/message context) suffices.
+// Calling Schedule after FlushAll runs the flush inline rather than dropping it
+// (the shutdown race where a message arrives after the drain has begun).
+func (b *pendingBatcher) Schedule(key string, flush func()) {
+ b.mu.Lock()
+ if b.stopped {
+ b.mu.Unlock()
+ flush()
+ return
+ }
+ b.seq++
+ gen := b.seq
+ fire := func() { b.onFire(key, gen) }
+ if e, ok := b.pending[key]; ok {
+ e.timer.Stop()
+ e.flush = flush
+ e.gen = gen
+ e.timer = b.afterFunc(b.window, fire)
+ b.mu.Unlock()
+ return
+ }
+ b.pending[key] = &pendingEntry{
+ flush: flush,
+ gen: gen,
+ timer: b.afterFunc(b.window, fire),
+ }
+ b.mu.Unlock()
+}
+
+// onFire runs the flush for key if it is still the live, armed generation. It
+// is the timer callback; in production it runs on time.AfterFunc's goroutine,
+// so the flush is naturally detached from the inbound path.
+func (b *pendingBatcher) onFire(key string, gen uint64) {
+ b.mu.Lock()
+ e, ok := b.pending[key]
+ if !ok || b.stopped || e.gen != gen {
+ b.mu.Unlock()
+ return
+ }
+ delete(b.pending, key)
+ flush := e.flush
+ b.inflight.Add(1)
+ b.mu.Unlock()
+
+ defer b.inflight.Done()
+ flush()
+}
+
+// FlushAll stops the batcher and runs every still-pending flush exactly once,
+// then waits for concurrently-firing flushes to finish. Call once from
+// graceful shutdown AFTER inbound delivery has stopped. After FlushAll the
+// batcher is terminal: later Schedule calls run inline.
+func (b *pendingBatcher) FlushAll() {
+ b.mu.Lock()
+ b.stopped = true
+ entries := make([]*pendingEntry, 0, len(b.pending))
+ for _, e := range b.pending {
+ e.timer.Stop()
+ entries = append(entries, e)
+ }
+ b.pending = make(map[string]*pendingEntry)
+ b.mu.Unlock()
+
+ for _, e := range entries {
+ e.flush()
+ }
+ b.inflight.Wait()
+}
+
+// pendingCount reports how many sessions currently have an armed window.
+func (b *pendingBatcher) pendingCount() int {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return len(b.pending)
+}
diff --git a/server/internal/integrations/lark/pending_batcher_test.go b/server/internal/integrations/channel/engine/batcher_test.go
similarity index 81%
rename from server/internal/integrations/lark/pending_batcher_test.go
rename to server/internal/integrations/channel/engine/batcher_test.go
index 844f1b132c..ff0d0b8e91 100644
--- a/server/internal/integrations/lark/pending_batcher_test.go
+++ b/server/internal/integrations/channel/engine/batcher_test.go
@@ -1,4 +1,4 @@
-package lark
+package engine
import (
"sync"
@@ -14,8 +14,6 @@ type fakeBatchTimer struct {
fired bool
}
-// Stop mirrors *time.Timer.Stop: returns true only if the timer was still
-// armed (not already stopped or fired).
func (t *fakeBatchTimer) Stop() bool {
if t.stopped || t.fired {
return false
@@ -24,9 +22,8 @@ func (t *fakeBatchTimer) Stop() bool {
return true
}
-// fakeTimerFactory hands out fakeBatchTimers and lets a test fire whichever
-// ones are currently armed — modelling the wall clock advancing past the
-// window for every pending session at once.
+// fakeTimerFactory hands out fakeBatchTimers and lets a test fire whichever are
+// currently armed — modelling the wall clock advancing past the window.
type fakeTimerFactory struct {
mu sync.Mutex
all []*fakeBatchTimer
@@ -40,8 +37,6 @@ func (f *fakeTimerFactory) after(_ time.Duration, fn func()) stoppableTimer {
return t
}
-// fireArmed invokes every timer that is armed (not stopped, not already
-// fired) right now.
func (f *fakeTimerFactory) fireArmed() {
f.mu.Lock()
armed := make([]*fakeBatchTimer, 0, len(f.all))
@@ -70,7 +65,7 @@ func (f *fakeTimerFactory) armedCount() int {
}
// newTestBatcher builds a batcher whose timers are driven by f. Shared with
-// dispatcher_test.go (same package) to drive the debounce coalescing test.
+// router_test.go (same package) to drive the debounce coalescing test.
func newTestBatcher(f *fakeTimerFactory) *pendingBatcher {
return &pendingBatcher{
window: DefaultChatRunBatchWindow,
@@ -123,10 +118,6 @@ func TestPendingBatcher_MultiSessionIndependent(t *testing.T) {
}
func TestPendingBatcher_StaleTimerFireIsNoop(t *testing.T) {
- // Reproduces the AfterFunc race: a timer fires concurrently with the
- // Stop() that was meant to cancel it after a reschedule. The
- // generation guard must make the stale fire a no-op so the burst still
- // flushes exactly once.
f := &fakeTimerFactory{}
b := newTestBatcher(f)
calls := 0
@@ -135,7 +126,6 @@ func TestPendingBatcher_StaleTimerFireIsNoop(t *testing.T) {
first := f.all[0]
b.Schedule("s", func() { calls++ }) // resets: cancels first, arms a new timer
- // First timer fires anyway despite having been Stop()ed.
first.fired = true
first.fn()
if calls != 0 {
@@ -164,8 +154,6 @@ func TestPendingBatcher_FlushAllDrainsPending(t *testing.T) {
t.Fatalf("FlushAll must clear pending state; got %d", got)
}
- // After FlushAll the batcher is terminal: a later Schedule runs inline
- // rather than silently dropping (the shutdown-race best-effort path).
ran := false
b.Schedule("d", func() { ran = true })
if !ran {
@@ -183,8 +171,6 @@ func TestNewPendingBatcher_DefaultsWindow(t *testing.T) {
}
func TestPendingBatcher_RealTimerFlushes(t *testing.T) {
- // Exercises the production afterFunc (time.AfterFunc) path with a short
- // real window so a mis-wired default would be caught.
b := newPendingBatcher(15 * time.Millisecond)
done := make(chan struct{})
b.Schedule("s", func() { close(done) })
diff --git a/server/internal/integrations/channel/engine/doc.go b/server/internal/integrations/channel/engine/doc.go
new file mode 100644
index 0000000000..a38d7f30d3
--- /dev/null
+++ b/server/internal/integrations/channel/engine/doc.go
@@ -0,0 +1,31 @@
+// Package engine is the channel-agnostic runtime that DRIVES the
+// channel.Channel adapters defined in the parent channel package. Stage-1
+// (MUL-3515) shipped the abstraction (Channel / InboundMessage /
+// OutboundMessage / Registry) but no engine consumed it; this package is
+// that engine — the "通用引擎" of MUL-3620, generalized out of the
+// Feishu-specific lark.Hub / lark.Dispatcher.
+//
+// It provides:
+//
+// 1. Supervisor — the per-installation connection supervisor generalized
+// from lark.Hub. It enumerates active installations across ALL
+// channel types (no hard-coded platform), fences each behind the WS
+// lease CAS so at most one replica connects per installation, builds
+// the platform Channel via the channel.Registry, drives its
+// Connect/Disconnect lifecycle with exponential backoff + jitter, and
+// restarts a connection whose credentials rotated.
+//
+// 2. Router — the inbound pipeline generalized from lark.Dispatcher. It is
+// the single shared channel.InboundHandler the Supervisor injects into
+// every Channel: it routes by ChannelType to that platform's registered
+// ResolverSet and runs the same ordered pipeline for every platform
+// (installation route → two-phase dedup → group @bot filter → identity +
+// membership → ensure session → append+mark → /issue → debounced run),
+// then drives the detached OutboundReplier + typing indicator.
+//
+// Everything platform-specific lives behind the resolver interfaces in
+// resolvers.go; adding a platform is "register a Factory + ResolverSet",
+// never "edit the engine". The engine depends only on the channel package,
+// the platform-agnostic service layer, and small interfaces; the DB-backed
+// store/resolvers and the concrete platform adapters are wired at boot.
+package engine
diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.go
new file mode 100644
index 0000000000..af5ba24f66
--- /dev/null
+++ b/server/internal/integrations/channel/engine/resolvers.go
@@ -0,0 +1,217 @@
+package engine
+
+import (
+ "context"
+ "errors"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// This file defines the pluggable seams the Router runs the inbound pipeline
+// through. Everything platform-specific lives behind these interfaces; a
+// platform registers a ResolverSet and the channel-agnostic Router stays
+// unchanged. The Feishu implementation is the first ResolverSet.
+
+// Outcome categorizes what the Router decided to do with an inbound message.
+// Values match the legacy lark outcomes 1:1 so behavior and dashboards carry
+// over unchanged.
+type Outcome string
+
+const (
+ OutcomeDropped Outcome = "dropped"
+ OutcomeNeedsBinding Outcome = "needs_binding"
+ OutcomeIngested Outcome = "ingested"
+ OutcomeAgentOffline Outcome = "agent_offline"
+ OutcomeAgentArchived Outcome = "agent_archived"
+)
+
+// DropReason enumerates the drop-audit categories. Values match the legacy
+// lark drop reasons 1:1.
+type DropReason string
+
+const (
+ DropReasonUnboundUser DropReason = "unbound_user"
+ DropReasonNonWorkspaceMember DropReason = "non_workspace_member"
+ DropReasonNotAddressedInGroup DropReason = "not_addressed_in_group"
+ DropReasonDuplicate DropReason = "duplicate"
+ DropReasonRevokedInstallation DropReason = "revoked_installation"
+ DropReasonInvalidEvent DropReason = "invalid_event"
+)
+
+// Result is the typed verdict the Router produces for one inbound message,
+// consumed by the outbound side (OutboundReplier / typing). It mirrors the
+// legacy lark.DispatchResult.
+type Result struct {
+ Outcome Outcome
+ DropReason DropReason
+ InstallationID pgtype.UUID
+ ChatSessionID pgtype.UUID
+ // Sender is the platform-native sender id (e.g. Lark open_id), so the
+ // replier can target a binding prompt back to the sender.
+ Sender string
+ IssueID pgtype.UUID
+ IssueNumber int32
+ IssueIdentifier string
+ IssueTitle string
+}
+
+// ResolvedInstallation is the channel-agnostic installation context the Router
+// needs after routing. Platform carries the adapter's own installation value
+// opaquely so the set's other ports (binder, replier, typing) reuse it without
+// a re-fetch; the Router never reads Platform.
+type ResolvedInstallation struct {
+ ID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ InstallerUserID pgtype.UUID
+ Active bool
+ Platform any
+}
+
+// ResolvedIdentity is the sender mapped to a Multica user.
+type ResolvedIdentity struct {
+ UserID pgtype.UUID
+}
+
+// EnsureSessionParams carries the inputs for SessionBinder.EnsureSession.
+// Sender is the resolved session creator (the sole human for p2p, the
+// installer for group chats — the Router decides which and passes it here).
+type EnsureSessionParams struct {
+ Installation ResolvedInstallation
+ Sender pgtype.UUID
+ Message channel.InboundMessage
+}
+
+// AppendParams carries the inputs for SessionBinder.AppendMessage. ClaimToken
+// is the dedup owner-fence token; the binder runs the dedup Mark INSIDE its
+// chat_message+session tx so the durable write and the Mark commit atomically.
+type AppendParams struct {
+ SessionID pgtype.UUID
+ Sender pgtype.UUID
+ InstallationID pgtype.UUID
+ Message channel.InboundMessage
+ ClaimToken pgtype.UUID
+}
+
+// AppendResult reports what AppendMessage decided.
+type AppendResult struct {
+ // IssueCommand is non-nil when the message was an /issue command.
+ IssueCommand *IssueCommand
+ // DedupMarked is true when AppendMessage finalized the dedup claim in its
+ // own tx; the Router then skips the post-pipeline finalize.
+ DedupMarked bool
+}
+
+// IssueCommand is the parsed /issue command.
+type IssueCommand struct {
+ Title string
+ Description string
+}
+
+// Sentinel errors the resolvers return so the Router can map them to the right
+// product outcome instead of an infrastructure failure.
+var (
+ // ErrInstallationNotFound: no installation matches the message's routing
+ // key → invalid_event drop.
+ ErrInstallationNotFound = errors.New("engine: installation not found")
+ // ErrSenderUnbound: the sender has no identity binding → needs_binding.
+ ErrSenderUnbound = errors.New("engine: sender unbound")
+ // ErrSenderNotMember: the sender is bound but not a workspace member →
+ // non_workspace_member drop.
+ ErrSenderNotMember = errors.New("engine: sender not a workspace member")
+ // ErrDuplicate: Claim found the message already processed / in flight →
+ // duplicate drop.
+ ErrDuplicate = errors.New("engine: duplicate message")
+ // ErrClaimLost: a concurrent reclaim rotated the dedup token mid-flight →
+ // treated as a duplicate.
+ ErrClaimLost = errors.New("engine: dedup claim lost")
+)
+
+// InstallationResolver routes an inbound message to its installation. The
+// adapter reads whatever platform routing key it needs from the message
+// (Source or Raw). Return ErrInstallationNotFound when none matches; return a
+// ResolvedInstallation with Active=false when it exists but is revoked.
+type InstallationResolver interface {
+ ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (ResolvedInstallation, error)
+}
+
+// IdentityResolver maps the message sender to a Multica user within the
+// installation, re-checking workspace membership. Return ErrSenderUnbound or
+// ErrSenderNotMember for the product cases.
+type IdentityResolver interface {
+ ResolveSender(ctx context.Context, inst ResolvedInstallation, msg channel.InboundMessage) (ResolvedIdentity, error)
+}
+
+// Deduper is the two-phase idempotency seam. Claim mints an owner-fence token
+// (ErrDuplicate when already processed / in flight); Mark/Release are fenced on
+// the token (a no-op on token mismatch is not an error).
+type Deduper interface {
+ Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (claimToken pgtype.UUID, err error)
+ Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error
+ Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error
+}
+
+// SessionBinder ensures the chat_session and appends the message (with the
+// in-tx dedup Mark). AppendMessage returns ErrClaimLost when the token was
+// rotated mid-flight.
+type SessionBinder interface {
+ EnsureSession(ctx context.Context, p EnsureSessionParams) (pgtype.UUID, error)
+ AppendMessage(ctx context.Context, p AppendParams) (AppendResult, error)
+}
+
+// Auditor records a dropped inbound event (no message body — drop-audit
+// policy). instID may be the zero UUID for installation-less events.
+type Auditor interface {
+ RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason DropReason) error
+}
+
+// OutboundReplier delivers the verdict-driven reply (binding prompt, offline /
+// archived notice, /issue confirmation). Optional; nil disables outbound
+// replies. Driven off the ACK critical path by the Router.
+type OutboundReplier interface {
+ Reply(ctx context.Context, inst ResolvedInstallation, msg channel.InboundMessage, res Result)
+}
+
+// TypingNotifier shows a "processing" indicator when a message is ingested.
+// Optional; nil disables it.
+type TypingNotifier interface {
+ OnIngested(ctx context.Context, inst ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID)
+}
+
+// ResolverSet is the per-platform bundle the Router runs the pipeline through.
+// Installation/Identity/Dedup/Session/Audit are required; Replier/Typing are
+// optional. OriginType is the issue.origin_type label written for /issue
+// commands from this channel (Feishu: "lark_chat").
+type ResolverSet struct {
+ Installation InstallationResolver
+ Identity IdentityResolver
+ Dedup Deduper
+ Session SessionBinder
+ Audit Auditor
+ Replier OutboundReplier
+ Typing TypingNotifier
+ OriginType string
+}
+
+// IssueCreator is the narrow subset of service.IssueService the Router needs
+// for the /issue command. Shared across platforms.
+type IssueCreator interface {
+ Create(ctx context.Context, p service.IssueCreateParams, opts service.IssueCreateOpts) (service.IssueCreateResult, error)
+}
+
+// TaskEnqueuer is the narrow subset of service.TaskService the Router needs to
+// trigger a chat run. Shared across platforms.
+type TaskEnqueuer interface {
+ EnqueueChatTask(ctx context.Context, session db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error)
+}
+
+// SessionReader reads the rows the debounced flush + /issue identifier need.
+// Shared across platforms; backed by *db.Queries (the channel-backed store).
+type SessionReader interface {
+ GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)
+ GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error)
+}
diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.go
new file mode 100644
index 0000000000..4705761870
--- /dev/null
+++ b/server/internal/integrations/channel/engine/router.go
@@ -0,0 +1,461 @@
+package engine
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/service"
+)
+
+// Router is the channel-agnostic inbound pipeline — the generalization of the
+// Feishu-only lark.Dispatcher (+ the Hub's handleEvent outbound seam). It is
+// the single shared channel.InboundHandler the Supervisor injects into every
+// Channel: a Channel translates its platform payload into a
+// channel.InboundMessage and calls Handle, which routes by ChannelType to that
+// platform's registered resolver set and runs the same ordered pipeline for
+// every platform — installation route → two-phase dedup → group @bot filter →
+// identity + membership → ensure session → append+mark → /issue → debounced
+// run trigger — then drives the detached outbound replier + typing indicator.
+//
+// The core contains no platform specifics: everything platform-shaped lives
+// behind the resolver interfaces (a feishu ResolverSet is the first
+// implementation). Adding a platform is "register a ResolverSet", not "edit
+// the Router".
+type Router struct {
+ mu sync.RWMutex
+ sets map[channel.Type]ResolverSet
+
+ issues IssueCreator
+ tasks TaskEnqueuer
+ reader SessionReader
+
+ batcher *pendingBatcher
+
+ replyTimeout time.Duration
+ replyWg sync.WaitGroup
+
+ logger *slog.Logger
+
+ pendingFreshMu sync.Mutex
+ pendingFresh map[string]bool
+}
+
+// Config tunes the Router. Zero values default.
+type RouterConfig struct {
+ // ReplyTimeout caps a single detached OutboundReplier.Reply / typing
+ // call. It runs off the connector ACK path, so it must stay strictly
+ // under the platform ACK deadline (Lark: 3s). Defaults to 2.5s.
+ ReplyTimeout time.Duration
+ Logger *slog.Logger
+}
+
+// NewRouter builds a Router around the shared (platform-agnostic) services:
+// the IssueCreator + TaskEnqueuer that /issue and chat runs go through, and a
+// SessionReader for the debounced flush. Register a platform's ResolverSet
+// with Register before Handle is called.
+func NewRouter(issues IssueCreator, tasks TaskEnqueuer, reader SessionReader, cfg RouterConfig) *Router {
+ if cfg.ReplyTimeout == 0 {
+ cfg.ReplyTimeout = 2500 * time.Millisecond
+ }
+ if cfg.Logger == nil {
+ cfg.Logger = slog.Default()
+ }
+ return &Router{
+ sets: make(map[channel.Type]ResolverSet),
+ issues: issues,
+ tasks: tasks,
+ reader: reader,
+ replyTimeout: cfg.ReplyTimeout,
+ logger: cfg.Logger,
+ pendingFresh: make(map[string]bool),
+ }
+}
+
+// Register binds a platform's ResolverSet under t. Call at boot, before Run.
+// Registering an empty Type or a set missing a required resolver is ignored.
+func (r *Router) Register(t channel.Type, set ResolverSet) {
+ if t == "" || set.Installation == nil || set.Identity == nil || set.Dedup == nil || set.Session == nil || set.Audit == nil {
+ r.logger.Warn("channel router: ignoring incomplete resolver set", "channel_type", string(t))
+ return
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.sets[t] = set
+}
+
+// EnableRunBatching installs the debouncer in front of the per-session run
+// trigger. Call once at boot. A non-positive window uses
+// DefaultChatRunBatchWindow. Without it, runs fire inline (used by tests).
+func (r *Router) EnableRunBatching(window time.Duration) {
+ r.batcher = newPendingBatcher(window)
+}
+
+// Drain flushes debounced run triggers and joins in-flight reply goroutines.
+// Call on shutdown AFTER the Supervisor has stopped delivering events.
+func (r *Router) Drain() {
+ if r.batcher != nil {
+ r.batcher.FlushAll()
+ }
+ r.replyWg.Wait()
+}
+
+// ErrNoResolverSet is returned by Handle when a message arrives for a channel
+// type that has no registered ResolverSet — a boot/registration bug. It is an
+// infrastructure error so the adapter surfaces it rather than silently
+// dropping.
+var ErrNoResolverSet = errors.New("channel router: no resolver set for channel type")
+
+// Handle is the shared channel.InboundHandler. It runs the pipeline and then
+// drives the detached outbound side; it returns a non-nil error only for
+// infrastructure failures (the adapter reconnects). Product outcomes (dropped,
+// needs-binding, …) are not errors.
+func (r *Router) Handle(ctx context.Context, msg channel.InboundMessage) error {
+ r.mu.RLock()
+ set, ok := r.sets[msg.Source.ChannelType]
+ r.mu.RUnlock()
+ if !ok {
+ r.logger.Error("channel router: no resolver set", "channel_type", string(msg.Source.ChannelType))
+ return ErrNoResolverSet
+ }
+
+ res, inst, err := r.dispatch(ctx, set, msg)
+ if err != nil {
+ r.logger.Error("channel router: dispatch error",
+ "channel_type", string(msg.Source.ChannelType),
+ "event_id", msg.EventID,
+ "error", err,
+ )
+ return err
+ }
+ r.logger.Debug("channel router: dispatch outcome",
+ "channel_type", string(msg.Source.ChannelType),
+ "event_id", msg.EventID,
+ "outcome", string(res.Outcome),
+ "drop_reason", string(res.DropReason),
+ )
+
+ // Typing indicator on ingest, detached so the reaction HTTP call never
+ // blocks the connector ACK path.
+ if res.Outcome == OutcomeIngested && set.Typing != nil {
+ go func() {
+ tctx, cancel := context.WithTimeout(context.Background(), r.replyTimeout)
+ defer cancel()
+ set.Typing.OnIngested(tctx, inst, msg, res.ChatSessionID)
+ }()
+ }
+ r.scheduleReply(set, inst, msg, res)
+ return nil
+}
+
+// dispatch runs the pipeline and returns the typed result plus the resolved
+// installation (needed by the outbound side). Mirrors lark.Dispatcher.Handle.
+func (r *Router) dispatch(ctx context.Context, set ResolverSet, msg channel.InboundMessage) (Result, ResolvedInstallation, error) {
+ // 1. Route to installation. The adapter maps the platform routing key
+ // (carried on the message) to its installation row. These drop
+ // branches run BEFORE the dedup claim because they have no valid
+ // installation to attach a claim to.
+ inst, err := set.Installation.ResolveInstallation(ctx, msg)
+ if err != nil {
+ if errors.Is(err, ErrInstallationNotFound) {
+ _ = set.Audit.RecordDrop(ctx, pgtype.UUID{}, msg, DropReasonInvalidEvent)
+ return Result{Outcome: OutcomeDropped, DropReason: DropReasonInvalidEvent}, ResolvedInstallation{}, nil
+ }
+ return Result{}, ResolvedInstallation{}, fmt.Errorf("resolve installation: %w", err)
+ }
+ if !inst.Active {
+ return r.drop(ctx, set, msg, inst.ID, DropReasonRevokedInstallation), inst, nil
+ }
+
+ // 2. Two-phase dedup claim with owner fencing — before group filter and
+ // identity so a reconnect replay cannot re-trigger a binding prompt,
+ // re-write a drop audit, or re-touch the session. Empty MessageID
+ // means there is no key to dedup by; skip the claim.
+ var claimToken pgtype.UUID
+ claimed := false
+ if msg.MessageID != "" {
+ token, err := set.Dedup.Claim(ctx, inst.ID, msg.MessageID)
+ if err != nil {
+ if errors.Is(err, ErrDuplicate) {
+ return r.drop(ctx, set, msg, inst.ID, DropReasonDuplicate), inst, nil
+ }
+ return Result{}, inst, fmt.Errorf("dedup claim: %w", err)
+ }
+ claimToken = token
+ claimed = true
+ }
+
+ res, finalize, err := r.processClaimed(ctx, set, msg, inst, claimToken)
+
+ if claimed {
+ r.applyFinalize(ctx, set, inst.ID, msg.MessageID, claimToken, finalize)
+ }
+
+ // ErrClaimLost: another worker holds the claim. Surface as duplicate.
+ if errors.Is(err, ErrClaimLost) {
+ return r.drop(ctx, set, msg, inst.ID, DropReasonDuplicate), inst, nil
+ }
+ return res, inst, err
+}
+
+// dedupFinalize tells dispatch how to land the claim row after processClaimed.
+type dedupFinalize int
+
+const (
+ finalizeNone dedupFinalize = iota
+ finalizeMark
+ finalizeRelease
+)
+
+// processClaimed runs the post-dedup pipeline. Mirrors
+// lark.Dispatcher.processClaimed; see its boundary contract per step.
+func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channel.InboundMessage, inst ResolvedInstallation, claimToken pgtype.UUID) (Result, dedupFinalize, error) {
+ // 3. Group-mention filter (group chats only), before identity so an
+ // unbound user's idle group chatter never spams a binding card.
+ if msg.Source.ChatType == channel.ChatTypeGroup && !msg.AddressedToBot {
+ return r.drop(ctx, set, msg, inst.ID, DropReasonNotAddressedInGroup), finalizeMark, nil
+ }
+
+ // 4. Identity check: map the platform sender to a Multica user and
+ // re-verify workspace membership (no binding->member FK; MUL-3515 §4).
+ identity, err := set.Identity.ResolveSender(ctx, inst, msg)
+ if err != nil {
+ switch {
+ case errors.Is(err, ErrSenderUnbound):
+ _ = set.Audit.RecordDrop(ctx, inst.ID, msg, DropReasonUnboundUser)
+ return Result{
+ Outcome: OutcomeNeedsBinding,
+ DropReason: DropReasonUnboundUser,
+ InstallationID: inst.ID,
+ Sender: msg.Source.SenderID,
+ }, finalizeMark, nil
+ case errors.Is(err, ErrSenderNotMember):
+ return r.drop(ctx, set, msg, inst.ID, DropReasonNonWorkspaceMember), finalizeMark, nil
+ default:
+ return Result{}, finalizeRelease, fmt.Errorf("resolve sender: %w", err)
+ }
+ }
+
+ // 5. Resolve the chat_session. Group sessions are created by the INSTALLER
+ // (stable workspace identity that won't churn with group membership);
+ // p2p sessions by the sole human sender.
+ sessionCreator := identity.UserID
+ if msg.Source.ChatType == channel.ChatTypeGroup {
+ sessionCreator = inst.InstallerUserID
+ }
+ sessionID, err := set.Session.EnsureSession(ctx, EnsureSessionParams{
+ Installation: inst,
+ Sender: sessionCreator,
+ Message: msg,
+ })
+ if err != nil {
+ // Single tx; an error rolled it back, nothing landed. Release.
+ return Result{}, finalizeRelease, fmt.Errorf("ensure chat session: %w", err)
+ }
+
+ // 6. Append message + in-tx dedup Mark — the durable transition point.
+ appendRes, err := set.Session.AppendMessage(ctx, AppendParams{
+ SessionID: sessionID,
+ Sender: identity.UserID,
+ InstallationID: inst.ID,
+ Message: msg,
+ ClaimToken: claimToken,
+ })
+ if err != nil {
+ if errors.Is(err, ErrClaimLost) {
+ return Result{}, finalizeNone, err
+ }
+ return Result{}, finalizeRelease, fmt.Errorf("append user message: %w", err)
+ }
+
+ // Post-append paths must NOT Release (chat_message + Mark already
+ // committed). Mark-again is a no-op, so finalizeNone — unless the binder
+ // did not Mark in-tx (defensive), then fall back to a post-pipeline Mark.
+ postAppendFinalize := finalizeNone
+ if !appendRes.DedupMarked {
+ postAppendFinalize = finalizeMark
+ }
+
+ res := Result{
+ Outcome: OutcomeIngested,
+ InstallationID: inst.ID,
+ ChatSessionID: sessionID,
+ Sender: msg.Source.SenderID,
+ }
+
+ // 7. /issue command, if present. chat_message is already durable; all
+ // error returns from here signal finalizeNone (or the defensive Mark).
+ if appendRes.IssueCommand != nil {
+ issueRes, err := r.createIssue(ctx, inst, set.OriginType, identity.UserID, sessionID, *appendRes.IssueCommand)
+ if err != nil {
+ return Result{}, postAppendFinalize, fmt.Errorf("create issue from command: %w", err)
+ }
+ res.IssueID = issueRes.Issue.ID
+ res.IssueNumber = issueRes.Issue.Number
+ res.IssueTitle = issueRes.Issue.Title
+ if ws, werr := r.reader.GetWorkspace(ctx, inst.WorkspaceID); werr == nil && ws.IssuePrefix != "" {
+ res.IssueIdentifier = fmt.Sprintf("%s-%d", ws.IssuePrefix, issueRes.Issue.Number)
+ } else {
+ res.IssueIdentifier = fmt.Sprintf("#%d", issueRes.Issue.Number)
+ }
+ }
+
+ // 8. Debounce the run trigger. The synchronous outcome is OutcomeIngested
+ // with no TaskID — the task row is created at flush. identity.UserID is
+ // THIS message's sender (the task initiator), deliberately not the
+ // session creator (group sessions are creator=installer). Latest sender
+ // in a window wins (MUL-2645).
+ r.scheduleRun(set, inst, msg, sessionID, identity.UserID)
+ return res, postAppendFinalize, nil
+}
+
+// scheduleRun hands the per-session run trigger to the debouncer (or fires it
+// inline when batching is disabled).
+func (r *Router) scheduleRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID) {
+ key := keyForSession(sessionID)
+ fresh := msg.ForceFresh
+ if r.batcher == nil {
+ r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, fresh)
+ return
+ }
+ if fresh {
+ r.markPendingFresh(key)
+ }
+ flush := func() {
+ r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, r.takePendingFresh(key, fresh))
+ }
+ r.batcher.Schedule(key, flush)
+}
+
+// chatRunFlushTimeout bounds the detached flush (session reload + enqueue +
+// notice), which runs on its own fresh context.
+const chatRunFlushTimeout = 10 * time.Second
+
+// flushChatRun is the debounced run-trigger: reload session, enqueue exactly
+// one chat task for the window, and emit the offline/archived notice (only
+// known here now) via the replier. Errors are logged, not returned.
+func (r *Router) flushChatRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, forceFresh bool) {
+ ctx, cancel := context.WithTimeout(context.Background(), chatRunFlushTimeout)
+ defer cancel()
+
+ session, err := r.reader.GetChatSession(ctx, sessionID)
+ if err != nil {
+ r.logger.Error("channel router: flush reload chat session failed",
+ "chat_session_id", uuidString(sessionID), "err", err.Error())
+ return
+ }
+ if _, err := r.tasks.EnqueueChatTask(ctx, session, initiatorUserID, forceFresh); err != nil {
+ switch {
+ case errors.Is(err, service.ErrChatTaskAgentNoRuntime):
+ r.emitFlushReply(ctx, set, inst, msg, sessionID, OutcomeAgentOffline)
+ case errors.Is(err, service.ErrChatTaskAgentArchived):
+ r.emitFlushReply(ctx, set, inst, msg, sessionID, OutcomeAgentArchived)
+ default:
+ r.logger.Error("channel router: flush enqueue chat task failed",
+ "chat_session_id", uuidString(sessionID), "err", err.Error())
+ }
+ }
+}
+
+func (r *Router) markPendingFresh(key string) {
+ r.pendingFreshMu.Lock()
+ defer r.pendingFreshMu.Unlock()
+ r.pendingFresh[key] = true
+}
+
+func (r *Router) takePendingFresh(key string, fallback bool) bool {
+ r.pendingFreshMu.Lock()
+ defer r.pendingFreshMu.Unlock()
+ fresh := fallback || r.pendingFresh[key]
+ delete(r.pendingFresh, key)
+ return fresh
+}
+
+// emitFlushReply delivers an offline/archived notice for a flushed run.
+func (r *Router) emitFlushReply(ctx context.Context, set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, outcome Outcome) {
+ if set.Replier == nil {
+ return
+ }
+ set.Replier.Reply(ctx, inst, msg, Result{
+ Outcome: outcome,
+ InstallationID: inst.ID,
+ ChatSessionID: sessionID,
+ Sender: msg.Source.SenderID,
+ })
+}
+
+// scheduleReply detaches the OutboundReplier from the ACK critical path. The
+// reply goroutine uses a fresh context with a ReplyTimeout deadline so it is
+// independent of the inbound emit ctx (which the adapter cancels when its
+// receive loop exits). A nil replier short-circuits — no goroutine.
+func (r *Router) scheduleReply(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, res Result) {
+ if set.Replier == nil {
+ return
+ }
+ r.replyWg.Add(1)
+ go func() {
+ defer r.replyWg.Done()
+ ctx, cancel := context.WithTimeout(context.Background(), r.replyTimeout)
+ defer cancel()
+ set.Replier.Reply(ctx, inst, msg, res)
+ if ctx.Err() == context.DeadlineExceeded {
+ r.logger.Warn("channel router: outbound reply timed out",
+ "event_id", msg.EventID, "outcome", string(res.Outcome),
+ "timeout", r.replyTimeout.String())
+ }
+ }()
+}
+
+// keyForSession is the batcher key. chat_session_id is globally unique.
+func keyForSession(sessionID pgtype.UUID) string {
+ return string(sessionID.Bytes[:])
+}
+
+// applyFinalize flips the in-flight claim row to its terminal state,
+// token-fenced. Best-effort: a transport failure cannot abort the outcome.
+func (r *Router) applyFinalize(ctx context.Context, set ResolverSet, instID pgtype.UUID, messageID string, claimToken pgtype.UUID, action dedupFinalize) {
+ switch action {
+ case finalizeMark:
+ _ = set.Dedup.Mark(ctx, instID, messageID, claimToken)
+ case finalizeRelease:
+ _ = set.Dedup.Release(ctx, instID, messageID, claimToken)
+ case finalizeNone:
+ }
+}
+
+func (r *Router) drop(ctx context.Context, set ResolverSet, msg channel.InboundMessage, instID pgtype.UUID, reason DropReason) Result {
+ _ = set.Audit.RecordDrop(ctx, instID, msg, reason)
+ return Result{Outcome: OutcomeDropped, DropReason: reason, InstallationID: instID}
+}
+
+func (r *Router) createIssue(ctx context.Context, inst ResolvedInstallation, originType string, creatorUserID, sessionID pgtype.UUID, cmd IssueCommand) (service.IssueCreateResult, error) {
+ if cmd.Title == "" {
+ return service.IssueCreateResult{}, ErrEmptyIssueTitle
+ }
+ params := service.IssueCreateParams{
+ WorkspaceID: inst.WorkspaceID,
+ Title: cmd.Title,
+ Description: pgtype.Text{String: cmd.Description, Valid: cmd.Description != ""},
+ Status: "todo",
+ Priority: "none",
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ AssigneeID: inst.AgentID,
+ CreatorType: "member",
+ CreatorID: creatorUserID,
+ OriginType: pgtype.Text{String: originType, Valid: originType != ""},
+ OriginID: sessionID,
+ }
+ return r.issues.Create(ctx, params, service.IssueCreateOpts{})
+}
+
+// ErrEmptyIssueTitle is returned by createIssue when /issue has no title and
+// the binder's previous-message fallback found nothing usable.
+var ErrEmptyIssueTitle = errors.New("issue title is empty")
+
+var _ channel.InboundHandler = (*Router)(nil).Handle
diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.go
new file mode 100644
index 0000000000..797b31a454
--- /dev/null
+++ b/server/internal/integrations/channel/engine/router_test.go
@@ -0,0 +1,506 @@
+package engine
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// ---- fakes ----
+
+type fakeInstaller struct {
+ inst ResolvedInstallation
+ err error
+}
+
+func (f *fakeInstaller) ResolveInstallation(_ context.Context, _ channel.InboundMessage) (ResolvedInstallation, error) {
+ return f.inst, f.err
+}
+
+type fakeIdentity struct {
+ id ResolvedIdentity
+ err error
+}
+
+func (f *fakeIdentity) ResolveSender(_ context.Context, _ ResolvedInstallation, _ channel.InboundMessage) (ResolvedIdentity, error) {
+ return f.id, f.err
+}
+
+type fakeDedup struct {
+ mu sync.Mutex
+ token pgtype.UUID
+ claimErr error
+ markCalls int
+ relCalls int
+ claimCalls int
+}
+
+func (f *fakeDedup) Claim(_ context.Context, _ pgtype.UUID, _ string) (pgtype.UUID, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.claimCalls++
+ if f.claimErr != nil {
+ return pgtype.UUID{}, f.claimErr
+ }
+ return f.token, nil
+}
+func (f *fakeDedup) Mark(_ context.Context, _ pgtype.UUID, _ string, _ pgtype.UUID) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.markCalls++
+ return nil
+}
+func (f *fakeDedup) Release(_ context.Context, _ pgtype.UUID, _ string, _ pgtype.UUID) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.relCalls++
+ return nil
+}
+func (f *fakeDedup) marks() int { f.mu.Lock(); defer f.mu.Unlock(); return f.markCalls }
+func (f *fakeDedup) releases() int { f.mu.Lock(); defer f.mu.Unlock(); return f.relCalls }
+
+type fakeBinder struct {
+ ensureID pgtype.UUID
+ ensureErr error
+ appendResult AppendResult
+ appendErr error
+ lastEnsure EnsureSessionParams
+ lastAppend AppendParams
+}
+
+func (f *fakeBinder) EnsureSession(_ context.Context, p EnsureSessionParams) (pgtype.UUID, error) {
+ f.lastEnsure = p
+ return f.ensureID, f.ensureErr
+}
+func (f *fakeBinder) AppendMessage(_ context.Context, p AppendParams) (AppendResult, error) {
+ f.lastAppend = p
+ return f.appendResult, f.appendErr
+}
+
+type fakeAuditor struct {
+ mu sync.Mutex
+ drops []DropReason
+}
+
+func (f *fakeAuditor) RecordDrop(_ context.Context, _ pgtype.UUID, _ channel.InboundMessage, reason DropReason) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.drops = append(f.drops, reason)
+ return nil
+}
+func (f *fakeAuditor) last() (DropReason, bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if len(f.drops) == 0 {
+ return "", false
+ }
+ return f.drops[len(f.drops)-1], true
+}
+
+type fakeReplier struct {
+ mu sync.Mutex
+ results []Result
+}
+
+func (f *fakeReplier) Reply(_ context.Context, _ ResolvedInstallation, _ channel.InboundMessage, res Result) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.results = append(f.results, res)
+}
+func (f *fakeReplier) calls() []Result {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]Result(nil), f.results...)
+}
+
+type fakeTyping struct {
+ mu sync.Mutex
+ count int
+}
+
+func (f *fakeTyping) OnIngested(_ context.Context, _ ResolvedInstallation, _ channel.InboundMessage, _ pgtype.UUID) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.count++
+}
+func (f *fakeTyping) calls() int { f.mu.Lock(); defer f.mu.Unlock(); return f.count }
+
+type fakeIssues struct {
+ called bool
+ params service.IssueCreateParams
+ result service.IssueCreateResult
+ err error
+}
+
+func (f *fakeIssues) Create(_ context.Context, p service.IssueCreateParams, _ service.IssueCreateOpts) (service.IssueCreateResult, error) {
+ f.called = true
+ f.params = p
+ return f.result, f.err
+}
+
+type fakeTasks struct {
+ mu sync.Mutex
+ called bool
+ forceFresh bool
+ initiator pgtype.UUID
+ err error
+}
+
+func (f *fakeTasks) EnqueueChatTask(_ context.Context, _ db.ChatSession, initiator pgtype.UUID, forceFresh bool) (db.AgentTaskQueue, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.called = true
+ f.forceFresh = forceFresh
+ f.initiator = initiator
+ return db.AgentTaskQueue{}, f.err
+}
+func (f *fakeTasks) wasCalled() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.called }
+func (f *fakeTasks) freshArg() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.forceFresh }
+
+type fakeReader struct {
+ session db.ChatSession
+ ws db.Workspace
+ sessErr error
+}
+
+func (f *fakeReader) GetChatSession(_ context.Context, _ pgtype.UUID) (db.ChatSession, error) {
+ return f.session, f.sessErr
+}
+func (f *fakeReader) GetWorkspace(_ context.Context, _ pgtype.UUID) (db.Workspace, error) {
+ return f.ws, nil
+}
+
+// ---- harness ----
+
+func activeResolved(t *testing.T) ResolvedInstallation {
+ return ResolvedInstallation{
+ ID: uuidFromString(t, "11111111-1111-1111-1111-111111111111"),
+ WorkspaceID: uuidFromString(t, "22222222-2222-2222-2222-222222222222"),
+ AgentID: uuidFromString(t, "33333333-3333-3333-3333-333333333333"),
+ InstallerUserID: uuidFromString(t, "99999999-9999-9999-9999-999999999999"),
+ Active: true,
+ }
+}
+
+func p2pMessage(t *testing.T) channel.InboundMessage {
+ return channel.InboundMessage{
+ EventID: "evt-1",
+ MessageID: "om-1",
+ Type: channel.MsgTypeText,
+ Text: "hello",
+ Source: channel.Source{
+ ChannelType: channel.TypeFeishu,
+ ChatID: "oc_chat",
+ ChatType: channel.ChatTypeP2P,
+ SenderID: "ou_user_a",
+ },
+ }
+}
+
+type harness struct {
+ router *Router
+ inst *fakeInstaller
+ ident *fakeIdentity
+ dedup *fakeDedup
+ binder *fakeBinder
+ audit *fakeAuditor
+ replier *fakeReplier
+ typing *fakeTyping
+ issues *fakeIssues
+ tasks *fakeTasks
+ reader *fakeReader
+}
+
+func newHarness(t *testing.T) *harness {
+ t.Helper()
+ h := &harness{
+ inst: &fakeInstaller{inst: activeResolved(t)},
+ ident: &fakeIdentity{id: ResolvedIdentity{UserID: uuidFromString(t, "44444444-4444-4444-4444-444444444444")}},
+ dedup: &fakeDedup{token: uuidFromString(t, "55555555-5555-5555-5555-555555555555")},
+ binder: &fakeBinder{ensureID: uuidFromString(t, "66666666-6666-6666-6666-666666666666"), appendResult: AppendResult{DedupMarked: true}},
+ audit: &fakeAuditor{},
+ replier: &fakeReplier{},
+ typing: &fakeTyping{},
+ issues: &fakeIssues{},
+ tasks: &fakeTasks{},
+ reader: &fakeReader{ws: db.Workspace{IssuePrefix: "MUL"}},
+ }
+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{Logger: discardLogger()})
+ h.router.Register(channel.TypeFeishu, ResolverSet{
+ Installation: h.inst,
+ Identity: h.ident,
+ Dedup: h.dedup,
+ Session: h.binder,
+ Audit: h.audit,
+ Replier: h.replier,
+ Typing: h.typing,
+ OriginType: "lark_chat",
+ })
+ return h
+}
+
+func TestRouter_NoResolverSet_ReturnsError(t *testing.T) {
+ h := newHarness(t)
+ msg := p2pMessage(t)
+ msg.Source.ChannelType = channel.Type("slack")
+ if err := h.router.Handle(context.Background(), msg); !errors.Is(err, ErrNoResolverSet) {
+ t.Fatalf("expected ErrNoResolverSet, got %v", err)
+ }
+}
+
+func TestRouter_InstallationNotFound_Drops(t *testing.T) {
+ h := newHarness(t)
+ h.inst.err = ErrInstallationNotFound
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("drop must not be an error: %v", err)
+ }
+ if r, _ := h.audit.last(); r != DropReasonInvalidEvent {
+ t.Fatalf("expected invalid_event audit, got %q", r)
+ }
+ if h.dedup.claimCalls != 0 {
+ t.Fatalf("must not claim dedup before installation routing")
+ }
+}
+
+func TestRouter_RevokedInstallation_Drops(t *testing.T) {
+ h := newHarness(t)
+ h.inst.inst.Active = false
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if r, _ := h.audit.last(); r != DropReasonRevokedInstallation {
+ t.Fatalf("expected revoked_installation, got %q", r)
+ }
+}
+
+func TestRouter_Duplicate_Drops(t *testing.T) {
+ h := newHarness(t)
+ h.dedup.claimErr = ErrDuplicate
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if r, _ := h.audit.last(); r != DropReasonDuplicate {
+ t.Fatalf("expected duplicate, got %q", r)
+ }
+}
+
+func TestRouter_GroupNotAddressed_Drops(t *testing.T) {
+ h := newHarness(t)
+ msg := p2pMessage(t)
+ msg.Source.ChatType = channel.ChatTypeGroup
+ msg.AddressedToBot = false
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if r, _ := h.audit.last(); r != DropReasonNotAddressedInGroup {
+ t.Fatalf("expected not_addressed_in_group, got %q", r)
+ }
+ if h.dedup.marks() != 1 {
+ t.Fatalf("group-filter drop must finalize Mark (1), got %d", h.dedup.marks())
+ }
+}
+
+func TestRouter_UnboundSender_NeedsBinding(t *testing.T) {
+ h := newHarness(t)
+ h.ident.err = ErrSenderUnbound
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if r, _ := h.audit.last(); r != DropReasonUnboundUser {
+ t.Fatalf("expected unbound_user audit, got %q", r)
+ }
+ if h.dedup.marks() != 1 {
+ t.Fatalf("unbound drop must finalize Mark, got %d", h.dedup.marks())
+ }
+ if !waitFor(time.Second, func() bool {
+ for _, r := range h.replier.calls() {
+ if r.Outcome == OutcomeNeedsBinding && r.Sender == "ou_user_a" {
+ return true
+ }
+ }
+ return false
+ }) {
+ t.Fatalf("expected a NeedsBinding reply targeting the sender")
+ }
+}
+
+func TestRouter_NonMember_Drops(t *testing.T) {
+ h := newHarness(t)
+ h.ident.err = ErrSenderNotMember
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if r, _ := h.audit.last(); r != DropReasonNonWorkspaceMember {
+ t.Fatalf("expected non_workspace_member, got %q", r)
+ }
+}
+
+func TestRouter_EnsureSessionError_Releases(t *testing.T) {
+ h := newHarness(t)
+ h.binder.ensureErr = errors.New("db down")
+ err := h.router.Handle(context.Background(), p2pMessage(t))
+ if err == nil {
+ t.Fatal("ensure-session infra error must surface to the caller")
+ }
+ if h.dedup.releases() != 1 {
+ t.Fatalf("ensure-session error must Release the claim (1), got %d", h.dedup.releases())
+ }
+}
+
+func TestRouter_Ingested_InTxMark_FinalizeNone(t *testing.T) {
+ h := newHarness(t)
+ h.reader.session = db.ChatSession{}
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ // AppendMessage marked in-tx (DedupMarked=true) -> no post-pipeline Mark.
+ if h.dedup.marks() != 0 {
+ t.Fatalf("in-tx Mark must skip post-pipeline finalize Mark, got %d", h.dedup.marks())
+ }
+ if h.dedup.releases() != 0 {
+ t.Fatalf("a durable ingest must not Release, got %d", h.dedup.releases())
+ }
+ if !h.tasks.wasCalled() {
+ t.Fatalf("ingest must trigger a chat run (inline, no batcher)")
+ }
+ if !waitFor(time.Second, func() bool { return h.typing.calls() == 1 }) {
+ t.Fatalf("ingest must show the typing indicator")
+ }
+}
+
+func TestRouter_ClaimLost_Drops(t *testing.T) {
+ h := newHarness(t)
+ h.binder.appendErr = ErrClaimLost
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("ErrClaimLost must be a duplicate drop, not an error: %v", err)
+ }
+ if r, _ := h.audit.last(); r != DropReasonDuplicate {
+ t.Fatalf("expected duplicate, got %q", r)
+ }
+ if h.dedup.releases() != 0 || h.dedup.marks() != 0 {
+ t.Fatalf("ErrClaimLost must finalizeNone (no Mark/Release); marks=%d rel=%d", h.dedup.marks(), h.dedup.releases())
+ }
+}
+
+func TestRouter_IssueCommand_Creates(t *testing.T) {
+ h := newHarness(t)
+ h.binder.appendResult = AppendResult{DedupMarked: true, IssueCommand: &IssueCommand{Title: "Fix login", Description: "details"}}
+ h.issues.result = service.IssueCreateResult{Issue: db.Issue{ID: uuidFromString(t, "77777777-7777-7777-7777-777777777777"), Number: 42, Title: "Fix login"}}
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !h.issues.called {
+ t.Fatal("expected issue create")
+ }
+ if h.issues.params.OriginType.String != "lark_chat" {
+ t.Fatalf("origin_type must come from the resolver set, got %q", h.issues.params.OriginType.String)
+ }
+ if !waitFor(time.Second, func() bool {
+ for _, r := range h.replier.calls() {
+ if r.IssueIdentifier == "MUL-42" && r.IssueTitle == "Fix login" {
+ return true
+ }
+ }
+ return false
+ }) {
+ t.Fatalf("expected an issue-created reply with the workspace-qualified identifier")
+ }
+}
+
+func TestRouter_GroupSessionCreatorIsInstaller(t *testing.T) {
+ h := newHarness(t)
+ msg := p2pMessage(t)
+ msg.Source.ChatType = channel.ChatTypeGroup
+ msg.AddressedToBot = true
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if h.binder.lastEnsure.Sender != h.inst.inst.InstallerUserID {
+ t.Fatalf("group session creator must be the installer")
+ }
+ // And the run initiator is the sender, not the installer.
+ if h.tasks.initiator != h.ident.id.UserID {
+ t.Fatalf("run initiator must be the message sender")
+ }
+}
+
+func TestRouter_P2PSessionCreatorIsSender(t *testing.T) {
+ h := newHarness(t)
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if h.binder.lastEnsure.Sender != h.ident.id.UserID {
+ t.Fatalf("p2p session creator must be the sender")
+ }
+}
+
+func TestRouter_FlushOffline_RepliesAgentOffline(t *testing.T) {
+ h := newHarness(t)
+ h.tasks.err = service.ErrChatTaskAgentNoRuntime
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ // Inline flush (no batcher) emits the offline notice synchronously via replier.
+ found := false
+ for _, r := range h.replier.calls() {
+ if r.Outcome == OutcomeAgentOffline {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("agent-no-runtime must emit an AgentOffline reply")
+ }
+}
+
+func TestRouter_ForceFresh_Propagates(t *testing.T) {
+ h := newHarness(t)
+ msg := p2pMessage(t)
+ msg.ForceFresh = true
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !h.tasks.freshArg() {
+ t.Fatalf("ForceFresh must propagate to EnqueueChatTask")
+ }
+}
+
+func TestRouter_DrainJoinsReplies(t *testing.T) {
+ h := newHarness(t)
+ h.ident.err = ErrSenderUnbound // triggers a NeedsBinding reply goroutine
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ done := make(chan struct{})
+ go func() { h.router.Drain(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("Drain did not join the reply goroutine")
+ }
+ if len(h.replier.calls()) != 1 {
+ t.Fatalf("expected exactly one reply after drain, got %d", len(h.replier.calls()))
+ }
+}
+
+func TestRouter_EmptyMessageID_SkipsDedup(t *testing.T) {
+ h := newHarness(t)
+ msg := p2pMessage(t)
+ msg.MessageID = ""
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if h.dedup.claimCalls != 0 {
+ t.Fatalf("empty message id must skip the dedup claim, got %d", h.dedup.claimCalls)
+ }
+ if !h.tasks.wasCalled() {
+ t.Fatalf("message must still ingest without a dedup key")
+ }
+}
diff --git a/server/internal/integrations/channel/engine/supervisor.go b/server/internal/integrations/channel/engine/supervisor.go
new file mode 100644
index 0000000000..6afceba26d
--- /dev/null
+++ b/server/internal/integrations/channel/engine/supervisor.go
@@ -0,0 +1,663 @@
+package engine
+
+import (
+ "context"
+ cryptorand "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ mathrand "math/rand/v2"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// Installation is the channel-agnostic view of one channel_installation
+// row the Supervisor needs to drive a connection. It is intentionally
+// minimal: the engine never reads platform credentials directly — it
+// hands Config to the registry factory, which decodes what it needs — and
+// it never branches on ChannelType beyond using it to pick the factory.
+type Installation struct {
+ // ID is the channel_installation primary key. It is the lease key and
+ // the supervisors-map key (one supervisor goroutine per ID).
+ ID pgtype.UUID
+
+ // ChannelType selects the registry Factory that builds this row's
+ // Channel ("feishu", "slack", …).
+ ChannelType channel.Type
+
+ // Fingerprint condenses the credential-bearing config into an opaque
+ // string. Two rows with equal fingerprints are interchangeable to the
+ // supervisor; any change between sweeps tears the running connection
+ // down and rebuilds it so a re-installed channel (fresh app_id /
+ // secret / region) is picked up instead of running indefinitely
+ // against stale credentials. The store computes it; the engine treats
+ // it as opaque.
+ Fingerprint string
+
+ // Config is the platform credential/config blob, passed verbatim to
+ // the registry Factory as channel.Config.Raw. The engine never reads
+ // inside it.
+ Config json.RawMessage
+}
+
+// AcquireLeaseParams fences the WS supervisor lease for an installation.
+// The store performs the CAS: grant when the row is unleased, expired, or
+// already held by Token (renewal); otherwise report it held elsewhere via
+// ErrLeaseNotAcquired.
+type AcquireLeaseParams struct {
+ ID pgtype.UUID
+ Token string
+ ExpiresAt time.Time
+}
+
+// ReleaseLeaseParams releases a WS supervisor lease the caller still
+// holds. The store must fence on Token so a stale release from a rotation
+// predecessor cannot clobber a successor's freshly acquired lease.
+type ReleaseLeaseParams struct {
+ ID pgtype.UUID
+ Token string
+}
+
+// ErrLeaseNotAcquired is the sentinel a store returns from AcquireWSLease
+// when the CAS predicate did not match — i.e. another replica (or an
+// in-process predecessor mid-rotation) holds a live lease. The Supervisor
+// treats it as "not ours yet, retry later", distinct from a transport
+// error. Stores wrap their backend's no-rows signal into this.
+var ErrLeaseNotAcquired = errors.New("engine: ws lease held elsewhere")
+
+// InstallationStore is the narrow data seam the Supervisor needs:
+// enumerate active installations across every channel type and manage the
+// per-installation WS lease. The application backs it with the generalized
+// channel_* tables; tests substitute a fake.
+type InstallationStore interface {
+ // ListActiveInstallations returns every active installation across ALL
+ // channel types. There is no per-platform filter here — that hard-coded
+ // "feishu" was the whole limitation MUL-3620 removes.
+ ListActiveInstallations(ctx context.Context) ([]Installation, error)
+
+ // AcquireWSLease grants or renews the lease, or returns
+ // ErrLeaseNotAcquired when it is held elsewhere.
+ AcquireWSLease(ctx context.Context, arg AcquireLeaseParams) error
+
+ // ReleaseWSLease releases a lease the caller holds (token-fenced).
+ ReleaseWSLease(ctx context.Context, arg ReleaseLeaseParams) error
+}
+
+// Config tunes the Supervisor's lifecycle loops. All fields have sensible
+// production defaults via withDefaults; tests typically set Now and Logger
+// to inject determinism.
+type Config struct {
+ // LeaseTTL is how long a successful AcquireWSLease grant is valid
+ // before another replica may steal it. Renewals happen on the tighter
+ // LeaseRenewInterval; the gap absorbs transient DB blips.
+ LeaseTTL time.Duration
+
+ // LeaseRenewInterval is the cadence at which the Supervisor re-acquires
+ // leases it already owns. MUST be substantially less than LeaseTTL so a
+ // single missed renewal does not yield the lease.
+ LeaseRenewInterval time.Duration
+
+ // PollInterval is how often the Supervisor scans for installations to
+ // take over (new ones, or ones whose lease expired on another replica).
+ PollInterval time.Duration
+
+ // MinBackoff / MaxBackoff bound the per-installation reconnect
+ // schedule: start at MinBackoff, double after each consecutive failure
+ // (capped at MaxBackoff), reset on any connection that lived at least
+ // ResetBackoffAfter.
+ MinBackoff time.Duration
+ MaxBackoff time.Duration
+ ResetBackoffAfter time.Duration
+
+ // LeaseReleaseTimeout caps a single ReleaseWSLease call. The release
+ // runs on a fresh context (the parent ctx is already cancelled by the
+ // time we release on shutdown), so without a deadline a frozen pool
+ // could hang shutdown indefinitely. On timeout the lease falls back to
+ // natural TTL expiry on the next replica.
+ LeaseReleaseTimeout time.Duration
+
+ // DisconnectTimeout caps a single Channel.Disconnect call made after a
+ // connection ends, for the same reason as LeaseReleaseTimeout.
+ DisconnectTimeout time.Duration
+
+ // ShutdownTimeout bounds how long Wait blocks for supervisor goroutines
+ // after their parent ctx is cancelled. Wait itself does not enforce it;
+ // callers pass it to WaitWithTimeout. Exposed so boot and tests share a
+ // default.
+ ShutdownTimeout time.Duration
+
+ // Now returns the current time. Injected for tests; production uses
+ // time.Now.
+ Now func() time.Time
+
+ // Logger optional; defaults to slog.Default.
+ Logger *slog.Logger
+}
+
+func (c Config) withDefaults() Config {
+ if c.LeaseTTL == 0 {
+ c.LeaseTTL = 90 * time.Second
+ }
+ if c.LeaseRenewInterval == 0 {
+ c.LeaseRenewInterval = 30 * time.Second
+ }
+ if c.PollInterval == 0 {
+ c.PollInterval = 30 * time.Second
+ }
+ if c.MinBackoff == 0 {
+ c.MinBackoff = 2 * time.Second
+ }
+ if c.MaxBackoff == 0 {
+ c.MaxBackoff = 60 * time.Second
+ }
+ if c.ResetBackoffAfter == 0 {
+ c.ResetBackoffAfter = 60 * time.Second
+ }
+ if c.LeaseReleaseTimeout == 0 {
+ c.LeaseReleaseTimeout = 5 * time.Second
+ }
+ if c.DisconnectTimeout == 0 {
+ c.DisconnectTimeout = 5 * time.Second
+ }
+ if c.ShutdownTimeout == 0 {
+ c.ShutdownTimeout = 15 * time.Second
+ }
+ if c.Now == nil {
+ c.Now = time.Now
+ }
+ if c.Logger == nil {
+ c.Logger = slog.Default()
+ }
+ return c
+}
+
+// Supervisor owns the per-installation supervisor goroutines that keep a
+// long-running connection per active installation, across every channel
+// type. It enforces the multi-replica safety rule via the WS lease CAS —
+// at most one Supervisor globally holds the lease for any installation, so
+// duplicate event consumption across replicas is impossible.
+//
+// It is the channel-agnostic generalization of lark.Hub: where the Hub
+// drove a Feishu-only EventConnector built by a ConnectorFactory, the
+// Supervisor drives any channel.Channel built by the channel.Registry, and
+// enumerates installations of every channel type rather than just feishu.
+//
+// Lifecycle:
+//
+// sup := NewSupervisor(store, registry, handler, engine.Config{})
+// go sup.Run(ctx) // returns when ctx is cancelled
+// ... ctx cancellation triggers ...
+// sup.Wait() // joins on every per-installation goroutine
+type Supervisor struct {
+ store InstallationStore
+ registry *channel.Registry
+ handler channel.InboundHandler
+ cfg Config
+
+ // nodeID is the per-process lease ownership token. AcquireWSLease
+ // treats matching tokens as "this is us, renew", so a stable nodeID
+ // keeps renewals from ping-ponging between replicas.
+ nodeID string
+
+ mu sync.Mutex
+ // supervisors keys each in-flight supervisor goroutine by
+ // installation_id, alongside the credentials fingerprint the channel
+ // was built with. When the row's fingerprint drifts (re-install), the
+ // next sweep tears the connection down and rebuilds it with fresh
+ // credentials.
+ supervisors map[string]supervisorEntry
+ // supervisorGen is the source of the monotonic gen counter stored on
+ // each entry. Bumped under mu when a new entry is minted (initial start
+ // or rotation restart).
+ supervisorGen uint64
+ wg sync.WaitGroup
+ stopped bool
+ stopChan chan struct{}
+}
+
+// supervisorEntry is the per-installation state the Supervisor holds on
+// each running goroutine. cancel terminates the goroutine (cascading into
+// channel teardown + lease release); fingerprint is the credentials
+// snapshot the channel was built with, used by sweep to detect mid-life
+// rotation; gen is a monotonic counter so the goroutine's deferred cleanup
+// can tell its own entry apart from a successor entry that the rotation
+// path already swapped in.
+type supervisorEntry struct {
+ cancel context.CancelFunc
+ fingerprint string
+ gen uint64
+}
+
+// NewSupervisor constructs a Supervisor bound to the supplied store,
+// channel registry, and shared inbound handler. The handler is injected
+// into every Channel the Supervisor builds (via channel.Config.Handler) so
+// the inbound pipeline is written once and shared across platforms. The
+// Supervisor starts no goroutines until Run is called. A nil registry or
+// store is a programming error and will panic at Run.
+func NewSupervisor(store InstallationStore, registry *channel.Registry, handler channel.InboundHandler, cfg Config) *Supervisor {
+ cfg = cfg.withDefaults()
+ return &Supervisor{
+ store: store,
+ registry: registry,
+ handler: handler,
+ cfg: cfg,
+ nodeID: newNodeID(),
+ supervisors: make(map[string]supervisorEntry),
+ stopChan: make(chan struct{}),
+ }
+}
+
+// NodeID exposes the per-process lease token, for tests and observability
+// (so operators can correlate DB lease rows to a running replica).
+func (s *Supervisor) NodeID() string { return s.nodeID }
+
+// Run is the Supervisor's main loop. It scans installations every
+// PollInterval, attempts to lease any not currently supervised by this
+// process, and reaps supervisors for installations that were revoked or
+// whose lease was lost. Returns when ctx is cancelled; the caller MUST then
+// call Wait to join all supervisor goroutines before exiting.
+func (s *Supervisor) Run(ctx context.Context) {
+ defer close(s.stopChan)
+
+ // First sweep immediately so a freshly-restarted server doesn't wait a
+ // full PollInterval before picking up its installations.
+ s.sweep(ctx)
+
+ t := time.NewTicker(s.cfg.PollInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ s.cancelAll()
+ return
+ case <-t.C:
+ s.sweep(ctx)
+ }
+ }
+}
+
+// Wait blocks until every supervisor goroutine the Supervisor started has
+// exited. Call this AFTER cancelling Run's context.
+//
+// Prefer WaitWithTimeout in shutdown paths so a stuck supervisor (typically
+// a hung lease release on a frozen DB pool) cannot block process exit
+// indefinitely.
+func (s *Supervisor) Wait() {
+ s.wg.Wait()
+}
+
+// WaitWithTimeout is the bounded variant of Wait. Returns true if all
+// supervisor goroutines exited within the deadline, false on timeout. On
+// timeout the orphaned goroutines are reclaimed by the OS and any
+// unreleased leases expire naturally after LeaseTTL on the next replica. A
+// timeout <= 0 falls back to unbounded Wait.
+func (s *Supervisor) WaitWithTimeout(timeout time.Duration) bool {
+ if timeout <= 0 {
+ s.Wait()
+ return true
+ }
+ done := make(chan struct{})
+ go func() {
+ s.Wait()
+ close(done)
+ }()
+ t := time.NewTimer(timeout)
+ defer t.Stop()
+ select {
+ case <-done:
+ return true
+ case <-t.C:
+ return false
+ }
+}
+
+// ShutdownTimeout exposes the configured graceful-shutdown deadline so boot
+// can pass the same value to WaitWithTimeout without re-deriving it.
+func (s *Supervisor) ShutdownTimeout() time.Duration { return s.cfg.ShutdownTimeout }
+
+// sweep enumerates currently-active installations and starts a supervisor
+// for any this process does not yet supervise. Supervisors for revoked
+// installations are cancelled. Supervisors whose installation row rotated
+// credentials are cancelled and replaced inline so the new channel picks up
+// the fresh row.
+func (s *Supervisor) sweep(ctx context.Context) {
+ rows, err := s.store.ListActiveInstallations(ctx)
+ if err != nil {
+ s.cfg.Logger.Warn("channel engine: list active installations failed", "error", err)
+ return
+ }
+ active := make(map[string]struct{}, len(rows))
+ for _, row := range rows {
+ id := uuidString(row.ID)
+ active[id] = struct{}{}
+ s.maybeRestartOnRotation(id, row)
+ s.startSupervisor(ctx, row)
+ }
+ // Reap supervisors whose installation is no longer active (revoked
+ // since the last sweep). The supervisor exits on the next boundary,
+ // releases its lease, and the goroutine returns.
+ s.mu.Lock()
+ for id, entry := range s.supervisors {
+ if _, stillActive := active[id]; !stillActive {
+ entry.cancel()
+ delete(s.supervisors, id)
+ }
+ }
+ s.mu.Unlock()
+}
+
+// maybeRestartOnRotation cancels an existing supervisor when its
+// fingerprint differs from the current row's. The replacement is started by
+// the subsequent startSupervisor call in the same sweep iteration. The map
+// entry is dropped inline so the startSupervisor "skip if already
+// supervised" guard does not race the cancel.
+func (s *Supervisor) maybeRestartOnRotation(id string, row Installation) {
+ want := row.Fingerprint
+ s.mu.Lock()
+ entry, ok := s.supervisors[id]
+ if !ok || entry.fingerprint == want {
+ s.mu.Unlock()
+ return
+ }
+ s.cfg.Logger.Info("channel engine: credentials rotated, restarting supervisor",
+ "installation_id", id,
+ "channel_type", string(row.ChannelType),
+ )
+ entry.cancel()
+ delete(s.supervisors, id)
+ s.mu.Unlock()
+}
+
+func (s *Supervisor) startSupervisor(parent context.Context, inst Installation) {
+ id := uuidString(inst.ID)
+ s.mu.Lock()
+ if s.stopped {
+ s.mu.Unlock()
+ return
+ }
+ if _, exists := s.supervisors[id]; exists {
+ s.mu.Unlock()
+ return
+ }
+ ctx, cancel := context.WithCancel(parent)
+ s.supervisorGen++
+ gen := s.supervisorGen
+ s.supervisors[id] = supervisorEntry{
+ cancel: cancel,
+ fingerprint: inst.Fingerprint,
+ gen: gen,
+ }
+ s.wg.Add(1)
+ s.mu.Unlock()
+ go s.supervise(ctx, inst, id, gen)
+}
+
+// leaseToken composes the per-supervisor lease token: the process-wide
+// nodeID (for cross-replica observability) paired with the supervisor's gen
+// so two supervisors inside the SAME process running back-to-back for the
+// same installation (the rotation path) carry different tokens. That
+// distinction stops an old supervisor's post-cancel release from
+// CAS-matching and deleting the successor's just-acquired lease.
+func leaseToken(nodeID string, gen uint64) string {
+ return nodeID + "-g" + strconv.FormatUint(gen, 10)
+}
+
+// supervise owns one installation's connection lifecycle. It loops:
+// acquire lease → build channel → run it (Connect blocks) → renew lease
+// while it runs → on exit, release + back off → repeat. Returns when ctx is
+// cancelled.
+func (s *Supervisor) supervise(ctx context.Context, inst Installation, id string, gen uint64) {
+ defer s.wg.Done()
+ defer func() {
+ // Only clear the map entry if it still belongs to us — gen
+ // disambiguates "this entry is mine" from "the rotation path already
+ // replaced me with a fresh supervisor."
+ s.mu.Lock()
+ if entry, ok := s.supervisors[id]; ok && entry.gen == gen {
+ delete(s.supervisors, id)
+ }
+ s.mu.Unlock()
+ }()
+
+ leaseTok := leaseToken(s.nodeID, gen)
+ log := s.cfg.Logger.With(
+ "installation_id", id,
+ "channel_type", string(inst.ChannelType),
+ "node_id", s.nodeID,
+ "lease_token", leaseTok,
+ )
+ backoff := s.cfg.MinBackoff
+
+ for {
+ if ctx.Err() != nil {
+ return
+ }
+
+ // Claim the WS lease. If another replica owns a live lease, sleep
+ // until it expires or our context is cancelled.
+ leased, err := s.acquireLease(ctx, inst.ID, leaseTok)
+ if err != nil {
+ log.Warn("channel engine: acquire lease error", "error", err)
+ if sleep(ctx, s.cfg.LeaseRenewInterval) {
+ return
+ }
+ continue
+ }
+ if !leased {
+ if sleep(ctx, s.cfg.LeaseRenewInterval) {
+ return
+ }
+ continue
+ }
+
+ // Lease acquired. Build the platform channel via the registry,
+ // run it under a child context, and renew the lease in parallel.
+ ch, err := s.registry.Build(channel.Config{
+ Type: inst.ChannelType,
+ Raw: inst.Config,
+ Handler: s.handler,
+ })
+ if err != nil {
+ log.Error("channel engine: build channel failed", "error", err)
+ s.releaseLease(inst.ID, leaseTok)
+ if sleep(ctx, backoff) {
+ return
+ }
+ backoff = nextBackoff(backoff, s.cfg.MaxBackoff)
+ continue
+ }
+
+ runCtx, runCancel := context.WithCancel(ctx)
+ renewDone := make(chan struct{})
+ go func() {
+ defer close(renewDone)
+ // renewLeaseUntil cancels runCtx itself on lease loss so the
+ // channel exits even if its wire I/O is blocked. This is what
+ // makes "at most one active connection per installation across
+ // replicas" hold under lease theft.
+ s.renewLeaseUntil(runCtx, runCancel, inst.ID, leaseTok)
+ }()
+
+ startedAt := s.cfg.Now()
+ runErr := ch.Connect(runCtx)
+ runCancel()
+ <-renewDone
+ s.disconnect(ch, id, log)
+ s.releaseLease(inst.ID, leaseTok)
+
+ if ctx.Err() != nil {
+ return
+ }
+
+ // If the connection lived long enough to be "stable", reset the
+ // backoff so a single late failure does not start us at the cap.
+ uptime := s.cfg.Now().Sub(startedAt)
+ if uptime >= s.cfg.ResetBackoffAfter {
+ backoff = s.cfg.MinBackoff
+ }
+ if runErr != nil {
+ log.Warn("channel engine: connection exited with error", "error", runErr, "uptime", uptime.String())
+ } else {
+ log.Info("channel engine: connection exited cleanly", "uptime", uptime.String())
+ }
+ if sleep(ctx, jitter(backoff)) {
+ return
+ }
+ backoff = nextBackoff(backoff, s.cfg.MaxBackoff)
+ }
+}
+
+// acquireLease tries to claim or renew the WS lease. Returns (true, nil)
+// when owned after the call; (false, nil) when held elsewhere; (false, err)
+// for transport / DB failures. token is the per-supervisor token (see
+// leaseToken), NOT the process-wide nodeID.
+func (s *Supervisor) acquireLease(ctx context.Context, instID pgtype.UUID, token string) (bool, error) {
+ expires := s.cfg.Now().Add(s.cfg.LeaseTTL)
+ err := s.store.AcquireWSLease(ctx, AcquireLeaseParams{
+ ID: instID,
+ Token: token,
+ ExpiresAt: expires,
+ })
+ if err == nil {
+ return true, nil
+ }
+ if errors.Is(err, ErrLeaseNotAcquired) {
+ return false, nil
+ }
+ return false, err
+}
+
+// renewLeaseUntil re-acquires the lease on a tight cadence so a single
+// missed renewal does not yield it. Exits when ctx is cancelled. Lease loss
+// MUST cancel the channel's run context — otherwise the supervise loop would
+// release the lease while the channel's receive loop kept consuming events
+// until its wire I/O finally errored, exactly the "two replicas processing
+// the same installation" failure mode. cancelRun forces the channel's ctx
+// done immediately, so Connect returns in bounded time even on a silent
+// socket. token MUST be the same per-supervisor token used to acquire.
+func (s *Supervisor) renewLeaseUntil(ctx context.Context, cancelRun context.CancelFunc, instID pgtype.UUID, token string) {
+ t := time.NewTicker(s.cfg.LeaseRenewInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ leased, err := s.acquireLease(ctx, instID, token)
+ if err != nil {
+ s.cfg.Logger.Warn("channel engine: lease renewal error",
+ "installation_id", uuidString(instID),
+ "error", err,
+ )
+ continue
+ }
+ if !leased {
+ s.cfg.Logger.Warn("channel engine: lease lost; tearing down connection",
+ "installation_id", uuidString(instID),
+ )
+ cancelRun()
+ return
+ }
+ }
+ }
+}
+
+// releaseLease writes a token-fenced release so the next supervisor (this
+// process or another replica) can pick up the installation without waiting
+// for LeaseTTL. It runs on a fresh, bounded context (the parent ctx is
+// already cancelled by shutdown time). token MUST be the same per-supervisor
+// token used to acquire — a rotation successor's lease carries a different
+// token, so a stale release no-ops instead of clobbering it.
+func (s *Supervisor) releaseLease(instID pgtype.UUID, token string) {
+ ctx, cancel := context.WithTimeout(context.Background(), s.cfg.LeaseReleaseTimeout)
+ defer cancel()
+ if err := s.store.ReleaseWSLease(ctx, ReleaseLeaseParams{
+ ID: instID,
+ Token: token,
+ }); err != nil {
+ s.cfg.Logger.Warn("channel engine: release lease failed",
+ "installation_id", uuidString(instID),
+ "error", err,
+ )
+ }
+}
+
+// disconnect tears down a channel after its Connect returned, on a fresh
+// bounded context so a wedged Disconnect cannot hang the supervise loop. By
+// the time we get here the link is already down (Connect returned), so this
+// is best-effort resource cleanup.
+func (s *Supervisor) disconnect(ch channel.Channel, id string, log *slog.Logger) {
+ ctx, cancel := context.WithTimeout(context.Background(), s.cfg.DisconnectTimeout)
+ defer cancel()
+ if err := ch.Disconnect(ctx); err != nil {
+ log.Warn("channel engine: disconnect failed", "installation_id", id, "error", err)
+ }
+}
+
+func (s *Supervisor) cancelAll() {
+ s.mu.Lock()
+ s.stopped = true
+ for id, entry := range s.supervisors {
+ entry.cancel()
+ delete(s.supervisors, id)
+ }
+ s.mu.Unlock()
+}
+
+// newNodeID returns a 16-byte hex random string unique to this process.
+// Stored in channel_installation.ws_lease_token; matching tokens on a
+// subsequent acquire are treated as renewals (same owner).
+func newNodeID() string {
+ buf := make([]byte, 16)
+ if _, err := cryptorand.Read(buf); err != nil {
+ // crypto/rand failure is catastrophic and rare; fall back to a
+ // timestamp-derived token rather than panicking on boot.
+ return fmt.Sprintf("nodeid-fallback-%d", time.Now().UnixNano())
+ }
+ return hex.EncodeToString(buf)
+}
+
+// nextBackoff doubles the current backoff up to max.
+func nextBackoff(cur, max time.Duration) time.Duration {
+ next := cur * 2
+ if next > max {
+ return max
+ }
+ return next
+}
+
+// jitter spreads reconnect storms across the [0.5d, 1.5d) window so many
+// installations do not all retry on the same timer edge.
+func jitter(d time.Duration) time.Duration {
+ if d <= 0 {
+ return d
+ }
+ delta := d / 2
+ return d - delta + time.Duration(mathrand.Int64N(int64(2*delta)+1))
+}
+
+// sleep is a ctx-aware time.Sleep. Returns true iff ctx was cancelled before
+// the sleep completed, so callers can short-circuit shutdown.
+func sleep(ctx context.Context, d time.Duration) bool {
+ if d <= 0 {
+ return ctx.Err() != nil
+ }
+ t := time.NewTimer(d)
+ defer t.Stop()
+ select {
+ case <-ctx.Done():
+ return true
+ case <-t.C:
+ return false
+ }
+}
+
+func uuidString(u pgtype.UUID) string { return util.UUIDToString(u) }
diff --git a/server/internal/integrations/channel/engine/supervisor_test.go b/server/internal/integrations/channel/engine/supervisor_test.go
new file mode 100644
index 0000000000..b0aea27679
--- /dev/null
+++ b/server/internal/integrations/channel/engine/supervisor_test.go
@@ -0,0 +1,610 @@
+package engine
+
+import (
+ "context"
+ "errors"
+ "io"
+ "log/slog"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// fakeStore is the unit-test seam for InstallationStore. Lease state is
+// held in memory so a single fake can play both "we hold the lease" and
+// "another replica holds the lease" within one test.
+type fakeStore struct {
+ mu sync.Mutex
+ installations []Installation
+ listErr error
+ leaseOwner map[string]string // installation_id -> lease token
+ leaseExpiresAt map[string]time.Time // installation_id -> expiry
+ acquireErr error
+ releaseErr error
+ now func() time.Time
+ acquireCount int32
+
+ // releaseBlock, if non-nil, makes ReleaseWSLease block until it is
+ // closed/sent on OR the caller's ctx fires. Simulates a frozen pool so
+ // the bounded-release timeout can be exercised without real infra.
+ releaseBlock chan struct{}
+ releaseObservedCtxErr error
+}
+
+func newFakeStore() *fakeStore {
+ return &fakeStore{
+ leaseOwner: make(map[string]string),
+ leaseExpiresAt: make(map[string]time.Time),
+ now: time.Now,
+ }
+}
+
+func (f *fakeStore) ListActiveInstallations(ctx context.Context) ([]Installation, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.listErr != nil {
+ return nil, f.listErr
+ }
+ out := make([]Installation, len(f.installations))
+ copy(out, f.installations)
+ return out, nil
+}
+
+func (f *fakeStore) AcquireWSLease(ctx context.Context, arg AcquireLeaseParams) error {
+ atomic.AddInt32(&f.acquireCount, 1)
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.acquireErr != nil {
+ return f.acquireErr
+ }
+ id := uuidString(arg.ID)
+ owner, hasOwner := f.leaseOwner[id]
+ exp := f.leaseExpiresAt[id]
+ now := f.now()
+ // CAS: accept when no holder, holder expired, or holder is us.
+ if !hasOwner || exp.Before(now) || owner == arg.Token {
+ f.leaseOwner[id] = arg.Token
+ f.leaseExpiresAt[id] = arg.ExpiresAt
+ return nil
+ }
+ return ErrLeaseNotAcquired
+}
+
+func (f *fakeStore) ReleaseWSLease(ctx context.Context, arg ReleaseLeaseParams) error {
+ f.mu.Lock()
+ block := f.releaseBlock
+ f.mu.Unlock()
+ if block != nil {
+ select {
+ case <-block:
+ case <-ctx.Done():
+ f.mu.Lock()
+ f.releaseObservedCtxErr = ctx.Err()
+ f.mu.Unlock()
+ return ctx.Err()
+ }
+ }
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.releaseErr != nil {
+ return f.releaseErr
+ }
+ id := uuidString(arg.ID)
+ if f.leaseOwner[id] == arg.Token {
+ delete(f.leaseOwner, id)
+ delete(f.leaseExpiresAt, id)
+ }
+ return nil
+}
+
+func (f *fakeStore) presetLease(id pgtype.UUID, token string, expires time.Time) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.leaseOwner[uuidString(id)] = token
+ f.leaseExpiresAt[uuidString(id)] = expires
+}
+
+func (f *fakeStore) leaseHolder(id pgtype.UUID) (string, bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ owner, ok := f.leaseOwner[uuidString(id)]
+ return owner, ok
+}
+
+// fakeChannel is a channel.Channel whose Connect behaves per a script
+// (default: block until ctx is cancelled). It records connect/disconnect
+// counts and captures the injected handler.
+type fakeChannel struct {
+ mu sync.Mutex
+ typ channel.Type
+ connects int
+ disconnects int
+ script []func(ctx context.Context) error
+ handler channel.InboundHandler
+}
+
+func (f *fakeChannel) Type() channel.Type { return f.typ }
+
+func (f *fakeChannel) Connect(ctx context.Context) error {
+ f.mu.Lock()
+ idx := f.connects
+ f.connects++
+ var fn func(ctx context.Context) error
+ if idx < len(f.script) {
+ fn = f.script[idx]
+ }
+ f.mu.Unlock()
+ if fn != nil {
+ return fn(ctx)
+ }
+ <-ctx.Done()
+ return nil
+}
+
+func (f *fakeChannel) Disconnect(ctx context.Context) error {
+ f.mu.Lock()
+ f.disconnects++
+ f.mu.Unlock()
+ return nil
+}
+
+func (f *fakeChannel) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ return channel.SendResult{}, nil
+}
+
+func (f *fakeChannel) Capabilities() channel.Capability { return channel.CapText }
+
+func (f *fakeChannel) Connects() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.connects
+}
+
+// fakeRegistry wires a single fakeChannel under channel.TypeFeishu and
+// counts how many times the factory built a channel (i.e. supervise-loop
+// rebuilds). buildErr, when set, makes the factory fail.
+func fakeRegistry(fc *fakeChannel, builds *int32, buildErr error) *channel.Registry {
+ reg := channel.NewRegistry()
+ reg.Register(channel.TypeFeishu, func(cfg channel.Config) (channel.Channel, error) {
+ atomic.AddInt32(builds, 1)
+ if buildErr != nil {
+ return nil, buildErr
+ }
+ fc.mu.Lock()
+ fc.handler = cfg.Handler
+ fc.mu.Unlock()
+ return fc, nil
+ })
+ return reg
+}
+
+func uuidFromString(t *testing.T, s string) pgtype.UUID {
+ t.Helper()
+ var u pgtype.UUID
+ if err := u.Scan(s); err != nil {
+ t.Fatalf("scan uuid %q: %v", s, err)
+ }
+ return u
+}
+
+func discardLogger() *slog.Logger {
+ return slog.New(slog.NewTextHandler(io.Discard, nil))
+}
+
+func fastConfig() Config {
+ return Config{
+ LeaseTTL: 500 * time.Millisecond,
+ LeaseRenewInterval: 20 * time.Millisecond,
+ PollInterval: 10 * time.Millisecond,
+ MinBackoff: 5 * time.Millisecond,
+ MaxBackoff: 50 * time.Millisecond,
+ ResetBackoffAfter: 1 * time.Second,
+ Logger: discardLogger(),
+ }
+}
+
+func waitFor(timeout time.Duration, cond func() bool) bool {
+ deadline := time.Now().Add(timeout)
+ for time.Now().Before(deadline) {
+ if cond() {
+ return true
+ }
+ time.Sleep(time.Millisecond)
+ }
+ return cond()
+}
+
+func activeInst(id pgtype.UUID, fingerprint string) Installation {
+ return Installation{ID: id, ChannelType: channel.TypeFeishu, Fingerprint: fingerprint, Config: []byte(`{}`)}
+}
+
+func TestSupervisorAcquiresLeaseAndConnects(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "11111111-1111-1111-1111-111111111111")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ sup := NewSupervisor(q, reg, nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return fc.Connects() >= 1 }) {
+ t.Fatalf("expected channel to connect; connects=%d", fc.Connects())
+ }
+
+ cancel()
+ sup.Wait()
+
+ // Lease released after shutdown so another replica can take over.
+ if owner, ok := q.leaseHolder(instID); ok {
+ t.Fatalf("lease should be released after shutdown, got owner %q", owner)
+ }
+ // The injected handler is threaded into the built channel.
+ fc.mu.Lock()
+ defer fc.mu.Unlock()
+ if fc.disconnects == 0 {
+ t.Fatalf("expected Disconnect to be called after Connect returned")
+ }
+}
+
+func TestSupervisorInjectsHandler(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "1a111111-1111-1111-1111-111111111111")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ var called atomic.Bool
+ handler := func(ctx context.Context, msg channel.InboundMessage) error {
+ called.Store(true)
+ return nil
+ }
+ sup := NewSupervisor(q, reg, handler, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return fc.Connects() >= 1 }) {
+ t.Fatalf("channel never connected")
+ }
+ fc.mu.Lock()
+ h := fc.handler
+ fc.mu.Unlock()
+ if h == nil {
+ t.Fatalf("expected handler injected into channel.Config.Handler")
+ }
+ _ = h(context.Background(), channel.InboundMessage{})
+ if !called.Load() {
+ t.Fatalf("injected handler was not the supervisor's handler")
+ }
+
+ cancel()
+ sup.Wait()
+}
+
+func TestSupervisorSkipsWhenAnotherReplicaHoldsLease(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "22222222-2222-2222-2222-222222222222")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+ q.presetLease(instID, "other-replica", time.Now().Add(10*time.Second))
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ sup := NewSupervisor(q, reg, nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+
+ // Give the supervisor time to try and fail to acquire.
+ time.Sleep(120 * time.Millisecond)
+ if fc.Connects() != 0 {
+ t.Fatalf("channel should not connect while another replica holds lease; connects=%d", fc.Connects())
+ }
+ if owner, _ := q.leaseHolder(instID); owner != "other-replica" {
+ t.Fatalf("foreign lease should be untouched, got %q", owner)
+ }
+
+ cancel()
+ sup.Wait()
+}
+
+func TestSupervisorReclaimsLeaseAfterExpiry(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "33333333-3333-3333-3333-333333333333")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+ q.presetLease(instID, "other-replica", time.Now().Add(80*time.Millisecond))
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ sup := NewSupervisor(q, reg, nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+
+ if !waitFor(600*time.Millisecond, func() bool { return fc.Connects() >= 1 }) {
+ t.Fatalf("expected to reclaim lease after expiry; connects=%d", fc.Connects())
+ }
+
+ cancel()
+ sup.Wait()
+}
+
+func TestSupervisorReapsSupervisorWhenRevoked(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "44444444-4444-4444-4444-444444444444")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ sup := NewSupervisor(q, reg, nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sup.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return fc.Connects() >= 1 }) {
+ t.Fatalf("channel never connected")
+ }
+
+ // Revoke: drop from the active list.
+ q.mu.Lock()
+ q.installations = nil
+ q.mu.Unlock()
+
+ // The supervisor exits and releases its lease.
+ if !waitFor(400*time.Millisecond, func() bool {
+ _, held := q.leaseHolder(instID)
+ return !held
+ }) {
+ t.Fatalf("expected lease released after revoke")
+ }
+}
+
+func TestSupervisorRestartsOnCredentialsRotation(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "55555555-5555-5555-5555-555555555555")
+ q.installations = []Installation{activeInst(instID, "fp-one")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ sup := NewSupervisor(q, reg, nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sup.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return atomic.LoadInt32(&builds) >= 1 }) {
+ t.Fatalf("channel never built")
+ }
+ buildsBefore := atomic.LoadInt32(&builds)
+
+ // Rotate credentials: fingerprint changes -> supervisor restart -> rebuild.
+ q.mu.Lock()
+ q.installations[0].Fingerprint = "fp-two"
+ q.mu.Unlock()
+
+ if !waitFor(500*time.Millisecond, func() bool { return atomic.LoadInt32(&builds) > buildsBefore }) {
+ t.Fatalf("expected rebuild after rotation; builds before=%d after=%d", buildsBefore, atomic.LoadInt32(&builds))
+ }
+}
+
+func TestSupervisorDoesNotRestartOnUnchangedRow(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "66666666-6666-6666-6666-666666666666")
+ q.installations = []Installation{activeInst(instID, "stable")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ sup := NewSupervisor(q, reg, nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sup.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return atomic.LoadInt32(&builds) >= 1 }) {
+ t.Fatalf("channel never built")
+ }
+ // Several sweeps observe the same fingerprint; no rebuild should happen.
+ time.Sleep(150 * time.Millisecond)
+ if got := atomic.LoadInt32(&builds); got != 1 {
+ t.Fatalf("expected exactly 1 build for an unchanged row, got %d", got)
+ }
+}
+
+func TestSupervisorBacksOffOnBuildError(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "77777777-7777-7777-7777-777777777777")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, errors.New("boom"))
+
+ sup := NewSupervisor(q, reg, nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sup.Run(ctx)
+
+ // It keeps retrying (building) under backoff, and releases the lease
+ // between attempts so it never wedges holding the lease.
+ if !waitFor(400*time.Millisecond, func() bool { return atomic.LoadInt32(&builds) >= 2 }) {
+ t.Fatalf("expected repeated build attempts under backoff; builds=%d", atomic.LoadInt32(&builds))
+ }
+ if fc.Connects() != 0 {
+ t.Fatalf("channel should never connect when build fails; connects=%d", fc.Connects())
+ }
+}
+
+func TestSupervisorLeaseLossCancelsConnection(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "88888888-8888-8888-8888-888888888888")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+
+ connectReturned := make(chan struct{}, 1)
+ fc := &fakeChannel{
+ typ: channel.TypeFeishu,
+ script: []func(ctx context.Context) error{
+ func(ctx context.Context) error {
+ <-ctx.Done()
+ connectReturned <- struct{}{}
+ return ctx.Err()
+ },
+ },
+ }
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ sup := NewSupervisor(q, reg, nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sup.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return fc.Connects() >= 1 }) {
+ t.Fatalf("channel never connected")
+ }
+
+ // A thief steals the lease with a far-future expiry; the renewer's CAS
+ // fails and must cancel the running Connect.
+ q.presetLease(instID, "thief", time.Now().Add(10*time.Second))
+
+ select {
+ case <-connectReturned:
+ case <-time.After(500 * time.Millisecond):
+ t.Fatalf("lease loss did not cancel the running connection")
+ }
+}
+
+func TestSupervisorReleaseLeaseBoundedByTimeout(t *testing.T) {
+ q := newFakeStore()
+ q.releaseBlock = make(chan struct{}) // never closed; release always hits ctx.Done
+ instID := uuidFromString(t, "99999999-9999-9999-9999-999999999999")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ cfg := fastConfig()
+ cfg.LeaseReleaseTimeout = 40 * time.Millisecond
+ sup := NewSupervisor(q, reg, nil, cfg)
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return fc.Connects() >= 1 }) {
+ t.Fatalf("channel never connected")
+ }
+
+ cancel()
+ if !sup.WaitWithTimeout(2 * time.Second) {
+ t.Fatalf("shutdown should complete despite a frozen release (bounded by timeout)")
+ }
+ q.mu.Lock()
+ observed := q.releaseObservedCtxErr
+ q.mu.Unlock()
+ if !errors.Is(observed, context.DeadlineExceeded) {
+ t.Fatalf("expected release to observe DeadlineExceeded, got %v", observed)
+ }
+}
+
+func TestSupervisorWaitWithTimeoutReturnsFalseWhenStuck(t *testing.T) {
+ q := newFakeStore()
+ q.releaseBlock = make(chan struct{}) // never closed
+ instID := uuidFromString(t, "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
+ q.installations = []Installation{activeInst(instID, "fp1")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ cfg := fastConfig()
+ cfg.LeaseReleaseTimeout = 10 * time.Second // longer than the WaitWithTimeout below
+ sup := NewSupervisor(q, reg, nil, cfg)
+ ctx, cancel := context.WithCancel(context.Background())
+ go sup.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return fc.Connects() >= 1 }) {
+ t.Fatalf("channel never connected")
+ }
+
+ cancel()
+ if sup.WaitWithTimeout(80 * time.Millisecond) {
+ t.Fatalf("expected WaitWithTimeout to report timeout while release is wedged")
+ }
+ close(q.releaseBlock) // let the goroutine finish so the test cleans up
+ sup.Wait()
+}
+
+// TestSupervisorRotationStaleReleaseDoesNotClearSuccessorLease proves the
+// per-supervisor token fence: an old supervisor's post-cancel release must
+// not delete the lease a rotation successor just acquired with a different
+// token. We drive it through the public API by rotating credentials while
+// the old connection is held open, then asserting a live lease remains.
+func TestSupervisorRotationStaleReleaseDoesNotClearSuccessorLease(t *testing.T) {
+ q := newFakeStore()
+ instID := uuidFromString(t, "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb")
+ q.installations = []Installation{activeInst(instID, "fp-one")}
+
+ fc := &fakeChannel{typ: channel.TypeFeishu}
+ var builds int32
+ reg := fakeRegistry(fc, &builds, nil)
+
+ sup := NewSupervisor(q, reg, nil, fastConfig())
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ go sup.Run(ctx)
+
+ if !waitFor(300*time.Millisecond, func() bool { return atomic.LoadInt32(&builds) >= 1 }) {
+ t.Fatalf("channel never built")
+ }
+
+ // Rotate: old supervisor cancelled, successor starts with a new token.
+ q.mu.Lock()
+ q.installations[0].Fingerprint = "fp-two"
+ q.mu.Unlock()
+
+ // After the dust settles, a live lease should remain held by the
+ // successor (token ending in a higher gen) — not cleared by the
+ // predecessor's stale release.
+ if !waitFor(500*time.Millisecond, func() bool { return atomic.LoadInt32(&builds) >= 2 }) {
+ t.Fatalf("successor never built after rotation")
+ }
+ if !waitFor(300*time.Millisecond, func() bool {
+ owner, held := q.leaseHolder(instID)
+ return held && owner != ""
+ }) {
+ t.Fatalf("successor lease was cleared by a stale predecessor release")
+ }
+}
+
+func TestSupervisorConfigDefaults(t *testing.T) {
+ sup := NewSupervisor(newFakeStore(), channel.NewRegistry(), nil, Config{})
+ if sup.cfg.LeaseTTL <= 0 || sup.cfg.LeaseRenewInterval <= 0 || sup.cfg.PollInterval <= 0 {
+ t.Fatalf("lifecycle intervals must default to positive values")
+ }
+ if sup.cfg.LeaseRenewInterval >= sup.cfg.LeaseTTL {
+ t.Fatalf("renew interval must be well under the TTL")
+ }
+ if sup.ShutdownTimeout() <= 0 {
+ t.Fatalf("shutdown timeout must default to a positive value")
+ }
+ if sup.cfg.Now == nil || sup.cfg.Logger == nil {
+ t.Fatalf("Now and Logger must be defaulted")
+ }
+ if sup.NodeID() == "" {
+ t.Fatalf("node id must be assigned")
+ }
+}
diff --git a/server/internal/integrations/channel/handler.go b/server/internal/integrations/channel/handler.go
new file mode 100644
index 0000000000..370bd0f02b
--- /dev/null
+++ b/server/internal/integrations/channel/handler.go
@@ -0,0 +1,30 @@
+package channel
+
+import "context"
+
+// InboundHandler is the shared, channel-agnostic entry point a Channel
+// invokes for every inbound message it receives. The engine supervisor
+// injects ONE handler into every Channel it builds (via Config.Handler),
+// mirroring the reference design's single set_message_handler wiring: the
+// engine's inbound processing is written once and every platform adapter
+// funnels into it. The adapter owns its receive loop and calls the handler;
+// the core never polls the Channel.
+//
+// Contract:
+//
+// - A non-nil error signals an INFRASTRUCTURE failure (the core could
+// not process the message at all — DB down, dispatcher misconfigured,
+// etc.). The adapter should treat it like a failed delivery: surface
+// it to ops and let the supervisor's reconnect/backoff handle it. It
+// MUST NOT be used for product outcomes.
+// - A nil error means the message was accepted and classified. The
+// message may still have been dropped for a legitimate product reason
+// (dedup hit, unbound sender, group filter) — that is NOT an error.
+// Any outbound reply the verdict implies (binding card, offline
+// notice, typing indicator) is the handler's own responsibility,
+// detached from the adapter's ACK path.
+//
+// The handler is deliberately fire-and-classify (no return value beyond
+// error): the adapter does not branch on the outcome, so coupling it to a
+// platform-specific result type would defeat the abstraction.
+type InboundHandler func(ctx context.Context, msg InboundMessage) error
diff --git a/server/internal/integrations/channel/message.go b/server/internal/integrations/channel/message.go
index 912c672886..6b688a6787 100644
--- a/server/internal/integrations/channel/message.go
+++ b/server/internal/integrations/channel/message.go
@@ -143,6 +143,12 @@ type InboundMessage struct {
// arrays, parent ids) stay in Raw.
AddressedToBot bool
+ // ForceFresh asks the core to start a fresh agent session for this
+ // message instead of resuming the prior one (the platform's "/fresh"
+ // affordance). The adapter normalizes its platform-specific trigger
+ // into this boolean; the core only reads the flag.
+ ForceFresh bool
+
// Raw is the untouched platform payload. Adapters stash platform-
// specific fields here (Lark raw msg_type / parent_id / root_id /
// mention arrays, …) and read them back only inside the adapter. The
diff --git a/server/internal/integrations/lark/connector.go b/server/internal/integrations/lark/connector.go
new file mode 100644
index 0000000000..c0f9e9b756
--- /dev/null
+++ b/server/internal/integrations/lark/connector.go
@@ -0,0 +1,38 @@
+package lark
+
+import "context"
+
+// EventEmitter is the per-message callback an EventConnector calls for
+// each decoded inbound message. It dispatches the normalized message and
+// returns the typed outcome plus any infrastructure error.
+//
+// The connector reacts only to the error: a non-nil error is a real infra
+// failure (DB down, dispatcher misconfigured) and the connector should
+// surface it and let the engine reconnect under backoff; a nil error means
+// the message was accepted and classified (it may still have been dropped
+// for a product reason — that is not an error, and any outbound reply the
+// verdict implies is handled off the ACK path by the runtime). The
+// connector MUST NOT bypass emit by writing to the DB directly; emit is the
+// only ingress path.
+//
+// Historically the Feishu Hub passed this to the connector; with the
+// channel-agnostic engine the feishuChannel adapter wraps the connector and
+// supplies an emit that normalizes each event and hands it to the engine
+// Router (injected via channel.Config.Handler).
+type EventEmitter func(ctx context.Context, msg InboundMessage) (DispatchResult, error)
+
+// EventConnector is the per-installation Feishu transport: it opens the
+// Lark long connection, decodes events, normalizes them into
+// InboundMessage, and calls emit for each. Run MUST block until either ctx
+// is cancelled (returns nil) or the connection ends and cannot be recovered
+// locally (returns an error). Implementations MUST tolerate repeated Run
+// calls on different contexts — the engine may Run, return, and Run again
+// after backoff.
+type EventConnector interface {
+ Run(ctx context.Context, inst Installation, emit EventEmitter) error
+}
+
+// ConnectorFactory builds an EventConnector. Kept for the bootstrap /
+// fallback path (NoopConnectorFactory); the real WS connector is a single
+// shared instance whose Run is parameterized by the installation.
+type ConnectorFactory func(inst Installation) (EventConnector, error)
diff --git a/server/internal/integrations/lark/dispatcher.go b/server/internal/integrations/lark/dispatcher.go
deleted file mode 100644
index b38d90d7e7..0000000000
--- a/server/internal/integrations/lark/dispatcher.go
+++ /dev/null
@@ -1,802 +0,0 @@
-package lark
-
-import (
- "context"
- "errors"
- "fmt"
- "log/slog"
- "sync"
- "time"
-
- "github.com/jackc/pgx/v5"
- "github.com/jackc/pgx/v5/pgtype"
- "github.com/multica-ai/multica/server/internal/service"
- db "github.com/multica-ai/multica/server/pkg/db/generated"
-)
-
-// InboundMessage is the normalized shape the WebSocket adapter hands
-// to the Dispatcher. The adapter (Phase 2 PR) translates the raw Lark
-// event payload into this struct; the Dispatcher does NOT know what a
-// Lark event JSON object looks like. This keeps event-schema changes
-// from rippling into business logic.
-//
-// AddressedToBot is the adapter's verdict on whether a group-chat
-// message is an interaction with the Bot (@-mention or reply to a
-// Bot card). For p2p messages this field is ignored.
-type InboundMessage struct {
- EventType string
- EventID string
- AppID string
- ChatID ChatID
- ChatType ChatType
- MessageID string
- SenderOpenID OpenID
- Body string
- // ForceFreshSession marks this dispatch as a one-off fresh start:
- // the daemon should skip prior session resume when it claims the
- // resulting chat task.
- ForceFreshSession bool
- AddressedToBot bool
-
- // MessageType is the raw Lark msg_type ("text", "post",
- // "merge_forward", "image", "interactive", …). The decoder
- // populates it so the inbound enricher can decide whether a
- // message needs an HTTP round-trip to expand (merge_forward) while
- // the dispatcher itself stays msg_type-agnostic and only reads Body.
- MessageType string
-
- // CreateTime is the trigger message's creation time (epoch
- // milliseconds, as Lark sends it). The enricher uses it to anchor the
- // group recent-context window to the moment of the @-mention — it
- // fetches the conversation up to this time rather than whatever is
- // newest when the (slightly later) prefetch HTTP call runs.
- CreateTime string
-
- // ParentID is the message_id of the message this one quote-replies
- // to, taken verbatim from the receive event's `parent_id`. Empty
- // when the message is not a reply. The enricher fetches it and
- // prepends a <quoted_message> block. RootID is the thread/root
- // anchor Lark also reports; we keep it for completeness but the
- // quoted-reply expansion keys off ParentID (the immediate parent),
- // not the root.
- ParentID string
- RootID string
-
- // ThreadID is the Lark topic (话题) id this message belongs to,
- // taken verbatim from the receive event's `thread_id`. Lark only
- // populates it for messages posted inside a thread, so a non-empty
- // value is the signal that the @-mention happened in a thread. The
- // dispatcher persists it on the chat binding so the (decoupled)
- // outbound patcher can reply back into the same thread instead of
- // posting at the chat level.
- ThreadID string
-
- // CommandBody is the user's OWN typed text (the decoded Body before
- // the enricher prepends any <quoted_message> / <forwarded_messages>
- // context). The `/issue` command is parsed from THIS, not from the
- // enriched Body: enrichment prepends context blocks, which would
- // otherwise push the user's `/issue …` off the first line and
- // silently stop creating the issue. The enricher leaves CommandBody
- // untouched while it rewrites Body.
- CommandBody string
-}
-
-// Outcome categorizes what the Dispatcher decided to do with an
-// inbound message. The WS adapter inspects this and chooses what to
-// reply with on the Lark side.
-type Outcome string
-
-const (
- // OutcomeDropped — the message was not ingested (identity failed,
- // dedup hit, group filter, etc.). DispatchResult.DropReason holds
- // the audit category.
- OutcomeDropped Outcome = "dropped"
-
- // OutcomeNeedsBinding — the open_id is unbound; the WS adapter
- // should mint a binding token via BindingTokenService and send
- // the "click here to bind" card. DispatchResult.SenderOpenID and
- // .InstallationID are populated so the adapter can target the
- // reply.
- OutcomeNeedsBinding Outcome = "needs_binding"
-
- // OutcomeIngested — the message landed in chat_session and an
- // agent task was enqueued. Empty IssueCommand means a plain chat
- // message; non-empty means /issue ran (see IssueID for the new
- // issue's UUID).
- OutcomeIngested Outcome = "ingested"
-
- // OutcomeAgentOffline — the message landed in chat_session, but
- // the agent has no runtime bound at all (agent.runtime_id IS
- // NULL). The adapter should reply with "agent offline, will run
- // on next online." The chat_message row remains so the agent
- // picks it up on resume.
- //
- // IMPORTANT: this is NOT triggered when a daemon is merely
- // disconnected. If agent.runtime_id IS set, the chat task is
- // enqueued and waits for the daemon to claim it on next online;
- // that path returns OutcomeIngested with a TaskID.
- OutcomeAgentOffline Outcome = "agent_offline"
-
- // OutcomeAgentArchived — the message landed in chat_session, but
- // the agent has been archived. The adapter should reply with a
- // distinct copy ("this agent has been archived; ask an admin to
- // unarchive or rebind"). Kept separate from OutcomeAgentOffline
- // because the user-facing remediation differs.
- OutcomeAgentArchived Outcome = "agent_archived"
-)
-
-// DispatchResult is the typed return from Dispatcher.Handle. Callers
-// (the WS adapter) consume this to drive their outbound side; nothing
-// here implies the adapter MUST reply, only that it CAN.
-type DispatchResult struct {
- Outcome Outcome
- DropReason DropReason
- InstallationID pgtype.UUID
- ChatSessionID pgtype.UUID
- SenderOpenID OpenID
- // TaskID was populated when the dispatcher enqueued the chat task
- // synchronously. With the short-window debounce (MUL-2968) the run is
- // triggered asynchronously at flush time, so Handle no longer knows a
- // task id — this field is left zero for the chat path. Kept on the
- // struct because the emit contract still carries it for any future
- // synchronous enqueue (e.g. /issue follow-ups).
- TaskID pgtype.UUID
- IssueID pgtype.UUID
- IssueNumber int32
- // IssueIdentifier is the workspace-qualified human key for the
- // created issue ("MUL-42"). Populated only when /issue produced a
- // new row. The OutcomeReplier uses this verbatim in the "Created
- // [MUL-42]" confirmation message.
- IssueIdentifier string
- // IssueTitle is the title the user supplied on /issue, echoed back
- // in the confirmation message so the chat history reads naturally
- // even when the Multica deep link is not reachable.
- IssueTitle string
-}
-
-// IssueCreator is the narrow subset of service.IssueService the
-// Dispatcher needs. Declared here as an interface so this package can
-// be unit-tested without bringing the full service graph along.
-type IssueCreator interface {
- Create(ctx context.Context, p service.IssueCreateParams, opts service.IssueCreateOpts) (service.IssueCreateResult, error)
-}
-
-// ChatTaskEnqueuer is the narrow subset of service.TaskService the
-// Dispatcher needs. It exists for the same reason as IssueCreator:
-// the Dispatcher is small enough that depending on the whole
-// TaskService struct is gratuitous.
-type ChatTaskEnqueuer interface {
- EnqueueChatTask(ctx context.Context, session db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error)
-}
-
-// DispatcherQueries is the narrow subset of *db.Queries the Dispatcher
-// needs for installation routing, identity lookup, dedup, and session
-// reload. *db.Queries satisfies it directly; tests substitute a fake.
-//
-// Dedup is two-phase with owner fencing:
-//
-// - ClaimLarkInboundDedup mints a fresh claim_token UUID on insert
-// and on stale-reclaim re-take. The token is the dispatcher's
-// ownership receipt for the row.
-//
-// - MarkLarkInboundDedupProcessed and ReleaseLarkInboundDedup are
-// fenced on (message_id, claim_token, processed_at IS NULL). A
-// stale-reclaim that rotates the token invalidates earlier
-// finalizers, so a slow-but-alive worker whose claim was taken
-// over cannot stomp the new holder's row. Both queries return
-// rowsAffected; zero means "your token is no longer the live one"
-// and the dispatcher treats it as a no-op (not an error — the
-// other worker is responsible for the row now).
-//
-// - AppendUserMessage invokes the Mark INSIDE its chat_message tx
-// when a claim token is supplied, so the durable write and the
-// Mark commit atomically. That closes the "crashed between
-// commit and Mark" window. See lark_inbound_message_dedup comment
-// in 109_lark_integration.up.sql for the full invariant set.
-type DispatcherQueries interface {
- GetLarkInstallationByAppID(ctx context.Context, appID string) (Installation, error)
- GetLarkUserBindingByOpenID(ctx context.Context, arg GetUserBindingByOpenIDParams) (UserBinding, error)
- GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)
- ClaimLarkInboundDedup(ctx context.Context, arg ClaimInboundDedupParams) (InboundMessageDedup, error)
- MarkLarkInboundDedupProcessed(ctx context.Context, arg MarkInboundDedupProcessedParams) (int64, error)
- ReleaseLarkInboundDedup(ctx context.Context, arg ReleaseInboundDedupParams) (int64, error)
- // GetWorkspace is needed to read IssuePrefix so the /issue
- // confirmation message can render the workspace-qualified key
- // ("MUL-42"). A lookup failure is non-fatal — we degrade to
- // emitting just the issue number — so callers handle the error
- // inline rather than aborting the whole dispatch.
- GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error)
-
- // IsWorkspaceMember re-checks current membership in the inbound
- // identity step. With the lark_user_binding -> member foreign key
- // removed (MUL-3515 §4), a binding row no longer proves the bound
- // user is still a workspace member, so the dispatcher verifies it
- // explicitly instead of trusting the row's existence.
- IsWorkspaceMember(ctx context.Context, workspaceID, userID pgtype.UUID) (bool, error)
-}
-
-// Dispatcher is the single per-message entry point on the inbound
-// path. It owns the order in which identity check, group filter,
-// dedup, ingest, /issue, and task enqueue happen — the WS adapter
-// MUST NOT bypass it. That ordering is the invariant that keeps the
-// design's §4.3 safety property ("unbound users never reach
-// chat_session") true at runtime.
-type Dispatcher struct {
- Queries DispatcherQueries
- Chat ChatSessionService
- Audit AuditLogger
- IssueService IssueCreator
- TaskService ChatTaskEnqueuer
-
- // FlushReply emits the offline/archived notice that EnqueueChatTask
- // now produces only at debounce-flush time. Before MUL-2968 those
- // outcomes were returned synchronously from Handle and the hub's
- // OutcomeReplier sent the card; with the run trigger debounced, the
- // verdict is not known until the window closes, so the dispatcher
- // drives the reply itself via this callback. Wired to
- // OutcomeReplier.Reply in production; nil disables the notice (the
- // message is still durable, only the card is skipped).
- FlushReply FlushReplyFunc
-
- // Logger is used by the detached flush path, which cannot return
- // errors to a caller and must log them. Defaults to slog.Default().
- Logger *slog.Logger
-
- // batcher debounces the per-session run trigger. Installed via
- // EnableRunBatching in production; when nil (unit tests / degenerate
- // config) the run fires inline with no debounce — a zero-length
- // window, not a separate code path.
- batcher *pendingBatcher
-
- // pendingFresh tracks whether any message in the current debounced
- // session window asked for a fresh run. The debouncer intentionally
- // keeps the latest flush closure so the latest sender wins, but the
- // fresh-start directive is sticky across the window.
- pendingFreshMu sync.Mutex
- pendingFresh map[string]bool
-}
-
-// FlushReplyFunc matches OutcomeReplier.Reply so the production replier can
-// be injected directly. It is invoked from the debounced flush goroutine
-// to deliver the agent-offline / agent-archived notice.
-type FlushReplyFunc func(ctx context.Context, inst Installation, msg InboundMessage, res DispatchResult)
-
-// chatRunFlushTimeout bounds the detached flush (session reload +
-// EnqueueChatTask + offline/archived notice). The flush runs on its own
-// fresh context because the inbound request ctx is long cancelled by the
-// time the window closes.
-const chatRunFlushTimeout = 10 * time.Second
-
-// EnableRunBatching installs the in-memory debouncer in front of the
-// per-session run trigger. Call once at boot. A non-positive window uses
-// DefaultChatRunBatchWindow. Without this, the dispatcher triggers runs
-// inline (used by unit tests that assert the immediate effect).
-func (d *Dispatcher) EnableRunBatching(window time.Duration) {
- d.batcher = newPendingBatcher(window)
-}
-
-// FlushPendingRuns drains every still-pending run trigger immediately and
-// blocks until in-flight flushes finish. The hub calls this on graceful
-// shutdown, after inbound delivery has stopped, so a normal restart does
-// not silently drop a window's worth of messages. No-op when batching is
-// disabled.
-func (d *Dispatcher) FlushPendingRuns() {
- if d.batcher != nil {
- d.batcher.FlushAll()
- }
-}
-
-func (d *Dispatcher) logger() *slog.Logger {
- if d.Logger != nil {
- return d.Logger
- }
- return slog.Default()
-}
-
-// Handle processes one inbound Lark message end-to-end. It never
-// returns an error for "this message was dropped" — those are
-// reported via Outcome + DropReason and a non-nil err is reserved for
-// real infrastructure failures (DB down, etc.) that the WS adapter
-// should retry.
-//
-// Dedup is two-phase. After the installation lookup, ClaimLarkInbound-
-// Dedup acquires an in-flight claim on msg.MessageID. After the rest
-// of the pipeline runs, the claim is finalized exactly once:
-//
-// - MarkLarkInboundDedupProcessed — a durable outcome was reached
-// (audit drop row persisted, OR chat_message + session touched).
-// Future replays of this message_id are dropped as duplicates.
-//
-// - ReleaseLarkInboundDedup — an infra error occurred BEFORE any
-// durable side effect. The claim row is deleted so the WS
-// adapter's retry can re-acquire it immediately; otherwise the
-// message would be permanently swallowed as a duplicate even
-// though it never actually landed in chat_session.
-func (d *Dispatcher) Handle(ctx context.Context, msg InboundMessage) (DispatchResult, error) {
- // 1. Route to installation. The app_id is the only identifier
- // that ties an event to its installation row. These two drop
- // branches run BEFORE the dedup claim because they have no
- // valid installation row to attach to — see the spec note on
- // lark_inbound_audit allowing a NULL installation_id.
- inst, err := d.Queries.GetLarkInstallationByAppID(ctx, msg.AppID)
- if err != nil {
- if errors.Is(err, pgx.ErrNoRows) {
- _ = d.Audit.RecordDrop(ctx, AuditDropParams{
- EventType: msg.EventType,
- LarkEventID: msg.EventID,
- LarkMessageID: msg.MessageID,
- ChatID: msg.ChatID,
- Reason: DropReasonInvalidEvent,
- })
- return DispatchResult{Outcome: OutcomeDropped, DropReason: DropReasonInvalidEvent}, nil
- }
- return DispatchResult{}, fmt.Errorf("load installation: %w", err)
- }
- if InstallationStatus(inst.Status) != InstallationActive {
- return d.drop(ctx, msg, inst.ID, DropReasonRevokedInstallation), nil
- }
-
- // 2. Two-phase dedup claim with owner fencing. Spec §4.3 puts this
- // before group filter and identity check so a WebSocket
- // reconnect that replays an event cannot:
- // a) re-trigger the binding prompt for an unbound user, or
- // b) re-write the not_addressed_in_group / unbound_user audit
- // rows, or
- // c) re-touch the chat_session for a bound message.
- //
- // The Claim returns claim_token; subsequent Mark / Release calls
- // are fenced on (message_id, claim_token), and AppendUserMessage
- // invokes the Mark INSIDE its chat_message tx, so the durable
- // write + Mark commit atomically. Stale-reclaim by another
- // worker rotates the token, which invalidates our same-tx Mark
- // (zero rows → ErrClaimLost → tx rollback).
- //
- // Empty MessageID means the event has no Lark message_id at all
- // (non-message events, malformed payloads); skipping dedup is
- // the safe default — we have no key to deduplicate by, and no
- // claim to finalize at the end.
- var claimToken pgtype.UUID
- claimed := false
- if msg.MessageID != "" {
- claim, err := d.Queries.ClaimLarkInboundDedup(ctx, ClaimInboundDedupParams{
- InstallationID: inst.ID,
- MessageID: msg.MessageID,
- })
- if err != nil {
- if errors.Is(err, pgx.ErrNoRows) {
- // Either the row is processed_at IS NOT NULL
- // (terminal) or another worker is actively
- // processing. Either way, the right behavior is to
- // drop without re-doing the work.
- return d.drop(ctx, msg, inst.ID, DropReasonDuplicate), nil
- }
- return DispatchResult{}, fmt.Errorf("dedup claim: %w", err)
- }
- claimToken = claim.ClaimToken
- claimed = true
- }
-
- res, finalize, err := d.processClaimed(ctx, msg, inst, claimToken)
-
- if claimed {
- d.applyFinalize(ctx, inst.ID, msg.MessageID, claimToken, finalize)
- }
-
- // ErrClaimLost is the dispatcher's signal that another worker
- // holds the claim. Surface it as a duplicate drop to the caller —
- // nothing else needs to happen, and the audit row was already
- // written by the in-tx rollback path's caller (see processClaimed).
- if errors.Is(err, ErrClaimLost) {
- return d.drop(ctx, msg, inst.ID, DropReasonDuplicate), nil
- }
-
- return res, err
-}
-
-// dedupFinalize captures the dispatcher's instruction to applyFinalize
-// after processClaimed returns. The three states correspond to the
-// three terminal positions in the inbound pipeline:
-//
-// - finalizeMark: a durable side effect landed OUTSIDE
-// AppendUserMessage's tx (audit drop row, or a post-AppendUser-
-// Message error that left the chat_message committed). Token-
-// fenced Mark locks the row terminal.
-//
-// - finalizeRelease: the run did not reach durability. Delete the
-// in-flight row so the WS adapter's retry can re-claim it
-// immediately instead of waiting for the 60s staleness TTL.
-//
-// - finalizeNone: AppendUserMessage already finalized the row in
-// its own tx (success → Mark in-tx; ErrClaimLost → another worker
-// owns it). The dispatcher does not touch the row again.
-type dedupFinalize int
-
-const (
- finalizeNone dedupFinalize = iota
- finalizeMark
- finalizeRelease
-)
-
-// processClaimed runs the post-dedup pipeline. It returns the typed
-// dispatch result, a dedupFinalize directive telling the caller how to
-// land the claim row, and any error.
-//
-// Boundary contract per step:
-//
-// - Group filter / unbound-user drop → audit row written →
-// finalizeMark.
-// - EnsureChatSession error → tx rolled back, no durable side effect
-// → finalizeRelease.
-// - AppendUserMessage success → chat_message committed AND
-// dedup row already Marked in the same tx → finalizeNone.
-// - AppendUserMessage error → tx rolled back, no chat_message →
-// finalizeRelease (ErrClaimLost is treated specially by Handle).
-// - Post-AppendUserMessage error (issue create, session reload,
-// task enqueue) → chat_message already committed but the
-// in-tx Mark also already committed → finalizeNone.
-func (d *Dispatcher) processClaimed(ctx context.Context, msg InboundMessage, inst Installation, claimToken pgtype.UUID) (DispatchResult, dedupFinalize, error) {
- // 3. Group-mention filter (group chats only). We do this BEFORE
- // identity check so that an unbound user's idle group chatter
- // never produces an "you need to bind" reply card spam — the
- // Bot is not addressed, so we say nothing.
- if msg.ChatType == ChatTypeGroup && !msg.AddressedToBot {
- return d.drop(ctx, msg, inst.ID, DropReasonNotAddressedInGroup), finalizeMark, nil
- }
-
- // 4. Identity check. A row in lark_user_binding maps the open_id to
- // a Multica user. Its mere existence USED to prove current
- // workspace membership (a composite FK to member cascaded the
- // binding away on revocation); MUL-3515 §4 removed that FK, so
- // step 4b re-checks membership explicitly below.
- binding, err := d.Queries.GetLarkUserBindingByOpenID(ctx, GetUserBindingByOpenIDParams{
- InstallationID: inst.ID,
- ChannelUserID: string(msg.SenderOpenID),
- })
- if err != nil {
- if errors.Is(err, pgx.ErrNoRows) {
- _ = d.Audit.RecordDrop(ctx, AuditDropParams{
- InstallationID: inst.ID,
- ChatID: msg.ChatID,
- EventType: msg.EventType,
- LarkEventID: msg.EventID,
- LarkMessageID: msg.MessageID,
- Reason: DropReasonUnboundUser,
- })
- return DispatchResult{
- Outcome: OutcomeNeedsBinding,
- DropReason: DropReasonUnboundUser,
- InstallationID: inst.ID,
- SenderOpenID: msg.SenderOpenID,
- }, finalizeMark, nil
- }
- return DispatchResult{}, finalizeRelease, fmt.Errorf("load user binding: %w", err)
- }
-
- // 4b. Re-check workspace membership. With the binding->member FK gone
- // (MUL-3515 §4), a stale binding can outlive the user's
- // membership, so the row from step 4 is necessary but no longer
- // sufficient. A former member's leftover binding must not leak
- // content into a chat_session (§4.3); we drop + audit it the same
- // way as the group-mention filter (durable audit row →
- // finalizeMark), with the non_workspace_member reason that used
- // to be unreachable while the FK guaranteed it could not happen.
- isMember, err := d.Queries.IsWorkspaceMember(ctx, inst.WorkspaceID, binding.MulticaUserID)
- if err != nil {
- return DispatchResult{}, finalizeRelease, fmt.Errorf("check workspace membership: %w", err)
- }
- if !isMember {
- return d.drop(ctx, msg, inst.ID, DropReasonNonWorkspaceMember), finalizeMark, nil
- }
-
- // 5. Resolve the chat_session. For group chats, the session
- // creator is the INSTALLER (stable workspace identity that
- // won't cascade-delete when individual group members churn);
- // for p2p, the sender is the one and only human in the chat
- // so we use them.
- sessionCreator := binding.MulticaUserID
- if msg.ChatType == ChatTypeGroup {
- sessionCreator = inst.InstallerUserID
- }
- sessionID, err := d.Chat.EnsureChatSession(ctx, EnsureChatSessionParams{
- WorkspaceID: inst.WorkspaceID,
- InstallationID: inst.ID,
- AgentID: inst.AgentID,
- ChatID: msg.ChatID,
- ChatType: msg.ChatType,
- Sender: sessionCreator,
- })
- if err != nil {
- // chat_session create + lark_chat_session_binding create are
- // in a single tx; an error here means the tx rolled back and
- // nothing landed. Safe to release the dedup claim.
- return DispatchResult{}, finalizeRelease, fmt.Errorf("ensure chat session: %w", err)
- }
-
- // 6. Append message + in-tx dedup Mark — the durable transition
- // point. After this returns nil the chat_message AND the dedup
- // Mark have committed atomically; any subsequent failure path
- // must return finalizeNone (the row is already terminal,
- // re-Marking is a no-op but re-Releasing would undo nothing
- // and we don't want to call DELETE on a Marked row).
- //
- // ErrClaimLost = our token was rotated by a stale-reclaim mid-
- // flight; the deferred Rollback in AppendUserMessage already
- // undid the chat_message insert, so Handle treats this as a
- // duplicate drop. finalizeNone — the other holder owns the row.
- appendRes, err := d.Chat.AppendUserMessage(ctx, AppendUserMessageParams{
- ChatSessionID: sessionID,
- Sender: binding.MulticaUserID,
- Body: msg.Body,
- CommandBody: msg.CommandBody,
- InstallationID: inst.ID,
- LarkMessageID: msg.MessageID,
- LarkThreadID: msg.ThreadID,
- ClaimToken: claimToken,
- })
- if err != nil {
- if errors.Is(err, ErrClaimLost) {
- return DispatchResult{}, finalizeNone, err
- }
- // AppendUserMessage's transaction either commits or rolls
- // back atomically; an error means rollback, so no
- // chat_message was written. Safe to release.
- return DispatchResult{}, finalizeRelease, fmt.Errorf("append user message: %w", err)
- }
-
- // Post-AppendUserMessage paths must NOT Release the claim, because
- // the chat_message + dedup Mark are already committed. Mark-again
- // is a no-op (the in-tx Mark already landed), so finalizeNone.
- postAppendFinalize := finalizeNone
- if !appendRes.DedupMarked {
- // Defensive: the dispatcher always passes a valid claim token,
- // but if a future caller wires AppendUserMessage with an
- // invalid token the Mark would not have run in-tx. Fall back
- // to the post-pipeline Mark so the row still terminates.
- postAppendFinalize = finalizeMark
- }
-
- res := DispatchResult{
- Outcome: OutcomeIngested,
- InstallationID: inst.ID,
- ChatSessionID: sessionID,
- SenderOpenID: msg.SenderOpenID,
- }
-
- // 7. /issue command, if present. chat_message is already durable
- // above; from here all error returns must signal finalizeNone
- // (or finalizeMark in the defensive fallback above).
- if appendRes.IssueCommand != nil {
- issueRes, err := d.createIssueFromCommand(ctx, inst, binding.MulticaUserID, sessionID, *appendRes.IssueCommand)
- if err != nil {
- return DispatchResult{}, postAppendFinalize, fmt.Errorf("create issue from command: %w", err)
- }
- res.IssueID = issueRes.Issue.ID
- res.IssueNumber = issueRes.Issue.Number
- res.IssueTitle = issueRes.Issue.Title
- // Render the workspace-qualified key ("MUL-42") so the
- // outbound confirmation reads like a Linear/Jira identifier
- // rather than a bare number. A workspace lookup failure here
- // degrades gracefully — we still surface the issue number,
- // just without the workspace prefix — so a Postgres blip on
- // the workspace row does not eat the "/issue created" signal.
- if ws, werr := d.Queries.GetWorkspace(ctx, inst.WorkspaceID); werr == nil && ws.IssuePrefix != "" {
- res.IssueIdentifier = fmt.Sprintf("%s-%d", ws.IssuePrefix, issueRes.Issue.Number)
- } else {
- res.IssueIdentifier = fmt.Sprintf("#%d", issueRes.Issue.Number)
- }
- }
-
- // 8. Debounce the run trigger. The chat_message + dedup Mark are
- // already durable; the agent run reads the WHOLE session at
- // execution time, so a burst of messages in this session is
- // collapsed into ONE run by deferring EnqueueChatTask behind a
- // short silence window (MUL-2968). The synchronous outcome is
- // OutcomeIngested with NO TaskID — the task row is created later,
- // at flush. EnqueueChatTask's productizable verdicts (agent
- // offline / archived) and infra errors are now handled inside the
- // flush (see flushChatRun), not returned here.
- //
- // Note: a daemon that's merely disconnected is NOT an error. As
- // long as agent.runtime_id is set, the chat task is enqueued at
- // flush and waits for the daemon to claim it on next online.
- // binding.MulticaUserID is THIS message's sender — the task initiator. It is
- // deliberately not the session creator (group sessions are creator=installer,
- // see step 5). The debouncer keeps the latest scheduled flush per session, so
- // in a multi-sender silence window the last sender wins, matching the
- // "latest message in a window wins" rule above. See MUL-2645.
- d.scheduleRun(inst, msg, sessionID, binding.MulticaUserID)
- return res, postAppendFinalize, nil
-}
-
-// scheduleRun hands the per-session run trigger to the debouncer (or fires
-// it inline when batching is disabled). The flush closure captures this
-// message's installation + InboundMessage so the offline/archived notice,
-// if any, targets the right chat; the latest message in a window wins.
-func (d *Dispatcher) scheduleRun(inst Installation, msg InboundMessage, sessionID pgtype.UUID, initiatorUserID pgtype.UUID) {
- key := keyForSession(sessionID)
- flush := func() { d.flushChatRun(inst, msg, sessionID, initiatorUserID, msg.ForceFreshSession) }
- if d.batcher == nil {
- // Batching disabled (unit tests / degenerate config): trigger the
- // run immediately. Production always installs a batcher via
- // EnableRunBatching, so this branch does not run in prod.
- flush()
- return
- }
- if msg.ForceFreshSession {
- d.markPendingFresh(key)
- }
- flush = func() {
- d.flushChatRun(inst, msg, sessionID, initiatorUserID, d.takePendingFresh(key, msg.ForceFreshSession))
- }
- d.batcher.Schedule(key, flush)
-}
-
-// flushChatRun is the debounced run-trigger. It runs once per silence
-// window per chat session, detached from the inbound path (on its own
-// goroutine and fresh context). It reloads the session, enqueues exactly
-// one chat task for the whole window's worth of messages, and — because
-// EnqueueChatTask's offline/archived verdict is only known here now —
-// emits the corresponding notice itself via FlushReply. Errors cannot be
-// returned to a caller (the message is already ACKed and durable), so they
-// are logged: a failed enqueue leaves the message in the session to be
-// picked up by the next message's run.
-func (d *Dispatcher) flushChatRun(inst Installation, msg InboundMessage, sessionID pgtype.UUID, initiatorUserID pgtype.UUID, forceFreshSession bool) {
- ctx, cancel := context.WithTimeout(context.Background(), chatRunFlushTimeout)
- defer cancel()
-
- session, err := d.Queries.GetChatSession(ctx, sessionID)
- if err != nil {
- d.logger().Error("lark dispatcher: flush reload chat session failed",
- "chat_session_id", uuidString(sessionID),
- "err", err.Error(),
- )
- return
- }
- if _, err := d.TaskService.EnqueueChatTask(ctx, session, initiatorUserID, forceFreshSession); err != nil {
- switch {
- case errors.Is(err, service.ErrChatTaskAgentNoRuntime):
- d.emitFlushReply(ctx, inst, msg, sessionID, OutcomeAgentOffline)
- case errors.Is(err, service.ErrChatTaskAgentArchived):
- d.emitFlushReply(ctx, inst, msg, sessionID, OutcomeAgentArchived)
- default:
- // Infra failure (DB down, etc.). Nothing to retry against —
- // the inbound frame was ACKed long ago. Log so the gap is
- // visible; the next message in this session re-triggers a run
- // that will read this message too.
- d.logger().Error("lark dispatcher: flush enqueue chat task failed",
- "chat_session_id", uuidString(sessionID),
- "err", err.Error(),
- )
- }
- }
-}
-
-func (d *Dispatcher) markPendingFresh(key string) {
- d.pendingFreshMu.Lock()
- defer d.pendingFreshMu.Unlock()
- if d.pendingFresh == nil {
- d.pendingFresh = make(map[string]bool)
- }
- d.pendingFresh[key] = true
-}
-
-func (d *Dispatcher) takePendingFresh(key string, fallback bool) bool {
- d.pendingFreshMu.Lock()
- defer d.pendingFreshMu.Unlock()
- fresh := fallback
- if d.pendingFresh != nil {
- fresh = fresh || d.pendingFresh[key]
- delete(d.pendingFresh, key)
- }
- return fresh
-}
-
-// emitFlushReply delivers an offline/archived notice for a flushed run.
-func (d *Dispatcher) emitFlushReply(ctx context.Context, inst Installation, msg InboundMessage, sessionID pgtype.UUID, outcome Outcome) {
- if d.FlushReply == nil {
- return
- }
- d.FlushReply(ctx, inst, msg, DispatchResult{
- Outcome: outcome,
- InstallationID: inst.ID,
- ChatSessionID: sessionID,
- SenderOpenID: msg.SenderOpenID,
- })
-}
-
-// keyForSession is the batcher key. chat_session_id is a globally-unique
-// UUID, so it alone disambiguates sessions across installations.
-func keyForSession(sessionID pgtype.UUID) string {
- return string(sessionID.Bytes[:])
-}
-
-// applyFinalize flips the in-flight claim row to its terminal state,
-// token-fenced so a slow-but-alive worker whose claim was reclaimed
-// cannot stomp the new holder's row.
-//
-// Best-effort by design for the I/O layer: a transport failure here
-// cannot abort the outcome (the user's message is already in
-// chat_session or the audit row already exists), and the worst case
-// is a stuck in-flight row that the 60-second staleness fallback in
-// ClaimLarkInboundDedup re-takes on retry. zero-rows-affected is the
-// EXPECTED outcome whenever our token was rotated; it is not an error.
-func (d *Dispatcher) applyFinalize(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID, action dedupFinalize) {
- switch action {
- case finalizeMark:
- _, _ = d.Queries.MarkLarkInboundDedupProcessed(ctx, MarkInboundDedupProcessedParams{
- InstallationID: installationID,
- MessageID: messageID,
- ClaimToken: claimToken,
- })
- case finalizeRelease:
- _, _ = d.Queries.ReleaseLarkInboundDedup(ctx, ReleaseInboundDedupParams{
- InstallationID: installationID,
- MessageID: messageID,
- ClaimToken: claimToken,
- })
- case finalizeNone:
- // AppendUserMessage already finalized the row in-tx, or our
- // claim was lost to a concurrent reclaim. Do not touch it.
- }
-}
-
-func (d *Dispatcher) drop(ctx context.Context, msg InboundMessage, instID pgtype.UUID, reason DropReason) DispatchResult {
- _ = d.Audit.RecordDrop(ctx, AuditDropParams{
- InstallationID: instID,
- ChatID: msg.ChatID,
- EventType: msg.EventType,
- LarkEventID: msg.EventID,
- LarkMessageID: msg.MessageID,
- Reason: reason,
- })
- return DispatchResult{
- Outcome: OutcomeDropped,
- DropReason: reason,
- InstallationID: instID,
- }
-}
-
-func (d *Dispatcher) createIssueFromCommand(
- ctx context.Context,
- inst Installation,
- creatorUserID pgtype.UUID,
- sessionID pgtype.UUID,
- cmd IssueCommand,
-) (service.IssueCreateResult, error) {
- // Empty title at this point means the /issue alone fallback found
- // no previous user message either. The product copy ("请填标题")
- // belongs in the WS adapter's reply card; we surface this to the
- // caller as ErrEmptyIssueTitle so the dispatcher can short-circuit
- // without paying the IssueService cost.
- if cmd.Title == "" {
- return service.IssueCreateResult{}, ErrEmptyIssueTitle
- }
- params := service.IssueCreateParams{
- WorkspaceID: inst.WorkspaceID,
- Title: cmd.Title,
- Description: pgtype.Text{String: cmd.Description, Valid: cmd.Description != ""},
- Status: "todo",
- Priority: "none",
- AssigneeType: pgtype.Text{String: "agent", Valid: true},
- AssigneeID: inst.AgentID,
- CreatorType: "member",
- CreatorID: creatorUserID,
- OriginType: pgtype.Text{String: originLarkChat, Valid: true},
- OriginID: sessionID,
- }
- return d.IssueService.Create(ctx, params, service.IssueCreateOpts{})
-}
-
-// originLarkChat is the issue.origin_type label written for issues
-// created via the Lark `/issue` command. The analytics classifier in
-// service.classifyOrigin currently maps unknown origin_type values to
-// SourceManual with a warning — that is acceptable for MVP. A
-// dedicated analytics source label can be added when product asks for
-// it.
-const originLarkChat = "lark_chat"
-
-// ErrEmptyIssueTitle is returned by createIssueFromCommand when the
-// caller invoked /issue with no title AND the previous-user-message
-// fallback found nothing usable. The WS adapter translates this into
-// the "please supply a title" reply card per §2.3.
-var ErrEmptyIssueTitle = errors.New("issue title is empty")
diff --git a/server/internal/integrations/lark/dispatcher_test.go b/server/internal/integrations/lark/dispatcher_test.go
deleted file mode 100644
index 932ea150b7..0000000000
--- a/server/internal/integrations/lark/dispatcher_test.go
+++ /dev/null
@@ -1,1912 +0,0 @@
-package lark
-
-import (
- "context"
- "errors"
- "testing"
-
- "github.com/jackc/pgx/v5"
- "github.com/jackc/pgx/v5/pgtype"
- "github.com/multica-ai/multica/server/internal/service"
- db "github.com/multica-ai/multica/server/pkg/db/generated"
-)
-
-// fakeDedupRow is the test-side model of a lark_inbound_message_dedup
-// row. It tracks the three pieces of state that drive the dispatcher's
-// finalize logic: terminal flag (processed_at IS NOT NULL), the
-// currently-live claim_token, and a counter of how many distinct
-// claim_tokens have ever been minted for this message_id (used by
-// tests to assert that a stale-reclaim actually rotated the token).
-type fakeDedupRow struct {
- processed bool
- token pgtype.UUID
- // rotations is the number of times claim_token has been minted
- // for this row (1 = inserted, 2+ = stale-reclaimed N-1 times).
- rotations int
-}
-
-// fakeQueries is the unit-test seam for DispatcherQueries. Each field
-// is the canned response the fake returns from the corresponding
-// method; ErrNoRows variants pin specific failure modes.
-//
-// Dedup state mirrors lark_inbound_message_dedup with owner fencing:
-// each row carries a current claim_token, and Mark/Release require a
-// matching token to succeed (zero rows otherwise, exactly like the
-// production query). Tests pre-seed terminal rows by writing
-// processed=true; tests exercising the in-flight branch write
-// processed=false. The default empty map means "first delivery for
-// every message_id".
-type fakeQueries struct {
- installationByApp Installation
- installationErr error
- userBinding UserBinding
- userBindingErr error
- // userBindingByOpenID, when set, overrides userBinding per Lark open ID so a
- // test can simulate distinct senders in one chat (MUL-2645 latest-sender-wins).
- userBindingByOpenID map[string]UserBinding
- chatSession db.ChatSession
- chatSessionErr error
- workspace db.Workspace
- workspaceErr error
- // notWorkspaceMember inverts the default so the zero value means
- // "is a member" — existing tests that resolve a binding keep
- // flowing through the identity step without setting it. Set it true
- // to simulate a former member whose binding outlived membership.
- notWorkspaceMember bool
- membershipErr error
- calledMembership int
- dedup map[string]*fakeDedupRow
- dedupClaimErr error
- dedupReclaim bool // when true, in-flight rows are re-claimable (simulates staleness)
- nextTokenByte byte // monotonically incremented; ensures each minted token is distinct
- calledUserBinding int
- calledChatSession int
- calledInstallation int
- calledClaim int
- calledMark int
- calledRelease int
-}
-
-// mintToken produces a deterministic, distinct token per call so
-// tests can compare them. Production uses gen_random_uuid(); the
-// fake only needs uniqueness, not randomness.
-func (f *fakeQueries) mintToken() pgtype.UUID {
- f.nextTokenByte++
- return validUUID(0xA0 + f.nextTokenByte)
-}
-
-func (f *fakeQueries) GetLarkInstallationByAppID(ctx context.Context, appID string) (Installation, error) {
- f.calledInstallation++
- return f.installationByApp, f.installationErr
-}
-
-func (f *fakeQueries) GetLarkUserBindingByOpenID(ctx context.Context, arg GetUserBindingByOpenIDParams) (UserBinding, error) {
- f.calledUserBinding++
- if f.userBindingByOpenID != nil {
- if b, ok := f.userBindingByOpenID[arg.ChannelUserID]; ok {
- return b, nil
- }
- }
- return f.userBinding, f.userBindingErr
-}
-
-func (f *fakeQueries) GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error) {
- f.calledChatSession++
- return f.chatSession, f.chatSessionErr
-}
-
-// ClaimLarkInboundDedup mirrors the production query's three outcomes:
-//
-// - Row not present → INSERT succeeds, mints a fresh claim_token →
-// returns the row.
-// - Row present, processed=false, dedupReclaim=true → staleness
-// fallback re-takes the claim and ROTATES the claim_token →
-// returns the row.
-// - Row present otherwise → ON CONFLICT WHERE filter excludes the
-// UPDATE → RETURNING returns 0 rows → pgx.ErrNoRows.
-func (f *fakeQueries) ClaimLarkInboundDedup(ctx context.Context, arg ClaimInboundDedupParams) (InboundMessageDedup, error) {
- f.calledClaim++
- if f.dedupClaimErr != nil {
- return InboundMessageDedup{}, f.dedupClaimErr
- }
- if f.dedup == nil {
- f.dedup = map[string]*fakeDedupRow{}
- }
- key := dedupKey(arg.InstallationID, arg.MessageID)
- row, exists := f.dedup[key]
- if !exists {
- token := f.mintToken()
- f.dedup[key] = &fakeDedupRow{token: token, rotations: 1}
- return InboundMessageDedup{
- InstallationID: arg.InstallationID,
- MessageID: arg.MessageID,
- ClaimToken: token,
- }, nil
- }
- if !row.processed && f.dedupReclaim {
- // In-flight claim re-taken — rotate the token. This is what
- // fences the previous worker out: their saved claim_token no
- // longer matches the row's live one, so Mark/Release becomes
- // a no-op for them and (for the in-tx Mark) the chat_message
- // tx rolls back.
- row.token = f.mintToken()
- row.rotations++
- return InboundMessageDedup{
- InstallationID: arg.InstallationID,
- MessageID: arg.MessageID,
- ClaimToken: row.token,
- }, nil
- }
- return InboundMessageDedup{}, pgx.ErrNoRows
-}
-
-// dedupKey mirrors the production (installation_id, message_id) composite
-// PK in the test map. Installations are not isolated by message_id alone:
-// a Lark group with multiple bots installed delivers the SAME message_id
-// to every bot's WS, and each one must be free to claim, evaluate
-// AddressedToBot independently, and either ingest or drop as
-// not_addressed_in_group.
-func dedupKey(installationID pgtype.UUID, messageID string) string {
- var b [16]byte
- if installationID.Valid {
- b = installationID.Bytes
- }
- return string(b[:]) + "|" + messageID
-}
-
-// MarkLarkInboundDedupProcessed mirrors the production UPDATE: only
-// the holder of the current claim_token can mark the row, and only
-// while it is still in-flight (processed_at IS NULL). Mismatched token
-// or already-terminal row returns 0 rows affected (and nil error) —
-// the dispatcher relies on this for the in-tx ErrClaimLost path.
-func (f *fakeQueries) MarkLarkInboundDedupProcessed(ctx context.Context, arg MarkInboundDedupProcessedParams) (int64, error) {
- f.calledMark++
- if f.dedup == nil {
- return 0, nil
- }
- row, ok := f.dedup[dedupKey(arg.InstallationID, arg.MessageID)]
- if !ok {
- return 0, nil
- }
- if row.processed {
- return 0, nil
- }
- if row.token != arg.ClaimToken {
- return 0, nil
- }
- row.processed = true
- return 1, nil
-}
-
-// ReleaseLarkInboundDedup mirrors the production DELETE: only the
-// holder of the current claim_token can release the row, and only
-// while it is still in-flight.
-func (f *fakeQueries) GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error) {
- return f.workspace, f.workspaceErr
-}
-
-func (f *fakeQueries) IsWorkspaceMember(ctx context.Context, workspaceID, userID pgtype.UUID) (bool, error) {
- f.calledMembership++
- if f.membershipErr != nil {
- return false, f.membershipErr
- }
- return !f.notWorkspaceMember, nil
-}
-
-func (f *fakeQueries) ReleaseLarkInboundDedup(ctx context.Context, arg ReleaseInboundDedupParams) (int64, error) {
- f.calledRelease++
- if f.dedup == nil {
- return 0, nil
- }
- key := dedupKey(arg.InstallationID, arg.MessageID)
- row, ok := f.dedup[key]
- if !ok {
- return 0, nil
- }
- if row.processed {
- return 0, nil
- }
- if row.token != arg.ClaimToken {
- return 0, nil
- }
- delete(f.dedup, key)
- return 1, nil
-}
-
-// fakeChat is a stub ChatSessionService that records what the
-// dispatcher asked of it and returns canned outcomes.
-//
-// When `queries` is non-nil and the dispatcher hands AppendUserMessage
-// a valid ClaimToken, the stub mirrors the production in-tx Mark: it
-// invokes fakeQueries.MarkLarkInboundDedupProcessed with the supplied
-// token before returning success. This is what reproduces the
-// stale-reclaim race in tests — if the token has been rotated by a
-// concurrent Claim, the Mark matches zero rows and AppendUserMessage
-// returns ErrClaimLost, exactly like the real chatSessionService's
-// rolled-back transaction.
-//
-// `beforeAppend` is a hook fired at the top of AppendUserMessage, used
-// by the stale-reclaim regression test to inject a concurrent reclaim
-// between the dispatcher's Claim and AppendUserMessage's in-tx Mark.
-type fakeChat struct {
- ensureID pgtype.UUID
- ensureErr error
- appendResult AppendResult
- appendErr error
- queries *fakeQueries // when set, runs the in-tx Mark
- beforeAppend func(AppendUserMessageParams) // race-injection hook
- calledEnsure int
- calledAppend int
- lastAppendParams AppendUserMessageParams
- lastEnsureParams EnsureChatSessionParams
-}
-
-func (f *fakeChat) EnsureChatSession(ctx context.Context, p EnsureChatSessionParams) (pgtype.UUID, error) {
- f.calledEnsure++
- f.lastEnsureParams = p
- return f.ensureID, f.ensureErr
-}
-
-func (f *fakeChat) AppendUserMessage(ctx context.Context, p AppendUserMessageParams) (AppendResult, error) {
- f.calledAppend++
- f.lastAppendParams = p
- if f.beforeAppend != nil {
- f.beforeAppend(p)
- }
- if f.appendErr != nil {
- return f.appendResult, f.appendErr
- }
- res := f.appendResult
- // Mirror chatSessionService.AppendUserMessage: when the dispatcher
- // supplies a claim token, Mark in-tx; zero rows ↔ stale-reclaim
- // rotated the token under our feet, surface ErrClaimLost.
- if f.queries != nil && p.ClaimToken.Valid && p.LarkMessageID != "" {
- rows, err := f.queries.MarkLarkInboundDedupProcessed(ctx, MarkInboundDedupProcessedParams{
- InstallationID: p.InstallationID,
- MessageID: p.LarkMessageID,
- ClaimToken: p.ClaimToken,
- })
- if err != nil {
- return AppendResult{}, err
- }
- if rows == 0 {
- return AppendResult{}, ErrClaimLost
- }
- res.DedupMarked = true
- }
- return res, nil
-}
-
-type fakeAudit struct {
- drops []AuditDropParams
-}
-
-func (f *fakeAudit) RecordDrop(ctx context.Context, p AuditDropParams) error {
- f.drops = append(f.drops, p)
- return nil
-}
-
-type fakeIssueCreator struct {
- called int
- params service.IssueCreateParams
- result service.IssueCreateResult
- err error
-}
-
-func (f *fakeIssueCreator) Create(ctx context.Context, p service.IssueCreateParams, _ service.IssueCreateOpts) (service.IssueCreateResult, error) {
- f.called++
- f.params = p
- return f.result, f.err
-}
-
-type fakeEnqueuer struct {
- called int
- task db.AgentTaskQueue
- err error
- lastInitiatorUID pgtype.UUID
- lastForceFresh bool
-}
-
-func (f *fakeEnqueuer) EnqueueChatTask(ctx context.Context, _ db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error) {
- f.called++
- f.lastInitiatorUID = initiatorUserID
- f.lastForceFresh = forceFreshSession
- return f.task, f.err
-}
-
-// validUUID builds a deterministic Valid pgtype.UUID from the supplied
-// byte. Useful for distinguishing IDs in assertions.
-func validUUID(b byte) pgtype.UUID {
- var u pgtype.UUID
- for i := range u.Bytes {
- u.Bytes[i] = b
- }
- u.Valid = true
- return u
-}
-
-func activeInstallation() Installation {
- return Installation{
- ID: validUUID(0x11),
- WorkspaceID: validUUID(0x22),
- AgentID: validUUID(0x33),
- InstallerUserID: validUUID(0x99),
- Status: string(InstallationActive),
- }
-}
-
-// seedDedupKey composes a fake-table key for the default activeInstallation
-// fixture (installation_id = validUUID(0x11)). Pre-seeded dedup rows in
-// dispatcher tests use this to satisfy the new (installation_id,
-// message_id) composite PK.
-func seedDedupKey(messageID string) string {
- return dedupKey(validUUID(0x11), messageID)
-}
-
-func boundUser() UserBinding {
- return UserBinding{
- ID: validUUID(0x44),
- WorkspaceID: validUUID(0x22),
- MulticaUserID: validUUID(0x55),
- InstallationID: validUUID(0x11),
- ChannelUserID: "ou_user_a",
- }
-}
-
-func TestDispatcher_UnknownAppDropped(t *testing.T) {
- queries := &fakeQueries{installationErr: pgx.ErrNoRows}
- audit := &fakeAudit{}
- d := &Dispatcher{Queries: queries, Audit: audit}
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "missing",
- EventType: "im.message.receive_v1",
- })
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if res.Outcome != OutcomeDropped || res.DropReason != DropReasonInvalidEvent {
- t.Fatalf("unexpected outcome: %+v", res)
- }
- if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonInvalidEvent {
- t.Fatalf("expected one invalid_event audit row, got %+v", audit.drops)
- }
- if audit.drops[0].InstallationID.Valid {
- t.Fatalf("audit row should omit installation_id for unknown app: %+v", audit.drops[0])
- }
-}
-
-func TestDispatcher_RevokedInstallationDropped(t *testing.T) {
- inst := activeInstallation()
- inst.Status = string(InstallationRevoked)
- queries := &fakeQueries{installationByApp: inst}
- audit := &fakeAudit{}
- d := &Dispatcher{Queries: queries, Audit: audit}
-
- res, err := d.Handle(context.Background(), InboundMessage{AppID: "ok"})
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if res.DropReason != DropReasonRevokedInstallation {
- t.Fatalf("got drop reason %q", res.DropReason)
- }
- if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonRevokedInstallation {
- t.Fatalf("audit drops: %+v", audit.drops)
- }
-}
-
-func TestDispatcher_GroupWithoutMentionDropped(t *testing.T) {
- queries := &fakeQueries{installationByApp: activeInstallation()}
- audit := &fakeAudit{}
- d := &Dispatcher{Queries: queries, Audit: audit}
-
- res, _ := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeGroup,
- AddressedToBot: false,
- })
- if res.DropReason != DropReasonNotAddressedInGroup {
- t.Fatalf("got drop reason %q", res.DropReason)
- }
- if queries.calledUserBinding != 0 {
- t.Fatalf("identity check should be skipped before group filter, got %d calls", queries.calledUserBinding)
- }
-}
-
-func TestDispatcher_UnboundUserAsksForBinding(t *testing.T) {
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBindingErr: pgx.ErrNoRows,
- }
- audit := &fakeAudit{}
- d := &Dispatcher{Queries: queries, Audit: audit}
-
- res, _ := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- })
- if res.Outcome != OutcomeNeedsBinding {
- t.Fatalf("expected OutcomeNeedsBinding, got %q", res.Outcome)
- }
- if res.DropReason != DropReasonUnboundUser {
- t.Fatalf("expected unbound_user drop reason, got %q", res.DropReason)
- }
- if res.SenderOpenID != "ou_user_a" {
- t.Fatalf("sender propagation broken: %q", res.SenderOpenID)
- }
- if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonUnboundUser {
- t.Fatalf("expected one unbound_user audit row, got %+v", audit.drops)
- }
-}
-
-// A binding row that outlived its user's workspace membership (possible
-// now that MUL-3515 §4 removed the member FK that used to cascade it
-// away) must be dropped at the explicit re-check, never reaching
-// chat_session — the §4.3 safety property.
-func TestDispatcher_FormerMemberWithStaleBindingDropped(t *testing.T) {
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(), // binding row still present...
- notWorkspaceMember: true, // ...but the user is no longer a member
- }
- audit := &fakeAudit{}
- chat := &fakeChat{}
- d := &Dispatcher{Queries: queries, Audit: audit, Chat: chat}
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- MessageID: "msg-stale",
- })
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if res.Outcome != OutcomeDropped {
- t.Fatalf("expected OutcomeDropped, got %q", res.Outcome)
- }
- if res.DropReason != DropReasonNonWorkspaceMember {
- t.Fatalf("expected non_workspace_member drop reason, got %q", res.DropReason)
- }
- if queries.calledMembership != 1 {
- t.Fatalf("expected exactly one membership check, got %d", queries.calledMembership)
- }
- if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonNonWorkspaceMember {
- t.Fatalf("expected one non_workspace_member audit row, got %+v", audit.drops)
- }
- if chat.calledEnsure != 0 {
- t.Fatalf("a non-member must not reach chat_session; got %d ensure calls", chat.calledEnsure)
- }
-}
-
-// An infra error from the membership re-check is surfaced (not silently
-// treated as "not a member"), so the dispatcher releases the dedup claim
-// and the WS adapter can retry instead of permanently dropping the event.
-func TestDispatcher_MembershipCheckErrorSurfaces(t *testing.T) {
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- membershipErr: errors.New("member lookup failed"),
- }
- chat := &fakeChat{}
- d := &Dispatcher{Queries: queries, Audit: &fakeAudit{}, Chat: chat}
-
- _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- MessageID: "msg-err",
- })
- if err == nil {
- t.Fatal("expected the membership-check error to surface")
- }
- if chat.calledEnsure != 0 {
- t.Fatalf("must not reach chat_session on a membership-check error; got %d", chat.calledEnsure)
- }
-}
-
-func TestDispatcher_PlainMessageEnqueuesTask(t *testing.T) {
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{
- ensureID: sessionID,
- appendResult: AppendResult{},
- }
- enq := &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: enq,
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi bot",
- MessageID: "msg-1",
- })
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if res.Outcome != OutcomeIngested {
- t.Fatalf("expected ingested, got %q", res.Outcome)
- }
- // The run trigger is debounced (MUL-2968): no TaskID is surfaced
- // synchronously anymore, and with batching disabled the flush fires
- // inline so the enqueue is observable right here.
- if res.TaskID.Valid {
- t.Fatalf("TaskID must not be set synchronously after debounce; got %+v", res.TaskID)
- }
- if enq.called != 1 {
- t.Fatalf("expected exactly one EnqueueChatTask at flush; called=%d", enq.called)
- }
- // For p2p the session creator should be the bound user, not the
- // installer — verifies the chat-type branch in Handle.
- if chat.lastEnsureParams.Sender != queries.userBinding.MulticaUserID {
- t.Fatalf("p2p session creator should be sender; got %+v", chat.lastEnsureParams.Sender)
- }
- // The task initiator is also the sender (MUL-2645).
- if enq.lastInitiatorUID != queries.userBinding.MulticaUserID {
- t.Fatalf("p2p task initiator should be sender; got %+v want %+v",
- enq.lastInitiatorUID, queries.userBinding.MulticaUserID)
- }
- if enq.lastForceFresh {
- t.Fatalf("plain chat message must not force a fresh session")
- }
-}
-
-func TestDispatcher_FreshMessageEnqueuesFreshTask(t *testing.T) {
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- enq := &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: enq,
- }
-
- _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "rebuild the plan",
- ForceFreshSession: true,
- MessageID: "msg-fresh",
- })
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if enq.called != 1 {
- t.Fatalf("expected exactly one EnqueueChatTask at flush; called=%d", enq.called)
- }
- if !enq.lastForceFresh {
- t.Fatalf("fresh Lark message should force a fresh chat task")
- }
-}
-
-// TestDispatcher_ForwardsThreadIDToAppend verifies the dispatcher
-// threads the inbound message's thread_id into AppendUserMessage, which
-// is what lets the chat binding remember the topic so the outbound
-// patcher can reply back into it.
-func TestDispatcher_ForwardsThreadIDToAppend(t *testing.T) {
- inst := activeInstallation()
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: inst,
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeGroup,
- AddressedToBot: true,
- SenderOpenID: "ou_user_a",
- Body: "hey in a topic",
- MessageID: "om_in_thread",
- ThreadID: "omt_topic_42",
- })
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if chat.lastAppendParams.LarkThreadID != "omt_topic_42" {
- t.Errorf("LarkThreadID forwarded to AppendUserMessage: got %q want omt_topic_42",
- chat.lastAppendParams.LarkThreadID)
- }
- if chat.lastAppendParams.LarkMessageID != "om_in_thread" {
- t.Errorf("LarkMessageID forwarded to AppendUserMessage: got %q want om_in_thread",
- chat.lastAppendParams.LarkMessageID)
- }
-}
-
-func TestDispatcher_GroupMessageUsesInstallerAsCreator(t *testing.T) {
- inst := activeInstallation()
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: inst,
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- _, _ = d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeGroup,
- AddressedToBot: true,
- SenderOpenID: "ou_user_a",
- Body: "hey",
- MessageID: "msg-g",
- })
- if chat.lastEnsureParams.Sender != inst.InstallerUserID {
- t.Fatalf("group session creator should be installer; got %+v want %+v",
- chat.lastEnsureParams.Sender, inst.InstallerUserID)
- }
-}
-
-// TestDispatcher_GroupMessageEnqueuesWithSenderAsInitiator is the MUL-2645
-// review regression: in a Lark group chat the session creator is the installer,
-// but the TASK INITIATOR must be the actual message sender. Before the fix the
-// claim derived the initiator from chat_session.creator_id (= installer), so
-// every group member appeared to the agent as the installer. The dispatcher now
-// passes the sender's MulticaUserID to EnqueueChatTask; this asserts that the
-// enqueued initiator is the sender (boundUser), NOT the installer.
-func TestDispatcher_GroupMessageEnqueuesWithSenderAsInitiator(t *testing.T) {
- inst := activeInstallation()
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: inst,
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- enq := &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: enq,
- }
-
- // Batching is disabled (d.batcher == nil), so the flush fires inline and the
- // enqueue is observable synchronously.
- _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeGroup,
- AddressedToBot: true,
- SenderOpenID: "ou_user_a",
- Body: "hey bot",
- MessageID: "msg-g2",
- })
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if enq.called != 1 {
- t.Fatalf("expected exactly one EnqueueChatTask at flush; called=%d", enq.called)
- }
- // Session creator stays the installer (member-churn stability)...
- if chat.lastEnsureParams.Sender != inst.InstallerUserID {
- t.Fatalf("group session creator should be installer; got %+v", chat.lastEnsureParams.Sender)
- }
- // ...but the task initiator is the SENDER, not the installer.
- if enq.lastInitiatorUID != queries.userBinding.MulticaUserID {
- t.Fatalf("group task initiator should be the sender; got %+v want %+v",
- enq.lastInitiatorUID, queries.userBinding.MulticaUserID)
- }
- if enq.lastInitiatorUID == inst.InstallerUserID {
- t.Fatalf("group task initiator must NOT be the installer (%+v)", inst.InstallerUserID)
- }
-}
-
-func TestDispatcher_DedupHitDoesNotEnqueue(t *testing.T) {
- // Pre-seed the dedup table so the top-level dedup gate trips on
- // the first Handle call — simulates a Lark reconnect replaying an
- // event we already processed in a previous run.
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- dedup: map[string]*fakeDedupRow{seedDedupKey("msg-dup"): {processed: true, token: validUUID(0xAB)}},
- }
- chat := &fakeChat{
- ensureID: validUUID(0x66),
- }
- enq := &fakeEnqueuer{}
- audit := &fakeAudit{}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: audit,
- TaskService: enq,
- }
-
- res, _ := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "replay",
- MessageID: "msg-dup",
- })
- if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {
- t.Fatalf("expected duplicate drop, got %+v", res)
- }
- if enq.called != 0 {
- t.Fatalf("dedup hit must not enqueue task, called=%d", enq.called)
- }
- if chat.calledEnsure != 0 || chat.calledAppend != 0 {
- t.Fatalf("dedup hit must short-circuit before chat lookup; ensure=%d append=%d",
- chat.calledEnsure, chat.calledAppend)
- }
- if queries.calledUserBinding != 0 {
- t.Fatalf("dedup hit must short-circuit before identity check, got %d binding calls",
- queries.calledUserBinding)
- }
- if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonDuplicate {
- t.Fatalf("expected duplicate audit row, got %+v", audit.drops)
- }
-}
-
-// TestDispatcher_DedupBeforeGroupFilter pins the §4.3 ordering: a
-// replayed group event that was NOT addressed to the Bot must NOT
-// re-write a not_addressed_in_group audit row on every reconnect, and
-// must NOT re-trigger any binding-prompt side effect. The top-level
-// dedup gate is what guarantees this; before this fix the group
-// filter ran first and unbounded replays produced unbounded audit
-// noise + reply-card spam.
-func TestDispatcher_DedupBeforeGroupFilter(t *testing.T) {
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- dedup: map[string]*fakeDedupRow{seedDedupKey("msg-replay"): {processed: true, token: validUUID(0xAB)}},
- }
- audit := &fakeAudit{}
- d := &Dispatcher{Queries: queries, Audit: audit}
-
- res, _ := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeGroup,
- AddressedToBot: false,
- MessageID: "msg-replay",
- })
- if res.DropReason != DropReasonDuplicate {
- t.Fatalf("dedup must beat group filter; got drop reason %q", res.DropReason)
- }
- if len(audit.drops) != 1 || audit.drops[0].Reason != DropReasonDuplicate {
- t.Fatalf("expected exactly one duplicate audit row, got %+v", audit.drops)
- }
-}
-
-// TestDispatcher_DedupIsScopedPerInstallation pins MUL-2671's multi-bot
-// invariant: in a Lark group with TWO Multica bots installed, the
-// same Lark message_id arrives at both WS supervisors and each one
-// MUST be free to claim, evaluate AddressedToBot independently, and
-// either ingest or drop. Before the (installation_id, message_id)
-// composite PK landed, whichever WS claimed first would mark the
-// shared row terminal and the bot that was actually @-ed would lose
-// to dedup before its filter ran — every @ to the "second" bot
-// silently disappeared.
-func TestDispatcher_DedupIsScopedPerInstallation(t *testing.T) {
- otherInst := activeInstallation()
- otherInst.ID = validUUID(0x12) // distinct from the default 0x11
- queries := &fakeQueries{
- installationByApp: otherInst,
- // Pre-seed a terminal dedup row for installation 0x11 — that's
- // the OTHER bot's already-processed claim. The current Handle
- // runs under installation 0x12 (composite-key miss → fresh
- // claim → continues processing).
- dedup: map[string]*fakeDedupRow{
- dedupKey(validUUID(0x11), "msg-shared"): {processed: true, token: validUUID(0xAB)},
- },
- }
- audit := &fakeAudit{}
- d := &Dispatcher{Queries: queries, Audit: audit}
-
- res, _ := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeGroup,
- AddressedToBot: false, // simulate "not @-ed FROM this bot's perspective"
- MessageID: "msg-shared",
- })
- if res.DropReason != DropReasonNotAddressedInGroup {
- t.Fatalf("composite-key dedup miss must let group filter run, got drop reason %q", res.DropReason)
- }
- // And the new (0x12, msg-shared) row must now exist — only the
- // other installation's row was pre-seeded.
- if _, ok := queries.dedup[dedupKey(otherInst.ID, "msg-shared")]; !ok {
- t.Fatalf("expected a fresh claim row for installation 0x12; got %v", queries.dedup)
- }
-}
-
-// TestDispatcher_DedupBeforeIdentityCheck pins the same ordering for
-// unbound users: a replayed event from an unbound open_id must not
-// re-fire the OutcomeNeedsBinding path on every reconnect — that
-// would spam the user with binding-prompt cards.
-func TestDispatcher_DedupBeforeIdentityCheck(t *testing.T) {
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBindingErr: pgx.ErrNoRows, // unbound — would normally trigger OutcomeNeedsBinding
- dedup: map[string]*fakeDedupRow{seedDedupKey("msg-replay"): {processed: true, token: validUUID(0xAB)}},
- }
- audit := &fakeAudit{}
- d := &Dispatcher{Queries: queries, Audit: audit}
-
- res, _ := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- MessageID: "msg-replay",
- })
- if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {
- t.Fatalf("dedup must beat identity check; got %+v", res)
- }
- if queries.calledUserBinding != 0 {
- t.Fatalf("identity check must not run for a deduped replay, got %d calls",
- queries.calledUserBinding)
- }
-}
-
-func TestDispatcher_IssueCommandCreatesIssue(t *testing.T) {
- sessionID := validUUID(0x66)
- inst := activeInstallation()
- queries := &fakeQueries{
- installationByApp: inst,
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},
- workspace: db.Workspace{ID: inst.WorkspaceID, IssuePrefix: "MUL"},
- }
- chat := &fakeChat{
- ensureID: sessionID,
- appendResult: AppendResult{
- IssueCommand: &IssueCommand{Title: "ship it", Description: "ship the thing"},
- },
- }
- issueSvc := &fakeIssueCreator{result: service.IssueCreateResult{Issue: db.Issue{
- ID: validUUID(0x88),
- Number: 42,
- Title: "ship it",
- }}}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- IssueService: issueSvc,
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "/issue ship it\nship the thing",
- MessageID: "msg-ic",
- })
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if issueSvc.called != 1 {
- t.Fatalf("expected IssueService.Create called once, got %d", issueSvc.called)
- }
- if issueSvc.params.Title != "ship it" || issueSvc.params.Description.String != "ship the thing" {
- t.Fatalf("wrong issue params: %+v", issueSvc.params)
- }
- if issueSvc.params.OriginType.String != originLarkChat {
- t.Fatalf("origin_type should be lark_chat, got %q", issueSvc.params.OriginType.String)
- }
- if !issueSvc.params.AssigneeType.Valid || issueSvc.params.AssigneeType.String != "agent" ||
- issueSvc.params.AssigneeID != inst.AgentID {
- t.Fatalf("assignee should default to the installation's agent: %+v", issueSvc.params)
- }
- if !res.IssueID.Valid || res.IssueNumber != 42 {
- t.Fatalf("issue id/number not propagated: %+v", res)
- }
- // IssueIdentifier and IssueTitle are how the OutcomeReplier knows
- // what to put in the "Created [MUL-42] ship it" confirmation
- // message. They MUST be populated whenever a /issue command
- // produced a row.
- if res.IssueIdentifier != "MUL-42" {
- t.Fatalf("issue identifier should reflect workspace prefix; got %q", res.IssueIdentifier)
- }
- if res.IssueTitle != "ship it" {
- t.Fatalf("issue title should be propagated; got %q", res.IssueTitle)
- }
-}
-
-// TestDispatcher_IssueIdentifierFallsBackToNumberOnWorkspaceLookupErr
-// pins the degrade-gracefully behaviour: a Postgres blip on the
-// workspace row should NOT silently drop the issue-created
-// confirmation. We emit "#42" instead of "MUL-42" in that case so
-// the user still sees that the issue was created.
-func TestDispatcher_IssueIdentifierFallsBackToNumberOnWorkspaceLookupErr(t *testing.T) {
- sessionID := validUUID(0x66)
- inst := activeInstallation()
- queries := &fakeQueries{
- installationByApp: inst,
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},
- workspaceErr: errors.New("workspace lookup failed"),
- }
- chat := &fakeChat{
- ensureID: sessionID,
- appendResult: AppendResult{
- IssueCommand: &IssueCommand{Title: "fallback path", Description: ""},
- },
- }
- issueSvc := &fakeIssueCreator{result: service.IssueCreateResult{Issue: db.Issue{
- ID: validUUID(0x88),
- Number: 7,
- Title: "fallback path",
- }}}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- IssueService: issueSvc,
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "/issue fallback path",
- MessageID: "msg-fallback",
- })
- if err != nil {
- t.Fatalf("workspace lookup error must NOT abort dispatch; got %v", err)
- }
- if res.IssueIdentifier != "#7" {
- t.Errorf("expected fallback identifier '#7'; got %q", res.IssueIdentifier)
- }
-}
-
-func TestDispatcher_EmptyTitleSurfacesError(t *testing.T) {
- sessionID := validUUID(0x66)
- inst := activeInstallation()
- queries := &fakeQueries{
- installationByApp: inst,
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},
- }
- chat := &fakeChat{
- ensureID: sessionID,
- appendResult: AppendResult{
- IssueCommand: &IssueCommand{Title: ""},
- },
- }
- issueSvc := &fakeIssueCreator{}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- IssueService: issueSvc,
- TaskService: &fakeEnqueuer{},
- }
-
- _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "/issue",
- MessageID: "msg-empty",
- })
- if !errors.Is(err, ErrEmptyIssueTitle) {
- t.Fatalf("expected ErrEmptyIssueTitle wrapped, got %v", err)
- }
- if issueSvc.called != 0 {
- t.Fatalf("IssueService.Create must not run when title is empty")
- }
-}
-
-// captureReply is a FlushReply seam: it records every offline/archived
-// notice the dispatcher emits at flush time so tests can assert what the
-// user-facing card would say.
-type captureReply struct {
- count int
- results []DispatchResult
-}
-
-func (c *captureReply) reply(_ context.Context, _ Installation, _ InboundMessage, res DispatchResult) {
- c.count++
- c.results = append(c.results, res)
-}
-
-func TestDispatcher_AgentOfflineRepliesAtFlush(t *testing.T) {
- // With the run trigger debounced (MUL-2968), the agent-offline verdict
- // is only known at flush time. Handle itself returns OutcomeIngested
- // (the message is durable + ACKed); the offline notice is delivered
- // through FlushReply. With batching disabled the flush fires inline.
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- enq := &fakeEnqueuer{err: service.ErrChatTaskAgentNoRuntime}
- cap := &captureReply{}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: enq,
- FlushReply: cap.reply,
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: "msg-off",
- })
- if err != nil {
- t.Fatalf("offline path should not return error, got %v", err)
- }
- if res.Outcome != OutcomeIngested {
- t.Fatalf("synchronous outcome must be ingested, got %q", res.Outcome)
- }
- if enq.called != 1 {
- t.Fatalf("flush must call EnqueueChatTask exactly once; called=%d", enq.called)
- }
- if cap.count != 1 {
- t.Fatalf("expected exactly one flush reply; got %d", cap.count)
- }
- if cap.results[0].Outcome != OutcomeAgentOffline {
- t.Fatalf("expected OutcomeAgentOffline at flush, got %q", cap.results[0].Outcome)
- }
- if cap.results[0].ChatSessionID != sessionID {
- t.Fatalf("session id not propagated to flush reply: %+v", cap.results[0].ChatSessionID)
- }
-}
-
-func TestDispatcher_AgentArchivedRepliesAtFlush(t *testing.T) {
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- enq := &fakeEnqueuer{err: service.ErrChatTaskAgentArchived}
- cap := &captureReply{}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: enq,
- FlushReply: cap.reply,
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: "msg-arch",
- })
- if err != nil {
- t.Fatalf("archived path should not return error, got %v", err)
- }
- if res.Outcome != OutcomeIngested {
- t.Fatalf("synchronous outcome must be ingested, got %q", res.Outcome)
- }
- if cap.count != 1 || cap.results[0].Outcome != OutcomeAgentArchived {
- t.Fatalf("expected OutcomeAgentArchived at flush, got count=%d results=%+v", cap.count, cap.results)
- }
-}
-
-func TestDispatcher_FlushInfraFailureIsNotReplied(t *testing.T) {
- // A DB / load / create failure from EnqueueChatTask is NOT a
- // productizable state. The inbound frame was ACKed and the message is
- // already durable, so Handle returns no error (nothing for the
- // connector to retry against), the failure is logged, and NO
- // offline/archived card is sent — a bogus "offline" card would
- // silently hide the outage.
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- infraErr := errors.New("create chat task: connection refused")
- enq := &fakeEnqueuer{err: infraErr}
- cap := &captureReply{}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: enq,
- FlushReply: cap.reply,
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: "msg-infra",
- })
- if err != nil {
- t.Fatalf("flush infra failure must not surface from Handle, got %v", err)
- }
- if res.Outcome != OutcomeIngested {
- t.Fatalf("synchronous outcome must be ingested, got %q", res.Outcome)
- }
- if enq.called != 1 {
- t.Fatalf("flush must attempt EnqueueChatTask once; called=%d", enq.called)
- }
- if cap.count != 0 {
- t.Fatalf("infra failure must not emit any offline/archived card; replies=%d", cap.count)
- }
-}
-
-func TestDispatcher_DebounceCoalescesRunTrigger(t *testing.T) {
- // Two messages in the same chat_session within the silence window must
- // produce exactly ONE EnqueueChatTask (one agent run). The run reads
- // the whole session history, so both messages are covered by it. This
- // is the core MUL-2968 behaviour: "forward a transcript, then type a
- // note" stops triggering two runs.
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- enq := &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}}
- f := &fakeTimerFactory{}
- d := &Dispatcher{Queries: queries, Chat: chat, Audit: &fakeAudit{}, TaskService: enq}
- d.batcher = newTestBatcher(f)
-
- send := func(id string) {
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: id,
- })
- if err != nil {
- t.Fatalf("unexpected error for %s: %v", id, err)
- }
- if res.Outcome != OutcomeIngested {
- t.Fatalf("expected ingested for %s, got %q", id, res.Outcome)
- }
- }
-
- send("m1")
- send("m2")
-
- // Both messages are durable + ACKed, but the run is still pending.
- if enq.called != 0 {
- t.Fatalf("run trigger must be debounced; enqueue called=%d before window closed", enq.called)
- }
- if got := d.batcher.pendingCount(); got != 1 {
- t.Fatalf("both messages share one session window; pending=%d", got)
- }
-
- f.fireArmed() // window closes
- if enq.called != 1 {
- t.Fatalf("a coalesced burst must enqueue exactly once; called=%d", enq.called)
- }
-
- // A message arriving after the window fired is a new burst → new run.
- send("m3")
- f.fireArmed()
- if enq.called != 2 {
- t.Fatalf("a message after the window must start a new run; called=%d", enq.called)
- }
-}
-
-func TestDispatcher_DebouncePreservesFreshAcrossWindow(t *testing.T) {
- // If any message in the coalesced window is /new, the single
- // resulting run must be fresh even though the latest sender/message
- // still supplies the reply target and initiator.
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- enq := &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}}
- f := &fakeTimerFactory{}
- d := &Dispatcher{Queries: queries, Chat: chat, Audit: &fakeAudit{}, TaskService: enq}
- d.batcher = newTestBatcher(f)
-
- send := func(id string, forceFresh bool) {
- if _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- ForceFreshSession: forceFresh,
- MessageID: id,
- }); err != nil {
- t.Fatalf("unexpected error for %s: %v", id, err)
- }
- }
-
- send("m-fresh", true)
- send("m-normal", false)
- f.fireArmed()
-
- if enq.called != 1 {
- t.Fatalf("a coalesced burst must enqueue exactly once; called=%d", enq.called)
- }
- if !enq.lastForceFresh {
- t.Fatalf("fresh directive should stick across the debounced window")
- }
-}
-
-// TestDispatcher_LatestSenderWinsAsInitiator pins the MUL-2645 batching
-// decision: when several people speak in one chat within a single silence
-// window, the coalesced run's initiator is the LAST sender. The debouncer keeps
-// only the latest scheduled flush per session, and each flush captures its own
-// message's sender, so the final enqueue carries the last sender's identity.
-func TestDispatcher_LatestSenderWinsAsInitiator(t *testing.T) {
- sessionID := validUUID(0x66)
- alice := boundUser() // MulticaUserID 0x55, open id ou_alice below
- bob := boundUser()
- bob.MulticaUserID = validUUID(0xBB)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- userBindingByOpenID: map[string]UserBinding{"ou_alice": alice, "ou_bob": bob},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- enq := &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}}
- f := &fakeTimerFactory{}
- d := &Dispatcher{Queries: queries, Chat: chat, Audit: &fakeAudit{}, TaskService: enq}
- d.batcher = newTestBatcher(f)
-
- send := func(openID, msgID string) {
- if _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: OpenID(openID),
- Body: "hi",
- MessageID: msgID,
- }); err != nil {
- t.Fatalf("unexpected error for %s: %v", msgID, err)
- }
- }
-
- send("ou_alice", "m1") // Alice first...
- send("ou_bob", "m2") // ...then Bob, within the same window.
- f.fireArmed() // window closes → one coalesced run
-
- if enq.called != 1 {
- t.Fatalf("a coalesced burst must enqueue exactly once; called=%d", enq.called)
- }
- if enq.lastInitiatorUID != bob.MulticaUserID {
- t.Fatalf("latest sender (Bob) should be the initiator; got %+v want %+v",
- enq.lastInitiatorUID, bob.MulticaUserID)
- }
-}
-
-// TestDispatcher_EnsureChatSessionFailureReleasesClaim is the
-// regression for the dedup-blocker Elon flagged in PR #3277: the
-// pre-fix Dispatcher inserted the dedup row before EnsureChatSession,
-// so an infra error in EnsureChatSession would leave a permanent
-// dedup row behind and the WS adapter's retry would be mis-classified
-// as a duplicate — the user's message would be silently lost.
-//
-// With the two-phase claim/Release contract, the first attempt's
-// claim is released, and the retry must observe a fresh first
-// delivery: identity check + EnsureChatSession + AppendUserMessage
-// run normally, no duplicate drop.
-func TestDispatcher_EnsureChatSessionFailureReleasesClaim(t *testing.T) {
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{
- ensureID: sessionID,
- ensureErr: errors.New("ensure chat session: connection refused"),
- }
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- // First attempt — infra error in EnsureChatSession.
- _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: "msg-retry",
- })
- if err == nil {
- t.Fatalf("first attempt should surface ensure-chat-session error, got nil")
- }
- if queries.calledMark != 0 {
- t.Fatalf("must not mark processed when no durable side effect landed; calledMark=%d", queries.calledMark)
- }
- if queries.calledRelease != 1 {
- t.Fatalf("must release the claim on pre-durable infra error; calledRelease=%d", queries.calledRelease)
- }
- if _, present := queries.dedup[seedDedupKey("msg-retry")]; present {
- t.Fatalf("release must delete the in-flight claim row; dedup=%+v", queries.dedup)
- }
-
- // Retry — same message_id, ensure succeeds this time. The claim
- // was released, so the retry must be able to re-claim and run
- // the full ingest pipeline. The bug being regressed would have
- // caused a DropReasonDuplicate here.
- chat.ensureErr = nil
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: "msg-retry",
- })
- if err != nil {
- t.Fatalf("retry should succeed, got %v", err)
- }
- if res.Outcome != OutcomeIngested {
- t.Fatalf("retry must ingest; got outcome=%q reason=%q", res.Outcome, res.DropReason)
- }
- if chat.calledAppend != 1 {
- t.Fatalf("retry must reach AppendUserMessage; calledAppend=%d", chat.calledAppend)
- }
- if queries.calledMark != 1 {
- t.Fatalf("retry must mark processed; calledMark=%d", queries.calledMark)
- }
- if row, ok := queries.dedup[seedDedupKey("msg-retry")]; !ok || !row.processed {
- t.Fatalf("retry must finalize claim as processed; dedup=%+v", queries.dedup)
- }
-
- // A third attempt with the same message_id (post-success replay)
- // must now be a duplicate-drop — the Mark from the retry is the
- // terminal state.
- queries.calledClaim = 0
- chat.calledAppend = 0
- res, err = d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: "msg-retry",
- })
- if err != nil {
- t.Fatalf("post-success replay should not error, got %v", err)
- }
- if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {
- t.Fatalf("post-success replay must duplicate-drop; got %+v", res)
- }
- if chat.calledAppend != 0 {
- t.Fatalf("post-success replay must not re-append; calledAppend=%d", chat.calledAppend)
- }
-}
-
-// TestDispatcher_AppendUserMessageFailureReleasesClaim is the
-// regression for the second variant of the dedup blocker: an infra
-// error from AppendUserMessage (e.g. tx commit failure) must also
-// release the claim so a retry can re-ingest. AppendUserMessage's
-// transaction is atomic — an error means rollback, no chat_message
-// landed.
-func TestDispatcher_AppendUserMessageFailureReleasesClaim(t *testing.T) {
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{
- ensureID: sessionID,
- appendErr: errors.New("create chat message: connection refused"),
- }
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- // First attempt — append fails.
- _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: "msg-append-retry",
- })
- if err == nil {
- t.Fatalf("first attempt should surface append error, got nil")
- }
- if queries.calledMark != 0 {
- t.Fatalf("must not mark processed when AppendUserMessage rolled back; calledMark=%d", queries.calledMark)
- }
- if queries.calledRelease != 1 {
- t.Fatalf("must release the claim; calledRelease=%d", queries.calledRelease)
- }
-
- // Retry — same message_id, append succeeds.
- chat.appendErr = nil
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: "msg-append-retry",
- })
- if err != nil {
- t.Fatalf("retry should succeed, got %v", err)
- }
- if res.Outcome != OutcomeIngested {
- t.Fatalf("retry must ingest; got %+v", res)
- }
- if chat.calledAppend != 2 {
- t.Fatalf("expected exactly two append attempts (1 failed + 1 retry); calledAppend=%d", chat.calledAppend)
- }
-}
-
-// TestDispatcher_DurableErrorMarksClaim pins the inverse of the
-// release path: when AppendUserMessage has succeeded (chat_message
-// committed) but a downstream step returns an error, the dispatcher
-// MUST mark the claim processed. Otherwise a replay would re-process
-// the message and write a second chat_message row.
-//
-// The run-trigger enqueue is now debounced and cannot fail synchronously,
-// so the synchronous downstream error this pins is the /issue create
-// path — the remaining step that runs after the chat_message is durable
-// and can still surface an error to the caller.
-func TestDispatcher_DurableErrorMarksClaim(t *testing.T) {
- sessionID := validUUID(0x66)
- inst := activeInstallation()
- queries := &fakeQueries{
- installationByApp: inst,
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: inst.AgentID},
- }
- chat := &fakeChat{
- ensureID: sessionID,
- appendResult: AppendResult{IssueCommand: &IssueCommand{Title: "boom"}},
- }
- issueErr := errors.New("create issue: connection refused")
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- IssueService: &fakeIssueCreator{err: issueErr},
- TaskService: &fakeEnqueuer{},
- }
-
- _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "/issue boom",
- MessageID: "msg-durable-err",
- })
- if !errors.Is(err, issueErr) {
- t.Fatalf("expected post-append durable error to propagate, got %v", err)
- }
- if queries.calledRelease != 0 {
- t.Fatalf("must not release: chat_message already committed; calledRelease=%d", queries.calledRelease)
- }
- if queries.calledMark != 1 {
- t.Fatalf("must mark processed: chat_message committed before the enqueue error; calledMark=%d", queries.calledMark)
- }
- if row, ok := queries.dedup[seedDedupKey("msg-durable-err")]; !ok || !row.processed {
- t.Fatalf("dedup row must end up processed=true; got %+v", queries.dedup)
- }
-}
-
-// TestDispatcher_DropMarksClaim pins that audit-drop branches (group
-// filter, unbound user) finalize their claim as processed, so a
-// reconnect replay does NOT re-write the audit row or re-fire any
-// binding-prompt side effect. This is the "no audit / card spam"
-// invariant from §4.3.
-func TestDispatcher_DropMarksClaim(t *testing.T) {
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBindingErr: pgx.ErrNoRows,
- }
- audit := &fakeAudit{}
- d := &Dispatcher{Queries: queries, Audit: audit}
-
- _, _ = d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- MessageID: "msg-unbound",
- })
- if queries.calledMark != 1 {
- t.Fatalf("unbound-user drop must mark claim processed; calledMark=%d", queries.calledMark)
- }
- if queries.calledRelease != 0 {
- t.Fatalf("unbound-user drop must not release; calledRelease=%d", queries.calledRelease)
- }
-}
-
-// TestDispatcher_EmptyMessageIDSkipsDedup pins that non-message
-// events (no MessageID) bypass dedup entirely — there is no key to
-// deduplicate by, and the dispatcher must not call Claim / Mark /
-// Release for them.
-func TestDispatcher_EmptyMessageIDSkipsDedup(t *testing.T) {
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- }
- d := &Dispatcher{Queries: queries, Audit: &fakeAudit{}}
-
- _, _ = d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeGroup, // group filter drops it
- // MessageID intentionally empty
- })
- if queries.calledClaim != 0 || queries.calledMark != 0 || queries.calledRelease != 0 {
- t.Fatalf("empty MessageID must skip dedup entirely; claim=%d mark=%d release=%d",
- queries.calledClaim, queries.calledMark, queries.calledRelease)
- }
-}
-
-// TestDispatcher_InFlightClaimDropsReplay covers the "another worker
-// is processing" branch: a fresh in-flight claim (processed=false,
-// not yet stale) must duplicate-drop a concurrent replay, NOT
-// re-process. This is the protection against two replicas
-// simultaneously consuming the same Lark event during a brief
-// double-leased window.
-func TestDispatcher_InFlightClaimDropsReplay(t *testing.T) {
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- // In-flight claim (processed=false) and reclaim disabled
- // (simulates "the row is fresh — not stale yet").
- dedup: map[string]*fakeDedupRow{seedDedupKey("msg-inflight"): {processed: false, token: validUUID(0xAB)}},
- }
- chat := &fakeChat{}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: &fakeEnqueuer{},
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "race",
- MessageID: "msg-inflight",
- })
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {
- t.Fatalf("in-flight claim must drop the replay; got %+v", res)
- }
- if chat.calledEnsure != 0 || chat.calledAppend != 0 {
- t.Fatalf("in-flight drop must short-circuit before chat lookup; ensure=%d append=%d",
- chat.calledEnsure, chat.calledAppend)
- }
-}
-
-// TestDispatcher_StaleInFlightClaimReclaimable covers the
-// crash-recovery branch: an in-flight claim older than the staleness
-// TTL must be re-takeable so a process crash mid-pipeline does not
-// leave the message stuck forever.
-func TestDispatcher_StaleInFlightClaimReclaimable(t *testing.T) {
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- dedup: map[string]*fakeDedupRow{seedDedupKey("msg-stale"): {processed: false, token: validUUID(0xAB)}},
- dedupReclaim: true, // simulates received_at < now() - 60s
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "after-crash retry",
- MessageID: "msg-stale",
- })
- if err != nil {
- t.Fatalf("stale-claim retry should succeed, got %v", err)
- }
- if res.Outcome != OutcomeIngested {
- t.Fatalf("stale-claim retry must ingest; got %+v", res)
- }
- if queries.calledMark != 1 {
- t.Fatalf("stale-claim retry must mark processed; calledMark=%d", queries.calledMark)
- }
-}
-
-// TestDispatcher_StaleReclaimRaceDoesNotDoubleWrite is the regression
-// for Elon's first must-fix on PR #3277 dedup: worker A claims a
-// dedup row at t=0 with token T_A, runs slowly past the 60-second
-// staleness TTL, and is still alive. Worker B (a replay) sees the row
-// as stale-reclaimable, takes the claim, rotates the token to T_B,
-// and runs the full ingest pipeline. A subsequently reaches its in-tx
-// Mark with the old T_A. WITHOUT owner fencing both A and B would
-// commit a chat_message for the same Lark message_id — the bug Elon
-// flagged. WITH owner fencing A's Mark matches zero rows, the in-tx
-// Mark returns ErrClaimLost, A's chat_message+session transaction
-// rolls back, and B is the sole writer.
-//
-// The test reproduces this by inverting the timeline: worker A is
-// Handle()'s active call, and worker B is injected by the
-// `beforeAppend` hook, which rotates the row's claim_token between
-// the dispatcher's ClaimLarkInboundDedup call and AppendUserMessage's
-// in-tx Mark. The hook fires exactly once so the second Handle()
-// continues normally.
-func TestDispatcher_StaleReclaimRaceDoesNotDoubleWrite(t *testing.T) {
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- chat.queries = queries // model the production in-tx Mark
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- // Inject worker B's reclaim. The hook fires while worker A's
- // AppendUserMessage is running with its original (now-stale)
- // token; ClaimLarkInboundDedup with dedupReclaim=true rotates the
- // row's claim_token to T_B. When fakeChat then attempts the in-tx
- // Mark with T_A it must match zero rows and return ErrClaimLost.
- raceFired := false
- originalToken := pgtype.UUID{}
- chat.beforeAppend = func(p AppendUserMessageParams) {
- if raceFired {
- return
- }
- raceFired = true
- originalToken = p.ClaimToken
- // Make the existing in-flight row reclaimable, then have
- // worker B re-Claim. This rotates claim_token under A's feet.
- queries.dedupReclaim = true
- if _, err := queries.ClaimLarkInboundDedup(context.Background(), ClaimInboundDedupParams{
- InstallationID: p.InstallationID,
- MessageID: p.LarkMessageID,
- }); err != nil {
- t.Fatalf("worker-B reclaim setup failed: %v", err)
- }
- // Switch reclaim off so the dispatcher-level retry path (the
- // second Handle below) doesn't keep rotating the token.
- queries.dedupReclaim = false
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "slow-worker A",
- MessageID: "msg-race",
- })
- if err != nil {
- t.Fatalf("stale-reclaim race should surface as duplicate drop, not error; got %v", err)
- }
- if res.Outcome != OutcomeDropped || res.DropReason != DropReasonDuplicate {
- t.Fatalf("worker A must observe duplicate drop after losing claim; got %+v", res)
- }
-
- // Critical regression assertion: worker A must NOT have committed
- // a chat_message. AppendUserMessage was called (race hook fired),
- // but its in-tx Mark matched zero rows, so the tx rolled back.
- // The "chat_message committed" signal in this fake is appendResult
- // — fakeChat returning success would have made calledAppend bump
- // AND the row would have been marked under A's token; instead A
- // got ErrClaimLost. To pin "no double write" we check that the
- // row's processed_at was set by worker B's path (the rotated
- // token, T_B), not by worker A's old token (T_A).
- row, ok := queries.dedup[seedDedupKey("msg-race")]
- if !ok {
- t.Fatalf("dedup row must still exist after race; got %+v", queries.dedup)
- }
- if row.rotations < 2 {
- t.Fatalf("worker B's reclaim must have rotated the token; rotations=%d", row.rotations)
- }
- if row.token == originalToken {
- t.Fatalf("token must have rotated away from worker A's original; both=%v", originalToken)
- }
-
- // And the loser's audit row records duplicate (not double-ingest).
- if chat.calledAppend != 1 {
- t.Fatalf("worker A's append must have been attempted exactly once; calledAppend=%d", chat.calledAppend)
- }
-
- // A subsequent replay of the same message_id must still
- // duplicate-drop — the row is in the in-flight state belonging to
- // worker B's (uncompleted) run; the dispatcher cannot double-write
- // even if B's process never finishes. We simulate that by leaving
- // dedupReclaim=false so the row is treated as fresh in-flight.
- chat.beforeAppend = nil
- res2, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "third-arrival replay",
- MessageID: "msg-race",
- })
- if err != nil {
- t.Fatalf("post-race replay should not error, got %v", err)
- }
- if res2.Outcome != OutcomeDropped || res2.DropReason != DropReasonDuplicate {
- t.Fatalf("post-race replay must duplicate-drop; got %+v", res2)
- }
-}
-
-// TestDispatcher_InTxMarkPreventsPostCommitReclaim is the regression
-// for Elon's second must-fix on PR #3277 dedup: in the previous
-// design, a process that committed chat_message but crashed or failed
-// before MarkLarkInboundDedupProcessed left the dedup row in-flight;
-// 60 seconds later a retry would treat the row as stale, re-claim it,
-// and write a second chat_message. The fix moves Mark INSIDE the
-// chat_message+session transaction, so the durable write and the Mark
-// commit (or roll back) atomically — there is no window where
-// chat_message is committed but dedup is not.
-//
-// This test pins the invariant by simulating a successful in-tx Mark,
-// then "crashing" (Handle returns without further bookkeeping), then
-// replaying the same message_id and verifying it is duplicate-dropped
-// regardless of the staleness TTL setting.
-func TestDispatcher_InTxMarkPreventsPostCommitReclaim(t *testing.T) {
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- chat.queries = queries
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- res, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "first delivery",
- MessageID: "msg-atomic",
- })
- if err != nil {
- t.Fatalf("first delivery should succeed, got %v", err)
- }
- if res.Outcome != OutcomeIngested {
- t.Fatalf("first delivery must ingest; got %+v", res)
- }
-
- // AppendUserMessage's in-tx Mark fired; the dispatcher's post-
- // pipeline applyFinalize saw DedupMarked=true and skipped its
- // own Mark call. Total fakeQueries.MarkLarkInboundDedupProcessed
- // calls must therefore be exactly 1 — proves the in-tx path was
- // the sole writer.
- if queries.calledMark != 1 {
- t.Fatalf("expected exactly one Mark call (in-tx only, no post-finalize duplicate); calledMark=%d",
- queries.calledMark)
- }
- row, ok := queries.dedup[seedDedupKey("msg-atomic")]
- if !ok || !row.processed {
- t.Fatalf("dedup row must be terminal after in-tx Mark; got %+v", queries.dedup)
- }
-
- // Now simulate the dangerous scenario the OLD design failed: a
- // retry replays the same message_id AFTER the staleness TTL would
- // have expired. With the new design, processed_at IS NOT NULL
- // shadows the staleness check, so even with dedupReclaim=true the
- // Claim cannot re-acquire the row. The retry is a duplicate-drop.
- queries.dedupReclaim = true
- chat.calledAppend = 0
- res2, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "after-crash retry",
- MessageID: "msg-atomic",
- })
- if err != nil {
- t.Fatalf("post-mark retry should not error, got %v", err)
- }
- if res2.Outcome != OutcomeDropped || res2.DropReason != DropReasonDuplicate {
- t.Fatalf("post-mark retry must duplicate-drop; got %+v", res2)
- }
- if chat.calledAppend != 0 {
- t.Fatalf("post-mark retry must short-circuit before AppendUserMessage; calledAppend=%d",
- chat.calledAppend)
- }
- // The dedup row must remain processed=true and unrotated — the
- // Claim hit the terminal-row branch (no UPDATE), so claim_token
- // did NOT mint a new value.
- if row, ok := queries.dedup[seedDedupKey("msg-atomic")]; !ok || !row.processed {
- t.Fatalf("dedup row must stay terminal after replay; got %+v", queries.dedup)
- }
- if queries.dedup[seedDedupKey("msg-atomic")].rotations != 1 {
- t.Fatalf("claim_token must not rotate when the row is already processed; rotations=%d",
- queries.dedup[seedDedupKey("msg-atomic")].rotations)
- }
-}
-
-// TestDispatcher_InTxMarkSucceedsAndSkipsPostFinalize is a positive
-// regression for the in-tx Mark path: when AppendUserMessage returns
-// DedupMarked=true the dispatcher must NOT issue an additional Mark
-// from applyFinalize. This is the contract that makes the new design
-// safe — calling Mark twice is benign at the SQL layer (the
-// processed_at IS NULL guard makes the second call a no-op), but the
-// extra round-trip would defeat the "in-tx atomic finalize" goal.
-func TestDispatcher_InTxMarkSucceedsAndSkipsPostFinalize(t *testing.T) {
- sessionID := validUUID(0x66)
- queries := &fakeQueries{
- installationByApp: activeInstallation(),
- userBinding: boundUser(),
- chatSession: db.ChatSession{ID: sessionID, AgentID: validUUID(0x33)},
- }
- chat := &fakeChat{ensureID: sessionID, appendResult: AppendResult{}}
- chat.queries = queries
- d := &Dispatcher{
- Queries: queries,
- Chat: chat,
- Audit: &fakeAudit{},
- TaskService: &fakeEnqueuer{task: db.AgentTaskQueue{ID: validUUID(0x77)}},
- }
-
- _, err := d.Handle(context.Background(), InboundMessage{
- AppID: "ok",
- ChatType: ChatTypeP2P,
- SenderOpenID: "ou_user_a",
- Body: "hi",
- MessageID: "msg-in-tx",
- })
- if err != nil {
- t.Fatalf("unexpected error: %v", err)
- }
- if queries.calledMark != 1 {
- t.Fatalf("exactly one Mark call expected (in-tx only); calledMark=%d", queries.calledMark)
- }
- // Verify the dispatcher did not also Release — applyFinalize must
- // be a no-op (finalizeNone) when AppendUserMessage marked in-tx.
- if queries.calledRelease != 0 {
- t.Fatalf("dispatcher must not release after successful in-tx Mark; calledRelease=%d",
- queries.calledRelease)
- }
-}
diff --git a/server/internal/integrations/lark/feishu_channel.go b/server/internal/integrations/lark/feishu_channel.go
new file mode 100644
index 0000000000..abfb781bed
--- /dev/null
+++ b/server/internal/integrations/lark/feishu_channel.go
@@ -0,0 +1,295 @@
+package lark
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+
+ "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"
+)
+
+// feishuChannel is the Feishu implementation of channel.Channel — the first
+// adapter driven by the channel-agnostic engine (MUL-3620). It wraps the
+// existing Lark transport: Connect runs the shared WS long-conn connector for
+// this installation, translating each decoded event into a normalized
+// channel.InboundMessage and handing it to the engine's shared inbound handler
+// (the Router, injected via channel.Config.Handler); Send posts a text reply
+// through the Lark HTTP API. One instance is built per channel_installation by
+// the registered Factory; the connector is shared across instances.
+//
+// The Channel holds only the credentials it needs for Connect/Send (decoded
+// from the per-installation config blob). The installation IDENTITY
+// (workspace / agent / installer) is resolved per message by the Router's
+// InstallationResolver, so it is deliberately absent here.
+type feishuChannel struct {
+ inst Installation
+ conn EventConnector
+ handler channel.InboundHandler
+ sender APIClient
+ creds CredentialsResolver
+ logger *slog.Logger
+}
+
+var _ channel.Channel = (*feishuChannel)(nil)
+
+func (c *feishuChannel) Type() channel.Type { return channel.TypeFeishu }
+
+// Connect runs the Feishu long connection for this installation, blocking
+// until ctx is cancelled or the link drops — the contract engine.Supervisor
+// relies on to tie lease renewal to connection liveness. Each decoded event is
+// normalized to a channel.InboundMessage and handed to the engine handler. The
+// connector discards the (DispatchResult) return and reacts only to the error,
+// so the handler's error is what flows back.
+func (c *feishuChannel) Connect(ctx context.Context) error {
+ return c.conn.Run(ctx, c.inst, func(emitCtx context.Context, lm InboundMessage) (DispatchResult, error) {
+ if c.handler == nil {
+ return DispatchResult{}, errors.New("lark: inbound handler not configured")
+ }
+ return DispatchResult{}, c.handler(emitCtx, channelMessageFromLark(lm))
+ })
+}
+
+// Disconnect is a no-op: the connector's receive loop is torn down by ctx
+// cancellation (the Supervisor cancels the run context). Safe to call repeatedly.
+func (c *feishuChannel) Disconnect(ctx context.Context) error { return nil }
+
+// Send delivers a minimal text reply via the Lark IM API. Rich cards, media,
+// and the streaming card patch stay on the existing Patcher / OutcomeReplier
+// paths; this is the cross-platform OutboundMessage path.
+func (c *feishuChannel) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ if c.sender == nil {
+ return channel.SendResult{}, errors.New("lark: api client not configured")
+ }
+ creds, err := c.installationCredentials()
+ if err != nil {
+ return channel.SendResult{}, err
+ }
+ msgID, err := c.sender.SendTextMessage(ctx, SendTextParams{
+ InstallationID: creds,
+ ChatID: ChatID(out.ChatID),
+ Text: out.Text,
+ ReplyTarget: outboundReplyTarget(out),
+ })
+ if err != nil {
+ return channel.SendResult{}, err
+ }
+ return channel.SendResult{MessageID: msgID}, nil
+}
+
+// Capabilities declares what the Feishu adapter supports. Declaration only —
+// the engine performs no degradation (channel.Capability docs).
+func (c *feishuChannel) Capabilities() channel.Capability {
+ return channel.CapText |
+ channel.CapRichCard |
+ channel.CapThreadReply |
+ channel.CapQuoteReply |
+ channel.CapAttachment |
+ channel.CapTypingIndicator |
+ channel.CapMessageEdit
+}
+
+func (c *feishuChannel) installationCredentials() (InstallationCredentials, error) {
+ if c.creds == nil {
+ return InstallationCredentials{}, errors.New("lark: credentials resolver missing")
+ }
+ secret, err := c.creds.DecryptAppSecret(c.inst)
+ if err != nil {
+ return InstallationCredentials{}, fmt.Errorf("decrypt app_secret: %w", err)
+ }
+ creds := InstallationCredentials{
+ AppID: c.inst.AppID,
+ AppSecret: secret,
+ Region: RegionOrDefault(c.inst.Region),
+ }
+ if c.inst.TenantKey.Valid {
+ creds.TenantKey = c.inst.TenantKey.String
+ }
+ return creds, nil
+}
+
+// channelMessageFromLark normalizes a decoded Feishu InboundMessage into the
+// cross-platform channel.InboundMessage. The original struct is stashed in Raw
+// so the Feishu resolvers can read the platform-specific fields (app_id,
+// event_type, command body, create time) the envelope does not carry.
+func channelMessageFromLark(lm InboundMessage) channel.InboundMessage {
+ raw, _ := json.Marshal(lm)
+ var reply *channel.ReplyCtx
+ if lm.ParentID != "" || lm.RootID != "" {
+ reply = &channel.ReplyCtx{MessageID: lm.ParentID, RootID: lm.RootID}
+ }
+ return channel.InboundMessage{
+ EventID: lm.EventID,
+ MessageID: lm.MessageID,
+ Type: channelMsgType(lm.MessageType),
+ Text: lm.Body,
+ ReplyTo: reply,
+ AddressedToBot: lm.AddressedToBot,
+ ForceFresh: lm.ForceFreshSession,
+ Source: channel.Source{
+ ChannelType: channel.TypeFeishu,
+ ChatID: string(lm.ChatID),
+ ChatType: channel.ChatType(string(lm.ChatType)),
+ SenderID: string(lm.SenderOpenID),
+ ThreadID: lm.ThreadID,
+ },
+ Raw: raw,
+ }
+}
+
+// channelMsgType maps the raw Lark msg_type onto the normalized enum. Text-ish
+// Lark types (text / post / merge_forward / interactive) all flatten to text
+// (the human-readable content is in Body); media types map across.
+func channelMsgType(larkMsgType string) channel.MsgType {
+ switch larkMsgType {
+ case "image":
+ return channel.MsgTypeImage
+ case "file":
+ return channel.MsgTypeFile
+ case "audio":
+ return channel.MsgTypeAudio
+ case "media", "video":
+ return channel.MsgTypeVideo
+ case "", "text", "post", "merge_forward", "interactive":
+ return channel.MsgTypeText
+ default:
+ return channel.MsgTypeUnknown
+ }
+}
+
+// outboundReplyTarget maps the cross-platform OutboundMessage reply hints to a
+// Lark ReplyTarget. Only a quote-reply (ReplyTo set) routes through the reply
+// endpoint; a bare thread continuation falls back to a chat-level send.
+func outboundReplyTarget(out channel.OutboundMessage) ReplyTarget {
+ if out.ReplyTo == "" {
+ return ReplyTarget{}
+ }
+ return ReplyTarget{MessageID: out.ReplyTo, InThread: out.ThreadID != ""}
+}
+
+// FeishuChannelDeps bundles the shared dependencies the Feishu Factory closes
+// over: the WS connector (one shared instance), the outbound HTTP client, and
+// the credentials resolver. The inbound handler is supplied per-build by the
+// engine via channel.Config.Handler.
+type FeishuChannelDeps struct {
+ Connector EventConnector
+ APIClient APIClient
+ Credentials CredentialsResolver
+ Logger *slog.Logger
+}
+
+// RegisterFeishu registers the Feishu Factory on reg under channel.TypeFeishu
+// so the engine.Supervisor can build a feishuChannel per installation. "Adding
+// a channel" is this call plus the adapter — no engine edit.
+func RegisterFeishu(reg *channel.Registry, deps FeishuChannelDeps) {
+ reg.Register(channel.TypeFeishu, newFeishuFactory(deps))
+}
+
+func newFeishuFactory(deps FeishuChannelDeps) channel.Factory {
+ logger := deps.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return func(cfg channel.Config) (channel.Channel, error) {
+ if deps.Connector == nil {
+ return nil, errors.New("lark: feishu factory missing connector")
+ }
+ // cfg.Raw is the per-installation config blob (the channel_installation
+ // .config JSONB): app_id, encrypted app_secret, tenant_key, region, ….
+ // We build a credentials-only Installation from it; the workspace /
+ // agent identity is resolved per message by the Router, not needed here.
+ inst, err := installationFromRow(db.ChannelInstallation{
+ ChannelType: channelTypeFeishu,
+ Config: cfg.Raw,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("decode feishu installation config: %w", err)
+ }
+ return &feishuChannel{
+ inst: inst,
+ conn: deps.Connector,
+ handler: cfg.Handler,
+ sender: deps.APIClient,
+ creds: deps.Credentials,
+ logger: logger,
+ }, nil
+ }
+}
+
+// channelInstallationStore adapts *db.Queries to engine.InstallationStore. It
+// enumerates active installations across ALL channel types (the de-hardcoded
+// counterpart of the old per-feishu boot list) and manages the per-installation
+// WS lease, translating each row into the engine's Installation: ChannelType
+// selects the Factory, Config carries the platform config JSONB (verbatim), and
+// Fingerprint is a generic hash over channel_type + config so a credential
+// rotation forces a reconnect for any platform.
+type channelInstallationStore struct {
+ q *db.Queries
+}
+
+// NewChannelInstallationStore builds the engine.InstallationStore backed by the
+// generalized channel_* tables.
+func NewChannelInstallationStore(q *db.Queries) engine.InstallationStore {
+ return &channelInstallationStore{q: q}
+}
+
+func (s *channelInstallationStore) ListActiveInstallations(ctx context.Context) ([]engine.Installation, error) {
+ rows, err := s.q.ListAllActiveChannelInstallations(ctx)
+ if err != nil {
+ return nil, err
+ }
+ out := make([]engine.Installation, 0, len(rows))
+ for _, row := range rows {
+ out = append(out, engine.Installation{
+ ID: row.ID,
+ ChannelType: channel.Type(row.ChannelType),
+ Fingerprint: rowFingerprint(row),
+ Config: row.Config,
+ })
+ }
+ return out, nil
+}
+
+func (s *channelInstallationStore) AcquireWSLease(ctx context.Context, arg engine.AcquireLeaseParams) error {
+ _, err := s.q.AcquireChannelWSLease(ctx, db.AcquireChannelWSLeaseParams{
+ NewToken: pgtype.Text{String: arg.Token, Valid: true},
+ NewExpiresAt: pgtype.Timestamptz{Time: arg.ExpiresAt, Valid: true},
+ ID: arg.ID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ErrLeaseNotAcquired
+ }
+ return err
+ }
+ return nil
+}
+
+func (s *channelInstallationStore) ReleaseWSLease(ctx context.Context, arg engine.ReleaseLeaseParams) error {
+ return s.q.ReleaseChannelWSLease(ctx, db.ReleaseChannelWSLeaseParams{
+ ID: arg.ID,
+ CurrentToken: pgtype.Text{String: arg.Token, Valid: true},
+ })
+}
+
+// rowFingerprint condenses the credential-bearing config of a
+// channel_installation row into an opaque string. Any change to the platform
+// config (Feishu rotates app_id / app_secret / region on re-install) flips the
+// fingerprint and the Supervisor restarts the connection. The config JSONB
+// carries only the secret ciphertext (never plaintext), so hashing it is safe
+// and channel-agnostic — no platform field is read directly.
+func rowFingerprint(row db.ChannelInstallation) string {
+ h := sha256.New()
+ _, _ = h.Write([]byte(row.ChannelType))
+ _, _ = h.Write([]byte{0})
+ _, _ = h.Write(row.Config)
+ return hex.EncodeToString(h.Sum(nil))
+}
diff --git a/server/internal/integrations/lark/feishu_channel_test.go b/server/internal/integrations/lark/feishu_channel_test.go
new file mode 100644
index 0000000000..6bb1317ad5
--- /dev/null
+++ b/server/internal/integrations/lark/feishu_channel_test.go
@@ -0,0 +1,226 @@
+package lark
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// fakeSender embeds the APIClient interface (nil) and overrides only
+// SendTextMessage — the single method feishuChannel.Send calls.
+type fakeSender struct {
+ APIClient
+ last SendTextParams
+ msgID string
+}
+
+func (f *fakeSender) SendTextMessage(_ context.Context, p SendTextParams) (string, error) {
+ f.last = p
+ return f.msgID, nil
+}
+
+type fakeCreds struct{ secret string }
+
+func (f fakeCreds) DecryptAppSecret(_ Installation) (string, error) { return f.secret, nil }
+
+// feishuConfigJSON builds a channel_installation.config blob like migration 124
+// backfills — the shape the Feishu factory decodes.
+func feishuConfigJSON(t *testing.T, appID, region string) []byte {
+ t.Helper()
+ cfg := map[string]any{
+ "app_id": appID,
+ "app_secret_encrypted": base64.StdEncoding.EncodeToString([]byte("sealed-secret")),
+ "tenant_key": "tk_1",
+ "bot_open_id": "ou_bot",
+ "region": region,
+ }
+ raw, err := json.Marshal(cfg)
+ if err != nil {
+ t.Fatalf("marshal config: %v", err)
+ }
+ return raw
+}
+
+func buildFeishuChannel(t *testing.T, deps FeishuChannelDeps, cfg channel.Config) *feishuChannel {
+ t.Helper()
+ ch, err := newFeishuFactory(deps)(cfg)
+ if err != nil {
+ t.Fatalf("factory: %v", err)
+ }
+ fc, ok := ch.(*feishuChannel)
+ if !ok {
+ t.Fatalf("factory returned %T, want *feishuChannel", ch)
+ }
+ return fc
+}
+
+func TestFeishuFactory_DecodesConfigCredentials(t *testing.T) {
+ cfg := channel.Config{Type: channel.TypeFeishu, Raw: feishuConfigJSON(t, "cli_app", "lark")}
+ fc := buildFeishuChannel(t, FeishuChannelDeps{Connector: NewNoopConnector(nil)}, cfg)
+
+ if fc.inst.AppID != "cli_app" {
+ t.Fatalf("app_id = %q, want cli_app", fc.inst.AppID)
+ }
+ if fc.inst.Region != "lark" {
+ t.Fatalf("region = %q, want lark", fc.inst.Region)
+ }
+ if !fc.inst.TenantKey.Valid || fc.inst.TenantKey.String != "tk_1" {
+ t.Fatalf("tenant_key not decoded: %+v", fc.inst.TenantKey)
+ }
+ if len(fc.inst.AppSecretEncrypted) == 0 {
+ t.Fatalf("app_secret_encrypted not decoded")
+ }
+ if fc.Type() != channel.TypeFeishu {
+ t.Fatalf("Type() = %q", fc.Type())
+ }
+}
+
+func TestFeishuFactory_MissingConnectorFails(t *testing.T) {
+ _, err := newFeishuFactory(FeishuChannelDeps{})(channel.Config{Type: channel.TypeFeishu, Raw: feishuConfigJSON(t, "cli", "feishu")})
+ if err == nil {
+ t.Fatal("expected an error when the factory has no connector")
+ }
+}
+
+func TestFeishuChannel_Capabilities(t *testing.T) {
+ fc := &feishuChannel{}
+ caps := fc.Capabilities()
+ for _, want := range []channel.Capability{
+ channel.CapText, channel.CapRichCard, channel.CapThreadReply,
+ channel.CapQuoteReply, channel.CapAttachment, channel.CapTypingIndicator, channel.CapMessageEdit,
+ } {
+ if !caps.Has(want) {
+ t.Fatalf("Capabilities missing %s", want)
+ }
+ }
+ if caps.Has(channel.CapVoice) {
+ t.Fatalf("Feishu adapter does not declare voice")
+ }
+}
+
+func TestFeishuChannel_SendMapsTextAndReplyTarget(t *testing.T) {
+ sender := &fakeSender{msgID: "om_sent"}
+ fc := &feishuChannel{
+ inst: Installation{AppID: "cli", Region: "feishu"},
+ sender: sender,
+ creds: fakeCreds{secret: "plain"},
+ }
+ res, err := fc.Send(context.Background(), channel.OutboundMessage{
+ ChatID: "oc_chat",
+ Text: "hi there",
+ ReplyTo: "om_parent",
+ ThreadID: "t_1",
+ })
+ if err != nil {
+ t.Fatalf("Send: %v", err)
+ }
+ if res.MessageID != "om_sent" {
+ t.Fatalf("MessageID = %q, want om_sent", res.MessageID)
+ }
+ if sender.last.ChatID != "oc_chat" || sender.last.Text != "hi there" {
+ t.Fatalf("unexpected send params: %+v", sender.last)
+ }
+ if sender.last.InstallationID.AppID != "cli" || sender.last.InstallationID.AppSecret != "plain" {
+ t.Fatalf("credentials not threaded into send: %+v", sender.last.InstallationID)
+ }
+ // ReplyTo present -> route through the reply endpoint, threaded.
+ if sender.last.ReplyTarget.MessageID != "om_parent" || !sender.last.ReplyTarget.InThread {
+ t.Fatalf("reply target mapping wrong: %+v", sender.last.ReplyTarget)
+ }
+}
+
+func TestOutboundReplyTarget(t *testing.T) {
+ if got := outboundReplyTarget(channel.OutboundMessage{}); got.IsSet() {
+ t.Fatalf("no ReplyTo must yield an unset target, got %+v", got)
+ }
+ got := outboundReplyTarget(channel.OutboundMessage{ReplyTo: "om", ThreadID: ""})
+ if got.MessageID != "om" || got.InThread {
+ t.Fatalf("non-thread quote reply mapping wrong: %+v", got)
+ }
+}
+
+func TestChannelMessageFromLark_NormalizesAndStashesRaw(t *testing.T) {
+ lm := InboundMessage{
+ EventID: "evt",
+ MessageID: "om",
+ AppID: "cli",
+ ChatID: "oc",
+ ChatType: ChatTypeGroup,
+ SenderOpenID: "ou_user",
+ Body: "enriched body",
+ CommandBody: "/issue do it",
+ MessageType: "post",
+ AddressedToBot: true,
+ ForceFreshSession: true,
+ ParentID: "om_parent",
+ RootID: "om_root",
+ ThreadID: "t_9",
+ }
+ cm := channelMessageFromLark(lm)
+
+ if cm.EventID != "evt" || cm.MessageID != "om" || cm.Text != "enriched body" {
+ t.Fatalf("scalar fields not mapped: %+v", cm)
+ }
+ if cm.Type != channel.MsgTypeText {
+ t.Fatalf("post must normalize to text, got %q", cm.Type)
+ }
+ if cm.Source.ChannelType != channel.TypeFeishu || cm.Source.ChatID != "oc" ||
+ cm.Source.ChatType != channel.ChatTypeGroup || cm.Source.SenderID != "ou_user" || cm.Source.ThreadID != "t_9" {
+ t.Fatalf("source not mapped: %+v", cm.Source)
+ }
+ if !cm.AddressedToBot || !cm.ForceFresh {
+ t.Fatalf("addressed/forcefresh not mapped: %+v", cm)
+ }
+ if cm.ReplyTo == nil || cm.ReplyTo.MessageID != "om_parent" || cm.ReplyTo.RootID != "om_root" {
+ t.Fatalf("reply context not mapped: %+v", cm.ReplyTo)
+ }
+ // Raw must round-trip back to the original lark message (the boundary the
+ // Feishu resolvers read app_id / command_body / event_type from).
+ got, err := larkMsgFromRaw(cm)
+ if err != nil {
+ t.Fatalf("larkMsgFromRaw: %v", err)
+ }
+ if got.AppID != "cli" || got.CommandBody != "/issue do it" || got.MessageType != "post" {
+ t.Fatalf("raw round-trip lost platform fields: %+v", got)
+ }
+}
+
+func TestChannelMsgType(t *testing.T) {
+ cases := map[string]channel.MsgType{
+ "": channel.MsgTypeText,
+ "text": channel.MsgTypeText,
+ "post": channel.MsgTypeText,
+ "merge_forward": channel.MsgTypeText,
+ "image": channel.MsgTypeImage,
+ "file": channel.MsgTypeFile,
+ "audio": channel.MsgTypeAudio,
+ "media": channel.MsgTypeVideo,
+ "sticker": channel.MsgTypeUnknown,
+ }
+ for in, want := range cases {
+ if got := channelMsgType(in); got != want {
+ t.Fatalf("channelMsgType(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestDispatchResultFromEngine(t *testing.T) {
+ res := dispatchResultFromEngine(engine.Result{
+ Outcome: engine.OutcomeNeedsBinding,
+ Sender: "ou_user",
+ IssueIdentifier: "MUL-7",
+ })
+ if res.Outcome != OutcomeNeedsBinding {
+ t.Fatalf("outcome not mapped: %q", res.Outcome)
+ }
+ if res.SenderOpenID != "ou_user" {
+ t.Fatalf("sender not mapped: %q", res.SenderOpenID)
+ }
+ if res.IssueIdentifier != "MUL-7" {
+ t.Fatalf("issue identifier not mapped: %q", res.IssueIdentifier)
+ }
+}
diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.go
new file mode 100644
index 0000000000..9ac29d9743
--- /dev/null
+++ b/server/internal/integrations/lark/feishu_resolvers.go
@@ -0,0 +1,254 @@
+package lark
+
+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"
+)
+
+// This file is the Feishu ResolverSet: the platform-specific implementations
+// the channel-agnostic engine.Router runs the inbound pipeline through. Each
+// resolver translates between the engine's normalized channel.InboundMessage /
+// engine types and the Feishu store / services. Platform-specific fields the
+// normalized envelope does not carry (app_id, event_type, the un-enriched
+// command body, create time) are read from the original InboundMessage the
+// feishuChannel stashes in channel.InboundMessage.Raw — the documented adapter
+// boundary (the core never reads Raw).
+
+// originFeishuChat is the issue.origin_type label written for issues created
+// via the Feishu /issue command. Kept as "lark_chat" (unchanged from the
+// pre-cutover dispatcher) so analytics classification does not shift.
+const originFeishuChat = "lark_chat"
+
+// larkMsgFromRaw decodes the original Feishu InboundMessage the feishuChannel
+// stashed in channel.InboundMessage.Raw.
+func larkMsgFromRaw(msg channel.InboundMessage) (InboundMessage, error) {
+ var lm InboundMessage
+ if len(msg.Raw) == 0 {
+ return InboundMessage{}, errors.New("lark: inbound message Raw is empty")
+ }
+ if err := json.Unmarshal(msg.Raw, &lm); err != nil {
+ return InboundMessage{}, fmt.Errorf("decode feishu inbound raw: %w", err)
+ }
+ 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 {
+ set := engine.ResolverSet{
+ Installation: &feishuInstallationResolver{store: store},
+ Identity: &feishuIdentityResolver{store: store},
+ Dedup: &feishuDeduper{store: store},
+ Session: &feishuSessionBinder{chat: chat},
+ Audit: &feishuAuditor{audit: audit},
+ OriginType: originFeishuChat,
+ }
+ if replier != nil {
+ set.Replier = &feishuOutboundReplier{replier: replier}
+ }
+ if typing != nil {
+ set.Typing = &feishuTypingNotifier{mgr: typing}
+ }
+ return set
+}
+
+// ---- installation routing ----
+
+type feishuInstallationResolver struct{ store *ChannelStore }
+
+func (r *feishuInstallationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
+ lm, err := larkMsgFromRaw(msg)
+ if err != nil {
+ return engine.ResolvedInstallation{}, err
+ }
+ inst, err := r.store.GetLarkInstallationByAppID(ctx, lm.AppID)
+ 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: InstallationStatus(inst.Status) == InstallationActive,
+ Platform: inst,
+ }, nil
+}
+
+// ---- identity ----
+
+type feishuIdentityResolver struct{ store *ChannelStore }
+
+func (r *feishuIdentityResolver) ResolveSender(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) (engine.ResolvedIdentity, error) {
+ binding, err := r.store.GetLarkUserBindingByOpenID(ctx, GetUserBindingByOpenIDParams{
+ 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
+ }
+ isMember, err := r.store.IsWorkspaceMember(ctx, inst.WorkspaceID, binding.MulticaUserID)
+ if err != nil {
+ return engine.ResolvedIdentity{}, err
+ }
+ if !isMember {
+ return engine.ResolvedIdentity{}, engine.ErrSenderNotMember
+ }
+ return engine.ResolvedIdentity{UserID: binding.MulticaUserID}, nil
+}
+
+// ---- dedup ----
+
+type feishuDeduper struct{ store *ChannelStore }
+
+func (r *feishuDeduper) Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (pgtype.UUID, error) {
+ claim, err := r.store.ClaimLarkInboundDedup(ctx, ClaimInboundDedupParams{
+ 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 *feishuDeduper) Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.store.MarkLarkInboundDedupProcessed(ctx, MarkInboundDedupProcessedParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+func (r *feishuDeduper) Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.store.ReleaseLarkInboundDedup(ctx, ReleaseInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+// ---- session bind / append ----
+
+type feishuSessionBinder struct{ chat ChatSessionService }
+
+func (r *feishuSessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
+ return r.chat.EnsureChatSession(ctx, EnsureChatSessionParams{
+ WorkspaceID: p.Installation.WorkspaceID,
+ InstallationID: p.Installation.ID,
+ AgentID: p.Installation.AgentID,
+ ChatID: ChatID(p.Message.Source.ChatID),
+ ChatType: ChatType(p.Message.Source.ChatType),
+ Sender: p.Sender,
+ })
+}
+
+func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
+ lm, err := larkMsgFromRaw(p.Message)
+ if err != nil {
+ return engine.AppendResult{}, err
+ }
+ res, err := r.chat.AppendUserMessage(ctx, AppendUserMessageParams{
+ ChatSessionID: p.SessionID,
+ Sender: p.Sender,
+ Body: p.Message.Text,
+ CommandBody: lm.CommandBody,
+ InstallationID: p.InstallationID,
+ LarkMessageID: p.Message.MessageID,
+ LarkThreadID: 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 ----
+
+type feishuAuditor struct{ audit AuditLogger }
+
+func (r *feishuAuditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
+ // event_type is platform-specific (read from Raw); a decode failure is
+ // non-fatal — the drop is still worth auditing without it.
+ lm, _ := larkMsgFromRaw(msg)
+ return r.audit.RecordDrop(ctx, AuditDropParams{
+ InstallationID: instID,
+ ChatID: ChatID(msg.Source.ChatID),
+ EventType: lm.EventType,
+ LarkEventID: msg.EventID,
+ LarkMessageID: msg.MessageID,
+ Reason: DropReason(string(reason)),
+ })
+}
+
+// ---- outbound replier ----
+
+type feishuOutboundReplier struct{ replier OutcomeReplier }
+
+func (r *feishuOutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) {
+ larkInst, ok := inst.Platform.(Installation)
+ if !ok {
+ return
+ }
+ lm, _ := larkMsgFromRaw(msg)
+ r.replier.Reply(ctx, larkInst, lm, dispatchResultFromEngine(res))
+}
+
+// dispatchResultFromEngine maps the engine verdict to the Feishu DispatchResult
+// the OutcomeReplier consumes. The Outcome/DropReason string values match 1:1.
+func dispatchResultFromEngine(res engine.Result) DispatchResult {
+ return DispatchResult{
+ Outcome: Outcome(string(res.Outcome)),
+ DropReason: DropReason(string(res.DropReason)),
+ InstallationID: res.InstallationID,
+ ChatSessionID: res.ChatSessionID,
+ SenderOpenID: OpenID(res.Sender),
+ IssueID: res.IssueID,
+ IssueNumber: res.IssueNumber,
+ IssueIdentifier: res.IssueIdentifier,
+ IssueTitle: res.IssueTitle,
+ }
+}
+
+// ---- typing indicator ----
+
+type feishuTypingNotifier struct{ mgr *TypingIndicatorManager }
+
+func (r *feishuTypingNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID) {
+ larkInst, ok := inst.Platform.(Installation)
+ if !ok {
+ return
+ }
+ lm, _ := larkMsgFromRaw(msg)
+ r.mgr.Add(ctx, larkInst, sessionID, msg.MessageID, lm.CreateTime)
+}
diff --git a/server/internal/integrations/lark/feishu_types.go b/server/internal/integrations/lark/feishu_types.go
new file mode 100644
index 0000000000..179733420d
--- /dev/null
+++ b/server/internal/integrations/lark/feishu_types.go
@@ -0,0 +1,93 @@
+package lark
+
+import "github.com/jackc/pgx/v5/pgtype"
+
+// This file holds the Feishu adapter's native-ish inbound/outbound value
+// types. The WS connector decodes a raw Lark event into an InboundMessage;
+// feishuChannel translates that into a channel.InboundMessage for the
+// channel-agnostic engine.Router, and the feishu resolvers / OutcomeReplier
+// translate back at the adapter boundary. (Formerly defined on dispatcher.go,
+// which the MUL-3620 Router cutover removed.)
+
+// InboundMessage is the Feishu connector's decoded, enriched event. It is the
+// adapter's internal shape: feishuChannel maps it to a channel.InboundMessage
+// (stashing this struct in Raw) so the resolvers can read the platform-
+// specific fields the normalized envelope does not carry.
+type InboundMessage struct {
+ EventType string
+ EventID string
+ AppID string
+ ChatID ChatID
+ ChatType ChatType
+ MessageID string
+ SenderOpenID OpenID
+ Body string
+ // ForceFreshSession marks this dispatch as a one-off fresh start: the
+ // daemon should skip prior session resume when it claims the resulting
+ // chat task.
+ ForceFreshSession bool
+ AddressedToBot bool
+
+ // MessageType is the raw Lark msg_type ("text", "post", "merge_forward",
+ // "image", "interactive", …). The decoder populates it so the inbound
+ // enricher can decide whether a message needs an HTTP round-trip to
+ // expand while the core stays msg_type-agnostic and only reads Body.
+ MessageType string
+
+ // CreateTime is the trigger message's creation time (epoch milliseconds).
+ // The enricher anchors the group recent-context window to it; the typing
+ // indicator uses it to skip stale reactions.
+ CreateTime string
+
+ // ParentID is the message_id this one quote-replies to (verbatim
+ // parent_id); RootID is the thread/root anchor. The enricher expands
+ // quoted replies off ParentID.
+ ParentID string
+ RootID string
+
+ // ThreadID is the Lark topic (话题) id, populated only for messages posted
+ // inside a thread, so a non-empty value signals an in-thread @-mention.
+ // Persisted on the chat binding so the outbound patcher threads its reply.
+ ThreadID string
+
+ // CommandBody is the user's OWN typed text (the decoded Body before the
+ // enricher prepends quoted/forwarded context). `/issue` is parsed from
+ // THIS, not the enriched Body.
+ CommandBody string
+}
+
+// Outcome categorizes what the inbound pipeline decided. The OutcomeReplier
+// inspects it to choose the Lark-side reply. Values mirror engine.Outcome.
+type Outcome string
+
+const (
+ // OutcomeDropped — not ingested (identity, dedup, group filter, …).
+ OutcomeDropped Outcome = "dropped"
+ // OutcomeNeedsBinding — the open_id is unbound; send the binding card.
+ OutcomeNeedsBinding Outcome = "needs_binding"
+ // OutcomeIngested — the message landed and a run was (or will be) enqueued.
+ OutcomeIngested Outcome = "ingested"
+ // OutcomeAgentOffline — landed, but the agent has no runtime bound.
+ OutcomeAgentOffline Outcome = "agent_offline"
+ // OutcomeAgentArchived — landed, but the agent is archived.
+ OutcomeAgentArchived Outcome = "agent_archived"
+)
+
+// DispatchResult is the Feishu-side verdict the OutcomeReplier consumes to
+// drive its outbound reply. The engine produces an engine.Result; the feishu
+// OutboundReplier adapter translates it into this shape.
+type DispatchResult struct {
+ Outcome Outcome
+ DropReason DropReason
+ InstallationID pgtype.UUID
+ ChatSessionID pgtype.UUID
+ SenderOpenID OpenID
+ TaskID pgtype.UUID
+ IssueID pgtype.UUID
+ IssueNumber int32
+ // IssueIdentifier is the workspace-qualified key ("MUL-42") for the
+ // created issue, used verbatim in the confirmation message.
+ IssueIdentifier string
+ // IssueTitle is the title supplied on /issue, echoed in the confirmation.
+ IssueTitle string
+}
diff --git a/server/internal/integrations/lark/hub.go b/server/internal/integrations/lark/hub.go
deleted file mode 100644
index ca8643a93b..0000000000
--- a/server/internal/integrations/lark/hub.go
+++ /dev/null
@@ -1,922 +0,0 @@
-package lark
-
-import (
- "context"
- cryptorand "crypto/rand"
- "crypto/sha256"
- "encoding/hex"
- "errors"
- "fmt"
- "log/slog"
- mathrand "math/rand/v2"
- "strconv"
- "sync"
- "time"
-
- "github.com/jackc/pgx/v5/pgtype"
- "github.com/multica-ai/multica/server/internal/util"
-)
-
-// HubQueries is the narrow subset of *db.Queries the Hub needs for
-// installation enumeration and lease management. *db.Queries satisfies
-// it directly; tests substitute a fake.
-type HubQueries interface {
- ListActiveLarkInstallations(ctx context.Context) ([]Installation, error)
- AcquireLarkWSLease(ctx context.Context, arg AcquireWSLeaseParams) (Installation, error)
- ReleaseLarkWSLease(ctx context.Context, arg ReleaseWSLeaseParams) error
-}
-
-// EventEmitter is the per-message callback the Hub hands to an
-// EventConnector. Calling it dispatches the normalized inbound
-// message and returns the typed outcome plus any infrastructure
-// error from the Dispatcher.
-//
-// Connectors react to the return value to decide what to do on the
-// Lark side:
-//
-// - A non-nil error is a real infrastructure failure (DB down,
-// etc.) — the connector should reconnect (the Hub will retry
-// under backoff) and surface the error to ops, NOT swallow it.
-// - A nil error with OutcomeNeedsBinding tells the connector to
-// send the binding-prompt card to the sender's open_id.
-// - OutcomeAgentOffline / OutcomeAgentArchived tell the connector
-// to send the respective copy as a Lark card; the chat_message
-// row is already persisted, so the agent will pick the message
-// up on resume.
-// - OutcomeIngested means the message landed and (optionally) a
-// task was enqueued; the connector emits a "thinking…" card and
-// lets the outbound Patcher take over from there.
-// - OutcomeDropped is informational only (the message was filtered
-// for a legitimate reason); typical connectors do nothing.
-//
-// The Dispatcher's invariants (identity check, dedup, audit) are NOT
-// the connector's concern — the connector only sees the verdict.
-type EventEmitter func(ctx context.Context, msg InboundMessage) (DispatchResult, error)
-
-// EventConnector is the per-installation transport. The Hub owns the
-// lifecycle (when to start, when to stop, when to back off), and the
-// connector owns the actual wire protocol — opening the Lark long
-// connection, decoding events, normalizing them into InboundMessage.
-//
-// Run MUST block until either:
-// - the ctx is cancelled (graceful shutdown / lease loss / revoke),
-// in which case it returns nil; or
-// - the connection ends and cannot be recovered locally, in which
-// case it returns an error describing why. The Hub treats a
-// non-nil return as "this attempt failed" and schedules a retry
-// under exponential backoff.
-//
-// Implementations MUST be tolerant of repeated Run calls on different
-// contexts — the Hub may call Run, return, and call Run again after
-// backoff. Allocating per-call state is fine; persistent state lives in
-// the connector struct.
-//
-// emit returns the Dispatcher's verdict + any infra error so the
-// connector can post the corresponding Lark-side reply (binding card,
-// offline card, etc.) and / or decide to disconnect on a hard failure.
-// The connector MUST NOT bypass the Dispatcher by writing to the DB
-// directly; emit is the only ingress path.
-type EventConnector interface {
- Run(ctx context.Context, inst Installation, emit EventEmitter) error
-}
-
-// ConnectorFactory builds an EventConnector for a specific installation
-// row. The factory exists so the Hub doesn't need to know about Lark
-// SDK construction (auth, app credentials decryption) — call sites
-// inject a factory configured with their APIClient + secretbox box.
-type ConnectorFactory func(inst Installation) (EventConnector, error)
-
-// HubConfig tunes the Hub's lifecycle loops. All fields have sensible
-// production defaults via withDefaults; tests typically set Now and
-// Logger to inject determinism.
-type HubConfig struct {
- // LeaseTTL is how long a successful AcquireLarkWSLease grant is
- // valid before another server replica may steal it. Renewals
- // happen on a tighter interval (LeaseRenewInterval); the gap
- // between renew and TTL absorbs transient DB blips.
- LeaseTTL time.Duration
-
- // LeaseRenewInterval is the cadence at which the Hub re-acquires
- // the lease on connections it already owns. MUST be substantially
- // less than LeaseTTL so a single missed renewal does not yield
- // the lease.
- LeaseRenewInterval time.Duration
-
- // PollInterval is how often the Hub scans for new installations
- // (or ones whose lease has expired on another replica) to take
- // over.
- PollInterval time.Duration
-
- // MinBackoff / MaxBackoff bound the per-installation reconnect
- // schedule. The actual delay starts at MinBackoff, doubles after
- // each consecutive failure (capped at MaxBackoff), and resets on
- // any successful Run that lives at least ResetBackoffAfter.
- MinBackoff time.Duration
- MaxBackoff time.Duration
- ResetBackoffAfter time.Duration
-
- // LeaseReleaseTimeout caps how long a single ReleaseLarkWSLease
- // call may block. The release runs on a fresh context (not the
- // parent supervisor ctx, which is already cancelled by the time
- // we release on shutdown), so without an explicit deadline a
- // stalled DB pool could hang shutdown indefinitely. A bounded
- // timeout means a hung release falls back to the natural lease
- // TTL expiry on the next replica — slower than a clean release,
- // but still bounded.
- LeaseReleaseTimeout time.Duration
-
- // ShutdownTimeout bounds how long Hub.Wait blocks waiting for
- // supervisor goroutines to exit after their parent ctx is
- // cancelled. Hub.Wait itself does not enforce this — callers
- // pass it to WaitWithTimeout. Exposed on the config so main.go
- // and tests share the same default.
- ShutdownTimeout time.Duration
-
- // ReplyTimeout caps an OutcomeReplier.Reply call. The replier
- // runs in a detached goroutine off the ACK critical path —
- // dispatch returns the verdict to the connector immediately so
- // the ACK can be written, then the reply (a NeedsBinding card,
- // an offline notice, etc.) is best-effort under this deadline.
- // Lark's long-conn server expects a frame ACK within 3 seconds,
- // so this MUST stay strictly under 3s to keep the connector's
- // own ACK path comfortably bounded even if the dispatch itself
- // takes a few hundred ms (DB roundtrips, identity checks, etc.).
- // Zero defaults to 2.5s.
- ReplyTimeout time.Duration
-
- // Now returns the current time. Injected for tests; production
- // uses time.Now.
- Now func() time.Time
-
- // Logger optional; defaults to slog.Default.
- Logger *slog.Logger
-}
-
-func (c HubConfig) withDefaults() HubConfig {
- if c.LeaseTTL == 0 {
- c.LeaseTTL = 90 * time.Second
- }
- if c.LeaseRenewInterval == 0 {
- c.LeaseRenewInterval = 30 * time.Second
- }
- if c.PollInterval == 0 {
- c.PollInterval = 30 * time.Second
- }
- if c.MinBackoff == 0 {
- c.MinBackoff = 2 * time.Second
- }
- if c.MaxBackoff == 0 {
- c.MaxBackoff = 60 * time.Second
- }
- if c.ResetBackoffAfter == 0 {
- c.ResetBackoffAfter = 60 * time.Second
- }
- if c.LeaseReleaseTimeout == 0 {
- c.LeaseReleaseTimeout = 5 * time.Second
- }
- if c.ShutdownTimeout == 0 {
- c.ShutdownTimeout = 15 * time.Second
- }
- if c.ReplyTimeout == 0 {
- c.ReplyTimeout = 2500 * time.Millisecond
- }
- if c.Now == nil {
- c.Now = time.Now
- }
- if c.Logger == nil {
- c.Logger = slog.Default()
- }
- return c
-}
-
-// Hub owns the per-installation supervisor goroutines that keep a
-// long-running Lark connection per active installation. It enforces
-// the §4.4 multi-replica safety rule via the WS lease CAS — at most
-// one Hub instance globally holds the lease for any installation, so
-// duplicate event consumption across replicas is impossible.
-//
-// Lifecycle:
-//
-// hub := NewHub(queries, factory, dispatcher, HubConfig{})
-// go hub.Run(ctx) // returns when ctx is cancelled
-// ... ctx cancellation triggers ...
-// hub.Wait() // joins on every per-installation goroutine
-type Hub struct {
- queries HubQueries
- factory ConnectorFactory
- dispatcher *Dispatcher
- replier OutcomeReplier
- typingIndicator *TypingIndicatorManager
- cfg HubConfig
-
- // nodeID is the per-process lease ownership token. The CAS
- // predicate on AcquireLarkWSLease treats matching tokens as
- // "this is us, renew" — so as long as nodeID is stable for the
- // Hub's lifetime, lease renewals don't ping-pong between replicas.
- nodeID string
-
- mu sync.Mutex
- // supervisors keys each in-flight supervisor goroutine by
- // installation_id, alongside a fingerprint of the credentials the
- // connector was started with. When the underlying lark_installation
- // row changes (re-scan creates a fresh bot → new app_id / new
- // encrypted secret), the next sweep detects the fingerprint drift
- // and forces a restart so the new connector picks up fresh
- // credentials. Without this, a stale connector keeps a WS open
- // against the OLD bot's app_id and the new bot silently goes dark.
- supervisors map[string]supervisorEntry
- // supervisorGen is the source of the monotonic gen counter stored
- // on each supervisorEntry. Bumped under mu when a new entry is
- // minted (initial start OR rotation restart).
- supervisorGen uint64
- wg sync.WaitGroup
- stopped bool
- stopChan chan struct{}
-
- // replyWg tracks in-flight outbound reply goroutines (NeedsBinding
- // card, offline notice, etc.). The replier is detached from the
- // inbound ACK critical path — the connector ACKs as soon as
- // dispatch returns — so reply goroutines may still be running when
- // the supervisor goroutines have already exited. Hub.Wait joins on
- // these too, with each goroutine bounded by ReplyTimeout, so a
- // hung outbound Lark HTTP call cannot block shutdown beyond the
- // timeout.
- replyWg sync.WaitGroup
-}
-
-// supervisorEntry is the per-installation state the Hub holds on each
-// running supervisor goroutine. cancel terminates the goroutine
-// (cascading into connector teardown + lease release); fingerprint is
-// the credentials snapshot the connector was launched with, used by
-// sweep to detect mid-life rotation (re-scan replaces the bot's
-// app_id / app_secret) and force a restart; gen is a monotonic
-// counter so the goroutine's deferred cleanup can tell its own entry
-// apart from a successor entry that the rotation path already swapped
-// in. Without the gen check, the old goroutine's defer would race to
-// delete the new entry it knows nothing about.
-type supervisorEntry struct {
- cancel context.CancelFunc
- fingerprint string
- gen uint64
-}
-
-// NewHub constructs a Hub bound to the supplied queries, connector
-// factory and dispatcher. The Hub does not start any goroutines until
-// Run is called. The replier (OutcomeReplier) handles the outbound
-// side of the EventEmitter contract — NeedsBinding / AgentOffline /
-// AgentArchived cards — and is best-effort: failures are logged and
-// do not interrupt inbound processing. A nil replier falls back to
-// the noop replier so callers that have not wired outbound replies
-// yet still get the inbound pipeline running.
-func NewHub(queries HubQueries, factory ConnectorFactory, dispatcher *Dispatcher, cfg HubConfig) *Hub {
- cfg = cfg.withDefaults()
- return &Hub{
- queries: queries,
- factory: factory,
- dispatcher: dispatcher,
- replier: NewNoopOutcomeReplier(cfg.Logger),
- cfg: cfg,
- nodeID: newNodeID(),
- supervisors: make(map[string]supervisorEntry),
- stopChan: make(chan struct{}),
- }
-}
-
-// SetOutcomeReplier installs the production replier on the Hub. Must
-// be called BEFORE Run; setting it afterwards is a data race against
-// the supervisor's emit goroutines. Nil resets back to the noop
-// replier (useful for tests).
-func (h *Hub) SetOutcomeReplier(r OutcomeReplier) {
- if r == nil {
- r = NewNoopOutcomeReplier(h.cfg.Logger)
- }
- h.replier = r
-}
-
-// SetTypingIndicatorManager installs the typing-indicator manager on
-// the Hub. Must be called BEFORE Run. Nil is safe and disables the
-// typing reaction lifecycle.
-func (h *Hub) SetTypingIndicatorManager(m *TypingIndicatorManager) {
- h.typingIndicator = m
-}
-
-// NodeID exposes the per-process lease token. Useful for tests and
-// for observability (so operators can correlate DB lease rows to a
-// running replica).
-func (h *Hub) NodeID() string { return h.nodeID }
-
-// Run is the Hub's main loop. It scans installations every
-// PollInterval, attempts to lease any that are not currently being
-// supervised by this process, and reaps supervisors for installations
-// that have been revoked or whose lease was lost. Returns when ctx is
-// cancelled; the caller MUST then call Wait to join all supervisor
-// goroutines before exiting.
-func (h *Hub) Run(ctx context.Context) {
- defer close(h.stopChan)
-
- // First sweep immediately so a freshly-restarted server doesn't
- // wait a full PollInterval before picking up its installations.
- h.sweep(ctx)
-
- t := time.NewTicker(h.cfg.PollInterval)
- defer t.Stop()
- for {
- select {
- case <-ctx.Done():
- h.cancelAll()
- return
- case <-t.C:
- h.sweep(ctx)
- }
- }
-}
-
-// Wait blocks until every supervisor goroutine AND every detached
-// reply goroutine the Hub started has exited. Call this AFTER
-// cancelling Run's context; calling it before returns immediately if
-// no goroutines are active.
-//
-// Prefer WaitWithTimeout in shutdown paths so a stuck supervisor
-// (typically a hung lease release on a frozen DB pool) cannot block
-// process exit indefinitely. Reply goroutines are independently
-// bounded by ReplyTimeout, so even Wait() (unbounded) eventually
-// returns once those deadlines elapse.
-func (h *Hub) Wait() {
- h.wg.Wait()
- // Supervisors (and thus inbound delivery) have stopped, so no new
- // run triggers can be scheduled. Drain the debounced pending triggers
- // before joining replies: the flush may itself emit an offline/archived
- // notice, and FlushPendingRuns blocks until those finish.
- if h.dispatcher != nil {
- h.dispatcher.FlushPendingRuns()
- }
- h.replyWg.Wait()
-}
-
-// WaitWithTimeout is the bounded variant of Wait. Returns true if all
-// supervisor AND reply goroutines exited within the deadline, false if
-// the timeout fired first. On timeout, the process owner should log
-// the fact and proceed with exit; the orphaned goroutines will be
-// reclaimed by the OS, any unreleased leases expire naturally after
-// LeaseTTL on the next replica, and in-flight replies abort at their
-// own ReplyTimeout (already strictly under 3s, so well under any
-// reasonable ShutdownTimeout).
-//
-// A timeout <= 0 falls back to unbounded Wait, matching the legacy
-// behavior.
-func (h *Hub) WaitWithTimeout(timeout time.Duration) bool {
- if timeout <= 0 {
- h.Wait()
- return true
- }
- done := make(chan struct{})
- go func() {
- h.Wait()
- close(done)
- }()
- t := time.NewTimer(timeout)
- defer t.Stop()
- select {
- case <-done:
- return true
- case <-t.C:
- return false
- }
-}
-
-// ShutdownTimeout exposes the configured graceful-shutdown deadline so
-// main.go can use the same value WaitWithTimeout is checked against
-// without re-deriving it.
-func (h *Hub) ShutdownTimeout() time.Duration { return h.cfg.ShutdownTimeout }
-
-// sweep enumerates currently-active installations and starts a
-// supervisor for any that this Hub does not yet supervise. Supervisors
-// for revoked installations are cancelled. Supervisors whose
-// underlying installation row has rotated credentials (re-scan in the
-// device flow creates a fresh app_id / app_secret) are cancelled and
-// replaced inline so the new connector picks up the fresh row instead
-// of running indefinitely against stale credentials.
-func (h *Hub) sweep(ctx context.Context) {
- rows, err := h.queries.ListActiveLarkInstallations(ctx)
- if err != nil {
- h.cfg.Logger.Warn("lark hub: list active installations failed", "error", err)
- return
- }
- active := make(map[string]struct{}, len(rows))
- for _, row := range rows {
- id := uuidString(row.ID)
- active[id] = struct{}{}
- h.maybeRestartOnRotation(id, row)
- h.startSupervisor(ctx, row)
- }
- // Reap supervisors whose installation is no longer active (revoked
- // since the last sweep). The supervisor will exit on the next
- // boundary, release its lease, and the goroutine returns.
- h.mu.Lock()
- for id, entry := range h.supervisors {
- if _, stillActive := active[id]; !stillActive {
- entry.cancel()
- delete(h.supervisors, id)
- }
- }
- h.mu.Unlock()
-}
-
-// maybeRestartOnRotation cancels an existing supervisor when its
-// credentials fingerprint differs from the current row's. The new
-// supervisor is started by the subsequent startSupervisor call within
-// the same sweep iteration. We drop the map entry inline so the
-// startSupervisor "skip if already supervised" guard does not race the
-// cancel — the deleted entry's goroutine releases its lease as part of
-// teardown, and the new supervisor's acquireLease takes over on its
-// own clock.
-func (h *Hub) maybeRestartOnRotation(id string, row Installation) {
- want := installationFingerprint(row)
- h.mu.Lock()
- entry, ok := h.supervisors[id]
- if !ok || entry.fingerprint == want {
- h.mu.Unlock()
- return
- }
- h.cfg.Logger.Info("lark hub: credentials rotated, restarting supervisor",
- "installation_id", id,
- "app_id", row.AppID,
- )
- entry.cancel()
- delete(h.supervisors, id)
- h.mu.Unlock()
-}
-
-func (h *Hub) startSupervisor(parent context.Context, inst Installation) {
- id := uuidString(inst.ID)
- h.mu.Lock()
- if h.stopped {
- h.mu.Unlock()
- return
- }
- if _, exists := h.supervisors[id]; exists {
- h.mu.Unlock()
- return
- }
- ctx, cancel := context.WithCancel(parent)
- h.supervisorGen++
- gen := h.supervisorGen
- h.supervisors[id] = supervisorEntry{
- cancel: cancel,
- fingerprint: installationFingerprint(inst),
- gen: gen,
- }
- h.wg.Add(1)
- h.mu.Unlock()
- go h.supervise(ctx, inst, id, gen)
-}
-
-// leaseToken composes the per-supervisor lease token. We pair the
-// Hub-wide nodeID (so multi-replica observability still works — an
-// operator inspecting lark_installation.ws_lease_token can map it
-// back to a process) with the supervisor's gen so two supervisors
-// inside the SAME Hub running back-to-back for the same installation
-// (the rotation path) carry different tokens. That distinction is
-// what stops an old supervisor's post-cancel releaseLease from
-// CAS-matching and DELETE-ing the lease the successor just acquired.
-//
-// We use strconv.FormatUint rather than fmt.Sprintf because this is on
-// the supervise hot path (called on every renew tick when its result
-// would be ineligible to be cached) and we'd like to keep allocation
-// pressure minimal.
-func leaseToken(nodeID string, gen uint64) string {
- return nodeID + "-g" + strconv.FormatUint(gen, 10)
-}
-
-// installationFingerprint condenses the credentials-bearing columns of
-// the installation row into an opaque string. Two rows with the same
-// fingerprint are interchangeable as far as the connector is concerned;
-// any byte difference here means the next sweep will tear the running
-// supervisor down and start it again with the fresh credentials. We
-// include app_id (which Lark rotates on every device-flow registration),
-// bot_open_id (sanity — protects against an app_id reuse with a
-// different bot identity), and a SHA-256 of the encrypted app_secret
-// blob so a re-encrypt at rest also triggers a restart. The plaintext
-// secret is never extracted; the encrypted ciphertext is fine to hash.
-func installationFingerprint(inst Installation) string {
- sum := sha256.Sum256(inst.AppSecretEncrypted)
- // region is part of the fingerprint: if a re-install corrects the
- // cloud (e.g. a row mis-detected as feishu is re-scanned as lark),
- // the WS bootstrap host changes, so the running supervisor must be
- // torn down and restarted against the new host.
- return inst.AppID + "|" + inst.BotOpenID + "|" + inst.Region + "|" + hex.EncodeToString(sum[:])
-}
-
-// supervise owns one installation's connection lifecycle. It loops:
-// acquire lease → spin up connector → renew lease while connector is
-// running → on connector exit, back off → repeat. Returns (and the
-// goroutine ends) when ctx is cancelled.
-func (h *Hub) supervise(ctx context.Context, inst Installation, id string, gen uint64) {
- defer h.wg.Done()
- defer func() {
- // Only clear the supervisors map entry if it still belongs to
- // us — gen disambiguates "this entry is mine" from "the
- // rotation path already replaced me with a fresh supervisor."
- // Without the gen check, the old goroutine's defer would race
- // to delete the new entry it knows nothing about.
- h.mu.Lock()
- if entry, ok := h.supervisors[id]; ok && entry.gen == gen {
- delete(h.supervisors, id)
- }
- h.mu.Unlock()
- }()
-
- // Per-supervisor lease token: scopes the DB-level token fence to
- // THIS goroutine so a stale post-cancel release from a rotation
- // predecessor can't clobber a successor's just-acquired lease.
- // Embeds the Hub's nodeID for cross-replica observability and the
- // supervisor gen so the same Hub running multiple sequential
- // supervisors for the same installation (rotation) gets distinct
- // tokens for each.
- leaseTok := leaseToken(h.nodeID, gen)
- log := h.cfg.Logger.With(
- "installation_id", id,
- "node_id", h.nodeID,
- "lease_token", leaseTok,
- )
- backoff := h.cfg.MinBackoff
-
- for {
- if ctx.Err() != nil {
- return
- }
-
- // Try to claim the WS lease for this installation. If another
- // replica already owns a live lease, sleep until either the
- // lease expires or our context is cancelled.
- leased, err := h.acquireLease(ctx, inst.ID, leaseTok)
- if err != nil {
- log.Warn("lark hub: acquire lease error", "error", err)
- if sleep(ctx, h.cfg.LeaseRenewInterval) {
- return
- }
- continue
- }
- if !leased {
- // Another replica owns the lease. Wait LeaseRenewInterval
- // (less than LeaseTTL) and re-check; if they die, we'll
- // pick it up on the next iteration.
- if sleep(ctx, h.cfg.LeaseRenewInterval) {
- return
- }
- continue
- }
-
- // Lease acquired. Build a connector, run it under a child
- // context, and start the lease renewer in parallel. The
- // connector returns when its connection dies or our ctx is
- // cancelled; we always release the lease afterwards.
- conn, err := h.factory(inst)
- if err != nil {
- log.Error("lark hub: connector factory failed", "error", err)
- h.releaseLease(inst.ID, leaseTok)
- if sleep(ctx, backoff) {
- return
- }
- backoff = nextBackoff(backoff, h.cfg.MaxBackoff)
- continue
- }
-
- runCtx, runCancel := context.WithCancel(ctx)
- renewDone := make(chan struct{})
- go func() {
- defer close(renewDone)
- // renewLeaseUntil cancels runCtx itself on lease loss so the
- // connector exits even if its wire I/O is currently blocked.
- // This is what makes the "at most one active WS per
- // installation across replicas" invariant hold under lease
- // theft: A's renewer fails CAS the moment B steals the
- // lease, A's runCtx flips done, A's connector returns, and
- // only B is consuming events.
- h.renewLeaseUntil(runCtx, runCancel, inst.ID, leaseTok)
- }()
-
- startedAt := h.cfg.Now()
- runErr := conn.Run(runCtx, inst, func(emitCtx context.Context, msg InboundMessage) (DispatchResult, error) {
- return h.handleEvent(emitCtx, inst, log, msg)
- })
- runCancel()
- <-renewDone
- h.releaseLease(inst.ID, leaseTok)
-
- if ctx.Err() != nil {
- return
- }
-
- // If the connection lived long enough that we believe it was
- // "stable", reset the backoff so a single late failure does
- // not start us at the cap. Otherwise step up the backoff.
- uptime := h.cfg.Now().Sub(startedAt)
- if uptime >= h.cfg.ResetBackoffAfter {
- backoff = h.cfg.MinBackoff
- }
- if runErr != nil {
- log.Warn("lark hub: connector exited with error", "error", runErr, "uptime", uptime.String())
- } else {
- log.Info("lark hub: connector exited cleanly", "uptime", uptime.String())
- }
- if sleep(ctx, jitter(backoff)) {
- return
- }
- backoff = nextBackoff(backoff, h.cfg.MaxBackoff)
- }
-}
-
-// acquireLease tries to claim or renew the WS lease for an
-// installation. Returns (true, nil) when the lease is owned by this
-// supervisor after the call; (false, nil) when another replica or
-// in-process predecessor holds a live lease; or (false, err) for
-// transport / DB failures.
-//
-// token is a per-supervisor identifier (see leaseToken) — NOT the
-// hub-wide nodeID. This is the load-bearing change for rotation
-// safety: an old supervisor and its successor inside the same Hub
-// each carry a distinct token, so the old supervisor's stale release
-// can no longer match (and DELETE) the successor's just-acquired
-// lease row.
-func (h *Hub) acquireLease(ctx context.Context, instID pgtype.UUID, token string) (bool, error) {
- expires := h.cfg.Now().Add(h.cfg.LeaseTTL)
- _, err := h.queries.AcquireLarkWSLease(ctx, AcquireWSLeaseParams{
- ID: instID,
- NewToken: pgtype.Text{String: token, Valid: true},
- NewExpiresAt: pgtype.Timestamptz{Time: expires, Valid: true},
- })
- if err == nil {
- return true, nil
- }
- if isNoRowsErr(err) {
- // CAS predicate didn't match — someone else (another replica
- // OR a sibling supervisor mid-rotation) holds the lease. We
- // back off and let the renewer / supervise loop re-poll on its
- // own clock.
- return false, nil
- }
- return false, err
-}
-
-// renewLeaseUntil re-acquires the lease on a tight cadence so a single
-// missed renewal does not yield it. Exits when ctx is cancelled.
-//
-// Lease loss (acquireLease returns leased=false) MUST cancel the
-// connector's run context — otherwise the supervise loop would
-// release the lease but the connector goroutine could still be
-// blocked on its wire I/O and continue consuming Lark events until
-// its TCP read finally errored out. That window is exactly the
-// "two replicas processing the same installation" failure mode the
-// §4.4 ownership invariant rules out. Calling cancelRun here forces
-// the connector's ctx to flip done immediately, so conn.Run returns
-// in bounded time even when the underlying socket is silent.
-//
-// token MUST be the same per-supervisor token threaded through the
-// initial acquireLease call. Otherwise the very first renewal would
-// CAS-fail against the supervisor's own previous renew and tear the
-// connector down on every renew interval.
-func (h *Hub) renewLeaseUntil(ctx context.Context, cancelRun context.CancelFunc, instID pgtype.UUID, token string) {
- t := time.NewTicker(h.cfg.LeaseRenewInterval)
- defer t.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-t.C:
- leased, err := h.acquireLease(ctx, instID, token)
- if err != nil {
- h.cfg.Logger.Warn("lark hub: lease renewal error",
- "installation_id", uuidString(instID),
- "error", err,
- )
- continue
- }
- if !leased {
- h.cfg.Logger.Warn("lark hub: lease lost; tearing down connector",
- "installation_id", uuidString(instID),
- )
- cancelRun()
- return
- }
- }
- }
-}
-
-// releaseLease writes a token-fenced DELETE to lark_installation's
-// lease columns so the next supervisor (this process or another
-// replica) can pick up the installation without waiting for LeaseTTL
-// to expire.
-//
-// The supervisor calls this from two places — factory-error retry and
-// post-Run cleanup — and at shutdown the parent ctx is already done,
-// so passing it through would short-circuit the DB call before it ever
-// reached the pool. Instead we derive a fresh background ctx with a
-// bounded LeaseReleaseTimeout: a healthy pool finishes in milliseconds,
-// and a frozen pool can no longer hang shutdown indefinitely. The
-// fallback when the bound trips is the same as a crash — the lease row
-// stays put until its TTL elapses on the next replica.
-//
-// token MUST be the same per-supervisor token used to acquire. If a
-// rotation has already replaced this supervisor and the successor has
-// taken the lease with its own token, the DELETE's WHERE clause won't
-// match this supervisor's stale token and the call no-ops instead of
-// clobbering the successor's lease. That fence is the whole point of
-// per-supervisor tokens.
-func (h *Hub) releaseLease(instID pgtype.UUID, token string) {
- ctx, cancel := context.WithTimeout(context.Background(), h.cfg.LeaseReleaseTimeout)
- defer cancel()
- if err := h.queries.ReleaseLarkWSLease(ctx, ReleaseWSLeaseParams{
- ID: instID,
- CurrentToken: pgtype.Text{String: token, Valid: true},
- }); err != nil {
- h.cfg.Logger.Warn("lark hub: release lease failed",
- "installation_id", uuidString(instID),
- "error", err,
- )
- }
-}
-
-// handleEvent is the seam between the connector (which emits normalized
-// InboundMessage) and the inbound Dispatcher + outbound OutcomeReplier.
-// We deliberately do not retry here — the Dispatcher classifies errors
-// itself (productizable outcomes vs. infra failures), and infra
-// failures propagate up to the connector, which decides whether to
-// reconnect.
-//
-// CRITICAL: handleEvent MUST return promptly because the connector
-// writes the frame ACK right after emit returns, and Lark's long-conn
-// server expects an ACK within 3 seconds. The dispatcher itself is
-// fast (one DB roundtrip + identity check) but the outbound replier
-// can do real Lark HTTP calls — token mint, card send — each with
-// its own multi-second client timeout. Running the replier inline
-// would couple ACK latency to outbound HTTP, and if that HTTP stalls
-// for >3s Lark treats the event as un-ACKed and re-pushes it; by then
-// Dispatcher has already marked the dedup row terminal, so the retry
-// gets dropped and the user never receives the binding prompt /
-// offline notice.
-//
-// Fix: dispatch is synchronous (in the connector's read loop), the
-// reply is detached. Each reply runs in its own goroutine under a
-// fresh context bounded by ReplyTimeout (strictly under 3s). Hub.Wait
-// joins on replyWg so shutdown still drains in-flight replies.
-func (h *Hub) handleEvent(ctx context.Context, inst Installation, log *slog.Logger, msg InboundMessage) (DispatchResult, error) {
- if h.dispatcher == nil {
- log.Warn("lark hub: dispatcher not configured; dropping event",
- "event_id", msg.EventID,
- )
- return DispatchResult{}, ErrDispatcherNotConfigured
- }
- res, err := h.dispatcher.Handle(ctx, msg)
- if err != nil {
- log.Error("lark hub: dispatcher error",
- "event_id", msg.EventID,
- "error", err,
- )
- return res, err
- }
- log.Debug("lark hub: dispatch outcome",
- "event_id", msg.EventID,
- "outcome", string(res.Outcome),
- "drop_reason", string(res.DropReason),
- )
- if res.Outcome == OutcomeIngested && h.typingIndicator != nil {
- // Detached: the typing reaction HTTP call must not block the
- // connector's ACK path. A short timeout keeps the goroutine
- // from hanging if Lark is slow.
- go func() {
- addCtx, cancel := context.WithTimeout(context.Background(), h.cfg.ReplyTimeout)
- defer cancel()
- h.typingIndicator.Add(addCtx, inst, res.ChatSessionID, msg.MessageID, msg.CreateTime)
- }()
- }
- h.scheduleReply(inst, msg, res, log)
- return res, nil
-}
-
-// scheduleReply detaches the OutcomeReplier from the ACK critical path.
-// The reply goroutine uses a fresh context.Background() with a
-// ReplyTimeout deadline so it is independent of the inbound emit ctx
-// (which the connector cancels as soon as Run exits). A nil or noop
-// replier short-circuits — no goroutine, no wg tracking.
-//
-// Why a fresh background ctx instead of inheriting from the emit ctx:
-// the emit ctx is cancelled when the connector's runCtx fires, which
-// can happen mid-reply on a normal reconnect cycle. Inheriting would
-// kill the outbound reply for no reason — the binding card / offline
-// notice is still wanted. ReplyTimeout is the only guard we need.
-func (h *Hub) scheduleReply(inst Installation, msg InboundMessage, res DispatchResult, log *slog.Logger) {
- r := h.replier
- if r == nil {
- return
- }
- // Fast path: noop replier doesn't do any IO, run it inline so we
- // don't pay goroutine + waitgroup cost for a no-op. The exposed
- // type is unexported but the test seam uses NewNoopOutcomeReplier
- // which returns *noopReplier, so the type-assert is safe.
- if _, isNoop := r.(*noopReplier); isNoop {
- r.Reply(context.Background(), inst, msg, res)
- return
- }
- h.replyWg.Add(1)
- go func() {
- defer h.replyWg.Done()
- ctx, cancel := context.WithTimeout(context.Background(), h.cfg.ReplyTimeout)
- defer cancel()
- r.Reply(ctx, inst, msg, res)
- if ctx.Err() == context.DeadlineExceeded {
- log.Warn("lark hub: outbound reply timed out",
- "event_id", msg.EventID,
- "outcome", string(res.Outcome),
- "timeout", h.cfg.ReplyTimeout.String(),
- )
- }
- }()
-}
-
-// ErrDispatcherNotConfigured is surfaced to the connector when emit is
-// called on a Hub that was constructed without a Dispatcher. Returning
-// it (instead of silently dropping) lets the connector log and / or
-// disconnect so the misconfiguration is visible in production.
-var ErrDispatcherNotConfigured = errors.New("lark hub: dispatcher not configured")
-
-func (h *Hub) cancelAll() {
- h.mu.Lock()
- h.stopped = true
- for id, entry := range h.supervisors {
- entry.cancel()
- delete(h.supervisors, id)
- }
- h.mu.Unlock()
-}
-
-// newNodeID returns a 16-byte hex random string unique to this process.
-// The DB stores it in lark_installation.ws_lease_token; matching tokens
-// on subsequent acquires are treated as renewals (same owner).
-func newNodeID() string {
- buf := make([]byte, 16)
- if _, err := cryptorand.Read(buf); err != nil {
- // crypto/rand failure is catastrophic and rare; fall back to a
- // timestamp-derived token rather than panicking on boot.
- return fmt.Sprintf("nodeid-fallback-%d", time.Now().UnixNano())
- }
- return hex.EncodeToString(buf)
-}
-
-// nextBackoff doubles the current backoff up to max. Pure helper so
-// the supervise loop reads top-to-bottom.
-func nextBackoff(cur, max time.Duration) time.Duration {
- next := cur * 2
- if next > max {
- return max
- }
- return next
-}
-
-// jitter spreads reconnect storms (e.g. after a Lark-side outage)
-// across the [0.5d, 1.5d) window, so 100 installations don't all
-// retry on the same timer edge.
-func jitter(d time.Duration) time.Duration {
- if d <= 0 {
- return d
- }
- delta := d / 2
- return d - delta + time.Duration(mathrand.Int64N(int64(2*delta)+1))
-}
-
-// sleep is a ctx-aware time.Sleep. Returns true iff the ctx was
-// cancelled before the sleep completed — callers use the boolean to
-// short-circuit shutdown.
-func sleep(ctx context.Context, d time.Duration) bool {
- if d <= 0 {
- return ctx.Err() != nil
- }
- t := time.NewTimer(d)
- defer t.Stop()
- select {
- case <-ctx.Done():
- return true
- case <-t.C:
- return false
- }
-}
-
-// isNoRowsErr is the local equivalent of errors.Is(err, pgx.ErrNoRows)
-// without importing pgx into this file. The CAS predicate on
-// AcquireLarkWSLease surfaces "lease held by someone else" as a
-// no-rows return, not a structured error type.
-func isNoRowsErr(err error) bool {
- if err == nil {
- return false
- }
- // pgx.ErrNoRows is the sentinel; matching by message is
- // sufficient and avoids importing pgx purely for this comparison.
- return errors.Is(err, errPgxNoRows) || err.Error() == "no rows in result set"
-}
-
-// errPgxNoRows is initialized in hub_pgx.go to pgx.ErrNoRows so the
-// no-rows check above works under both the real pgx import path and
-// the string-matched fallback (test fakes return that string directly).
-var errPgxNoRows error
-
-func uuidString(u pgtype.UUID) string { return util.UUIDToString(u) }
diff --git a/server/internal/integrations/lark/hub_pgx.go b/server/internal/integrations/lark/hub_pgx.go
deleted file mode 100644
index 4e309d3cfe..0000000000
--- a/server/internal/integrations/lark/hub_pgx.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package lark
-
-import "github.com/jackc/pgx/v5"
-
-func init() {
- // Bind the package-level sentinel used by hub.go's isNoRowsErr.
- // Keeping the pgx import isolated to this file means the rest of
- // hub.go (and the test seam against fake queries) doesn't need the
- // pgx import path; fakes can return errors.New("no rows in result
- // set") and still trigger the lease "held elsewhere" branch.
- errPgxNoRows = pgx.ErrNoRows
-}
diff --git a/server/internal/integrations/lark/hub_test.go b/server/internal/integrations/lark/hub_test.go
deleted file mode 100644
index 9f7a2aa476..0000000000
--- a/server/internal/integrations/lark/hub_test.go
+++ /dev/null
@@ -1,1292 +0,0 @@
-package lark
-
-import (
- "bytes"
- "context"
- "errors"
- "io"
- "log/slog"
- "sync"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/jackc/pgx/v5/pgtype"
-)
-
-// fakeHubQueries is the unit-test seam for HubQueries. The lease state
-// is held in memory so a single fake can play both "we hold the lease"
-// and "another replica holds the lease" scenarios across one test.
-type fakeHubQueries struct {
- mu sync.Mutex
- installations []Installation
- listErr error
- leaseOwner map[string]string // installation_id -> ws_lease_token
- leaseExpiresAt map[string]time.Time // installation_id -> expiry
- acquireErr error
- releaseErr error
- now func() time.Time
- acquireCount int32
-
- // releaseBlock, if non-nil, makes ReleaseLarkWSLease block until
- // either the channel is closed/sent on OR the caller's ctx fires.
- // Used to simulate a frozen DB pool so the bounded-release timeout
- // can be exercised without standing up real infrastructure.
- releaseBlock chan struct{}
- // releaseObservedCtxErr captures the ctx error (typically
- // context.DeadlineExceeded) the blocked release call observed
- // when its bounded ctx fired. Inspected by tests to prove the
- // bound actually fired instead of the test happening to win the
- // race naturally.
- releaseObservedCtxErr error
-}
-
-func newFakeHubQueries() *fakeHubQueries {
- return &fakeHubQueries{
- leaseOwner: make(map[string]string),
- leaseExpiresAt: make(map[string]time.Time),
- now: time.Now,
- }
-}
-
-func (f *fakeHubQueries) ListActiveLarkInstallations(ctx context.Context) ([]Installation, error) {
- f.mu.Lock()
- defer f.mu.Unlock()
- if f.listErr != nil {
- return nil, f.listErr
- }
- out := make([]Installation, len(f.installations))
- copy(out, f.installations)
- return out, nil
-}
-
-func (f *fakeHubQueries) AcquireLarkWSLease(ctx context.Context, arg AcquireWSLeaseParams) (Installation, error) {
- atomic.AddInt32(&f.acquireCount, 1)
- f.mu.Lock()
- defer f.mu.Unlock()
- if f.acquireErr != nil {
- return Installation{}, f.acquireErr
- }
- id := uuidString(arg.ID)
- owner, hasOwner := f.leaseOwner[id]
- exp := f.leaseExpiresAt[id]
- now := f.now()
- // CAS: accept when no holder, holder expired, or holder is us.
- if !hasOwner || exp.Before(now) || owner == arg.NewToken.String {
- f.leaseOwner[id] = arg.NewToken.String
- f.leaseExpiresAt[id] = arg.NewExpiresAt.Time
- // Return the (synthetic) row — the supervise loop only checks
- // the error, not the row contents.
- return Installation{ID: arg.ID}, nil
- }
- // Live lease held by someone else.
- return Installation{}, errPgxNoRows
-}
-
-func (f *fakeHubQueries) ReleaseLarkWSLease(ctx context.Context, arg ReleaseWSLeaseParams) error {
- f.mu.Lock()
- block := f.releaseBlock
- f.mu.Unlock()
- if block != nil {
- select {
- case <-block:
- // Released by the test — fall through to the normal path.
- case <-ctx.Done():
- f.mu.Lock()
- f.releaseObservedCtxErr = ctx.Err()
- f.mu.Unlock()
- return ctx.Err()
- }
- }
- f.mu.Lock()
- defer f.mu.Unlock()
- if f.releaseErr != nil {
- return f.releaseErr
- }
- id := uuidString(arg.ID)
- if f.leaseOwner[id] == arg.CurrentToken.String {
- delete(f.leaseOwner, id)
- delete(f.leaseExpiresAt, id)
- }
- return nil
-}
-
-// presetLease forcibly assigns a lease to a holder other than the hub
-// under test. Used to verify "another replica owns it" branches.
-func (f *fakeHubQueries) presetLease(id pgtype.UUID, token string, expires time.Time) {
- f.mu.Lock()
- defer f.mu.Unlock()
- f.leaseOwner[uuidString(id)] = token
- f.leaseExpiresAt[uuidString(id)] = expires
-}
-
-// fakeConnector counts how many times Run was invoked and behaves
-// according to the script provided per-call. The default behavior
-// (script nil) blocks on ctx.Done — useful for the "owns lease, stays
-// connected" test.
-type fakeConnector struct {
- mu sync.Mutex
- runs int
- script []func(ctx context.Context, emit EventEmitter) error
- emit EventEmitter
-}
-
-func (f *fakeConnector) Run(ctx context.Context, _ Installation, emit EventEmitter) error {
- f.mu.Lock()
- idx := f.runs
- f.runs++
- if idx < len(f.script) {
- fn := f.script[idx]
- f.mu.Unlock()
- return fn(ctx, emit)
- }
- f.mu.Unlock()
- // Default: hold until cancelled.
- f.emit = emit
- <-ctx.Done()
- return nil
-}
-
-func (f *fakeConnector) Runs() int {
- f.mu.Lock()
- defer f.mu.Unlock()
- return f.runs
-}
-
-func uuidFromString(t *testing.T, s string) pgtype.UUID {
- t.Helper()
- var u pgtype.UUID
- if err := u.Scan(s); err != nil {
- t.Fatalf("scan uuid %q: %v", s, err)
- }
- return u
-}
-
-func newDiscardLogger() *slog.Logger {
- return slog.New(slog.NewTextHandler(io.Discard, nil))
-}
-
-func TestHubAcquiresLeaseAndStartsSupervisor(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "11111111-1111-1111-1111-111111111111")
- q.installations = []Installation{{ID: instID, Status: "active"}}
-
- conn := &fakeConnector{}
- factory := func(_ Installation) (EventConnector, error) { return conn, nil }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 50 * time.Millisecond,
- PollInterval: 10 * time.Millisecond,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 50 * time.Millisecond,
- ResetBackoffAfter: 1 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
-
- // Wait until the supervisor has started the connector at least once.
- if !waitFor(200*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {
- t.Fatalf("expected connector to start; runs=%d", conn.Runs())
- }
-
- cancel()
- hub.Wait()
-
- // After shutdown the lease should be released so another replica
- // can take over without waiting for the TTL to elapse.
- q.mu.Lock()
- defer q.mu.Unlock()
- if _, ok := q.leaseOwner[uuidString(instID)]; ok {
- t.Fatalf("lease should be released after shutdown, got owner %q", q.leaseOwner[uuidString(instID)])
- }
-}
-
-func TestHubSkipsInstallationWhenAnotherReplicaHoldsLease(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "22222222-2222-2222-2222-222222222222")
- q.installations = []Installation{{ID: instID, Status: "active"}}
- // Another replica already owns the lease for the next 10 seconds.
- q.presetLease(instID, "other-replica", time.Now().Add(10*time.Second))
-
- conn := &fakeConnector{}
- factory := func(_ Installation) (EventConnector, error) { return conn, nil }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 20 * time.Millisecond,
- PollInterval: 20 * time.Millisecond,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 1 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
-
- // Give the hub plenty of opportunity to try to take over.
- time.Sleep(150 * time.Millisecond)
-
- if conn.Runs() != 0 {
- t.Fatalf("connector should not run while another replica owns lease; runs=%d", conn.Runs())
- }
-
- cancel()
- hub.Wait()
-}
-
-func TestHubReclaimsLeaseAfterAnotherReplicaExpires(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "33333333-3333-3333-3333-333333333333")
- q.installations = []Installation{{ID: instID, Status: "active"}}
- // Set the other replica's lease to expire in 80ms so the hub
- // (which polls/renews on 20ms intervals) will pick it up.
- q.presetLease(instID, "other-replica", time.Now().Add(80*time.Millisecond))
-
- conn := &fakeConnector{}
- factory := func(_ Installation) (EventConnector, error) { return conn, nil }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 20 * time.Millisecond,
- PollInterval: 20 * time.Millisecond,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 1 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
-
- if !waitFor(500*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {
- t.Fatalf("expected connector to start after lease expiry; runs=%d", conn.Runs())
- }
- cancel()
- hub.Wait()
-}
-
-func TestHubReapsSupervisorWhenInstallationRevoked(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "44444444-4444-4444-4444-444444444444")
- q.installations = []Installation{{ID: instID, Status: "active"}}
-
- conn := &fakeConnector{}
- factory := func(_ Installation) (EventConnector, error) { return conn, nil }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 20 * time.Millisecond,
- PollInterval: 20 * time.Millisecond,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 1 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
- defer func() { cancel(); hub.Wait() }()
-
- if !waitFor(200*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {
- t.Fatalf("expected connector to start; runs=%d", conn.Runs())
- }
-
- // Simulate revocation: the installation disappears from
- // ListActiveLarkInstallations. The Hub should cancel its
- // supervisor on the next sweep, which releases the lease.
- q.mu.Lock()
- q.installations = nil
- q.mu.Unlock()
-
- if !waitFor(500*time.Millisecond, func() bool {
- q.mu.Lock()
- defer q.mu.Unlock()
- _, stillHeld := q.leaseOwner[uuidString(instID)]
- return !stillHeld
- }) {
- t.Fatalf("expected lease to be released after revocation")
- }
-}
-
-// TestHubRestartsSupervisorOnCredentialsRotation pins the rotation
-// invariant Bohan hit on the live env: re-scanning the same agent
-// runs the device flow again, which mints a brand-new Lark bot with
-// a fresh app_id / encrypted app_secret. The lark_installation row is
-// updated in place (UNIQUE(agent_id)), but the running supervisor
-// holds the OLD inst struct by value. Without a fingerprint-driven
-// restart the connector keeps a WS open against the OLD bot's app_id
-// and the new bot silently goes dark — exactly the "claude code 没反应"
-// symptom Bohan reported.
-//
-// Repro: start the hub with installation A (app_id=app_one), wait for
-// the connector factory to be called, then mutate the row to a new
-// app_id (app_two). The next sweep MUST cancel the first supervisor
-// and start a second one with the new credentials.
-func TestHubRestartsSupervisorOnCredentialsRotation(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "abcdabcd-abcd-abcd-abcd-abcdabcdabcd")
- q.installations = []Installation{{
- ID: instID,
- Status: "active",
- AppID: "app_one",
- BotOpenID: "bot_open_id_one",
- AppSecretEncrypted: []byte("encrypted_one"),
- }}
-
- type seenInst struct{ AppID string }
- var mu sync.Mutex
- var seen []seenInst
- factory := func(inst Installation) (EventConnector, error) {
- mu.Lock()
- seen = append(seen, seenInst{AppID: inst.AppID})
- mu.Unlock()
- return &fakeConnector{}, nil
- }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 50 * time.Millisecond,
- PollInterval: 20 * time.Millisecond,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 1 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
- defer func() { cancel(); hub.Wait() }()
-
- if !waitFor(300*time.Millisecond, func() bool {
- mu.Lock()
- defer mu.Unlock()
- return len(seen) >= 1
- }) {
- t.Fatalf("expected initial connector start; got %d", len(seen))
- }
-
- // Rotate credentials in place — same installation_id, new app_id +
- // new encrypted secret. This is exactly what device-flow re-scan
- // produces.
- q.mu.Lock()
- q.installations[0].AppID = "app_two"
- q.installations[0].BotOpenID = "bot_open_id_two"
- q.installations[0].AppSecretEncrypted = []byte("encrypted_two")
- q.mu.Unlock()
-
- if !waitFor(500*time.Millisecond, func() bool {
- mu.Lock()
- defer mu.Unlock()
- for _, s := range seen {
- if s.AppID == "app_two" {
- return true
- }
- }
- return false
- }) {
- mu.Lock()
- got := append([]seenInst(nil), seen...)
- mu.Unlock()
- t.Fatalf("expected a second connector start with rotated app_id; got %+v", got)
- }
-}
-
-// TestHubDoesNotRestartSupervisorOnUnchangedRow pins the negative case:
-// a sweep that observes an installation row identical to the fingerprint
-// the supervisor was started with MUST NOT restart. Without this guard
-// the rotation logic would degrade into a busy-loop, tearing the
-// connector down on every poll tick.
-func TestHubDoesNotRestartSupervisorOnUnchangedRow(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "bcdebcde-bcde-bcde-bcde-bcdebcdebcde")
- q.installations = []Installation{{
- ID: instID,
- Status: "active",
- AppID: "app_stable",
- BotOpenID: "bot_stable",
- AppSecretEncrypted: []byte("stable"),
- }}
-
- starts := int32(0)
- factory := func(_ Installation) (EventConnector, error) {
- atomic.AddInt32(&starts, 1)
- return &fakeConnector{}, nil
- }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 50 * time.Millisecond,
- PollInterval: 10 * time.Millisecond,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 1 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
- defer func() { cancel(); hub.Wait() }()
-
- // Wait until the supervisor has called the factory at least once.
- if !waitFor(200*time.Millisecond, func() bool { return atomic.LoadInt32(&starts) >= 1 }) {
- t.Fatalf("expected initial connector start; got %d", starts)
- }
- // Let several sweep ticks happen with an unchanged row.
- time.Sleep(120 * time.Millisecond)
- got := atomic.LoadInt32(&starts)
- if got > 2 {
- // Allow one extra start in case the fakeConnector returns
- // immediately and the supervise loop re-enters the connector
- // factory under backoff. More than that is the busy-loop bug.
- t.Fatalf("supervisor restarted unexpectedly on unchanged row: %d factory calls in 320ms", got)
- }
-}
-
-// TestHubRotationStaleReleaseDoesNotClearSuccessorLease pins the
-// fix for Elon's review of HEAD be8d4cef. Before per-supervisor lease
-// tokens, both old and new supervisors of the same Hub used the same
-// hub-wide nodeID as their lease token. The rotation race went:
-//
-// 1. Old supervisor cancelled by maybeRestartOnRotation.
-// 2. New supervisor started; acquireLease takes the lease.
-// 3. Old supervisor finishes post-cancel unwind and calls
-// releaseLease(nodeID).
-// 4. DB row's CurrentToken still equals nodeID (because new
-// supervisor wrote the SAME token). DELETE matches → DB row
-// cleared → new supervisor's lease silently lost.
-//
-// Per-supervisor tokens (nodeID + "-g" + gen) make step 3's
-// CurrentToken belong to the OLD supervisor, and the DB row's actual
-// CurrentToken belongs to the NEW supervisor — so the DELETE no-ops
-// and the successor keeps its lease.
-//
-// This test drives the lease state machine directly through the
-// fakeHubQueries, simulating the exact ordering: old acquires
-// (token_A) → rotation → new acquires (token_B) → old's stale
-// release(token_A). The lease must remain held by token_B.
-func TestHubRotationStaleReleaseDoesNotClearSuccessorLease(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "deadbeef-dead-beef-dead-beefdeadbeef")
- expires := time.Now().Add(time.Minute)
-
- tokenA := leaseToken("node_xyz", 1)
- tokenB := leaseToken("node_xyz", 2)
- if tokenA == tokenB {
- t.Fatalf("per-supervisor tokens must differ; got %q for both", tokenA)
- }
-
- // Old supervisor acquires.
- if _, err := q.AcquireLarkWSLease(context.Background(), AcquireWSLeaseParams{
- ID: instID,
- NewToken: pgtype.Text{String: tokenA, Valid: true},
- NewExpiresAt: pgtype.Timestamptz{Time: expires, Valid: true},
- }); err != nil {
- t.Fatalf("old acquire: %v", err)
- }
- q.mu.Lock()
- if got := q.leaseOwner[uuidString(instID)]; got != tokenA {
- t.Fatalf("after old acquire, owner = %q; want %q", got, tokenA)
- }
- q.mu.Unlock()
-
- // Rotation: new supervisor takes over. acquireLease's CAS in the
- // production query accepts "matching token" as a renewal — but
- // here we want to exercise the post-cancel succession where the
- // old lease is gone or being replaced. The fake's CAS also accepts
- // expired rows, so we simulate the old supervisor's lease having
- // been released cleanly (its renewal hasn't fired yet on rotation
- // boundary, but in production a rotation cancels the old loop and
- // the old supervisor's defer eventually calls releaseLease — let
- // the new supervisor acquire BEFORE that release lands).
- q.mu.Lock()
- delete(q.leaseOwner, uuidString(instID))
- delete(q.leaseExpiresAt, uuidString(instID))
- q.mu.Unlock()
- if _, err := q.AcquireLarkWSLease(context.Background(), AcquireWSLeaseParams{
- ID: instID,
- NewToken: pgtype.Text{String: tokenB, Valid: true},
- NewExpiresAt: pgtype.Timestamptz{Time: expires, Valid: true},
- }); err != nil {
- t.Fatalf("new acquire: %v", err)
- }
- q.mu.Lock()
- if got := q.leaseOwner[uuidString(instID)]; got != tokenB {
- t.Fatalf("after new acquire, owner = %q; want %q", got, tokenB)
- }
- q.mu.Unlock()
-
- // Old supervisor's defer / cleanup fires AFTER new acquired.
- // Without per-supervisor tokens this would clobber tokenB's lease.
- if err := q.ReleaseLarkWSLease(context.Background(), ReleaseWSLeaseParams{
- ID: instID,
- CurrentToken: pgtype.Text{String: tokenA, Valid: true},
- }); err != nil {
- t.Fatalf("old release: %v", err)
- }
-
- // Successor's lease must still be held by tokenB.
- q.mu.Lock()
- got, ok := q.leaseOwner[uuidString(instID)]
- q.mu.Unlock()
- if !ok {
- t.Fatalf("successor lease silently cleared by stale release — the rotation race is back")
- }
- if got != tokenB {
- t.Fatalf("after stale release, owner = %q; want %q (successor's token)", got, tokenB)
- }
-}
-
-// TestHubRotationEndToEndKeepsSuccessorLeased exercises the same
-// rotation race through the live supervise loop — not just the lease
-// state machine in isolation. Drives a hub through:
-//
-// 1. install row with credentials A → supervisor1 acquires lease(A)
-// 2. credentials rotate to B → maybeRestartOnRotation cancels sup1
-// 3. supervisor2 starts, acquires lease(B)
-// 4. sup1's post-cancel releaseLease(A) runs; must NOT clear lease(B)
-//
-// Even with the timing being non-deterministic (real goroutines), the
-// fake's lease map either ends up with sup2's token or empty — empty
-// means the successor lost its lease and would never deliver events,
-// which is exactly the bug Elon flagged. We assert the lease ends up
-// held by sup2's token.
-func TestHubRotationEndToEndKeepsSuccessorLeased(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "feedfeed-feed-feed-feed-feedfeedfeed")
- q.installations = []Installation{{
- ID: instID,
- Status: "active",
- AppID: "app_one",
- BotOpenID: "bot_one",
- AppSecretEncrypted: []byte("secret_one"),
- }}
-
- // Use a fakeConnector that blocks on ctx.Done so the renewer keeps
- // running and refreshes the lease at each tick, mirroring
- // production timing for the rotation handoff.
- factoryCalls := int32(0)
- factory := func(_ Installation) (EventConnector, error) {
- atomic.AddInt32(&factoryCalls, 1)
- return &fakeConnector{}, nil
- }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 30 * time.Millisecond,
- PollInterval: 15 * time.Millisecond,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 1 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
- defer func() { cancel(); hub.Wait() }()
-
- if !waitFor(300*time.Millisecond, func() bool { return atomic.LoadInt32(&factoryCalls) >= 1 }) {
- t.Fatalf("expected sup1 to start; got %d factory calls", factoryCalls)
- }
- q.mu.Lock()
- sup1Token := q.leaseOwner[uuidString(instID)]
- q.mu.Unlock()
- if sup1Token == "" {
- t.Fatalf("sup1 did not write a lease token")
- }
-
- // Rotation.
- q.mu.Lock()
- q.installations[0].AppID = "app_two"
- q.installations[0].BotOpenID = "bot_two"
- q.installations[0].AppSecretEncrypted = []byte("secret_two")
- q.mu.Unlock()
-
- // Wait for sup2 to start AND its lease token to differ from sup1's.
- // The successor's token must end up owning the row regardless of
- // when sup1's stale release lands.
- if !waitFor(500*time.Millisecond, func() bool {
- if atomic.LoadInt32(&factoryCalls) < 2 {
- return false
- }
- q.mu.Lock()
- defer q.mu.Unlock()
- curr, ok := q.leaseOwner[uuidString(instID)]
- return ok && curr != sup1Token
- }) {
- q.mu.Lock()
- got, ok := q.leaseOwner[uuidString(instID)]
- q.mu.Unlock()
- t.Fatalf("successor lease never present; ok=%v owner=%q factoryCalls=%d",
- ok, got, atomic.LoadInt32(&factoryCalls))
- }
-
- // Give sup1's deferred release a chance to land, then re-check.
- time.Sleep(150 * time.Millisecond)
- q.mu.Lock()
- owner, ok := q.leaseOwner[uuidString(instID)]
- q.mu.Unlock()
- if !ok {
- t.Fatalf("successor lease cleared after sup1's stale release — rotation fencing broken")
- }
- if owner == sup1Token {
- t.Fatalf("lease still held by sup1 token %q; successor never took over", sup1Token)
- }
-}
-
-func TestHubBacksOffOnFactoryError(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "55555555-5555-5555-5555-555555555555")
- q.installations = []Installation{{ID: instID, Status: "active"}}
-
- factoryCalls := int32(0)
- factory := func(_ Installation) (EventConnector, error) {
- atomic.AddInt32(&factoryCalls, 1)
- return nil, errors.New("boom")
- }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 20 * time.Millisecond,
- PollInterval: 20 * time.Millisecond,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 1 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
-
- // Let the supervisor retry under backoff. We want > 1 call to
- // prove the loop is alive but the increasing delay should keep
- // the rate sane.
- if !waitFor(200*time.Millisecond, func() bool { return atomic.LoadInt32(&factoryCalls) >= 2 }) {
- t.Fatalf("expected factory retries under backoff; got %d", atomic.LoadInt32(&factoryCalls))
- }
- calls := atomic.LoadInt32(&factoryCalls)
- cancel()
- hub.Wait()
- if calls > 200 {
- t.Fatalf("backoff appears broken: %d factory calls in 200ms", calls)
- }
-}
-
-// TestHubLeaseLossCancelsConnector pins the §4.4 ownership invariant.
-// When another replica steals the lease, the renewer must cancel the
-// connector's run context so the connector exits even if its wire I/O
-// is currently blocked. Without that cancel, replica A could keep
-// reading Lark events for an unbounded window while replica B already
-// believes it is the sole owner — duplicate consumption, exactly what
-// the lease is supposed to prevent.
-func TestHubLeaseLossCancelsConnector(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "66666666-6666-6666-6666-666666666666")
- q.installations = []Installation{{ID: instID, Status: "active"}}
-
- // fakeConnector default behavior blocks on ctx.Done — perfect for
- // "simulate a socket that never returns until we explicitly cancel
- // it" scenarios. We capture the ctx the supervisor handed it so we
- // can wait on its done channel directly.
- connCtxCh := make(chan context.Context, 1)
- conn := &fakeConnector{
- script: []func(ctx context.Context, emit EventEmitter) error{
- func(ctx context.Context, _ EventEmitter) error {
- connCtxCh <- ctx
- <-ctx.Done()
- return ctx.Err()
- },
- },
- }
- factory := func(_ Installation) (EventConnector, error) { return conn, nil }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 20 * time.Millisecond,
- PollInterval: 1 * time.Hour, // disable sweep noise; we drive lease state by hand.
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 10 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- defer func() { cancel(); hub.Wait() }()
- go hub.Run(ctx)
-
- // Wait for the supervisor to hand the connector a run context.
- var runCtx context.Context
- select {
- case runCtx = <-connCtxCh:
- case <-time.After(500 * time.Millisecond):
- t.Fatalf("connector never started")
- }
-
- // Simulate lease theft: rewrite the lease row to point at another
- // replica with a fresh expiry. The next renewal CAS will fail
- // because the token no longer matches our nodeID, the renewer
- // returns leased=false, and (with the fix) cancels the run ctx.
- q.presetLease(instID, "thief-replica", time.Now().Add(10*time.Second))
-
- select {
- case <-runCtx.Done():
- // Expected: renewer cancelled runCtx within a few renewal ticks.
- case <-time.After(500 * time.Millisecond):
- t.Fatalf("renewer did not cancel run ctx after lease loss")
- }
-}
-
-// TestHubEmitReturnsDispatchResultAndError pins the connector-facing
-// emit contract: the supervisor's emit shim wraps the Dispatcher and
-// surfaces both the typed DispatchResult and any infra error so the
-// real Lark connector can post the right outbound (binding card,
-// offline card, etc.) and react to infra failures.
-func TestHubEmitReturnsDispatchResultAndError(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "77777777-7777-7777-7777-777777777777")
- q.installations = []Installation{{ID: instID, Status: "active"}}
-
- // Capture what emit returned on the first invocation so the
- // connector goroutine can stash it for the test.
- var (
- gotRes DispatchResult
- gotErr error
- gotMu sync.Mutex
- )
- emitDone := make(chan struct{})
-
- conn := &fakeConnector{
- script: []func(ctx context.Context, emit EventEmitter) error{
- func(ctx context.Context, emit EventEmitter) error {
- res, err := emit(ctx, InboundMessage{
- EventID: "evt-1",
- EventType: "im.message.receive_v1",
- })
- gotMu.Lock()
- gotRes = res
- gotErr = err
- gotMu.Unlock()
- close(emitDone)
- <-ctx.Done()
- return ctx.Err()
- },
- },
- }
- factory := func(_ Installation) (EventConnector, error) { return conn, nil }
-
- // No dispatcher wired -> emit must return ErrDispatcherNotConfigured.
- // The point is the error surfaces back to the connector instead of
- // being silently dropped at the Hub.
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 20 * time.Millisecond,
- PollInterval: 1 * time.Hour,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 10 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- defer func() { cancel(); hub.Wait() }()
- go hub.Run(ctx)
-
- select {
- case <-emitDone:
- case <-time.After(500 * time.Millisecond):
- t.Fatalf("connector never invoked emit")
- }
-
- gotMu.Lock()
- defer gotMu.Unlock()
- if !errors.Is(gotErr, ErrDispatcherNotConfigured) {
- t.Fatalf("emit should propagate dispatcher errors; got %v", gotErr)
- }
- if gotRes.Outcome != "" {
- t.Fatalf("emit should not invent an outcome on dispatcher error; got %q", gotRes.Outcome)
- }
-}
-
-// TestHubReleaseLeaseBoundedByTimeout pins the shutdown-safety
-// invariant: a frozen DB pool must NOT keep the supervisor blocked
-// on releaseLease past the configured LeaseReleaseTimeout. Without
-// the bound, ctx.Background()-rooted release calls could hang
-// forever on a stalled pool, dragging out process shutdown well
-// past the operator's expected drain budget.
-func TestHubReleaseLeaseBoundedByTimeout(t *testing.T) {
- q := newFakeHubQueries()
- q.releaseBlock = make(chan struct{}) // never closed; release always sees ctx.Done
- instID := uuidFromString(t, "88888888-8888-8888-8888-888888888888")
- q.installations = []Installation{{ID: instID, Status: "active"}}
-
- conn := &fakeConnector{}
- factory := func(_ Installation) (EventConnector, error) { return conn, nil }
-
- releaseTimeout := 50 * time.Millisecond
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 20 * time.Millisecond,
- PollInterval: 1 * time.Hour,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 10 * time.Second,
- LeaseReleaseTimeout: releaseTimeout,
- ShutdownTimeout: 2 * time.Second, // generous; we want WaitWithTimeout to succeed
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
-
- if !waitFor(500*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {
- cancel()
- hub.Wait()
- t.Fatalf("expected connector to start; runs=%d", conn.Runs())
- }
-
- start := time.Now()
- cancel()
- // WaitWithTimeout MUST return true: the bound on releaseLease
- // has to let the supervisor unwind even though our fake release
- // never returns on its own.
- if !hub.WaitWithTimeout(2 * time.Second) {
- t.Fatalf("supervisor stuck despite bounded release; lease release timeout did not fire")
- }
- elapsed := time.Since(start)
-
- // Sanity bound: shutdown must complete in roughly the release
- // timeout plus a small jitter, NOT seconds. If the bound regressed
- // (e.g. someone reintroduced ctx.Background() without a deadline),
- // this assertion catches it.
- if elapsed > 500*time.Millisecond {
- t.Fatalf("shutdown took %s; expected ≈ %s + slack", elapsed, releaseTimeout)
- }
-
- q.mu.Lock()
- gotErr := q.releaseObservedCtxErr
- q.mu.Unlock()
- if !errors.Is(gotErr, context.DeadlineExceeded) {
- t.Fatalf("release should have observed DeadlineExceeded from its bounded ctx; got %v", gotErr)
- }
-}
-
-// TestHubWaitWithTimeoutReturnsTrueWhenSupervisorsExit covers the
-// happy path: everything stops cleanly within the deadline, so the
-// caller can proceed without logging a timeout warning.
-func TestHubWaitWithTimeoutReturnsTrueWhenSupervisorsExit(t *testing.T) {
- q := newFakeHubQueries()
- instID := uuidFromString(t, "99999999-9999-9999-9999-999999999999")
- q.installations = []Installation{{ID: instID, Status: "active"}}
-
- conn := &fakeConnector{}
- factory := func(_ Installation) (EventConnector, error) { return conn, nil }
-
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 20 * time.Millisecond,
- PollInterval: 1 * time.Hour,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 10 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
-
- if !waitFor(500*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {
- cancel()
- hub.Wait()
- t.Fatalf("expected connector to start; runs=%d", conn.Runs())
- }
-
- cancel()
- if !hub.WaitWithTimeout(1 * time.Second) {
- t.Fatalf("WaitWithTimeout returned false despite supervisor exiting promptly")
- }
-}
-
-// TestHubWaitWithTimeoutReturnsFalseWhenSupervisorStuck pins the
-// bound on the join itself: if a (future real) connector or release
-// path ignores ctx and refuses to exit, WaitWithTimeout MUST return
-// false so main.go can log + proceed with shutdown rather than block
-// the process forever.
-func TestHubWaitWithTimeoutReturnsFalseWhenSupervisorStuck(t *testing.T) {
- q := newFakeHubQueries()
- q.releaseBlock = make(chan struct{}) // never closed
- instID := uuidFromString(t, "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
- q.installations = []Installation{{ID: instID, Status: "active"}}
-
- conn := &fakeConnector{}
- factory := func(_ Installation) (EventConnector, error) { return conn, nil }
-
- // LeaseReleaseTimeout > ShutdownTimeout so the release is still
- // blocked when the join deadline expires. This pins the "join
- // deadline trips before the supervisor unwinds" branch.
- hub := NewHub(q, factory, nil, HubConfig{
- LeaseTTL: 500 * time.Millisecond,
- LeaseRenewInterval: 20 * time.Millisecond,
- PollInterval: 1 * time.Hour,
- MinBackoff: 5 * time.Millisecond,
- MaxBackoff: 20 * time.Millisecond,
- ResetBackoffAfter: 10 * time.Second,
- LeaseReleaseTimeout: 5 * time.Second,
- Logger: newDiscardLogger(),
- })
-
- ctx, cancel := context.WithCancel(context.Background())
- go hub.Run(ctx)
-
- if !waitFor(500*time.Millisecond, func() bool { return conn.Runs() >= 1 }) {
- cancel()
- hub.Wait() // unbounded fallback; test will time out instead of hanging
- t.Fatalf("expected connector to start; runs=%d", conn.Runs())
- }
-
- cancel()
- if hub.WaitWithTimeout(50 * time.Millisecond) {
- t.Fatalf("WaitWithTimeout returned true while release was still blocked")
- }
-
- // Unblock the release so the supervisor can finally exit and the
- // test doesn't leak a goroutine.
- close(q.releaseBlock)
- hub.Wait()
-}
-
-// TestHubConfigDefaultsCoverShutdownKnobs documents that callers
-// that omit the new shutdown knobs still get sensible defaults
-// (matching the behavior router.go relies on by passing HubConfig{}).
-// If the defaults regress to zero, releaseLease would derive a
-// 0-deadline ctx that fails instantly — the real symptom would be
-// "release lease failed: context deadline exceeded" warnings on
-// every shutdown.
-func TestHubConfigDefaultsCoverShutdownKnobs(t *testing.T) {
- c := HubConfig{}.withDefaults()
- if c.LeaseReleaseTimeout <= 0 {
- t.Fatalf("LeaseReleaseTimeout default must be > 0; got %s", c.LeaseReleaseTimeout)
- }
- if c.ShutdownTimeout <= 0 {
- t.Fatalf("ShutdownTimeout default must be > 0; got %s", c.ShutdownTimeout)
- }
-}
-
-// waitFor polls cond until it returns true or the deadline is reached.
-// Returns true on success. Tests use this instead of time.Sleep so they
-// remain robust on slow CI runners without slowing fast ones down.
-func waitFor(timeout time.Duration, cond func() bool) bool {
- deadline := time.Now().Add(timeout)
- for time.Now().Before(deadline) {
- if cond() {
- return true
- }
- time.Sleep(time.Millisecond)
- }
- return cond()
-}
-
-// slowReplier blocks Reply for the configured duration unless the ctx
-// fires first. Used to prove the Hub's reply-off-critical-path
-// invariant: a Reply that exceeds ReplyTimeout MUST get its ctx
-// cancelled instead of running unbounded.
-type slowReplier struct {
- delay time.Duration
- startCh chan struct{}
- finishCh chan struct{}
- mu sync.Mutex
- callCount int
- lastCtxErr error // ctx.Err() observed when Reply returned
-}
-
-func newSlowReplier(delay time.Duration) *slowReplier {
- return &slowReplier{
- delay: delay,
- startCh: make(chan struct{}, 16),
- finishCh: make(chan struct{}, 16),
- }
-}
-
-func (s *slowReplier) Reply(ctx context.Context, _ Installation, _ InboundMessage, _ DispatchResult) {
- s.mu.Lock()
- s.callCount++
- s.mu.Unlock()
- select {
- case s.startCh <- struct{}{}:
- default:
- }
- select {
- case <-time.After(s.delay):
- case <-ctx.Done():
- }
- s.mu.Lock()
- s.lastCtxErr = ctx.Err()
- s.mu.Unlock()
- select {
- case s.finishCh <- struct{}{}:
- default:
- }
-}
-
-func (s *slowReplier) calls() int {
- s.mu.Lock()
- defer s.mu.Unlock()
- return s.callCount
-}
-
-func (s *slowReplier) ctxErr() error {
- s.mu.Lock()
- defer s.mu.Unlock()
- return s.lastCtxErr
-}
-
-// TestHubScheduleReplyReturnsImmediately verifies the core invariant
-// behind the OutcomeReplier refactor: a slow replier MUST NOT block
-// the dispatch caller. handleEvent is on the ACK critical path — the
-// connector ACKs as soon as it returns — so coupling it to outbound
-// Lark HTTP would let any slow card-send stall ACK past Lark's 3s
-// deadline. This test puts a 10s sleep in the replier and asserts the
-// scheduling call still returns in < 50ms.
-func TestHubScheduleReplyReturnsImmediately(t *testing.T) {
- t.Parallel()
- rep := newSlowReplier(10 * time.Second)
- hub := NewHub(nil, nil, nil, HubConfig{
- ReplyTimeout: 100 * time.Millisecond,
- Logger: newDiscardLogger(),
- })
- hub.SetOutcomeReplier(rep)
-
- start := time.Now()
- hub.scheduleReply(Installation{}, InboundMessage{EventID: "e1"},
- DispatchResult{Outcome: OutcomeNeedsBinding}, newDiscardLogger())
- elapsed := time.Since(start)
-
- if elapsed > 50*time.Millisecond {
- t.Fatalf("scheduleReply took %s; ACK critical path would be blocked by outbound HTTP", elapsed)
- }
-
- // The replier should still be in flight — proves it really did
- // detach into a goroutine.
- select {
- case <-rep.startCh:
- // good — Reply was invoked async
- case <-time.After(500 * time.Millisecond):
- t.Fatal("detached replier never ran")
- }
-
- // Drain the timeout-bounded reply so the test doesn't leak goroutines.
- if !hub.WaitWithTimeout(1 * time.Second) {
- t.Fatal("reply goroutine did not exit after ReplyTimeout fired")
- }
-
- if !errors.Is(rep.ctxErr(), context.DeadlineExceeded) {
- t.Fatalf("replier ctx.Err() = %v; want DeadlineExceeded", rep.ctxErr())
- }
-}
-
-// TestHubReplyTimeoutCancelsHungReplier pins the bound on the detached
-// reply: a replier that ignores ctx (or its outbound HTTP that hasn't
-// noticed yet) MUST be cancelled at ReplyTimeout. The test gives the
-// replier a deliberately long sleep and a short timeout, then asserts
-// the reply goroutine exits within roughly the timeout — not the sleep.
-func TestHubReplyTimeoutCancelsHungReplier(t *testing.T) {
- t.Parallel()
- timeout := 80 * time.Millisecond
- rep := newSlowReplier(10 * time.Second)
- hub := NewHub(nil, nil, nil, HubConfig{
- ReplyTimeout: timeout,
- Logger: newDiscardLogger(),
- })
- hub.SetOutcomeReplier(rep)
-
- start := time.Now()
- hub.scheduleReply(Installation{}, InboundMessage{EventID: "e2"},
- DispatchResult{Outcome: OutcomeAgentOffline}, newDiscardLogger())
-
- select {
- case <-rep.finishCh:
- case <-time.After(1 * time.Second):
- t.Fatal("replier never exited; ReplyTimeout did not fire")
- }
- elapsed := time.Since(start)
-
- // Sanity bound: shutdown must complete in roughly timeout + jitter.
- if elapsed > 500*time.Millisecond {
- t.Fatalf("replier exit took %s; expected ≈ %s", elapsed, timeout)
- }
- if !errors.Is(rep.ctxErr(), context.DeadlineExceeded) {
- t.Fatalf("replier should observe DeadlineExceeded; got %v", rep.ctxErr())
- }
- hub.Wait()
-}
-
-// TestHubWaitDrainsInFlightReplies verifies that Hub.Wait (and
-// WaitWithTimeout) joins on the replier goroutines, not just the
-// supervisor goroutines. Without this, shutdown could close the
-// process while a binding-card send is still in flight — the user
-// gets no card, no log entry, and the binding token they were going
-// to receive is orphaned with no observability.
-func TestHubWaitDrainsInFlightReplies(t *testing.T) {
- t.Parallel()
- rep := newSlowReplier(30 * time.Millisecond) // shorter than ReplyTimeout
- hub := NewHub(nil, nil, nil, HubConfig{
- ReplyTimeout: 1 * time.Second,
- Logger: newDiscardLogger(),
- })
- hub.SetOutcomeReplier(rep)
-
- hub.scheduleReply(Installation{}, InboundMessage{EventID: "e3"},
- DispatchResult{Outcome: OutcomeNeedsBinding}, newDiscardLogger())
-
- // Wait should block until the reply finishes its 30ms work.
- start := time.Now()
- hub.Wait()
- elapsed := time.Since(start)
-
- if elapsed < 20*time.Millisecond {
- t.Fatalf("Wait returned in %s; should have blocked until reply completed", elapsed)
- }
- if rep.calls() != 1 {
- t.Fatalf("reply call count = %d; want 1", rep.calls())
- }
- // Reply finished naturally (sleep returned), not via cancellation.
- if rep.ctxErr() != nil {
- t.Errorf("reply ctxErr = %v; want nil (slept normally)", rep.ctxErr())
- }
-}
-
-// TestHubNoopReplierInlineNoGoroutine verifies the optimisation: the
-// noop replier (used when outbound APIClient isn't configured) runs
-// inline, not under a goroutine. This avoids the cost of a goroutine
-// per inbound event on a deployment that hasn't wired outbound replies
-// yet. Indirectly proven by observing replyWg is not bumped (Wait
-// returns immediately without any reply goroutine to drain).
-func TestHubNoopReplierInlineNoGoroutine(t *testing.T) {
- t.Parallel()
- hub := NewHub(nil, nil, nil, HubConfig{
- Logger: newDiscardLogger(),
- })
- // hub.replier defaults to noop. Call scheduleReply many times — if
- // it spawned goroutines, Wait would wait at least until those
- // goroutines schedule, but with the fast-path it must return
- // instantly.
- for i := 0; i < 1000; i++ {
- hub.scheduleReply(Installation{}, InboundMessage{EventID: "e"},
- DispatchResult{Outcome: OutcomeNeedsBinding}, newDiscardLogger())
- }
- done := make(chan struct{})
- go func() { hub.Wait(); close(done) }()
- select {
- case <-done:
- case <-time.After(100 * time.Millisecond):
- t.Fatal("Wait should return immediately when no goroutine replies were scheduled")
- }
-}
-
-// TestHubReplyTimeoutDefaultIsUnder3s pins the value the production
-// path uses — Lark requires ACK within 3 seconds, and the replier
-// runs ON TOP of the dispatch latency, so it must complete strictly
-// under 3s even if dispatch took 500ms. Defaulting to 2.5s leaves
-// headroom both for outbound HTTP and for shutdown to drain replies
-// without hitting the broader ShutdownTimeout.
-func TestHubReplyTimeoutDefaultIsUnder3s(t *testing.T) {
- t.Parallel()
- c := HubConfig{}.withDefaults()
- if c.ReplyTimeout <= 0 {
- t.Fatalf("ReplyTimeout default must be > 0; got %s", c.ReplyTimeout)
- }
- if c.ReplyTimeout >= 3*time.Second {
- t.Fatalf("ReplyTimeout default %s is too close to Lark's 3s ACK deadline; outbound HTTP would race ACK", c.ReplyTimeout)
- }
-}
-
-// TestHubACKNotBlockedByOutboundReply proves the full integrated
-// invariant: even when the OutcomeReplier hangs for far longer than
-// the Lark ACK deadline, the connector's data-frame ACK still lands
-// on the wire promptly. This is the end-to-end version of the unit
-// test above, exercising connector -> Hub.handleEvent -> scheduleReply
-// against a fakeWSConn so we can observe the actual binary ACK frame
-// timing.
-//
-// Construct a dispatcher manually that returns OutcomeNeedsBinding
-// (the outcome most prone to expensive outbound work — token mint +
-// card send). Wire a slowReplier that sleeps 5s. Push one event.
-// Assert: an ACK frame appears in conn.writes within 500ms (well
-// under Lark's 3s budget).
-func TestHubACKNotBlockedByOutboundReply(t *testing.T) {
- t.Parallel()
-
- conn := newFakeWSConn()
- decoder := FrameDecoderFunc(func(payload []byte, _ Installation) (InboundMessage, bool, error) {
- return InboundMessage{EventID: string(payload)}, true, nil
- })
- c := quietConnector(t, conn, decoder, time.Hour) // disable ping
-
- // Slow replier that would block ACK if the critical path coupling
- // regressed. 5s sleep, ReplyTimeout 2.5s — replier must be
- // cancelled at ~2.5s and the ACK must NOT have waited for it.
- rep := newSlowReplier(5 * time.Second)
- hub := NewHub(nil, nil, nil, HubConfig{
- ReplyTimeout: 2500 * time.Millisecond,
- Logger: newDiscardLogger(),
- })
- hub.SetOutcomeReplier(rep)
-
- emit := func(ctx context.Context, msg InboundMessage) (DispatchResult, error) {
- // Simulate the dispatcher's "successful binding-needed" verdict
- // without standing up the full Dispatcher (concrete struct +
- // service deps). The async reply is the only behaviour under
- // test here, and scheduleReply is what the real handleEvent
- // hands to the replier.
- res := DispatchResult{
- Outcome: OutcomeNeedsBinding,
- SenderOpenID: "ou_user_42",
- }
- hub.scheduleReply(Installation{}, msg, res, newDiscardLogger())
- return res, nil
- }
-
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- done := make(chan error, 1)
- go func() {
- done <- c.Run(ctx, Installation{AppID: "test_app"}, emit)
- }()
-
- start := time.Now()
- pushDataFrame(conn, []byte("evt-binding"), "om-binding")
-
- // The data-frame ACK MUST appear well under Lark's 3s budget.
- if !waitFor(500*time.Millisecond, func() bool {
- for _, w := range conn.snapshot() {
- f, err := UnmarshalFrame(w)
- if err != nil {
- continue
- }
- if f.Method == FrameMethodData && bytes.Contains(f.Payload, []byte(`"code":200`)) {
- return true
- }
- }
- return false
- }) {
- t.Fatalf("data-frame ACK did not land within 500ms; outbound reply blocked the critical path (replier still running? %v)", rep.calls() == 1)
- }
- ackLatency := time.Since(start)
- if ackLatency >= 3*time.Second {
- t.Fatalf("ACK landed in %s, past Lark's 3s deadline", ackLatency)
- }
-
- // Verify the replier was indeed launched (proves we didn't accidentally
- // short-circuit it).
- select {
- case <-rep.startCh:
- case <-time.After(200 * time.Millisecond):
- t.Fatal("replier never ran; the reply path is silently broken")
- }
-
- cancel()
- <-done
- hub.WaitWithTimeout(5 * time.Second)
-}
diff --git a/server/internal/integrations/lark/ids.go b/server/internal/integrations/lark/ids.go
new file mode 100644
index 0000000000..c952c1e265
--- /dev/null
+++ b/server/internal/integrations/lark/ids.go
@@ -0,0 +1,12 @@
+package lark
+
+import (
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// uuidString renders a pgtype.UUID as its canonical string form. Shared by
+// the package's logging and map-keying sites. (Formerly defined on hub.go,
+// which the channel-engine cutover removed.)
+func uuidString(u pgtype.UUID) string { return util.UUIDToString(u) }
diff --git a/server/internal/integrations/lark/outcome_replier_test.go b/server/internal/integrations/lark/outcome_replier_test.go
index 4737a788e6..e345397e7f 100644
--- a/server/internal/integrations/lark/outcome_replier_test.go
+++ b/server/internal/integrations/lark/outcome_replier_test.go
@@ -287,18 +287,10 @@ func TestLarkOutcomeReplierOfflineSwallowsAPIError(t *testing.T) {
rep.Reply(context.Background(), Installation{}, InboundMessage{ChatID: "oc"}, DispatchResult{Outcome: OutcomeAgentOffline})
}
-// TestNoopReplierIsHandledByHub verifies that NewHub installs a noop
-// replier by default — so the inbound pipeline runs even when the
-// caller never calls SetOutcomeReplier (e.g. in deployments that
-// only run the inbound dispatcher pre-outbound-wiring). This guards
-// the "no nil replier crash" contract on hub.handleEvent.
-func TestNoopReplierIsHandledByHub(t *testing.T) {
- t.Parallel()
- hub := NewHub(nil, nil, nil, HubConfig{})
- if hub.replier == nil {
- t.Fatal("Hub.replier must default to noop, not nil")
- }
-}
+// The legacy "install a noop replier by default" safety is now split: the
+// engine Router skips reply scheduling entirely when no OutboundReplier is
+// registered (boot registers one only when larkClient.IsConfigured()), and
+// NewLarkOutcomeReplier still falls back to its own noop when unconfigured.
// TestLarkOutcomeReplierIssueCreatedSendsConfirmation pins the
// recovered /issue confirmation path. Before the plain-text refactor
diff --git a/server/internal/integrations/lark/pending_batcher.go b/server/internal/integrations/lark/pending_batcher.go
deleted file mode 100644
index 196d38b6ee..0000000000
--- a/server/internal/integrations/lark/pending_batcher.go
+++ /dev/null
@@ -1,176 +0,0 @@
-package lark
-
-import (
- "sync"
- "time"
-)
-
-// DefaultChatRunBatchWindow is the silence window the inbound debouncer
-// waits before triggering an agent run for a chat session. Owner-aligned
-// at 3s on MUL-2968: long enough to absorb a "forward a transcript, then
-// type a note" burst into one run, short enough that the bot's first
-// reply is not perceptibly late.
-const DefaultChatRunBatchWindow = 3 * time.Second
-
-// stoppableTimer is the slice of *time.Timer the batcher depends on.
-// Pinned to an interface so unit tests inject a manually-fired fake
-// instead of sleeping real wall-clock seconds. *time.Timer satisfies it
-// directly (Stop() bool).
-type stoppableTimer interface {
- Stop() bool
-}
-
-// pendingBatcher debounces the per-chat_session run trigger. Each inbound
-// Lark message that lands in a session calls Schedule, which (re)arms a
-// single timer for that session; when the session goes quiet for the
-// configured window the latest-registered flush runs exactly once. This
-// collapses a burst of messages into ONE agent run instead of one run per
-// message — safe because the chat task reads the WHOLE session history at
-// run time, so the individually-persisted messages are all visible to the
-// single run. Only the run TRIGGER is debounced; the chat_message rows,
-// per-message dedup, and frame ACK already happened synchronously upstream.
-//
-// State is in-process only, keyed by chat_session_id (a globally-unique
-// UUID, so no installation qualifier is needed). The WS lease guarantees a
-// single active owner per installation, so a session is only ever debounced
-// by one process. A hard crash inside the window drops the pending trigger
-// (the messages are already durable in chat_session; they simply do not
-// fire a run until the next message arrives) — an accepted low-frequency
-// boundary per MUL-2968 decision 5. Graceful shutdown calls FlushAll so
-// that boundary is not hit on a normal restart.
-//
-// The batcher is goroutine-safe: a single instance is shared across all
-// supervisor goroutines.
-type pendingBatcher struct {
- window time.Duration
-
- // afterFunc builds a timer that invokes fn after d. Defaults to
- // time.AfterFunc; tests substitute a fake so flushes are deterministic.
- afterFunc func(d time.Duration, fn func()) stoppableTimer
-
- mu sync.Mutex
- pending map[string]*pendingEntry
- // seq mints a monotonic generation per (re)schedule. onFire carries
- // the generation it was armed with and bails if a newer schedule has
- // superseded it — this fences the classic AfterFunc race where a timer
- // fires concurrently with the Stop() that was meant to cancel it.
- seq uint64
- stopped bool
- // inflight tracks flush callbacks that are currently executing (timer
- // already fired) so FlushAll can join them before a graceful shutdown
- // proceeds.
- inflight sync.WaitGroup
-}
-
-type pendingEntry struct {
- timer stoppableTimer
- flush func()
- gen uint64
-}
-
-// newPendingBatcher returns a batcher with the given silence window. A
-// non-positive window falls back to DefaultChatRunBatchWindow.
-func newPendingBatcher(window time.Duration) *pendingBatcher {
- if window <= 0 {
- window = DefaultChatRunBatchWindow
- }
- return &pendingBatcher{
- window: window,
- afterFunc: realAfterFunc,
- pending: make(map[string]*pendingEntry),
- }
-}
-
-// realAfterFunc adapts time.AfterFunc to the stoppableTimer seam.
-func realAfterFunc(d time.Duration, fn func()) stoppableTimer {
- return time.AfterFunc(d, fn)
-}
-
-// Schedule (re)arms the silence window for key. The most recent flush wins:
-// only session-level information is needed to fire a run, so keeping the
-// latest closure (which captures the latest installation/message context
-// for the offline/archived notice) is sufficient. Calling Schedule after
-// FlushAll runs the flush inline best-effort rather than silently dropping
-// it; this only happens on the shutdown race where a message arrives after
-// the drain has begun.
-func (b *pendingBatcher) Schedule(key string, flush func()) {
- b.mu.Lock()
- if b.stopped {
- b.mu.Unlock()
- flush()
- return
- }
- b.seq++
- gen := b.seq
- fire := func() { b.onFire(key, gen) }
- if e, ok := b.pending[key]; ok {
- // Reset the window: cancel the prior timer and arm a fresh one.
- // The gen bump means a stale fire from the cancelled timer is a
- // no-op even if Stop loses the race.
- e.timer.Stop()
- e.flush = flush
- e.gen = gen
- e.timer = b.afterFunc(b.window, fire)
- b.mu.Unlock()
- return
- }
- b.pending[key] = &pendingEntry{
- flush: flush,
- gen: gen,
- timer: b.afterFunc(b.window, fire),
- }
- b.mu.Unlock()
-}
-
-// onFire runs the flush for key if it is still the live, armed generation.
-// It is the timer callback; in production it runs on time.AfterFunc's own
-// goroutine, so the flush is naturally detached from the inbound path.
-func (b *pendingBatcher) onFire(key string, gen uint64) {
- b.mu.Lock()
- e, ok := b.pending[key]
- if !ok || b.stopped || e.gen != gen {
- // Superseded by a newer Schedule, already flushed, or draining via
- // FlushAll (which owns this entry now). Do nothing.
- b.mu.Unlock()
- return
- }
- delete(b.pending, key)
- flush := e.flush
- b.inflight.Add(1)
- b.mu.Unlock()
-
- defer b.inflight.Done()
- flush()
-}
-
-// FlushAll stops the batcher and runs every still-pending flush exactly
-// once, then waits for any concurrently-firing flushes to finish. Intended
-// to be called once from the graceful-shutdown path AFTER inbound delivery
-// has stopped, so a normal restart does not drop a window's worth of
-// triggers. After FlushAll the batcher is terminal: later Schedule calls
-// run inline.
-func (b *pendingBatcher) FlushAll() {
- b.mu.Lock()
- b.stopped = true
- entries := make([]*pendingEntry, 0, len(b.pending))
- for _, e := range b.pending {
- e.timer.Stop()
- entries = append(entries, e)
- }
- b.pending = make(map[string]*pendingEntry)
- b.mu.Unlock()
-
- for _, e := range entries {
- e.flush()
- }
- // Join flushes whose timer had already fired before we set stopped.
- b.inflight.Wait()
-}
-
-// pendingCount reports how many sessions currently have an armed window.
-// Used by tests and useful for ops visibility.
-func (b *pendingBatcher) pendingCount() int {
- b.mu.Lock()
- defer b.mu.Unlock()
- return len(b.pending)
-}
diff --git a/server/internal/integrations/lark/testhelpers_test.go b/server/internal/integrations/lark/testhelpers_test.go
new file mode 100644
index 0000000000..03719769ca
--- /dev/null
+++ b/server/internal/integrations/lark/testhelpers_test.go
@@ -0,0 +1,26 @@
+package lark
+
+import (
+ "io"
+ "log/slog"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+// Shared unit-test helpers for the lark package. (Formerly defined on
+// hub_test.go, which the channel-engine cutover removed; relocated here so
+// the surviving connector / outbound / runtime tests keep using them.)
+
+func uuidFromString(t *testing.T, s string) pgtype.UUID {
+ t.Helper()
+ var u pgtype.UUID
+ if err := u.Scan(s); err != nil {
+ t.Fatalf("scan uuid %q: %v", s, err)
+ }
+ return u
+}
+
+func newDiscardLogger() *slog.Logger {
+ return slog.New(slog.NewTextHandler(io.Discard, nil))
+}
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index 334d9d301c..7f6f4634e3 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -654,6 +654,56 @@ func (q *Queries) ListActiveChannelInstallations(ctx context.Context, channelTyp
return items, nil
}
+const listAllActiveChannelInstallations = `-- name: ListAllActiveChannelInstallations :many
+SELECT ci.id, ci.workspace_id, ci.agent_id, ci.channel_type, ci.config, ci.status, ci.ws_lease_token, ci.ws_lease_expires_at, ci.installer_user_id, ci.installed_at, ci.created_at, ci.updated_at FROM channel_installation ci
+JOIN workspace w ON w.id = ci.workspace_id
+JOIN agent a ON a.id = ci.agent_id
+WHERE ci.status = 'active'
+ORDER BY ci.created_at ASC
+`
+
+// Boot path for the channel-agnostic engine Supervisor (MUL-3620): every
+// active installation across ALL channel types, so one Supervisor drives every
+// platform's connections rather than a per-platform hub. This is the de-
+// hardcoded counterpart of ListActiveChannelInstallations — the Supervisor
+// routes each row to its registered channel.Factory by channel_type, so it
+// never needs to know which platforms exist. Same orphan guard as the per-type
+// query: the workspace + agent JOINs drop installations whose owning rows are
+// gone (channel_installation has no FK, MUL-3515 §4), matching the old ON
+// DELETE CASCADE semantics (row existence, not agent archival).
+func (q *Queries) ListAllActiveChannelInstallations(ctx context.Context) ([]ChannelInstallation, error) {
+ rows, err := q.db.Query(ctx, listAllActiveChannelInstallations)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ChannelInstallation{}
+ for rows.Next() {
+ var i ChannelInstallation
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.ChannelType,
+ &i.Config,
+ &i.Status,
+ &i.WsLeaseToken,
+ &i.WsLeaseExpiresAt,
+ &i.InstallerUserID,
+ &i.InstalledAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listChannelInboundAuditByInstallation = `-- name: ListChannelInboundAuditByInstallation :many
SELECT id, installation_id, channel_type, channel_chat_id, event_type, channel_event_id, channel_message_id, drop_reason, received_at FROM channel_inbound_audit
WHERE installation_id = $1
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index ecc8bdf1e8..5865d09746 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -91,6 +91,22 @@ WHERE ci.status = 'active'
AND ci.channel_type = sqlc.arg('channel_type')
ORDER BY ci.created_at ASC;
+-- name: ListAllActiveChannelInstallations :many
+-- Boot path for the channel-agnostic engine Supervisor (MUL-3620): every
+-- active installation across ALL channel types, so one Supervisor drives every
+-- platform's connections rather than a per-platform hub. This is the de-
+-- hardcoded counterpart of ListActiveChannelInstallations — the Supervisor
+-- routes each row to its registered channel.Factory by channel_type, so it
+-- never needs to know which platforms exist. Same orphan guard as the per-type
+-- query: the workspace + agent JOINs drop installations whose owning rows are
+-- gone (channel_installation has no FK, MUL-3515 §4), matching the old ON
+-- DELETE CASCADE semantics (row existence, not agent archival).
+SELECT ci.* FROM channel_installation ci
+JOIN workspace w ON w.id = ci.workspace_id
+JOIN agent a ON a.id = ci.agent_id
+WHERE ci.status = 'active'
+ORDER BY ci.created_at ASC;
+
-- name: SetChannelInstallationStatus :exec
UPDATE channel_installation
SET status = $2, updated_at = now()