Skip to content

feat(collaboration): add Google Chat messaging platform (#790) - #1337

Merged
petr-sandbox merged 4 commits into
sandbox-quantum:mainfrom
Deepak-Kambala:main
Nov 12, 2026
Merged

petr-sandbox merged 4 commits into
sandbox-quantum:mainfrom
Deepak-Kambala:main

Conversation

@Deepak-Kambala

@Deepak-Kambala Deepak-Kambala commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Ran automated unit test suite mocking Google Chat REST API, Cloud Pub/Sub pull/ack, and Workspace Events API:
    • Service account JSON validation and OAuth token minting (verify_credentials).
    • Dual parser handling of Chat App interaction events (ADDED_TO_SPACE, MESSAGE, CARD_CLICKED, SLASH_COMMAND) and Workspace CloudEvents (message.v1.created, membership.v1.created).
    • Deduplication between @mention interaction events and Workspace message.v1.created CloudEvents for the same message resource.
    • Multi-pod lease safety and Pub/Sub ack-after-write with ack deadline extension and redelivery on failure.
    • Cards v2 interactive approvals with single-winner/replay protection and card patching.
    • Free-text question fallback and outbound attachment text-and-link fallback.
    • Long message splitting (<32KB) preserving code fences.
  • Ran repo checks:
    • uv run --project core ruff format --check
    • uv run --project core ruff check
    • uv run --project core mypy --config-file core/pyproject.toml core/switch_core/bridges/collaboration/google_chat/ core/switch_core/bridges/collaboration/platforms.py

Adding 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:

============================= test session starts ==============================
platform darwin -- Python 3.13.9, pytest-9.0.3, pluggy-1.6.0
rootdir: /Users/deepakkambala/Desktop/switch/core
configfile: pyproject.toml
plugins: xdist-3.8.0, split-0.11.0, timeout-2.4.0, asyncio-1.3.0, anyio-4.13.0
asyncio: mode=Mode.AUTO, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function
collecting ... collected 27 items

core/tests/switch_core/bridges/collaboration/test_google_chat_adapter.py . [  3%]
..........................                                               [100%]

============================== 27 passed in 0.39s ==============================

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

  • the platform in Switch Console's "Connect a messaging app" list, with its own name and icon
  • filling in its connect form and connecting it
  • webhook platforms only: the address from the "connected" step pasted into the platform (N/A — dials out via Pub/Sub pull)
  • an agent's message reaching the platform
  • a message sent on the platform reaching the room, and the agent replying
  • an approval card answered from the platform, and Switch showing it was answered from your platform

Checks:

  • Nothing changed outside the platform's adapter folder, its line in platforms.py and its docs page (with 1-line table updates in test_channel_retirement.py and test_room_delete_channel_outcome.py to assert the registered google_chat channel retirement behavior)
  • What the platform can't do is declared on the adapter (channel creation, user search, reactions, custom URL schemes)
  • The docs page docs/messaging-platforms/google-chat.md is written

@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

All contributors have signed the CLA. ✅
Posted by the CLA Assistant Lite bot.

@Deepak-Kambala

Copy link
Copy Markdown
Contributor Author

I have read the CLA Document and I hereby sign the CLA

@abeldantas

Copy link
Copy Markdown
Collaborator

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 ADDED_TO_SPACE and tracked only in the owning pod's memory, which is what the renewal loop walks (google_chat/subscriptions.py:39, 83-147). After the bridge moves to another pod, the new owner has nothing to renew, so within 4 hours unaddressed messages stop arriving in every space it had joined.

The dedupe between the interaction event and the CloudEvent for the same message is in memory too (consumer.py:81, 135), and it's lost on a handover.

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 MessagingEventReceiptStore, keyed by message name. The Pub/Sub pull and the renewal are already gated on self._listening, which is right.

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.

@Deepak-Kambala

Deepak-Kambala commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor Author

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):

  1. Workspace Events Subscriptions Lifecycle across Handovers:

    • Added list_workspace_events_subscriptions to client.py.
    • In subscriptions.py, added reconcile_subscriptions() which runs on startup of the renewal loop when holding the lease (self._listening=True). It discovers active subscriptions already registered in Google Workspace Events API and adopts them into renewal tracking.
    • It lists joined spaces via client.list_spaces() and ensures subscriptions exist for all of them.
    • In adapter.py, implemented ensure_channel_subscriptions(channels) (invoked by collaboration_core.py on startup from Postgres room_store) to guarantee database-backed rooms/channels are subscribed and tracked in the renewal loop.
    • Handled HTTP 409 (ALREADY_EXISTS) in ensure_space_subscription to gracefully adopt and renew existing subscriptions rather than failing.
  2. Cross-Pod Deduplication via MessagingEventReceiptStore:

    • Added set_session_factory to PlatformAdapter and wired adapter.set_session_factory(self._session_factory) in lifecycle_service.py.
    • In consumer.py, replaced in-memory deduplication with MessagingEventReceiptStore.claim() in a tenant_session, keyed by message resource name (spaces/{space}/messages/{message}).
    • Claims are committed immediately before dispatching to release the unique index lock. Concurrent deliveries, retries, and handover deliveries find the receipt already claimed and are immediately acknowledged and dropped.
    • Dispatched events mark the receipt as handled and prune expired rows.
    • Standalone unit tests without a database gracefully fall back to in-memory deduplication.
  3. Multi-Pod Verification & Test Coverage:

    • Added test_subscription_adoption_and_reconciliation_on_startup_and_handoff verifying that after failover, the successor pod adopts existing Workspace Events subscriptions, creates subscriptions for joined spaces and database rooms, and maintains renewals.
    • Added test_lease_handoff_with_shared_receipt_store_prevents_duplicate simulating two pods sharing a receipt store where Pod B drops redelivered interaction events and CloudEvents already processed by Pod A.
    • All 29 unit tests pass, and ruff check, ruff format --check, and mypy pass with 0 diagnostics.

Pushed in commit 02e07245. Ready for re-review!

@petr-sandbox petr-sandbox left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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}"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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,
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Deepak-Kambala and others added 4 commits November 12, 2026 07:25
- 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]>

@petr-sandbox petr-sandbox left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Very good.

@petr-sandbox
petr-sandbox merged commit 5ef4d86 into sandbox-quantum:main Nov 12, 2026
19 checks passed
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.

Add Google Chat as a messaging platform

3 participants