Skip to content

fix(googlechat): sanitize thread resource names in outbound messages - #28153

Closed
asdf618 wants to merge 1 commit into
openclaw:mainfrom
asdf618:fix/googlechat-thread-id-sanitization
Closed

asdf618 wants to merge 1 commit into
openclaw:mainfrom
asdf618:fix/googlechat-thread-id-sanitization

Conversation

@asdf618

@asdf618 asdf618 commented Feb 27, 2026

Copy link
Copy Markdown

When replyToMode is 'off' (or when threadId inherits a message resource name), the Google Chat extension passes strings like spaces/X/messages/Y as thread parameters to the Chat API. The API rejects these with INVALID_ARGUMENT since it expects spaces/X/threads/Y format.

This commit sanitizes thread IDs in three places:

  • channel.ts sendText/sendMedia: drop thread IDs containing /messages/ and prepend spaces/X/threads/ to bare IDs missing the prefix
  • monitor.ts finalizeInboundContext: filter out message.thread.name values containing /messages/ before setting ReplyToId
  • monitor.ts deliverGoogleChatReply: sanitize payload.replyToId before passing to sendGoogleChatMessage, applying the same /messages/ guard and bare-ID prefix logic

Summary

  • Problem: Google Chat's message.thread.name sometimes returns message resource names (spaces/X/messages/Y) instead of thread resource names (spaces/X/threads/Y). When passed as thread to the Chat API, it returns INVALID_ARGUMENT.
  • Why it matters: Outbound message delivery fails intermittently, silently dropping bot replies in both DMs and spaces.
  • What changed: Defensive sanitization in three code paths (sendText, sendMedia, finalizeInboundContext, deliverGoogleChatReply) to discard /messages/-format strings and normalize bare IDs with the correct spaces/X/threads/ prefix.
  • What did NOT change (scope boundary): No changes to the gateway lifecycle, session management, thread session mode, or any non-Google Chat channel. startAccount and replyToMode default are untouched.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

User-visible / Behavior Changes

  • Google Chat outbound replies that previously failed with INVALID_ARGUMENT will now be delivered successfully.
  • No config changes required. No new defaults introduced.

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: Ubuntu 22.04 (remote server)
  • Runtime/container: Node.js v24.13.0
  • Model/provider: Any (bug is in the channel layer, not model)
  • Integration/channel: Google Chat (service account, webhook mode)
  • Relevant config: channels.googlechat.replyToMode: "thread" (also reproducible with "off")

Steps

  1. Configure a Google Chat channel with a service account and webhook
  2. Send a message to the bot in a Google Chat space
  3. The bot receives an inbound event where message.thread.name is spaces/AAAA/threads/BBBB (normal) or spaces/AAAA/messages/CCCC (problematic)
  4. The bot attempts to reply using the thread name as the thread parameter

Expected

  • The reply is delivered successfully, threaded under the original message

Actual

  • When message.thread.name contains /messages/, the Google Chat API returns:
    INVALID_ARGUMENT: The request contains an invalid thread resource name spaces/AAAA/messages/CCCC
  • The reply silently fails

Evidence

  • Trace/log snippets

Gateway log showing the error before the fix:

Error: 3 INVALID_ARGUMENT: The request contains an invalid thread resource name spaces/AAAA/messages/CCCC. at callErrorFromStatus (...) at Object.onReceiveStatus (...)

After applying the patch, all outbound replies in the same space succeed without errors.

Human Verification (required)

  • Verified scenarios: Tested on a live OpenClaw v2026.2.23 → v2026.2.25 deployment with real Google Chat inbound/outbound traffic over several days. Both DM and space (group) threading confirmed working.
  • Edge cases checked: Bare thread IDs without prefix (normalized to spaces/X/threads/ID); message.thread.name with /messages/ format (dropped to undefined); normal spaces/X/threads/Y format (passed through unchanged); undefined/missing thread IDs (no-op).
  • What you did NOT verify: Behavior with replyToMode: "sender" or custom thread session mode. Unit tests not added (no existing test harness for these code paths).

Compatibility / Migration

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

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: Revert the two changed files (extensions/googlechat/src/channel.ts and extensions/googlechat/src/monitor.ts) to their upstream versions
  • Files/config to restore: extensions/googlechat/src/channel.ts, extensions/googlechat/src/monitor.ts
  • Known bad symptoms reviewers should watch for: If thread IDs are being incorrectly dropped (set to undefined), replies would be sent as new top-level messages instead of threaded replies

Risks and Mitigations

  • Risk: Legitimate thread names containing /messages/ could be incorrectly discarded.
    • Mitigation: Google Chat thread resource names always follow the spaces/{space}/threads/{thread} format per the API spec. A valid thread name should never contain /messages/. The guard is conservative — it only drops, never mutates, the string.

@openclaw-barnacle openclaw-barnacle Bot added channel: googlechat Channel integration: googlechat size: S labels Feb 27, 2026
@greptile-apps

greptile-apps Bot commented Feb 27, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds defensive sanitization to prevent INVALID_ARGUMENT errors when Google Chat returns message resource names instead of thread resource names.

Changes:

  • Sanitizes thread IDs in sendText, sendMedia, and deliverGoogleChatReply by dropping /messages/ format and normalizing bare IDs with spaces/X/threads/ prefix
  • Filters out invalid thread names in finalizeInboundContext before setting ReplyToId

Review findings:

  • Sanitization logic is consistent and correctly handles the documented edge cases (message resource names, bare IDs, and properly-formatted thread names)
  • One minor cleanup opportunity: unused variable validThreadId in monitor.ts:652

Confidence Score: 4/5

  • Safe to merge with one minor style cleanup opportunity
  • The fix is well-targeted and defensive, addressing a documented API issue. The sanitization logic is consistent across all three code paths and correctly handles edge cases. One unused variable should be cleaned up but doesn't affect functionality. No security concerns or breaking changes.
  • No files require special attention beyond the minor cleanup noted in comments

Last reviewed commit: b5a0312

@greptile-apps greptile-apps Bot 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.

2 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment thread extensions/googlechat/src/monitor.ts Outdated
@@ -649,6 +649,8 @@ async function processMessageWithPipeline(params: {

const groupSystemPrompt = groupConfigResolved.entry?.systemPrompt?.trim() || undefined;

const validThreadId = message.thread?.name?.includes("/messages/") ? undefined : message.thread?.name;

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.

validThreadId is defined but never used; lines 674-675 duplicate this check inline

Suggested change
const validThreadId = message.thread?.name?.includes("/messages/") ? undefined : message.thread?.name;
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/googlechat/src/monitor.ts
Line: 652

Comment:
`validThreadId` is defined but never used; lines 674-675 duplicate this check inline

```suggestion
```

How can I resolve this? If you propose a fix, please make it concise.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Mar 4, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 18fc247566

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread extensions/googlechat/src/monitor.ts Outdated
@@ -230,6 +230,12 @@ async function processMessageWithPipeline(params: {
body: rawBody,
});

const groupSystemPrompt = groupConfigResolved.entry?.systemPrompt?.trim() || undefined;

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.

P1 Badge Remove undefined thread prompt reassignment

processMessageWithPipeline already destructures groupSystemPrompt from access, but this new assignment redeclares groupSystemPrompt and references groupConfigResolved, which is not defined anywhere in the function. That makes extensions/googlechat/src/monitor.ts fail to parse/type-check, so Google Chat monitor code cannot be built or loaded in environments that include this extension.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Mar 5, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Mar 31, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d4ebbf3d91

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread extensions/googlechat/src/channel.ts Outdated
Comment on lines +278 to +281
let thread = (threadId ?? replyToId ?? undefined) as string | undefined;

if (thread) {
if (thread.includes("/messages/")) {

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.

P2 Badge Coerce thread identifiers before string sanitization

threadId is allowed to be a number in outbound channel contexts (ChannelOutboundContext.threadId), but this new logic casts it to string only at the type level and then immediately calls thread.includes(...). If a numeric threadId reaches Google Chat outbound delivery, sendText/sendMedia will throw a TypeError before sending anything. This turns previously tolerated inputs into hard delivery failures; coerce to a real string (or guard by typeof thread === "string") before using string methods.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Apr 2, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Apr 8, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0e40e589d0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread extensions/googlechat/src/api.ts Outdated
Comment on lines 153 to 154
if (thread && /^spaces\/[^/]+\/threads\/[^/]+$/.test(thread)) {
body.thread = { name: thread };

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.

P2 Badge Reject invalid thread IDs instead of silently dropping them

This new guard turns any non-matching thread into a top-level send instead of an error, which can misroute messages while still returning success. In particular, extensions/googlechat/src/actions.ts passes user-supplied threadId straight through; with this change, malformed/stale values (for example a bare ID or typo) no longer fail fast and instead post to the space root, so automation gets {ok:true} even though the message was delivered to the wrong context. Consider rejecting invalid thread formats (or limiting silent fallback to the specific /messages/ recovery case) so bad thread inputs do not degrade into unintended destinations.

Useful? React with 👍 / 👎.

When replyToId inherits a message resource name, the Google Chat
extension passes strings like 'spaces/X/messages/Y' as thread
parameters to the Chat API. The API rejects these with
INVALID_ARGUMENT since it expects 'spaces/X/threads/Y' format.

This commit sanitizes thread IDs in four places:

- channel.adapters.ts sendText/sendMedia: drop thread IDs containing
  '/messages/' and prepend 'spaces/X/threads/' to bare IDs
- monitor.ts finalizeInboundContext: filter out message.thread.name
  values containing '/messages/' before setting ReplyToId
- monitor.ts deliverGoogleChatReply: sanitize payload.replyToId before
  passing to sendGoogleChatMessage
- api.ts sendGoogleChatMessage: regex guard as defense-in-depth to only
  set body.thread when the value matches spaces/X/threads/Y format
@openclaw-barnacle openclaw-barnacle Bot added size: S and removed size: XS stale Marked as stale due to inactivity labels Apr 9, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Apr 16, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #pr-thunderdome-dangerzone on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

steipete pushed a commit that referenced this pull request Aug 1, 2026
)

Reply routing can hand sendGoogleChatMessage a `thread` that is not a
valid `spaces/{space}/threads/{thread}` resource name — a bare id, a
`spaces/{space}/messages/{message}` name, or a thread from a different
(or wrongly-cased) space. The Chat API rejects the whole request with
`400 INVALID_ARGUMENT`, so the reply is never delivered even though the
agent already produced it (and did any side effects).

Guard the send so the `thread` field and the messageReplyOption fallback
are applied only when the thread is a well-formed name belonging to the
target space; otherwise post to the space as a new thread. Revives the
approach of #28153 (auto-closed as stale) and addresses the failure mode
behind #64313.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 2, 2026
…claw#108324)

Reply routing can hand sendGoogleChatMessage a `thread` that is not a
valid `spaces/{space}/threads/{thread}` resource name — a bare id, a
`spaces/{space}/messages/{message}` name, or a thread from a different
(or wrongly-cased) space. The Chat API rejects the whole request with
`400 INVALID_ARGUMENT`, so the reply is never delivered even though the
agent already produced it (and did any side effects).

Guard the send so the `thread` field and the messageReplyOption fallback
are applied only when the thread is a well-formed name belonging to the
target space; otherwise post to the space as a new thread. Revives the
approach of openclaw#28153 (auto-closed as stale) and addresses the failure mode
behind openclaw#64313.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: googlechat Channel integration: googlechat size: S stale Marked as stale due to inactivity

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant