Skip to content

feat(channel): add DingTalk channel plugin (Stream mode) - #8

Open
echohn wants to merge 10 commits into
marswaveai:mainfrom
echohn:feat/dingtalk-channel
Open

echohn wants to merge 10 commits into
marswaveai:mainfrom
echohn:feat/dingtalk-channel

Conversation

@echohn

@echohn echohn commented Sep 22, 2026

Copy link
Copy Markdown

Summary

Adds a DingTalk channel plugin connecting Cola via an enterprise internal application robot using the official Stream mode (outbound WebSocket via dingtalk-stream) — no public callback URL, domain, or TLS certificate required.

Features

  • Gateway: Stream connection lifecycle (initial connect loop with 1s→60s backoff, then SDK auto-reconnect), TOPIC_ROBOT message parsing (direct-chat / group @-mention branch, @bot prefix stripping, non-text messages as text summaries), msgId-level deduplication, and real connection-state reporting.
  • Outbound: access-token manager (7200s in-memory cache with refresh coalescing, never persisted), oToMessages / groupMessages delivery, text + markdown, UTF-8-safe 15000-byte msgParam guard.
  • Group chats: opt-in via groupEnabled; non-owner @mentions are annotated with sender identity and a scope-constraint line (configurable ownerStaffId) so the assistant can answer group-scoped questions while treating strangers conservatively.
  • i18n: en / es / ja / ko / zh-CN / zh-TW.
  • Tests: 57 unit tests (message parsing, token cache, client payloads, dedup, gateway status, owner annotation). All fixtures use fake credentials; no secrets are ever persisted or logged.

Implementation notes

  • Connection state is derived from the socket being open: DingTalk's stream gateway does not push REGISTERED system frames to nodejs SDK clients (verified with a raw WebSocket probe against a live org; heartbeat ping/pong flows normally). Gating "connected" on DWClient.registered would report "connecting" forever.
  • Group @ messages carry senderStaffId / senderNick (when the robot version is published), used for the owner-identification annotation.
  • Media send/receive (image/audio/file via media upload) is planned as a follow-up; first release covers text + markdown both ways.

Verification

  • pnpm build / typecheck / lint / fmt:check / test all green (25 files / 206+ tests repo-wide).
  • Live-tested end-to-end against a real DingTalk org: direct chat replies and group @-mention replies both confirmed working.

Connect Cola to DingTalk via an enterprise internal application robot
using the official Stream mode (outbound WebSocket, no public callback).

- Gateway: DWClient Stream lifecycle (initial backoff loop + SDK
  auto-reconnect), TOPIC_ROBOT message parsing (direct/group branch,
  @bot prefix strip, non-text fallback), msgId-level dedup, real
  connection-state reporting (socket-open based; DingTalk's stream
  gateway does not push REGISTERED system frames)
- Outbound: access-token manager (7200s in-memory cache, refresh
  coalescing), oToMessages/groupMessages send, text/markdown,
  15000-byte UTF-8-safe msgParam guard
- Group chats opt-in (groupEnabled); non-owner group @mentions are
  annotated with sender identity and a scope constraint line
  (configurable ownerStaffId)
- Auth: SDK access gate with polite secretary-style hints, 6 locales
  (en/es/ja/ko/zh-CN/zh-TW)
- Tests: 57 unit tests (parsing, token cache, client payloads,
  dedup, status); all fixtures use fake credentials
- Verified: typecheck/build/lint/fmt/test all green; live-tested
  against a real DingTalk org (direct + group)

Closes nothing; media send/receive planned for a follow-up.
…ections

The dingtalk-stream SDK's internal auto-reconnect swallows errors, so a
half-open TCP connection (sleep/wake, proxy failover) can stay reported
as connected while no frames ever arrive — messages are lost silently
(observed live: 18+ hours unaware).

Track the last inbound frame timestamp (any downstream frame counts)
and re-establish the connection when no frame arrives within 5 minutes;
log a WARN on watchdog-triggered reconnects, clean up the timer on
stop/abort, and re-arm after each successful reconnect.
Send: upload media via the robot media upload API, then deliver via
oToMessages/groupMessages as sampleImageMsg / sampleAudio / sampleFile.
Declares outbound mediaCapabilities (image/file, 20MB DingTalk cap) so
the host validates size client-side. Video is intentionally
unsupported: sampleVideo requires a separate cover-image mediaId that
cannot be derived from a single file.

Receive: image/file messages are downloaded (downloadCode -> temp URL,
50MB cap, filename sanitization) instead of degrading to a text-only
summary.
Image+caption messages arrive as richText payloads. The media parser
only handled picture/audio/video/file, so richText picture nodes (which
carry downloadCode) were dropped: no download was attempted, delivery
text degraded to a bare '[图文]' placeholder, and the agent — never
receiving the media — fabricated a description from session memory
(observed live).

- richText parsing: walk text and picture nodes; build '[图文] <text>'
  with the extracted downloadCode; plain-text richText no longer gets
  any media marker
- delivery annotations: on success the agent is told the attachment was
  downloaded and is available; if media was expected but delivery
  failed, the agent receives an explicit bilingual instruction not to
  guess and to tell the user honestly (plus a WARN log, previously
  silent)
- tests: 95 passing (richText node cases, annotation cases, no-media
  paths, no regressions)
Image messages carry no fileName, so the raw downloadCode (a very long
base64 variant) was used as the file name and every media download
failed with ENAMETOOLONG (observed live).

When no real fileName is present, derive a short deterministic name
from a sha256 of the downloadCode plus an extension inferred from the
media kind; basename length is also capped at 120 characters in the
client layer regardless of source.
The dingtalk.com favicon renders poorly as a plugin icon. Ship the
official app icon (extracted from the DingTalk macOS client, 256px PNG)
in the plugin's assets and point iconUrl at the repository asset URL,
consistent with the host's https-only iconUrl validation.
…ommand

The previous unauthorizedHint override replaced the host's default guidance
(which names the 'cola channel allow[-group]' command) with a polite dead-end
reply. The owner had no in-band way to learn the ID needed for authorization —
it only appeared in host logs.

The hint now always includes the target ID (group or user) and the matching
command, in all locales. Covered by tests/unauthorized-hint.test.ts.
…derId

Group robot payloads carry senderId as a LWCP union id, which never matches
the staffId configured as ownerStaffId — so the owner was tagged as a
non-owner (with the no-private-info constraint) in every group message.
Match via senderStaffId (present for published robots) and fall back to
senderId when it is absent.
…nect storms

dingtalk-stream 2.1.5 creates its heartbeat setInterval inside the socket
open handler but only clears it in disconnect(); its internal autoReconnect
calls _connect() again without clearing, so every reconnect leaves an
orphaned interval behind. The orphans eventually fire socket.ping() while
the new socket is still CONNECTING, and ws.ping() throws 'WebSocket is not
open: readyState 0' — 1,991 uncaught exceptions in one evening, each
dragging a fresh reconnect, piling up 16k ESTABLISHED sockets until the
router behind NAT gave out.

Disable the SDK heartbeat and run a guarded one instead:
- ping only when readyState === OPEN
- a single timer for the whole monitor lifetime, never re-created per reconnect
- pong/inbound frames refresh a signal timestamp; 30s of silence recycles the connection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant