diff --git a/.agents/skills/gog-chat/SKILL.md b/.agents/skills/gog-chat/SKILL.md index dbcf6b049..10f1d8c26 100644 --- a/.agents/skills/gog-chat/SKILL.md +++ b/.agents/skills/gog-chat/SKILL.md @@ -28,6 +28,7 @@ gog --readonly --account user@example.com chat --help | Command | Purpose | | --- | --- | +| `attachments` | Message attachments (read-only download) | | `dm` | Direct messages | | `messages` | Chat messages | | `spaces` | Chat spaces | diff --git a/CHANGELOG.md b/CHANGELOG.md index 861521fad..8164ee380 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 0.48.1 - Unreleased +- Chat: include attachment metadata (`name`, `contentName`, `contentType`, `source`, data reference) in `chat messages list --json`, and add read-only `chat attachments download` for uploaded attachments; Drive attachments point to `gog drive download`. (#1320) — thanks @voska. + ## 0.48.0 - 2026-11-05 **Highlights:** New backups stay local until you configure a remote; existing configurations keep working. Store service-account keys in the keyring, search Gmail IDs efficiently, and use environment-backed watch tokens, with Calendar fixes and security dependency updates. diff --git a/docs/commands.generated.md b/docs/commands.generated.md index 37715ba7b..e1740cbbe 100644 --- a/docs/commands.generated.md +++ b/docs/commands.generated.md @@ -153,6 +153,8 @@ Generated from `gog schema --json`. - [`gog calendar (cal) users [flags]`](commands/gog-calendar-users.md) - List workspace users (use their email as calendar ID) - [`gog calendar (cal) working-location (wl) --from=STRING --to=STRING --type=STRING [] [flags]`](commands/gog-calendar-working-location.md) - Set working location (home/office/custom) - [`gog chat [flags]`](commands/gog-chat.md) - Google Chat + - [`gog chat attachments `](commands/gog-chat-attachments.md) - Message attachments (read-only download) + - [`gog chat attachments download [flags]`](commands/gog-chat-attachments-download.md) - Download a message's attachments read-only (spaces.messages.get + media.download) - [`gog chat dm `](commands/gog-chat-dm.md) - Direct messages - [`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 diff --git a/docs/commands/README.md b/docs/commands/README.md index f15eae3a5..0837e488f 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: 781. +Generated pages: 783. ## Top-level Commands @@ -207,6 +207,8 @@ Generated pages: 781. - [gog calendar users](gog-calendar-users.md) - List workspace users (use their email as calendar ID) - [gog calendar working-location](gog-calendar-working-location.md) - Set working location (home/office/custom) - [gog chat](gog-chat.md) - Google Chat + - [gog chat attachments](gog-chat-attachments.md) - Message attachments (read-only download) + - [gog chat attachments download](gog-chat-attachments-download.md) - Download a message's attachments read-only (spaces.messages.get + media.download) - [gog chat dm](gog-chat-dm.md) - Direct messages - [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 diff --git a/docs/commands/gog-chat-attachments-download.md b/docs/commands/gog-chat-attachments-download.md new file mode 100644 index 000000000..b4e9aee72 --- /dev/null +++ b/docs/commands/gog-chat-attachments-download.md @@ -0,0 +1,49 @@ +# `gog chat attachments download` + +> Generated from `gog schema --json`. Do not edit this page by hand; run `make docs-commands`. + +Download a message's attachments read-only (spaces.messages.get + media.download) + +## Usage + +```bash +gog chat attachments download [flags] +``` + +## Parent + +- [gog chat attachments](gog-chat-attachments.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) | +| `--out`
`--output` | `string` | | Output file (one attachment) or directory (default: the current directory) | +| `--overwrite` | `bool` | | Overwrite an existing file | +| `-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. | +| `-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 attachments](gog-chat-attachments.md) +- [Command index](README.md) diff --git a/docs/commands/gog-chat-attachments.md b/docs/commands/gog-chat-attachments.md new file mode 100644 index 000000000..2a38f5c7b --- /dev/null +++ b/docs/commands/gog-chat-attachments.md @@ -0,0 +1,51 @@ +# `gog chat attachments` + +> Generated from `gog schema --json`. Do not edit this page by hand; run `make docs-commands`. + +Message attachments (read-only download) + +## Usage + +```bash +gog chat attachments +``` + +## Parent + +- [gog chat](gog-chat.md) + +## Subcommands + +- [gog chat attachments download](gog-chat-attachments-download.md) - Download a message's attachments read-only (spaces.messages.get + media.download) + +## 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. | +| `-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](gog-chat.md) +- [Command index](README.md) diff --git a/docs/commands/gog-chat.md b/docs/commands/gog-chat.md index fc90b483c..3e32954b4 100644 --- a/docs/commands/gog-chat.md +++ b/docs/commands/gog-chat.md @@ -16,6 +16,7 @@ gog chat [flags] ## Subcommands +- [gog chat attachments](gog-chat-attachments.md) - Message attachments (read-only download) - [gog chat dm](gog-chat-dm.md) - Direct messages - [gog chat messages](gog-chat-messages.md) - Chat messages - [gog chat spaces](gog-chat-spaces.md) - Chat spaces diff --git a/internal/cmd/chat.go b/internal/cmd/chat.go index 2ea35deb1..cdcbc953d 100644 --- a/internal/cmd/chat.go +++ b/internal/cmd/chat.go @@ -1,8 +1,9 @@ package cmd type ChatCmd struct { - Spaces ChatSpacesCmd `cmd:"" name:"spaces" help:"Chat spaces"` - Messages ChatMessagesCmd `cmd:"" name:"messages" help:"Chat messages"` - Threads ChatThreadsCmd `cmd:"" name:"threads" help:"Chat threads"` - DM ChatDMCmd `cmd:"" name:"dm" help:"Direct messages"` + Spaces ChatSpacesCmd `cmd:"" name:"spaces" help:"Chat spaces"` + Messages ChatMessagesCmd `cmd:"" name:"messages" help:"Chat messages"` + Threads ChatThreadsCmd `cmd:"" name:"threads" help:"Chat threads"` + DM ChatDMCmd `cmd:"" name:"dm" help:"Direct messages"` + Attachments ChatAttachmentsCmd `cmd:"" name:"attachments" help:"Message attachments (read-only download)"` } diff --git a/internal/cmd/chat_attachments.go b/internal/cmd/chat_attachments.go new file mode 100644 index 000000000..9f4e2dea3 --- /dev/null +++ b/internal/cmd/chat_attachments.go @@ -0,0 +1,245 @@ +package cmd + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "path/filepath" + "strings" + + "google.golang.org/api/chat/v1" + + "github.com/openclaw/gogcli/internal/config" + "github.com/openclaw/gogcli/internal/outfmt" + "github.com/openclaw/gogcli/internal/ui" +) + +type ChatAttachmentsCmd struct { + Download ChatAttachmentsDownloadCmd `cmd:"" name:"download" help:"Download a message's attachments read-only (spaces.messages.get + media.download)"` +} + +// chatAttachmentItem is the attachment metadata of a Chat message, as carried by +// `chat messages list --json` and `chat attachments download`. +type chatAttachmentItem struct { + Name string `json:"name"` + ContentName string `json:"contentName,omitempty"` + ContentType string `json:"contentType,omitempty"` + Source string `json:"source,omitempty"` + AttachmentDataRef *chatAttachmentDataRef `json:"attachmentDataRef,omitempty"` + DriveDataRef *chatDriveDataRef `json:"driveDataRef,omitempty"` +} + +type chatAttachmentDataRef struct { + ResourceName string `json:"resourceName,omitempty"` +} + +type chatDriveDataRef struct { + DriveFileID string `json:"driveFileId,omitempty"` +} + +const defaultChatAttachmentFilename = "attachment.bin" + +func compactChatAttachments(attachments []*chat.Attachment) []*chatAttachmentItem { + var items []*chatAttachmentItem + for _, attachment := range attachments { + if attachment == nil { + continue + } + item := &chatAttachmentItem{ + Name: attachment.Name, + ContentName: attachment.ContentName, + ContentType: attachment.ContentType, + Source: attachment.Source, + } + if ref := attachment.AttachmentDataRef; ref != nil && ref.ResourceName != "" { + item.AttachmentDataRef = &chatAttachmentDataRef{ResourceName: ref.ResourceName} + } + if ref := attachment.DriveDataRef; ref != nil && ref.DriveFileId != "" { + item.DriveDataRef = &chatDriveDataRef{DriveFileID: ref.DriveFileId} + } + items = append(items, item) + } + return items +} + +type ChatAttachmentsDownloadCmd struct { + Name string `arg:"" name:"name" help:"Message (spaces/.../messages/...) or one attachment (spaces/.../messages/.../attachments/...)"` + Out string `name:"out" aliases:"output" help:"Output file (one attachment) or directory (default: the current directory)"` + Overwrite bool `name:"overwrite" help:"Overwrite an existing file"` +} + +// splitChatAttachmentName accepts a message name or an attachment name and returns +// (message, attachment); attachment is empty when the whole message was named. +func splitChatAttachmentName(raw string) (string, string, error) { + name := strings.TrimSpace(raw) + parts := strings.Split(name, "/") + valid := func(n int) bool { + if len(parts) != n || parts[0] != "spaces" || parts[2] != "messages" { + return false + } + if n == 6 && parts[4] != "attachments" { + return false + } + for _, part := range parts { + if part == "" { + return false + } + } + return true + } + switch { + case valid(4): + return name, "", nil + case valid(6): + return strings.Join(parts[:4], "/"), name, nil + } + return "", "", usagef("invalid name %q: expected spaces//messages/[/attachments/]", raw) +} + +func chatAttachmentFallbackName(name string) string { + if i := strings.LastIndex(name, "/"); i >= 0 && i+1 < len(name) { + return name[i+1:] + } + return defaultChatAttachmentFilename +} + +func (c *ChatAttachmentsDownloadCmd) Run(ctx context.Context, flags *RootFlags) error { + u := ui.FromContext(ctx) + messageName, attachmentName, err := splitChatAttachmentName(c.Name) + if err != nil { + return err + } + outFlag := strings.TrimSpace(c.Out) + outPath := "" + if outFlag != "" { + outPath, err = config.ExpandPath(outFlag) + if err != nil { + return err + } + } + if dryRunErr := dryRunExit(ctx, flags, "chat.attachments.download", map[string]any{ + "message": messageName, + "attachment": attachmentName, + "out": outPath, + "overwrite": c.Overwrite, + }); dryRunErr != nil { + return dryRunErr + } + + 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 + } + + msg, err := svc.Spaces.Messages.Get(messageName).Context(ctx).Do() + if err != nil { + return err + } + attachments := compactChatAttachments(msg.Attachment) + if attachmentName != "" { + var picked []*chatAttachmentItem + for _, item := range attachments { + if item.Name == attachmentName { + picked = append(picked, item) + } + } + if len(picked) == 0 { + return usagef("attachment %q not found on %s (%d attachment(s))", attachmentName, messageName, len(attachments)) + } + attachments = picked + } + toDir := outFlag == "" || isDirIntent(outFlag, outPath) + if !toDir && len(attachments) > 1 { + return usagef("--out %q names a file but %s has %d attachments: name one attachment or pass a directory (trailing slash)", outFlag, messageName, len(attachments)) + } + + results := make([]map[string]any, 0, len(attachments)) + for _, item := range attachments { + row := map[string]any{ + "name": item.Name, + "contentName": item.ContentName, + "contentType": item.ContentType, + "source": item.Source, + } + switch { + case item.DriveDataRef != nil: + row["driveFileId"] = item.DriveDataRef.DriveFileID + row["skipped"] = "DRIVE_FILE: read it with gog drive download " + item.DriveDataRef.DriveFileID + case item.AttachmentDataRef == nil: + row["skipped"] = "no attachmentDataRef to download" + default: + dest := outPath + if toDir { + dir := outPath + if dir == "" { + dir = "." + } + dest = filepath.Join(dir, sanitizeAttachmentFilename(item.ContentName, chatAttachmentFallbackName(item.Name))) + } + path, size, sum, dlErr := downloadChatAttachment(ctx, svc, item.AttachmentDataRef.ResourceName, dest, c.Overwrite) + if dlErr != nil { + return fmt.Errorf("download %s: %w", item.Name, dlErr) + } + row["path"] = path + row["bytes"] = size + row["sha256"] = sum + } + results = append(results, row) + } + + if outfmt.IsJSON(ctx) { + return outfmt.WriteJSON(ctx, stdoutWriter(ctx), map[string]any{ + "message": messageName, + "attachments": results, + }) + } + if len(results) == 0 { + u.Err().Println("No attachments") + return nil + } + for _, row := range results { + u.Out().Linef("name\t%s", row["name"]) + for _, key := range []string{"contentName", "contentType", "source", "path", "bytes", "sha256", "driveFileId", "skipped"} { + if v, ok := row[key]; ok && fmt.Sprint(v) != "" { + u.Out().Linef("%s\t%s", key, tsvSafeValue(v)) + } + } + } + return nil +} + +// downloadChatAttachment streams media.download (a GET; allowed under --readonly) to +// dest and returns the absolute path, the byte count and the SHA-256 of what was written. +func downloadChatAttachment(ctx context.Context, svc *chat.Service, resourceName, dest string, overwrite bool) (string, int64, string, error) { + resp, err := svc.Media.Download(resourceName).Context(ctx).Download() + if err != nil { + return "", 0, "", err + } + defer resp.Body.Close() + f, path, err := openUserOutputFile(dest, outputFileOptions{Overwrite: overwrite, FileMode: 0o600, DirMode: 0o700}) + if err != nil { + return "", 0, "", err + } + hash := sha256.New() + n, copyErr := io.Copy(io.MultiWriter(f, hash), resp.Body) + closeErr := f.Close() + if copyErr != nil { + return "", 0, "", copyErr + } + if closeErr != nil { + return "", 0, "", closeErr + } + if abs, absErr := filepath.Abs(path); absErr == nil { + path = abs + } + return path, n, hex.EncodeToString(hash.Sum(nil)), nil +} diff --git a/internal/cmd/chat_attachments_test.go b/internal/cmd/chat_attachments_test.go new file mode 100644 index 000000000..f73e5c0d7 --- /dev/null +++ b/internal/cmd/chat_attachments_test.go @@ -0,0 +1,214 @@ +package cmd + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "os" + "path/filepath" + "strings" + "testing" +) + +func chatAttachmentFixtureMessage(name string, attachments ...map[string]any) map[string]any { + return map[string]any{ + "name": name, + "text": "See attached", + "createTime": "2026-01-02T03:04:05Z", + "sender": map[string]any{"name": "users/1", "displayName": "Test User", "type": "HUMAN"}, + "thread": map[string]any{"name": "spaces/aaa/threads/m1"}, + "attachment": attachments, + } +} + +func chatUploadedAttachmentFixture(messageName string) map[string]any { + return map[string]any{ + "name": messageName + "/attachments/att1", + "contentName": "Screenshot.png", + "contentType": "image/png", + "source": "UPLOADED_CONTENT", + "attachmentDataRef": map[string]any{"resourceName": messageName + "/attachments/att1"}, + "thumbnailUri": "https://chat.google.com/thumb", + "downloadUri": "https://chat.google.com/dl", + } +} + +func TestExecute_ChatMessagesList_JSON_CarriesAttachments(t *testing.T) { + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { + if !(r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/spaces/aaa/messages")) { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "messages": []map[string]any{ + chatAttachmentFixtureMessage("spaces/aaa/messages/m1", chatUploadedAttachmentFixture("spaces/aaa/messages/m1")), + {"name": "spaces/aaa/messages/m2", "text": "No attachment here", "createTime": "2026-01-02T03:04:00Z"}, + }, + }) + }) + + result := executeWithChatTestService(t, []string{"--account", "a@b.com", "--json", "chat", "messages", "list", "spaces/aaa"}, svc) + if result.err != nil { + t.Fatalf("Execute: %v", result.err) + } + var out struct { + Messages []struct { + Resource string `json:"resource"` + Attachments []*chatAttachmentItem `json:"attachments"` + } `json:"messages"` + } + if err := json.Unmarshal([]byte(result.stdout), &out); err != nil { + t.Fatalf("parse stdout: %v\n%s", err, result.stdout) + } + if len(out.Messages) != 2 { + t.Fatalf("messages = %d, want 2\n%s", len(out.Messages), result.stdout) + } + atts := out.Messages[0].Attachments + if len(atts) != 1 { + t.Fatalf("attachments = %d, want 1\n%s", len(atts), result.stdout) + } + a := atts[0] + if a.Name != "spaces/aaa/messages/m1/attachments/att1" || a.ContentName != "Screenshot.png" || a.ContentType != "image/png" || + a.Source != "UPLOADED_CONTENT" || a.AttachmentDataRef == nil || a.AttachmentDataRef.ResourceName != "spaces/aaa/messages/m1/attachments/att1" || + a.DriveDataRef != nil { + t.Fatalf("attachment = %+v (ref=%+v)", a, a.AttachmentDataRef) + } + if out.Messages[1].Attachments != nil { + t.Fatalf("message without attachments must omit the field:\n%s", result.stdout) + } + for _, leaked := range []string{"thumbnailUri", "downloadUri"} { + if strings.Contains(result.stdout, leaked) { + t.Fatalf("%s must not be projected:\n%s", leaked, result.stdout) + } + } +} + +func TestExecute_ChatAttachmentsDownload_JSON(t *testing.T) { + payload := []byte("\x89PNG\r\n\x1a\nfake-bytes-for-the-test") + mediaCalls := 0 + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/spaces/aaa/messages/m1"): + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(chatAttachmentFixtureMessage("spaces/aaa/messages/m1", chatUploadedAttachmentFixture("spaces/aaa/messages/m1"))) + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/media/spaces/aaa/messages/m1/attachments/att1") && r.URL.Query().Get("alt") == "media": + mediaCalls++ + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write(payload) + default: + http.NotFound(w, r) + } + }) + + dir := t.TempDir() + result := executeWithChatTestService(t, []string{"--account", "a@b.com", "--json", "chat", "attachments", "download", "spaces/aaa/messages/m1", "--out", dir + "/"}, svc) + if result.err != nil { + t.Fatalf("Execute: %v (stderr=%q)", result.err, result.stderr) + } + var out struct { + Message string `json:"message"` + Attachments []struct { + Name string `json:"name"` + ContentName string `json:"contentName"` + ContentType string `json:"contentType"` + Source string `json:"source"` + Path string `json:"path"` + Bytes int64 `json:"bytes"` + Sha256 string `json:"sha256"` + } `json:"attachments"` + } + if err := json.Unmarshal([]byte(result.stdout), &out); err != nil { + t.Fatalf("parse stdout: %v\n%s", err, result.stdout) + } + if out.Message != "spaces/aaa/messages/m1" || len(out.Attachments) != 1 { + t.Fatalf("unexpected output:\n%s", result.stdout) + } + got := out.Attachments[0] + wantPath := filepath.Join(dir, "Screenshot.png") + sum := sha256.Sum256(payload) + if got.Path != wantPath || got.Bytes != int64(len(payload)) || got.Sha256 != hex.EncodeToString(sum[:]) || + got.ContentName != "Screenshot.png" || got.ContentType != "image/png" || got.Source != "UPLOADED_CONTENT" { + t.Fatalf("attachment row = %+v, want path=%s bytes=%d sha256=%s", got, wantPath, len(payload), hex.EncodeToString(sum[:])) + } + data, err := os.ReadFile(wantPath) + if err != nil { + t.Fatalf("read downloaded file: %v", err) + } + if string(data) != string(payload) { + t.Fatalf("downloaded bytes differ") + } + if mediaCalls != 1 { + t.Fatalf("media.download calls = %d, want 1", mediaCalls) + } + + // a second run refuses to overwrite unless asked + result = executeWithChatTestService(t, []string{"--account", "a@b.com", "--json", "chat", "attachments", "download", "spaces/aaa/messages/m1", "--out", dir + "/"}, svc) + if result.err == nil { + t.Fatalf("expected an error on an existing file without --overwrite") + } + result = executeWithChatTestService(t, []string{"--account", "a@b.com", "--json", "chat", "attachments", "download", "spaces/aaa/messages/m1", "--out", dir + "/", "--overwrite"}, svc) + if result.err != nil { + t.Fatalf("Execute with --overwrite: %v", result.err) + } +} + +func TestExecute_ChatAttachmentsDownload_DriveFileIsNotFetched(t *testing.T) { + svc := useFakeChatService(t, func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/spaces/aaa/messages/m1"): + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(chatAttachmentFixtureMessage("spaces/aaa/messages/m1", + chatUploadedAttachmentFixture("spaces/aaa/messages/m1"), + map[string]any{ + "name": "spaces/aaa/messages/m1/attachments/d1", + "contentName": "Shared sheet", + "contentType": "application/vnd.google-apps.spreadsheet", + "source": "DRIVE_FILE", + "driveDataRef": map[string]any{"driveFileId": "1AbCdEf"}, + })) + case strings.Contains(r.URL.Path, "/media/"): + t.Errorf("media.download must not be called for a Drive attachment: %s", r.URL.Path) + http.NotFound(w, r) + default: + http.NotFound(w, r) + } + }) + + dir := t.TempDir() + result := executeWithChatTestService(t, []string{"--account", "a@b.com", "--json", "chat", "attachments", "download", "spaces/aaa/messages/m1/attachments/d1", "--out", dir + "/"}, svc) + if result.err != nil { + t.Fatalf("Execute: %v", result.err) + } + var out struct { + Attachments []map[string]any `json:"attachments"` + } + if err := json.Unmarshal([]byte(result.stdout), &out); err != nil { + t.Fatalf("parse stdout: %v\n%s", err, result.stdout) + } + if len(out.Attachments) != 1 || out.Attachments[0]["driveFileId"] != "1AbCdEf" || out.Attachments[0]["path"] != nil || + !strings.Contains(out.Attachments[0]["skipped"].(string), "gog drive download 1AbCdEf") { + t.Fatalf("unexpected output:\n%s", result.stdout) + } + entries, _ := os.ReadDir(dir) + if len(entries) != 0 { + t.Fatalf("nothing may be written for a Drive attachment, got %d file(s)", len(entries)) + } +} + +func TestSplitChatAttachmentName(t *testing.T) { + msg, att, err := splitChatAttachmentName("spaces/aaa/messages/m1.m1") + if err != nil || msg != "spaces/aaa/messages/m1.m1" || att != "" { + t.Fatalf("message name: %q %q %v", msg, att, err) + } + msg, att, err = splitChatAttachmentName(" spaces/aaa/messages/m1/attachments/x ") + if err != nil || msg != "spaces/aaa/messages/m1" || att != "spaces/aaa/messages/m1/attachments/x" { + t.Fatalf("attachment name: %q %q %v", msg, att, err) + } + for _, bad := range []string{"", "spaces/aaa", "spaces/aaa/threads/t1", "spaces/aaa/messages/m1/reactions/r1", "spaces//messages/m1", "m1"} { + if _, _, err := splitChatAttachmentName(bad); err == nil { + t.Fatalf("%q must be rejected", bad) + } + } +} diff --git a/internal/cmd/chat_messages.go b/internal/cmd/chat_messages.go index 799226d0d..32b3d7db5 100644 --- a/internal/cmd/chat_messages.go +++ b/internal/cmd/chat_messages.go @@ -229,6 +229,7 @@ func (c *ChatMessagesListCmd) Run(ctx context.Context, flags *RootFlags) error { Thread string `json:"thread,omitempty"` Annotations []*chat.Annotation `json:"annotations,omitempty"` EmojiReactionSummaries []*chat.EmojiReactionSummary `json:"emojiReactionSummaries,omitempty"` + Attachments []*chatAttachmentItem `json:"attachments,omitempty"` } items := make([]item, 0, len(messages)) for _, msg := range messages { @@ -265,6 +266,7 @@ func (c *ChatMessagesListCmd) Run(ctx context.Context, flags *RootFlags) error { Thread: chatMessageThread(msg), Annotations: mentions, EmojiReactionSummaries: reactions, + Attachments: compactChatAttachments(msg.Attachment), }) } if err := outfmt.WriteJSON(ctx, stdoutWriter(ctx), map[string]any{ diff --git a/safety-profiles/agent-safe.yaml b/safety-profiles/agent-safe.yaml index a75921044..5801bd486 100644 --- a/safety-profiles/agent-safe.yaml +++ b/safety-profiles/agent-safe.yaml @@ -256,6 +256,8 @@ chat: dm: send: false space: false + attachments: + download: true forms: get: true diff --git a/safety-profiles/readonly.yaml b/safety-profiles/readonly.yaml index 00a2e7d9d..e746f91d2 100644 --- a/safety-profiles/readonly.yaml +++ b/safety-profiles/readonly.yaml @@ -261,6 +261,8 @@ chat: dm: send: false space: false + attachments: + download: true forms: get: true