Repository navigation
feat(collaboration): add Google Chat messaging platform (#790) - #1337
Conversation
|
All contributors have signed the CLA. ✅ |
|
I have read the CLA Document and I hereby sign the CLA |
|
Thanks for working on this. switch-core now runs as several pods that share one Postgres database (#1307), and horizontal scaling support is essential before we can move this forward. Here is where this PR breaks with more than one pod. Workspace Events subscriptions (4-hour TTL) are created only on The dedupe between the interaction event and the CloudEvent for the same message is in memory too ( Suggested fix: on start, have the owning pod list the spaces it is in (or read them from a database row) and create or renew their subscriptions. Claim Pub/Sub messages through For context: work that must run once, like a bridge's connection to its platform or a scheduler, belongs to one pod at a time, and it can move to another pod on any deploy. The other pods run a quiet copy that serves requests and webhooks. So anything another pod needs has to live in the database, or travel through NOTIFY, not in memory. |
|
Hi @abeldantas, thank you for the review and clear guidance! I have updated PR #1337 to make the Google Chat collaboration bridge fully horizontally scalable and multi-pod safe across pods sharing Postgres (#1307):
Pushed in commit |
petr-sandbox
left a comment
There was a problem hiding this comment.
Review of the Google Chat bridge. Findings were read against the PR head; nothing was run.
| logger.warning( | ||
| "Failed to fetch message for CloudEvent (%s): %s", message_name, exc | ||
| ) | ||
| return True |
There was a problem hiding this comment.
If get_message fails (5xx, network, 401) this returns True, so the Pub/Sub message is acked and the inbound message is dropped with only a warning. Return False here so it is redelivered. The claim is made later, at line 674, so a retry would not be dropped as a duplicate.
There was a problem hiding this comment.
Fixed in 9d1472a: a failed get_message now returns False, so the Pub/Sub message stays unacked and is redelivered. Test: test_failed_message_fetch_is_left_for_redelivery (the redelivery is not dropped as a duplicate).
| await self.on_message( | ||
| InboundMessage( | ||
| channel_id=space_name, | ||
| channel_type="channel_public", |
There was a problem hiding this comment.
This path shares its dedupe key (the message name) with the interaction path, but builds a much thinner InboundMessage: channel_type is hard-coded to channel_public (a DM is mis-typed), and there is no self_mention_token, no attachments, and no !command parsing. The bot's @Name also stays in the text. An @mention produces both a MESSAGE interaction and a message.v1.created event, so whichever is claimed first decides how it is handled. Consider sharing one builder between the two paths.
There was a problem hiding this comment.
Fixed in 9d1472a: both paths now go through one _dispatch_message, so channel type (read from the space, or fetched with get_space when the payload doesn't say), self-mention, attachments and !command parsing are the same whichever delivery is claimed first. Test: test_workspace_event_builds_the_same_message_as_interaction.
| result = re.sub(rf"@?{re.escape(disp_name)}\b", "", result) | ||
|
|
||
| # Generic clean-up of leading @-mention of the bot | ||
| result = re.sub(r"^@\w+\s*", "", result) |
There was a problem hiding this comment.
This removes any leading @word, not only the bot mention, which contradicts the docstring about preserving @agent routing. With no argumentText (the Workspace Events path), @reviewer-agent please check becomes -agent please check, because \w does not match -. Only strip the mention identified from annotations.
There was a problem hiding this comment.
Fixed in 9d1472a: the generic ^@\w+ strip is gone. Only spans that annotations identify as an app mention are cut (by startIndex/length, falling back to the display name), so @reviewer-agent please check survives. Test: test_strip_bot_mention_leaves_other_mentions.
| ) -> None: | ||
| """Remove membership (leave a space).""" | ||
| space_name = self._normalize_space_name(space_id) | ||
| url = f"{self.chat_api_base}/{space_name}/members/{member_name}" |
There was a problem hiding this comment.
retire_channel passes users/app, so this URL becomes .../members/users/app. The Chat API name for the calling app is members/app. The non-2xx case is also only logged, so retire_channel returns left while the bot stays in the space. Raise on failure, as the fail-loud rule in CLAUDE.md asks.
There was a problem hiding this comment.
Fixed in 9d1472a: replaced with leave_space, which deletes {space}/members/app and raises BridgeOperationError on a non-2xx, so retire_channel reports a failure instead of left. Test: test_retire_channel_leaves_as_app_and_fails_loud.
|
|
||
| formatted = self._render_outbound(body_text) | ||
|
|
||
| # Maintainer-approved outbound attachment text-and-link fallback |
There was a problem hiding this comment.
Outbound attachments are never uploaded. The user only sees a filename, size and mimetype line, with no link, so the file contents are lost without any signal. The comment says "text-and-link" but there is no link. Please upload the file, or raise or warn visibly. The comment also reads as a note about the change ("Maintainer-approved..."), which CLAUDE.md asks us to avoid.
There was a problem hiding this comment.
Fixed in 9d1472a: the attachments argument on send_message was never passed by core (files go through send_attachment(s)), so the block was dead code and is removed. Outbound files now get the base adapter's disclosed note ("sent an attachment that couldn't be relayed: "), and the docs page says files are not uploaded. Native upload needs user OAuth, so it's left for a follow-up.
| if space.get("type") == "DM" or space.get("singleUserBotDm"): | ||
| return "direct" | ||
| return "channel_public" | ||
| except Exception: |
There was a problem hiding this comment.
The bare except Exception returns channel_public silently. If get_space fails with a 403, 5xx or network error, a DM is treated as a public channel with no log line. At least log a warning, or let the error propagate.
There was a problem hiding this comment.
Fixed in 9d1472a: get_channel_type no longer catches anything; Chat API errors propagate. Test: test_get_channel_type_does_not_hide_failures.
| ack_id = msg_item.get("ackId") | ||
| if not ack_id: | ||
| continue | ||
| # Process message with ack-after-write |
There was a problem hiding this comment.
The ack-after-write comments here and at line 317 don't match behavior. _claim_event commits the receipt before the handler runs (by design: MessagingEventReceipt chooses at-most-once). If a handler raises, the message stays unacked, but the redelivery is then dropped as a duplicate (claimed=False) and acked. Retry never works. Either ack and log an error when a handler fails, or release the claim so a retry can run.
Separately, only the message being processed is in _inflight_ack_ids. The other messages in a batch of 10 are not extended while they wait their turn, and the extender runs every 20s. Add the whole batch to _inflight_ack_ids up front, and check that ACK_EXTENSION_INTERVAL is shorter than the subscription's ack deadline.
There was a problem hiding this comment.
Fixed in 9d1472a, going with the first option since receipts are at-most-once by design: a handler failure after the claim is logged at error level and the message acked; the receipt stays unhandled, which is how a lost event shows up. Failures before the claim (fetch, receipt-store errors) still leave the message unacked for redelivery. The misleading ack-after-write comments are gone.
The whole pulled batch is now added to _inflight_ack_ids and has its deadline extended to 60s right after the pull, so the subscription's own ack deadline (10s by default) no longer matters; the extender keeps it at 60s every 20s. Tests: test_handler_failure_after_claim_is_acked_and_logged, test_whole_batch_deadline_extended_on_pull.
| session, | ||
| platform="google_chat", | ||
| external_event_id=dedupe_key, | ||
| ) |
There was a problem hiding this comment.
The receipt key has no bridge_id. The unique index is (tenant_id, platform, external_event_id). If a tenant has two Google Chat bridges that see the same message, the second claims nothing and silently drops it. self.bridge_id is stored on the consumer but unused. Prefixing the key with the bridge id would fix it.
There was a problem hiding this comment.
Fixed in 9d1472a: receipt keys are now {bridge_id}:{key}. A consumer with a database but no bridge id raises rather than claiming unscoped keys, and a receipt-store error now propagates instead of silently falling back to in-memory dedupe. Test: test_receipts_are_scoped_to_the_bridge.
| "Could not patch settled card on %s: %s", message_name, exc | ||
| ) | ||
|
|
||
| await self._mark_handled(receipt_id) |
There was a problem hiding this comment.
Every click is settled here, whatever it was or however core handled it. (1) A press on the turn-activity Stop button (INTERRUPT_ACTION) replaces the activity card with a settled approval card. (2) on_interaction returns nothing, so a refused press (an unauthorized user, or TURN_NOT_RUNNING) still burns the token and disables the buttons for everyone. Only settle the card when core accepted an approval answer, and skip the Stop action.
There was a problem hiding this comment.
Fixed in 9d1472a: the consumer no longer settles or patches the card and no longer claims the token. A click is passed to core as-is, and core redraws the card through update_rich when it accepts an answer (render_request_card already draws the settled state). Only a redelivery of the same Pub/Sub message is deduped, so a refused press or the Stop button leaves the card untouched. render_settled_approval_card is removed. Test: test_card_click_is_handed_to_core_without_settling.
…receipt store deduplication
- Leave a space as `members/app` and raise when the Chat API refuses, so retire_channel no longer reports `left` while the app stays in the space. - Read Workspace Events messages through the same builder as interaction events: channel type from the space, self-mention, attachments and `!command` parsing no longer depend on which delivery is claimed first. - Strip only the app mention identified by annotations; other `@name` mentions are kept for routing. - Leave a CloudEvent unacked when fetching its message fails, so it is redelivered rather than dropped. - A failure after a receipt is claimed is logged as an error and acked, since the claim makes a retry impossible. The whole pulled batch has its ack deadline extended up front and stays under the extender. - Scope receipt keys by bridge id; a receipt-store error propagates instead of falling back to in-memory dedupe. - Card clicks are passed to core without settling the card or burning the token; core redraws the card through update_rich when it accepts an answer. - get_channel_type lets Chat API errors propagate. - Drop the unused `attachments` argument on send_message; outbound files use the base adapter's disclosed "couldn't be relayed" note. - Match create_channel to the current PlatformAdapter signature. Co-Authored-By: Claude Opus 5.5 <[email protected]>
What this changes
Adds Google Chat as a supported collaboration messaging platform (Issue #790). Users can now connect a Google Chat app in Switch Console to enable bidirectional messaging, thread mapping, Cards v2 approvals, and command routing between Switch AI agents and Google Workspace spaces/DMs.
Transport is implemented via Cloud Pub/Sub pull subscriptions combined with Google Workspace Events API space subscriptions (
keeps_quiet_unless_listening = True), ensuring ordinary unaddressed space messages reach the room while only the lease-holding pod pulls and renews subscriptions.Closes #790
How it was tested
verify_credentials).ADDED_TO_SPACE,MESSAGE,CARD_CLICKED,SLASH_COMMAND) and Workspace CloudEvents (message.v1.created,membership.v1.created).@mentioninteraction events and Workspacemessage.v1.createdCloudEvents for the same message resource.uv run --project core ruff format --checkuv run --project core ruff checkuv run --project core mypy --config-file core/pyproject.toml core/switch_core/bridges/collaboration/google_chat/ core/switch_core/bridges/collaboration/platforms.pyAdding or changing a messaging platform
Platform: Google Chat (
google_chat)How it connects: dials out (Cloud Pub/Sub pull subscription + Google Workspace Events subscriptions)
Adapter test summary:
Video:
The end-to-end demo video below was headlessly recorded using Playwright, verifying the full Done-When flow against the adapter:
https://github.com/Deepak-Kambala/switch/releases/download/v-demo/google-chat-demo.mp4
Checks:
platforms.pyand its docs page (with 1-line table updates intest_channel_retirement.pyandtest_room_delete_channel_outcome.pyto assert the registeredgoogle_chatchannel retirement behavior)docs/messaging-platforms/google-chat.mdis written