Files
multica/server/internal/handler/feedback.go
Naiyuan Qing d6e7824ff1 feat(feedback): in-app feedback flow + Help launcher (#1546)
* feat(feedback): add in-app feedback flow and Help launcher

Replaces the duplicated bottom-sidebar user popover and "What's new" links
with a single Help menu (Docs / Feedback / Change log) pinned to the
sidebar footer. Feedback opens a rich-text modal that POSTs to a new
/api/feedback endpoint; submissions land in a dedicated feedback table
with per-user hourly rate limiting (10/hr) to deter spam without adding
middleware infrastructure. User identity (avatar + name + email) moves
into the workspace dropdown header so the sidebar is no longer visually
redundant.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(feedback): harden submit path and cap request body

- Read editor markdown via ref at submit time instead of debounced state,
  so ⌘+Enter immediately after typing doesn't drop the last keystrokes.
- Block submission while images are still uploading; toast prompts the
  user to wait instead of silently sending markdown with blob: URLs
  that get stripped.
- Cap /api/feedback request body at 64 KiB via MaxBytesReader so an
  authenticated client can't bloat the metadata JSONB column with an
  oversized url field.
- Add Go handler tests covering happy path, empty-message rejection,
  and the hourly rate limit boundary.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(analytics): instrument feedback funnel

Adds two events pairing frontend intent with backend conversion so we
can compute a completion rate for the in-app Feedback modal:

- `feedback_opened` (frontend) — fires once on FeedbackModal mount.
  Source is currently always "help_menu" but the type is a union so
  future entry points have to extend it explicitly. Workspace id is
  attached when present.
- `feedback_submitted` (backend) — fires from CreateFeedback after the
  DB insert succeeds and the hourly rate-limit check has passed.
  Message content itself is never sent to PostHog; the event carries
  a coarse length bucket (0-100 / 100-500 / 500-2000 / 2000+), an
  image-presence flag, and the client platform / version pulled from
  X-Client-* headers via middleware.ClientMetadataFromContext.

Affects no existing funnel; seeds a new Feedback funnel for product
triage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:35:55 +08:00

129 lines
4.0 KiB
Go

package handler
import (
"encoding/json"
"log/slog"
"net/http"
"regexp"
"strings"
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/middleware"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// feedbackImageRegex is a coarse check for markdown image syntax ![alt](url).
// It exists only to set the `has_images` analytics flag — we don't need a
// full markdown parser; a false positive on a literal "![" in prose is
// acceptable for a support-triage signal.
var feedbackImageRegex = regexp.MustCompile(`!\[[^\]]*\]\([^)]+\)`)
const (
feedbackMaxMessageLen = 10000
feedbackHourlyRateLimit = 10
// feedbackBodyLimit caps the request body at 64 KiB. Message is capped at
// 10k chars separately; the extra budget covers JSON overhead plus the
// optional url/workspace_id fields without letting an authenticated client
// POST megabytes of junk into the metadata JSONB column.
feedbackBodyLimit = 64 * 1024
)
type CreateFeedbackRequest struct {
Message string `json:"message"`
URL string `json:"url"`
WorkspaceID *string `json:"workspace_id,omitempty"`
}
type FeedbackResponse struct {
ID string `json:"id"`
CreatedAt string `json:"created_at"`
}
func (h *Handler) CreateFeedback(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
return
}
r.Body = http.MaxBytesReader(w, r.Body, feedbackBodyLimit)
var req CreateFeedbackRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
message := strings.TrimSpace(req.Message)
if message == "" {
writeError(w, http.StatusBadRequest, "message is required")
return
}
if len(message) > feedbackMaxMessageLen {
writeError(w, http.StatusBadRequest, "message too long")
return
}
// Per-user rate limit: hourly cap on feedback submissions. DB-backed so it
// survives process restarts and works across multiple instances without a
// shared cache — cost is one cheap indexed count per submit.
count, err := h.Queries.CountRecentFeedbackByUser(r.Context(), parseUUID(userID))
if err != nil {
slog.Warn("count recent feedback failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to check rate limit")
return
}
if count >= feedbackHourlyRateLimit {
writeError(w, http.StatusTooManyRequests, "too many feedback submissions, please try again later")
return
}
platform, version, clientOS := middleware.ClientMetadataFromContext(r.Context())
metadata := map[string]any{
"url": req.URL,
"platform": platform,
"version": version,
"os": clientOS,
"user_agent": r.UserAgent(),
}
metaBytes, err := json.Marshal(metadata)
if err != nil {
// Impossible in practice — map[string]any with primitive values never
// fails to marshal — but fall through with an empty object rather than
// 500ing on a non-critical field.
metaBytes = []byte("{}")
}
var workspaceID = parseUUID("")
if req.WorkspaceID != nil && *req.WorkspaceID != "" {
workspaceID = parseUUID(*req.WorkspaceID)
}
fb, err := h.Queries.CreateFeedback(r.Context(), db.CreateFeedbackParams{
UserID: parseUUID(userID),
Message: message,
Metadata: metaBytes,
WorkspaceID: workspaceID,
})
if err != nil {
slog.Warn("create feedback failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to submit feedback")
return
}
slog.Info("feedback submitted", append(logger.RequestAttrs(r), "feedback_id", uuidToString(fb.ID))...)
h.Analytics.Capture(analytics.FeedbackSubmitted(
userID,
uuidToString(fb.WorkspaceID),
len(message),
feedbackImageRegex.MatchString(message),
platform,
version,
))
writeJSON(w, http.StatusCreated, FeedbackResponse{
ID: uuidToString(fb.ID),
CreatedAt: timestampToString(fb.CreatedAt),
})
}