Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/ararahq/cli

go 1.26.3
go 1.26.5

require (
github.com/charmbracelet/bubbles v1.0.0
Expand Down
94 changes: 84 additions & 10 deletions internal/api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@ import (
"errors"
"fmt"
"net/http"
"strings"
"time"
)

const (
errorCodeWindowClosed = "ararahq-63016"
errorCodeInvalidNumber = "ararahq-63024"
errorCodeReengagement = "ararahq-reengagement"
errorCodeInvalidNumber = "ararahq-invalid-number"
errorCodeTemplateError = "ararahq-63024"
errorCodeTemplateNotFound = "ararahq-template-not-found"
errorCodeInsufficientFunds = "ararahq-insufficient-funds"
errorCodeRateLimit = "ararahq-rate-limit"
errorCodeTemplateMismatch = "ararahq-template-mismatch"
Expand All @@ -19,7 +23,10 @@ const (

var friendlyMessages = map[string]string{
errorCodeWindowClosed: "Janela de 24h fechada. Envie um template primeiro.",
errorCodeReengagement: "Janela de 24h fechada. Envie um template primeiro.",
errorCodeInvalidNumber: "Numero invalido. Use formato: +5511999999999",
errorCodeTemplateError: "Template rejeitado ou pausado pela Meta. Confira o status no dashboard.",
errorCodeTemplateNotFound: "Template nao existe ou nao esta aprovado nesta conta.",
errorCodeInsufficientFunds: "Saldo insuficiente. Recarregue em ararahq.com/dashboard",
errorCodeRateLimit: "Rate limit atingido. Aguarde ou use campaigns para envio em massa.",
errorCodeTemplateMismatch: "Variaveis nao batem com o template.",
Expand All @@ -30,13 +37,34 @@ type APIError struct {
StatusCode int
Code string `json:"code"`
Message string `json:"message"`
RawBody string
RetryAfter time.Duration
// DiagnosticCode carries the real business code ("ararahq-63016") that the
// backend buries in error.details.diagnostic.code. GlobalExceptionHandler
// flattens every BusinessException to code "UNPROCESSABLE_ENTITY", so Code
// alone never identifies what went wrong.
DiagnosticCode string
// DiagnosticHint is the backend-authored explanation (whatHappened +
// howToAct) used when the code has no entry in friendlyMessages. The
// backend emits a diagnostic for every provider code, including ones the
// CLI does not know about.
DiagnosticHint string
RawBody string
RetryAfter time.Duration
}

// BusinessCode returns the code that identifies the failure for the user,
// preferring the diagnostic over the generic envelope code.
func (apiError *APIError) BusinessCode() string {
if apiError.DiagnosticCode != "" {
return apiError.DiagnosticCode
}

return apiError.Code
}

func (apiError *APIError) Error() string {
if apiError.Code != "" {
return fmt.Sprintf("[%d] %s: %s", apiError.StatusCode, apiError.Code, apiError.Message)
businessCode := apiError.BusinessCode()
if businessCode != "" {
return fmt.Sprintf("[%d] %s: %s", apiError.StatusCode, businessCode, apiError.Message)
}

if apiError.Message != "" {
Expand All @@ -47,11 +75,15 @@ func (apiError *APIError) Error() string {
}

func (apiError *APIError) FriendlyMessage() string {
friendlyMessage, exists := friendlyMessages[apiError.Code]
friendlyMessage, exists := friendlyMessages[apiError.BusinessCode()]
if exists {
return friendlyMessage
}

if apiError.DiagnosticHint != "" {
return apiError.DiagnosticHint
}

if apiError.Message != "" {
return apiError.Message
}
Expand Down Expand Up @@ -84,18 +116,60 @@ type apiErrorEnvelope struct {
type apiErrorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
// Details is free-form per exception type: some handlers put a diagnostic
// object in it, others put plan metadata or a list. Decoding it lazily
// keeps an unexpected shape from failing the whole envelope and losing the
// error code.
Details json.RawMessage `json:"details"`
}

type apiErrorDetails struct {
Diagnostic apiErrorDiagnostic `json:"diagnostic"`
}

type apiErrorDiagnostic struct {
Code string `json:"code"`
WhatHappened string `json:"whatHappened"`
HowToAct string `json:"howToAct"`
}

func (diagnostic apiErrorDiagnostic) hint() string {
parts := make([]string, 0, 2)
for _, part := range []string{diagnostic.WhatHappened, diagnostic.HowToAct} {
if trimmed := strings.TrimSpace(part); trimmed != "" {
parts = append(parts, trimmed)
}
}

return strings.Join(parts, " ")
}

func extractDiagnostic(rawDetails json.RawMessage) apiErrorDiagnostic {
if len(rawDetails) == 0 {
return apiErrorDiagnostic{}
}

var details apiErrorDetails
if unmarshalError := json.Unmarshal(rawDetails, &details); unmarshalError != nil {
return apiErrorDiagnostic{}
}

return details.Diagnostic
}

func ParseErrorResponse(statusCode int, body []byte) *APIError {
rawBody := string(body)

var envelope apiErrorEnvelope
if unmarshalError := json.Unmarshal(body, &envelope); unmarshalError == nil && envelope.Error.Code != "" {
diagnostic := extractDiagnostic(envelope.Error.Details)
return &APIError{
StatusCode: statusCode,
Code: envelope.Error.Code,
Message: envelope.Error.Message,
RawBody: rawBody,
StatusCode: statusCode,
Code: envelope.Error.Code,
Message: envelope.Error.Message,
DiagnosticCode: strings.TrimSpace(diagnostic.Code),
DiagnosticHint: diagnostic.hint(),
RawBody: rawBody,
}
}

Expand Down
63 changes: 63 additions & 0 deletions internal/api/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,69 @@ func TestAPIError_FriendlyMessage(t *testing.T) {
}
}

func TestParseErrorResponse_ReadsDiagnosticCode(t *testing.T) {
body := []byte(`{"error":{"code":"UNPROCESSABLE_ENTITY","message":"Janela de 24h fechada.",` +
`"details":{"diagnostic":{"code":"ararahq-63016","whatHappened":"Janela fechada.",` +
`"howToAct":"Envie um template."}}}}`)
got := ParseErrorResponse(http.StatusUnprocessableEntity, body)

if got.Code != "UNPROCESSABLE_ENTITY" {
t.Errorf("envelope code should be preserved, got %q", got.Code)
}
if got.DiagnosticCode != errorCodeWindowClosed {
t.Errorf("diagnostic code: want %q, got %q", errorCodeWindowClosed, got.DiagnosticCode)
}
if got.BusinessCode() != errorCodeWindowClosed {
t.Errorf("business code should prefer the diagnostic, got %q", got.BusinessCode())
}
if !strings.Contains(got.FriendlyMessage(), "Janela de 24h fechada. Envie um template primeiro.") {
t.Errorf("friendly message should be reachable, got %q", got.FriendlyMessage())
}
}

func TestParseErrorResponse_UnknownDiagnosticFallsBackToHint(t *testing.T) {
body := []byte(`{"error":{"code":"UNPROCESSABLE_ENTITY","message":"[131037]",` +
`"details":{"diagnostic":{"code":"ararahq-display-name",` +
`"whatHappened":"Nome de exibicao nao aprovado.","howToAct":"Peca a aprovacao."}}}}`)
got := ParseErrorResponse(http.StatusUnprocessableEntity, body)

if got.BusinessCode() != "ararahq-display-name" {
t.Errorf("business code: got %q", got.BusinessCode())
}
want := "Nome de exibicao nao aprovado. Peca a aprovacao."
if got.FriendlyMessage() != want {
t.Errorf("friendly message: want %q, got %q", want, got.FriendlyMessage())
}
}

func TestParseErrorResponse_DetailsWithoutDiagnostic(t *testing.T) {
body := []byte(`{"error":{"code":"PLAN_FEATURE_LOCKED","message":"Faca upgrade.",` +
`"details":{"feature":"campaigns","currentPlan":"FREE","upgradeTo":"VOO"}}}`)
got := ParseErrorResponse(http.StatusForbidden, body)

if got.BusinessCode() != "PLAN_FEATURE_LOCKED" {
t.Errorf("business code should fall back to the envelope code, got %q", got.BusinessCode())
}
if got.DiagnosticCode != "" {
t.Errorf("no diagnostic expected, got %q", got.DiagnosticCode)
}
if got.FriendlyMessage() != "Faca upgrade." {
t.Errorf("friendly message: got %q", got.FriendlyMessage())
}
}

func TestParseErrorResponse_NonObjectDetailsKeepsCode(t *testing.T) {
body := []byte(`{"error":{"code":"VALIDATION_ERROR","message":"invalido","details":["campo"]}}`)
got := ParseErrorResponse(http.StatusBadRequest, body)

if got.Code != "VALIDATION_ERROR" {
t.Errorf("unexpected details shape must not lose the code, got %q", got.Code)
}
if got.DiagnosticCode != "" {
t.Errorf("no diagnostic expected, got %q", got.DiagnosticCode)
}
}

func TestIsAuthError(t *testing.T) {
if !IsAuthError(&APIError{StatusCode: http.StatusUnauthorized}) {
t.Error("401 should be auth error")
Expand Down
7 changes: 6 additions & 1 deletion internal/api/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,17 @@ const (
messagesBasePath = "/v1/messages"
)

// SendMessageRequest mirrors the Kotlin SendMessageRequest DTO. Every field is
// camelCase except scheduledAt, which the backend binds with
// @JsonProperty("scheduled_at") and no @JsonAlias. Sending "scheduledAt" is
// dropped silently (FAIL_ON_UNKNOWN_PROPERTIES is off), so the message goes out
// immediately and the caller never sees an error.
type SendMessageRequest struct {
Receiver string `json:"receiver"`
TemplateName string `json:"templateName,omitempty"`
TemplateVariables []string `json:"variables,omitempty"`
Body string `json:"body,omitempty"`
ScheduledAt string `json:"scheduledAt,omitempty"`
ScheduledAt string `json:"scheduled_at,omitempty"`
}

type DryRunPreview struct {
Expand Down
39 changes: 39 additions & 0 deletions internal/api/messages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,45 @@ func TestEnsurePhonePrefix(t *testing.T) {
}
}

func TestSendMessageRequest_SerializesScheduledAtAsSnakeCase(t *testing.T) {
encoded, marshalErr := json.Marshal(SendMessageRequest{
Receiver: "whatsapp:+5511999999999",
TemplateName: "hello",
ScheduledAt: "2026-01-01T00:00:00Z",
})
if marshalErr != nil {
t.Fatalf("marshal: %v", marshalErr)
}

var wire map[string]any
if err := json.Unmarshal(encoded, &wire); err != nil {
t.Fatalf("unmarshal: %v", err)
}

if wire["scheduled_at"] != "2026-01-01T00:00:00Z" {
t.Errorf("backend binds scheduled_at, got payload %s", encoded)
}
if _, hasCamelCase := wire["scheduledAt"]; hasCamelCase {
t.Errorf("scheduledAt is dropped silently by the backend, got payload %s", encoded)
}
}

func TestSendMessageRequest_OmitsScheduledAtWhenEmpty(t *testing.T) {
encoded, marshalErr := json.Marshal(SendMessageRequest{Receiver: "whatsapp:+5511", Body: "hi"})
if marshalErr != nil {
t.Fatalf("marshal: %v", marshalErr)
}

var wire map[string]any
if err := json.Unmarshal(encoded, &wire); err != nil {
t.Fatalf("unmarshal: %v", err)
}

if _, present := wire["scheduled_at"]; present {
t.Errorf("empty schedule must not be sent, got payload %s", encoded)
}
}

func TestMessageResponse_UnmarshalNullIDAsEmpty(t *testing.T) {
body := `{"id":null,"status":"queued","receiver":"+5511","mode":"test"}`
var response MessageResponse
Expand Down
7 changes: 6 additions & 1 deletion internal/api/webhook_listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"net/http"
"strings"
)

const (
Expand Down Expand Up @@ -97,7 +98,11 @@ func classifyCaptureError(err error) error {
return ErrCaptureNotSupported
}

if apiError.StatusCode == http.StatusConflict && apiError.Code == "capture_listener_active" {
// EqualFold porque o backend emite CAPTURE_LISTENER_ACTIVE em maiusculo
// (GlobalExceptionHandler.kt) e a comparacao exata em minusculo nunca casava: o usuario via
// um conflito generico em vez de quem esta com o listener e ate quando.
if apiError.StatusCode == http.StatusConflict &&
strings.EqualFold(apiError.Code, "CAPTURE_LISTENER_ACTIVE") {
return &CaptureConflictError{
ListenerID: stringFromDetails(apiError, "listenerId"),
Owner: stringFromDetails(apiError, "owner"),
Expand Down
2 changes: 1 addition & 1 deletion internal/api/webhook_listener_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func TestCreateWebhookListener_409ReturnsTypedConflict(t *testing.T) {
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{
"error":{
"code":"capture_listener_active",
"code":"CAPTURE_LISTENER_ACTIVE",
"message":"another CLI session is already capturing for this org",
"details":{
"listenerId":"lst_existing",
Expand Down
2 changes: 1 addition & 1 deletion internal/cmd/listen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ func TestRunListenCapture_PropagatesConflict(t *testing.T) {
if r.URL.Path == "/v1/cli/webhook-listeners" && r.Method == http.MethodPost {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
_, _ = w.Write([]byte(`{"error":{"code":"capture_listener_active","message":"taken","details":{"listenerId":"lst_other","owner":"laptop@there","expiresAt":"2026-12-01T00:00:00Z"}}}`))
_, _ = w.Write([]byte(`{"error":{"code":"CAPTURE_LISTENER_ACTIVE","message":"taken","details":{"listenerId":"lst_other","owner":"laptop@there","expiresAt":"2026-12-01T00:00:00Z"}}}`))
return
}
w.WriteHeader(http.StatusNotFound)
Expand Down
2 changes: 1 addition & 1 deletion internal/mcp/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func classifyError(err error) toolErrorBody {
var apiError *api.APIError
if errors.As(err, &apiError) {
body := toolErrorBody{
Code: apiError.Code,
Code: apiError.BusinessCode(),
Message: apiError.FriendlyMessage(),
}
if apiError.StatusCode == httpTooManyRequests || apiError.StatusCode >= 500 {
Expand Down
Loading