feat(dingtalk): land the finished answer through the plain card update

Streamed card content is replayed by the DingTalk client with a typewriter
animation it drives itself, so an answer that is already complete on the server
can still be typed out - and a client that leaves the foreground pauses that
animation, which reads as 'streaming stopped, it continues when I switch back'
long after the final frame was pushed.

Add DINGTALK_CARD_FINAL_WRITE (streaming default | update): in update mode the
streaming finalize is followed by one plain PUT /v1.0/card/instances write with
the identical template variables, so the terminal content has no typewriter
queue behind it. The follow-up write never fails a delivered answer.
This commit is contained in:
agent
2026-09-20 17:21:40 +08:00
parent 341b7e3990
commit ba35e251be
7 changed files with 501 additions and 13 deletions
+22
View File
@@ -22,3 +22,25 @@ func cardPartialUpdatesMode() dingtalk.CardPartialUpdatesMode {
log.Printf("DingTalk card partial updates mode=%s", mode)
return mode
}
// cardFinalWriteMode returns the configured terminal-write mode for a finished
// answer (see dingtalk.CardFinalWriteMode):
//
// unset / streaming → the finished answer is written with the card streaming
// API and isFinalize=true (historical behaviour)
// update / plain → the same answer is written once more through the plain
// card update API (PUT /v1.0/card/instances), so the
// terminal content carries no client-side typewriter queue
//
// DingTalk renders streamed card content with a typewriter animation the client
// drives itself, so an answer that is already complete on the server can still be
// replayed character by character - and a client that is not in the foreground
// pauses that animation, which reads as "streaming stopped, it continues when I
// switch back". The default stays "streaming" so an environment without the
// variable behaves exactly as before; DINGTALK_CARD_FINAL_WRITE selects the other
// mode. The resolved mode is logged so the startup log always states what ran.
func cardFinalWriteMode() dingtalk.CardFinalWriteMode {
mode := dingtalk.ParseCardFinalWriteMode(os.Getenv("DINGTALK_CARD_FINAL_WRITE"))
log.Printf("DingTalk card final write mode=%s", mode)
return mode
}
+24
View File
@@ -29,3 +29,27 @@ func TestCardPartialUpdatesMode(t *testing.T) {
})
}
}
func TestCardFinalWriteMode(t *testing.T) {
tests := []struct {
name string
raw string
want dingtalk.CardFinalWriteMode
}{
{"unset keeps the streaming finalize", "", dingtalk.CardFinalWriteStreaming},
{"streaming stays streaming", "streaming", dingtalk.CardFinalWriteStreaming},
{"unknown keeps the streaming finalize", "hammer", dingtalk.CardFinalWriteStreaming},
{"update", " update ", dingtalk.CardFinalWriteUpdate},
{"plain alias", "plain", dingtalk.CardFinalWriteUpdate},
{"on alias", "ON", dingtalk.CardFinalWriteUpdate},
{"1 alias", "1", dingtalk.CardFinalWriteUpdate},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("DINGTALK_CARD_FINAL_WRITE", tt.raw)
if got := cardFinalWriteMode(); got != tt.want {
t.Fatalf("cardFinalWriteMode(%q)=%q want %q", tt.raw, got, tt.want)
}
})
}
}
+1
View File
@@ -298,6 +298,7 @@ func main() {
cardTemplateID,
nil,
dingtalk.WithCardDebugUserID(cardDebugUserID),
dingtalk.WithCardFinalWrite(cardFinalWriteMode()),
)
if err != nil {
log.Fatalf("DingTalk card sender init failed: %v", err)
+75 -13
View File
@@ -20,6 +20,7 @@ import (
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
@@ -57,9 +58,11 @@ type CardSender struct {
tokenURL string
createURL string
streamURL string
updateURL string
apiClient *http.Client
allowTestURL bool
debugUserID string
finalWrite CardFinalWriteMode
mu sync.Mutex
token string
@@ -77,20 +80,31 @@ func WithCardDebugUserID(userID string) CardSenderOption {
}
}
// 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, false, options...)
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) {
streamURL := strings.TrimSuffix(createURL, "/create") + "/stream"
return newCardSender(clientID, clientSecret, cardTemplateID, client, tokenURL, createURL, streamURL, true, options...)
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 string, allowTest bool, options ...CardSenderOption) (*CardSender, error) {
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)
@@ -130,6 +144,7 @@ func newCardSender(clientID, clientSecret, cardTemplateID string, client *http.C
tokenURL: tokenURL,
createURL: createURL,
streamURL: streamURL,
updateURL: updateURL,
apiClient: &apiClient,
allowTestURL: allowTest,
}
@@ -232,7 +247,38 @@ func (s *CardSender) UpdateCard(ctx context.Context, outTrackID, content string,
return err
}
return s.finalizeCard(ctx, outTrackID, content, token, isFinalize, isError)
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 isFinalize && !isError && 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
}
// 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 {
@@ -241,14 +287,7 @@ func (s *CardSender) buildCardBody(req CardRequest, outTrackID string) map[strin
"outTrackId": outTrackID,
"callbackType": "STREAM",
"cardData": map[string]any{
"cardParamMap": map[string]any{
"content": req.Content,
"feedbackSelected": "",
"feedbackReasonSelected": "",
"showFeedbackReasons": "false",
"feedbackMessage": "",
cardWideScreenJSONKey: cardWideScreenJSON,
},
"cardParamMap": cardParamMap(req.Content),
},
"userIdType": 1,
}
@@ -370,6 +409,29 @@ func (s *CardSender) finalizeCard(ctx context.Context, outTrackID, content, toke
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)
}
@@ -50,3 +50,48 @@ func (m CardPartialUpdatesMode) streamsPartialFrames() bool {
func (m CardPartialUpdatesMode) placeholderCardRequested() bool {
return m != CardPartialUpdatesDirect
}
// CardFinalWriteMode selects how the terminal write of a finished answer lands
// in the card.
//
// streaming (default) → the finished answer is written with the card streaming
// API and isFinalize=true (historical behaviour). DingTalk
// renders content that arrives through the streaming
// endpoint with a typewriter animation driven by the
// client itself: an answer that is already complete on the
// server can still be replayed character by character, and
// a client that is not in the foreground pauses that
// animation - which reads as "the streaming stopped and it
// resumes when I switch back", long after the server has
// pushed the final frame.
// update → after the streaming finalize, the same finished answer is
// written once more through the plain card update API
// (PUT /v1.0/card/instances). That write carries no
// streaming semantics, so the terminal state is applied to
// the card without leaving a typewriter queue behind.
//
// The default stays "streaming" so an environment without the variable behaves
// exactly as before; DINGTALK_CARD_FINAL_WRITE selects the other mode.
type CardFinalWriteMode string
const (
CardFinalWriteStreaming CardFinalWriteMode = "streaming"
CardFinalWriteUpdate CardFinalWriteMode = "update"
)
// ParseCardFinalWriteMode maps DINGTALK_CARD_FINAL_WRITE onto a mode. Unset or
// unrecognised values keep the historical streaming finalize.
func ParseCardFinalWriteMode(raw string) CardFinalWriteMode {
switch strings.ToLower(strings.TrimSpace(raw)) {
case "update", "plain", "plain_update", "on", "true", "1", "yes":
return CardFinalWriteUpdate
default:
return CardFinalWriteStreaming
}
}
// alsoPlainUpdates reports whether the finished answer must additionally be
// written through the plain (non-streaming) card update endpoint.
func (m CardFinalWriteMode) alsoPlainUpdates() bool {
return m == CardFinalWriteUpdate
}
@@ -51,3 +51,44 @@ func TestCardPartialUpdatesModeFramesAndPlaceholder(t *testing.T) {
}
}
}
func TestParseCardFinalWriteMode(t *testing.T) {
tests := []struct {
raw string
want CardFinalWriteMode
}{
{"", CardFinalWriteStreaming},
{"streaming", CardFinalWriteStreaming},
{"stream", CardFinalWriteStreaming},
{"sometimes", CardFinalWriteStreaming},
{"0", CardFinalWriteStreaming},
{"off", CardFinalWriteStreaming},
{"update", CardFinalWriteUpdate},
{" UPDATE ", CardFinalWriteUpdate},
{"plain", CardFinalWriteUpdate},
{"plain_update", CardFinalWriteUpdate},
{"on", CardFinalWriteUpdate},
{"true", CardFinalWriteUpdate},
{"yes", CardFinalWriteUpdate},
{"1", CardFinalWriteUpdate},
}
for _, tt := range tests {
if got := ParseCardFinalWriteMode(tt.raw); got != tt.want {
t.Fatalf("ParseCardFinalWriteMode(%q)=%q want %q", tt.raw, got, tt.want)
}
}
}
func TestCardFinalWriteModeAlsoPlainUpdates(t *testing.T) {
// Only the explicit update mode adds the plain write; the zero value and the
// historical streaming mode must leave the single-write behaviour untouched.
for mode, want := range map[CardFinalWriteMode]bool{
CardFinalWriteStreaming: false,
CardFinalWriteUpdate: true,
"": false,
} {
if got := mode.alsoPlainUpdates(); got != want {
t.Fatalf("mode=%q alsoPlainUpdates=%v want %v", mode, got, want)
}
}
}
@@ -0,0 +1,293 @@
package dingtalk
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
)
// ---------------------------------------------------------------------------
// Helper: test server with token + create + streaming + plain update endpoints
// ---------------------------------------------------------------------------
type finalWriteTestServer struct {
server *httptest.Server
createCalls int
streamCalls int
updateCalls int
lastCreateBody map[string]any
lastStreamBody map[string]any
lastUpdateBody map[string]any
lastUpdateMethod string
lastUpdateHeader string
streamStatus int
streamResponse any
updateStatus int
updateResponse any
createResponse any
}
func newFinalWriteTestServer() *finalWriteTestServer {
ts := &finalWriteTestServer{
streamStatus: http.StatusOK,
updateStatus: http.StatusOK,
streamResponse: map[string]any{"result": "ok"},
updateResponse: map[string]any{"result": true, "success": true},
createResponse: map[string]any{"result": "ok"},
}
ts.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/token":
json.NewEncoder(w).Encode(map[string]any{"accessToken": "test-access-token", "expireIn": 3600})
case "/create":
ts.createCalls++
ts.lastCreateBody = make(map[string]any)
json.NewDecoder(r.Body).Decode(&ts.lastCreateBody)
json.NewEncoder(w).Encode(ts.createResponse)
case "/stream":
ts.streamCalls++
ts.lastStreamBody = make(map[string]any)
json.NewDecoder(r.Body).Decode(&ts.lastStreamBody)
if ts.streamStatus != http.StatusOK {
w.WriteHeader(ts.streamStatus)
return
}
json.NewEncoder(w).Encode(ts.streamResponse)
case "/update":
ts.updateCalls++
ts.lastUpdateMethod = r.Method
ts.lastUpdateHeader = r.Header.Get("x-acs-dingtalk-access-token")
ts.lastUpdateBody = make(map[string]any)
json.NewDecoder(r.Body).Decode(&ts.lastUpdateBody)
if ts.updateStatus != http.StatusOK {
w.WriteHeader(ts.updateStatus)
return
}
json.NewEncoder(w).Encode(ts.updateResponse)
default:
http.NotFound(w, r)
}
}))
return ts
}
func (ts *finalWriteTestServer) Close() { ts.server.Close() }
func (ts *finalWriteTestServer) sender(t *testing.T, mode CardFinalWriteMode) *CardSender {
t.Helper()
sender, err := newCardSenderForTest("id", "secret", "tpl", ts.server.Client(),
ts.server.URL+"/token", ts.server.URL+"/create", WithCardFinalWrite(mode))
if err != nil {
t.Fatalf("newCardSenderForTest: %v", err)
}
return sender
}
func (ts *finalWriteTestServer) paramMap(t *testing.T) map[string]any {
t.Helper()
cardData, ok := ts.lastUpdateBody["cardData"].(map[string]any)
if !ok {
t.Fatalf("update body has no cardData: %#v", ts.lastUpdateBody)
}
paramMap, ok := cardData["cardParamMap"].(map[string]any)
if !ok {
t.Fatalf("update body has no cardParamMap: %#v", cardData)
}
return paramMap
}
// ---------------------------------------------------------------------------
// Default (streaming) mode keeps the historical single-write behaviour
// ---------------------------------------------------------------------------
func TestCardFinalWriteStreamingModeDoesNotTouchPlainUpdate(t *testing.T) {
ts := newFinalWriteTestServer()
defer ts.Close()
sender := ts.sender(t, CardFinalWriteStreaming)
if err := sender.UpdateCard(context.Background(), "track-1", "答案", true, false); err != nil {
t.Fatalf("UpdateCard: %v", err)
}
if ts.streamCalls != 1 {
t.Fatalf("streamCalls=%d, want 1", ts.streamCalls)
}
if ts.updateCalls != 0 {
t.Fatalf("updateCalls=%d, want 0 in streaming mode", ts.updateCalls)
}
// The zero value (option not passed at all) must behave the same.
ts2 := newFinalWriteTestServer()
defer ts2.Close()
plain, err := newCardSenderForTest("id", "secret", "tpl", ts2.server.Client(),
ts2.server.URL+"/token", ts2.server.URL+"/create")
if err != nil {
t.Fatal(err)
}
if err := plain.UpdateCard(context.Background(), "track-2", "答案", true, false); err != nil {
t.Fatalf("UpdateCard: %v", err)
}
if ts2.updateCalls != 0 {
t.Fatalf("updateCalls=%d, want 0 with the zero-value mode", ts2.updateCalls)
}
}
// ---------------------------------------------------------------------------
// update mode: one plain write after the streaming finalize, same variables
// ---------------------------------------------------------------------------
func TestCardFinalWriteUpdateModeWritesPlainUpdateAfterFinalize(t *testing.T) {
ts := newFinalWriteTestServer()
defer ts.Close()
sender := ts.sender(t, CardFinalWriteUpdate)
if _, err := sender.StartCard(context.Background(), CardRequest{
ConversationType: core.ConversationDirect,
ExternalUserID: "user-1",
Content: "占位",
}); err != nil {
t.Fatalf("StartCard: %v", err)
}
const answer = "| 型号 | 速度 |\n| --- | --- |\n| CRV3 | 180°/s |"
if err := sender.UpdateCard(context.Background(), "track-1", answer, true, false); err != nil {
t.Fatalf("UpdateCard: %v", err)
}
if ts.streamCalls != 1 || ts.updateCalls != 1 {
t.Fatalf("streamCalls=%d updateCalls=%d, want 1/1", ts.streamCalls, ts.updateCalls)
}
if ts.lastUpdateMethod != http.MethodPut {
t.Fatalf("plain update method=%q, want PUT", ts.lastUpdateMethod)
}
if ts.lastUpdateHeader != "test-access-token" {
t.Fatalf("plain update token header=%q", ts.lastUpdateHeader)
}
if ts.lastUpdateBody["outTrackId"] != ts.lastStreamBody["outTrackId"] {
t.Fatalf("outTrackId mismatch: update=%v stream=%v", ts.lastUpdateBody["outTrackId"], ts.lastStreamBody["outTrackId"])
}
options, ok := ts.lastUpdateBody["cardUpdateOptions"].(map[string]any)
if !ok || options["updateCardDataByKey"] != false {
t.Fatalf("cardUpdateOptions=%#v, want updateCardDataByKey=false", ts.lastUpdateBody["cardUpdateOptions"])
}
paramMap := ts.paramMap(t)
if paramMap["content"] != answer {
t.Fatalf("plain update content=%v, want the finished answer", paramMap["content"])
}
if paramMap[cardWideScreenJSONKey] != cardWideScreenJSON {
t.Fatalf("plain update lost the wide-screen config: %#v", paramMap[cardWideScreenJSONKey])
}
// The plain write replaces the whole param map, so it must carry exactly the
// same variables as the create call.
createParamMap, ok := ts.lastCreateBody["cardData"].(map[string]any)["cardParamMap"].(map[string]any)
if !ok {
t.Fatalf("create body has no cardParamMap: %#v", ts.lastCreateBody)
}
if len(createParamMap) != len(paramMap) {
t.Fatalf("param map size differs: create=%d update=%d", len(createParamMap), len(paramMap))
}
for key := range createParamMap {
if _, present := paramMap[key]; !present {
t.Fatalf("plain update is missing create variable %q", key)
}
}
}
func TestCardFinalWriteUpdateModeSkipsNonFinalAndErrorFrames(t *testing.T) {
ts := newFinalWriteTestServer()
defer ts.Close()
sender := ts.sender(t, CardFinalWriteUpdate)
if err := sender.UpdateCard(context.Background(), "track-1", "部分", false, false); err != nil {
t.Fatalf("partial UpdateCard: %v", err)
}
if ts.updateCalls != 0 {
t.Fatalf("updateCalls=%d after a partial frame, want 0", ts.updateCalls)
}
if err := sender.UpdateCard(context.Background(), "track-1", "出错了", true, true); err != nil {
t.Fatalf("error UpdateCard: %v", err)
}
if ts.updateCalls != 0 {
t.Fatalf("updateCalls=%d after an error card, want 0", ts.updateCalls)
}
}
// ---------------------------------------------------------------------------
// A failing follow-up write must never fail an already delivered answer
// ---------------------------------------------------------------------------
func TestCardFinalWriteUpdateModeSwallowsPlainUpdateFailure(t *testing.T) {
for _, tt := range []struct {
name string
status int
response any
}{
{"http error", http.StatusInternalServerError, nil},
{"business failure", http.StatusOK, map[string]any{"success": false, "errcode": 40035}},
} {
t.Run(tt.name, func(t *testing.T) {
ts := newFinalWriteTestServer()
defer ts.Close()
ts.updateStatus = tt.status
if tt.response != nil {
ts.updateResponse = tt.response
}
sender := ts.sender(t, CardFinalWriteUpdate)
if err := sender.UpdateCard(context.Background(), "track-1", "答案", true, false); err != nil {
t.Fatalf("UpdateCard must succeed once the streaming finalize landed, got %v", err)
}
if ts.updateCalls != 1 {
t.Fatalf("updateCalls=%d, want 1", ts.updateCalls)
}
})
}
}
func TestCardFinalWriteUpdateModeSkipsPlainUpdateWhenFinalizeFails(t *testing.T) {
ts := newFinalWriteTestServer()
defer ts.Close()
ts.streamStatus = http.StatusInternalServerError
sender := ts.sender(t, CardFinalWriteUpdate)
if err := sender.UpdateCard(context.Background(), "track-1", "答案", true, false); err == nil {
t.Fatal("expected the streaming finalize failure to surface")
}
if ts.updateCalls != 0 {
t.Fatalf("updateCalls=%d after a failed finalize, want 0", ts.updateCalls)
}
}
// ---------------------------------------------------------------------------
// SendFinalCard (direct delivery) honours the mode too
// ---------------------------------------------------------------------------
func TestCardFinalWriteUpdateModeAppliesToSendFinalCard(t *testing.T) {
ts := newFinalWriteTestServer()
defer ts.Close()
sender := ts.sender(t, CardFinalWriteUpdate)
if _, err := sender.SendFinalCard(context.Background(), CardRequest{
ConversationType: core.ConversationDirect,
ExternalUserID: "user-1",
Content: "答案",
}); err != nil {
t.Fatalf("SendFinalCard: %v", err)
}
if ts.createCalls != 1 || ts.streamCalls != 1 || ts.updateCalls != 1 {
t.Fatalf("create/stream/update=%d/%d/%d, want 1/1/1", ts.createCalls, ts.streamCalls, ts.updateCalls)
}
if ts.paramMap(t)["content"] != "答案" {
t.Fatalf("plain update content=%v", ts.paramMap(t)["content"])
}
}