A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat: allow users to report problems from the web app (#3268)
Mohamed Basseme979d3e69e2c
diff --git a/apps/web/components/dashboard/ErrorFallback.tsx b/apps/web/components/dashboard/ErrorFallback.tsxindex 9b65971d..b9c4490f 100644--- a/apps/web/components/dashboard/ErrorFallback.tsx+++ b/apps/web/components/dashboard/ErrorFallback.tsx@@ -2,9 +2,15 @@import Link from "next/link";import { Button } from "@/components/ui/button";-import { AlertTriangle, Home, RefreshCw } from "lucide-react";+import { useClientConfig } from "@/lib/clientConfig";+import { useTranslation } from "@/lib/i18n/client";+import { useProblemReportStore } from "@/lib/store/useProblemReportStore";+import { AlertTriangle, Bug, Home, RefreshCw } from "lucide-react";export default function ErrorFallback() {+ const { t } = useTranslation();+ const clientConfig = useClientConfig();+ const setReportProblemOpen = useProblemReportStore((s) => s.setOpen);return (<div className="flex flex-1 items-center justify-center rounded-lg bg-slate-50 p-8 shadow-sm dark:border dark:bg-card dark:shadow-none"><div className="w-full max-w-md space-y-8 text-center">@@ -36,6 +42,17 @@ export default function ErrorFallback() {Go Home</Button></Link>++ {clientConfig.problemReports.enabled && (+ <Button+ variant="ghost"+ className="w-full"+ onClick={() => setReportProblemOpen(true)}+ >+ <Bug className="h-4 w-4" />+ {t("problem_report.error_page_cta")}+ </Button>+ )}</div></div></div>diff --git a/apps/web/components/dashboard/ReportProblemDialog.tsx b/apps/web/components/dashboard/ReportProblemDialog.tsxnew file mode 100644index 00000000..c62c407e--- /dev/null+++ b/apps/web/components/dashboard/ReportProblemDialog.tsx@@ -0,0 +1,302 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { ActionButton } from "@/components/ui/action-button";+import { Button } from "@/components/ui/button";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@/components/ui/collapsible";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/components/ui/form";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { Textarea } from "@/components/ui/textarea";+import { useSession } from "@/lib/auth/client";+import { useTranslation } from "@/lib/i18n/client";+import {+ getRecentErrors,+ setRecentErrorsOwner,+} from "@/lib/problemReport/recentErrors";+import { useProblemReportStore } from "@/lib/store/useProblemReportStore";+import { zodResolver } from "@hookform/resolvers/zod";+import { useMutation } from "@tanstack/react-query";+import { CheckCircle2, ChevronRight } from "lucide-react";+import { useTheme } from "next-themes";+import { useForm } from "react-hook-form";+import { toast } from "sonner";+import { z } from "zod";++import type { ZProblemReportClientDiagnostics } from "@karakeep/shared/types/problemReports";+import { useTRPC } from "@karakeep/shared-react/trpc";+import {+ PROBLEM_REPORT_CATEGORIES,+ zProblemReportCategorySchema,+} from "@karakeep/shared/types/problemReports";++const DIALOG_CLOSE_RESET_DELAY_MS = 200;++const formSchema = z.object({+ category: zProblemReportCategorySchema,+ description: z.string().trim().min(10).max(5000),+ includeDiagnostics: z.boolean(),+});++function collectDiagnostics(theme?: string): ZProblemReportClientDiagnostics {+ // Truncate to the server-side limits so that, for example, a long search+ // query in the URL doesn't cause the whole report to be rejected.+ return {+ pageUrl: window.location.href.slice(0, 2000),+ userAgent: navigator.userAgent.slice(0, 1000),+ language: navigator.language.slice(0, 100),+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone.slice(0, 100),+ viewport: `${window.innerWidth}x${window.innerHeight}`,+ screen: `${window.screen.width}x${window.screen.height}`,+ devicePixelRatio: window.devicePixelRatio,+ theme,+ online: navigator.onLine,+ clientTimestamp: new Date().toISOString(),+ recentErrors: getRecentErrors(),+ };+}++export default function ReportProblemDialog() {+ const { t } = useTranslation();+ const api = useTRPC();+ const { data: session } = useSession();+ const { resolvedTheme } = useTheme();+ const open = useProblemReportStore((s) => s.open);+ const setOpen = useProblemReportStore((s) => s.setOpen);+ const [submittedReportId, setSubmittedReportId] = useState<string | null>(+ null,+ );+ const [detailsOpen, setDetailsOpen] = useState(false);++ const userId = session?.user.id ?? null;+ useEffect(() => {+ setRecentErrorsOwner(userId);+ }, [userId]);++ const form = useForm<z.infer<typeof formSchema>>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ category: "bug",+ description: "",+ includeDiagnostics: true,+ },+ });++ // Snapshot the diagnostics when the dialog opens so that they reflect the+ // page the user was on, and what we show is exactly what we send.+ const diagnostics = useMemo(+ () => (open ? collectDiagnostics(resolvedTheme) : undefined),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [open],+ );++ useEffect(() => {+ if (open) return;+ const timeout = setTimeout(() => {+ form.reset();+ setSubmittedReportId(null);+ setDetailsOpen(false);+ }, DIALOG_CLOSE_RESET_DELAY_MS);+ return () => clearTimeout(timeout);+ }, [open, form]);++ const { mutate, isPending } = useMutation(+ api.problemReports.submit.mutationOptions({+ onSuccess: (res) => {+ // If the dialog was closed while the report was in flight, don't+ // populate the success screen (it'd show up the next time the+ // dialog is opened). Confirm with a toast instead.+ if (!useProblemReportStore.getState().open) {+ toast.success(t("problem_report.toasts.sent"));+ return;+ }+ setSubmittedReportId(res.reportId);+ },+ onError: (e) =>+ toast.error(e.message || t("problem_report.toasts.failed")),+ }),+ );++ const onSubmit = (values: z.infer<typeof formSchema>) => {+ mutate({+ category: values.category,+ description: values.description,+ diagnostics: values.includeDiagnostics ? diagnostics : undefined,+ });+ };++ const includeDiagnostics = form.watch("includeDiagnostics");++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">+ {submittedReportId ? (+ <div className="flex flex-col items-center gap-3 py-4 text-center">+ <CheckCircle2 className="size-12 text-green-600" />+ <DialogTitle>{t("problem_report.success.title")}</DialogTitle>+ <DialogDescription className="text-pretty">+ {session?.user.email+ ? t("problem_report.success.description_with_email", {+ email: session.user.email,+ })+ : t("problem_report.success.description")}+ </DialogDescription>+ <p className="font-mono text-xs text-muted-foreground">+ {t("problem_report.success.reference", {+ id: submittedReportId,+ })}+ </p>+ <DialogClose asChild>+ <Button className="mt-2">{t("actions.close")}</Button>+ </DialogClose>+ </div>+ ) : (+ <>+ <DialogHeader>+ <DialogTitle>{t("problem_report.title")}</DialogTitle>+ <DialogDescription>+ {t("problem_report.description")}+ </DialogDescription>+ </DialogHeader>+ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(onSubmit)}+ className="flex flex-col gap-4"+ >+ <FormField+ control={form.control}+ name="category"+ render={({ field }) => (+ <FormItem>+ <FormLabel>{t("problem_report.category")}</FormLabel>+ <Select+ value={field.value}+ onValueChange={field.onChange}+ >+ <FormControl>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {PROBLEM_REPORT_CATEGORIES.map((c) => (+ <SelectItem key={c} value={c}>+ {t(`problem_report.categories.${c}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="description"+ render={({ field }) => (+ <FormItem>+ <FormLabel>{t("problem_report.what_happened")}</FormLabel>+ <FormControl>+ <Textarea+ {...field}+ rows={6}+ maxLength={5000}+ placeholder={t(+ "problem_report.what_happened_placeholder",+ )}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="includeDiagnostics"+ render={({ field }) => (+ <FormItem className="rounded-md border p-3">+ <div className="flex items-start justify-between gap-4">+ <div className="space-y-1">+ <FormLabel>+ {t("problem_report.include_diagnostics")}+ </FormLabel>+ <p className="text-sm text-muted-foreground">+ {t(+ "problem_report.include_diagnostics_description",+ )}+ </p>+ </div>+ <FormControl>+ <Switch+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </div>+ {includeDiagnostics && diagnostics && (+ <Collapsible+ open={detailsOpen}+ onOpenChange={setDetailsOpen}+ >+ <CollapsibleTrigger className="flex items-center gap-1 pt-2 text-sm font-medium text-muted-foreground hover:text-foreground">+ <ChevronRight+ className={`size-4 transition-transform ${detailsOpen ? "rotate-90" : ""}`}+ />+ {t("problem_report.view_diagnostics", {+ count: diagnostics.recentErrors?.length ?? 0,+ })}+ </CollapsibleTrigger>+ <CollapsibleContent>+ <pre className="mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded bg-muted p-2 font-mono text-xs">+ {JSON.stringify(diagnostics, null, 2)}+ </pre>+ </CollapsibleContent>+ </Collapsible>+ )}+ </FormItem>+ )}+ />+ <DialogFooter className="gap-2 sm:gap-0">+ <DialogClose asChild>+ <Button type="button" variant="secondary">+ {t("actions.cancel")}+ </Button>+ </DialogClose>+ <ActionButton type="submit" loading={isPending}>+ {t("problem_report.submit")}+ </ActionButton>+ </DialogFooter>+ </form>+ </Form>+ </>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/apps/web/components/dashboard/header/ProfileOptions.tsx b/apps/web/components/dashboard/header/ProfileOptions.tsxindex 225e53d8..27626668 100644--- a/apps/web/components/dashboard/header/ProfileOptions.tsx+++ b/apps/web/components/dashboard/header/ProfileOptions.tsx@@ -13,12 +13,15 @@ import {import { Separator } from "@/components/ui/separator";import { UserAvatar } from "@/components/ui/user-avatar";import { useSession } from "@/lib/auth/client";+import { useClientConfig } from "@/lib/clientConfig";import { useTranslation } from "@/lib/i18n/client";import { useInBookmarkGridStore } from "@/lib/store/useInBookmarkGridStore";import { useKeyboardNavigationStore } from "@/lib/store/useKeyboardNavigationStore";+import { useProblemReportStore } from "@/lib/store/useProblemReportStore";import { cn } from "@/lib/utils";import {BookOpen,+ Bug,Keyboard,Laptop,LogOut,@@ -36,6 +39,7 @@ import { useTheme } from "next-themes";import { useWhoAmI } from "@karakeep/shared-react/hooks/users";import { AdminNoticeBadge } from "../../admin/AdminNotices";+import ReportProblemDialog from "../ReportProblemDialog";const THEME_OPTIONS = [{ value: "light", icon: Sun, label: "options.light_mode" },@@ -91,6 +95,8 @@ export default function SidebarProfileOptions() {const setShortcutsDialogOpen = useKeyboardNavigationStore((state) => state.setShortcutsDialogOpen,);+ const clientConfig = useClientConfig();+ const setReportProblemOpen = useProblemReportStore((s) => s.setOpen);const avatarImage = whoami?.image ?? null;const avatarUrl = useMemo(() => avatarImage ?? null, [avatarImage]);@@ -98,91 +104,112 @@ export default function SidebarProfileOptions() {if (!session) return redirect("/");return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- className="border-new-gray-200 shrink-0 rounded-full border-4 bg-black p-0 text-white"- variant="ghost"- size="icon"- >- <UserAvatar- image={avatarUrl}- name={session.user.name}- className="h-full w-full rounded-full"- />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent className="mr-2 min-w-64 p-2">- <div className="flex gap-2">- <div className="border-new-gray-200 flex aspect-square size-11 items-center justify-center overflow-hidden rounded-full border-4 bg-black p-0 text-white">+ <>+ {clientConfig.problemReports.enabled && <ReportProblemDialog />}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ className="border-new-gray-200 shrink-0 rounded-full border-4 bg-black p-0 text-white"+ variant="ghost"+ size="icon"+ ><UserAvatarimage={avatarUrl}name={session.user.name}- className="h-full w-full"+ className="h-full w-full rounded-full"/>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent className="mr-2 min-w-64 p-2">+ <div className="flex gap-2">+ <div className="border-new-gray-200 flex aspect-square size-11 items-center justify-center overflow-hidden rounded-full border-4 bg-black p-0 text-white">+ <UserAvatar+ image={avatarUrl}+ name={session.user.name}+ className="h-full w-full"+ />+ </div>+ <div className="flex flex-col">+ <p>{session.user.name}</p>+ <p className="text-sm text-gray-400">{session.user.email}</p>+ </div></div>- <div className="flex flex-col">- <p>{session.user.name}</p>- <p className="text-sm text-gray-400">{session.user.email}</p>- </div>- </div>- <Separator className="my-2" />- <DropdownMenuItem asChild>- <Link href="/settings">- <Settings className="size-4" />- {t("settings.user_settings")}- </Link>- </DropdownMenuItem>- {session.user.role == "admin" && (+ <Separator className="my-2" />+ <DropdownMenuItem asChild>+ <Link href="/settings">+ <Settings className="size-4" />+ {t("settings.user_settings")}+ </Link>+ </DropdownMenuItem>+ {session.user.role == "admin" && (+ <DropdownMenuItem asChild>+ <Link href="/admin" className="flex justify-between">+ <div className="items-cente flex gap-2">+ <Shield className="size-4" />+ {t("admin.admin_settings")}+ </div>+ <AdminNoticeBadge />+ </Link>+ </DropdownMenuItem>+ )}+ <Separator className="my-2" /><DropdownMenuItem asChild>- <Link href="/admin" className="flex justify-between">- <div className="items-cente flex gap-2">- <Shield className="size-4" />- {t("admin.admin_settings")}- </div>- <AdminNoticeBadge />+ <Link href="/dashboard/cleanups">+ <Paintbrush className="size-4" />+ {t("cleanups.cleanups")}</Link></DropdownMenuItem>- )}- <Separator className="my-2" />- <DropdownMenuItem asChild>- <Link href="/dashboard/cleanups">- <Paintbrush className="size-4" />- {t("cleanups.cleanups")}- </Link>- </DropdownMenuItem>- <ThemeSelector />- {inBookmarkGrid && (- <DropdownMenuItem onClick={() => setShortcutsDialogOpen(true)}>- <Keyboard className="size-4" />- {t("keyboard_shortcuts.title")}+ <ThemeSelector />+ {inBookmarkGrid && (+ <DropdownMenuItem onClick={() => setShortcutsDialogOpen(true)}>+ <Keyboard className="size-4" />+ {t("keyboard_shortcuts.title")}+ </DropdownMenuItem>+ )}+ <Separator className="my-2" />+ <DropdownMenuItem asChild>+ <a+ href="https://karakeep.com/apps"+ target="_blank"+ rel="noreferrer"+ >+ <Puzzle className="size-4" />+ {t("options.apps_extensions")}+ </a>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <a+ href="https://docs.karakeep.com"+ target="_blank"+ rel="noreferrer"+ >+ <BookOpen className="size-4" />+ {t("options.documentation")}+ </a>+ </DropdownMenuItem>+ <DropdownMenuItem asChild>+ <a+ href="https://x.com/karakeep_app"+ target="_blank"+ rel="noreferrer"+ >+ <Twitter className="size-4" />+ {t("options.follow_us_on_x")}+ </a>+ </DropdownMenuItem>+ {clientConfig.problemReports.enabled && (+ <DropdownMenuItem onClick={() => setReportProblemOpen(true)}>+ <Bug className="size-4" />+ {t("options.report_a_problem")}+ </DropdownMenuItem>+ )}+ <Separator className="my-2" />+ <DropdownMenuItem onClick={() => router.push("/logout")}>+ <LogOut className="size-4" />+ <span>{t("actions.sign_out")}</span></DropdownMenuItem>- )}- <Separator className="my-2" />- <DropdownMenuItem asChild>- <a href="https://karakeep.com/apps" target="_blank" rel="noreferrer">- <Puzzle className="size-4" />- {t("options.apps_extensions")}- </a>- </DropdownMenuItem>- <DropdownMenuItem asChild>- <a href="https://docs.karakeep.com" target="_blank" rel="noreferrer">- <BookOpen className="size-4" />- {t("options.documentation")}- </a>- </DropdownMenuItem>- <DropdownMenuItem asChild>- <a href="https://x.com/karakeep_app" target="_blank" rel="noreferrer">- <Twitter className="size-4" />- {t("options.follow_us_on_x")}- </a>- </DropdownMenuItem>- <Separator className="my-2" />- <DropdownMenuItem onClick={() => router.push("/logout")}>- <LogOut className="size-4" />- <span>{t("actions.sign_out")}</span>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ </DropdownMenuContent>+ </DropdownMenu>+ </>);}diff --git a/apps/web/lib/i18n/locales/en/translation.json b/apps/web/lib/i18n/locales/en/translation.jsonindex 58e9c17a..682ce32e 100644--- a/apps/web/lib/i18n/locales/en/translation.json+++ b/apps/web/lib/i18n/locales/en/translation.json@@ -856,7 +856,8 @@"system_mode": "System Mode","apps_extensions": "Apps & Extensions","documentation": "Documentation",- "follow_us_on_x": "Follow us on X"+ "follow_us_on_x": "Follow us on X",+ "report_a_problem": "Report a Problem"},"lists": {"all_lists": "All Lists",@@ -1263,5 +1264,35 @@"deselect_all": "Deselect all","show_help": "Show keyboard shortcuts","focus_search_alt": "Focus search"+ },+ "problem_report": {+ "title": "Report a problem",+ "description": "Tell us what went wrong. Your report will be emailed to the administrator of this Karakeep instance.",+ "category": "What kind of problem is it?",+ "categories": {+ "bug": "Something isn't working",+ "content": "Bookmark content / crawling issue",+ "performance": "Slowness or performance",+ "account": "Account or login",+ "other": "Other"+ },+ "what_happened": "What happened?",+ "what_happened_placeholder": "Describe what you were doing, what you expected to happen, and what happened instead.",+ "include_diagnostics": "Include diagnostic information",+ "include_diagnostics_description": "Helps with investigating. Includes the current page, browser details and recent errors from this tab.",+ "view_diagnostics_one": "Show what will be sent ({{count}} recent error)",+ "view_diagnostics_other": "Show what will be sent ({{count}} recent errors)",+ "submit": "Send report",+ "error_page_cta": "Report this problem",+ "success": {+ "title": "Thanks for your report!",+ "description": "Your report has been sent to the administrator.",+ "description_with_email": "Your report has been sent to the administrator. They may follow up with you at {{email}}.",+ "reference": "Reference: {{id}}"+ },+ "toasts": {+ "failed": "Failed to send the report. Please try again later.",+ "sent": "Your problem report has been sent."+ }}}diff --git a/apps/web/lib/problemReport/recentErrors.test.ts b/apps/web/lib/problemReport/recentErrors.test.tsnew file mode 100644index 00000000..3f7838d2--- /dev/null+++ b/apps/web/lib/problemReport/recentErrors.test.ts@@ -0,0 +1,44 @@+// @vitest-environment jsdom+import { beforeAll, describe, expect, test, vi } from "vitest";++import {+ getRecentErrors,+ installRecentErrorCapture,+ setRecentErrorsOwner,+} from "./recentErrors";++describe("recentErrors", () => {+ beforeAll(() => {+ vi.spyOn(console, "error").mockImplementation(() => undefined);+ installRecentErrorCapture();+ });++ test("keeps errors captured before the owner is known", () => {+ console.error("early error");+ setRecentErrorsOwner("user-a");+ expect(getRecentErrors().map((e) => e.message)).toEqual(["early error"]);+ });++ test("drops errors captured under a different account", () => {+ console.error("user a error");+ setRecentErrorsOwner("user-a");+ expect(getRecentErrors().length).toBeGreaterThan(0);++ setRecentErrorsOwner("user-b");+ expect(getRecentErrors()).toEqual([]);++ console.error("user b error");+ setRecentErrorsOwner("user-b");+ expect(getRecentErrors().map((e) => e.message)).toEqual(["user b error"]);+ });++ test("records rejections with no reason", () => {+ window.dispatchEvent(+ Object.assign(new Event("unhandledrejection"), { reason: undefined }),+ );+ expect(getRecentErrors().at(-1)).toMatchObject({+ message: "undefined",+ source: "unhandledrejection",+ });+ });+});diff --git a/apps/web/lib/problemReport/recentErrors.ts b/apps/web/lib/problemReport/recentErrors.tsnew file mode 100644index 00000000..0c623598--- /dev/null+++ b/apps/web/lib/problemReport/recentErrors.ts@@ -0,0 +1,89 @@+import type { ZProblemReportRecentError } from "@karakeep/shared/types/problemReports";+import { MAX_PROBLEM_REPORT_RECENT_ERRORS } from "@karakeep/shared/types/problemReports";++const MAX_MESSAGE_LENGTH = 2000;++// In-memory ring buffer of the most recent client-side errors. It's only ever+// read when the user explicitly submits a problem report.+const recentErrors: ZProblemReportRecentError[] = [];+let installed = false;+// The user the buffered errors belong to. `undefined` means not known yet.+let bufferOwner: string | null | undefined = undefined;++function stringify(value: unknown): string {+ if (value instanceof Error) {+ return value.stack ?? `${value.name}: ${value.message}`;+ }+ if (typeof value === "string") {+ return value;+ }+ try {+ // JSON.stringify returns undefined for undefined, functions and symbols+ return JSON.stringify(value) ?? String(value);+ } catch {+ return String(value);+ }+}++function record(getMessage: () => string, source?: string) {+ let message: string;+ try {+ message = getMessage();+ } catch {+ // Never let error capturing itself throw+ return;+ }+ recentErrors.push({+ message: message.slice(0, MAX_MESSAGE_LENGTH),+ source: source?.slice(0, 500),+ timestamp: new Date().toISOString(),+ });+ if (recentErrors.length > MAX_PROBLEM_REPORT_RECENT_ERRORS) {+ recentErrors.splice(+ 0,+ recentErrors.length - MAX_PROBLEM_REPORT_RECENT_ERRORS,+ );+ }+}++export function installRecentErrorCapture() {+ if (installed || typeof window === "undefined") {+ return;+ }+ installed = true;++ window.addEventListener("error", (event) => {+ record(+ () => stringify(event.error ?? event.message),+ event.filename+ ? `${event.filename}:${event.lineno}:${event.colno}`+ : "window.onerror",+ );+ });++ window.addEventListener("unhandledrejection", (event) => {+ record(() => stringify(event.reason), "unhandledrejection");+ });++ // eslint-disable-next-line no-console+ const originalConsoleError = console.error;+ // eslint-disable-next-line no-console+ console.error = (...args: unknown[]) => {+ record(() => args.map(stringify).join(" "), "console.error");+ originalConsoleError.apply(console, args);+ };+}++// Login and logout are client-side navigations, so this module outlives a+// session. Drop errors captured under a different account so they're never+// attached to another user's report.+export function setRecentErrorsOwner(userId: string | null) {+ if (bufferOwner !== undefined && bufferOwner !== userId) {+ recentErrors.length = 0;+ }+ bufferOwner = userId;+}++export function getRecentErrors(): ZProblemReportRecentError[] {+ return [...recentErrors];+}diff --git a/apps/web/lib/providers.tsx b/apps/web/lib/providers.tsxindex d329317f..d02a6b0a 100644--- a/apps/web/lib/providers.tsx+++ b/apps/web/lib/providers.tsx@@ -1,10 +1,11 @@"use client";import type { UserLocalSettings } from "@/lib/userLocalSettings/types";-import React, { useState } from "react";+import React, { useEffect, useState } from "react";import { ThemeProvider } from "@/components/theme-provider";import { TooltipProvider } from "@/components/ui/tooltip";import { Session, SessionProvider } from "@/lib/auth/client";+import { installRecentErrorCapture } from "@/lib/problemReport/recentErrors";import { UserLocalSettingsCtx } from "@/lib/userLocalSettings/bookmarksLayout";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { createTRPCClient, httpBatchLink, loggerLink } from "@trpc/client";@@ -61,6 +62,12 @@ export default function Providers({}) {const queryClient = getQueryClient();+ useEffect(() => {+ if (clientConfig.problemReports.enabled) {+ installRecentErrorCapture();+ }+ }, [clientConfig.problemReports.enabled]);+const [trpcClient] = useState(() =>createTRPCClient<AppRouter>({links: [diff --git a/apps/web/lib/store/useProblemReportStore.ts b/apps/web/lib/store/useProblemReportStore.tsnew file mode 100644index 00000000..3a4d6192--- /dev/null+++ b/apps/web/lib/store/useProblemReportStore.ts@@ -0,0 +1,11 @@+import { create } from "zustand";++interface ProblemReportState {+ open: boolean;+ setOpen: (open: boolean) => void;+}++export const useProblemReportStore = create<ProblemReportState>((set) => ({+ open: false,+ setOpen: (open) => set({ open }),+}));diff --git a/packages/shared-react/providers/client-config-provider.tsx b/packages/shared-react/providers/client-config-provider.tsxindex 71da99e8..ee24d72e 100644--- a/packages/shared-react/providers/client-config-provider.tsx+++ b/packages/shared-react/providers/client-config-provider.tsx@@ -34,6 +34,9 @@ export const DEFAULT_CLIENT_CONFIG: ZClientConfig = {purchasePlatforms: [],},legal: {},+ problemReports: {+ enabled: false,+ },disableNewReleaseCheck: true,};@@ -84,6 +87,10 @@ export function ClientConfigProvider({...DEFAULT_CLIENT_CONFIG.legal,...value?.legal,},+ problemReports: {+ ...DEFAULT_CLIENT_CONFIG.problemReports,+ ...value?.problemReports,+ },}),[value],);diff --git a/packages/shared/config.ts b/packages/shared/config.tsindex 7589bf13..28c310e6 100644--- a/packages/shared/config.ts+++ b/packages/shared/config.ts@@ -210,6 +210,9 @@ const allEnv = z.object({SMTP_USER: z.string().optional(),SMTP_PASSWORD: z.string().optional(),SMTP_FROM: z.string().optional(),++ // Problem reports+ PROBLEM_REPORTS_EMAIL: z.string().email().optional(),EMAIL_VERIFICATION_REQUIRED: stringBool("false"),// Asset storage configuration@@ -367,6 +370,10 @@ const serverConfigSchema = allEnv.transform((val, ctx) => {}: undefined,},+ problemReports: {+ enabled: !!val.PROBLEM_REPORTS_EMAIL,+ email: val.PROBLEM_REPORTS_EMAIL,+ },inference: {isConfigured: !!val.OPENAI_API_KEY || !!val.OLLAMA_BASE_URL,numWorkers: val.INFERENCE_NUM_WORKERS,@@ -608,6 +615,15 @@ const serverConfigSchema = allEnv.transform((val, ctx) => {});return z.NEVER;}+ if (obj.problemReports.enabled && !obj.email.smtp) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ "To enable problem reports (PROBLEM_REPORTS_EMAIL), SMTP settings must be configured",+ fatal: true,+ });+ return z.NEVER;+ }if (obj.auth.turnstile.enabled && !obj.auth.turnstile.secretKey) {ctx.addIssue({code: z.ZodIssueCode.custom,@@ -690,6 +706,9 @@ export const clientConfig = {termsOfServiceUrl: serverConfig.legal.termsOfServiceUrl,privacyPolicyUrl: serverConfig.legal.privacyPolicyUrl,},+ problemReports: {+ enabled: serverConfig.problemReports.enabled,+ },serverVersion: serverConfig.serverVersion,disableNewReleaseCheck: serverConfig.disableNewReleaseCheck,};diff --git a/packages/shared/types/config.ts b/packages/shared/types/config.tsindex 06d8f0b6..da29ee3b 100644--- a/packages/shared/types/config.ts+++ b/packages/shared/types/config.ts@@ -45,6 +45,9 @@ export const zClientConfigSchema = z.object({termsOfServiceUrl: z.string().optional(),privacyPolicyUrl: z.string().optional(),}),+ problemReports: z.object({+ enabled: z.boolean(),+ }),serverVersion: z.string().optional(),disableNewReleaseCheck: z.boolean(),});diff --git a/packages/shared/types/problemReports.ts b/packages/shared/types/problemReports.tsnew file mode 100644index 00000000..87aad7e2--- /dev/null+++ b/packages/shared/types/problemReports.ts@@ -0,0 +1,54 @@+import { z } from "zod";++export const PROBLEM_REPORT_CATEGORIES = [+ "bug",+ "content",+ "performance",+ "account",+ "other",+] as const;++export const zProblemReportCategorySchema = z.enum(PROBLEM_REPORT_CATEGORIES);+export type ZProblemReportCategory = z.infer<+ typeof zProblemReportCategorySchema+>;++export const MAX_PROBLEM_REPORT_RECENT_ERRORS = 20;++export const zProblemReportRecentErrorSchema = z.object({+ message: z.string().max(2000),+ source: z.string().max(500).optional(),+ timestamp: z.string().max(64),+});+export type ZProblemReportRecentError = z.infer<+ typeof zProblemReportRecentErrorSchema+>;++// Diagnostics collected by the client. Everything here is optional and+// size-bounded since it's user controlled.+export const zProblemReportClientDiagnosticsSchema = z.object({+ pageUrl: z.string().max(2000).optional(),+ userAgent: z.string().max(1000).optional(),+ language: z.string().max(100).optional(),+ timezone: z.string().max(100).optional(),+ viewport: z.string().max(50).optional(),+ screen: z.string().max(50).optional(),+ devicePixelRatio: z.number().optional(),+ theme: z.string().max(50).optional(),+ online: z.boolean().optional(),+ clientTimestamp: z.string().max(64).optional(),+ recentErrors: z+ .array(zProblemReportRecentErrorSchema)+ .max(MAX_PROBLEM_REPORT_RECENT_ERRORS)+ .optional(),+});+export type ZProblemReportClientDiagnostics = z.infer<+ typeof zProblemReportClientDiagnosticsSchema+>;++export const zSubmitProblemReportSchema = z.object({+ category: zProblemReportCategorySchema,+ description: z.string().trim().min(10).max(5000),+ diagnostics: zProblemReportClientDiagnosticsSchema.optional(),+});+export type ZSubmitProblemReport = z.infer<typeof zSubmitProblemReportSchema>;diff --git a/packages/trpc/email.ts b/packages/trpc/email.tsindex 4a056dcf..07723308 100644--- a/packages/trpc/email.ts+++ b/packages/trpc/email.ts@@ -2,6 +2,10 @@ import { createTransport } from "nodemailer";import { getTracer, withSpan } from "@karakeep/shared-server";import serverConfig from "@karakeep/shared/config";+import type {+ ZProblemReportClientDiagnostics,+ ZProblemReportCategory,+} from "@karakeep/shared/types/problemReports";import { escapeHtml } from "@karakeep/shared/utils/htmlUtils";const tracer = getTracer("@karakeep/trpc");@@ -233,3 +237,158 @@ If you weren't expecting this invitation, you can safely ignore this email or de},{ silentFail: true },);++export interface ProblemReportEmail {+ reportId: string;+ category: ZProblemReportCategory;+ description: string;+ reporter: {+ id: string;+ name?: string | null;+ email?: string | null;+ role?: string | null;+ };+ server: {+ version?: string;+ publicUrl: string;+ receivedAt: string;+ };+ diagnostics?: ZProblemReportClientDiagnostics;+}++const PROBLEM_REPORT_CATEGORY_LABELS: Record<ZProblemReportCategory, string> = {+ bug: "Something isn't working",+ content: "Bookmark content / crawling issue",+ performance: "Slowness or performance",+ account: "Account or login",+ other: "Other",+};++function problemReportSections(report: ProblemReportEmail) {+ const d = report.diagnostics;+ const fmt = (v: unknown) =>+ v === undefined || v === null || v === "" ? "—" : String(v);+ return {+ reporter: [+ ["User ID", report.reporter.id],+ ["Name", fmt(report.reporter.name)],+ ["Email", fmt(report.reporter.email)],+ ["Role", fmt(report.reporter.role)],+ ],+ server: [+ ["Report ID", report.reportId],+ ["Received at", report.server.receivedAt],+ ["Server version", fmt(report.server.version)],+ ["Instance URL", report.server.publicUrl],+ ],+ client: d+ ? [+ ["Page", fmt(d.pageUrl)],+ ["User agent", fmt(d.userAgent)],+ ["Language", fmt(d.language)],+ ["Timezone", fmt(d.timezone)],+ ["Viewport", fmt(d.viewport)],+ ["Screen", fmt(d.screen)],+ ["Pixel ratio", fmt(d.devicePixelRatio)],+ ["Theme", fmt(d.theme)],+ ["Online", fmt(d.online)],+ ["Client time", fmt(d.clientTimestamp)],+ ]+ : null,+ recentErrors: d?.recentErrors ?? [],+ };+}++function htmlTable(rows: string[][]) {+ return `<table style="border-collapse: collapse; width: 100%; font-size: 13px;">${rows+ .map(+ ([k, v]) =>+ `<tr><td style="padding: 4px 8px; color: #666; white-space: nowrap; vertical-align: top; border-bottom: 1px solid #eee;">${escapeHtml(k)}</td><td style="padding: 4px 8px; border-bottom: 1px solid #eee; word-break: break-all;">${escapeHtml(v)}</td></tr>`,+ )+ .join("")}</table>`;+}++function textTable(rows: string[][]) {+ return rows.map(([k, v]) => ` ${k}: ${v}`).join("\n");+}++export function buildProblemReportEmail(report: ProblemReportEmail) {+ const sections = problemReportSections(report);+ const categoryLabel = PROBLEM_REPORT_CATEGORY_LABELS[report.category];+ const firstLine = report.description.split(/\r?\n/)[0].trim().slice(0, 80);+ const subject = `[Karakeep problem report] ${categoryLabel}: ${firstLine}`;++ const errorsHtml =+ sections.recentErrors.length > 0+ ? sections.recentErrors+ .map(+ (e) =>+ `<div style="margin-bottom: 8px;"><div style="color: #666; font-size: 12px;">${escapeHtml(e.timestamp)}${e.source ? ` · ${escapeHtml(e.source)}` : ""}</div><pre style="margin: 2px 0 0; white-space: pre-wrap; word-break: break-all; background: #f6f6f6; padding: 6px; border-radius: 4px; font-size: 12px;">${escapeHtml(e.message)}</pre></div>`,+ )+ .join("")+ : `<p style="color: #666; font-size: 13px;">None captured.</p>`;++ const html = `+ <div style="font-family: Arial, sans-serif; max-width: 700px; margin: 0 auto;">+ <h2 style="margin-bottom: 4px;">New problem report</h2>+ <p style="margin-top: 0; color: #666;">${escapeHtml(categoryLabel)}</p>+ <h3>Description</h3>+ <div style="white-space: pre-wrap; background: #f6f6f6; padding: 12px; border-radius: 6px;">${escapeHtml(report.description)}</div>+ <h3>Reporter</h3>+ ${htmlTable(sections.reporter)}+ <h3>Server</h3>+ ${htmlTable(sections.server)}+ <h3>Browser</h3>+ ${sections.client ? htmlTable(sections.client) : `<p style="color: #666; font-size: 13px;">The user chose not to share browser diagnostics.</p>`}+ ${sections.client ? `<h3>Recent client errors</h3>${errorsHtml}` : ""}+ <p style="color: #999; font-size: 12px; margin-top: 24px;">Reply to this email to respond directly to the reporter.</p>+ </div>+ `;++ const errorsText =+ sections.recentErrors.length > 0+ ? sections.recentErrors+ .map(+ (e) =>+ ` [${e.timestamp}]${e.source ? ` (${e.source})` : ""} ${e.message}`,+ )+ .join("\n")+ : " None captured.";++ const text = `+New problem report: ${categoryLabel}++Description:+${report.description}++Reporter:+${textTable(sections.reporter)}++Server:+${textTable(sections.server)}++Browser:+${sections.client ? textTable(sections.client) : " The user chose not to share browser diagnostics."}+${sections.client ? `\nRecent client errors:\n${errorsText}\n` : ""}`;++ return { subject, html, text };+}++export const sendProblemReportEmail = withTracing(+ "sendProblemReportEmail",+ async (transporter: Transporter, report: ProblemReportEmail) => {+ const to = serverConfig.problemReports.email;+ if (!to) {+ throw new Error("PROBLEM_REPORTS_EMAIL is not configured");+ }+ const { subject, html, text } = buildProblemReportEmail(report);+ await transporter.sendMail({+ from: serverConfig.email.smtp!.from,+ to,+ replyTo: report.reporter.email ?? undefined,+ subject,+ html,+ text,+ });+ },+);diff --git a/packages/trpc/routers/_app.ts b/packages/trpc/routers/_app.tsindex 9e20bb7e..7841d9c4 100644--- a/packages/trpc/routers/_app.ts+++ b/packages/trpc/routers/_app.ts@@ -11,6 +11,7 @@ import { importSessionsRouter } from "./importSessions";import { invitesAppRouter } from "./invites";import { listsAppRouter } from "./lists";import { promptsAppRouter } from "./prompts";+import { problemReportsAppRouter } from "./problemReports";import { publicBookmarks } from "./publicBookmarks";import { rulesAppRouter } from "./rules";import { subscriptionsRouter } from "./subscriptions";@@ -37,6 +38,7 @@ export const appRouter = router({publicBookmarks: publicBookmarks,subscriptions: subscriptionsRouter,config: configAppRouter,+ problemReports: problemReportsAppRouter,});// export type definition of APIexport type AppRouter = typeof appRouter;diff --git a/packages/trpc/routers/problemReports.test.ts b/packages/trpc/routers/problemReports.test.tsnew file mode 100644index 00000000..a38046af--- /dev/null+++ b/packages/trpc/routers/problemReports.test.ts@@ -0,0 +1,161 @@+import { beforeEach, describe, expect, test, vi } from "vitest";++import serverConfig from "@karakeep/shared/config";++import type { CustomTestContext } from "../testUtils";+import { buildProblemReportEmail, sendProblemReportEmail } from "../email";+import { createTestUser, defaultBeforeEach, getApiCaller } from "../testUtils";++vi.mock("@karakeep/shared/config", async (original) => {+ const mod = (await original()) as typeof import("@karakeep/shared/config");+ return {+ ...mod,+ default: {+ ...mod.default,+ email: {+ smtp: {+ host: "test-smtp.example.com",+ port: 587,+ secure: false,+ from: "[email protected]",+ },+ },+ problemReports: {+ enabled: true,+ email: "[email protected]",+ },+ },+ };+});++vi.mock("../email", async (original) => {+ const mod = (await original()) as typeof import("../email");+ return {+ ...mod,+ sendProblemReportEmail: vi.fn().mockResolvedValue(undefined),+ };+});++beforeEach<CustomTestContext>(defaultBeforeEach(false));++describe("Problem reports router", () => {+ beforeEach(() => {+ vi.mocked(sendProblemReportEmail).mockClear();+ (+ serverConfig.problemReports as { enabled: boolean; email?: string }+ ).enabled = true;+ });++ test<CustomTestContext>("sends a report with server and client diagnostics", async ({+ db,+ }) => {+ const user = await createTestUser(db, {+ name: "Reporter",+ email: "[email protected]",+ password: "pass1234",+ });+ const caller = getApiCaller(db, user.id, user.email);++ const res = await caller.problemReports.submit({+ category: "bug",+ description: "Clicking save does nothing on the bookmark page.",+ diagnostics: {+ pageUrl: "https://karakeep.test/dashboard/bookmarks",+ userAgent: "Mozilla/5.0",+ recentErrors: [+ {+ message: "TypeError: x is undefined",+ timestamp: new Date().toISOString(),+ },+ ],+ },+ });++ expect(res.reportId).toBeDefined();+ expect(sendProblemReportEmail).toHaveBeenCalledOnce();+ const report = vi.mocked(sendProblemReportEmail).mock.calls[0][0];+ expect(report.reportId).toBe(res.reportId);+ expect(report.reporter).toMatchObject({+ id: user.id,+ email: "[email protected]",+ });+ expect(report.diagnostics?.recentErrors).toHaveLength(1);+ });++ test<CustomTestContext>("rejects when problem reports are disabled", async ({+ db,+ }) => {+ (+ serverConfig.problemReports as { enabled: boolean; email?: string }+ ).enabled = false;+ const user = await createTestUser(db, {+ name: "Reporter",+ email: "[email protected]",+ password: "pass1234",+ });+ const caller = getApiCaller(db, user.id, user.email);++ await expect(+ caller.problemReports.submit({+ category: "other",+ description: "This should not be sent at all.",+ }),+ ).rejects.toThrow(/not enabled/);+ expect(sendProblemReportEmail).not.toHaveBeenCalled();+ });++ test<CustomTestContext>("rejects API key auth", async ({ db }) => {+ const user = await createTestUser(db, {+ name: "Reporter",+ email: "[email protected]",+ password: "pass1234",+ });+ const caller = getApiCaller(db, user.id, user.email, "user", {+ type: "apiKey",+ keyId: "key",+ scopes: [],+ });++ await expect(+ caller.problemReports.submit({+ category: "bug",+ description: "Sent from a script using an API key.",+ }),+ ).rejects.toThrow();+ expect(sendProblemReportEmail).not.toHaveBeenCalled();+ });++ test<CustomTestContext>("rejects too short descriptions", async ({ db }) => {+ const user = await createTestUser(db, {+ name: "Reporter",+ email: "[email protected]",+ password: "pass1234",+ });+ const caller = getApiCaller(db, user.id, user.email);++ await expect(+ caller.problemReports.submit({ category: "bug", description: "short" }),+ ).rejects.toThrow();+ });+});++describe("buildProblemReportEmail", () => {+ test("escapes user content in the html body", () => {+ const { subject, html, text } = buildProblemReportEmail({+ reportId: "r1",+ category: "bug",+ description: "<script>alert(1)</script>\nsecond line",+ reporter: { id: "u1", email: "[email protected]" },+ server: { publicUrl: "https://k.test", receivedAt: "now" },+ diagnostics: {+ recentErrors: [{ message: "<img src=x>", timestamp: "t" }],+ },+ });+ expect(subject).toBe(+ "[Karakeep problem report] Something isn't working: <script>alert(1)</script>",+ );+ expect(html).not.toContain("<script>");+ expect(html).not.toContain("<img src=x>");+ expect(text).toContain("second line");+ });+});diff --git a/packages/trpc/routers/problemReports.ts b/packages/trpc/routers/problemReports.tsnew file mode 100644index 00000000..4722c3bf--- /dev/null+++ b/packages/trpc/routers/problemReports.ts@@ -0,0 +1,68 @@+import { randomUUID } from "crypto";+import { TRPCError } from "@trpc/server";+import { z } from "zod";++import serverConfig from "@karakeep/shared/config";+import logger from "@karakeep/shared/logger";+import { zSubmitProblemReportSchema } from "@karakeep/shared/types/problemReports";++import { sendProblemReportEmail } from "../email";+import { createRateLimitMiddleware, router, sessionProcedure } from "../index";++export const problemReportsAppRouter = router({+ submit: sessionProcedure+ .use(+ createRateLimitMiddleware({+ name: "problemReports.submit",+ windowMs: 60 * 60 * 1000,+ maxRequests: 5,+ }),+ )+ .input(zSubmitProblemReportSchema)+ .output(z.object({ reportId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ if (!serverConfig.problemReports.enabled) {+ throw new TRPCError({+ code: "PRECONDITION_FAILED",+ message: "Problem reports are not enabled on this server",+ });+ }++ const reportId = randomUUID();+ // Logged so the report can be correlated with server logs around the+ // same time.+ logger.info(+ `[problemReports] Received report ${reportId} (category: ${input.category}) from user ${ctx.user.id}`,+ );++ try {+ await sendProblemReportEmail({+ reportId,+ category: input.category,+ description: input.description,+ reporter: {+ id: ctx.user.id,+ name: ctx.user.name,+ email: ctx.user.email,+ role: ctx.user.role,+ },+ server: {+ version: serverConfig.serverVersion,+ publicUrl: serverConfig.publicUrl,+ receivedAt: new Date().toISOString(),+ },+ diagnostics: input.diagnostics,+ });+ } catch (e) {+ logger.error(+ `[problemReports] Failed to send report ${reportId}: ${e instanceof Error ? e.message : String(e)}`,+ );+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to send the problem report. Please try again later.",+ });+ }++ return { reportId };+ }),+});