Files
dobotai-platform/internal/channels/dingtalk/card.go
T
姚章浩 e2b46faa05 feat(dingtalk): add card terminal-write order modes (refresh, close-refresh)
A DingTalk AI card replays streamed content with a typewriter animation the
client drives itself, so a finished answer can still be typed out character
by character - and a card that is not in the foreground pauses that replay.

DINGTALK_CARD_FINAL_WRITE now sequences the two terminal writes explicitly:

  streaming (default)  streaming finalize only (unchanged)
  update               finalize, then a plain write (observed to blank the card)
  refresh              plain write of the finished answer, then a zero-delta
                       finalize carrying the same text
  close-refresh        zero-delta finalize on the text the card already shows,
                       then a plain write of the finished answer

The sender remembers the text each live card shows so a terminal write can
close the stream with a frame the client has nothing to animate; a failing
plain write is logged and never fails the delivery.
2026-09-20 18:15:04 +08:00

571 lines
19 KiB
Go

package dingtalk
import (
"bytes"
"context"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"
"sync"
"time"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
)
const (
cardCreateURL = "https://api.dingtalk.com/v1.0/card/instances/createAndDeliver"
cardStreamingURL = "https://api.dingtalk.com/v1.0/card/streaming"
cardUpdateURL = "https://api.dingtalk.com/v1.0/card/instances"
cardDebugPrivateKey = "_CARD_DEBUG_TOOL_ENTRY"
// cardWideScreenJSONKey is DingTalk's reserved system field inside
// cardData.cardParamMap. Template variables whose value is a complex type
// (object / array of objects) must be passed through this field as a JSON
// string; plain string/number/boolean variables go in cardParamMap
// directly. Putting a complex value anywhere else (for example as a
// sibling of cardParamMap under cardData) leaves the template variable
// unassigned and silently falls back to the default layout.
cardWideScreenJSONKey = "sys_full_json_obj"
// cardWideScreenJSON configures the AI card's root "config": PC clients
// render the card wide (auto layout) when autoLayout is true. The card
// template must declare an object variable "config" with a boolean child
// "autoLayout" (card builder > 数据源 > 编辑变量) and the value must be
// passed when the card is created - setting it statically inside the
// template does not take effect. Mobile clients keep their own adaptive
// layout, so this only widens the card on desktop.
cardWideScreenJSON = `{"config":{"autoLayout":true}}`
)
// CardRequest is the input for sending a final AI card.
type CardRequest struct {
ConversationType core.ConversationType
ExternalUserID string
ExternalChatID string
Content string
}
// CardSender sends DingTalk AI cards via the OpenAPI.
type CardSender struct {
clientID string
clientSecret string
cardTemplateID string
tokenURL string
createURL string
streamURL string
updateURL string
apiClient *http.Client
allowTestURL bool
debugUserID string
finalWrite CardFinalWriteMode
mu sync.Mutex
token string
tokenTill time.Time
// streamed keeps the text every live card currently shows, so a terminal
// write can close the stream with a frame the client has nothing to animate
// (see CardFinalWriteMode). Bounded by the number of cards in flight in one
// process; entries are dropped once the card is finalized.
contentMu sync.Mutex
streamed map[string]string
}
// CardSenderOption configures optional CardSender behavior.
type CardSenderOption func(*CardSender)
// WithCardDebugUserID enables DingTalk's official card debug entry only for
// the matching user through per-user privateData. A blank value keeps it off.
func WithCardDebugUserID(userID string) CardSenderOption {
return func(sender *CardSender) {
sender.debugUserID = strings.TrimSpace(userID)
}
}
// WithCardFinalWrite selects how the terminal write of a finished answer lands
// in the card; see CardFinalWriteMode. The zero value keeps the historical
// streaming finalize.
func WithCardFinalWrite(mode CardFinalWriteMode) CardSenderOption {
return func(sender *CardSender) {
sender.finalWrite = mode
}
}
// NewCardSender creates a CardSender. All three config values are required
// after trimming whitespace. A nil http.Client installs a hardened default
// (no redirects, Proxy=nil, 15s timeout).
func NewCardSender(clientID, clientSecret, cardTemplateID string, client *http.Client, options ...CardSenderOption) (*CardSender, error) {
return newCardSender(clientID, clientSecret, cardTemplateID, client, oauthTokenURL, cardCreateURL, cardStreamingURL, cardUpdateURL, false, options...)
}
// newCardSenderForTest is used by tests to inject httptest URLs.
func newCardSenderForTest(clientID, clientSecret, cardTemplateID string, client *http.Client, tokenURL, createURL string, options ...CardSenderOption) (*CardSender, error) {
base := strings.TrimSuffix(createURL, "/create")
streamURL := base + "/stream"
updateURL := base + "/update"
return newCardSender(clientID, clientSecret, cardTemplateID, client, tokenURL, createURL, streamURL, updateURL, true, options...)
}
func newCardSender(clientID, clientSecret, cardTemplateID string, client *http.Client, tokenURL, createURL, streamURL, updateURL string, allowTest bool, options ...CardSenderOption) (*CardSender, error) {
clientID = strings.TrimSpace(clientID)
clientSecret = strings.TrimSpace(clientSecret)
cardTemplateID = strings.TrimSpace(cardTemplateID)
if clientID == "" {
return nil, errors.New("dingtalk card sender: clientID is required")
}
if clientSecret == "" {
return nil, errors.New("dingtalk card sender: clientSecret is required")
}
if cardTemplateID == "" {
return nil, errors.New("dingtalk card sender: cardTemplateID is required")
}
base := &http.Client{Timeout: 15 * time.Second}
if client != nil {
copyClient := *client
base = &copyClient
if base.Timeout <= 0 {
base.Timeout = 15 * time.Second
}
}
apiClient := *base
apiClient.CheckRedirect = func(*http.Request, []*http.Request) error {
return errors.New("dingtalk API redirect refused")
}
if !allowTest {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = nil
apiClient.Transport = transport
}
sender := &CardSender{
clientID: clientID,
clientSecret: clientSecret,
cardTemplateID: cardTemplateID,
tokenURL: tokenURL,
createURL: createURL,
streamURL: streamURL,
updateURL: updateURL,
apiClient: &apiClient,
allowTestURL: allowTest,
}
for _, option := range options {
if option != nil {
option(sender)
}
}
return sender, nil
}
// SendFinalCard sends the AI card to DingTalk and returns the generated outTrackID.
// It is a thin wrapper: StartCard → UpdateCard(finalize=true).
func (s *CardSender) SendFinalCard(ctx context.Context, req CardRequest) (string, error) {
outTrackID, err := s.StartCard(ctx, req)
if err != nil {
return "", err
}
if err := s.UpdateCard(ctx, outTrackID, req.Content, true, false); err != nil {
return "", err
}
return outTrackID, nil
}
// StartCard creates a card instance via createAndDeliver and returns the
// generated outTrackID. It does NOT call the streaming finalize endpoint;
// callers must use UpdateCard to stream content.
func (s *CardSender) StartCard(ctx context.Context, req CardRequest) (string, error) {
// Validate conversation type before any API call
if req.ConversationType != core.ConversationDirect && req.ConversationType != core.ConversationGroup {
return "", fmt.Errorf("dingtalk card: unsupported conversation type %q", req.ConversationType)
}
// Validate content
req.Content = strings.TrimSpace(req.Content)
if req.Content == "" {
return "", errors.New("dingtalk card: content is required")
}
if len(req.Content) > 64*1024 {
return "", errors.New("dingtalk card: content exceeds 64 KiB")
}
// Validate identity fields. ExternalUserID is also available for group
// askers and is used only for per-user card private data.
req.ExternalUserID = strings.TrimSpace(req.ExternalUserID)
if req.ConversationType == core.ConversationDirect {
if req.ExternalUserID == "" {
return "", errors.New("dingtalk card: ExternalUserID is required for direct conversations")
}
} else {
req.ExternalChatID = strings.TrimSpace(req.ExternalChatID)
if req.ExternalChatID == "" {
return "", errors.New("dingtalk card: ExternalChatID is required for group conversations")
}
}
// Generate outTrackID
outTrackID, err := generateUUID()
if err != nil {
return "", fmt.Errorf("dingtalk card: generate outTrackId: %w", err)
}
// Build card body
body := s.buildCardBody(req, outTrackID)
// Get access token
token, err := s.accessToken(ctx)
if err != nil {
return "", err
}
// Send card (create only, no finalize)
if err := s.postCard(ctx, body, token); err != nil {
return "", err
}
return outTrackID, nil
}
// UpdateCard sends a streaming update to an existing card. outTrackID and
// content must be non-empty after trimming; content must not exceed 64 KiB.
// Set isFinalize=true to close the card; set isError=true to mark the card
// as an error state.
func (s *CardSender) UpdateCard(ctx context.Context, outTrackID, content string, isFinalize, isError bool) error {
outTrackID = strings.TrimSpace(outTrackID)
if outTrackID == "" {
return errors.New("dingtalk card: outTrackID is required")
}
content = strings.TrimSpace(content)
if content == "" {
return errors.New("dingtalk card: content is required")
}
if len(content) > 64*1024 {
return errors.New("dingtalk card: content exceeds 64 KiB")
}
log.Print(formatCardUpdateDiagnostic(content, isFinalize, isError))
token, err := s.accessToken(ctx)
if err != nil {
return err
}
if !isFinalize || isError {
if err := s.finalizeCard(ctx, outTrackID, content, token, isFinalize, isError); err != nil {
return err
}
if !isFinalize {
// Remember what the card now shows: a terminal write can close the
// stream with a frame that carries no new text.
s.rememberStreamedContent(outTrackID, content)
}
return nil
}
// Terminal write. The order of the two available writes decides whether the
// client replays the finished answer with its own typewriter animation, so
// each mode sequences them explicitly - see CardFinalWriteMode.
defer s.forgetStreamedContent(outTrackID)
switch {
case s.finalWrite.refreshBeforeFinalize():
// Show the finished answer first (plain write, no streaming semantics)
// and close the stream with the very same text afterwards: the client
// has no delta left to animate, so the answer is simply there.
s.refreshCardPlain(ctx, outTrackID, content, token)
return s.finalizeCard(ctx, outTrackID, content, token, true, false)
case s.finalWrite.closeThenRefresh():
shown := s.lastStreamedContent(outTrackID)
if shown == "" {
// Nothing was streamed into this card: there is no zero-delta frame
// to close on, so refresh first and finalize after.
s.refreshCardPlain(ctx, outTrackID, content, token)
return s.finalizeCard(ctx, outTrackID, content, token, true, false)
}
// Close the stream on the text the card already shows (zero delta,
// nothing to animate), then refresh with the finished answer.
if err := s.finalizeCard(ctx, outTrackID, shown, token, true, false); err != nil {
return err
}
s.refreshCardPlain(ctx, outTrackID, content, token)
return nil
default:
if err := s.finalizeCard(ctx, outTrackID, content, token, isFinalize, isError); err != nil {
return err
}
// Optionally let the terminal content land through the plain card update
// API as well: content written through the streaming endpoint is replayed
// by the client with a typewriter animation, while a plain write has no
// streaming semantics. The streaming finalize above already closed the
// card, so a failing follow-up write is logged and swallowed - it must
// never turn a delivered answer into an error.
if s.finalWrite.alsoPlainUpdates() {
if err := s.replaceCardContent(ctx, outTrackID, content, token); err != nil {
log.Printf("DingTalk card final write: plain update failed error=%v", err)
} else {
log.Printf("DingTalk card final write: plain update ok bytes=%d", len(content))
}
}
return nil
}
}
// refreshCardPlain writes a finished answer through the plain card update API
// and logs the outcome. The write is best effort: the answer is already on its
// way through the streaming channel, so a failure here is never turned into an
// error for the caller.
func (s *CardSender) refreshCardPlain(ctx context.Context, outTrackID, content, token string) {
if err := s.replaceCardContent(ctx, outTrackID, content, token); err != nil {
log.Printf("DingTalk card final write: plain refresh failed error=%v", err)
return
}
log.Printf("DingTalk card final write: plain refresh ok bytes=%d", len(content))
}
// rememberStreamedContent records the text a card currently shows.
func (s *CardSender) rememberStreamedContent(outTrackID, content string) {
s.contentMu.Lock()
defer s.contentMu.Unlock()
if s.streamed == nil {
s.streamed = make(map[string]string)
}
s.streamed[outTrackID] = content
}
// lastStreamedContent returns the text a card currently shows, or "" when the
// card was created but never received a partial frame.
func (s *CardSender) lastStreamedContent(outTrackID string) string {
s.contentMu.Lock()
defer s.contentMu.Unlock()
return s.streamed[outTrackID]
}
// forgetStreamedContent drops the remembered text of a finalized card.
func (s *CardSender) forgetStreamedContent(outTrackID string) {
s.contentMu.Lock()
defer s.contentMu.Unlock()
delete(s.streamed, outTrackID)
}
// cardParamMap builds the template variables for a given answer. The plain card
// update must receive exactly the same variables as the create call: the update
// replaces the whole param map, so anything omitted here would be cleared on the
// delivered card.
func cardParamMap(content string) map[string]any {
return map[string]any{
"content": content,
"feedbackSelected": "",
"feedbackReasonSelected": "",
"showFeedbackReasons": "false",
"feedbackMessage": "",
cardWideScreenJSONKey: cardWideScreenJSON,
}
}
func (s *CardSender) buildCardBody(req CardRequest, outTrackID string) map[string]any {
body := map[string]any{
"cardTemplateId": s.cardTemplateID,
"outTrackId": outTrackID,
"callbackType": "STREAM",
"cardData": map[string]any{
"cardParamMap": cardParamMap(req.Content),
},
"userIdType": 1,
}
if req.ConversationType == core.ConversationDirect {
body["openSpaceId"] = "dtv1.card//IM_ROBOT." + req.ExternalUserID
body["imRobotOpenSpaceModel"] = map[string]any{
"supportForward": true,
}
body["imRobotOpenDeliverModel"] = map[string]any{
"robotCode": s.clientID,
"spaceType": "IM_ROBOT",
"extension": map[string]any{},
}
} else {
body["openSpaceId"] = "dtv1.card//IM_GROUP." + req.ExternalChatID
body["imGroupOpenSpaceModel"] = map[string]any{
"supportForward": true,
}
body["imGroupOpenDeliverModel"] = map[string]any{
"robotCode": s.clientID,
"extension": map[string]any{},
}
}
if s.debugUserID != "" && req.ExternalUserID == s.debugUserID {
body["privateData"] = map[string]any{
req.ExternalUserID: map[string]any{
"cardParamMap": map[string]any{
cardDebugPrivateKey: "show",
},
},
}
}
return body
}
func (s *CardSender) accessToken(ctx context.Context) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.token != "" && time.Now().Before(s.tokenTill) {
return s.token, nil
}
payload, err := s.postJSON(ctx, s.tokenURL, map[string]string{
"appKey": s.clientID,
"appSecret": s.clientSecret,
}, "")
if err != nil {
return "", err
}
var response struct {
AccessToken string `json:"accessToken"`
ExpireIn int64 `json:"expireIn"`
}
if json.Unmarshal(payload, &response) != nil || strings.TrimSpace(response.AccessToken) == "" {
return "", errors.New("dingtalk card: invalid OAuth response")
}
ttl := time.Duration(response.ExpireIn) * time.Second
refreshAfter := ttl - 5*time.Minute
if refreshAfter <= 0 {
refreshAfter = ttl / 2
}
if refreshAfter <= 0 {
refreshAfter = time.Minute
}
s.token = response.AccessToken
s.tokenTill = time.Now().Add(refreshAfter)
return s.token, nil
}
func (s *CardSender) postCard(ctx context.Context, body map[string]any, token string) error {
payload, err := s.postJSON(ctx, s.createURL, body, token)
if err != nil {
return err
}
return validateDingTalkBusinessResponse(payload)
}
func validateDingTalkBusinessResponse(payload []byte) error {
if len(bytes.TrimSpace(payload)) == 0 {
return nil
}
var response struct {
Success *bool `json:"success"`
ErrCode any `json:"errcode"`
}
if json.Unmarshal(payload, &response) != nil {
return nil
}
if response.Success != nil && !*response.Success {
return errors.New("dingtalk card: API business failure")
}
if response.ErrCode != nil && fmt.Sprint(response.ErrCode) != "0" {
return errors.New("dingtalk card: API business failure")
}
return nil
}
func (s *CardSender) finalizeCard(ctx context.Context, outTrackID, content, token string, isFinalize, isError bool) error {
guid, err := generateUUID()
if err != nil {
return errors.New("dingtalk card: generate stream guid failed")
}
body := map[string]any{
"outTrackId": outTrackID,
"guid": guid,
"key": "content",
"content": content,
"isFull": true,
"isFinalize": isFinalize,
"isError": isError,
}
payload, err := s.doJSON(ctx, http.MethodPut, s.streamURL, body, token)
if err != nil {
return err
}
return validateDingTalkBusinessResponse(payload)
}
// replaceCardContent writes an already finished answer through the plain card
// update API (PUT /v1.0/card/instances). The payload carries the same template
// variables as the create call and replaces the whole param map, so the card
// keeps its wide-screen configuration and feedback placeholders. Because this
// write does not go through the streaming endpoint, the client applies the
// terminal content without running a typewriter animation over it.
func (s *CardSender) replaceCardContent(ctx context.Context, outTrackID, content, token string) error {
body := map[string]any{
"outTrackId": outTrackID,
"cardData": map[string]any{
"cardParamMap": cardParamMap(content),
},
"cardUpdateOptions": map[string]any{
"updateCardDataByKey": false,
},
}
payload, err := s.doJSON(ctx, http.MethodPut, s.updateURL, body, token)
if err != nil {
return err
}
return validateDingTalkBusinessResponse(payload)
}
func (s *CardSender) postJSON(ctx context.Context, endpoint string, value any, token string) ([]byte, error) {
return s.doJSON(ctx, http.MethodPost, endpoint, value, token)
}
func (s *CardSender) doJSON(ctx context.Context, method, endpoint string, value any, token string) ([]byte, error) {
body, err := json.Marshal(value)
if err != nil {
return nil, errors.New("dingtalk card: encode API request failed")
}
req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(body))
if err != nil {
return nil, errors.New("dingtalk card: create API request failed")
}
req.Header.Set("Content-Type", "application/json")
if token != "" {
req.Header.Set("x-acs-dingtalk-access-token", token)
}
resp, err := s.apiClient.Do(req)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, errors.New("dingtalk card: API request failed")
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
// Discard body without reading it
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxAPIResponseBytes))
return nil, fmt.Errorf("dingtalk card: API HTTP %d", resp.StatusCode)
}
return readBoundedAPIResponse(resp)
}
// generateUUID creates a UUID v4 (random) using crypto/rand, formatted as
// lowercase hex with dashes: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
func generateUUID() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
// Set version 4
b[6] = (b[6] & 0x0f) | 0x40
// Set variant bits (10xx)
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x",
b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil
}