Skip to content

Commit d7759c6

Browse files
authored
feat(googlechat): add native approval cards
## Summary - Adds native Google Chat approval cards for exec and plugin approval requests that originate from Google Chat spaces or threads. - Uses opaque server-side action tokens for Google Chat `cardsV2` button callbacks and updates delivered approval messages after resolution or expiry. - Preserves the shipped Google Chat typing-message default while keeping approval cards on the channel-local native path. - Suppresses duplicate manual `/approve ...` follow-up delivery inside `extensions/googlechat/` when the native card path owns the approval prompt. - Documents Google Chat native approval behavior and the `typingIndicator: "message"` default. ## Linked context Which issue does this close? Closes # Which issues, PRs, or discussions are related? Related Spec 24.8: Google Chat native approval cards. Was this requested by a maintainer or owner? Requested by maintainer in the Codex task thread. ## Real behavior proof (required for external PRs) - Behavior addressed: Google Chat exec and plugin approvals render as native cards and resolve through Google Chat button clicks. The latest change verifies an exec approval card is not accompanied by a duplicate manual `/approve` instruction bubble. - Real environment tested: OpenClaw dev profile with a real Google Chat DM to the OpenClaw app, local gateway behind a temporary Cloudflare quick tunnel, and Arc/Computer Use against the signed-in Google Chat session. - Exact steps or command run after this patch: Rebuilt the gateway runtime, started the dev-profile gateway with the Google Chat webhook routed through the tunnel, sent a fresh exec request from Google Chat, verified only the native approval card appeared, clicked `Allow Once` in Google Chat, and checked the command output reply plus marker file. - Evidence after fix (screenshot, recording, terminal capture, console output, redacted runtime log, linked artifact, or copied live output): Latest proof used nonce `GCHAT_NODOUBLE_LIVE_20260604070730`, approval id `949bc08c-9e57-47c0-b045-137603782292`, and proof directory `.mem/main/proofs/demo-89502-dev-gchat-exec-approval-no-double-send-channel-race/`. `raw/google-chat-gchat-nodouble-request-card-only-clean.png` shows the fresh user message followed by a single native `Exec Approval Required` card with `Allow Once`/`Deny` and no manual `/approve` follow-up bubble. `raw/google-chat-gchat-nodouble-resolved-clean.png` shows the card edited to `Exec Approval: Allowed once` and the final successful command reply. `raw/gchat-nodouble-live-filtered-log.txt` contains `googlechat approval resolved id=949bc08c-9e57-47c0-b045-137603782292 decision=allow-once`. `raw/marker-file-check.txt` records `/tmp/openclaw-gchat-no-double-GCHAT_NODOUBLE_LIVE_20260604070730` as created. - Observed result after fix: The approval prompt posted as a native Google Chat card only. No duplicate manual approval-instruction bubble was sent. Clicking `Allow Once` resolved the approval through the gateway and OpenClaw replied with the successful exec output in the same Google Chat DM. - What was not tested: A persistent production Google Chat app URL; live proof used a temporary Cloudflare tunnel for the local dev callback. - Proof limitations or environment constraints: Video was not captured for the final resumed manual UI run; still screenshots, gateway/proxy logs, a marker-file artifact, and Showboat verification were captured. - Before evidence (optional but encouraged): Before the final channel-local suppression path, Google Chat could show both the native approval card and a separate manual `/approve` instruction bubble. ## Tests and validation Which commands did you run? - `node scripts/build-all.mjs gatewayWatch` - `node scripts/run-vitest.mjs extensions/googlechat/src/monitor-webhook.test.ts extensions/googlechat/src/monitor.test.ts extensions/googlechat/src/monitor.reply-delivery.test.ts extensions/googlechat/src/monitor-durable.test.ts extensions/googlechat/src/approval-card-actions.test.ts extensions/googlechat/src/approval-handler.runtime.test.ts extensions/googlechat/src/approval-native.test.ts extensions/googlechat/src/approval-card-click.test.ts extensions/googlechat/src/channel-config.test.ts extensions/googlechat/src/targets.test.ts` - `git diff --check` - `pnpm docs:list` - `uvx showboat --workdir .mem/main/proofs/demo-89502-dev-gchat-exec-approval-no-double-send-channel-race verify .mem/main/proofs/demo-89502-dev-gchat-exec-approval-no-double-send-channel-race/raw/showboat-summary.md` - Live dev-profile Google Chat proof described above. What regression coverage was added or updated? - Added Google Chat native approval capability, runtime delivery, card token, and card-click resolver tests. - Added in-flight native card send suppression coverage so manual follow-up text is suppressed while native card delivery is pending. - Added cleanup coverage so manual follow-ups are restored if native card send fails. - Updated webhook ACK coverage for card-click events and default typing-indicator behavior coverage. What failed before this fix, if known? Google Chat could deliver the native approval card and still allow a model/message-tool manual `/approve` follow-up to appear as a second visible bubble. If no test was added, why not? Tests were added for the changed runtime and webhook behavior. ## Risk checklist Did user-visible behavior change? (`Yes/No`) Yes. Did config, environment, or migration behavior change? (`Yes/No`) No migration. The shipped Google Chat `typingIndicator: "message"` default is preserved. Did security, auth, secrets, network, or tool execution behavior change? (`Yes/No`) Yes. What is the highest-risk area? Approval authorization and callback token handling for native Google Chat card actions. How is that risk mitigated? Callbacks carry opaque action tokens only, token bindings check account, space, message, expiry, allowed decision, and in-flight state, and actor authorization reuses the existing Google Chat approver allowlist adapter based on stable `users/<id>` principals. ## Current review state What is the next action? Merge after current-head CI for `5923f2af46`. What is still waiting on author, maintainer, CI, or external proof? Current-head CI is green for `5923f2af46`; live dev-profile proof is complete. Which bot or reviewer comments were addressed? Addressed duplicate approval delivery by keeping the final suppression path inside `extensions/googlechat/`, preserving default typing-message behavior, and proving the current Google Chat surface sends only the native approval card.
1 parent e001838 commit d7759c6

24 files changed

Lines changed: 2846 additions & 27 deletions

docs/channels/googlechat.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ Configure your tunnel's ingress rules to only route the webhook path:
162162
4. DM access is pairing by default. Unknown senders receive a pairing code; approve with:
163163
- `openclaw pairing approve googlechat <code>`
164164
5. Group spaces require @-mention by default. Use `botUser` if mention detection needs the app's user name.
165+
6. When an exec or plugin approval request starts from Google Chat and a stable `users/<id>` approver is configured, OpenClaw posts a native Google Chat approval card in the originating space or thread. The card buttons use opaque callback tokens, and the manual `/approve <id> <decision>` prompt is only shown when native approval delivery is unavailable.
165166

166167
## Targets
167168

@@ -214,8 +215,9 @@ Notes:
214215
- Default webhook path is `/googlechat` if `webhookPath` isn't set.
215216
- `dangerouslyAllowNameMatching` re-enables mutable email principal matching for allowlists (break-glass compatibility mode).
216217
- Reactions are available via the `reactions` tool and `channels action` when `actions.reactions` is enabled.
218+
- Native approval cards use Google Chat `cardsV2` button clicks, not reaction events. Approvers come from `dm.allowFrom` or `defaultTo` and must be stable numeric `users/<id>` values.
217219
- Message actions expose `send` for text and `upload-file` for explicit attachment sends. `upload-file` accepts `media` / `filePath` / `path` plus optional `message`, `filename`, and thread targeting.
218-
- `typingIndicator` supports `none`, `message` (default), and `reaction` (reaction requires user OAuth).
220+
- `typingIndicator` supports `message` (default), `none`, and `reaction` (reaction requires user OAuth).
219221
- Attachments are downloaded through the Chat API and stored in the media pipeline (size capped by `mediaMaxMb`).
220222
- Bot-authored Google Chat messages are ignored by default. If you intentionally set `allowBots: true`, accepted bot-authored messages use shared [bot loop protection](/channels/bot-loop-protection). Configure `channels.defaults.botLoopProtection`, then override with `channels.googlechat.botLoopProtection` or `channels.googlechat.groups.<space>.botLoopProtection` when one space needs a different budget.
221223

docs/tools/exec-approvals-advanced.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,9 @@ Generic model:
287287
- Slack plugin approvals can use Slack's native approval client when the request comes from Slack
288288
and Slack plugin approvers resolve; `approvals.plugin` can also route plugin approvals to Slack
289289
sessions or targets even when Slack exec approvals are disabled
290+
- Google Chat native approval cards handle exec and plugin approvals that originate from Google
291+
Chat spaces or threads when stable `users/<id>` approvers resolve from `dm.allowFrom` or
292+
`defaultTo`; they do not use reaction events for decisions
290293
- WhatsApp and Signal reaction approval delivery are gated by `approvals.exec` and
291294
`approvals.plugin`; they do not have `channels.<channel>.execApprovals` blocks
292295

@@ -306,6 +309,8 @@ FAQ: [Why are there two exec approval configs for chat approvals?](/help/faq-fir
306309
- Discord: `channels.discord.execApprovals.*`
307310
- Slack: `channels.slack.execApprovals.*`
308311
- Telegram: `channels.telegram.execApprovals.*`
312+
- Google Chat: configure stable approvers with `channels.googlechat.dm.allowFrom` or
313+
`channels.googlechat.defaultTo`; no `execApprovals` block is required
309314
- WhatsApp: use `approvals.exec` and `approvals.plugin` to route approval prompts to WhatsApp
310315
- Signal: use `approvals.exec` and `approvals.plugin` to route approval prompts to Signal
311316

@@ -325,6 +330,9 @@ Shared behavior:
325330
routing, not Slack exec approvers
326331
- Slack native buttons preserve approval id kind, so `plugin:` ids can resolve plugin approvals
327332
without a second Slack-local fallback layer
333+
- Google Chat native cards preserve the manual `/approve` fallback in message text but card button
334+
callbacks carry only opaque action tokens; approval id and decision are recovered from server-side
335+
pending state
328336
- WhatsApp emoji approvals handle both exec and plugin prompts only when the matching top-level
329337
forwarding family is enabled and routes to WhatsApp; target-only WhatsApp forwarding stays on
330338
the shared forwarding path unless it matches the same native origin target

extensions/googlechat/src/api.ts

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@ import { parseMediaContentLength } from "openclaw/plugin-sdk/media-runtime";
55
import { readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
66
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
77
import type { ResolvedGoogleChatAccount } from "./accounts.js";
8+
import { shouldSuppressGoogleChatManualExecApprovalFollowupText } from "./approval-card-actions.js";
89
import { getGoogleChatAccessToken } from "./auth.js";
9-
import type { GoogleChatReaction } from "./types.js";
10+
import type { GoogleChatCardV2, GoogleChatReaction } from "./types.js";
1011

1112
const CHAT_API_BASE = "https://chat.googleapis.com/v1";
1213
const CHAT_UPLOAD_BASE = "https://chat.googleapis.com/upload/v1";
@@ -139,13 +140,25 @@ export async function sendGoogleChatMessage(params: {
139140
space: string;
140141
text?: string;
141142
thread?: string;
143+
cardsV2?: GoogleChatCardV2[];
142144
attachments?: Array<{ attachmentUploadToken: string; contentName?: string }>;
143145
}): Promise<{ messageName?: string } | null> {
144-
const { account, space, text, thread, attachments } = params;
146+
const { account, space, text, thread, cardsV2, attachments } = params;
147+
if (
148+
text &&
149+
(!cardsV2 || cardsV2.length === 0) &&
150+
(!attachments || attachments.length === 0) &&
151+
shouldSuppressGoogleChatManualExecApprovalFollowupText(text)
152+
) {
153+
return null;
154+
}
145155
const body: Record<string, unknown> = {};
146156
if (text) {
147157
body.text = text;
148158
}
159+
if (cardsV2 && cardsV2.length > 0) {
160+
body.cardsV2 = cardsV2;
161+
}
149162
if (thread) {
150163
body.thread = { name: thread };
151164
}
@@ -172,13 +185,28 @@ export async function sendGoogleChatMessage(params: {
172185
export async function updateGoogleChatMessage(params: {
173186
account: ResolvedGoogleChatAccount;
174187
messageName: string;
175-
text: string;
188+
text?: string;
189+
cardsV2?: GoogleChatCardV2[];
176190
}): Promise<{ messageName?: string }> {
177-
const { account, messageName, text } = params;
178-
const url = `${CHAT_API_BASE}/${messageName}?updateMask=text`;
191+
const { account, messageName, text, cardsV2 } = params;
192+
const updateMask = [
193+
...(text !== undefined ? ["text"] : []),
194+
...(cardsV2 !== undefined ? ["cardsV2"] : []),
195+
];
196+
if (updateMask.length === 0) {
197+
throw new Error("Google Chat message update requires text or cardsV2.");
198+
}
199+
const url = `${CHAT_API_BASE}/${messageName}?updateMask=${updateMask.join(",")}`;
200+
const body: Record<string, unknown> = {};
201+
if (text !== undefined) {
202+
body.text = text;
203+
}
204+
if (cardsV2 !== undefined) {
205+
body.cardsV2 = cardsV2;
206+
}
179207
const result = await fetchJson<{ name?: string }>(account, url, {
180208
method: "PATCH",
181-
body: JSON.stringify({ text }),
209+
body: JSON.stringify(body),
182210
});
183211
return { messageName: result.name };
184212
}

extensions/googlechat/src/approval-auth.ts

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coer
77
import { resolveGoogleChatAccount } from "./accounts.js";
88
import { isGoogleChatUserTarget, normalizeGoogleChatTarget } from "./targets.js";
99

10-
function normalizeGoogleChatApproverId(value: string | number): string | undefined {
10+
export function normalizeGoogleChatApproverId(value: string | number): string | undefined {
1111
const normalized = normalizeGoogleChatTarget(String(value));
1212
if (!normalized || !isGoogleChatUserTarget(normalized)) {
1313
return undefined;
@@ -19,15 +19,20 @@ function normalizeGoogleChatApproverId(value: string | number): string | undefin
1919
return `users/${suffix}`;
2020
}
2121

22+
export function getGoogleChatApprovalApprovers(params: {
23+
cfg: Parameters<typeof resolveGoogleChatAccount>[0]["cfg"];
24+
accountId?: string | null;
25+
}): string[] {
26+
const account = resolveGoogleChatAccount(params).config;
27+
return resolveApprovalApprovers({
28+
allowFrom: account.dm?.allowFrom,
29+
defaultTo: account.defaultTo,
30+
normalizeApprover: normalizeGoogleChatApproverId,
31+
});
32+
}
33+
2234
export const googleChatApprovalAuth = createResolvedApproverActionAuthAdapter({
2335
channelLabel: "Google Chat",
24-
resolveApprovers: ({ cfg, accountId }) => {
25-
const account = resolveGoogleChatAccount({ cfg, accountId }).config;
26-
return resolveApprovalApprovers({
27-
allowFrom: account.dm?.allowFrom,
28-
defaultTo: account.defaultTo,
29-
normalizeApprover: normalizeGoogleChatApproverId,
30-
});
31-
},
36+
resolveApprovers: getGoogleChatApprovalApprovers,
3237
normalizeSenderId: (value) => normalizeGoogleChatApproverId(value),
3338
});
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import { beforeEach, describe, expect, it } from "vitest";
2+
import {
3+
clearGoogleChatApprovalCardBindingsForTest,
4+
registerGoogleChatManualApprovalFollowupSuppression,
5+
registerGoogleChatApprovalCardBinding,
6+
shouldSuppressGoogleChatManualExecApprovalFollowupPayload,
7+
shouldSuppressGoogleChatManualExecApprovalFollowupText,
8+
} from "./approval-card-actions.js";
9+
10+
const approvalId = "12345678-1234-1234-1234-123456789012";
11+
type TestExecApprovalDecision = "allow-once" | "allow-always" | "deny";
12+
let tokenCounter = 0;
13+
14+
function registerExecApprovalCard(overrides?: {
15+
approvalId?: string;
16+
expiresAtMs?: number;
17+
allowedDecisions?: readonly TestExecApprovalDecision[];
18+
}): void {
19+
registerGoogleChatApprovalCardBinding({
20+
token: `token-${tokenCounter++}`,
21+
accountId: "default",
22+
approvalId: overrides?.approvalId ?? approvalId,
23+
approvalKind: "exec",
24+
decision: "allow-once",
25+
allowedDecisions: overrides?.allowedDecisions ?? ["allow-once", "deny"],
26+
spaceName: "spaces/AAA",
27+
messageName: "spaces/AAA/messages/msg-1",
28+
expiresAtMs: overrides?.expiresAtMs ?? Date.now() + 60_000,
29+
});
30+
}
31+
32+
describe("Google Chat approval card action registry", () => {
33+
beforeEach(() => {
34+
clearGoogleChatApprovalCardBindingsForTest();
35+
tokenCounter = 0;
36+
});
37+
38+
it("suppresses manual exec approval follow-up text for an active native card", () => {
39+
registerExecApprovalCard();
40+
41+
expect(
42+
shouldSuppressGoogleChatManualExecApprovalFollowupText(
43+
`I need approval.\nReply with:\n/approve ${approvalId.slice(0, 8)} allow-once`,
44+
),
45+
).toBe(true);
46+
expect(
47+
shouldSuppressGoogleChatManualExecApprovalFollowupText(
48+
`Run this if needed: \`/approve ${approvalId} deny\``,
49+
),
50+
).toBe(true);
51+
});
52+
53+
it("suppresses manual exec approval follow-up text after native delivery before token binding", () => {
54+
registerGoogleChatManualApprovalFollowupSuppression({
55+
approvalId,
56+
approvalKind: "exec",
57+
allowedDecisions: ["allow-once", "deny"],
58+
expiresAtMs: Date.now() + 60_000,
59+
});
60+
61+
expect(
62+
shouldSuppressGoogleChatManualExecApprovalFollowupText(
63+
`Please reply with:\n/approve ${approvalId.slice(0, 8)} allow-once`,
64+
),
65+
).toBe(true);
66+
});
67+
68+
it("keeps unrelated, expired, and non-sendable approval text visible", () => {
69+
registerExecApprovalCard({ expiresAtMs: Date.now() - 1 });
70+
expect(
71+
shouldSuppressGoogleChatManualExecApprovalFollowupText(
72+
`/approve ${approvalId.slice(0, 8)} allow-once`,
73+
),
74+
).toBe(false);
75+
76+
clearGoogleChatApprovalCardBindingsForTest();
77+
registerExecApprovalCard();
78+
expect(
79+
shouldSuppressGoogleChatManualExecApprovalFollowupText("/approve deadbeef allow-once"),
80+
).toBe(false);
81+
expect(
82+
shouldSuppressGoogleChatManualExecApprovalFollowupText(`/approve ${approvalId} nope`),
83+
).toBe(false);
84+
});
85+
86+
it("suppresses only text-only manual approval follow-up payloads", () => {
87+
registerExecApprovalCard();
88+
89+
expect(
90+
shouldSuppressGoogleChatManualExecApprovalFollowupPayload({
91+
text: `/approve ${approvalId.slice(0, 8)} allow-once`,
92+
}),
93+
).toBe(true);
94+
expect(
95+
shouldSuppressGoogleChatManualExecApprovalFollowupPayload({
96+
text: `/approve ${approvalId.slice(0, 8)} allow-once`,
97+
mediaUrl: "https://example.test/image.png",
98+
}),
99+
).toBe(false);
100+
expect(
101+
shouldSuppressGoogleChatManualExecApprovalFollowupPayload({
102+
text: `/approve ${approvalId.slice(0, 8)} allow-once`,
103+
channelData: { execApproval: { approvalId } },
104+
}),
105+
).toBe(true);
106+
expect(
107+
shouldSuppressGoogleChatManualExecApprovalFollowupPayload({
108+
text: `/approve ${approvalId.slice(0, 8)} allow-once`,
109+
presentation: { blocks: [] },
110+
}),
111+
).toBe(false);
112+
});
113+
});

0 commit comments

Comments
 (0)