diff --git a/internal/im/feishu/adapter.go b/internal/im/feishu/adapter.go index eb2d7470..96444ad7 100644 --- a/internal/im/feishu/adapter.go +++ b/internal/im/feishu/adapter.go @@ -719,7 +719,7 @@ func (a *Adapter) DownloadFile(ctx context.Context, msg *im.IncomingMessage) (io // 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 +// 4. PATCH /cardkit/v1/cards/{id}/settings — finalize streaming and summary // // Reference: https://github.com/larksuite/openclaw-lark (official Lark plugin) // https://open.feishu.cn/document/cardkit-v1/streaming-updates-openapi-overview @@ -734,9 +734,9 @@ const ( type feishuStreamState struct { mu sync.Mutex content strings.Builder + contentSeq int64 // sequence of the last successfully sent content seq int64 // strictly incrementing sequence for CardKit API createdAt time.Time // for orphan stream detection - firstChunk bool // true after the first real content chunk clears the placeholder } const ( @@ -760,6 +760,16 @@ func (s *feishuStreamState) nextSeq() int { return int(s.seq) } +func cardSummaryPreview(content string) string { + content = feishuMarkdownImageRe.ReplaceAllString(content, "${1}") + content = feishuMarkdownLinkRe.ReplaceAllString(content, "${1}") + preview := []rune(strings.Join(strings.Fields(content), " ")) + if len(preview) > 120 { + preview = preview[:120] + } + return string(preview) +} + // buildStreamingCardJSON builds a Card JSON 2.0 with streaming_mode enabled. // The placeholder text follows the region so Lark users see English rather than // the Chinese wording Feishu users expect. @@ -831,11 +841,6 @@ func (a *Adapter) UpdateStreamContent(ctx context.Context, incoming *im.Incoming } state.mu.Lock() - if !state.firstChunk { - state.firstChunk = true - } - state.content.Reset() - state.content.WriteString(fullContent) seq := state.nextSeq() state.mu.Unlock() @@ -849,7 +854,18 @@ func (a *Adapter) UpdateStreamContent(ctx context.Context, incoming *im.Incoming // (uploading on demand) so the card update does not fail with 200570. content := a.resolveMarkdownImages(ctx, accessToken, fullContent) - return a.cardkitUpdateElement(ctx, accessToken, streamID, streamingElementID, content, seq) + if err := a.cardkitUpdateElement(ctx, accessToken, streamID, streamingElementID, content, seq); err != nil { + return err + } + + state.mu.Lock() + if int64(seq) > state.contentSeq { + state.content.Reset() + state.content.WriteString(fullContent) + state.contentSeq = int64(seq) + } + state.mu.Unlock() + return nil } // FinalizeStream replaces the card with answer-only content. @@ -862,7 +878,7 @@ func (a *Adapter) SendStreamChunk(ctx context.Context, incoming *im.IncomingMess return a.UpdateStreamContent(ctx, incoming, streamID, content) } -// EndStream disables streaming_mode and cleans up state. +// EndStream disables streaming_mode, replaces the temporary summary, and cleans up state. func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error { feishuStreamsMu.Lock() state, ok := feishuStreams[streamID] @@ -875,14 +891,22 @@ func (a *Adapter) EndStream(ctx context.Context, incoming *im.IncomingMessage, s } var seq int + var finalSummary *string if ok { state.mu.Lock() seq = state.nextSeq() + preview := cardSummaryPreview(state.content.String()) + if preview != "" { + finalSummary = &preview + } state.mu.Unlock() } - // Turn off streaming_mode to remove loading indicator - if err := a.cardkitSetStreaming(ctx, accessToken, streamID, false, seq); err != nil { + // Always close streaming_mode under config (CardKit rejects a top-level + // streaming_mode field). Attach a summary only when we have delivered text; + // an empty summary would leave the create-time "thinking" preview in place + // or blank the chat list unexpectedly. + if err := a.cardkitSetStreaming(ctx, accessToken, streamID, false, finalSummary, seq); err != nil { logger.Warnf(ctx, "[%s] Failed to disable streaming_mode: %v", a.region.Label, err) } @@ -1018,6 +1042,10 @@ func (a *Adapter) cardkitUpdateElement(ctx context.Context, accessToken, cardID, // feishuMarkdownImageRe matches a markdown image whose target is an http(s) URL. var feishuMarkdownImageRe = regexp.MustCompile(`!\[([^\]]*)\]\((https?://[^)\s]+)\)`) +// feishuMarkdownLinkRe matches a markdown link whose target is an http(s) URL. +// Applied after image stripping so signed image URLs are not left as links. +var feishuMarkdownLinkRe = regexp.MustCompile(`\[([^\]]*)\]\((https?://[^)\s]+)\)`) + // feishuMaxImageBytes caps the download size of an image before uploading to // Feishu (Feishu's limit is 10MB; keep a small margin). const feishuMaxImageBytes = 10 << 20 @@ -1171,12 +1199,18 @@ func (a *Adapter) uploadImageFromURL(ctx context.Context, accessToken, rawURL st return result.Data.ImageKey, nil } -// cardkitSetStreaming updates the card's streaming_mode setting. +// cardkitSetStreaming updates streaming_mode and, when available, the final summary. // 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{}{ +func (a *Adapter) cardkitSetStreaming( + ctx context.Context, accessToken, cardID string, streaming bool, finalSummary *string, sequence int, +) error { + config := map[string]interface{}{ "streaming_mode": streaming, - }) + } + if finalSummary != nil && strings.TrimSpace(*finalSummary) != "" { + config["summary"] = map[string]string{"content": *finalSummary} + } + settings, _ := json.Marshal(map[string]interface{}{"config": config}) payload, _ := json.Marshal(map[string]interface{}{ "settings": string(settings), "sequence": sequence, diff --git a/internal/im/feishu/adapter_test.go b/internal/im/feishu/adapter_test.go index 3e6e577d..6f498d85 100644 --- a/internal/im/feishu/adapter_test.go +++ b/internal/im/feishu/adapter_test.go @@ -2,6 +2,9 @@ package feishu import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" "strings" "testing" ) @@ -102,3 +105,337 @@ func TestResolveMarkdownImages_FallbackLabelFollowsRegion(t *testing.T) { } } } + +func TestEndStreamFinalizesCardSummary(t *testing.T) { + useTestHTTPClient(t) + type recordedRequest struct { + method string + path string + authorization string + sequence int + content string + settings string + statePresent bool + } + var requests []recordedRequest + + const cardID = "card-final-summary" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" { + _ = json.NewEncoder(w).Encode(map[string]any{ + "code": 0, "tenant_access_token": "test-token", "expire": 7200, + }) + return + } + + var body struct { + Sequence int `json:"sequence"` + Content string `json:"content"` + Settings string `json:"settings"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decode %s: %v", r.URL.Path, err) + } + feishuStreamsMu.Lock() + _, statePresent := feishuStreams[cardID] + feishuStreamsMu.Unlock() + requests = append(requests, recordedRequest{ + method: r.Method, path: r.URL.Path, authorization: r.Header.Get("Authorization"), + sequence: body.Sequence, content: body.Content, settings: body.Settings, + statePresent: statePresent, + }) + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "msg": "ok"}) + })) + defer srv.Close() + + adapter, _ := NewAdapter(testRegion(srv.URL), "app", "secret", "", "", "") + feishuStreamsMu.Lock() + feishuStreams[cardID] = &feishuStreamState{} + feishuStreamsMu.Unlock() + t.Cleanup(func() { + feishuStreamsMu.Lock() + delete(feishuStreams, cardID) + feishuStreamsMu.Unlock() + }) + + ctx := context.Background() + if err := adapter.UpdateStreamContent(ctx, nil, cardID, "progress"); err != nil { + t.Fatalf("UpdateStreamContent: %v", err) + } + const finalContent = " 最终\n回答 ✅ " + if err := adapter.FinalizeStream(ctx, nil, cardID, finalContent); err != nil { + t.Fatalf("FinalizeStream: %v", err) + } + if err := adapter.EndStream(ctx, nil, cardID); err != nil { + t.Fatalf("EndStream: %v", err) + } + + if len(requests) != 3 { + t.Fatalf("CardKit request count = %d, want 3", len(requests)) + } + for i, request := range requests { + if request.authorization != "Bearer test-token" { + t.Errorf("request %d Authorization = %q", i, request.authorization) + } + if request.sequence != i+1 { + t.Errorf("request %d sequence = %d, want %d", i, request.sequence, i+1) + } + } + if requests[1].content != finalContent { + t.Errorf("final content = %q, want %q", requests[1].content, finalContent) + } + if requests[2].method != http.MethodPatch || requests[2].path != "/open-apis/cardkit/v1/cards/"+cardID+"/settings" { + t.Errorf("final request = %s %s", requests[2].method, requests[2].path) + } + if requests[2].statePresent { + t.Error("stream state still present when final settings were sent") + } + + var settings struct { + Config *struct { + StreamingMode *bool `json:"streaming_mode"` + Summary struct { + Content string `json:"content"` + } `json:"summary"` + } `json:"config"` + } + if err := json.Unmarshal([]byte(requests[2].settings), &settings); err != nil { + t.Fatalf("decode final settings: %v", err) + } + if settings.Config == nil || settings.Config.StreamingMode == nil || *settings.Config.StreamingMode { + t.Fatalf("final settings did not disable streaming under config: %s", requests[2].settings) + } + if settings.Config.Summary.Content != "最终 回答 ✅" { + t.Errorf("summary = %q, want %q", settings.Config.Summary.Content, "最终 回答 ✅") + } + + if err := adapter.EndStream(ctx, nil, "missing-card"); err != nil { + t.Fatalf("EndStream missing state: %v", err) + } + if len(requests) != 4 { + t.Fatalf("request count after missing state = %d, want 4", len(requests)) + } + assertStreamingClosed(t, requests[3].settings, "") + if requests[3].sequence != 0 { + t.Errorf("missing-state sequence = %d, want 0", requests[3].sequence) + } +} + +func TestEndStreamSummaryUsesLastSuccessfulContent(t *testing.T) { + useTestHTTPClient(t) + const cardID = "card-failed-final-content" + var finalSettings string + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" { + _ = json.NewEncoder(w).Encode(map[string]any{ + "code": 0, "tenant_access_token": "test-token", "expire": 7200, + }) + return + } + + var body struct { + Content string `json:"content"` + Settings string `json:"settings"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decode %s: %v", r.URL.Path, err) + return + } + if body.Content == "failed final content" { + _ = json.NewEncoder(w).Encode(map[string]any{"code": 1, "msg": "rejected"}) + return + } + if r.Method == http.MethodPatch { + finalSettings = body.Settings + } + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "msg": "ok"}) + })) + defer srv.Close() + + adapter, _ := NewAdapter(testRegion(srv.URL), "app", "secret", "", "", "") + feishuStreamsMu.Lock() + feishuStreams[cardID] = &feishuStreamState{} + feishuStreamsMu.Unlock() + t.Cleanup(func() { + feishuStreamsMu.Lock() + delete(feishuStreams, cardID) + feishuStreamsMu.Unlock() + }) + + ctx := context.Background() + if err := adapter.UpdateStreamContent(ctx, nil, cardID, "visible progress"); err != nil { + t.Fatalf("UpdateStreamContent: %v", err) + } + if err := adapter.FinalizeStream(ctx, nil, cardID, "failed final content"); err == nil { + t.Fatal("FinalizeStream succeeded, want CardKit rejection") + } + if err := adapter.EndStream(ctx, nil, cardID); err != nil { + t.Fatalf("EndStream: %v", err) + } + + var settings struct { + Config struct { + Summary struct { + Content string `json:"content"` + } `json:"summary"` + } `json:"config"` + } + if err := json.Unmarshal([]byte(finalSettings), &settings); err != nil { + t.Fatalf("decode final settings: %v", err) + } + if settings.Config.Summary.Content != "visible progress" { + t.Errorf("summary = %q, want last successful content", settings.Config.Summary.Content) + } +} + +func TestEndStreamFinalizeOnlyUsesFinalContent(t *testing.T) { + useTestHTTPClient(t) + const cardID = "card-full-output" + var finalSettings string + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" { + _ = json.NewEncoder(w).Encode(map[string]any{ + "code": 0, "tenant_access_token": "test-token", "expire": 7200, + }) + return + } + var body struct { + Settings string `json:"settings"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decode %s: %v", r.URL.Path, err) + return + } + if r.Method == http.MethodPatch { + finalSettings = body.Settings + } + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "msg": "ok"}) + })) + defer srv.Close() + + adapter, _ := NewAdapter(testRegion(srv.URL), "app", "secret", "", "", "") + feishuStreamsMu.Lock() + feishuStreams[cardID] = &feishuStreamState{} + feishuStreamsMu.Unlock() + t.Cleanup(func() { + feishuStreamsMu.Lock() + delete(feishuStreams, cardID) + feishuStreamsMu.Unlock() + }) + + ctx := context.Background() + if err := adapter.FinalizeStream(ctx, nil, cardID, "最终答案"); err != nil { + t.Fatalf("FinalizeStream: %v", err) + } + if err := adapter.EndStream(ctx, nil, cardID); err != nil { + t.Fatalf("EndStream: %v", err) + } + assertStreamingClosed(t, finalSettings, "最终答案") +} + +func TestEndStreamOmitsEmptySummary(t *testing.T) { + useTestHTTPClient(t) + const cardID = "card-empty-summary" + var finalSettings string + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal" { + _ = json.NewEncoder(w).Encode(map[string]any{ + "code": 0, "tenant_access_token": "test-token", "expire": 7200, + }) + return + } + var body struct { + Settings string `json:"settings"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Errorf("decode %s: %v", r.URL.Path, err) + return + } + if r.Method == http.MethodPatch { + finalSettings = body.Settings + } + _ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "msg": "ok"}) + })) + defer srv.Close() + + adapter, _ := NewAdapter(testRegion(srv.URL), "app", "secret", "", "", "") + feishuStreamsMu.Lock() + feishuStreams[cardID] = &feishuStreamState{} + feishuStreamsMu.Unlock() + t.Cleanup(func() { + feishuStreamsMu.Lock() + delete(feishuStreams, cardID) + feishuStreamsMu.Unlock() + }) + + if err := adapter.EndStream(context.Background(), nil, cardID); err != nil { + t.Fatalf("EndStream: %v", err) + } + assertStreamingClosed(t, finalSettings, "") +} + +func TestCardSummaryPreview(t *testing.T) { + tests := []struct { + name string + in string + want string + }{ + {name: "collapse whitespace", in: " 最终\n回答\t✅ ", want: "最终 回答 ✅"}, + {name: "image keeps alt only", in: "![架构图](https://cdn.example/a.png?sig=secret) 说明", want: "架构图 说明"}, + {name: "link keeps text only", in: "见 [文档](https://cdn.example/a.png?sig=secret) 说明", want: "见 文档 说明"}, + {name: "unicode limit", in: strings.Repeat("界", 121), want: strings.Repeat("界", 120)}, + {name: "empty", in: " \n\t ", want: ""}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := cardSummaryPreview(test.in); got != test.want { + t.Errorf("cardSummaryPreview() = %q, want %q", got, test.want) + } + }) + } +} + +type cardSettings struct { + Config *struct { + StreamingMode *bool `json:"streaming_mode"` + Summary *struct { + Content string `json:"content"` + } `json:"summary"` + } `json:"config"` +} + +func decodeCardSettings(t *testing.T, raw string) cardSettings { + t.Helper() + var settings cardSettings + if err := json.Unmarshal([]byte(raw), &settings); err != nil { + t.Fatalf("decode settings %q: %v", raw, err) + } + var top map[string]json.RawMessage + if err := json.Unmarshal([]byte(raw), &top); err != nil { + t.Fatalf("decode settings map %q: %v", raw, err) + } + if _, ok := top["streaming_mode"]; ok { + t.Fatalf("streaming_mode must be nested under config: %s", raw) + } + return settings +} + +func assertStreamingClosed(t *testing.T, raw, wantSummary string) { + t.Helper() + settings := decodeCardSettings(t, raw) + if settings.Config == nil || settings.Config.StreamingMode == nil || *settings.Config.StreamingMode { + t.Fatalf("settings did not disable streaming under config: %s", raw) + } + if wantSummary == "" { + if settings.Config.Summary != nil { + t.Fatalf("settings included empty summary: %s", raw) + } + return + } + if settings.Config.Summary == nil || settings.Config.Summary.Content != wantSummary { + t.Fatalf("summary = %v, want %q in %s", settings.Config.Summary, wantSummary, raw) + } +}