Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(feedback): in-app feedback flow + Help launcher (#1546)

Naiyuan Qingd6e7824ff191
diff --git a/docs/analytics.md b/docs/analytics.md
index c49ff09296..e86efdf1fb 100644
--- a/docs/analytics.md
+++ b/docs/analytics.md
@@ -270,6 +270,24 @@ funnel and used to size hosted-runtime interest.
`distinct_id` is the user's id.
+### `feedback_submitted`
+
+Fires from `CreateFeedback` after the `feedback` row is inserted and the
+hourly per-user rate-limit check has passed. Retries within the same hour
+that were rate-limited (429) don't emit. The free-text message is stored
+in the DB and never broadcast.
+
+| Property | Type | Description |
+|---|---|---|
+| `message_length_bucket` | string | `0-100` / `100-500` / `500-2000` / `2000+` — coarse bucket of `len(message)` so we can tell "quick note" from "bug report with repro steps" without leaking content. |
+| `has_images` | bool | `true` when the markdown contains at least one `![...](url)` image reference — signals bug reports with visual evidence. |
+| `platform` | string | Client platform from `X-Client-Platform` header (`web` / `desktop`). Omitted when the header is absent. |
+| `app_version` | string | Client version from `X-Client-Version` header. Omitted when absent. |
+
+`distinct_id` is the submitter's user id; `workspace_id` is attached from
+the modal's current-workspace context and may be empty when feedback is
+sent from a pre-workspace surface.
+
### `starter_content_decided`
Fires on the atomic NULL → terminal state transition in both
@@ -343,6 +361,16 @@ request payload.
- `matched_detect`: `true` when the chosen platform+arch matches
what the page detected. `false` lets us quantify detect misses
from the single event (no cross-join needed).
+- `feedback_opened` — fired when the in-app Feedback modal mounts
+ (user clicked "Feedback" in the Help launcher). Paired with the
+ backend's `feedback_submitted` to give a completion rate for the
+ form. Wrapper lives in `packages/core/analytics/feedback.ts`
+ (`captureFeedbackOpened`). Properties:
+ - `source`: `help_menu` (reserved — future entry points like
+ keyboard shortcut or error-toast CTA will pass their own value)
+ - `workspace_id`: string (UUID) when the modal opens inside a
+ workspace. Omitted on pre-workspace surfaces.
+
- Attribution is NOT a separate event; UTM + referrer origin are written
to the `multica_signup_source` cookie on the first anonymous pageview
and read by the backend's `signup` emission. The cookie carries a JSON
diff --git a/packages/core/analytics/feedback.ts b/packages/core/analytics/feedback.ts
new file mode 100644
index 0000000000..e9cde782c2
--- /dev/null
+++ b/packages/core/analytics/feedback.ts
@@ -0,0 +1,34 @@
+/**
+ * Feedback funnel instrumentation.
+ *
+ * Pairs with the backend's `feedback_submitted` event (emitted from
+ * `CreateFeedback` after a successful insert) so we can compute a
+ * completion rate: users who open the modal → users who actually send.
+ * The message content itself is never sent to PostHog; see
+ * docs/analytics.md and the backend `FeedbackSubmitted` helper for the
+ * PII contract.
+ */
+
+import { captureEvent } from "./index";
+
+/**
+ * Entry point the user took to reach the Feedback modal. Typed union so
+ * future surfaces (keyboard shortcut, error-toast CTA, sidebar menu
+ * item) have to extend this list explicitly rather than drift.
+ */
+export type FeedbackOpenedSource = "help_menu";
+
+/**
+ * Fires once on FeedbackModal mount. Workspace id is attached when the
+ * modal opens inside a workspace; pre-workspace surfaces (e.g. inbox,
+ * onboarding transitions) omit it rather than sending an empty string.
+ */
+export function captureFeedbackOpened(
+ source: FeedbackOpenedSource,
+ workspaceId?: string,
+): void {
+ captureEvent("feedback_opened", {
+ source,
+ ...(workspaceId ? { workspace_id: workspaceId } : {}),
+ });
+}
diff --git a/packages/core/analytics/index.ts b/packages/core/analytics/index.ts
index d512c350a4..4438a77edc 100644
--- a/packages/core/analytics/index.ts
+++ b/packages/core/analytics/index.ts
@@ -63,6 +63,11 @@ export {
type DownloadInitiatedPayload,
} from "./download";
+export {
+ captureFeedbackOpened,
+ type FeedbackOpenedSource,
+} from "./feedback";
+
export interface AnalyticsConfig {
key: string;
host: string;
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index ec1e6e63bd..220b89be68 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -395,6 +395,17 @@ export class ApiClient {
});
}
+ async createFeedback(data: {
+ message: string;
+ url?: string;
+ workspace_id?: string;
+ }): Promise<{ id: string; created_at: string }> {
+ return this.fetch("/api/feedback", {
+ method: "POST",
+ body: JSON.stringify(data),
+ });
+ }
+
async updateIssue(id: string, data: UpdateIssueRequest): Promise<Issue> {
return this.fetch(`/api/issues/${id}`, {
method: "PUT",
diff --git a/packages/core/feedback/index.ts b/packages/core/feedback/index.ts
new file mode 100644
index 0000000000..f8dd99d037
--- /dev/null
+++ b/packages/core/feedback/index.ts
@@ -0,0 +1 @@
+export * from "./mutations";
diff --git a/packages/core/feedback/mutations.ts b/packages/core/feedback/mutations.ts
new file mode 100644
index 0000000000..8d23eb0e8c
--- /dev/null
+++ b/packages/core/feedback/mutations.ts
@@ -0,0 +1,14 @@
+import { useMutation } from "@tanstack/react-query";
+import { api } from "../api";
+
+export interface CreateFeedbackInput {
+ message: string;
+ url?: string;
+ workspace_id?: string;
+}
+
+export function useCreateFeedback() {
+ return useMutation({
+ mutationFn: (input: CreateFeedbackInput) => api.createFeedback(input),
+ });
+}
diff --git a/packages/core/modals/store.ts b/packages/core/modals/store.ts
index 81031245df..4e05834a6e 100644
--- a/packages/core/modals/store.ts
+++ b/packages/core/modals/store.ts
@@ -2,7 +2,7 @@
import { create } from "zustand";
-type ModalType = "create-workspace" | "create-issue" | "create-project" | null;
+type ModalType = "create-workspace" | "create-issue" | "create-project" | "feedback" | null;
interface ModalStore {
modal: ModalType;
diff --git a/packages/core/package.json b/packages/core/package.json
index 43b781397a..2e9b2cfe2c 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -52,6 +52,8 @@
"./pins": "./pins/index.ts",
"./pins/queries": "./pins/queries.ts",
"./pins/mutations": "./pins/mutations.ts",
+ "./feedback": "./feedback/index.ts",
+ "./feedback/mutations": "./feedback/mutations.ts",
"./realtime": "./realtime/index.ts",
"./navigation": "./navigation/index.ts",
"./modals": "./modals/index.ts",
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index 452f419e66..c3dbe9a793 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -3,6 +3,7 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@multica/ui/lib/utils";
import { AppLink, useNavigation } from "../navigation";
+import { HelpLauncher } from "./help-launcher";
import {
DndContext,
PointerSensor,
@@ -28,7 +29,6 @@ import {
SquarePen,
CircleUser,
FolderKanban,
- Sparkles,
X,
Zap,
} from "lucide-react";
@@ -41,11 +41,11 @@ import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";
import {
Sidebar,
SidebarContent,
+ SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
- SidebarFooter,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
@@ -60,11 +60,6 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@multica/ui/components/ui/popover";
import { useAuthStore } from "@multica/core/auth";
import { useCurrentWorkspace, useWorkspacePaths, paths } from "@multica/core/paths";
import { workspaceListOptions, myInvitationListOptions, workspaceKeys } from "@multica/core/workspace/queries";
@@ -438,16 +433,27 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
}
/>
<DropdownMenuContent
- className="w-auto"
+ className="w-auto min-w-56"
align="start"
side="bottom"
sideOffset={4}
>
- <DropdownMenuGroup>
- <DropdownMenuLabel className="text-xs text-muted-foreground">
- {user?.email}
- </DropdownMenuLabel>
- </DropdownMenuGroup>
+ <div className="flex items-center gap-2.5 px-2 py-1.5">
+ <ActorAvatar
+ name={user?.name ?? ""}
+ initials={(user?.name ?? "U").charAt(0).toUpperCase()}
+ avatarUrl={user?.avatar_url}
+ size={32}
+ />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium leading-tight">
+ {user?.name}
+ </p>
+ <p className="truncate text-xs text-muted-foreground leading-tight">
+ {user?.email}
+ </p>
+ </div>
+ </div>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuLabel className="text-xs text-muted-foreground">
@@ -516,22 +522,6 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
)}
<DropdownMenuSeparator />
<DropdownMenuGroup>
- {/* Plain anchor with target=_blank works on both web
- (new tab) and desktop (intercepted by the main
- process's setWindowOpenHandler → openExternalSafely),
- so the shared component doesn't need to branch. */}
- <DropdownMenuItem
- render={
- <a
- href="https://multica.ai/changelog"
- target="_blank"
- rel="noopener noreferrer"
- />
- }
- >
- <Sparkles className="h-3.5 w-3.5" />
- What&apos;s new
- </DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={logout}>
<LogOut className="h-3.5 w-3.5" />
Log out
@@ -681,61 +671,8 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
</SidebarContent>
<SidebarFooter className="p-2">
- <div className="border-t pt-2">
- <Popover>
- <PopoverTrigger className="flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-accent transition-colors cursor-pointer">
- <ActorAvatar
- name={user?.name ?? ""}
- initials={(user?.name ?? "U").charAt(0).toUpperCase()}
- avatarUrl={user?.avatar_url}
- size={28}
- />
- <div className="min-w-0 flex-1 text-left">
- <p className="truncate text-sm font-medium leading-tight">
- {user?.name}
- </p>
- <p className="truncate text-xs text-muted-foreground leading-tight">
- {user?.email}
- </p>
- </div>
- </PopoverTrigger>
- <PopoverContent side="top" sideOffset={8} align="start" className="w-48 p-0">
- <div className="flex items-center gap-2.5 px-2.5 py-2 border-b">
- <ActorAvatar
- name={user?.name ?? ""}
- initials={(user?.name ?? "U").charAt(0).toUpperCase()}
- avatarUrl={user?.avatar_url}
- size={32}
- />
- <div className="min-w-0 flex-1">
- <p className="truncate text-sm font-medium">
- {user?.name}
- </p>
- <p className="truncate text-xs text-muted-foreground">
- {user?.email}
- </p>
- </div>
- </div>
- <div className="p-1">
- <a
- href="https://multica.ai/changelog"
- target="_blank"
- rel="noopener noreferrer"
- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm text-foreground hover:bg-accent transition-colors cursor-pointer"
- >
- <Sparkles className="h-3.5 w-3.5" />
- What&apos;s new
- </a>
- <button
- onClick={logout}
- className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm text-destructive hover:bg-destructive/10 transition-colors cursor-pointer"
- >
- <LogOut className="h-3.5 w-3.5" />
- Log out
- </button>
- </div>
- </PopoverContent>
- </Popover>
+ <div className="flex justify-end">
+ <HelpLauncher />
</div>
</SidebarFooter>
<SidebarRail />
diff --git a/packages/views/layout/help-launcher.tsx b/packages/views/layout/help-launcher.tsx
new file mode 100644
index 0000000000..973d491dd3
--- /dev/null
+++ b/packages/views/layout/help-launcher.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import { BookOpen, CircleHelp, History, MessageCircle } from "lucide-react";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { useModalStore } from "@multica/core/modals";
+
+const DOCS_URL = "https://multica.ai/docs";
+const CHANGELOG_URL = "https://multica.ai/changelog";
+
+export function HelpLauncher() {
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label="Help"
+ title="Help"
+ className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors cursor-pointer hover:bg-accent hover:text-foreground data-popup-open:bg-accent data-popup-open:text-foreground"
+ >
+ <CircleHelp className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ side="top"
+ sideOffset={8}
+ className="min-w-40"
+ >
+ <DropdownMenuItem
+ render={
+ <a href={DOCS_URL} target="_blank" rel="noopener noreferrer" />
+ }
+ >
+ <BookOpen className="h-3.5 w-3.5" />
+ Docs
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => useModalStore.getState().open("feedback")}
+ >
+ <MessageCircle className="h-3.5 w-3.5" />
+ Feedback
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ render={
+ <a
+ href={CHANGELOG_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ />
+ }
+ >
+ <History className="h-3.5 w-3.5" />
+ Change log
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/views/modals/feedback.tsx b/packages/views/modals/feedback.tsx
new file mode 100644
index 0000000000..46054e6dbe
--- /dev/null
+++ b/packages/views/modals/feedback.tsx
@@ -0,0 +1,124 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { toast } from "sonner";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ ContentEditor,
+ type ContentEditorRef,
+ useFileDropZone,
+ FileDropOverlay,
+} from "../editor";
+import { useCreateFeedback } from "@multica/core/feedback";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import { useFileUpload } from "@multica/core/hooks/use-file-upload";
+import { api } from "@multica/core/api";
+import { captureFeedbackOpened } from "@multica/core/analytics";
+
+const MAX_MESSAGE_LEN = 10000;
+
+export function FeedbackModal({ onClose }: { onClose: () => void }) {
+ const workspace = useCurrentWorkspace();
+ const editorRef = useRef<ContentEditorRef>(null);
+ const [message, setMessage] = useState("");
+ const { isDragOver, dropZoneProps } = useFileDropZone({
+ onDrop: (files) => files.forEach((f) => editorRef.current?.uploadFile(f)),
+ });
+ const { uploadWithToast } = useFileUpload(api);
+ const mutation = useCreateFeedback();
+
+ // Fire the "modal opened" analytics event once per mount. Pairs with
+ // the backend's `feedback_submitted` to give a funnel completion rate.
+ // Workspace id is captured from the closure at mount time — the modal
+ // is short-lived, so there's no meaningful workspace switch to track.
+ useEffect(() => {
+ captureFeedbackOpened("help_menu", workspace?.id);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const canSubmit =
+ message.trim().length > 0 &&
+ message.length <= MAX_MESSAGE_LEN &&
+ !mutation.isPending;
+
+ const handleSubmit = async () => {
+ if (!canSubmit) return;
+ if (editorRef.current?.hasActiveUploads()) {
+ toast.info("Please wait for uploads to finish…");
+ return;
+ }
+ // Read from the editor ref at submit time — `message` state lags 150ms
+ // behind keystrokes due to `debounceMs`, so ⌘+Enter fired immediately
+ // after typing would otherwise submit stale content.
+ const latest = editorRef.current?.getMarkdown()?.trim() ?? "";
+ if (!latest) return;
+ if (latest.length > MAX_MESSAGE_LEN) {
+ toast.error("Message is too long");
+ return;
+ }
+ try {
+ await mutation.mutateAsync({
+ message: latest,
+ url: typeof window !== "undefined" ? window.location.href : undefined,
+ workspace_id: workspace?.id,
+ });
+ toast.success("Thanks for the feedback!");
+ onClose();
+ } catch (err) {
+ const msg =
+ err instanceof Error && err.message
+ ? err.message
+ : "Failed to send feedback";
+ toast.error(msg);
+ }
+ };
+
+ return (
+ <Dialog open onOpenChange={(v) => !v && onClose()}>
+ <DialogContent className="sm:max-w-2xl !h-[28rem] p-0 gap-0 flex flex-col overflow-hidden">
+ <DialogHeader className="px-5 pt-4 pb-2 shrink-0">
+ <DialogTitle>Feedback</DialogTitle>
+ <DialogDescription>
+ We&apos;d love to hear what&apos;s working, what isn&apos;t, or
+ what you&apos;d like to see next.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex-1 min-h-0 px-5 pb-3">
+ <div
+ {...dropZoneProps}
+ className="relative h-full overflow-y-auto rounded-lg border-1 border-border transition-colors focus-within:border-brand"
+ >
+ <ContentEditor
+ ref={editorRef}
+ placeholder="Tell us about your experience, bugs you've found, or features you'd like to see…"
+ onUpdate={(md) => setMessage(md)}
+ onUploadFile={uploadWithToast}
+ onSubmit={handleSubmit}
+ debounceMs={150}
+ showBubbleMenu={false}
+ className="px-3 py-2"
+ />
+ {isDragOver && <FileDropOverlay />}
+ </div>
+ </div>
+
+ <div className="flex items-center justify-end px-4 py-3 border-t shrink-0">
+ <Button size="sm" onClick={handleSubmit} disabled={!canSubmit}>
+ {mutation.isPending ? "Sending…" : "Send feedback"}
+ <kbd className="ml-1 inline-flex h-4 items-center gap-0.5 rounded border border-border/50 bg-background/30 px-1 font-mono text-[10px] leading-none">
+ ⌘↵
+ </kbd>
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/modals/registry.tsx b/packages/views/modals/registry.tsx
index 6f0bd6a984..67552af3dc 100644
--- a/packages/views/modals/registry.tsx
+++ b/packages/views/modals/registry.tsx
@@ -4,6 +4,7 @@ import { useModalStore } from "@multica/core/modals";
import { CreateWorkspaceModal } from "./create-workspace";
import { CreateIssueModal } from "./create-issue";
import { CreateProjectModal } from "./create-project";
+import { FeedbackModal } from "./feedback";
export function ModalRegistry() {
const modal = useModalStore((s) => s.modal);
@@ -17,6 +18,8 @@ export function ModalRegistry() {
return <CreateIssueModal onClose={close} data={data} />;
case "create-project":
return <CreateProjectModal onClose={close} />;
+ case "feedback":
+ return <FeedbackModal onClose={close} />;
default:
return null;
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 82d77bdba6..144f6b6a6d 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -184,6 +184,7 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics
r.Post("/api/me/starter-content/dismiss", h.DismissStarterContent)
r.Post("/api/cli-token", h.IssueCliToken)
r.Post("/api/upload-file", h.UploadFile)
+ r.Post("/api/feedback", h.CreateFeedback)
r.Route("/api/workspaces", func(r chi.Router) {
r.Get("/", h.ListWorkspaces)
diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.go
index 0e84274954..6290462b62 100644
--- a/server/internal/analytics/events.go
+++ b/server/internal/analytics/events.go
@@ -15,6 +15,7 @@ const (
EventOnboardingCompleted = "onboarding_completed"
EventCloudWaitlistJoined = "cloud_waitlist_joined"
EventStarterContentDecided = "starter_content_decided"
+ EventFeedbackSubmitted = "feedback_submitted"
)
// Onboarding completion paths. Keep in sync with docs/analytics.md.
@@ -262,6 +263,42 @@ func StarterContentDecided(userID, workspaceID, decision, branch string) Event {
}
}
+// FeedbackSubmitted fires after a feedback row is successfully inserted.
+// The raw message is stored in the DB and never broadcast — we only emit a
+// coarse length bucket, an image-presence flag, and the client platform /
+// version so support can segment without leaking content.
+func FeedbackSubmitted(userID, workspaceID string, messageLen int, hasImages bool, platform, appVersion string) Event {
+ props := map[string]any{
+ "message_length_bucket": feedbackLengthBucket(messageLen),
+ "has_images": hasImages,
+ }
+ if platform != "" {
+ props["platform"] = platform
+ }
+ if appVersion != "" {
+ props["app_version"] = appVersion
+ }
+ return Event{
+ Name: EventFeedbackSubmitted,
+ DistinctID: userID,
+ WorkspaceID: workspaceID,
+ Properties: props,
+ }
+}
+
+func feedbackLengthBucket(n int) string {
+ switch {
+ case n < 100:
+ return "0-100"
+ case n < 500:
+ return "100-500"
+ case n < 2000:
+ return "500-2000"
+ default:
+ return "2000+"
+ }
+}
+
func emailDomain(email string) string {
at := strings.LastIndex(email, "@")
if at < 0 || at == len(email)-1 {
diff --git a/server/internal/handler/feedback.go b/server/internal/handler/feedback.go
new file mode 100644
index 0000000000..f427abcc76
--- /dev/null
+++ b/server/internal/handler/feedback.go
@@ -0,0 +1,128 @@
+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),
+ })
+}
diff --git a/server/internal/handler/feedback_test.go b/server/internal/handler/feedback_test.go
new file mode 100644
index 0000000000..9b3a2b1a21
--- /dev/null
+++ b/server/internal/handler/feedback_test.go
@@ -0,0 +1,75 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "testing"
+)
+
+func TestCreateFeedbackHappyPath(t *testing.T) {
+ clearFeedbackForTestUser(t)
+
+ req := newRequest("POST", "/api/feedback", CreateFeedbackRequest{
+ Message: "Love the product, dark mode flashes on startup",
+ })
+ w := httptest.NewRecorder()
+ testHandler.CreateFeedback(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp FeedbackResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.ID == "" {
+ t.Fatal("expected feedback id in response")
+ }
+}
+
+func TestCreateFeedbackEmptyMessage(t *testing.T) {
+ req := newRequest("POST", "/api/feedback", CreateFeedbackRequest{Message: " "})
+ w := httptest.NewRecorder()
+ testHandler.CreateFeedback(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestCreateFeedbackRateLimit(t *testing.T) {
+ clearFeedbackForTestUser(t)
+
+ for i := 0; i < feedbackHourlyRateLimit; i++ {
+ req := newRequest("POST", "/api/feedback", CreateFeedbackRequest{
+ Message: "feedback #" + strconv.Itoa(i),
+ })
+ w := httptest.NewRecorder()
+ testHandler.CreateFeedback(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("iteration %d: expected 201, got %d: %s", i, w.Code, w.Body.String())
+ }
+ }
+ req := newRequest("POST", "/api/feedback", CreateFeedbackRequest{Message: "one too many"})
+ w := httptest.NewRecorder()
+ testHandler.CreateFeedback(w, req)
+ if w.Code != http.StatusTooManyRequests {
+ t.Fatalf("expected 429, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// clearFeedbackForTestUser wipes all feedback rows for the shared test user
+// at both test start (fresh state) and test end (via t.Cleanup), so tests
+// in this file don't interfere with each other or with the hourly rate-limit
+// window when run in sequence.
+func clearFeedbackForTestUser(t *testing.T) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(), `DELETE FROM feedback WHERE user_id = $1`, parseUUID(testUserID)); err != nil {
+ t.Fatalf("clear feedback: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM feedback WHERE user_id = $1`, parseUUID(testUserID))
+ })
+}
diff --git a/server/migrations/057_feedback.down.sql b/server/migrations/057_feedback.down.sql
new file mode 100644
index 0000000000..77f1d85ef3
--- /dev/null
+++ b/server/migrations/057_feedback.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS feedback;
diff --git a/server/migrations/057_feedback.up.sql b/server/migrations/057_feedback.up.sql
new file mode 100644
index 0000000000..4e10b65897
--- /dev/null
+++ b/server/migrations/057_feedback.up.sql
@@ -0,0 +1,10 @@
+CREATE TABLE feedback (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,
+ workspace_id UUID REFERENCES workspace(id) ON DELETE SET NULL,
+ message TEXT NOT NULL,
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX idx_feedback_user_created ON feedback(user_id, created_at DESC);
diff --git a/server/pkg/db/generated/feedback.sql.go b/server/pkg/db/generated/feedback.sql.go
new file mode 100644
index 0000000000..d7d89ce9fd
--- /dev/null
+++ b/server/pkg/db/generated/feedback.sql.go
@@ -0,0 +1,56 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.30.0
+// source: feedback.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const countRecentFeedbackByUser = `-- name: CountRecentFeedbackByUser :one
+SELECT count(*) FROM feedback
+WHERE user_id = $1 AND created_at > now() - interval '1 hour'
+`
+
+func (q *Queries) CountRecentFeedbackByUser(ctx context.Context, userID pgtype.UUID) (int64, error) {
+ row := q.db.QueryRow(ctx, countRecentFeedbackByUser, userID)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const createFeedback = `-- name: CreateFeedback :one
+INSERT INTO feedback (user_id, workspace_id, message, metadata)
+VALUES ($1, $4, $2, $3)
+RETURNING id, user_id, workspace_id, message, metadata, created_at
+`
+
+type CreateFeedbackParams struct {
+ UserID pgtype.UUID `json:"user_id"`
+ Message string `json:"message"`
+ Metadata []byte `json:"metadata"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) CreateFeedback(ctx context.Context, arg CreateFeedbackParams) (Feedback, error) {
+ row := q.db.QueryRow(ctx, createFeedback,
+ arg.UserID,
+ arg.Message,
+ arg.Metadata,
+ arg.WorkspaceID,
+ )
+ var i Feedback
+ err := row.Scan(
+ &i.ID,
+ &i.UserID,
+ &i.WorkspaceID,
+ &i.Message,
+ &i.Metadata,
+ &i.CreatedAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index a749c967ad..ddfaec4625 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -221,6 +221,15 @@ type DaemonToken struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
+type Feedback struct {
+ ID pgtype.UUID `json:"id"`
+ UserID pgtype.UUID `json:"user_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Message string `json:"message"`
+ Metadata []byte `json:"metadata"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type InboxItem struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
diff --git a/server/pkg/db/queries/feedback.sql b/server/pkg/db/queries/feedback.sql
new file mode 100644
index 0000000000..93f8d2f574
--- /dev/null
+++ b/server/pkg/db/queries/feedback.sql
@@ -0,0 +1,8 @@
+-- name: CreateFeedback :one
+INSERT INTO feedback (user_id, workspace_id, message, metadata)
+VALUES ($1, sqlc.narg(workspace_id), $2, $3)
+RETURNING *;
+
+-- name: CountRecentFeedbackByUser :one
+SELECT count(*) FROM feedback
+WHERE user_id = $1 AND created_at > now() - interval '1 hour';