diff --git a/VERSION b/VERSION index 9084fa2..26aaba0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.1.0 +1.2.0 diff --git a/internal/api/attachments.go b/internal/api/attachments.go new file mode 100644 index 0000000..f8c4cc6 --- /dev/null +++ b/internal/api/attachments.go @@ -0,0 +1,92 @@ +package api + +import ( + "context" + "errors" + "io" + "mime/multipart" + "net/http" + "net/url" + "path/filepath" + "strings" +) + +// AttachmentBatch holds paths in delivery order and an opener for each path. +// A send opens and closes at most one input at a time. +type AttachmentBatch struct { + Paths []string + Open func(string) (io.ReadCloser, error) +} + +// AttachmentReadError means an input could not be opened or streamed. +type AttachmentReadError struct { + Path string + Err error +} + +func (e *AttachmentReadError) Error() string { return "could not read attachment" } +func (e *AttachmentReadError) Unwrap() error { return e.Err } + +// NotifyUserWithAttachments sends a batch to the user's private chat. +func (c *Client) NotifyUserWithAttachments(ctx context.Context, token, userID, message, platform string, batch AttachmentBatch) (Delivery, error) { + return c.notifyMultipart(ctx, "/cli/notify/user/"+url.PathEscape(userID), token, message, platform, batch) +} + +// NotifyChatWithAttachments sends a batch to a chat. +func (c *Client) NotifyChatWithAttachments(ctx context.Context, token, chatID, message string, batch AttachmentBatch) (Delivery, error) { + return c.notifyMultipart(ctx, "/cli/notify/chat/"+url.PathEscape(chatID), token, message, "", batch) +} + +func (c *Client) notifyMultipart(ctx context.Context, path, token, message, platform string, batch AttachmentBatch) (Delivery, error) { + reader, writer := io.Pipe() + form := multipart.NewWriter(writer) + contentType := form.FormDataContentType() + done := make(chan struct{}) + var producerErr error + go func() { + defer close(done) + producerErr = writeAttachments(form, message, platform, batch) + _ = writer.CloseWithError(producerErr) + }() + status, body, err := c.callBody(ctx, http.MethodPost, path, token, reader, contentType) + _ = reader.Close() + <-done + var inputErr *AttachmentReadError + if status == 0 && errors.As(producerErr, &inputErr) { + return Delivery{}, inputErr + } + return notifyResult(status, body, err) +} + +func writeAttachments(form *multipart.Writer, message, platform string, batch AttachmentBatch) error { + if err := form.WriteField("message", message); err != nil { + return err + } + if platform != "" { + if err := form.WriteField("platform", platform); err != nil { + return err + } + } + var buffer [32 * 1024]byte + for _, path := range batch.Paths { + // percent-encode line breaks so a basename cannot add headers to its part. + name := strings.ReplaceAll(strings.ReplaceAll(filepath.Base(path), "\r", "%0D"), "\n", "%0A") + part, err := form.CreateFormFile("attachments", name) + if err != nil { + return err + } + file, err := batch.Open(path) + if err != nil { + return &AttachmentReadError{Path: path, Err: err} + } + _, err = io.CopyBuffer(part, struct{ io.Reader }{file}, buffer[:]) + _ = file.Close() + if err != nil { + if errors.Is(err, io.ErrClosedPipe) { + return err + } + return &AttachmentReadError{Path: path, Err: err} + } + } + return form.Close() +} diff --git a/internal/api/client.go b/internal/api/client.go index 8aa477f..97d7bab 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -78,22 +78,25 @@ func New(o Options) *Client { // call sends one request and returns the body of a 2xx answer. A non-2xx answer is a classified // *Error; a transport failure is KindUnreachable. token is sent as a bearer token when not empty. func (c *Client) call(ctx context.Context, method, path, token string, payload any) (status int, body []byte, err error) { - var reader io.Reader - if payload != nil { - encoded, err := json.Marshal(payload) - if err != nil { - return 0, nil, err - } - reader = bytes.NewReader(encoded) + if payload == nil { + return c.callBody(ctx, method, path, token, nil, "") + } + encoded, err := json.Marshal(payload) + if err != nil { + return 0, nil, err } + return c.callBody(ctx, method, path, token, bytes.NewReader(encoded), "application/json") +} + +func (c *Client) callBody(ctx context.Context, method, path, token string, reader io.Reader, contentType string) (status int, body []byte, err error) { req, err := http.NewRequestWithContext(ctx, method, c.base+path, reader) if err != nil { return 0, nil, &Error{Kind: KindUnreachable, Cause: err} } req.Header.Set("Accept", "application/json") req.Header.Set("User-Agent", c.userAgent) - if payload != nil { - req.Header.Set("Content-Type", "application/json") + if contentType != "" { + req.Header.Set("Content-Type", contentType) } if token != "" { req.Header.Set("Authorization", "Bearer "+token) diff --git a/internal/api/endpoints.go b/internal/api/endpoints.go index 3d5918b..f4e2aef 100644 --- a/internal/api/endpoints.go +++ b/internal/api/endpoints.go @@ -176,6 +176,10 @@ func (c *Client) NotifyChat(ctx context.Context, token, chatID, message string) func (c *Client) notify(ctx context.Context, path, token string, payload any) (Delivery, error) { status, body, err := c.call(ctx, http.MethodPost, path, token, payload) + return notifyResult(status, body, err) +} + +func notifyResult(status int, body []byte, err error) (Delivery, error) { if err != nil && (status < 200 || status >= 300) { return Delivery{}, err } diff --git a/internal/api/endpoints_test.go b/internal/api/endpoints_test.go index 542d2e5..4018173 100644 --- a/internal/api/endpoints_test.go +++ b/internal/api/endpoints_test.go @@ -1,9 +1,19 @@ package api_test import ( + "context" "encoding/json" + "errors" + "io" + "mime" "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "strings" + "sync/atomic" "testing" + "testing/iotest" "time" "github.com/appifyhub/agent-cli/internal/api" @@ -314,3 +324,152 @@ func TestNotifyErrorsAreClassified(t *testing.T) { _, err := newClient(b).NotifyUser(t.Context(), secretToken, "u1", "hi", "") _ = wantKind(t, err, api.KindInsufficientCredits) } + +func TestNotifyMultipartContract(t *testing.T) { + for _, tc := range []struct { + name, route string + fields [][3]string + }{ + {"private", "/cli/notify/user/u%2F%3F", [][3]string{{"message", "", "caption"}, {"platform", "", "whatsapp"}}}, + {"chat", "/cli/notify/chat/c%2F%3F", [][3]string{{"message", "", "caption"}}}, + } { + t.Run(tc.name, func(t *testing.T) { + first, second := filepath.Join("local", "a.png"), filepath.Join("local", "b, revised.pdf") + data := map[string]string{first: "\x00one", second: "two\xff"} + want := append(tc.fields, [3]string{"attachments", "a.png", data[first]}, [3]string{"attachments", "b, revised.pdf", data[second]}) + var hits atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + if r.Method != http.MethodPost || r.URL.EscapedPath() != tc.route || r.URL.RawQuery != "" || r.Header.Get("Authorization") != "Bearer "+secretToken { + t.Errorf("unexpected route or credentials: %s %s", r.Method, r.URL) + } + form, err := r.MultipartReader() + if err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + var got [][3]string + for { + part, err := form.NextPart() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + t.Error(err) + break + } + bytes, err := io.ReadAll(part) + if err != nil { + t.Error(err) + } + disposition, params, err := mime.ParseMediaType(part.Header.Get("Content-Disposition")) + if err != nil || disposition != "form-data" { + t.Errorf("invalid multipart disposition: %q, %v", disposition, err) + } + got = append(got, [3]string{params["name"], params["filename"], string(bytes)}) + } + if !slices.Equal(got, want) { + t.Errorf("multipart parts = %q, want %q", got, want) + } + w.WriteHeader(http.StatusNoContent) + })) + defer server.Close() + client := api.New(api.Options{BaseURL: server.URL, Transport: server.Client().Transport}) + batch := api.AttachmentBatch{Paths: []string{first, second}, Open: func(path string) (io.ReadCloser, error) { + return io.NopCloser(strings.NewReader(data[path])), nil + }} + var err error + if tc.name == "private" { + _, err = client.NotifyUserWithAttachments(t.Context(), secretToken, "u/?", "caption", "whatsapp", batch) + } else { + _, err = client.NotifyChatWithAttachments(t.Context(), secretToken, "c/?", "caption", batch) + } + if err != nil || hits.Load() != 1 { + t.Fatalf("send = %v; requests = %d", err, hits.Load()) + } + }) + } +} + +func TestNotifyMultipartInterruptions(t *testing.T) { + for _, scenario := range []string{"cancelled", "input read failure", "early rejection", "lost response", "unreadable success"} { + t.Run(scenario, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + readErr := errors.New("input failed") + var reader io.Reader = strings.NewReader(strings.Repeat("x", 64*1024)) + if scenario == "input read failure" { + reader = iotest.ErrReader(readErr) + } + file := &trackedResponseBody{Reader: reader} + opens, hits := 0, 0 + batch := api.AttachmentBatch{Paths: []string{"a.png"}, Open: func(string) (io.ReadCloser, error) { + opens++ + return file, nil + }} + unreadable := unusableBody(`{"credit_balance":1}`, false) + client := api.New(api.Options{ + BaseURL: "http://backend.test", + Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) { + hits++ + if scenario == "cancelled" || scenario == "early rejection" { + form, err := req.MultipartReader() + if err != nil { + t.Fatal(err) + } + if _, err := form.NextPart(); err != nil { + t.Fatal(err) + } + part, err := form.NextPart() + if err != nil { + t.Fatal(err) + } + var firstByte [1]byte + if _, err := io.ReadFull(part, firstByte[:]); err != nil { + t.Fatal(err) + } + if scenario == "cancelled" { + cancel() + return nil, req.Context().Err() + } + return &http.Response{StatusCode: http.StatusTooManyRequests, Body: io.NopCloser(strings.NewReader(""))}, nil + } + if _, err := io.Copy(io.Discard, req.Body); err != nil { + return nil, err + } + if scenario == "lost response" { + return nil, io.ErrUnexpectedEOF + } + return &http.Response{StatusCode: http.StatusAccepted, Body: unreadable}, nil + }), + }) + got, err := client.NotifyChatWithAttachments(ctx, secretToken, "c1", "caption", batch) + switch scenario { + case "cancelled": + if !errors.Is(err, context.Canceled) { + t.Fatal(err) + } + case "input read failure": + var inputErr *api.AttachmentReadError + if !errors.Is(err, readErr) || !errors.As(err, &inputErr) || inputErr.Path != "a.png" { + t.Fatalf("missing local read failure: %v", err) + } + case "early rejection": + _ = wantKind(t, err, api.KindRateLimited) + case "lost response": + failure := wantKind(t, err, api.KindUnreachable) + if failure.Status != 0 { + t.Fatal("a lost response cannot establish delivery progress") + } + case "unreadable success": + if err != nil || got.CreditBalance != nil || got.Chat != nil || unreadable.closes != 1 { + t.Fatalf("delivery = %+v, %v; response closes = %d", got, err, unreadable.closes) + } + } + if hits != 1 || opens != 1 || file.closes != 1 { + t.Fatalf("requests = %d, input opens/closes = %d/%d", hits, opens, file.closes) + } + }) + } +} diff --git a/internal/api/errors.go b/internal/api/errors.go index 802decf..01c98dc 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -161,7 +161,7 @@ func decodeErrorBody(body []byte) (code int, message string, detail bool) { var ( errorMarker = regexp.MustCompile(`^\s*\[E\d+\][^\p{L}\p{N}]*`) - causeSuffix = regexp.MustCompile(`\s+# Caused by:.*$`) + causeSuffix = regexp.MustCompile(`(?s)\s+# Caused by:.*$`) ) // CleanMessage reduces a server message to its text: the leading [E] marker with the emoji diff --git a/internal/cli/connect_test.go b/internal/cli/connect_test.go index 36613e9..33ae35e 100644 --- a/internal/cli/connect_test.go +++ b/internal/cli/connect_test.go @@ -6,6 +6,8 @@ import ( "encoding/json" "errors" "io" + "mime" + "mime/multipart" "net/http" "os" "path/filepath" @@ -1831,6 +1833,143 @@ func TestNotifyBoundedInputAndArgumentPrecedence(t *testing.T) { } } +func TestNotifyAttachmentsContract(t *testing.T) { + for _, tc := range []struct { + name, input, caption, route, platform string + names []string + args []string + tty bool + }{ + {"screenshots", "ignored", "Before and after", "/cli/notify/chat/" + chatsFirstID, "", []string{"before.png", "after, revised.png"}, []string{"Before and after"}, false}, + {"document then photo", "\nNightly report\n", "Nightly report", "/cli/notify/user/u1", "whatsapp", []string{"report.pdf", "after.png"}, []string{"--platform", "WhatsApp"}, false}, + {"repeated file", "not read", "Build finished", "/cli/notify/chat/" + chatsFirstID, "", []string{"a file.png", "a file.png"}, []string{"Build finished"}, true}, + {"terminal without caption", "not read", "", "/cli/notify/chat/" + chatsFirstID, "", []string{"report.pdf"}, nil, true}, + {"blank caption", "not read", "", "/cli/notify/chat/" + chatsFirstID, "", []string{"report.pdf"}, []string{" "}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + r := newChatsRig(t, "linux") + stdin := strings.NewReader(tc.input) + r.deps.Stdin, r.terminal.TTYIn = stdin, tc.tty + r.backend.Handle(http.MethodPost, tc.route, testkit.NotifyOK(testkit.ChatJSON("c1", "telegram", stringPointer("Team"), false), 42.37)) + args := append([]string{"-v"}, tc.args...) + dir := t.TempDir() + for _, name := range tc.names { + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte("contents of "+name), 0o600); err != nil { + t.Fatal(err) + } + args = append(args, "--attach", path) + } + got := runNotifyTest(t, r, args...) + if got.Code != 0 || got.Stdout != "✓ Sent to Telegram · Team (group)\n" || !strings.Contains(got.Stderr, "warning: low credit balance: 42.37 credits left") || r.backend.Count() != 1 || len(r.terminal.Prompts) != 0 { + t.Fatalf("result = %+v; requests = %d; prompts = %v", got, r.backend.Count(), r.terminal.Prompts) + } + if tc.name != "document then photo" && stdin.Len() != len(tc.input) { + t.Fatal("read stdin when a caption argument or terminal stdin was present") + } + req := r.backend.Last(t) + mediaType, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil || mediaType != "multipart/form-data" || req.Method != http.MethodPost || req.Path != tc.route { + t.Fatalf("unexpected upload: %s %s (%s, %v)", req.Method, req.Path, mediaType, err) + } + form := multipart.NewReader(strings.NewReader(req.Body), params["boundary"]) + var parts [][3]string + for { + part, err := form.NextPart() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + t.Fatal(err) + } + content, err := io.ReadAll(part) + if err != nil { + t.Fatal(err) + } + parts = append(parts, [3]string{part.FormName(), part.FileName(), string(content)}) + } + want := [][3]string{{"message", "", tc.caption}} + if tc.platform != "" { + want = append(want, [3]string{"platform", "", tc.platform}) + } + for _, name := range tc.names { + want = append(want, [3]string{"attachments", name, "contents of " + name}) + } + if !slices.Equal(parts, want) { + t.Fatalf("parts = %q, want %q", parts, want) + } + }) + } +} + +func TestNotifyAttachmentsRejectInvalidInput(t *testing.T) { + dir := t.TempDir() + valid := filepath.Join(dir, "report.pdf") + if err := os.WriteFile(valid, []byte("report"), 0o600); err != nil { + t.Fatal(err) + } + for _, path := range []string{dir, filepath.Join(dir, "missing.png")} { + r := newConnectRig(t, "linux") + r.terminal.TTYIn = true + got := runNotifyTest(t, r, "Build finished", "--attach", valid, "--attach", path) + if got.Code != 2 || !strings.Contains(got.Stderr, strconv.Quote(path)) || r.backend.Count() != 0 || len(r.keychain.Calls) != 0 { + t.Fatalf("invalid path: %+v; requests = %d", got, r.backend.Count()) + } + } + r := newChatsRig(t, "linux") + reader := ¬ifyCountingReader{} + r.deps.Stdin = reader + got := runNotifyTest(t, r, "--attach", valid) + if got.Code != 2 || !strings.Contains(got.Stderr, "piped caption input is too long") || reader.bytes != 16385 || r.backend.Count() != 0 { + t.Fatalf("unbounded or truncated caption: %+v; bytes read = %d; requests = %d", got, reader.bytes, r.backend.Count()) + } + r.deps.Stdin = strings.NewReader(strings.Repeat("a", 4097)) + got = runNotifyTest(t, r, "--attach", valid) + if got.Code != 2 || !strings.Contains(got.Stderr, "max 4096 characters") || r.backend.Count() != 0 { + t.Fatalf("overlong caption was not rejected: %+v; requests = %d", got, r.backend.Count()) + } +} + +func TestNotifyAttachmentsFailureProgress(t *testing.T) { + dir := t.TempDir() + args := []string{"Build finished"} + for _, name := range []string{"first.png", "second\u202e.png", "third.pdf"} { + path := filepath.Join(dir, name) + if err := os.WriteFile(path, []byte("file"), 0o600); err != nil { + t.Fatal(err) + } + args = append(args, "--attach", path) + } + t.Run("confirmed prefix", func(t *testing.T) { + r := newChatsRig(t, "linux") + r.terminal.TTYIn = true + r.backend.Handle(http.MethodPost, "/cli/notify/chat/"+chatsFirstID, testkit.JSON(502, map[string]any{ + "error_code": 5018, "message": "Attachment delivery stopped: 1 of 3 attachments confirmed # Caused by: storage failure\nprivate diagnostic", + })) + got := runNotifyTest(t, r, args...) + if got.Code != 1 || got.Stdout != "" || got.Stderr != "error: Attachment delivery stopped: 1 of 3 attachments confirmed\n" || r.backend.Count() != 1 { + t.Fatalf("wrong progress or replay: %+v; requests = %d", got, r.backend.Count()) + } + }) + t.Run("lost response", func(t *testing.T) { + r := newChatsRig(t, "linux") + r.terminal.TTYIn = true + hits := 0 + r.deps.HTTP = commandRoundTrip(func(req *http.Request) (*http.Response, error) { + hits++ + defer func() { _ = req.Body.Close() }() + if _, err := io.Copy(io.Discard, req.Body); err != nil { + t.Error(err) + } + return nil, io.ErrUnexpectedEOF + }) + got := runNotifyTest(t, r, args...) + if got.Code != 1 || got.Stdout != "" || !strings.Contains(got.Stderr, "attachment delivery outcome unknown") || strings.Contains(got.Stderr, "Not attempted:") || strings.Contains(got.Stderr, "Confirmed:") || hits != 1 { + t.Fatalf("claimed progress or replayed: %+v; requests = %d", got, hits) + } + }) +} + func TestNotifyLockedCredentials(t *testing.T) { for _, goos := range []string{"linux", "windows"} { t.Run(goos, func(t *testing.T) { diff --git a/internal/cli/failures.go b/internal/cli/failures.go index 3e4a5d8..44760dc 100644 --- a/internal/cli/failures.go +++ b/internal/cli/failures.go @@ -2,6 +2,7 @@ package cli import ( "errors" + "strconv" "github.com/appifyhub/agent-cli/internal/api" "github.com/appifyhub/agent-cli/internal/config" @@ -133,6 +134,9 @@ func translate(cat *text.Catalog, name string, err error) error { // apiFailure gives the outcomes of backend calls their catalog text and exit code. func apiFailure(cat *text.Catalog, name string, err error) error { + if attachment, ok := errors.AsType[*api.AttachmentReadError](err); ok { + return &Failure{Code: ExitFailure, Message: cat.T("notify.invalid_attachment", "path", strconv.Quote(attachment.Path))} + } var apiErr *api.Error if !errors.As(err, &apiErr) { return err diff --git a/internal/cli/message.go b/internal/cli/message.go index e7beb1a..4a7ae66 100644 --- a/internal/cli/message.go +++ b/internal/cli/message.go @@ -9,7 +9,7 @@ import ( "github.com/appifyhub/agent-cli/internal/term" ) -func (s *rootState) notifyMessage(args []string) (string, error) { +func (s *rootState) notifyMessage(args []string, attachments bool) (string, error) { cat := s.deps.Text if len(args) > 1 { return "", usageError(cat.T("notify.single_argument")) @@ -19,20 +19,31 @@ func (s *rootState) notifyMessage(args []string) (string, error) { message = args[0] } else { if s.deps.Term.IsTTY(term.In) { + if attachments { + return "", nil + } return "", usageError(cat.T("notify.missing_message")) } - data, err := io.ReadAll(io.LimitReader(s.deps.Stdin, 4*4096)) + const maxBytes = 4 * 4096 + limit := int64(maxBytes) + if attachments { + limit++ + } + data, err := io.ReadAll(io.LimitReader(s.deps.Stdin, limit)) if err != nil { return "", err } + if attachments && len(data) > maxBytes { + return "", usageError(cat.T("notify.long_caption_input")) + } message = string(data) } message = strings.TrimSpace(strings.TrimPrefix(strings.ToValidUTF8(message, "\uFFFD"), "\uFEFF")) - if message == "" { + if message == "" && !attachments { return "", usageError(cat.T("notify.empty_message")) } if utf8.RuneCountInString(message) > 4096 { - if len(args) == 1 { + if len(args) == 1 || attachments { return "", usageError(cat.T("notify.long_message")) } count := 0 diff --git a/internal/cli/notify.go b/internal/cli/notify.go index 887e96a..b301205 100644 --- a/internal/cli/notify.go +++ b/internal/cli/notify.go @@ -2,7 +2,12 @@ package cli import ( "context" + "errors" "fmt" + "io" + "io/fs" + "os" + "strconv" "github.com/spf13/cobra" @@ -16,6 +21,7 @@ import ( func (s *rootState) notifyCommand() *cobra.Command { cat, name := s.deps.Text, s.deps.Build.Name var chat, platform string + var paths []string command := withHelp(&cobra.Command{ Use: "notify []", Short: cat.T("command.notify.short"), Long: cat.T("command.notify.long"), Args: func(cmd *cobra.Command, args []string) error { @@ -29,13 +35,22 @@ func (s *rootState) notifyCommand() *cobra.Command { return nil }, RunE: func(cmd *cobra.Command, args []string) error { - message, err := s.notifyMessage(args) + message, err := s.notifyMessage(args, len(paths) != 0) if err != nil { return err } - return s.runNotify(cmd.Context(), message, chat, platform, cmd.Flags().Changed("chat"), cmd.Flags().Changed("platform")) + for _, path := range paths { + file, err := openNotifyAttachment(path) + if err != nil { + return usageError(cat.T("notify.invalid_attachment", "path", strconv.Quote(path))) + } + _ = file.Close() + } + return s.runNotify(cmd.Context(), message, chat, platform, cmd.Flags().Changed("chat"), cmd.Flags().Changed("platform"), paths) }, }, cat.T("command.notify.examples", "name", name), cat.T("command.notify.environment"), cat.T("command.notify.exit_codes")) + command.Flags().StringArrayVar(&paths, "attach", nil, cat.T("command.notify.flag_attach")) + _ = command.MarkFlagFilename("attach") command.Flags().StringVar(&chat, "chat", "", cat.T("command.notify.flag_chat")) command.Flags().StringVar(&platform, "platform", "", cat.T("command.notify.flag_platform")) _ = command.RegisterFlagCompletionFunc("platform", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { @@ -44,7 +59,7 @@ func (s *rootState) notifyCommand() *cobra.Command { return command } -func (s *rootState) runNotify(ctx context.Context, message, chat, platform string, chatSet, platformSet bool) error { +func (s *rootState) runNotify(ctx context.Context, message, chat, platform string, chatSet, platformSet bool, paths []string) error { d := s.deps home, err := config.ResolveHome(d.Getenv, d.UserHomeDir, d.Build.Name) if err != nil { @@ -74,7 +89,21 @@ func (s *rootState) runNotify(ctx context.Context, message, chat, platform strin } client := s.newClient(apiURL) var callErr error - if target.ChatID != "" { + if len(paths) != 0 { + batch := api.AttachmentBatch{Paths: paths, Open: openNotifyAttachment} + if target.ChatID != "" { + delivery, callErr = client.NotifyChatWithAttachments(ctx, identity.Token, target.ChatID, message, batch) + } else { + delivery, callErr = client.NotifyUserWithAttachments(ctx, identity.Token, identity.UserID, message, target.Platform, batch) + } + if api.IsKind(callErr, api.KindUnreachable) || errors.Is(callErr, context.Canceled) || errors.Is(callErr, context.DeadlineExceeded) { + _, _ = fmt.Fprintln(d.Stderr, d.styled(term.Err, term.Warning, d.Text.T("notify.attachment_unknown"))) + } + var backend *api.Error + if errors.As(callErr, &backend) && backend.Kind == api.KindServerFault && backend.Code == api.CodeNotificationUndelivered && backend.Message != "" { + return &Failure{Code: ExitFailure, Message: backend.Message} + } + } else if target.ChatID != "" { delivery, callErr = client.NotifyChat(ctx, identity.Token, target.ChatID, message) } else { delivery, callErr = client.NotifyUser(ctx, identity.Token, identity.UserID, message, target.Platform) @@ -111,3 +140,26 @@ func (s *rootState) runNotify(ctx context.Context, message, chat, platform strin s.warnLowCredit(delivery.CreditBalance) return nil } + +func openNotifyAttachment(path string) (io.ReadCloser, error) { + info, err := os.Stat(path) + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, fs.ErrInvalid + } + file, err := os.OpenFile(path, os.O_RDONLY|notifyOpenFlags, 0) + if err != nil { + return nil, err + } + info, err = file.Stat() + if err == nil && info.Mode().IsRegular() { + return file, nil + } + _ = file.Close() + if err != nil { + return nil, err + } + return nil, fs.ErrInvalid +} diff --git a/internal/cli/notify_file_other.go b/internal/cli/notify_file_other.go new file mode 100644 index 0000000..52337be --- /dev/null +++ b/internal/cli/notify_file_other.go @@ -0,0 +1,5 @@ +//go:build !unix + +package cli + +const notifyOpenFlags = 0 diff --git a/internal/cli/notify_file_unix.go b/internal/cli/notify_file_unix.go new file mode 100644 index 0000000..4f85491 --- /dev/null +++ b/internal/cli/notify_file_unix.go @@ -0,0 +1,8 @@ +//go:build unix + +package cli + +import "golang.org/x/sys/unix" + +// opening a path swapped for a FIFO after stat must not block. +const notifyOpenFlags = unix.O_NONBLOCK diff --git a/internal/cli/testdata/notify_help_unix.golden b/internal/cli/testdata/notify_help_unix.golden index ca6405c..88a2b69 100644 --- a/internal/cli/testdata/notify_help_unix.golden +++ b/internal/cli/testdata/notify_help_unix.golden @@ -1,5 +1,6 @@ -Send one quoted message, or read stdin when no argument is given. An argument takes precedence over a pipe. A terminal without a message fails immediately. -Leading BOM and surrounding whitespace are removed; interior newlines are preserved. Messages must contain 1–4096 characters. Stdin reads at most 16 KiB and is truncated to 4096 characters; longer arguments are rejected. +Send one quoted message, or read stdin when no argument is given. An argument takes precedence over a pipe. +Use --attach once per local file. Files are sent individually in order; an optional message captions the first file only. +Leading BOM and surrounding whitespace are removed; interior newlines are preserved. Text-only sends require 1–4096 characters. Text-only stdin reads at most 16 KiB and is truncated to 4096 characters. Captions over 4096 characters or 16 KiB of piped input are rejected. Choose --chat or --platform, never both. Flags override THE_AGENT_CLI_DEFAULT_CHAT, then THE_AGENT_CLI_DEFAULT_PLATFORM, then the stored default. Without a target the backend selects your latest private chat. Success is silent unless --verbose is set. Notifications are never retried automatically. @@ -7,6 +8,7 @@ Notifications are never retried automatically. Usage: agent-cli notify [] Flags: + --attach Attach one local path per occurrence (repeatable) --chat Send to this chat ID --platform Send to your latest private chat on telegram or whatsapp -h, --help Print help @@ -16,6 +18,7 @@ Examples: agent-cli notify "Build finished" agent-cli notify --chat "" "Dinner's ready" agent-cli notify --platform whatsapp "Deploy done" -v + agent-cli notify "Before and after" --attach ./before.png --attach "./after, revised.png" echo "Backup finished" | agent-cli notify Environment: THE_AGENT_CLI_HOME, THE_AGENT_CLI_API_URL, THE_AGENT_CLI_TOKEN, THE_AGENT_CLI_PASSPHRASE, THE_AGENT_CLI_DEFAULT_CHAT, THE_AGENT_CLI_DEFAULT_PLATFORM diff --git a/internal/cli/testdata/notify_help_windows.golden b/internal/cli/testdata/notify_help_windows.golden index 40d57b6..8347ce1 100644 --- a/internal/cli/testdata/notify_help_windows.golden +++ b/internal/cli/testdata/notify_help_windows.golden @@ -1,5 +1,6 @@ -Send one quoted message, or read stdin when no argument is given. An argument takes precedence over a pipe. A terminal without a message fails immediately. -Leading BOM and surrounding whitespace are removed; interior newlines are preserved. Messages must contain 1–4096 characters. Stdin reads at most 16 KiB and is truncated to 4096 characters; longer arguments are rejected. +Send one quoted message, or read stdin when no argument is given. An argument takes precedence over a pipe. +Use --attach once per local file. Files are sent individually in order; an optional message captions the first file only. +Leading BOM and surrounding whitespace are removed; interior newlines are preserved. Text-only sends require 1–4096 characters. Text-only stdin reads at most 16 KiB and is truncated to 4096 characters. Captions over 4096 characters or 16 KiB of piped input are rejected. Choose --chat or --platform, never both. Flags override THE_AGENT_CLI_DEFAULT_CHAT, then THE_AGENT_CLI_DEFAULT_PLATFORM, then the stored default. Without a target the backend selects your latest private chat. Success is silent unless --verbose is set. Notifications are never retried automatically. @@ -8,6 +9,7 @@ PowerShell 7 pipes UTF-8 by default. In Windows PowerShell 5.1, set $OutputEncod Usage: agent-cli notify [] Flags: + --attach Attach one local path per occurrence (repeatable) --chat Send to this chat ID --platform Send to your latest private chat on telegram or whatsapp -h, --help Print help @@ -17,6 +19,7 @@ Examples: agent-cli notify "Build finished" agent-cli notify --chat "" "Dinner's ready" agent-cli notify --platform whatsapp "Deploy done" -v + agent-cli notify "Before and after" --attach ./before.png --attach "./after, revised.png" echo "Backup finished" | agent-cli notify Environment: THE_AGENT_CLI_HOME, THE_AGENT_CLI_API_URL, THE_AGENT_CLI_TOKEN, THE_AGENT_CLI_PASSPHRASE, THE_AGENT_CLI_DEFAULT_CHAT, THE_AGENT_CLI_DEFAULT_PLATFORM diff --git a/internal/cli/testdata/skill_guide_unix.golden b/internal/cli/testdata/skill_guide_unix.golden index 556141e..d3179e4 100644 --- a/internal/cli/testdata/skill_guide_unix.golden +++ b/internal/cli/testdata/skill_guide_unix.golden @@ -25,6 +25,7 @@ echo "Build finished" | agent-cli notify agent-cli notify --platform telegram "Build finished" agent-cli notify --platform whatsapp "Build finished" agent-cli notify --chat "" "Build finished" +agent-cli notify "Before and after" --attach ./before.png --attach "./after, revised.png" Choose --chat or --platform, never both. Run agent-cli chats to list valid chat IDs. Flags override environment defaults, which override the stored default. @@ -33,9 +34,9 @@ Without a target, the backend uses the user's latest private chat. agent-cli chats default shows the effective target offline. Only on the user's request, change it with agent-cli chats default --set "", --platform telegram or --platform whatsapp, or --clear. Success is silent. Use --verbose only when delivery details are needed. -An argument must be one quoted message. With no argument, stdin is read. -Messages are limited to 4096 characters; oversized stdin is truncated with a warning, but oversized arguments fail. -Do not claim delivery unless the command exits 0. +Pass the message as one argument or pipe it on stdin. With attachments, the message is optional. +Pass --attach once per file, in delivery order. An optional message captions the first file only. Piped captions over 4096 characters or 16 KiB of input fail. +Send only files the user intends to share. Treat exit 0 as success; on failure, report only the items explicitly confirmed, or say that delivery is unknown. ## Handle failures diff --git a/internal/cli/testdata/skill_guide_windows.golden b/internal/cli/testdata/skill_guide_windows.golden index 7e97d76..54d3995 100644 --- a/internal/cli/testdata/skill_guide_windows.golden +++ b/internal/cli/testdata/skill_guide_windows.golden @@ -25,6 +25,7 @@ echo "Build finished" | agent-cli notify agent-cli notify --platform telegram "Build finished" agent-cli notify --platform whatsapp "Build finished" agent-cli notify --chat "" "Build finished" +agent-cli notify "Before and after" --attach ./before.png --attach "./after, revised.png" Choose --chat or --platform, never both. Run agent-cli chats to list valid chat IDs. Flags override environment defaults, which override the stored default. @@ -33,9 +34,9 @@ Without a target, the backend uses the user's latest private chat. agent-cli chats default shows the effective target offline. Only on the user's request, change it with agent-cli chats default --set "", --platform telegram or --platform whatsapp, or --clear. Success is silent. Use --verbose only when delivery details are needed. -An argument must be one quoted message. With no argument, stdin is read. -Messages are limited to 4096 characters; oversized stdin is truncated with a warning, but oversized arguments fail. -Do not claim delivery unless the command exits 0. +Pass the message as one argument or pipe it on stdin. With attachments, the message is optional. +Pass --attach once per file, in delivery order. An optional message captions the first file only. Piped captions over 4096 characters or 16 KiB of input fail. +Send only files the user intends to share. Treat exit 0 as success; on failure, report only the items explicitly confirmed, or say that delivery is unknown. ## Handle failures diff --git a/internal/text/skill.md b/internal/text/skill.md index 820b8a9..51556ea 100644 --- a/internal/text/skill.md +++ b/internal/text/skill.md @@ -25,6 +25,7 @@ echo "Build finished" | {name} notify {name} notify --platform telegram "Build finished" {name} notify --platform whatsapp "Build finished" {name} notify --chat "" "Build finished" +{name} notify "Before and after" --attach ./before.png --attach "./after, revised.png" Choose --chat or --platform, never both. Run {name} chats to list valid chat IDs. Flags override environment defaults, which override the stored default. @@ -33,9 +34,9 @@ Without a target, the backend uses the user's latest private chat. {name} chats default shows the effective target offline. Only on the user's request, change it with {name} chats default --set "", --platform telegram or --platform whatsapp, or --clear. Success is silent. Use --verbose only when delivery details are needed. -An argument must be one quoted message. With no argument, stdin is read. -Messages are limited to 4096 characters; oversized stdin is truncated with a warning, but oversized arguments fail. -Do not claim delivery unless the command exits 0. +Pass the message as one argument or pipe it on stdin. With attachments, the message is optional. +Pass --attach once per file, in delivery order. An optional message captions the first file only. Piped captions over 4096 characters or 16 KiB of input fail. +Send only files the user intends to share. Treat exit 0 as success; on failure, report only the items explicitly confirmed, or say that delivery is unknown. ## Handle failures diff --git a/internal/text/strings.toml b/internal/text/strings.toml index 3be9612..01ab16f 100644 --- a/internal/text/strings.toml +++ b/internal/text/strings.toml @@ -342,13 +342,15 @@ override_warning = "warning: {variable} is set and overrides the stored default" [command.notify] short = "Send a notification to one of your chats" -long_unix = '''Send one quoted message, or read stdin when no argument is given. An argument takes precedence over a pipe. A terminal without a message fails immediately. -Leading BOM and surrounding whitespace are removed; interior newlines are preserved. Messages must contain 1–4096 characters. Stdin reads at most 16 KiB and is truncated to 4096 characters; longer arguments are rejected. +long_unix = '''Send one quoted message, or read stdin when no argument is given. An argument takes precedence over a pipe. +Use --attach once per local file. Files are sent individually in order; an optional message captions the first file only. +Leading BOM and surrounding whitespace are removed; interior newlines are preserved. Text-only sends require 1–4096 characters. Text-only stdin reads at most 16 KiB and is truncated to 4096 characters. Captions over 4096 characters or 16 KiB of piped input are rejected. Choose --chat or --platform, never both. Flags override THE_AGENT_CLI_DEFAULT_CHAT, then THE_AGENT_CLI_DEFAULT_PLATFORM, then the stored default. Without a target the backend selects your latest private chat. Success is silent unless --verbose is set. Notifications are never retried automatically.''' -long_windows = '''Send one quoted message, or read stdin when no argument is given. An argument takes precedence over a pipe. A terminal without a message fails immediately. -Leading BOM and surrounding whitespace are removed; interior newlines are preserved. Messages must contain 1–4096 characters. Stdin reads at most 16 KiB and is truncated to 4096 characters; longer arguments are rejected. +long_windows = '''Send one quoted message, or read stdin when no argument is given. An argument takes precedence over a pipe. +Use --attach once per local file. Files are sent individually in order; an optional message captions the first file only. +Leading BOM and surrounding whitespace are removed; interior newlines are preserved. Text-only sends require 1–4096 characters. Text-only stdin reads at most 16 KiB and is truncated to 4096 characters. Captions over 4096 characters or 16 KiB of piped input are rejected. Choose --chat or --platform, never both. Flags override THE_AGENT_CLI_DEFAULT_CHAT, then THE_AGENT_CLI_DEFAULT_PLATFORM, then the stored default. Without a target the backend selects your latest private chat. Success is silent unless --verbose is set. Notifications are never retried automatically. @@ -356,9 +358,11 @@ PowerShell 7 pipes UTF-8 by default. In Windows PowerShell 5.1, set $OutputEncod examples = ''' {name} notify "Build finished" {name} notify --chat "" "Dinner's ready" {name} notify --platform whatsapp "Deploy done" -v + {name} notify "Before and after" --attach ./before.png --attach "./after, revised.png" echo "Backup finished" | {name} notify''' environment = "Environment: THE_AGENT_CLI_HOME, THE_AGENT_CLI_API_URL, THE_AGENT_CLI_TOKEN, THE_AGENT_CLI_PASSPHRASE, THE_AGENT_CLI_DEFAULT_CHAT, THE_AGENT_CLI_DEFAULT_PLATFORM" exit_codes = "Exit codes: 0 sent · 1 delivery or local failure · 2 usage or validation error · 3 not connected, locked or revoked · 4 chat unreachable · 5 insufficient credits · 6 rate limited" +flag_attach = "Attach one local `path` per occurrence (repeatable)" flag_chat = "Send to this chat ID" flag_platform = "Send to your latest private chat on telegram or whatsapp" @@ -368,6 +372,9 @@ missing_message = "no message given; pass it as an argument or pipe it on stdin" empty_message = "message is empty" long_message = "message is too long (max 4096 characters)" truncated = "warning: input truncated to 4096 characters" +long_caption_input = "piped caption input is too long (max 16 KiB)" +invalid_attachment = "cannot read attachment {path} as a regular file" +attachment_unknown = "warning: attachment delivery outcome unknown; check the destination before resending" conflicting_targets = "use either --chat or --platform, not both" empty_chat = "--chat needs a chat id" sent = "✓ Sent" diff --git a/openspec/changes/archive/2026-11-30-add-notify-attachments/.openspec.yaml b/openspec/changes/archive/2026-11-30-add-notify-attachments/.openspec.yaml new file mode 100644 index 0000000..8c7aa0b --- /dev/null +++ b/openspec/changes/archive/2026-11-30-add-notify-attachments/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-27 diff --git a/openspec/changes/archive/2026-11-30-add-notify-attachments/design.md b/openspec/changes/archive/2026-11-30-add-notify-attachments/design.md new file mode 100644 index 0000000..c65fd74 --- /dev/null +++ b/openspec/changes/archive/2026-11-30-add-notify-attachments/design.md @@ -0,0 +1,26 @@ +# Design + +## Context + +`notify.go` already resolves the destination and opens an authenticated session. `message.go` currently requires text, and `internal/api/client.go` marshals non-nil bodies as JSON. The endpoint client treats any 2xx notification response as success because delivery and charging may already have occurred. + +## Goals / Non-Goals + +Support local files without duplicating destination or session logic, buffering an entire batch in memory, or teaching the CLI Telegram and WhatsApp media rules. No stdin-as-file convention, glob expansion inside the CLI, album mode, or per-file captions. + +## Decisions + +1. **One repeatable path flag.** Use a Cobra string-array flag like the existing repeatable `--agent`, not comma-splitting string slices or a variadic positional list. Preserve flag order and duplicates. Expand nothing: the shell owns quoting. Validate each path is a readable regular file (including a symlink resolving to one); check before starting the HTTP upload. Keep handles bounded and close them on all exits. Put only basenames on the wire. +2. **Allow captionless uploads.** Prefer the positional argument over stdin. With no caption, send an empty message string for attachments. Bound piped caption reads and reject oversized input instead of truncating it. +3. **Share the HTTP transport, not the JSON encoder.** Stream repeated `attachments` parts, the required `message`, and optional `platform` on the same escaped route. Keep the existing auth, cancellation, redirect and response handling. Stop and join the producer on early response and local read failure. +4. **Display the delivery error message.** Keep 2xx success handling and low-credit output. Display the sanitized backend delivery error without interpreting it. A lost response means the outcome is unknown. Never automatically resend. + +## Risks / Trade-offs + +- An old backend may reject multipart → display the classified failure and leave text-only notifications unchanged. Never retry with the caption alone. +- Upload or sequential delivery may outlast the client's bounded HTTP timeout → cancel cleanly and report an unknown outcome if no response arrived; a client timeout cannot prove that sending stopped. +- A file can change or become unreadable after preflight → propagate the streaming failure without claiming a delivery count. A snapshot copy of every file would double local I/O without guaranteeing remote delivery. + +## Migration Plan + +Ship after the matching `agent-backend` contract is available. Update installed `notify` help and the agent-facing usage guide with the two-screenshot example. No config or credential changes; rolling back the CLI only removes the flag. diff --git a/openspec/changes/archive/2026-11-30-add-notify-attachments/proposal.md b/openspec/changes/archive/2026-11-30-add-notify-attachments/proposal.md new file mode 100644 index 0000000..903cbaa --- /dev/null +++ b/openspec/changes/archive/2026-11-30-add-notify-attachments/proposal.md @@ -0,0 +1,25 @@ +# Proposal + +## Why + +`abot notify` can tell a chat that a comparison or report is ready, but cannot send the screenshots or report itself. Users should be able to attach local files to the same command without choosing a new destination or learning platform-specific media options. + +## What Changes + +- Add repeatable `--attach ` to `abot notify`, one local file per occurrence. Preserve flag order and existing `--chat`, `--platform`, and default destination selection. +- With attachments, use the positional message or piped text to caption the first item. Send an empty string when no caption is supplied. Text-only behavior is unchanged. +- For example, `abot notify "Before and after" --attach ./before.png --attach ./after.png` uploads two files in that order, with “Before and after” as the message. The backend applies the destination's media mode and attributes the first attachment. +- Check all files before streaming one multipart request with ordered `attachments`, the required `message`, and `platform` where applicable. Media classification stays on the backend. +- If delivery stops partway through, display the backend's delivery error message. Do not automatically resend. + +## Capabilities + +### New Capabilities + +- `notify-attachments`: Attach ordered local files to a CLI notification and use its message as the first attachment's caption. + +### Modified Capabilities + +## Impact + +Affects `notify` argument and stdin handling, the notification HTTP client, command help, and CLI tests. Attachment sends depend on the companion `add-notify-attachments` change in `agent-backend`; text-only sends remain compatible with existing backends. diff --git a/openspec/changes/archive/2026-11-30-add-notify-attachments/specs/notify-attachments/spec.md b/openspec/changes/archive/2026-11-30-add-notify-attachments/specs/notify-attachments/spec.md new file mode 100644 index 0000000..9ff2fa4 --- /dev/null +++ b/openspec/changes/archive/2026-11-30-add-notify-attachments/specs/notify-attachments/spec.md @@ -0,0 +1,43 @@ +# Spec Delta + +## Purpose + +Let users send local files through the CLI's existing notification command without choosing a platform-specific media type or a separate destination. + +## ADDED Requirements + +### Requirement: Repeatable ordered attachments +`notify` SHALL accept one local path per `--attach` occurrence and preserve occurrence order, including literal spaces and commas in paths. It SHALL retain existing destination and credential selection and send one multipart request with repeated `attachments` parts, not a request per path. Without attachments it SHALL retain the existing JSON request and text input rules. + +#### Scenario: Compare two screenshots +- **WHEN** the user runs `abot notify "Before and after" --attach before.png --attach "after, revised.png"` +- **THEN** the chosen notification destination receives one request with the two named files in that order and `Before and after` as `message` + +### Requirement: Caption belongs to the attachments +With attachments, the CLI SHALL send the positional argument or piped text as the caption. It SHALL send the `message` form field as an empty string when no caption is supplied and SHALL NOT send a separate text notification. Text-only sends still require a nonblank message. + +#### Scenario: No caption in a terminal +- **WHEN** the user runs `abot notify --attach report.pdf` with terminal stdin +- **THEN** the command uploads the file with an empty `message` field without prompting + +#### Scenario: Piped caption +- **WHEN** the user pipes `Nightly report` to `abot notify --attach report.pdf` without a positional argument +- **THEN** that text is sent as the caption; stdin is not treated as another attachment + +### Requirement: Check all paths before upload +The CLI SHALL reject missing, unreadable or non-regular files before starting an upload and identify the offending path. It SHALL NOT embed file contents or absolute directory paths in multipart filenames. + +#### Scenario: Later path is missing +- **WHEN** the first path is readable but the second does not exist +- **THEN** the command exits unsuccessfully, names the second path locally and sends no upload request + +### Requirement: Report delivery without replay +The CLI SHALL treat any successful notification status as success even without receipt metadata. It SHALL display the delivery error message without parsing it and SHALL NOT infer progress from a lost response or replay a batch. + +#### Scenario: Backend stops on the second item +- **WHEN** the backend reports that one of three attachments was confirmed +- **THEN** the CLI exits unsuccessfully and displays the message without listing individual files + +#### Scenario: No response after submission +- **WHEN** the connection drops before the CLI receives a status for the upload +- **THEN** it reports an unknown delivery outcome without claiming that no files were sent and without resubmitting them diff --git a/openspec/changes/archive/2026-11-30-add-notify-attachments/tasks.md b/openspec/changes/archive/2026-11-30-add-notify-attachments/tasks.md new file mode 100644 index 0000000..ee2ef2f --- /dev/null +++ b/openspec/changes/archive/2026-11-30-add-notify-attachments/tasks.md @@ -0,0 +1,18 @@ +# Tasks + +## 1. Add the upload contract to the API client + +- [x] 1.1 Verify streamed multipart notification requests preserve escaped routes, auth, attachment order, filenames and bytes, the required message, and private-route platform selection. +- [x] 1.2 Handle cancellation, input read failure and early server rejection without leaving the upload producer or files open. Test those paths offline and assert no automatic second request; retain existing JSON notification endpoint tests. +- [x] 1.3 Keep the existing error envelope and verify success with an unreadable receipt and failure on a lost response. + +## 2. Extend the notify command + +- [x] 2.1 Add repeatable `--attach` and local readable-file preflight. Cover spaces, commas, repeated paths, directories and a missing later path in command tests; verify an invalid batch makes no upload request. +- [x] 2.2 Verify captionless uploads send an empty message part, positional captions take precedence, and piped reads stay bounded. Keep text-only behavior unchanged. +- [x] 2.3 Verify the CLI displays a partial-delivery message, reports lost responses as unknown, and never replays. +- [x] 2.4 Verify help and agent-facing usage show the comparison example, optional caption and repeatable flag. + +## 3. Verify the companion contract offline + +- [x] 3.1 Run the command against a local backend fixture for a two-screenshot comparison and a document followed by a photo. Verify one upload with the agreed fields, existing destination selection, normal success/low-credit output and no standalone text request.