Skip to content

fix(slack): detect implicit thread mention when bot participated but did not start thread [upstreamed] - #9

Closed
zeroaltitude wants to merge 7 commits into
mainfrom
fix/slack-implicit-thread-mention
Closed

zeroaltitude wants to merge 7 commits into
mainfrom
fix/slack-implicit-thread-mention

Conversation

@zeroaltitude

@zeroaltitude zeroaltitude commented Mar 1, 2026 •

Copy link
Copy Markdown
Owner

Upstream: openclaw#30255

fix(slack): detect implicit thread mention when bot participated but did not start thread

When requireMention is enabled, thread replies were only routed to the bot if it authored the parent message. This missed the common case where a user @mentions the bot in a channel, the bot replies in-thread, and subsequent thread replies should route without repeated @mentions.

Summary

  • Problem: In channels with requireMention: true, follow-up thread replies were silently dropped unless the bot authored the parent message — even if the bot had already replied in the thread.
  • Why it matters: Users expect the bot to stay engaged in a thread once it has participated. Requiring a fresh @mention on every reply is unnatural and confusing.
  • What changed: Thread replies now check for prior bot participation via (1) existing thread session (cheap file read), then (2) Slack conversations.replies API (lightweight fallback, capped at 50 messages). Both checks are gated behind wouldRequireMention to avoid unnecessary work in channels that do not require mentions.
  • What did NOT change: Direct messages, parent-author detection, and non-threaded messages are unaffected. The conversations.replies API call only fires when there is no thread session and mention would otherwise be required.

Change Type

  • Bug fix

Scope

  • Integrations

User-visible / Behavior Changes

In Slack channels with requireMention: true (or defaultRequireMention: true), thread replies now route to the bot when the bot previously participated in the thread, even if the bot did not author the parent message. Previously these replies were silently dropped.

Security Impact

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? Yes — conversations.replies API call added as fallback
  • Command/tool execution surface changed? No
  • Data access scope changed? No
  • Risk + mitigation: The new conversations.replies call reads thread messages to detect bot participation. It only fires when (a) in a room with requireMention, (b) bot is not the parent author, (c) no thread session exists. Capped at 50 messages. Failure is caught silently (falls through to require explicit mention).

Evidence

  • 3 new test cases covering: session-based detection, API-based detection, and negative (no participation → skip)

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Failure Recovery

  • The conversations.replies fallback silently catches errors — if the API call fails, behavior reverts to the old require-explicit-mention path.
  • To fully disable: revert this commit.

Risks and Mitigations

  • Risk: Additional Slack API call per unrecognized thread reply in requireMention channels.
    • Mitigation: Only fires when no thread session exists (most threads will have one after the first exchange). Gated behind wouldRequireMention. Capped at 50 messages. Failure is silent.

… start thread

When requireMention is enabled, thread replies were only routed to the
bot if it authored the parent message. This missed the common case where
a user @mentions the bot in a channel, the bot replies in-thread, and
subsequent thread replies should route without repeated @mentions.

Now checks for bot participation via:
1. Existing thread session (cheap file read)
2. Slack conversations.replies API (lightweight fallback)

Both checks are gated behind wouldRequireMention to avoid unnecessary
API calls in channels that don't require mentions.

Includes 3 test cases covering session-based, API-based, and negative
(no participation) scenarios.

Co-authored-by: Eddie Abrams <[email protected]>
@zeroaltitude zeroaltitude changed the title fix(slack): implicit thread mention when bot participated but did not… fix(slack): detect implicit thread mention when bot participated but did not start thread Mar 1, 2026
zeroaltitude and others added 5 commits February 28, 2026 20:21
The mock appClient objects only implement conversations.replies,
so TypeScript rejects a direct cast to App["client"]. Cast through
unknown first to satisfy the type checker.
Bot messages in Slack threads can appear with only bot_id (no user
field). Thread the bot's bot_id from auth.test through the monitor
context so the conversations.replies participation check matches
both m.user === botUserId and m.bot_id === botId.
If the message already has an explicit @mention, the participation
check is unnecessary — it would pass mention-gating regardless.
Gate with !wasMentioned to avoid the extra session read and
conversations.replies API call.
In busy channels with requireMention, every unmentioned thread reply
in a non-bot thread was calling conversations.replies repeatedly
just to get the same negative result. Add an in-memory Set on the
monitor context that caches 'no bot participation' results so the
API is only called once per thread.

Includes test verifying the cache prevents repeated API calls.
Replace unbounded Set<string> with createDedupeCache (10 min TTL,
1000 max entries) so long-lived Slack monitors don't accumulate
thread keys indefinitely. Also handles staleness — entries expire,
allowing re-checks if bot participation appears later.

Addresses Codex review feedback on openclaw#30255.
@zeroaltitude zeroaltitude changed the title fix(slack): detect implicit thread mention when bot participated but did not start thread fix(slack): detect implicit thread mention when bot participated but did not start thread [upstreamed] Mar 1, 2026
@zeroaltitude

Copy link
Copy Markdown
Owner Author

Superceded!

@zeroaltitude
zeroaltitude deleted the fix/slack-implicit-thread-mention branch March 2, 2026 21:46
zeroaltitude pushed a commit that referenced this pull request Apr 2, 2026
* feat: add QQ Bot channel extension

* fix(qqbot): add setupWizard to runtime plugin for onboard re-entry

* fix: fix review

* fix: fix review

* chore: sync lockfile and config-docs baseline for qqbot extension

* refactor: 移除图床服务器相关代码

* fix

* docs: 新增 QQ Bot 插件文档并修正链接路径

* refactor: remove credential backup functionality and update setup logic

- Deleted the credential backup module to streamline the codebase.
- Updated the setup surface to handle client secrets more robustly, allowing for configured secret inputs.
- Simplified slash commands by removing unused hot upgrade compatibility checks and related functions.
- Adjusted types to use SecretInput for client secrets in QQBot configuration.
- Modified bundled plugin metadata to allow additional properties in the config schema.

* feat: 添加本地媒体路径解析功能,修正 QQBot 媒体路径处理

* feat: 添加本地媒体路径解析功能,修正 QQBot 媒体路径处理

* feat: remove qqbot-media and qqbot-remind skills, add tests for config and setup

- Deleted the qqbot-media and qqbot-remind skills documentation files.
- Added unit tests for qqbot configuration and setup processes, ensuring proper handling of SecretRef-backed credentials and account configurations.
- Implemented tests for local media path remapping, verifying correct resolution of media file paths.
- Removed obsolete channel and remind tools, streamlining the codebase.

* feat: 更新 QQBot 配置模式,添加音频格式和账户定义

* feat: 添加 QQBot 频道管理和定时提醒技能,更新媒体路径解析功能

* fix

* feat: 添加 /bot-upgrade 指令以查看 QQBot 插件升级指引

* feat: update reminder and qq channel skills

* feat: 更新remind工具投递目标地址格式

* feat: Refactor QQBot payload handling and improve code documentation

- Simplified and clarified the structure of payload interfaces for Cron reminders and media messages.
- Enhanced the parsing function to provide clearer error messages and improved validation.
- Updated platform utility functions for better cross-platform compatibility and clearer documentation.
- Improved text parsing utilities for better readability and consistency in emoji representation.
- Optimized upload cache management with clearer comments and reduced redundancy.
- Integrated QQBot plugin into the bundled channel plugins and updated metadata for installation.

* OK apps/macos/Sources/OpenClaw/HostEnvSecurityPolicy.generated.swift

> [email protected] check:bundled-channel-config-metadata /Users/yuehuali/code/PR/openclaw
> node --import tsx scripts/generate-bundled-channel-config-metadata.ts --check

[bundled-channel-config-metadata] stale generated output at src/config/bundled-channel-config-metadata.generated.ts
 ELIFECYCLE  Command failed with exit code 1.
 ELIFECYCLE  Command failed with exit code 1.

* feat: 添加 QQBot 渠道配置及相关账户设置

* fix(qqbot): resolve 14 high-priority bugs from PR openclaw#52986 review

DM routing (7 fixes):
- #1: DM slash-command replies use sendDmMessage(guildId) instead of sendC2CMessage(senderId)
- #2: DM qualifiedTarget uses qqbot:dm:${guildId} instead of qqbot:c2c:${senderId}
- #3: sendTextChunks adds DM branch
- #4: sendMarkdownReply adds DM branch for text and Base64 images
- #5: parseAndSendMediaTags maps DM to targetType:dm + guildId
- #6: sendTextToTarget DM branch uses sendDmMessage; MessageTarget adds guildId field
- #7: handleImage/Audio/Video/FilePayload add DM branches

Other high-priority fixes:
- #8: Fix sendC2CVoiceMessage/sendGroupVoiceMessage parameter misalignment
- #9: broadcastMessage uses groupOpenid instead of member_openid for group users
- #10: Unify KnownUser storage - proactive.ts delegates to known-users.ts
- #11: Remove invalid recordKnownUser calls for guild/DM users
- #12: sendGroupMessage uses sendAndNotify to trigger onMessageSent hook
- #13: sendPhoto channel unsupported returns error field
- #14: sendTextAfterMedia adds channel and dm branches

Type fixes:
- DeliverEventContext adds guildId field
- MediaTargetContext.targetType adds dm variant
- sendPlainTextReply imgMediaTarget adds DM branch

* fix(qqbot): resolve 2 blockers + 7 medium-priority bugs from PR openclaw#52986 review

Blocker-1: Remove unused dmPolicy config knob
- dmPolicy was declared in schema/types/plugin.json but never consumed at runtime
- Removed from config-schema.ts, types.ts, and openclaw.plugin.json
- allowFrom remains active (already wired into framework command-auth)

Blocker-2: Gate sensitive slash commands with allowFrom authorization
- SlashCommand interface adds requireAuth?: boolean
- SlashCommandContext adds commandAuthorized: boolean
- /bot-logs set to requireAuth: true (reads local log files)
- matchSlashCommand rejects unauthorized senders for requireAuth commands
- trySlashCommandOrEnqueue computes commandAuthorized from allowFrom config

Medium-priority fixes:
- #15: Strip non-HTTP/non-local markdown image tags to prevent path leakage
- #16: applyQQBotAccountConfig clears clientSecret when setting clientSecretFile and vice versa
- #17: getAdminMarkerFile sanitizes accountId to prevent path traversal
- #18: URGENT_COMMANDS uses exact match instead of startsWith prefix match
- #19: isCronExpression validates each token starts with a cron-valid character
- #20: --token format validation rejects malformed input without colon separator
- #21: resolveDefaultQQBotAccountId checks QQBOT_APP_ID environment variable

* test(qqbot): add focused tests for slash command authorization path

- Unauthorized sender rejected for /bot-logs (requireAuth: true)
- Authorized sender allowed for /bot-logs
- Non-requireAuth commands (/bot-ping, /bot-help, /bot-version) work for all senders
- Unknown slash commands return null (passthrough)
- Non-slash messages return null
- Usage query (/bot-logs ?) also gated by auth check

* fix(qqbot): align global TTS fallback with framework config resolution

- Extract isGlobalTTSAvailable to utils/audio-convert.ts, mirroring core
  resolveTtsConfig logic: check auto !== 'off', fall back to legacy
  enabled boolean, default to off when neither is set.
- Add pre-check in reply-dispatcher before calling globalTextToSpeech to
  avoid unnecessary TTS calls and noisy error logs when TTS is not
  configured.
- Remove inline as any casts; use OpenClawConfig type throughout.
- Refactor handleAudioPayload into flat early-return structure with
  unified send path (plugin TTS → global fallback → send).

* fix(qqbot): break ESM circular dependency causing multi-account startup crash

The bundled gateway chunk had a circular static import on the channel
chunk (gateway -> outbound-deliver -> channel, while channel dynamically
imports gateway). When two accounts start concurrently via Promise.all,
the first dynamic import triggers module graph evaluation; the circular
reference causes api exports (including runDiagnostics) to resolve as
undefined before the module finishes evaluating.

Fix: extract chunkText and TEXT_CHUNK_LIMIT from channel.ts into a new
text-utils.ts leaf module. outbound-deliver.ts now imports from
text-utils.ts, breaking the cycle. channel.ts re-exports for backward
compatibility.

* fix(qqbot): serialize gateway module import to prevent multi-account startup race

When multiple accounts start concurrently via Promise.all, each calls
await import('./gateway.js') independently. Due to ESM circular
dependencies in the bundled output, the first import can resolve
transitive exports as undefined before module evaluation completes.

Fix: cache the dynamic import promise in a module-level variable so all
concurrent startAccount calls share the same import, ensuring the
gateway module is fully evaluated before any account uses it.

* refactor(qqbot): remove startup greeting logic

Remove getStartupGreetingPlan and related startup greeting delivery:
- Delete startup-greeting.ts (greeting plan, marker persistence)
- Delete admin-resolver.ts (admin resolution, greeting dispatch)
- Remove startup greeting calls from gateway READY/RESUMED handlers
- Remove isFirstReadyGlobal flag and adminCtx

* fix(qqbot): skip octal escape decoding for Windows local paths

Windows paths like C:\Users\1\file.txt contain backslash-digit sequences
that were incorrectly matched as octal escape sequences and decoded,
corrupting the file path. Detect Windows local paths (drive letter or UNC
prefix) and skip the octal decoding step for them.

* fix bot issue

* feat: 支持 TTS 自动开关并清理配置中的 clientSecretFile

* docs: 添加 QQBot 配置和消息处理的设计说明

* rebase

* fix(qqbot): align slash-command auth with shared command-auth model

Route requireAuth:true slash commands (e.g. /bot-logs) through the
framework's api.registerCommand() so resolveCommandAuthorization()
applies commands.allowFrom.qqbot precedence and qqbot: prefix
normalization before any handler runs.

- slash-commands.ts: registerCommand() now auto-routes by requireAuth
  into two maps (commands / frameworkCommands); getFrameworkCommands()
  exports the auth-required set for framework registration; bot-help
  lists both maps
- index.ts: registerFull() iterates getFrameworkCommands() and calls
  api.registerCommand() for each; handler derives msgType from ctx.from,
  sends file attachments via sendDocument, supports multi-account via
  ctx.accountId
- gateway.ts (inbound): replace raw allowFrom string comparison with
  qqbotPlugin.config.formatAllowFrom() to strip qqbot: prefix and
  uppercase before matching event.senderId
- gateway.ts (pre-dispatch): remove stale auth computation; commandAuthorized
  is true (requireAuth:true commands never reach matchSlashCommand)
- command-auth.test.ts: add regression tests for qqbot: prefix
  normalization in the inbound commandAuthorized computation
- slash-commands.test.ts: update /bot-logs tests to expect null
  (command routed to framework, not in local registry)

* rebase and solve conflict

* fix(qqbot): preserve mixed env setup credentials

---------

Co-authored-by: yuehuali <[email protected]>
Co-authored-by: walli <[email protected]>
Co-authored-by: WideLee <[email protected]>
Co-authored-by: Frank Yang <[email protected]>
zeroaltitude pushed a commit that referenced this pull request Sep 5, 2026
…e text starts with a bidi mark (openclaw#137474)

* fix(ui): keep RTL chat messages right-aligned when they start with a bidi control

detectTextDirection() scans for the first strong character but only skipped
whitespace, punctuation and symbols. Unicode format characters (general
category Cf) such as RLM (U+200F) and RLI (U+2067) fell through to the script
test, matched no RTL script, and forced the entire message to dir="ltr".

Explicit directional controls now decide the direction outright, mirroring the
explicit-formatting step of UAX #9, and any remaining Cf characters are stepped
over so they cannot mask the first strong character behind them.

This matters because OpenClaw already emits these controls itself:
src/tui/tui-formatters.ts wraps RTL runs in RLI ... PDI, so text produced by
the project's own sanitizer rendered left-to-right in the Control UI.

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

* refactor(ui): fold bidi controls into the direction detector's skip set

Builds on Ariel's fix for leading bidi controls and absorbs it into the
owner instead of layering a fourth branch on top.

`detectTextDirection` carried a `skipPattern` parameter that no caller has
ever passed: all seven call sites in ui/src/pages/chat/components use the
default. That unused seam is the structure the bug hid in, because the skip
set it defaulted to was incomplete and nobody owned it. Dropping the
parameter lets the neutral-format characters join the same named class as
whitespace, punctuation, and symbols, so there is one skip set instead of a
parameter plus a separate format-character branch.

Behavior is identical to the previous revision across all 25 table cases;
9 of them are red on pre-fix code.

Production net drops from +32 to +17 lines; tests from +27 to +13 while
growing from 8 cases to 25, adding PDF (U+202C) and the full RLI...PDI
wrapper shape.

Formatting proof: oxfmt run on both files from an installed checkout;
the worktree has no node_modules so the pre-commit formatter hook was
bypassed after that separate proof.

* test(ui): sweep the whole Cf family in the direction detector

An audit of the leading-format-character behavior reported that eight code
points still resolved left-to-right: U+0600-U+0604, U+070F, U+0890, U+0891.
Sweeping all 170 Cf code points against the detector does not reproduce that:
each of the eight resolves rtl in front of a strong RTL letter, and against
pre-fix code the whole sweep shows zero regressions and 312 fixes. The report
does not hold, but the coverage gap behind it was real, so this pins it.

Adds per-code-point cases for the eight, the Arabic-Indic digit follow, and
the one place behavior does differ from pre-fix code: an Arabic number sign
followed by an ASCII digit contains no strong character at all, so first-strong
finds nothing and the ltr default stands where pre-fix code answered rtl on
sight. That is the correct reading and is now deliberate rather than incidental.

Adds a property sweep over every Cf code point so a skip class that stops
covering part of the family fails here instead of in a rendered message.
Enumerated cases only pin the characters someone thought of.

No production change: the skip class is already the \p{Cf} property class
rather than an enumerated list, which is what covers all eight.
Sweep costs 18ms. Fails on pre-fix code for the intended reason.

---------

Co-authored-by: Ariel <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: vyctorbrzezowski <[email protected]>
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