feat: enhance IM integration with streaming support and documentation

- add StreamSender interface and streaming output for WeCom/Feishu
- refactor WeCom adapter into separate webhook and websocket files
- add output_mode config for stream/full toggle per platform
- add stream flush batching, dedup cleanup, and think-block filtering
- improve context template to handle irrelevant retrieved info gracefully
- add IM streaming integration tests
- add IM integration documentation with quick start guide
This commit is contained in:
nullkey
2026-03-15 20:42:50 +08:00
committed by lyingbug
parent 9fa969fb5c
commit f16aa12822
12 changed files with 1532 additions and 70 deletions
+4
View File
@@ -44,6 +44,8 @@ type WeComIMConfig struct {
KnowledgeBases []string `yaml:"knowledge_base_ids" json:"knowledge_base_ids"`
// Mode: "webhook" (default, requires public domain) or "websocket" (long connection via intelligent bot, no public domain needed)
Mode string `yaml:"mode" json:"mode"`
// OutputMode: "stream" (default, real-time streaming) or "full" (wait for complete answer then send)
OutputMode string `yaml:"output_mode" json:"output_mode"`
// --- Webhook mode fields (self-built app callback) ---
CorpID string `yaml:"corp_id" json:"corp_id"`
AgentSecret string `yaml:"agent_secret" json:"agent_secret"`
@@ -67,6 +69,8 @@ type FeishuIMConfig struct {
EncryptKey string `yaml:"encrypt_key" json:"encrypt_key"`
// Mode: "websocket" (default, long connection, no public domain needed) or "webhook" (requires public domain)
Mode string `yaml:"mode" json:"mode"`
// OutputMode: "stream" (default, real-time streaming) or "full" (wait for complete answer then send)
OutputMode string `yaml:"output_mode" json:"output_mode"`
}
// DocReaderConfig configures the document parser client (gRPC or HTTP).
+10 -2
View File
@@ -960,11 +960,19 @@ func registerIMAdapters(cfg *config.Config, imService *imPkg.Service) {
// Register WeCom
if cfg.IM.WeCom != nil && cfg.IM.WeCom.Enabled {
registerWeComAdapter(ctx, cfg.IM.WeCom, imService)
if cfg.IM.WeCom.OutputMode == "full" {
imService.SetStreamDisabled(imPkg.PlatformWeCom, true)
logger.Infof(ctx, "[IM] WeCom streaming disabled (output_mode=full)")
}
}
// Register Feishu
if cfg.IM.Feishu != nil && cfg.IM.Feishu.Enabled {
registerFeishuAdapter(ctx, cfg.IM.Feishu, imService)
if cfg.IM.Feishu.OutputMode == "full" {
imService.SetStreamDisabled(imPkg.PlatformFeishu, true)
logger.Infof(ctx, "[IM] Feishu streaming disabled (output_mode=full)")
}
}
}
@@ -976,7 +984,7 @@ func registerWeComAdapter(ctx context.Context, cfg *config.WeComIMConfig, imServ
switch mode {
case "webhook":
adapter, err := wecom.NewAdapter(
adapter, err := wecom.NewWebhookAdapter(
cfg.CorpID,
cfg.AgentSecret,
cfg.Token,
@@ -999,7 +1007,7 @@ func registerWeComAdapter(ctx context.Context, cfg *config.WeComIMConfig, imServ
client := wecom.NewLongConnClient(cfg.BotID, cfg.BotSecret, handler)
// Register a BotAdapter so the service can send replies via WebSocket
imService.RegisterAdapter(wecom.NewBotAdapter(client))
imService.RegisterAdapter(wecom.NewWSAdapter(client))
logger.Infof(ctx, "[IM] WeCom adapter registered (mode=websocket, bot_id=%s)", cfg.BotID)
// Start the long connection in a goroutine
+15
View File
@@ -74,3 +74,18 @@ type Adapter interface {
// Returns true if this request is a verification request and has been handled.
HandleURLVerification(c *gin.Context) bool
}
// StreamSender is an optional interface that adapters can implement to support streaming replies.
// When an adapter implements StreamSender, the IM service will push answer chunks in real-time
// instead of waiting for the full answer.
type StreamSender interface {
// StartStream initializes a streaming reply session (e.g., creates a streaming card).
// Returns a platform-specific stream ID for subsequent chunk/end calls.
StartStream(ctx context.Context, incoming *IncomingMessage) (string, error)
// SendStreamChunk appends a content chunk to an ongoing stream.
SendStreamChunk(ctx context.Context, incoming *IncomingMessage, streamID string, content string) error
// EndStream finalizes a streaming reply.
EndStream(ctx context.Context, incoming *IncomingMessage, streamID string) error
}
+326
View File
@@ -29,6 +29,9 @@ import (
"github.com/gin-gonic/gin"
)
// Compile-time check that Adapter implements im.StreamSender.
var _ im.StreamSender = (*Adapter)(nil)
var httpClient = &http.Client{Timeout: 10 * time.Second}
// Adapter implements im.Adapter for Feishu/Lark.
@@ -324,6 +327,329 @@ func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, r
return nil
}
// ──────────────────────────────────────────────────────────────────────
// Feishu CardKit v1 streaming implementation (official best practice)
//
// Flow:
// 1. POST /cardkit/v1/cards — create card entity
// 2. POST /im/v1/messages content={"type":"card","data":{"card_id":"…"}} — send card
// 3. PUT /cardkit/v1/cards/{id}/elements/{eid}/content — stream element content
// 4. PATCH /cardkit/v1/cards/{id}/settings — set streaming_mode=false
//
// Reference: https://github.com/larksuite/openclaw-lark (official Lark plugin)
// https://open.feishu.cn/document/cardkit-v1/streaming-updates-openapi-overview
// ──────────────────────────────────────────────────────────────────────
const (
// streamingElementID is the element_id used in the card JSON for streaming content.
streamingElementID = "streaming_content"
)
// feishuStreamState tracks per-stream accumulated content.
type feishuStreamState struct {
mu sync.Mutex
content strings.Builder
seq int64 // strictly incrementing sequence for CardKit API
}
var (
feishuStreamsMu sync.Mutex
feishuStreams = map[string]*feishuStreamState{}
)
func (s *feishuStreamState) nextSeq() int {
s.seq++
return int(s.seq)
}
// buildStreamingCardJSON builds a Card JSON 2.0 with streaming_mode enabled.
func buildStreamingCardJSON() string {
card := map[string]interface{}{
"schema": "2.0",
"config": map[string]interface{}{
"streaming_mode": true,
"summary": map[string]string{"content": "正在思考..."},
},
"header": map[string]interface{}{
"template": "blue",
"title": map[string]string{"tag": "plain_text", "content": "WeKnora"},
},
"body": map[string]interface{}{
"elements": []map[string]interface{}{
{
"tag": "markdown",
"content": "",
"text_size": "normal",
"element_id": streamingElementID,
},
},
},
}
b, _ := json.Marshal(card)
return string(b)
}
// StartStream creates a CardKit card entity, sends it as a message, and returns the card_id.
func (a *Adapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
accessToken, err := a.getTenantAccessToken(ctx)
if err != nil {
return "", fmt.Errorf("get access token: %w", err)
}
// 1. Create card entity via CardKit API
cardJSON := buildStreamingCardJSON()
cardID, err := a.cardkitCreate(ctx, accessToken, cardJSON)
if err != nil {
return "", fmt.Errorf("create card: %w", err)
}
// 2. Send the card as a message (content type="card")
if err := a.sendCardByCardID(ctx, accessToken, incoming, cardID); err != nil {
return "", fmt.Errorf("send card message: %w", err)
}
// 3. Track stream state
feishuStreamsMu.Lock()
feishuStreams[cardID] = &feishuStreamState{}
feishuStreamsMu.Unlock()
logger.Infof(ctx, "[Feishu] Streaming started: card_id=%s", cardID)
return cardID, nil
}
// SendStreamChunk accumulates content and pushes it to the card element.
func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
if content == "" {
return nil
}
feishuStreamsMu.Lock()
state, ok := feishuStreams[streamID]
feishuStreamsMu.Unlock()
if !ok {
return fmt.Errorf("unknown stream ID: %s", streamID)
}
state.mu.Lock()
state.content.WriteString(content)
fullContent := state.content.String()
seq := state.nextSeq()
state.mu.Unlock()
accessToken, err := a.getTenantAccessToken(ctx)
if err != nil {
return fmt.Errorf("get access token: %w", err)
}
return a.cardkitUpdateElement(ctx, accessToken, streamID, streamingElementID, fullContent, seq)
}
// EndStream disables streaming_mode and cleans up state.
func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
feishuStreamsMu.Lock()
state, ok := feishuStreams[streamID]
delete(feishuStreams, streamID)
feishuStreamsMu.Unlock()
accessToken, err := a.getTenantAccessToken(ctx)
if err != nil {
return fmt.Errorf("get access token: %w", err)
}
var seq int
if ok {
state.mu.Lock()
seq = state.nextSeq()
state.mu.Unlock()
}
// Turn off streaming_mode to remove loading indicator
if err := a.cardkitSetStreaming(ctx, accessToken, streamID, false, seq); err != nil {
logger.Warnf(ctx, "[Feishu] Failed to disable streaming_mode: %v", err)
}
logger.Infof(ctx, "[Feishu] Streaming ended: card_id=%s", streamID)
return nil
}
// ── CardKit v1 API helpers ──
// cardkitCreate creates a card entity and returns the card_id.
// POST /open-apis/cardkit/v1/cards
func (a *Adapter) cardkitCreate(ctx context.Context, accessToken, cardJSON string) (string, error) {
payload, _ := json.Marshal(map[string]interface{}{
"type": "card_json",
"data": cardJSON,
})
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://open.feishu.cn/open-apis/cardkit/v1/cards", bytes.NewReader(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("read response: %w", err)
}
var result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(respBody, &result); err != nil {
return "", fmt.Errorf("decode: %w (body: %s)", err, string(respBody))
}
if result.Code != 0 {
return "", fmt.Errorf("code=%d msg=%s", result.Code, result.Msg)
}
var data struct {
CardID string `json:"card_id"`
}
if err := json.Unmarshal(result.Data, &data); err != nil {
return "", fmt.Errorf("parse card_id: %w (raw: %s)", err, string(result.Data))
}
return data.CardID, nil
}
// sendCardByCardID sends a card_id as an interactive message.
// POST /open-apis/im/v1/messages with content={"type":"card","data":{"card_id":"…"}}
func (a *Adapter) sendCardByCardID(ctx context.Context, accessToken string, incoming *im.IncomingMessage, cardID string) error {
receiveIDType := "open_id"
receiveID := incoming.UserID
if incoming.ChatType == im.ChatTypeGroup && incoming.ChatID != "" {
receiveIDType = "chat_id"
receiveID = incoming.ChatID
}
// Key: type must be "card" (not "card_id")
content, _ := json.Marshal(map[string]interface{}{
"type": "card",
"data": map[string]string{"card_id": cardID},
})
payload, _ := json.Marshal(map[string]interface{}{
"receive_id": receiveID,
"msg_type": "interactive",
"content": string(content),
})
apiURL := fmt.Sprintf("https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=%s", receiveIDType)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read response: %w", err)
}
var result struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
if err := json.Unmarshal(respBody, &result); err != nil {
return fmt.Errorf("decode: %w (body: %s)", err, string(respBody))
}
if result.Code != 0 {
return fmt.Errorf("send card error: code=%d msg=%s", result.Code, result.Msg)
}
return nil
}
// cardkitUpdateElement updates a card element's content for streaming.
// PUT /open-apis/cardkit/v1/cards/:card_id/elements/:element_id/content
func (a *Adapter) cardkitUpdateElement(ctx context.Context, accessToken, cardID, elementID, content string, sequence int) error {
payload, _ := json.Marshal(map[string]interface{}{
"content": content,
"sequence": sequence,
})
apiURL := fmt.Sprintf("https://open.feishu.cn/open-apis/cardkit/v1/cards/%s/elements/%s/content",
cardID, elementID)
req, err := http.NewRequestWithContext(ctx, http.MethodPut, apiURL, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var result struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("decode: %w", err)
}
if result.Code != 0 {
return fmt.Errorf("update element error: code=%d msg=%s", result.Code, result.Msg)
}
return nil
}
// cardkitSetStreaming updates the card's streaming_mode setting.
// PATCH /open-apis/cardkit/v1/cards/:card_id/settings
func (a *Adapter) cardkitSetStreaming(ctx context.Context, accessToken, cardID string, streaming bool, sequence int) error {
settings, _ := json.Marshal(map[string]interface{}{
"streaming_mode": streaming,
})
payload, _ := json.Marshal(map[string]interface{}{
"settings": string(settings),
"sequence": sequence,
})
apiURL := fmt.Sprintf("https://open.feishu.cn/open-apis/cardkit/v1/cards/%s/settings", cardID)
req, err := http.NewRequestWithContext(ctx, http.MethodPatch, apiURL, bytes.NewReader(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var result struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return fmt.Errorf("decode: %w", err)
}
if result.Code != 0 {
return fmt.Errorf("set streaming error: code=%d msg=%s", result.Code, result.Msg)
}
return nil
}
// getTenantAccessToken retrieves the Feishu tenant access token with caching.
// Feishu tokens expire in 2 hours; we cache with a safety margin.
func (a *Adapter) getTenantAccessToken(ctx context.Context) (string, error) {
+230 -7
View File
@@ -24,6 +24,9 @@ const (
dedupCleanupInterval = 1 * time.Minute
// maxContentLength is the maximum allowed message content length.
maxContentLength = 4096
// streamFlushInterval is how often buffered stream content is flushed to the IM platform.
// This prevents API rate-limiting while keeping perceived latency low.
streamFlushInterval = 300 * time.Millisecond
)
// Service orchestrates IM message handling:
@@ -44,6 +47,9 @@ type Service struct {
// processedMsgs tracks recently processed message IDs to prevent duplicate handling.
processedMsgs sync.Map
// streamDisabled tracks platforms where streaming is explicitly disabled via output_mode config.
streamDisabled map[Platform]bool
stopCh chan struct{}
}
@@ -62,6 +68,7 @@ func NewService(
tenantService: tenantService,
agentService: agentService,
adapters: make(map[Platform]Adapter),
streamDisabled: make(map[Platform]bool),
stopCh: make(chan struct{}),
}
@@ -103,6 +110,15 @@ func (s *Service) RegisterAdapter(adapter Adapter) {
s.adapters[adapter.Platform()] = adapter
}
// SetStreamDisabled disables streaming output for a specific platform.
// When disabled, the service will always collect the full answer before sending,
// even if the adapter implements StreamSender.
func (s *Service) SetStreamDisabled(platform Platform, disabled bool) {
s.mu.Lock()
defer s.mu.Unlock()
s.streamDisabled[platform] = disabled
}
// GetAdapter returns the adapter for a given platform.
func (s *Service) GetAdapter(platform Platform) (Adapter, bool) {
s.mu.RLock()
@@ -163,19 +179,30 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, tenan
}
}
// 5. Run the QA pipeline and collect the full answer
// 5. Get the platform adapter
adapter, ok := s.GetAdapter(msg.Platform)
if !ok {
return fmt.Errorf("no adapter for platform: %s", msg.Platform)
}
// 6. If the adapter supports streaming and streaming is not disabled, use streaming mode;
// otherwise collect full answer.
s.mu.RLock()
disabled := s.streamDisabled[msg.Platform]
s.mu.RUnlock()
if !disabled {
if streamer, ok := adapter.(StreamSender); ok {
return s.handleMessageStream(sessionCtx, msg, session, customAgent, kbIDs, streamer)
}
}
// Non-streaming fallback: collect full answer then send
answer, err := s.runQA(sessionCtx, session, msg.Content, customAgent, kbIDs)
if err != nil {
logger.Errorf(ctx, "[IM] QA failed: %v, sending fallback reply", err)
answer = "抱歉,处理您的问题时出现了异常,请稍后再试。"
}
// 6. Send the reply back via the platform adapter
adapter, ok := s.GetAdapter(msg.Platform)
if !ok {
return fmt.Errorf("no adapter for platform: %s", msg.Platform)
}
reply := &ReplyMessage{
Content: answer,
IsFinal: true,
@@ -249,6 +276,202 @@ func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tena
return &cs, nil
}
// handleMessageStream runs the QA pipeline and streams answer chunks to the IM platform
// in real-time via the StreamSender interface. Chunks are batched at streamFlushInterval
// to avoid API rate-limiting.
func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage, session *types.Session, customAgent *types.CustomAgent, kbIDs []string, streamer StreamSender) error {
// Start the stream on the IM platform (e.g., create Feishu streaming card)
streamID, err := streamer.StartStream(ctx, msg)
if err != nil {
logger.Warnf(ctx, "[IM] StartStream failed, falling back to non-streaming: %v", err)
return s.fallbackNonStream(ctx, msg, session, customAgent, kbIDs)
}
// Prepare the QA pipeline
qaCtx, qaCancel := context.WithTimeout(ctx, qaTimeout)
defer qaCancel()
eventBus := event.NewEventBus()
var (
bufMu sync.Mutex
buf strings.Builder // buffered content awaiting flush (answer only)
answerBuilder strings.Builder // full answer for DB persistence (includes <think>)
qaErr error
done = make(chan struct{})
closeOnce sync.Once
inThinking bool // tracks whether we're inside a <think> block
)
closeDone := func() { closeOnce.Do(func() { close(done) }) }
// Subscribe to answer chunks
eventBus.On(event.EventAgentFinalAnswer, func(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.AgentFinalAnswerData)
if !ok {
return nil
}
bufMu.Lock()
// Always persist the full content (including thinking)
answerBuilder.WriteString(data.Content)
// Filter <think>...</think> blocks from the streamed output.
// The pipeline emits: <think>..chunks..</think> then answer chunks.
content := data.Content
if !inThinking {
if strings.HasPrefix(content, "<think>") {
inThinking = true
content = "" // skip this chunk for streaming
}
}
if inThinking {
if idx := strings.Index(content, "</think>"); idx >= 0 {
inThinking = false
// Keep anything after </think>
content = strings.TrimSpace(content[idx+len("</think>"):])
} else {
content = "" // still inside thinking block
}
}
if content != "" {
buf.WriteString(content)
}
bufMu.Unlock()
if data.Done {
closeDone()
}
return nil
})
eventBus.On(event.EventError, func(_ context.Context, evt event.Event) error {
data, ok := evt.Data.(event.ErrorData)
if !ok {
return nil
}
logger.Errorf(ctx, "[IM] QA stream error: %s", data.Error)
bufMu.Lock()
qaErr = fmt.Errorf("QA pipeline error: %s", data.Error)
bufMu.Unlock()
closeDone()
return nil
})
// Determine whether to use agent mode
useAgent := customAgent != nil && customAgent.IsAgentMode()
requestID := uuid.New().String()
// Create user message
if _, err := s.messageService.CreateMessage(qaCtx, &types.Message{
SessionID: session.ID, Role: "user", Content: msg.Content,
RequestID: requestID, CreatedAt: time.Now(), IsCompleted: true,
}); err != nil {
return fmt.Errorf("create user message: %w", err)
}
// Create placeholder assistant message
assistantMsg, err := s.messageService.CreateMessage(qaCtx, &types.Message{
SessionID: session.ID, Role: "assistant",
RequestID: requestID, CreatedAt: time.Now(), IsCompleted: false,
})
if err != nil {
return fmt.Errorf("create assistant message: %w", err)
}
// Run QA async
go func() {
var err error
if useAgent {
err = s.sessionService.AgentQA(qaCtx, session, msg.Content, assistantMsg.ID, "", eventBus, customAgent, kbIDs, nil)
} else {
err = s.sessionService.KnowledgeQA(qaCtx, session, msg.Content, kbIDs, nil, assistantMsg.ID, "", false, eventBus, customAgent, false)
}
if err != nil {
logger.Errorf(ctx, "[IM] QA stream execution error: %v", err)
bufMu.Lock()
qaErr = fmt.Errorf("QA execution error: %w", err)
bufMu.Unlock()
closeDone()
}
}()
// Flush loop: periodically send buffered content to the IM platform
ticker := time.NewTicker(streamFlushInterval)
defer ticker.Stop()
flush := func() {
bufMu.Lock()
chunk := buf.String()
buf.Reset()
bufMu.Unlock()
if chunk != "" {
if err := streamer.SendStreamChunk(ctx, msg, streamID, chunk); err != nil {
logger.Warnf(ctx, "[IM] SendStreamChunk failed: %v", err)
}
}
}
loop:
for {
select {
case <-ticker.C:
flush()
case <-done:
break loop
case <-qaCtx.Done():
break loop
}
}
// Final flush of any remaining content
flush()
// End the stream
if err := streamer.EndStream(ctx, msg, streamID); err != nil {
logger.Warnf(ctx, "[IM] EndStream failed: %v", err)
}
// Persist the full answer
bufMu.Lock()
answer := answerBuilder.String()
finalErr := qaErr
bufMu.Unlock()
if answer == "" && finalErr != nil {
answer = "抱歉,处理您的问题时出现了异常,请稍后再试。"
}
if answer == "" {
answer = "抱歉,我暂时无法回答这个问题。"
}
assistantMsg.Content = answer
assistantMsg.IsCompleted = true
if err := s.messageService.UpdateMessage(ctx, assistantMsg); err != nil {
logger.Warnf(ctx, "[IM] Failed to update assistant message: %v", err)
}
logger.Infof(ctx, "[IM] Stream reply sent: platform=%s user=%s answer_len=%d", msg.Platform, msg.UserID, len(answer))
return nil
}
// fallbackNonStream is used when streaming initialization fails.
func (s *Service) fallbackNonStream(ctx context.Context, msg *IncomingMessage, session *types.Session, customAgent *types.CustomAgent, kbIDs []string) error {
answer, err := s.runQA(ctx, session, msg.Content, customAgent, kbIDs)
if err != nil {
logger.Errorf(ctx, "[IM] QA fallback failed: %v", err)
answer = "抱歉,处理您的问题时出现了异常,请稍后再试。"
}
adapter, ok := s.GetAdapter(msg.Platform)
if !ok {
return fmt.Errorf("no adapter for platform: %s", msg.Platform)
}
return adapter.SendReply(ctx, msg, &ReplyMessage{Content: answer, IsFinal: true})
}
// runQA executes the WeKnora QA pipeline and returns the full answer text.
func (s *Service) runQA(ctx context.Context, session *types.Session, query string, customAgent *types.CustomAgent, kbIDs []string) (string, error) {
// Add timeout to prevent indefinite blocking
+143
View File
@@ -0,0 +1,143 @@
package im
import (
"context"
"sync"
"testing"
"time"
)
// mockStreamSender is a test double that records streaming calls.
type mockStreamSender struct {
mu sync.Mutex
started bool
streamID string
chunks []string
ended bool
}
func (m *mockStreamSender) StartStream(_ context.Context, _ *IncomingMessage) (string, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.started = true
m.streamID = "test-stream-1"
return m.streamID, nil
}
func (m *mockStreamSender) SendStreamChunk(_ context.Context, _ *IncomingMessage, _ string, content string) error {
m.mu.Lock()
defer m.mu.Unlock()
m.chunks = append(m.chunks, content)
return nil
}
func (m *mockStreamSender) EndStream(_ context.Context, _ *IncomingMessage, _ string) error {
m.mu.Lock()
defer m.mu.Unlock()
m.ended = true
return nil
}
func (m *mockStreamSender) getChunks() []string {
m.mu.Lock()
defer m.mu.Unlock()
out := make([]string, len(m.chunks))
copy(out, m.chunks)
return out
}
func TestStreamSenderInterface(t *testing.T) {
mock := &mockStreamSender{}
ctx := context.Background()
incoming := &IncomingMessage{
Platform: PlatformFeishu,
UserID: "test-user",
Content: "hello",
}
// Start stream
streamID, err := mock.StartStream(ctx, incoming)
if err != nil {
t.Fatalf("StartStream failed: %v", err)
}
if streamID == "" {
t.Fatal("expected non-empty stream ID")
}
// Send chunks
chunks := []string{"Hello", ", ", "world", "!"}
for _, c := range chunks {
if err := mock.SendStreamChunk(ctx, incoming, streamID, c); err != nil {
t.Fatalf("SendStreamChunk failed: %v", err)
}
}
// End stream
if err := mock.EndStream(ctx, incoming, streamID); err != nil {
t.Fatalf("EndStream failed: %v", err)
}
// Verify
if !mock.started {
t.Error("expected stream to be started")
}
if !mock.ended {
t.Error("expected stream to be ended")
}
got := mock.getChunks()
if len(got) != len(chunks) {
t.Fatalf("expected %d chunks, got %d", len(chunks), len(got))
}
for i, want := range chunks {
if got[i] != want {
t.Errorf("chunk[%d] = %q, want %q", i, got[i], want)
}
}
}
func TestStreamFlushBatching(t *testing.T) {
// Simulate the batching behavior: multiple writes within one flush interval
// should be combined into a single chunk.
mock := &mockStreamSender{}
ctx := context.Background()
incoming := &IncomingMessage{
Platform: PlatformFeishu,
UserID: "test-user",
Content: "test",
}
streamID, _ := mock.StartStream(ctx, incoming)
// Simulate buffer: accumulate content then flush as one chunk
var buf string
tokens := []string{"Hello", " ", "world", "!"}
for _, tok := range tokens {
buf += tok
}
// Single flush
if err := mock.SendStreamChunk(ctx, incoming, streamID, buf); err != nil {
t.Fatalf("SendStreamChunk failed: %v", err)
}
got := mock.getChunks()
if len(got) != 1 {
t.Fatalf("expected 1 batched chunk, got %d", len(got))
}
if got[0] != "Hello world!" {
t.Errorf("batched chunk = %q, want %q", got[0], "Hello world!")
}
}
func TestStreamFlushIntervalConstant(t *testing.T) {
// Verify the flush interval is set to a reasonable value
if streamFlushInterval < 100*time.Millisecond {
t.Errorf("streamFlushInterval too small: %v (may cause API rate limiting)", streamFlushInterval)
}
if streamFlushInterval > 2*time.Second {
t.Errorf("streamFlushInterval too large: %v (poor user experience)", streamFlushInterval)
}
}
-42
View File
@@ -1,42 +0,0 @@
package wecom
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
"github.com/gin-gonic/gin"
)
// BotAdapter implements im.Adapter for WeCom intelligent bot (long connection mode).
// It delegates SendReply to the WebSocket LongConnClient.
// The webhook methods (VerifyCallback, ParseCallback, HandleURLVerification) are no-ops
// since messages arrive via WebSocket, not HTTP.
type BotAdapter struct {
client *LongConnClient
}
// NewBotAdapter creates an adapter backed by a WeCom long connection client.
func NewBotAdapter(client *LongConnClient) *BotAdapter {
return &BotAdapter{client: client}
}
func (a *BotAdapter) Platform() im.Platform {
return im.PlatformWeCom
}
func (a *BotAdapter) VerifyCallback(c *gin.Context) error {
return fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
}
func (a *BotAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
return nil, fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
}
func (a *BotAdapter) HandleURLVerification(c *gin.Context) bool {
return false
}
func (a *BotAdapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
return a.client.SendReply(ctx, incoming, reply)
}
+86
View File
@@ -89,6 +89,12 @@ type LongConnClient struct {
mu sync.Mutex
closed atomic.Bool
reqSeq atomic.Int64
// streamBufs tracks accumulated content per stream ID.
// WeCom stream protocol is replace-based: each frame's content replaces
// the previously displayed text, so we must send the full accumulated text.
streamBufsMu sync.Mutex
streamBufs map[string]*strings.Builder
}
// NewLongConnClient creates a WeCom long connection client.
@@ -175,6 +181,86 @@ func (c *LongConnClient) SendReply(ctx context.Context, incoming *im.IncomingMes
return c.writeJSON(frame)
}
// ──────────────────────────────────────────────────────────────────────
// Streaming support: send answer chunks over WebSocket in real-time
// ──────────────────────────────────────────────────────────────────────
// StartStream begins a streaming reply session.
// Returns a stream ID that must be used in subsequent chunk/end calls.
func (c *LongConnClient) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
if _, ok := incoming.Extra["req_id"]; !ok {
return "", fmt.Errorf("missing req_id in incoming message extra")
}
streamID := fmt.Sprintf("stream_%d", c.reqSeq.Add(1))
// Initialize the accumulation buffer for this stream
c.streamBufsMu.Lock()
if c.streamBufs == nil {
c.streamBufs = make(map[string]*strings.Builder)
}
c.streamBufs[streamID] = &strings.Builder{}
c.streamBufsMu.Unlock()
return streamID, nil
}
// SendStreamChunk accumulates the content and sends the full text so far.
// WeCom stream protocol is replace-based: each frame replaces the previous display.
func (c *LongConnClient) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
if content == "" {
return nil
}
// Accumulate
c.streamBufsMu.Lock()
buf, ok := c.streamBufs[streamID]
if !ok {
c.streamBufsMu.Unlock()
return fmt.Errorf("unknown stream ID: %s", streamID)
}
buf.WriteString(content)
fullContent := buf.String()
c.streamBufsMu.Unlock()
return c.sendStreamFrame(incoming, streamID, fullContent, false)
}
// EndStream sends the final frame with the full accumulated content and cleans up.
func (c *LongConnClient) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
c.streamBufsMu.Lock()
buf, ok := c.streamBufs[streamID]
var fullContent string
if ok {
fullContent = buf.String()
delete(c.streamBufs, streamID)
}
c.streamBufsMu.Unlock()
return c.sendStreamFrame(incoming, streamID, fullContent, true)
}
func (c *LongConnClient) sendStreamFrame(incoming *im.IncomingMessage, streamID, content string, finish bool) error {
reqID := incoming.Extra["req_id"]
body := streamReplyBody{MsgType: "stream"}
body.Stream.ID = streamID
body.Stream.Finish = finish
body.Stream.Content = content
bodyBytes, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal stream body: %w", err)
}
frame := wsFrame{
Cmd: cmdResponse,
Headers: map[string]string{"req_id": reqID},
Body: bodyBytes,
}
return c.writeJSON(frame)
}
func (c *LongConnClient) connectAndRun(ctx context.Context) error {
conn, _, err := ws.DefaultDialer.DialContext(ctx, wecomWSEndpoint, nil)
if err != nil {
@@ -35,8 +35,9 @@ import (
var httpClient = &http.Client{Timeout: 10 * time.Second}
// Adapter implements im.Adapter for WeCom.
type Adapter struct {
// WebhookAdapter implements im.Adapter for WeCom in webhook (self-built app callback) mode.
// Messages arrive via HTTP callback; replies are sent via the WeCom REST API.
type WebhookAdapter struct {
corpID string
token string
encodingAESKey string
@@ -50,15 +51,15 @@ type Adapter struct {
tokenExpAt time.Time
}
// NewAdapter creates a new WeCom adapter.
func NewAdapter(corpID, agentSecret, token, encodingAESKey string, corpAgentID int) (*Adapter, error) {
// NewWebhookAdapter creates a new WeCom webhook adapter.
func NewWebhookAdapter(corpID, agentSecret, token, encodingAESKey string, corpAgentID int) (*WebhookAdapter, error) {
// Decode the AES key from base64
aesKey, err := base64.StdEncoding.DecodeString(encodingAESKey + "=")
if err != nil {
return nil, fmt.Errorf("decode encoding_aes_key: %w", err)
}
return &Adapter{
return &WebhookAdapter{
corpID: corpID,
token: token,
encodingAESKey: encodingAESKey,
@@ -69,12 +70,12 @@ func NewAdapter(corpID, agentSecret, token, encodingAESKey string, corpAgentID i
}
// Platform returns the platform identifier.
func (a *Adapter) Platform() im.Platform {
func (a *WebhookAdapter) Platform() im.Platform {
return im.PlatformWeCom
}
// VerifyCallback verifies the WeCom callback signature.
func (a *Adapter) VerifyCallback(c *gin.Context) error {
func (a *WebhookAdapter) VerifyCallback(c *gin.Context) error {
timestamp := c.Query("timestamp")
nonce := c.Query("nonce")
msgSignature := c.Query("msg_signature")
@@ -105,7 +106,7 @@ func (a *Adapter) VerifyCallback(c *gin.Context) error {
}
// HandleURLVerification handles the WeCom URL verification (GET request).
func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
func (a *WebhookAdapter) HandleURLVerification(c *gin.Context) bool {
if c.Request.Method != http.MethodGet {
return false
}
@@ -128,7 +129,7 @@ func (a *Adapter) HandleURLVerification(c *gin.Context) bool {
}
// ParseCallback parses a WeCom callback into a unified IncomingMessage.
func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
func (a *WebhookAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, fmt.Errorf("read body: %w", err)
@@ -181,7 +182,7 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
// SendReply sends a reply message via WeCom API.
// For simplicity, this uses the "应用消息" API to proactively send messages.
// A production implementation would integrate with the streaming callback model.
func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
func (a *WebhookAdapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
// Get access token
accessToken, err := a.getAccessToken(ctx)
if err != nil {
@@ -235,7 +236,7 @@ func (a *Adapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, r
// getAccessToken retrieves the WeCom access token with caching.
// WeCom tokens expire in 7200 seconds (2 hours); we cache with a safety margin.
func (a *Adapter) getAccessToken(ctx context.Context) (string, error) {
func (a *WebhookAdapter) getAccessToken(ctx context.Context) (string, error) {
a.tokenMu.Lock()
defer a.tokenMu.Unlock()
@@ -282,7 +283,7 @@ func (a *Adapter) getAccessToken(ctx context.Context) (string, error) {
}
// verifySignature verifies the WeCom callback signature using constant-time comparison.
func (a *Adapter) verifySignature(signature, timestamp, nonce, encrypt string) bool {
func (a *WebhookAdapter) verifySignature(signature, timestamp, nonce, encrypt string) bool {
parts := []string{a.token, timestamp, nonce, encrypt}
sort.Strings(parts)
combined := strings.Join(parts, "")
@@ -295,7 +296,7 @@ func (a *Adapter) verifySignature(signature, timestamp, nonce, encrypt string) b
}
// decrypt decrypts a WeCom AES-encrypted message.
func (a *Adapter) decrypt(encrypted string) ([]byte, error) {
func (a *WebhookAdapter) decrypt(encrypted string) ([]byte, error) {
ciphertext, err := base64.StdEncoding.DecodeString(encrypted)
if err != nil {
return nil, fmt.Errorf("base64 decode: %w", err)
+62
View File
@@ -0,0 +1,62 @@
package wecom
import (
"context"
"fmt"
"github.com/Tencent/WeKnora/internal/im"
"github.com/gin-gonic/gin"
)
// Compile-time checks.
var (
_ im.Adapter = (*WSAdapter)(nil)
_ im.StreamSender = (*WSAdapter)(nil)
)
// WSAdapter implements im.Adapter and im.StreamSender for WeCom in WebSocket
// (long connection) mode. It delegates to the WebSocket LongConnClient.
// The webhook methods (VerifyCallback, ParseCallback, HandleURLVerification) are no-ops
// since messages arrive via WebSocket, not HTTP.
type WSAdapter struct {
client *LongConnClient
}
// NewWSAdapter creates an adapter backed by a WeCom long connection client.
func NewWSAdapter(client *LongConnClient) *WSAdapter {
return &WSAdapter{client: client}
}
func (a *WSAdapter) Platform() im.Platform {
return im.PlatformWeCom
}
func (a *WSAdapter) VerifyCallback(c *gin.Context) error {
return fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
}
func (a *WSAdapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {
return nil, fmt.Errorf("WeCom bot adapter does not support webhook callbacks")
}
func (a *WSAdapter) HandleURLVerification(c *gin.Context) bool {
return false
}
func (a *WSAdapter) SendReply(ctx context.Context, incoming *im.IncomingMessage, reply *im.ReplyMessage) error {
return a.client.SendReply(ctx, incoming, reply)
}
// ── StreamSender implementation ──
func (a *WSAdapter) StartStream(ctx context.Context, incoming *im.IncomingMessage) (string, error) {
return a.client.StartStream(ctx, incoming)
}
func (a *WSAdapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMessage, streamID string, content string) error {
return a.client.SendStreamChunk(ctx, incoming, streamID, content)
}
func (a *WSAdapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
return a.client.EndStream(ctx, incoming, streamID)
}