Skip to content

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

Go

MUL-7450 fix(lark): surface the event-delivery check a silent Bot needs (#8735)

Bohan Jiang9b8da372cc57
diff --git a/apps/docs/content/docs/lark-bot-integration.ja.mdx b/apps/docs/content/docs/lark-bot-integration.ja.mdx
index 47f4f50778..74e54a4416 100644
--- a/apps/docs/content/docs/lark-bot-integration.ja.mdx
+++ b/apps/docs/content/docs/lark-bot-integration.ja.mdx
@@ -85,6 +85,7 @@ API サービスを再起動した後、エージェントの**連携**ページ
- **QR コードの期限が切れた**: ダイアログを閉じて、接続をもう一度開始します。
- **Bot からアカウント連携を求められる**: 連携用リンクを開き、そのワークスペースで使う Multica アカウントにログインします。
- **Bot が実行しない**: エージェントがアーカイブされていないことと、使用する[ランタイム](/daemon-runtimes)がオンラインであることを確認します。
+- **Bot がまったく応答しない**: アプリは長時間接続でイベントを送信する必要があります。Multica に webhook の受信 URL はありません。Feishu/Lark の開発者コンソールで **イベントとコールバック → イベント設定** を開き、購読方法がリクエスト URL ではなく長時間接続になっていること、`im.message.receive_v1` が購読されていること、その設定を含むバージョンが公開済み(テナントで審査が必要な場合は承認済み)であることを確認します。リクエスト URL に設定されたアプリも接続自体は成功し「接続済み」と表示されますが、メッセージは 1 件も届きません。
## 次のステップ
diff --git a/apps/docs/content/docs/lark-bot-integration.ko.mdx b/apps/docs/content/docs/lark-bot-integration.ko.mdx
index 3dbd7941b1..b0428e9440 100644
--- a/apps/docs/content/docs/lark-bot-integration.ko.mdx
+++ b/apps/docs/content/docs/lark-bot-integration.ko.mdx
@@ -85,6 +85,7 @@ API 서비스를 다시 시작한 뒤 에이전트의 **연동** 페이지에서
- **QR 코드 만료**: 팝업을 닫고 연결을 다시 시작합니다.
- **Bot이 계정 연결을 요구함**: 연결 링크를 열고 해당 워크스페이스의 Multica 계정으로 로그인합니다.
- **Bot이 실행되지 않음**: 에이전트가 보관 처리되었는지, 사용하는 [런타임](/daemon-runtimes)이 온라인인지 확인합니다.
+- **Bot이 전혀 응답하지 않음**: 앱은 롱 커넥션으로 이벤트를 보내야 하며, Multica에는 webhook 수신 주소가 없습니다. Feishu/Lark 개발자 콘솔에서 **이벤트 및 콜백 → 이벤트 설정**을 열어 구독 방식이 요청 URL이 아닌 롱 커넥션인지, `im.message.receive_v1`이 구독되어 있는지, 해당 설정이 포함된 버전이 게시(테넌트 심사가 필요한 경우 승인)되었는지 확인합니다. 요청 URL로 설정된 앱도 연결은 성공하고 '연결됨'으로 표시되지만 메시지는 한 건도 도착하지 않습니다.
## 다음 단계
diff --git a/apps/docs/content/docs/lark-bot-integration.mdx b/apps/docs/content/docs/lark-bot-integration.mdx
index 9cec12dd70..6d06e35ea9 100644
--- a/apps/docs/content/docs/lark-bot-integration.mdx
+++ b/apps/docs/content/docs/lark-bot-integration.mdx
@@ -86,6 +86,7 @@ Restart the API server, then connect the Bot from the agent's **Integrations** p
- **QR code expired**: close the dialog and start the connection again.
- **The Bot asks for account binding**: open the binding link and sign in with the Multica account for that workspace.
- **The Bot doesn't run**: check whether the agent is archived and whether the [runtime](/daemon-runtimes) it uses is online.
+- **The Bot never replies at all**: the app must push events over a long connection — Multica has no webhook endpoint. In the Feishu/Lark developer console, open **Events & Callbacks → Event Configuration** and confirm that the subscription method is the long connection rather than a request URL, that `im.message.receive_v1` is subscribed, and that the app version carrying that configuration is published (and approved, where the tenant reviews releases). An app set to a request URL still binds, still shows Connected, and silently receives nothing.
## Next steps
diff --git a/apps/docs/content/docs/lark-bot-integration.zh.mdx b/apps/docs/content/docs/lark-bot-integration.zh.mdx
index fee912dc97..01fd3ccc5c 100644
--- a/apps/docs/content/docs/lark-bot-integration.zh.mdx
+++ b/apps/docs/content/docs/lark-bot-integration.zh.mdx
@@ -86,6 +86,7 @@ openssl rand -base64 32
- **二维码失效**:关闭弹窗后重新发起连接。
- **Bot 要求绑定账号**:打开绑定链接并使用该工作区的 Multica 账号登录。
- **Bot 不执行**:检查智能体是否已归档,以及它使用的[运行时](/daemon-runtimes)是否在线。
+- **Bot 完全不回复**:应用必须通过长连接推送事件,Multica 没有 webhook 接收地址。打开飞书开发者后台的 **事件与回调 → 事件配置**,确认订阅方式是使用长连接接收事件而不是请求地址,`im.message.receive_v1` 已订阅,并且包含该配置的版本已发布(企业需要审核时还要通过审核)。配成请求地址的应用照样能绑定、照样显示「已连接」,但一条消息都收不到。
## 接下来
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index ac1fadb86f..fac029e638 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -872,6 +872,8 @@
"agent_bot_connected_label_lark": "Connected to Lark",
"agent_bot_manage_link_feishu": "Manage in Feishu",
"agent_bot_manage_link_lark": "Manage in Lark",
+ "agent_bot_silent_hint": "Bot connected but silent? Check that the app delivers events over the long connection.",
+ "agent_bot_silent_hint_link": "Troubleshooting",
"agent_bot_manage_tooltip_feishu": "Open this Bot's app page in Feishu — manage scopes, edit display name, request additional permissions.",
"agent_bot_manage_tooltip_lark": "Open this Bot's app page in Lark — manage scopes, edit display name, request additional permissions.",
"agent_bot_disconnect_tooltip": "Unbind this Lark Bot from the Agent. The Bot will stop receiving Lark messages.",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 2cf6199839..77e6ad6ba7 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -872,6 +872,8 @@
"agent_bot_connected_label_lark": "Connecté à Lark",
"agent_bot_manage_link_feishu": "Gérer dans Feishu",
"agent_bot_manage_link_lark": "Gérer dans Lark",
+ "agent_bot_silent_hint": "Bot connecté mais silencieux ? Vérifiez que l'application envoie les événements via la connexion longue.",
+ "agent_bot_silent_hint_link": "Dépannage",
"agent_bot_manage_tooltip_feishu": "Ouvrir la page d'application de ce bot dans Feishu — gérer les portées, modifier le nom affiché, demander des permissions supplémentaires.",
"agent_bot_manage_tooltip_lark": "Ouvrir la page d'application de ce bot dans Lark — gérer les portées, modifier le nom affiché, demander des permissions supplémentaires.",
"agent_bot_disconnect_tooltip": "Dissocier ce bot Lark de l'agent. Le bot cessera de recevoir les messages Lark.",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 7ac2174897..066d6374b4 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -870,6 +870,8 @@
"agent_bot_connected_label_lark": "Lark に接続済み",
"agent_bot_manage_link_feishu": "Feishu で管理",
"agent_bot_manage_link_lark": "Lark で管理",
+ "agent_bot_silent_hint": "接続済みなのに Bot が応答しない場合は、アプリのイベント購読方法が長時間接続になっているか確認してください。",
+ "agent_bot_silent_hint_link": "トラブルシューティング",
"agent_bot_manage_tooltip_feishu": "Feishu のデベロッパーコンソールでこのボットのアプリページを開き、スコープ管理 / 名称変更 / 追加権限の申請ができます。",
"agent_bot_manage_tooltip_lark": "Lark のデベロッパーコンソールでこのボットのアプリページを開き、スコープ管理 / 名称変更 / 追加権限の申請ができます。",
"agent_bot_disconnect_tooltip": "この Lark ボットとエージェントの連携を解除します。ボットは Lark メッセージの受信を停止します。",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 3f1f455fde..d23371d761 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1115,6 +1115,8 @@
"agent_bot_connected_label_lark": "Lark에 연결됨",
"agent_bot_manage_link_feishu": "Feishu에서 관리",
"agent_bot_manage_link_lark": "Lark에서 관리",
+ "agent_bot_silent_hint": "연결됐는데 Bot이 응답하지 않나요? 앱의 이벤트 구독 방식이 롱 커넥션인지 확인하세요.",
+ "agent_bot_silent_hint_link": "문제 해결",
"agent_bot_manage_tooltip_feishu": "Feishu 개발자 콘솔에서 이 봇의 앱 페이지를 열어 스코프 관리, 이름 변경, 추가 권한 신청을 할 수 있어요.",
"agent_bot_manage_tooltip_lark": "Lark 개발자 콘솔에서 이 봇의 앱 페이지를 열어 스코프 관리, 이름 변경, 추가 권한 신청을 할 수 있어요.",
"agent_bot_disconnect_tooltip": "이 Lark 봇과 에이전트 연결을 해제합니다. 봇은 Lark 메시지 수신을 중단합니다.",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 8fa86d7062..c15b139171 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -870,6 +870,8 @@
"agent_bot_connected_label_lark": "已连接到 Lark",
"agent_bot_manage_link_feishu": "在飞书中管理",
"agent_bot_manage_link_lark": "在 Lark 中管理",
+ "agent_bot_silent_hint": "Bot 已连接但不回复?确认应用的事件订阅方式是长连接。",
+ "agent_bot_silent_hint_link": "排查指南",
"agent_bot_manage_tooltip_feishu": "打开飞书开发者控制台中该 Bot 的应用页面——管理权限、修改名称、申请新的权限范围。",
"agent_bot_manage_tooltip_lark": "打开 Lark 开发者控制台中该 Bot 的应用页面——管理权限、修改名称、申请新的权限范围。",
"agent_bot_disconnect_tooltip": "将该飞书 Bot 与智能体解绑,Bot 将停止接收飞书消息。",
diff --git a/packages/views/settings/components/lark-tab.test.tsx b/packages/views/settings/components/lark-tab.test.tsx
index 9916dac311..1425582aff 100644
--- a/packages/views/settings/components/lark-tab.test.tsx
+++ b/packages/views/settings/components/lark-tab.test.tsx
@@ -484,6 +484,20 @@ describe("LarkAgentBotConnectedBadge (Unbind / Disconnect)", () => {
expect(screen.getByRole("link", { name: /Manage in Feishu/i })).toBeTruthy();
});
+ it("points a silent bot at the event-delivery check (#8496)", () => {
+ render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
+ wrapper: I18nWrapper,
+ });
+ // A bound app whose events go to a request URL renders this exact
+ // badge and receives nothing, so the connected state has to name the
+ // one setting that explains the silence.
+ expect(screen.getByText(/long connection/i)).toBeTruthy();
+ const docs = screen.getByRole("link", { name: /Troubleshooting/i });
+ expect(docs.getAttribute("href")).toBe(
+ "https://multica.ai/docs/lark-bot-integration",
+ );
+ });
+
it("opens the confirm dialog and does NOT call the API until the user confirms", async () => {
const user = userEvent.setup();
render(<LarkAgentBindButton agentId="agent-1" agentName="Bot" />, {
diff --git a/packages/views/settings/components/lark-tab.tsx b/packages/views/settings/components/lark-tab.tsx
index c0f873cbb6..9640e33490 100644
--- a/packages/views/settings/components/lark-tab.tsx
+++ b/packages/views/settings/components/lark-tab.tsx
@@ -507,6 +507,19 @@ function larkDevConsoleHost(region?: string): string {
: "https://open.feishu.cn";
}
+// larkDocsUrl points at the Lark/Feishu integration guide, localized the
+// same way as the Telegram and Slack docs links.
+function larkDocsUrl(lang: string | undefined): string {
+ const prefix = lang?.startsWith("zh")
+ ? "/zh"
+ : lang?.startsWith("ja")
+ ? "/ja"
+ : lang?.startsWith("ko")
+ ? "/ko"
+ : "";
+ return `https://multica.ai/docs${prefix}/lark-bot-integration`;
+}
+
function LarkAgentBotConnectedBadge({
installation,
className,
@@ -514,7 +527,7 @@ function LarkAgentBotConnectedBadge({
installation: LarkInstallation;
className?: string;
}) {
- const { t } = useT("settings");
+ const { t, i18n } = useT("settings");
const wsId = useWorkspaceId();
const qc = useQueryClient();
const manageHref = `${larkDevConsoleHost(installation.region)}/app/${encodeURIComponent(installation.app_id)}`;
@@ -604,6 +617,23 @@ function LarkAgentBotConnectedBadge({
: t(($) => $.lark.agent_bot_manage_link_feishu)}
</a>
+ {/* Row 3: the check a silent Bot almost always needs (#8496). An app
+ whose events go to a request URL instead of the long connection
+ binds fine and shows exactly this badge while receiving nothing,
+ and this row is where someone looks when the Bot stays quiet —
+ the install dialog closes itself a beat after success. */}
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.lark.agent_bot_silent_hint)}{" "}
+ <a
+ href={larkDocsUrl(i18n.language)}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-2 transition-colors hover:text-foreground"
+ >
+ {t(($) => $.lark.agent_bot_silent_hint_link)}
+ </a>
+ </p>
+
<AlertDialog
open={confirmOpen}
onOpenChange={(v) => {
diff --git a/server/internal/integrations/lark/ws_connector.go b/server/internal/integrations/lark/ws_connector.go
index 52367f2e8f..c38e77a694 100644
--- a/server/internal/integrations/lark/ws_connector.go
+++ b/server/internal/integrations/lark/ws_connector.go
@@ -254,6 +254,13 @@ func (c *WSLongConnConnector) Run(ctx context.Context, inst Installation, emit E
// an abandoned event.
assembler := newChunkAssembler(c.cfg.ChunkTTL, c.cfg.Now)
+ // Event types this session has already reported dropping. An app can
+ // subscribe to events we do not handle (reactions, membership churn)
+ // and a busy chat delivers them continuously, so the log reports each
+ // type once per connection rather than once per frame. Read-loop-local:
+ // no lock, and a reconnect re-reports.
+ reportedDrops := make(map[string]struct{})
+
// Ping loop: app-layer binary ping frames at the server's PingInterval.
pingDone := make(chan struct{})
go c.pingLoop(runCtx, conn, &writeMu, endpoint.ServiceID, pingInterval, log, pingDone)
@@ -374,6 +381,21 @@ func (c *WSLongConnConnector) Run(ctx context.Context, inst Installation, emit E
// Heartbeat / unhandled event type. ACK 200 so the server
// stops sending it; the decoder owns the "what we handle"
// policy.
+ //
+ // Name the event type once per connection (#8496). This
+ // path writes no audit row either, so an app delivering
+ // only event types we decline otherwise leaves no trace
+ // at all. It says what IS arriving, not that anything is
+ // missing: an app whose events go to a request URL
+ // instead of this socket produces no frames, so it
+ // produces no line here. Heartbeats peek as "" and stay
+ // silent.
+ if eventType := PeekEventType(payload); eventType != "" {
+ if _, reported := reportedDrops[eventType]; !reported {
+ reportedDrops[eventType] = struct{}{}
+ log.Info("lark ws connector: dropping unhandled event type", "event_type", eventType)
+ }
+ }
if werr := c.writeFrame(&writeMu, conn, NewAckFrame(frame, true)); werr != nil {
log.Warn("lark ws connector: ack-after-drop write failed", "err", werr.Error())
return fmt.Errorf("write ack: %w", werr)
diff --git a/server/internal/integrations/lark/ws_connector_test.go b/server/internal/integrations/lark/ws_connector_test.go
index 9b1b3b2050..44637a9f45 100644
--- a/server/internal/integrations/lark/ws_connector_test.go
+++ b/server/internal/integrations/lark/ws_connector_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
+ "fmt"
"io"
"log/slog"
"net/http"
@@ -108,10 +109,36 @@ func (d *fakeWSDialer) DialContext(ctx context.Context, urlStr string, h http.He
return d.conn, nil, nil
}
+// syncBuffer is a mutex-guarded io.Writer, so a slog handler written
+// from the connector goroutine can be read from the test goroutine.
+type syncBuffer struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+}
+
+func (b *syncBuffer) Write(p []byte) (int, error) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.Write(p)
+}
+
+func (b *syncBuffer) String() string {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.buf.String()
+}
+
// quietConnector wires a connector with a deterministic decoder + the
// fakeWSConn. Caller controls the decoder so each test can assert
// per-payload behaviour.
func quietConnector(t *testing.T, conn *fakeWSConn, decoder FrameDecoder, pingInterval time.Duration) *WSLongConnConnector {
+ t.Helper()
+ return connectorWithLogger(t, conn, decoder, pingInterval, slog.New(slog.NewTextHandler(io.Discard, nil)))
+}
+
+// connectorWithLogger is quietConnector with the logger left to the
+// caller, for the tests that assert on what the connector logs.
+func connectorWithLogger(t *testing.T, conn *fakeWSConn, decoder FrameDecoder, pingInterval time.Duration, logger *slog.Logger) *WSLongConnConnector {
t.Helper()
c, err := NewWSLongConnConnector(WSConnectorConfig{
Dialer: &fakeWSDialer{conn: conn},
@@ -125,7 +152,7 @@ func quietConnector(t *testing.T, conn *fakeWSConn, decoder FrameDecoder, pingIn
PingInterval: pingInterval,
ReadDeadline: time.Second,
WriteTimeout: time.Second,
- Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ Logger: logger,
})
if err != nil {
t.Fatalf("NewWSLongConnConnector: %v", err)
@@ -459,6 +486,71 @@ func TestWSConnectorDecoderErrorAcksAndContinues(t *testing.T) {
<-done
}
+// TestWSConnectorLogsDroppedEventTypeOncePerType covers #8496: an app can
+// subscribe to event types we do not handle, and that path writes neither a
+// log line nor a DB row, so the socket leaves no trace of what it receives.
+// The type is named once per connection — a busy chat delivers reactions and
+// membership churn continuously, and one line per frame would be unbounded.
+// Heartbeats carry no event type and stay silent.
+func TestWSConnectorLogsDroppedEventTypeOncePerType(t *testing.T) {
+ t.Parallel()
+ conn := newFakeWSConn()
+ logs := &syncBuffer{}
+ decoder := FrameDecoderFunc(func([]byte, Installation) (InboundMessage, bool, error) {
+ return InboundMessage{}, false, nil
+ })
+ c := connectorWithLogger(t, conn, decoder, time.Hour, slog.New(slog.NewTextHandler(logs, nil)))
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() {
+ done <- c.Run(ctx, Installation{AppID: "test_app"}, func(context.Context, InboundMessage) (DispatchResult, error) {
+ return DispatchResult{}, nil
+ })
+ }()
+
+ reaction := `{"schema":"2.0","header":{"event_type":"im.message.reaction.created_v1","event_id":"e%d"}}`
+ pushDataFrame(conn, []byte(fmt.Sprintf(reaction, 1)), "m1")
+ waitForWrites(t, conn, 1)
+ if got := logs.String(); !strings.Contains(got, "im.message.reaction.created_v1") {
+ t.Fatalf("dropped event type not logged; log was:\n%s", got)
+ }
+
+ // Same type again, plus a heartbeat: both ACKed, neither logged.
+ pushDataFrame(conn, []byte(fmt.Sprintf(reaction, 2)), "m2")
+ pushDataFrame(conn, []byte(`{}`), "m3")
+ waitForWrites(t, conn, 3)
+ if got := strings.Count(logs.String(), "dropping unhandled event type"); got != 1 {
+ t.Errorf("log lines after a repeat + a heartbeat = %d, want 1; log was:\n%s", got, logs.String())
+ }
+
+ // A type we have not reported yet is worth one line of its own.
+ pushDataFrame(conn, []byte(`{"schema":"2.0","header":{"event_type":"im.chat.access_event_v1","event_id":"e4"}}`), "m4")
+ waitForWrites(t, conn, 4)
+ if got := strings.Count(logs.String(), "dropping unhandled event type"); got != 2 {
+ t.Errorf("log lines after a second event type = %d, want 2; log was:\n%s", got, logs.String())
+ }
+
+ cancel()
+ <-done
+}
+
+// waitForWrites blocks until the connector has written n frames (each
+// processed frame is ACKed), so a test can assert on what handling that
+// frame did without racing the connector goroutine.
+func waitForWrites(t *testing.T, conn *fakeWSConn, n int) {
+ t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ if len(conn.snapshot()) >= n {
+ return
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ t.Fatalf("connector wrote %d frames, want %d", len(conn.snapshot()), n)
+}
+
func TestWSConnectorReadErrorReturnsToHub(t *testing.T) {
t.Parallel()
conn := newFakeWSConn()
diff --git a/server/internal/integrations/lark/ws_frame_decoder.go b/server/internal/integrations/lark/ws_frame_decoder.go
index 4c4578b55b..10148d3a23 100644
--- a/server/internal/integrations/lark/ws_frame_decoder.go
+++ b/server/internal/integrations/lark/ws_frame_decoder.go
@@ -33,6 +33,26 @@ type LarkJSONFrameDecoder struct{}
func NewLarkJSONFrameDecoder() *LarkJSONFrameDecoder { return &LarkJSONFrameDecoder{} }
+// PeekEventType reads header.event_type out of a data-frame payload for
+// logging only — the decoder's drop outcome does not say WHICH event it
+// declined, and a dropped frame writes no audit row either (that table is
+// only reached once a message enters the Router).
+//
+// Returns "" for anything that is not an event envelope: an empty or
+// malformed payload, or a heartbeat. Callers use that to keep the steady
+// stream of heartbeats out of the log while still reporting real events we
+// do not handle.
+func PeekEventType(payload []byte) string {
+ if len(payload) == 0 {
+ return ""
+ }
+ var env larkEventEnvelope
+ if err := json.Unmarshal(payload, &env); err != nil {
+ return ""
+ }
+ return env.Header.EventType
+}
+
// Decode implements FrameDecoder.
func (d *LarkJSONFrameDecoder) Decode(payload []byte, inst Installation) (InboundMessage, bool, error) {
if len(payload) == 0 {
diff --git a/server/internal/integrations/lark/ws_frame_decoder_test.go b/server/internal/integrations/lark/ws_frame_decoder_test.go
index da02c250c3..853280557c 100644
--- a/server/internal/integrations/lark/ws_frame_decoder_test.go
+++ b/server/internal/integrations/lark/ws_frame_decoder_test.go
@@ -613,3 +613,26 @@ func TestLarkJSONFrameDecoderNonThreadHasEmptyThreadID(t *testing.T) {
t.Errorf("ThreadID = %q want empty for non-thread message", msg.ThreadID)
}
}
+
+func TestPeekEventType(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ payload string
+ want string
+ }{
+ {"empty payload", "", ""},
+ {"malformed json", "not json", ""},
+ {"heartbeat", "{}", ""},
+ {"handled event", `{"schema":"2.0","header":{"event_type":"im.message.receive_v1"}}`, "im.message.receive_v1"},
+ {"unhandled event", `{"schema":"2.0","header":{"event_type":"im.chat.access_event_v1"}}`, "im.chat.access_event_v1"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ if got := PeekEventType([]byte(tc.payload)); got != tc.want {
+ t.Errorf("PeekEventType(%q) = %q, want %q", tc.payload, got, tc.want)
+ }
+ })
+ }
+}