Files
multica/packages/views/modals/feedback.tsx
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

125 lines
4.4 KiB
TypeScript

"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>
);
}