From c7f986712be2af524b5010038e5e67992ce22b1c Mon Sep 17 00:00:00 2001 From: Jai Govindani Date: Fri, 16 Oct 2026 08:26:29 +0700 Subject: [PATCH 01/69] feat(chat): Add full message reads and text management --- .agents/skills/gog-chat/SKILL.md | 14 +- CHANGELOG.md | 2 + README.md | 16 + docs/automation.md | 7 + docs/chat-rich-messages.md | 106 +++++ docs/commands.generated.md | 3 + docs/commands/README.md | 5 +- docs/commands/gog-chat-messages-delete.md | 49 +++ docs/commands/gog-chat-messages-get.md | 49 +++ docs/commands/gog-chat-messages-list.md | 2 + docs/commands/gog-chat-messages-search.md | 1 + docs/commands/gog-chat-messages-update.md | 49 +++ docs/commands/gog-chat-messages.md | 3 + internal/cmd/chat_message.go | 151 +++++++ internal/cmd/chat_messages.go | 46 ++- internal/cmd/chat_rich_messages_test.go | 468 ++++++++++++++++++++++ internal/cmd/safety_profile_test.go | 31 ++ internal/googleapi/read_only_test.go | 26 ++ internal/outfmt/untrusted.go | 9 + internal/outfmt/untrusted_chat.go | 112 ++++++ internal/outfmt/untrusted_chat_test.go | 183 +++++++++ safety-profiles/agent-safe.yaml | 3 + safety-profiles/readonly.yaml | 3 + scripts/gen-agent-skills.mjs | 15 +- scripts/live-chat-rich-test.py | 322 +++++++++++++++ 25 files changed, 1665 insertions(+), 10 deletions(-) create mode 100644 docs/chat-rich-messages.md create mode 100644 docs/commands/gog-chat-messages-delete.md create mode 100644 docs/commands/gog-chat-messages-get.md create mode 100644 docs/commands/gog-chat-messages-update.md create mode 100644 internal/cmd/chat_message.go create mode 100644 internal/cmd/chat_rich_messages_test.go create mode 100644 internal/outfmt/untrusted_chat.go create mode 100644 internal/outfmt/untrusted_chat_test.go create mode 100755 scripts/live-chat-rich-test.py diff --git a/.agents/skills/gog-chat/SKILL.md b/.agents/skills/gog-chat/SKILL.md index dbcf6b049..55ed1952f 100644 --- a/.agents/skills/gog-chat/SKILL.md +++ b/.agents/skills/gog-chat/SKILL.md @@ -15,7 +15,7 @@ output, safety, and live-write rules. ```bash gog auth list --check --json --no-input gog schema chat --json -gog --readonly --account user@example.com chat --help +gog --readonly --account user@example.com chat messages list spaces/SPACE_ID --full --json --wrap-untrusted ``` - Select the account explicitly with `--account`. @@ -24,6 +24,18 @@ gog --readonly --account user@example.com chat --help - Use `--no-input` in automation and `--dry-run` before supported writes. - Confirm the exact account, object, and mutation before any write or delete. +## Rich messages + +- List/search default to compact output; add `--full --json` for full SDK-known message content. This is typed JSON, not raw/lossless output. +- `messages get spaces/SPACE/messages/MESSAGE --json` returns a full message; bare IDs require `--space`. +- `--view full` is a search provider option for read/mute metadata, independent of `--full`. List/search/get accept `--markup chat|markdown`. +- Full output includes card, image, GIF, and attachment metadata/URLs; it never fetches image or attachment bytes. +- Use `--wrap-untrusted` for nested card text, labels, filenames and alt text, including with `--results-only --select`. +- `messages update` (alias `edit`) requires `--text` and patches only text. Explicit empty text is sent; provider validation still applies. +- `messages delete` requires confirmation; root `--force` bypasses only the CLI prompt. `--delete-replies` separately enables Google's threaded-reply deletion. +- Preview mutations with `--dry-run`. Readonly blocks mutations. Google ownership/permissions still apply; these commands cannot edit app cards. +- This feature is maintained in the personal fork; upstream acceptance and live mutation permissions are not implied. + ## Commands | Command | Purpose | diff --git a/CHANGELOG.md b/CHANGELOG.md index 62e57c6c1..dd52943bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 0.44.1 - Unreleased +- Chat (personal fork): add full SDK message output for list/search, get with markup selection, text-only update/edit, and confirmed delete with explicit reply deletion; preserve compact defaults and wrap nested rich content for agents. (openclaw/gogcli#1000) — thanks @jai. + - Output: warn on stderr when a `--select` path matches no objects in a nonempty result, preserving JSON output and exit status. (#1210) — thanks @postoso. - Auth: clarify that `auth login` opens the browser account manager, and document manual authorization and unattended health checks. (#1214) — thanks @jingtying. - Dependencies: refresh Google API and MCP clients plus tracking-worker tooling within the Go 1.26 floor and 24-hour worker release cooldown; add a non-publishing release-pipeline dry run. diff --git a/README.md b/README.md index 928b3f825..5fc0e6588 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,22 @@ Identity Groups, Chat, Keep, and domain-wide delegation require a managed Google Workspace domain. The [Workspace Admin guide](docs/workspace-admin.md) explains that setup. +## Chat messages in this fork + +```bash +gog --account you@example.com chat messages list spaces/AAA --full --json --wrap-untrusted +gog --account you@example.com chat messages search 'release' --full --view full --json +gog --account you@example.com chat messages get spaces/AAA/messages/BBB --json +gog chat messages update spaces/AAA/messages/BBB --text='Replacement' --dry-run --json +gog chat messages delete spaces/AAA/messages/BBB --delete-replies --dry-run --json +``` + +Compact list/search defaults are preserved. Full output is SDK-typed JSON, +including rich content and image URLs; it does not download image bytes. +See [Chat rich messages](docs/chat-rich-messages.md) for output contracts, +permissions, safe text edits, and the distinction between CLI `--force` and +API reply deletion. This is a personal-fork feature. + ## Automate safely `--json` emits structured output and `--plain` emits stable TSV. Prompts, diff --git a/docs/automation.md b/docs/automation.md index 586a669b6..39ac8c171 100644 --- a/docs/automation.md +++ b/docs/automation.md @@ -63,6 +63,13 @@ system. Chat message and thread listings also wrap flattened sender display names. Raw Chat JSON responses, including those from `gog api call`, wrap `formattedText` too. Without the flag, ordinary JSON strings remain unchanged. +Full Chat list/search output (`--full --json`) and message get/update output +wrap nested rich content, including card subtitles, labels, alt text, filenames, +and button text. Structurally validated resource names and HTTP(S) URLs remain +usable; dotted selections retain these rules. Compact defaults are unchanged. +Full Chat JSON is SDK-typed rather than raw/lossless, and image/attachment bytes +are never fetched. See [Chat rich messages](chat-rich-messages.md). + Use `--readonly` (or `GOG_READONLY=1`) as a runtime backstop. It permits GET, HEAD, OPTIONS, and the small allowlist of Google APIs whose query operations use POST, while rejecting mutating API requests before network dispatch. This guard diff --git a/docs/chat-rich-messages.md b/docs/chat-rich-messages.md new file mode 100644 index 000000000..572f32754 --- /dev/null +++ b/docs/chat-rich-messages.md @@ -0,0 +1,106 @@ +# Chat rich messages (personal fork) + +This feature belongs to the `jai/gogcli` fork. It is not a statement that upstream +has accepted the design. Chat requires a Google Workspace account. + +## Read full messages + +```bash +gog --account you@example.com chat messages list spaces/AAA --json --full +gog --account you@example.com chat messages search 'release' --json --full --view full --markup markdown +gog --account you@example.com chat messages get spaces/AAA/messages/BBB --json +gog --account you@example.com chat messages get BBB --space AAA --markup chat --plain +``` + +List and search keep their compact JSON and TSV defaults. `--full` is an output +mode and requires JSON; invalid combinations fail before credential/service +lookup. `--view full` is a separate **search provider option** for read/mute +metadata, subject to Google's available permissions. `--full` does not enable +that provider view automatically. `--markup chat|markdown` selects the provider's +formatted-text syntax on list, search, and get; omitting it leaves Google's +default unchanged. + +Full list returns `{ "messages": [...], "nextPageToken": "..." }`, using Google's +`name` field instead of the compact `resource` alias. Full search keeps its +`results` envelope and paging aggregates; each result contains a full `message` +and available `read`/`spaceMuteSetting` metadata. Absent read state stays absent, +while explicit `false` stays false. Get and update return `{ "message": {...} }`. +Get/update text and plain output use the concise message summary columns. + +Full output serializes the current Google SDK `Message` type. It includes +SDK-known formatted text, annotations (including rich links), attachments, cards +V1/V2, GIFs, accessory widgets, emoji image references, and other message +metadata when returned by Google. Card-only messages are retained. This is +**typed output, not raw or lossless JSON**: unknown server fields and omitted +zero/empty fields are not preserved by the SDK. The feature does not render +cards, fetch image URLs, or download image/attachment bytes. URLs can expire or +require authorization. Full output makes no additional content-fetch requests. + +Paging options `--page`, `--all`, and `--fail-empty` retain their existing +behavior; exit code 3 reports empty results when requested. Full mode does not +change the server-side search, unread, thread, or ordering filters. + +## Consume content safely + +```bash +gog --readonly --account you@example.com chat messages list spaces/AAA \ + --full --json --wrap-untrusted --results-only \ + --select name,text,cardsV2,attachment +gog --readonly --account you@example.com chat messages get spaces/AAA/messages/BBB \ + --json --wrap-untrusted --results-only \ + --select name,cardsV2.0.card.header.title,cardsV2.0.card.header.imageUrl +``` + +`--wrap-untrusted` treats rich message strings conservatively, including card +text, titles/subtitles, labels, alt text, filenames, and button/action content. +Validated resource names, opaque identifiers, and HTTP(S) URL fields remain +usable. A usable URL is data, not a recommendation to fetch it or trust its +contents. Malformed metadata strings are wrapped too. Classification is scoped +to full Chat output and survives `--results-only` and dotted `--select` paths; +compact output keeps its existing mention/reaction filtering. Without wrapping, +SDK-known strings are emitted unchanged. + +## Replace text and delete + +```bash +# Preview without credentials or a Google request. +gog chat messages update spaces/AAA/messages/BBB --text='Replacement' --dry-run --json +gog chat messages delete spaces/AAA/messages/BBB --delete-replies --dry-run --json + +# Execute only for the intended account and message. +gog --account you@example.com chat messages update spaces/AAA/messages/BBB --text='Replacement' --json +gog --account you@example.com chat messages delete spaces/AAA/messages/BBB --force --no-input --json +``` + +`update` (alias `edit`) requires the **presence** of `--text`. `--text=''` sends +an explicit empty text field; Google can reject clearing a message if its rules +require content. The command always uses PATCH with `updateMask=text`. It does +not send cards or attachments, accept arbitrary masks, create a missing message, +or edit app cards. + +`delete` (aliases `rm`, `remove`, `del`) requires destructive confirmation. +Noninteractive execution, including `--no-input`, refuses without root `--force`. +Root `--force` only bypasses CLI confirmation. The separate `--delete-replies` +flag sets Google's API `force=true`, which deletes threaded replies as well. +Without it, API `force=false` is sent and Google refuses deletion of a message +with threaded replies. The JSON receipt is +`{ "deleted": "spaces/AAA/messages/BBB", "deleteReplies": false }` after success. +No success receipt is emitted for provider failures. + +Existing Chat authorization includes `chat.messages`; no new scope is requested. +Google still enforces message ownership, authorization type, and Workspace +permissions. App-authenticated updates/deletions are restricted to messages +created by that app. A resource ID or CLI `--force` grants no additional Google +permission; permission and not-found errors are propagated. `--readonly` blocks +both mutations, and the `agent-safe` and `readonly` safety profiles allow get +and explicitly deny update/delete (including aliases). Dry runs make no Google +calls and never prompt. + +## Verification boundary + +Focused HTTP transport tests cover full/compact output boundaries, cards and +image/attachment metadata, paging, missing read metadata, resource normalization, +markup, cancellation, provider errors, wrapping/projection, exact PATCH bodies, +explicit empty text, confirmation, force separation, dry run, and readonly +blocking. These tests use fake services; they do not establish live Workspace +edit/delete permission or exercise real Google messages. diff --git a/docs/commands.generated.md b/docs/commands.generated.md index 000e1c1bf..1985932de 100644 --- a/docs/commands.generated.md +++ b/docs/commands.generated.md @@ -155,6 +155,8 @@ Generated from `gog schema --json`. - [`gog chat dm send (create,post) [flags]`](commands/gog-chat-dm-send.md) - Send a direct message - [`gog chat dm space (find,setup) `](commands/gog-chat-dm-space.md) - Find or create a DM space - [`gog chat messages `](commands/gog-chat-messages.md) - Chat messages + - [`gog chat messages delete (rm,remove,del) [flags]`](commands/gog-chat-messages-delete.md) - Delete a message + - [`gog chat messages get [flags]`](commands/gog-chat-messages-get.md) - Get a full message - [`gog chat messages list (ls) [flags]`](commands/gog-chat-messages-list.md) - List messages - [`gog chat messages react [flags]`](commands/gog-chat-messages-react.md) - Add an emoji reaction to a message - [`gog chat messages reactions (reaction) `](commands/gog-chat-messages-reactions.md) - Manage emoji reactions on a message @@ -163,6 +165,7 @@ Generated from `gog schema --json`. - [`gog chat messages reactions (reaction) list (ls) [flags]`](commands/gog-chat-messages-reactions-list.md) - List reactions on a message - [`gog chat messages search (find,query) ... [flags]`](commands/gog-chat-messages-search.md) - Search messages across Chat - [`gog chat messages send (create,post) [flags]`](commands/gog-chat-messages-send.md) - Send a message + - [`gog chat messages update (edit) [flags]`](commands/gog-chat-messages-update.md) - Replace message text - [`gog chat spaces `](commands/gog-chat-spaces.md) - Chat spaces - [`gog chat spaces create (add,new) [flags]`](commands/gog-chat-spaces-create.md) - Create a space - [`gog chat spaces find (search,query) [flags]`](commands/gog-chat-spaces-find.md) - Find spaces by display name diff --git a/docs/commands/README.md b/docs/commands/README.md index 1c05b3f86..bebd8121f 100644 --- a/docs/commands/README.md +++ b/docs/commands/README.md @@ -2,7 +2,7 @@ Every `gog` command has a generated docs page. The source of truth is the live CLI schema; run `make docs-commands` after changing command names, flags, help text, aliases, or arguments. -Generated pages: 779. +Generated pages: 782. ## Top-level Commands @@ -209,6 +209,8 @@ Generated pages: 779. - [gog chat dm send](gog-chat-dm-send.md) - Send a direct message - [gog chat dm space](gog-chat-dm-space.md) - Find or create a DM space - [gog chat messages](gog-chat-messages.md) - Chat messages + - [gog chat messages delete](gog-chat-messages-delete.md) - Delete a message + - [gog chat messages get](gog-chat-messages-get.md) - Get a full message - [gog chat messages list](gog-chat-messages-list.md) - List messages - [gog chat messages react](gog-chat-messages-react.md) - Add an emoji reaction to a message - [gog chat messages reactions](gog-chat-messages-reactions.md) - Manage emoji reactions on a message @@ -217,6 +219,7 @@ Generated pages: 779. - [gog chat messages reactions list](gog-chat-messages-reactions-list.md) - List reactions on a message - [gog chat messages search](gog-chat-messages-search.md) - Search messages across Chat - [gog chat messages send](gog-chat-messages-send.md) - Send a message + - [gog chat messages update](gog-chat-messages-update.md) - Replace message text - [gog chat spaces](gog-chat-spaces.md) - Chat spaces - [gog chat spaces create](gog-chat-spaces-create.md) - Create a space - [gog chat spaces find](gog-chat-spaces-find.md) - Find spaces by display name diff --git a/docs/commands/gog-chat-messages-delete.md b/docs/commands/gog-chat-messages-delete.md new file mode 100644 index 000000000..7e6c83bad --- /dev/null +++ b/docs/commands/gog-chat-messages-delete.md @@ -0,0 +1,49 @@ +# `gog chat messages delete` + +> Generated from `gog schema --json`. Do not edit this page by hand; run `make docs-commands`. + +Delete a message + +## Usage + +```bash +gog chat messages delete (rm,remove,del) [flags] +``` + +## Parent + +- [gog chat messages](gog-chat-messages.md) + +## Flags + +| Flag | Type | Default | Help | +| --- | --- | --- | --- | +| `--access-token` | `string` | | Use provided access token directly (bypasses stored refresh tokens; token expires in ~1h) | +| `-a`
`--account`
`--acct` | `string` | | Account email, alias, or auto for authenticated Google API commands | +| `--client` | `string` | | OAuth client name (selects stored credentials + token bucket) | +| `--color` | `string` | auto | Color output: auto\|always\|never | +| `--delete-replies` | `bool` | | Also delete threaded replies (Google API force; distinct from CLI --force) | +| `--disable-commands` | `string` | | Comma-separated list of disabled commands; dot paths allowed | +| `-n`
`--dry-run`
`--dryrun`
`--noop`
`--preview` | `bool` | | Do not make changes; print intended actions and exit successfully | +| `--enable-commands` | `string` | | Comma-separated list of enabled command prefixes; dot paths allowed (restricts CLI) | +| `--enable-commands-exact` | `string` | | Comma-separated list of exact enabled commands; dot paths allowed and parent commands do not enable children | +| `-y`
`--force`
`--assume-yes`
`--yes` | `bool` | | Skip confirmations for destructive commands | +| `--gmail-no-send` | `bool` | false | Block Gmail send operations (agent safety) | +| `-h`
`--help` | `kong.helpFlag` | | Show context-sensitive help. | +| `--home` | `string` | | Override gogcli config/data/state/cache root (equivalent to GOG_HOME) | +| `-j`
`--json`
`--machine` | `bool` | false | Output JSON to stdout (best for scripting) | +| `--no-input`
`--non-interactive`
`--noninteractive` | `bool` | | Never prompt; fail instead (useful for CI) | +| `-p`
`--plain`
`--tsv` | `bool` | false | Output stable, parseable text to stdout (TSV; no colors) | +| `--quota-project` | `string` | | Google Cloud project to bill for API usage (sent as X-Goog-User-Project; some APIs require it with --access-token or ADC) | +| `--readonly` | `bool` | false | Block mutating API requests at runtime; auth add also requests read-only OAuth scopes | +| `--results-only` | `bool` | | In JSON mode, emit only the primary result (drops envelope fields like nextPageToken) | +| `--select`
`--pick`
`--project` | `string` | | In JSON mode, select comma-separated fields (best-effort; supports dot paths). Desire path: use --fields for most commands. | +| `--space` | `string` | | Space name (required when message is a bare ID) | +| `-v`
`--verbose` | `bool` | | Enable verbose logging | +| `--version` | `kong.VersionFlag` | | Print version and exit | +| `--wrap-untrusted` | `bool` | false | In JSON/raw output, wrap fetched text fields in external untrusted-content markers | + +## See Also + +- [gog chat messages](gog-chat-messages.md) +- [Command index](README.md) diff --git a/docs/commands/gog-chat-messages-get.md b/docs/commands/gog-chat-messages-get.md new file mode 100644 index 000000000..fd6631d21 --- /dev/null +++ b/docs/commands/gog-chat-messages-get.md @@ -0,0 +1,49 @@ +# `gog chat messages get` + +> Generated from `gog schema --json`. Do not edit this page by hand; run `make docs-commands`. + +Get a full message + +## Usage + +```bash +gog chat messages get [flags] +``` + +## Parent + +- [gog chat messages](gog-chat-messages.md) + +## Flags + +| Flag | Type | Default | Help | +| --- | --- | --- | --- | +| `--access-token` | `string` | | Use provided access token directly (bypasses stored refresh tokens; token expires in ~1h) | +| `-a`
`--account`
`--acct` | `string` | | Account email, alias, or auto for authenticated Google API commands | +| `--client` | `string` | | OAuth client name (selects stored credentials + token bucket) | +| `--color` | `string` | auto | Color output: auto\|always\|never | +| `--disable-commands` | `string` | | Comma-separated list of disabled commands; dot paths allowed | +| `-n`
`--dry-run`
`--dryrun`
`--noop`
`--preview` | `bool` | | Do not make changes; print intended actions and exit successfully | +| `--enable-commands` | `string` | | Comma-separated list of enabled command prefixes; dot paths allowed (restricts CLI) | +| `--enable-commands-exact` | `string` | | Comma-separated list of exact enabled commands; dot paths allowed and parent commands do not enable children | +| `-y`
`--force`
`--assume-yes`
`--yes` | `bool` | | Skip confirmations for destructive commands | +| `--gmail-no-send` | `bool` | false | Block Gmail send operations (agent safety) | +| `-h`
`--help` | `kong.helpFlag` | | Show context-sensitive help. | +| `--home` | `string` | | Override gogcli config/data/state/cache root (equivalent to GOG_HOME) | +| `-j`
`--json`
`--machine` | `bool` | false | Output JSON to stdout (best for scripting) | +| `--markup` | `string` | | Formatted text syntax: chat or markdown | +| `--no-input`
`--non-interactive`
`--noninteractive` | `bool` | | Never prompt; fail instead (useful for CI) | +| `-p`
`--plain`
`--tsv` | `bool` | false | Output stable, parseable text to stdout (TSV; no colors) | +| `--quota-project` | `string` | | Google Cloud project to bill for API usage (sent as X-Goog-User-Project; some APIs require it with --access-token or ADC) | +| `--readonly` | `bool` | false | Block mutating API requests at runtime; auth add also requests read-only OAuth scopes | +| `--results-only` | `bool` | | In JSON mode, emit only the primary result (drops envelope fields like nextPageToken) | +| `--select`
`--pick`
`--project` | `string` | | In JSON mode, select comma-separated fields (best-effort; supports dot paths). Desire path: use --fields for most commands. | +| `--space` | `string` | | Space name (required when message is a bare ID) | +| `-v`
`--verbose` | `bool` | | Enable verbose logging | +| `--version` | `kong.VersionFlag` | | Print version and exit | +| `--wrap-untrusted` | `bool` | false | In JSON/raw output, wrap fetched text fields in external untrusted-content markers | + +## See Also + +- [gog chat messages](gog-chat-messages.md) +- [Command index](README.md) diff --git a/docs/commands/gog-chat-messages-list.md b/docs/commands/gog-chat-messages-list.md index e97d3ecdd..1fdd5c462 100644 --- a/docs/commands/gog-chat-messages-list.md +++ b/docs/commands/gog-chat-messages-list.md @@ -29,10 +29,12 @@ gog chat messages list (ls) [flags] | `--enable-commands-exact` | `string` | | Comma-separated list of exact enabled commands; dot paths allowed and parent commands do not enable children | | `--fail-empty`
`--non-empty`
`--require-results` | `bool` | | Exit with code 3 if no results | | `-y`
`--force`
`--assume-yes`
`--yes` | `bool` | | Skip confirmations for destructive commands | +| `--full` | `bool` | | Return full SDK messages (requires --json) | | `--gmail-no-send` | `bool` | false | Block Gmail send operations (agent safety) | | `-h`
`--help` | `kong.helpFlag` | | Show context-sensitive help. | | `--home` | `string` | | Override gogcli config/data/state/cache root (equivalent to GOG_HOME) | | `-j`
`--json`
`--machine` | `bool` | false | Output JSON to stdout (best for scripting) | +| `--markup` | `string` | | Formatted text syntax: chat or markdown | | `--max`
`--limit` | `int64` | 50 | Max results | | `--no-input`
`--non-interactive`
`--noninteractive` | `bool` | | Never prompt; fail instead (useful for CI) | | `--order` | `string` | | Order by (e.g. createTime desc) | diff --git a/docs/commands/gog-chat-messages-search.md b/docs/commands/gog-chat-messages-search.md index 9eb422c8f..b9e8a93b8 100644 --- a/docs/commands/gog-chat-messages-search.md +++ b/docs/commands/gog-chat-messages-search.md @@ -29,6 +29,7 @@ gog chat messages search (find,query) ... [flags] | `--enable-commands-exact` | `string` | | Comma-separated list of exact enabled commands; dot paths allowed and parent commands do not enable children | | `--fail-empty`
`--non-empty`
`--require-results` | `bool` | | Exit with code 3 if no results | | `-y`
`--force`
`--assume-yes`
`--yes` | `bool` | | Skip confirmations for destructive commands | +| `--full` | `bool` | | Return full SDK messages and search metadata (requires --json) | | `--gmail-no-send` | `bool` | false | Block Gmail send operations (agent safety) | | `-h`
`--help` | `kong.helpFlag` | | Show context-sensitive help. | | `--home` | `string` | | Override gogcli config/data/state/cache root (equivalent to GOG_HOME) | diff --git a/docs/commands/gog-chat-messages-update.md b/docs/commands/gog-chat-messages-update.md new file mode 100644 index 000000000..a57fb561c --- /dev/null +++ b/docs/commands/gog-chat-messages-update.md @@ -0,0 +1,49 @@ +# `gog chat messages update` + +> Generated from `gog schema --json`. Do not edit this page by hand; run `make docs-commands`. + +Replace message text + +## Usage + +```bash +gog chat messages update (edit) [flags] +``` + +## Parent + +- [gog chat messages](gog-chat-messages.md) + +## Flags + +| Flag | Type | Default | Help | +| --- | --- | --- | --- | +| `--access-token` | `string` | | Use provided access token directly (bypasses stored refresh tokens; token expires in ~1h) | +| `-a`
`--account`
`--acct` | `string` | | Account email, alias, or auto for authenticated Google API commands | +| `--client` | `string` | | OAuth client name (selects stored credentials + token bucket) | +| `--color` | `string` | auto | Color output: auto\|always\|never | +| `--disable-commands` | `string` | | Comma-separated list of disabled commands; dot paths allowed | +| `-n`
`--dry-run`
`--dryrun`
`--noop`
`--preview` | `bool` | | Do not make changes; print intended actions and exit successfully | +| `--enable-commands` | `string` | | Comma-separated list of enabled command prefixes; dot paths allowed (restricts CLI) | +| `--enable-commands-exact` | `string` | | Comma-separated list of exact enabled commands; dot paths allowed and parent commands do not enable children | +| `-y`
`--force`
`--assume-yes`
`--yes` | `bool` | | Skip confirmations for destructive commands | +| `--gmail-no-send` | `bool` | false | Block Gmail send operations (agent safety) | +| `-h`
`--help` | `kong.helpFlag` | | Show context-sensitive help. | +| `--home` | `string` | | Override gogcli config/data/state/cache root (equivalent to GOG_HOME) | +| `-j`
`--json`
`--machine` | `bool` | false | Output JSON to stdout (best for scripting) | +| `--no-input`
`--non-interactive`
`--noninteractive` | `bool` | | Never prompt; fail instead (useful for CI) | +| `-p`
`--plain`
`--tsv` | `bool` | false | Output stable, parseable text to stdout (TSV; no colors) | +| `--quota-project` | `string` | | Google Cloud project to bill for API usage (sent as X-Goog-User-Project; some APIs require it with --access-token or ADC) | +| `--readonly` | `bool` | false | Block mutating API requests at runtime; auth add also requests read-only OAuth scopes | +| `--results-only` | `bool` | | In JSON mode, emit only the primary result (drops envelope fields like nextPageToken) | +| `--select`
`--pick`
`--project` | `string` | | In JSON mode, select comma-separated fields (best-effort; supports dot paths). Desire path: use --fields for most commands. | +| `--space` | `string` | | Space name (required when message is a bare ID) | +| `--text` | `*string` | | Replacement message text (required; empty explicitly clears text) | +| `-v`
`--verbose` | `bool` | | Enable verbose logging | +| `--version` | `kong.VersionFlag` | | Print version and exit | +| `--wrap-untrusted` | `bool` | false | In JSON/raw output, wrap fetched text fields in external untrusted-content markers | + +## See Also + +- [gog chat messages](gog-chat-messages.md) +- [Command index](README.md) diff --git a/docs/commands/gog-chat-messages.md b/docs/commands/gog-chat-messages.md index 503ee6f75..d261b3926 100644 --- a/docs/commands/gog-chat-messages.md +++ b/docs/commands/gog-chat-messages.md @@ -16,11 +16,14 @@ gog chat messages ## Subcommands +- [gog chat messages delete](gog-chat-messages-delete.md) - Delete a message +- [gog chat messages get](gog-chat-messages-get.md) - Get a full message - [gog chat messages list](gog-chat-messages-list.md) - List messages - [gog chat messages react](gog-chat-messages-react.md) - Add an emoji reaction to a message - [gog chat messages reactions](gog-chat-messages-reactions.md) - Manage emoji reactions on a message - [gog chat messages search](gog-chat-messages-search.md) - Search messages across Chat - [gog chat messages send](gog-chat-messages-send.md) - Send a message +- [gog chat messages update](gog-chat-messages-update.md) - Replace message text ## Flags diff --git a/internal/cmd/chat_message.go b/internal/cmd/chat_message.go new file mode 100644 index 000000000..84ac1ca3d --- /dev/null +++ b/internal/cmd/chat_message.go @@ -0,0 +1,151 @@ +package cmd + +import ( + "context" + "fmt" + + "google.golang.org/api/chat/v1" + + "github.com/openclaw/gogcli/internal/googleapi" + "github.com/openclaw/gogcli/internal/outfmt" + "github.com/openclaw/gogcli/internal/ui" +) + +type ChatMessagesGetCmd struct { + Message string `arg:"" name:"message" help:"Message resource (spaces/.../messages/...) or bare message ID"` + Space string `name:"space" help:"Space name (required when message is a bare ID)"` + Markup string `name:"markup" help:"Formatted text syntax: chat or markdown" enum:"chat,markdown," default:""` +} + +func (c *ChatMessagesGetCmd) Run(ctx context.Context, flags *RootFlags) error { + name, err := normalizeMessage(c.Space, c.Message) + if err != nil { + return usagef("invalid message: %v", err) + } + account, err := requireAccount(flags) + if err != nil { + return err + } + if err = requireWorkspaceAccount(account); err != nil { + return err + } + svc, err := chatService(ctx, account) + if err != nil { + return err + } + call := svc.Spaces.Messages.Get(name).Context(ctx) + if markup := chatMarkupSyntax(c.Markup); markup != "" { + call = call.MarkupSyntax(markup) + } + message, err := call.Do() + if err != nil { + return err + } + return writeChatMessage(ctx, message) +} + +type ChatMessagesUpdateCmd struct { + Message string `arg:"" name:"message" help:"Message resource (spaces/.../messages/...) or bare message ID"` + Space string `name:"space" help:"Space name (required when message is a bare ID)"` + Text *string `name:"text" help:"Replacement message text (required; empty explicitly clears text)"` +} + +func (c *ChatMessagesUpdateCmd) Run(ctx context.Context, flags *RootFlags) error { + name, err := normalizeMessage(c.Space, c.Message) + if err != nil { + return usagef("invalid message: %v", err) + } + if c.Text == nil { + return usage("required: --text") + } + message := &chat.Message{Text: *c.Text, ForceSendFields: []string{"Text"}} + if err = dryRunExit(ctx, flags, "chat.messages.update", map[string]any{ + "message": name, "updateMask": "text", "body": message, + }); err != nil { + return err + } + if googleapi.ReadOnly(ctx) || (flags != nil && flags.ReadOnly) { + return googleapi.ErrReadOnly + } + account, err := requireAccount(flags) + if err != nil { + return err + } + if err = requireWorkspaceAccount(account); err != nil { + return err + } + svc, err := chatService(ctx, account) + if err != nil { + return err + } + resp, err := svc.Spaces.Messages.Patch(name, message).UpdateMask("text").Context(ctx).Do() + if err != nil { + return err + } + return writeChatMessage(ctx, resp) +} + +type ChatMessagesDeleteCmd struct { + Message string `arg:"" name:"message" help:"Message resource (spaces/.../messages/...) or bare message ID"` + Space string `name:"space" help:"Space name (required when message is a bare ID)"` + DeleteReplies bool `name:"delete-replies" help:"Also delete threaded replies (Google API force; distinct from CLI --force)"` +} + +func (c *ChatMessagesDeleteCmd) Run(ctx context.Context, flags *RootFlags) error { + name, err := normalizeMessage(c.Space, c.Message) + if err != nil { + return usagef("invalid message: %v", err) + } + if err = dryRunExit(ctx, flags, "chat.messages.delete", map[string]any{ + "message": name, "deleteReplies": c.DeleteReplies, + }); err != nil { + return err + } + if googleapi.ReadOnly(ctx) || (flags != nil && flags.ReadOnly) { + return googleapi.ErrReadOnly + } + action := fmt.Sprintf("delete Chat message %s", name) + if c.DeleteReplies { + action += " and its threaded replies" + } + if err = confirmDestructiveChecked(ctx, flagsWithoutDryRun(flags), action); err != nil { + return err + } + account, err := requireAccount(flags) + if err != nil { + return err + } + if err = requireWorkspaceAccount(account); err != nil { + return err + } + svc, err := chatService(ctx, account) + if err != nil { + return err + } + if _, err := svc.Spaces.Messages.Delete(name).Force(c.DeleteReplies).Context(ctx).Do(); err != nil { + return err + } + if outfmt.IsJSON(ctx) { + return outfmt.WriteJSON(ctx, stdoutWriter(ctx), map[string]any{"deleted": name, "deleteReplies": c.DeleteReplies}) + } + ui.FromContext(ctx).Out().Linef("deleted\t%s", name) + return nil +} + +func chatMarkupSyntax(markup string) string { + switch markup { + case "chat": + return "MARKUP_SYNTAX_CHAT" + case "markdown": + return "MARKUP_SYNTAX_MARKDOWN" + default: + return "" + } +} + +func writeChatMessage(ctx context.Context, message *chat.Message) error { + if outfmt.IsJSON(ctx) { + return outfmt.WriteJSON(outfmt.WithUntrustedChatContent(ctx), stdoutWriter(ctx), map[string]any{"message": message}) + } + return outfmt.WriteTable(ctx, stdoutWriter(ctx), compactChatRows([]*chat.Message{message}), chatMessageColumns()) +} diff --git a/internal/cmd/chat_messages.go b/internal/cmd/chat_messages.go index 799226d0d..6195ff0c0 100644 --- a/internal/cmd/chat_messages.go +++ b/internal/cmd/chat_messages.go @@ -13,6 +13,9 @@ import ( ) type ChatMessagesCmd struct { + Get ChatMessagesGetCmd `cmd:"" name:"get" help:"Get a full message"` + Update ChatMessagesUpdateCmd `cmd:"" name:"update" aliases:"edit" help:"Replace message text"` + Delete ChatMessagesDeleteCmd `cmd:"" name:"delete" aliases:"rm,remove,del" help:"Delete a message"` List ChatMessagesListCmd `cmd:"" name:"list" aliases:"ls" help:"List messages"` Search ChatMessagesSearchCmd `cmd:"" name:"search" aliases:"find,query" help:"Search messages across Chat"` Send ChatMessagesSendCmd `cmd:"" name:"send" aliases:"create,post" help:"Send a message"` @@ -21,6 +24,7 @@ type ChatMessagesCmd struct { } type ChatMessagesSearchCmd struct { + Full bool `name:"full" help:"Return full SDK messages and search metadata (requires --json)"` Query []string `arg:"" name:"query" help:"Search query using Google Chat filter syntax"` Max int64 `name:"max" aliases:"limit" help:"Max results per page" default:"25"` Page string `name:"page" aliases:"cursor" help:"Page token"` @@ -32,6 +36,9 @@ type ChatMessagesSearchCmd struct { } func (c *ChatMessagesSearchCmd) Run(ctx context.Context, flags *RootFlags) error { + if c.Full && !outfmt.IsJSON(ctx) { + return usage("--full requires --json") + } u := ui.FromContext(ctx) query := strings.TrimSpace(strings.Join(c.Query, " ")) if query == "" { @@ -57,13 +64,7 @@ func (c *ChatMessagesSearchCmd) Run(ctx context.Context, flags *RootFlags) error if c.View == "full" { view = "SEARCH_MESSAGES_VIEW_FULL" } - markup := "" - switch c.Markup { - case "chat": - markup = "MARKUP_SYNTAX_CHAT" - case "markdown": - markup = "MARKUP_SYNTAX_MARKDOWN" - } + markup := chatMarkupSyntax(c.Markup) fetch := func(pageToken string) ([]*googleapi.ChatSearchResult, string, error) { req := &chat.SearchMessagesRequest{ @@ -85,6 +86,17 @@ func (c *ChatMessagesSearchCmd) Run(ctx context.Context, flags *RootFlags) error if err != nil { return err } + if c.Full { + items := make([]*googleapi.ChatSearchResult, 0, len(results)) + for _, result := range results { + if result != nil && result.Message != nil { + items = append(items, result) + } + } + return writePagedJSONResult(outfmt.WithUntrustedChatContent(ctx), map[string]any{ + "results": items, "nextPageToken": nextPageToken, + }, len(items), c.FailEmpty) + } items := compactChatSearchRows(results, c.View == "full") if outfmt.IsJSON(ctx) { @@ -143,6 +155,8 @@ func compactChatSearchRows(results []*googleapi.ChatSearchResult, includeRead bo } type ChatMessagesListCmd struct { + Full bool `name:"full" help:"Return full SDK messages (requires --json)"` + Markup string `name:"markup" help:"Formatted text syntax: chat or markdown" enum:"chat,markdown," default:""` Space string `arg:"" name:"space" help:"Space name (spaces/...)"` Max int64 `name:"max" aliases:"limit" help:"Max results" default:"50"` Page string `name:"page" aliases:"cursor" help:"Page token"` @@ -154,6 +168,9 @@ type ChatMessagesListCmd struct { } func (c *ChatMessagesListCmd) Run(ctx context.Context, flags *RootFlags) error { + if c.Full && !outfmt.IsJSON(ctx) { + return usage("--full requires --json") + } u := ui.FromContext(ctx) space, err := normalizeSpace(c.Space) if err != nil { @@ -208,6 +225,9 @@ func (c *ChatMessagesListCmd) Run(ctx context.Context, flags *RootFlags) error { if filter != "" { call = call.Filter(filter) } + if markup := chatMarkupSyntax(c.Markup); markup != "" { + call = call.MarkupSyntax(markup) + } resp, callErr := call.Do() if callErr != nil { return nil, "", callErr @@ -220,6 +240,18 @@ func (c *ChatMessagesListCmd) Run(ctx context.Context, flags *RootFlags) error { return err } + if c.Full { + messages = compactChatRows(messages) + if err := outfmt.WriteJSON(outfmt.WithUntrustedChatContent(ctx), stdoutWriter(ctx), map[string]any{ + "messages": messages, "nextPageToken": nextPageToken, + }); err != nil { + return err + } + if len(messages) == 0 { + return failEmptyExit(c.FailEmpty) + } + return nil + } if outfmt.IsJSON(ctx) { type item struct { Resource string `json:"resource"` diff --git a/internal/cmd/chat_rich_messages_test.go b/internal/cmd/chat_rich_messages_test.go new file mode 100644 index 000000000..193180757 --- /dev/null +++ b/internal/cmd/chat_rich_messages_test.go @@ -0,0 +1,468 @@ +package cmd + +import ( + "context" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + "testing" + + "google.golang.org/api/chat/v1" + gapi "google.golang.org/api/googleapi" + + "github.com/openclaw/gogcli/internal/app" + "github.com/openclaw/gogcli/internal/googleapi" +) + +const richChatFixture = `{ + "name":"spaces/AAA/messages/m1", "text":"hostile text", "formattedText":"**hostile text**", + "sender":{"name":"users/123","displayName":"hostile sender"}, + "thread":{"name":"spaces/AAA/threads/t1"}, "space":{"name":"spaces/AAA"}, + "annotations":[{"type":"RICH_LINK","richLinkMetadata":{"uri":"https://example.com/doc","driveLinkData":{"driveDataRef":{"driveFileId":"file-123"}}}}], + "attachment":[{"name":"spaces/AAA/messages/m1/attachments/a1","contentName":"hostile.png","downloadUri":"https://example.com/file","thumbnailUri":"https://example.com/thumb","attachmentDataRef":{"resourceName":"spaces/AAA/messages/m1/attachments/a1","attachmentUploadToken":"upload-token"}}], + "cards":[{"header":{"title":"hostile v1","subtitle":"hostile subtitle","imageUrl":"https://example.com/v1.png"},"sections":[{"widgets":[{"textParagraph":{"text":"hostile paragraph"}}]}]}], + "cardsV2":[{"cardId":"card-1","card":{"header":{"title":"hostile v2","subtitle":"hostile subtitle","imageUrl":"https://example.com/v2.png","imageAltText":"hostile alt"},"sections":[{"widgets":[{"decoratedText":{"topLabel":"hostile top","text":"hostile decorated","bottomLabel":"hostile bottom"}},{"buttonList":{"buttons":[{"text":"hostile button","altText":"hostile button alt","onClick":{"openLink":{"url":"https://example.com/button"}}}]}},{"image":{"imageUrl":"https://example.com/image.png","altText":"hostile image"}}]}]}}], + "attachedGifs":[{"uri":"https://example.com/animated.gif"}], + "accessoryWidgets":[{"buttonList":{"buttons":[{"text":"hostile accessory"}]}}], + "emojiReactionSummaries":[{"emoji":{"customEmoji":{"name":"customEmojis/abc","emojiName":":hostile:","uid":"abc","temporaryImageUri":"https://example.com/emoji.png"}},"reactionCount":1}], + "unknownFutureField":"not preserved by SDK" +}` + +func TestChatMessageGetResourceAndMarkup(t *testing.T) { + for _, tc := range []struct { + name string + args []string + markup string + }{ + {"full", []string{"spaces/AAA/messages/m1"}, ""}, + {"bare", []string{"m1", "--space", "AAA", "--markup", "markdown"}, "MARKUP_SYNTAX_MARKDOWN"}, + {"prefixed", []string{"messages/m1", "--space", "spaces/AAA", "--markup", "chat"}, "MARKUP_SYNTAX_CHAT"}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet || r.URL.Path != "/v1/spaces/AAA/messages/m1" || r.URL.Query().Get("markupSyntax") != tc.markup { + t.Errorf("request: %s %s", r.Method, r.URL) + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, richChatFixture) + }) + args := append([]string{"--account", "a@example.com", "--json", "chat", "messages", "get"}, tc.args...) + result := executeWithChatTestService(t, args, svc) + if result.err != nil { + t.Fatal(result.err) + } + assertRichChatJSON(t, result.stdout) + if !strings.Contains(result.stdout, `"message":`) { + t.Fatal(result.stdout) + } + }) + } +} + +func assertRichChatJSON(t *testing.T, output string) { + t.Helper() + for _, want := range []string{`"name": "spaces/AAA/messages/m1"`, `"formattedText"`, `"richLinkMetadata"`, `"attachment"`, `"cards"`, `"cardsV2"`, `"attachedGifs"`, `"accessoryWidgets"`, `https://example.com/emoji.png`, `hostile subtitle`, `hostile alt`} { + if !strings.Contains(output, want) { + t.Errorf("missing %q in %s", want, output) + } + } + if strings.Contains(output, "unknownFutureField") || strings.Contains(output, `"resource":`) { + t.Fatalf("not typed full output: %s", output) + } +} + +func TestChatMessageGetErrorsAndCancellation(t *testing.T) { + t.Run("not found", func(t *testing.T) { + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { + http.Error(w, `{"error":{"code":404,"message":"missing"}}`, http.StatusNotFound) + }) + result := executeWithChatTestService(t, []string{"--account", "a@example.com", "chat", "messages", "get", "spaces/AAA/messages/missing"}, svc) + var apiErr *gapi.Error + if !errors.As(result.err, &apiErr) || apiErr.Code != 404 { + t.Fatalf("error: %v", result.err) + } + }) + t.Run("cancelled", func(t *testing.T) { + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { t.Error("cancelled request reached server") }) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + ctx = app.WithRuntime(ctx, &app.Runtime{Services: app.Services{Chat: fixedGoogleTestService(svc)}}) + err := (&ChatMessagesGetCmd{Message: "spaces/AAA/messages/m1"}).Run(ctx, &RootFlags{Account: "a@example.com"}) + if !errors.Is(err, context.Canceled) { + t.Fatalf("error: %v", err) + } + }) +} + +func TestChatFullValidationBeforeService(t *testing.T) { + for _, args := range [][]string{ + {"list", "spaces/AAA", "--full"}, + {"search", "query", "--full"}, + {"get", "m1"}, + {"get", "spaces/AAA/messages/"}, + {"update", "spaces/AAA/messages/m1"}, + } { + t.Run(strings.Join(args, " "), func(t *testing.T) { + result := executeWithChatTestServiceFactory(t, append([]string{"--account", "user@gmail.com", "chat", "messages"}, args...), unexpectedChatTestService(t, "validation must precede service")) + if ExitCode(result.err) != 2 || strings.Contains(result.err.Error(), "Workspace") { + t.Fatalf("error: %v", result.err) + } + }) + } +} + +func TestChatFullListPaginationAndMarkup(t *testing.T) { + for _, all := range []bool{false, true} { + t.Run(map[bool]string{false: "page", true: "all"}[all], func(t *testing.T) { + calls := 0 + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + if r.Method != http.MethodGet || r.URL.Path != "/v1/spaces/AAA/messages" || r.URL.Query().Get("markupSyntax") != "MARKUP_SYNTAX_MARKDOWN" || r.URL.Query().Get("pageSize") != "1" { + t.Errorf("request: %s %s", r.Method, r.URL) + } + w.Header().Set("Content-Type", "application/json") + switch r.URL.Query().Get("pageToken") { + case "start": + io.WriteString(w, `{"messages":[`+richChatFixture+`],"nextPageToken":"next"}`) + case "next": + io.WriteString(w, `{"messages":[{"name":"spaces/AAA/messages/card-only","cardsV2":[{"card":{"header":{"title":"card only"}}}]}]}`) + default: + t.Errorf("page token: %s", r.URL) + } + }) + args := []string{"--account", "a@example.com", "--json", "chat", "messages", "list", "AAA", "--full", "--page", "start", "--max", "1", "--markup", "markdown"} + if all { + args = append(args, "--all") + } + result := executeWithChatTestService(t, args, svc) + if result.err != nil { + t.Fatal(result.err) + } + assertRichChatJSON(t, result.stdout) + var output struct { + Messages []*chat.Message + NextPageToken string + } + if err := json.Unmarshal([]byte(result.stdout), &output); err != nil { + t.Fatal(err) + } + want := 1 + token := "next" + if all { + want = 2 + token = "" + } + if len(output.Messages) != want || calls != want || output.NextPageToken != token { + t.Fatalf("calls=%d output=%s", calls, result.stdout) + } + }) + } +} + +func TestChatFullSearchMetadataAndPagination(t *testing.T) { + calls := 0 + svc := newChatSearchTestClient(t, func(w http.ResponseWriter, r *http.Request) { + calls++ + var req chat.SearchMessagesRequest + json.NewDecoder(r.Body).Decode(&req) + if req.View != "SEARCH_MESSAGES_VIEW_FULL" || req.MarkupSyntax != "MARKUP_SYNTAX_CHAT" { + t.Errorf("request: %+v", req) + } + w.Header().Set("Content-Type", "application/json") + if req.PageToken == "" { + io.WriteString(w, `{"results":[{"message":`+richChatFixture+`,"read":false,"spaceMuteSetting":"MUTED"}],"nextPageToken":"next"}`) + return + } + if req.PageToken != "next" { + t.Errorf("page token %q", req.PageToken) + } + io.WriteString(w, `{"results":[{"message":{"name":"spaces/AAA/messages/card-only","cards":[{"header":{"title":"card only"}}]}},null,{}]}`) + }) + result := executeWithChatSearchTestService(t, []string{"--account", "a@example.com", "--json", "chat", "messages", "search", "query", "--full", "--view", "full", "--markup", "chat", "--all"}, svc) + if result.err != nil { + t.Fatal(result.err) + } + assertRichChatJSON(t, result.stdout) + var output struct { + Results []*googleapi.ChatSearchResult + NextPageToken string + } + if err := json.Unmarshal([]byte(result.stdout), &output); err != nil { + t.Fatal(err) + } + if calls != 2 || len(output.Results) != 2 || output.Results[0].Read == nil || *output.Results[0].Read || output.Results[0].SpaceMuteSetting != "MUTED" || output.Results[1].Read != nil || output.NextPageToken != "" { + t.Fatalf("metadata lost: %s", result.stdout) + } +} + +func TestChatFullEmpty(t *testing.T) { + for _, response := range []string{`{}`, `{"messages":[null],"results":[null,{}]}`} { + t.Run(response, func(t *testing.T) { + for _, command := range []string{"list", "search"} { + t.Run(command, func(t *testing.T) { + handler := func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, response) + } + args := []string{"--account", "a@example.com", "--json", "chat", "messages", command, "AAA", "--full", "--fail-empty"} + var result executeTestResult + if command == "list" { + result = executeWithChatTestService(t, args, useFakeChatService(t, handler)) + } else { + result = executeWithChatSearchTestService(t, args, newChatSearchTestClient(t, handler)) + } + if ExitCode(result.err) != 3 || !json.Valid([]byte(result.stdout)) { + t.Fatalf("result: %+v", result) + } + }) + } + }) + } +} + +func TestChatMessageUpdatePatch(t *testing.T) { + for _, text := range []string{"replacement", "", " preserve whitespace\n"} { + t.Run(text, func(t *testing.T) { + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPatch || r.URL.Path != "/v1/spaces/AAA/messages/m1" || r.URL.Query().Get("updateMask") != "text" || r.URL.Query().Has("allowMissing") { + t.Errorf("request: %s %s", r.Method, r.URL) + } + var body map[string]any + json.NewDecoder(r.Body).Decode(&body) + if len(body) != 1 || body["text"] != text { + t.Errorf("body: %#v", body) + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, richChatFixture) + }) + result := executeWithChatTestService(t, []string{"--account", "a@example.com", "--json", "chat", "messages", "edit", "m1", "--space", "AAA", "--text=" + text}, svc) + if result.err != nil { + t.Fatal(result.err) + } + assertRichChatJSON(t, result.stdout) + }) + } +} + +func TestChatMessageDeleteForceSeparation(t *testing.T) { + for _, alias := range []string{"delete", "rm", "remove", "del"} { + t.Run(alias, func(t *testing.T) { + for _, replies := range []bool{false, true} { + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { + want := "false" + if replies { + want = "true" + } + if r.Method != http.MethodDelete || r.URL.Path != "/v1/spaces/AAA/messages/m1" || r.URL.Query().Get("force") != want { + t.Errorf("request: %s %s", r.Method, r.URL) + } + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{}`) + }) + args := []string{"--account", "a@example.com", "--json", "--no-input", "--force", "chat", "messages", alias, "m1", "--space", "AAA"} + if replies { + args = append(args, "--delete-replies") + } + result := executeWithChatTestService(t, args, svc) + if result.err != nil { + t.Fatal(result.err) + } + var receipt struct { + Deleted string + DeleteReplies bool + } + json.Unmarshal([]byte(result.stdout), &receipt) + if receipt.Deleted != "spaces/AAA/messages/m1" || receipt.DeleteReplies != replies { + t.Fatal(result.stdout) + } + } + }) + } +} + +func TestChatMessageMutationGuards(t *testing.T) { + for _, tc := range []struct { + name string + args []string + want string + code int + }{ + {"missing text", []string{"update", "spaces/AAA/messages/m1"}, "required: --text", 2}, + {"confirmation", []string{"delete", "spaces/AAA/messages/m1", "--no-input"}, "without --force", 2}, + {"reply confirmation", []string{"delete", "spaces/AAA/messages/m1", "--delete-replies", "--no-input"}, "and its threaded replies", 2}, + {"readonly update", []string{"update", "spaces/AAA/messages/m1", "--text=x", "--readonly"}, "--readonly", 2}, + {"readonly delete", []string{"delete", "spaces/AAA/messages/m1", "--force", "--readonly"}, "--readonly", 2}, + {"dry update", []string{"update", "m1", "--space", "AAA", "--text=", "--dry-run"}, "", 0}, + {"dry delete", []string{"delete", "m1", "--space", "AAA", "--delete-replies", "--no-input", "--dry-run"}, "", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + result := executeWithChatTestServiceFactory(t, append([]string{"--json", "chat", "messages"}, tc.args...), unexpectedChatTestService(t, "must not create service")) + if ExitCode(result.err) != tc.code { + t.Fatalf("error: %v", result.err) + } + if tc.want != "" && (result.err == nil || !strings.Contains(result.err.Error(), tc.want)) { + t.Fatalf("error: %v", result.err) + } + if tc.code == 0 && (!strings.Contains(result.stdout, "spaces/AAA/messages/m1") || !strings.Contains(result.stdout, "dry_run")) { + t.Fatal(result.stdout) + } + }) + } +} + +func TestChatMessageMutationProviderFailures(t *testing.T) { + for _, command := range []string{"update", "delete"} { + t.Run(command, func(t *testing.T) { + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { + http.Error(w, `{"error":{"code":403,"message":"permission denied"}}`, http.StatusForbidden) + }) + args := []string{"--account", "a@example.com", "--json", "--force", "chat", "messages", command, "spaces/AAA/messages/m1"} + if command == "update" { + args = append(args, "--text=x") + } + result := executeWithChatTestService(t, args, svc) + var apiErr *gapi.Error + if !errors.As(result.err, &apiErr) || apiErr.Code != 403 || strings.Contains(result.stdout, `"deleted"`) || strings.Contains(result.stdout, `"message": {`) { + t.Fatalf("result: %+v", result) + } + }) + } +} + +func TestChatFullWrappingAndProjection(t *testing.T) { + for _, command := range []string{"get", "list", "search"} { + for _, wrap := range []bool{false, true} { + for _, projection := range []bool{false, true} { + t.Run(command+map[bool]string{false: "/raw", true: "/wrapped"}[wrap]+map[bool]string{false: "", true: "/selected"}[projection], func(t *testing.T) { + args := []string{"--account", "a@example.com", "--json", "chat", "messages", command} + switch command { + case "get": + args = append(args, "spaces/AAA/messages/m1") + case "list": + args = append(args, "AAA", "--full") + case "search": + args = append(args, "query", "--full") + } + if wrap { + args = append(args, "--wrap-untrusted") + } + if projection { + prefix := "" + if command == "search" { + prefix = "message." + } + fields := []string{"name", "sender.name", "sender.displayName", "attachment.0.contentName", "cardsV2.0.card.header.title", "cardsV2.0.card.header.subtitle", "cardsV2.0.card.header.imageAltText", "cardsV2.0.card.header.imageUrl", "cardsV2.0.card.sections.0.widgets.0.decoratedText.topLabel", "cardsV2.0.card.sections.0.widgets.1.buttonList.buttons.0.altText", "cardsV2.0.card.sections.0.widgets.1.buttonList.buttons.0.onClick.openLink.url"} + for i := range fields { + fields[i] = prefix + fields[i] + } + args = append(args, "--results-only", "--select", strings.Join(fields, ",")) + } + handler := func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch command { + case "get": + io.WriteString(w, richChatFixture) + case "list": + io.WriteString(w, `{"messages":[`+richChatFixture+`]}`) + case "search": + io.WriteString(w, `{"results":[{"message":`+richChatFixture+`} ]}`) + } + } + var result executeTestResult + if command == "search" { + result = executeWithChatSearchTestService(t, args, newChatSearchTestClient(t, handler)) + } else { + result = executeWithChatTestService(t, args, useFakeChatService(t, handler)) + } + if result.err != nil { + t.Fatal(result.err) + } + var decoded any + if err := json.Unmarshal([]byte(result.stdout), &decoded); err != nil { + t.Fatal(err) + } + assertChatStringsWrapped(t, decoded, wrap) + }) + } + } + } +} + +func assertChatStringsWrapped(t *testing.T, value any, wrap bool) { + t.Helper() + switch v := value.(type) { + case map[string]any: + for _, child := range v { + assertChatStringsWrapped(t, child, wrap) + } + case []any: + for _, child := range v { + assertChatStringsWrapped(t, child, wrap) + } + case string: + marker := strings.Contains(v, "<<