Skip to content

fix(runtime): route DingTalk 1:1 replies by staff id - #5112

Merged
Astro-Han merged 2 commits into
apache:mainfrom
ying-hua:fix/dingtalk-oto-send-route
Sep 12, 2026
Merged

Astro-Han merged 2 commits into
apache:mainfrom
ying-hua:fix/dingtalk-oto-send-route

Conversation

@ying-hua

@ying-hua ying-hua commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

DingTalk direct messages were received but could never be answered. The channel looked healthy throughout — connected, operational, ingesting text — so from the user's side the bot simply went quiet.

Two defects stacked, and fixing only the first would not have helped:

  1. The route was guessed from the id, and the guess was wrong. pickDingTalkSendRoute picked the group endpoint whenever the chatId began with cid. A 1:1 conversationId also begins with cid, so every direct reply went to /v1.0/robot/groupMessages/send.
  2. There was no usable 1:1 address in the event. The single-chat endpoint addresses recipients by senderStaffId, which DingTalkBotMessagePayload never declared — so it was dropped at parse time. Neither conversationId nor senderId is accepted there.

The fix stamps the route into the chatId at receive time, where DingTalk's conversationType still says what the conversation is, and decodes it at send time. That is the convention qq-bridge.ts already follows — "based on the chatId prefix that the receive-side helpers stamp" — and DingTalk was the one bridge inferring from the platform's native id format instead. Group chats now carry group:<openConversationId>, single chats oto:<senderStaffId>.

The alternative — adding isGroup to BotSendOptions, which BotReplyStreamOptions already declares — would leave defect 2 unfixed, since senderStaffId would still never be captured.

Fixes #5111

Compatibility

Unstamped chatIds keep the pre-stamping discriminator, so both of its outcomes survive: cid… conversation ids still route to the group endpoint, and bare staff ids still route to the 1:1 endpoint. The old guess was only ever wrong for a 1:1 conversation id, which the stamped path now handles.

This matters because a chatId is not always freshly received:

  • scheduled-task bot delivery persists {platform, chatId} into workflow_scheduled_tasks.record_json (and fire claims), migrated verbatim from the legacy workflow_plan_reminders table, with no format validation;
  • the scheduled task form takes the chatId as free text, and DingTalk is in BOT_DELIVERY_PROVIDERS.

Making unstamped ids unroutable would have silently broken existing DingTalk reminders at fire time. Existing targets of both shapes keep working unchanged.

An earlier revision of this branch collapsed all unstamped ids onto the group endpoint, which would have broken a working bare-staff-id target; caught in review and fixed in ed622ec, with a test that pins it.

The ${platform}:${chatId} conversation map is process-local and rebuilt each launch, so the group chatId format change costs at most one lost session binding across a restart.

Verification

Unit — the tests fail without the fix. Reverting only dingtalk-bridge.ts to upstream/main and keeping the new tests:

# tests 14
# pass 8
# fail 6
not ok - routes a stamped single chat to the 1:1 endpoint by staff id
not ok - routes a stamped group chat to the group endpoint
not ok - rejects empty and prefix-only ids
not ok - addresses a single chat by staff id, not by conversation id
not ok - addresses a group chat by conversation id
not ok - round-trips a single chat from receive to the 1:1 send body

With the fix: # tests 15 # pass 15 # fail 0. Full bot suite: # tests 108 # pass 108 # fail 0.

The review fix is pinned the same way: keeps an unprefixed staff id on the 1:1 endpoint is the single failure when run against the revision it corrects.

The old fixtures passed because they were invented — cidp-abc for a group, user-99 for a single chat. No real 1:1 conversation id looks like user-99; real ones start with cid and took the group branch. The replacements use realistic shapes where both kinds begin with cid, so any implementation that infers the route from the id fails them, plus round-trip cases from payload through to send body.

Live account — the patched path, end to end. A probe mirroring the patched dingTalkPayloadToEvent and pickDingTalkSendRoute line-for-line connected over DingTalk Stream and auto-replied to incoming direct messages: no human copied an id between steps, so receive → stamp → decode → send is exercised as one chain. Two direct messages, two successful replies, both confirmed received in the DingTalk client. Identifiers masked.

Direct message — the path that was broken:

[probe] senderStaffId present in payload: true
[probe] mapped event: isGroup=false chatId=oto:…80 <24 chars> text="hi"
[probe] route chosen: POST /v1.0/robot/oToMessages/batchSend
[probe] ✅ REPLY DELIVERED — HTTP 200, processQueryKey present: true

Line by line: senderStaffId is present in the callback payload, so the old interface was discarding it; the stamped chatId identifies the conversation as 1:1; the route resolves to the single-chat endpoint, where the old code would have chosen the group endpoint; and the send returns 200.

Group message — the path that had to keep working. The bot was installed into a group and @-mentioned:

[probe] mapped event: isGroup=true chatId=grou…== <33 chars> text=" hi"
[probe] route chosen: POST /v1.0/robot/groupMessages/send
[probe] ✅ REPLY DELIVERED — HTTP 200, processQueryKey present: true

Two messages per conversation kind, four replies, all delivered and confirmed received in the DingTalk client.

Live account — three-way controlled experiment (how the diagnosis was pinned down before the patch). Same conversation, same robotCode, same token, same text; only the target id varied.

# Target passed as chatId Route Result
A conversationId (cid…=) — what the bridge stamped before this PR group ❌ 400 resource.not.found — "robot 不存在;请确认 robotCode 是否正确"
B senderId ($:LWCP_v1:$…) 1:1 ❌ 400 staffId.notExisted
C senderStaffId — what this PR stamps 1:1 ✅ delivered, receipt confirmed in the DingTalk client

Row A is what shipped; row C is what this PR does.

Row A's error is misleading: it blames robotCode, but robotCode is correct — the raw callback payload's robotCode matched the app's AppKey exactly, confirming the existing derivation from appId. The group endpoint rejects a 1:1 conversation and reports it as a missing robot.

Checks run: biome check on both changed files, tsc build of @maka/runtime, ASF header audit, protocol epoch guard, git diff --check.

Not run: the full repo suite (npm test) — this touches one bridge's pure helpers and the bot suite passes in full. The husky pre-commit wrapper could not spawn biome.cmd in this Windows environment, so its checks were run directly instead; the commit is --no-verify for that reason alone.

Scope

Both conversation kinds are exercised against a live account. Not covered: non-text message types, and orgs where the callback payload omits senderStaffId (external contacts) — that case falls back to the bare conversationId, which keeps the message flowing upward and routes the send exactly as it did before this PR.

Follow-ups (not in this PR)

  • The scheduled task form's chatId field is free text with the placeholder 例如 Telegram chat_id and no per-platform guidance. Targeting a DingTalk 1:1 reminder now requires typing oto:<staffId>, which nothing in the product teaches. QQ has had the same undocumented requirement (channel: / group: / c2c:) since it landed.
  • qq-bridge.ts looks to have a defect of the same family: guild DMs are stamped `dm:${channelLike.chatId}` producing dm:channel:<id>, but pickQQSendRoute has no dm: branch and falls through to return null, so those replies never send. Untested against a live account; I have not filed it.

AI use

Select exactly one:

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: Claude Code (Opus 5) — diagnosis via live-account probes, the patch, and the tests. Reviewed and verified by the author against a real DingTalk app. Commit carries a Generated-by trailer.

Checklist

  • Tests cover the change and fail without it
  • Lint, format, typecheck and the affected suites pass locally

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No

DingTalk direct messages were received but could never be answered.

`pickDingTalkSendRoute` chose the group endpoint whenever the chatId
began with `cid`. A 1:1 `conversationId` also begins with `cid`, so
every direct reply went to `/v1.0/robot/groupMessages/send` and came
back HTTP 400 `resource.not.found` — an error that blames `robotCode`,
which is in fact correct.

Fixing the prefix test alone would not have helped: the 1:1 endpoint
addresses recipients by `senderStaffId`, and that field was never
declared on `DingTalkBotMessagePayload`, so it was dropped at parse
time. Neither `conversationId` nor `senderId` is accepted there
(`senderId` returns `staffId.notExisted`).

Stamp the route into the chatId at receive time, where DingTalk's
`conversationType` still says what the conversation is, and decode it
at send time — the convention `qq-bridge.ts` already follows. Group
chats carry `group:<openConversationId>`, single chats carry
`oto:<senderStaffId>`.

Unprefixed ids keep resolving to the group endpoint. Scheduled-task
bot delivery persists a chatId in `workflow_scheduled_tasks`, and the
scheduled task form takes one as free text, so ids predating the
prefix must keep the meaning they had when they were saved.

The old tests passed because their fixtures were invented: `cidp-abc`
for a group and `user-99` for a single chat. No real 1:1 conversation
id looks like `user-99`. The replacements use realistic shapes where
both kinds start with `cid`, so inferring the route from the id fails
them, plus round-trip cases from payload through to send body.

Refs apache#5111

Generated-by: Claude Code (Opus 5)
@github-actions github-actions Bot added the effort/M Under 500 readable lines label Sep 9, 2026
@ying-hua
ying-hua marked this pull request as ready for review September 9, 2026 14:13
ying-hua added a commit to ying-hua/maka that referenced this pull request Sep 9, 2026
Rebased onto current main, which renamed the per-channel status reasons
to snake_case. Updated the three the guide quotes:
missing-slack-tokens to slack_tokens_missing,
missing-feishu-credentials to feishu_credentials_missing, and the
generic no-credentials to wecom_credentials_missing now that each
channel carries its own code.

Re-derived the capability matrix against the new tree; every row still
maps to the same bridges, and the load-bearing constants are unchanged
(Discord's 2000-character limit, Telegram's 4000 UTF-16 units and
message-only allowed_updates, QQ's fatal 4004/4014 closes, Slack
promoting to operational on connect).

Points the DingTalk defect at apache#5112, which replaces the
prefix guess with chat IDs stamped at receive time. That fix is not on
main yet, so the section still documents the broken behaviour and says
what to rewrite once it lands.

Refs apache#3894

Co-Authored-By: Claude Opus 5 <[email protected]>

@me2seeks me2seeks left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review (Command Code) — not an approval

The diagnosis is right and the stamping approach is the right root-cause fix (it mirrors qq-bridge.ts, and the new tests use realistic cid…= shapes for both conversation kinds). One compatibility case in the unstamped branch is wrong. Line numbers are the head revision.

P2 (Should-Fix) — the unstamped fallback routes bare 1:1 targets to the group endpoint, so a previously working numeric staff-id target now fails.

pickDingTalkSendRoute now treats any unprefixed id as a group openConversationId (:181-186). Before this PR the discriminator was targetId.startsWith('cid'), so an unprefixed non-cid id went to /v1.0/robot/oToMessages/batchSend.

That case is not hypothetical:

  • the base suite asserted exactly it — pickDingTalkSendRoute(' user-99 ', …) → oToMessages/batchSend with userIds: ['user-99'];
  • issue #5111's own live experiment shows the 1:1 endpoint accepts a 20-digit numeric senderStaffId (row C: delivered).

A persisted or hand-typed numeric DingTalk 1:1 delivery target in a scheduled task therefore worked before and now routes to the group endpoint, which rejects it. The description's compatibility note ("1:1 reminders were already failing before this PR") is accurate for a 1:1 conversation id (cid…), which the old guess misrouted, but not for a numeric staff id, which the old guess sent to the 1:1 endpoint correctly.

Smallest sound fix: keep the previous discriminator for the unstamped branch — treat an unprefixed id as a group openConversationId only when it matches the conversation-id shape (startsWith('cid')), otherwise as a 1:1 target. That preserves both prior behaviors and leaves the new stamped path exact, in the same number of lines.

P3 (Nice-to-have) — the "routes as before" comment for the staff-id-less 1:1 path is inaccurate and the outcome is untested.

When a 1:1 payload omits senderStaffId, chatId falls back to the bare conversationId (:271), which the new router sends to the group endpoint — a guaranteed 400, after which sendMessage flips readiness to degraded. The comment says "the send simply routes as before" (:261-266). It is not a regression (that id also took the group branch before), but it is a guaranteed failure and nothing asserts the send outcome. Fix the comment, or assert the failing send as intended behavior.

P3 — the regression above is now untested. The new suite pins the stamped paths and the unprefixed→group decision (keeps unprefixed ids on the group endpoint for pre-existing delivery targets), while the numeric/unprefixed 1:1 case the old suite covered was deleted rather than updated.

Note on duplication. #5116 fixes the same issue with the same stamping convention; its unstamped branch returns null for all bare ids, which is a narrower compatibility story than the one here. Only one of the two should land.

Review-relevant risks. No public contract, wire shape, security boundary, dependency, licensing, or release effect was identified. Note that a chatId decides a send target, so the stamping format becomes part of persisted scheduled-task state; that is a compatibility surface, not a security one.

Required conclusion.

  1. Optimal for the actual problem? Partially. Receive-time stamping is the correct fix; the unstamped→group default is the one wrong piece.
  2. Production code that can be deleted? none identified — the capture, the prefixes, and the decode are all load-bearing; dropping startsWith('cid') is correct.
  3. Low-quality tests to delete or replace? none identified — but re-add the uncovered numeric/unprefixed 1:1 case.
  4. Deeper refactor required? No. sendMessage receiving only chatId is the identified root cause of the guessing; receive-time stamping is the correct final structure (a shared cross-bridge prefix decoder is optional).
  5. Ready to merge? Yes as a fix for the live 1:1 defect once the unstamped fallback is corrected (or the compatibility claim corrected).
  6. Residual risks / verification gaps: a 1:1 message received without senderStaffId still cannot be replied to; the group path is exercised live by the author here but was not in the issue report; stored DingTalk targets need documented group:/oto: forms.

Approval boundary. This is automated review; it is not an approval. Per CONTRIBUTING.md, the merge decision requires an independent human review. No approve was submitted.

The first cut of this branch routed every unstamped chatId to the group
endpoint, on the reasoning that an unstamped id should keep resolving to
what it resolved to before. That reasoning was wrong: what an unstamped
id resolved to depended on its shape. `startsWith('cid')` sent `cid…`
conversation ids to the group endpoint and everything else to the 1:1
endpoint, and the 1:1 endpoint accepts a bare staff id — so a persisted
or hand-typed numeric delivery target was working, and collapsing both
shapes onto the group endpoint broke it.

Keep the pre-stamping discriminator for unstamped ids so both of its
outcomes survive. The old guess was only ever wrong for a 1:1
conversation id, which the stamped path now handles.

Also correct the comment on the staff-id-less receive path. It said the
send "routes as before", which reads as though the path works; a reply
there takes the unstamped `cid…` branch and fails at the group endpoint.
Same dead end as before this branch, but a dead end.

Reported in review of apache#5112.

Generated-by: Claude Code (Opus 5)
@ying-hua

Copy link
Copy Markdown
Contributor Author

Thanks — the P2 finding is correct and I've fixed it in ed622ec.

P2 — accepted. My compatibility reasoning was wrong in a way I should have caught. I wrote that an unstamped id "keeps resolving to what it resolved to when it was saved", but what it resolved to depended on its shape: startsWith('cid') sent conversation ids to the group endpoint and everything else to the 1:1 endpoint. Collapsing both onto the group endpoint changed behavior for the second half. And as you note, row C of #5111 proves that half was working — the 1:1 endpoint accepts a bare 20-digit staff id.

So a hand-typed numeric delivery target in a scheduled task worked before my branch and would have broken. Fixed by keeping the pre-stamping discriminator for unstamped ids, exactly as suggested; the stamped paths are unchanged.

P3 (comment) — accepted. "The send simply routes as before" was literally true but read as reassurance about a path that is a guaranteed 400. Reworded to say the reply takes the unstamped cid… branch and fails at the group endpoint — the same dead end as before this branch, but a dead end.

P3 (test) — accepted. Re-added as keeps an unprefixed staff id on the 1:1 endpoint. I checked it fails against the revision it corrects, and it is the only failure there — so it pins this regression specifically rather than just passing alongside it.

Suite is now 15/15 for the bridge, 108/108 across bots/.


One correction, on #5116 rather than on this PR. The note says its unstamped branch "returns null for all bare ids, which is a narrower compatibility story than the one here." That doesn't match what it does — it keeps startsWith('cid') and routes bare non-cid ids to oToMessages/batchSend, with a test asserting exactly that. After ed622ec the two branches' unstamped behavior is equivalent, so that comparison shouldn't factor into choosing between them.

Flagging it because the review used it as a point in this PR's favour, and it isn't one.

On the duplication. Agreed only one should land, and I have no stake in which. #5116 arrived about 2.5 hours after this one and reaches the same design independently — which is some evidence the approach is the natural one. Differences a maintainer may care about: this branch verifies both conversation kinds against a live DingTalk app (1:1 was the broken path, group the one at risk from the chatId format change), and carries the diagnosis in #5111. I'm happy to close this in favour of #5116 if a maintainer prefers it — please just say so.

Still not verified here: a 1:1 message arriving without senderStaffId (external contacts) remains unrepliable. That is a real gap, unchanged by this PR, and worth its own issue rather than being folded in silently.

@Astro-Han Astro-Han left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix and the compatibility follow-up. I checked the current stamped routing and the legacy cid/non-cid fallback against #5111 and the alternative in #5116. The earlier compatibility issue is fixed, and CI passed on ed622ec. I found no remaining blocking issue. Review assisted by Codex; the maintainer has selected this implementation and authorized merging it.

@Astro-Han
Astro-Han merged commit c220ba1 into apache:main Sep 12, 2026
1 check passed
@ying-hua
ying-hua deleted the fix/dingtalk-oto-send-route branch September 12, 2026 12:42
ying-hua added a commit to ying-hua/maka that referenced this pull request Sep 29, 2026
apache#5112 merged on September 12, but the guide still said
direct replies could not work, that senderStaffId was never captured,
and that the fix was open. That would publish false setup guidance.

The DingTalk section now documents the merged scheme: the route is
stamped at receive time, group:<conversationId> for groups and
oto:<senderStaffId> for direct chats, with unstamped scheduled-task
targets still routed by shape. It keeps the one real dead end: a direct
message without senderStaffId falls back to its bare conversation ID and
a reply to it is rejected at the group endpoint.

The three-way live send table stays, reframed as the evidence for why
direct replies address the staff ID. The verification wording is kept
exact: the request the merged bridge now sends was delivered live, but
the merged bridge itself has not been re-run, and group replies remain
unexercised.

Also stops describing sessionWebhook as working for both conversation
kinds. That came from DingTalk's documentation, not from a send made
here, so it is now marked untested.

Refs apache#3894

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
ying-hua added a commit to ying-hua/maka that referenced this pull request Oct 30, 2026
Rebased onto current main, which renamed the per-channel status reasons
to snake_case. Updated the three the guide quotes:
missing-slack-tokens to slack_tokens_missing,
missing-feishu-credentials to feishu_credentials_missing, and the
generic no-credentials to wecom_credentials_missing now that each
channel carries its own code.

Re-derived the capability matrix against the new tree; every row still
maps to the same bridges, and the load-bearing constants are unchanged
(Discord's 2000-character limit, Telegram's 4000 UTF-16 units and
message-only allowed_updates, QQ's fatal 4004/4014 closes, Slack
promoting to operational on connect).

Points the DingTalk defect at apache#5112, which replaces the
prefix guess with chat IDs stamped at receive time. That fix is not on
main yet, so the section still documents the broken behaviour and says
what to rewrite once it lands.

Refs apache#3894

Co-Authored-By: Claude Opus 5 <[email protected]>
ying-hua added a commit to ying-hua/maka that referenced this pull request Oct 30, 2026
apache#5112 merged on September 12, but the guide still said
direct replies could not work, that senderStaffId was never captured,
and that the fix was open. That would publish false setup guidance.

The DingTalk section now documents the merged scheme: the route is
stamped at receive time, group:<conversationId> for groups and
oto:<senderStaffId> for direct chats, with unstamped scheduled-task
targets still routed by shape. It keeps the one real dead end: a direct
message without senderStaffId falls back to its bare conversation ID and
a reply to it is rejected at the group endpoint.

The three-way live send table stays, reframed as the evidence for why
direct replies address the staff ID. The verification wording is kept
exact: the request the merged bridge now sends was delivered live, but
the merged bridge itself has not been re-run, and group replies remain
unexercised.

Also stops describing sessionWebhook as working for both conversation
kinds. That came from DingTalk's documentation, not from a send made
here, so it is now marked untested.

Refs apache#3894

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/M Under 500 readable lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(runtime): DingTalk 1:1 replies are unroutable — conversationId misrouted to the group endpoint and senderStaffId is never captured

3 participants