Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6010: fix(desktop): structure route error feedback context (#6737)
Ryan Yu7e920d60e7a2
diff --git a/apps/desktop/src/renderer/src/components/route-error-page.test.tsx b/apps/desktop/src/renderer/src/components/route-error-page.test.tsxindex 4edc8c50c3..7b0f8aa0ca 100644--- a/apps/desktop/src/renderer/src/components/route-error-page.test.tsx+++ b/apps/desktop/src/renderer/src/components/route-error-page.test.tsx@@ -29,7 +29,10 @@ vi.mock("@/stores/tab-store", () => {return { useTabStore };});-import { DesktopRouteErrorPage, formatRouteErrorReport } from "./route-error-page";+import {+ createRouteErrorFeedbackContext,+ DesktopRouteErrorPage,+} from "./route-error-page";function Boom(): null {throw new Error("route render exploded");@@ -96,7 +99,7 @@ describe("DesktopRouteErrorPage", () => {expect(closeActiveTab).toHaveBeenCalledTimes(1);});- it("opens the existing feedback modal with a structured markdown report only after click", async () => {+ it("opens the feedback modal with structured error context only after click", async () => {const router = createMemoryRouter([{ path: "/acme/issues", element: <Boom />, errorElement: <DesktopRouteErrorPage /> }],{ initialEntries: ["/acme/issues"] },@@ -110,23 +113,39 @@ describe("DesktopRouteErrorPage", () => {expect(openModal).toHaveBeenCalledWith("feedback",expect.objectContaining({- initialMessage: expect.stringContaining("kind: desktop_route_error"),kind: "bug",+ context: {+ kind: "desktop_route_error",+ trigger: "route-errorElement",+ error: {+ name: "Error",+ message: "route render exploded",+ stack: expect.stringContaining("route render exploded"),+ },+ },}),);+ expect(openModal.mock.calls[0]?.[1]).not.toHaveProperty("initialMessage");});- it("documents the structured context follow-up debt in the report template", () => {- const report = formatRouteErrorReport({- error: new Error("bad route"),- url: "app://desktop/acme/issues",- appInfo: { version: "1.2.3", os: "macos" },+ it("keeps system diagnostics out of the member-editable message", () => {+ const error = new Error("bad route");+ error.stack = "Error: bad route\n at Route";++ const context = createRouteErrorFeedbackContext({+ error,trigger: "route-errorElement",});- expect(report).toContain("kind: desktop_route_error");- expect(report).toContain("trigger: route-errorElement");- expect(report).toContain("TODO: promote error context to structured feedback fields");+ expect(context).toEqual({+ kind: "desktop_route_error",+ trigger: "route-errorElement",+ error: {+ name: "Error",+ message: "bad route",+ stack: "Error: bad route\n at Route",+ },+ });});// --- 404 as a first-class product state (MUL-4899) -----------------------diff --git a/apps/desktop/src/renderer/src/components/route-error-page.tsx b/apps/desktop/src/renderer/src/components/route-error-page.tsxindex 94b0cd586b..ec6c82c0e0 100644--- a/apps/desktop/src/renderer/src/components/route-error-page.tsx+++ b/apps/desktop/src/renderer/src/components/route-error-page.tsx@@ -2,44 +2,23 @@ import { useMemo } from "react";import { isRouteErrorResponse, useLocation, useRouteError } from "react-router-dom";import { AlertTriangle, Compass, RotateCw, Send, X } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";+import type { DesktopRouteErrorFeedbackContext } from "@multica/core/feedback";import { useModalStore } from "@multica/core/modals";import { useTabStore } from "@/stores/tab-store";-type DesktopAppInfo = {- version?: string;- os?: string;-};--export function formatRouteErrorReport({+export function createRouteErrorFeedbackContext({error,- url,- appInfo,trigger,}: {error: unknown;- url: string;- appInfo?: DesktopAppInfo;trigger: string;-}) {+}): DesktopRouteErrorFeedbackContext {const normalized = normalizeError(error);- return [- "kind: desktop_route_error",- `trigger: ${trigger}`,- `url: ${url}`,- `app_version: ${appInfo?.version ?? "unknown"}`,- `runtime_os: ${appInfo?.os ?? "unknown"}`,- "",- "context:",- `- name: ${normalized.name}`,- `- message: ${normalized.message}`,- "",- "stack:",- "```",- normalized.stack ?? "<no stack>",- "```",- "",- "TODO: promote error context to structured feedback fields once the feedback API supports them.",- ].join("\n");+ return {+ kind: "desktop_route_error",+ trigger,+ error: normalized,+ };}/**@@ -128,20 +107,14 @@ function DesktopNotFoundPage() {}function DesktopUnexpectedErrorPage({ error }: { error: unknown }) {- const location = useLocation();const recoveryRoute = useRecoveryRoute();- const report = useMemo(+ const feedbackContext = useMemo(() =>- formatRouteErrorReport({+ createRouteErrorFeedbackContext({error,- url:- typeof window !== "undefined"- ? `${window.location.origin}${location.pathname}${location.search}${location.hash}`- : location.pathname,- appInfo: typeof window !== "undefined" ? window.desktopAPI?.appInfo : undefined,trigger: "route-errorElement",}),- [error, location.hash, location.pathname, location.search],+ [error],);const message = normalizeError(error).message;@@ -197,8 +170,8 @@ function DesktopUnexpectedErrorPage({ error }: { error: unknown }) {type="button"onClick={() =>useModalStore.getState().open("feedback", {- initialMessage: report,kind: "bug",+ context: feedbackContext,})}>diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex c724768ac3..33c486be60 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -915,6 +915,15 @@ describe("ApiClient", () => {url: "app://desktop/acme/issues",workspace_id: "ws-1",kind: "bug",+ context: {+ kind: "desktop_route_error",+ trigger: "route-errorElement",+ error: {+ name: "TypeError",+ message: "Cannot read properties of undefined",+ stack: "TypeError: Cannot read properties of undefined",+ },+ },});expect(response).toEqual({@@ -930,6 +939,15 @@ describe("ApiClient", () => {url: "app://desktop/acme/issues",workspace_id: "ws-1",kind: "bug",+ context: {+ kind: "desktop_route_error",+ trigger: "route-errorElement",+ error: {+ name: "TypeError",+ message: "Cannot read properties of undefined",+ stack: "TypeError: Cannot read properties of undefined",+ },+ },}),}),);diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 2604d43a05..d7460de6bb 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -183,7 +183,11 @@ import type {CreateBillingPortalSessionResponse,} from "../types";import type { OnboardingCompletionPath } from "../onboarding/types";-import type { CreateFeedbackResponse, FeedbackKind } from "../feedback/types";+import type {+ CreateFeedbackResponse,+ FeedbackContext,+ FeedbackKind,+} from "../feedback/types";import type {CloudRuntimeNode,CreateCloudRuntimeNodeRequest,@@ -928,6 +932,7 @@ export class ApiClient {url?: string;workspace_id?: string;kind?: FeedbackKind;+ context?: FeedbackContext;}): Promise<CreateFeedbackResponse> {const raw = await this.fetch<unknown>("/api/feedback", {method: "POST",diff --git a/packages/core/feedback/index.ts b/packages/core/feedback/index.tsindex 2596ba47ac..08b70e6f78 100644--- a/packages/core/feedback/index.ts+++ b/packages/core/feedback/index.ts@@ -1,4 +1,10 @@export * from "./mutations";-export { FEEDBACK_KINDS } from "./types";-export type { CreateFeedbackResponse, FeedbackKind } from "./types";+export { FEEDBACK_KINDS, isFeedbackContext } from "./types";+export type {+ CreateFeedbackResponse,+ DesktopRouteErrorFeedbackContext,+ FeedbackContext,+ FeedbackErrorContext,+ FeedbackKind,+} from "./types";export { useFeedbackDraftStore } from "./draft-store";diff --git a/packages/core/feedback/mutations.ts b/packages/core/feedback/mutations.tsindex 93e7ad76f6..b7e3d542a8 100644--- a/packages/core/feedback/mutations.ts+++ b/packages/core/feedback/mutations.ts@@ -1,12 +1,13 @@import { useMutation } from "@tanstack/react-query";import { api } from "../api";-import type { FeedbackKind } from "./types";+import type { FeedbackContext, FeedbackKind } from "./types";export interface CreateFeedbackInput {message: string;url?: string;workspace_id?: string;kind?: FeedbackKind;+ context?: FeedbackContext;}export function useCreateFeedback() {diff --git a/packages/core/feedback/types.test.ts b/packages/core/feedback/types.test.tsnew file mode 100644index 0000000000..be3e5cd884--- /dev/null+++ b/packages/core/feedback/types.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { isFeedbackContext } from "./types";++describe("isFeedbackContext", () => {+ it("accepts desktop route error context", () => {+ expect(+ isFeedbackContext({+ kind: "desktop_route_error",+ trigger: "route-errorElement",+ error: {+ name: "TypeError",+ message: "Cannot read properties of undefined",+ stack: "TypeError: Cannot read properties of undefined",+ },+ }),+ ).toBe(true);+ });++ it("rejects malformed context", () => {+ expect(+ isFeedbackContext({+ kind: "desktop_route_error",+ trigger: "route-errorElement",+ error: { name: "TypeError" },+ }),+ ).toBe(false);+ expect(isFeedbackContext({ kind: "unknown" })).toBe(false);+ });+});diff --git a/packages/core/feedback/types.ts b/packages/core/feedback/types.tsindex e336ad6576..fc1537f170 100644--- a/packages/core/feedback/types.ts+++ b/packages/core/feedback/types.ts@@ -2,6 +2,39 @@ export const FEEDBACK_KINDS = ["bug", "feature", "general", "praise"] as const;export type FeedbackKind = (typeof FEEDBACK_KINDS)[number];+export interface FeedbackErrorContext {+ name: string;+ message: string;+ stack?: string;+}++export interface DesktopRouteErrorFeedbackContext {+ kind: "desktop_route_error";+ trigger: string;+ error: FeedbackErrorContext;+}++export type FeedbackContext = DesktopRouteErrorFeedbackContext;++export function isFeedbackContext(value: unknown): value is FeedbackContext {+ if (!value || typeof value !== "object") return false;+ const context = value as Record<string, unknown>;+ if (+ context.kind !== "desktop_route_error" ||+ typeof context.trigger !== "string" ||+ !context.error ||+ typeof context.error !== "object"+ ) {+ return false;+ }+ const error = context.error as Record<string, unknown>;+ return (+ typeof error.name === "string" &&+ typeof error.message === "string" &&+ (error.stack === undefined || typeof error.stack === "string")+ );+}+export interface CreateFeedbackResponse {id: string;created_at: string;diff --git a/packages/views/modals/feedback.test.tsx b/packages/views/modals/feedback.test.tsxindex 2debc6d1d8..258277e8e1 100644--- a/packages/views/modals/feedback.test.tsx+++ b/packages/views/modals/feedback.test.tsx@@ -59,6 +59,11 @@ vi.mock("@multica/core/api", () => ({ api: {} }));vi.mock("sonner", () => ({ toast: { info: vi.fn(), error: vi.fn(), success: vi.fn() } }));vi.mock("@multica/core/feedback", () => ({FEEDBACK_KINDS: ["bug", "feature", "general", "praise"] as const,+ isFeedbackContext: (value: unknown) =>+ typeof value === "object" &&+ value !== null &&+ "kind" in value &&+ value.kind === "desktop_route_error",useCreateFeedback: () => ({ isPending: false, mutateAsync: feedbackMocks.mutateAsync }),useFeedbackDraftStore: (selector: any) =>selector({ draft: { message: storedDraftMessage }, setDraft: vi.fn(), clearDraft: vi.fn() }),@@ -165,6 +170,40 @@ describe("FeedbackModal", () => {});});+ it("forwards structured diagnostic context without putting it in the message", async () => {+ storedDraftMessage = "";+ const context = {+ kind: "desktop_route_error" as const,+ trigger: "route-errorElement",+ error: {+ name: "Error",+ message: "route render exploded",+ stack: "Error: route render exploded",+ },+ };+ render(+ <FeedbackModal+ onClose={vi.fn()}+ data={{ kind: "bug", context }}+ />,+ );++ const editor = screen.getByLabelText("feedback editor");+ expect(editor).toHaveValue("");+ fireEvent.change(editor, { target: { value: "I clicked an issue link." } });+ fireEvent.keyDown(editor, { key: "Enter", metaKey: true });++ await waitFor(() => {+ expect(feedbackMocks.mutateAsync).toHaveBeenCalledWith(+ expect.objectContaining({+ message: "I clicked an issue link.",+ kind: "bug",+ context,+ }),+ );+ });+ });+// MUL-4808 — Feedback refused to submit mid-upload inside the handler, but// the Send button stayed enabled, so the only signal was a toast fired after// a click that looked like it should have worked.diff --git a/packages/views/modals/feedback.tsx b/packages/views/modals/feedback.tsxindex b6fdd16064..04a010b802 100644--- a/packages/views/modals/feedback.tsx+++ b/packages/views/modals/feedback.tsx@@ -22,6 +22,7 @@ import {useCreateFeedback,useFeedbackDraftStore,FEEDBACK_KINDS,+ isFeedbackContext,type FeedbackKind,} from "@multica/core/feedback";import { useCurrentWorkspace } from "@multica/core/paths";@@ -69,6 +70,7 @@ export function FeedbackModal({const kind = typeof data?.kind === "string" && FEEDBACK_KIND_SET.has(data.kind as FeedbackKind)? (data.kind as FeedbackKind): undefined;+ const context = isFeedbackContext(data?.context) ? data.context : undefined;const seededMessage = composeFeedbackInitialMessage(draft.message, incomingInitialMessage);const [message, setMessage] = useState(seededMessage);const { isDragOver, dropZoneProps } = useFileDropZone({@@ -112,6 +114,7 @@ export function FeedbackModal({url: typeof window !== "undefined" ? window.location.href : undefined,workspace_id: workspace?.id,kind,+ context,});clearDraft();toast.success(t(($) => $.feedback.toast_sent));diff --git a/server/internal/handler/feedback.go b/server/internal/handler/feedback.goindex 04360f6215..424daadfb8 100644--- a/server/internal/handler/feedback.go+++ b/server/internal/handler/feedback.go@@ -22,15 +22,28 @@ import (var feedbackImageRegex = regexp.MustCompile(`!\[[^\]]*\]\([^)]+\)`)const (- feedbackMaxMessageLen = 10000- feedbackHourlyRateLimit = 10+ feedbackMaxMessageLen = 10000+ feedbackHourlyRateLimit = 10+ desktopRouteErrorFeedbackContextKind = "desktop_route_error"// 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.+ // 10k chars separately; the extra budget covers JSON overhead, optional+ // request fields, and diagnostic context without letting an authenticated+ // client POST megabytes of junk into the metadata JSONB column.feedbackBodyLimit = 64 * 1024)+type FeedbackErrorContext struct {+ Name string `json:"name"`+ Message string `json:"message"`+ Stack string `json:"stack,omitempty"`+}++type FeedbackContext struct {+ Kind string `json:"kind"`+ Trigger string `json:"trigger"`+ Error FeedbackErrorContext `json:"error"`+}+type CreateFeedbackRequest struct {Message string `json:"message"`URL string `json:"url"`@@ -40,8 +53,9 @@ type CreateFeedbackRequest struct {// "general", "praise"); anything outside collapses to "other". Empty /// missing falls back to "general" so legacy clients that don't send the// field don't blackhole the metric.- Kind string `json:"kind"`- WorkspaceID *string `json:"workspace_id,omitempty"`+ Kind string `json:"kind"`+ WorkspaceID *string `json:"workspace_id,omitempty"`+ Context *FeedbackContext `json:"context,omitempty"`}type FeedbackResponse struct {@@ -71,6 +85,10 @@ func (h *Handler) CreateFeedback(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "message too long")return}+ if !validFeedbackContext(req.Context) {+ writeError(w, http.StatusBadRequest, "invalid feedback context")+ return+ }// Per-user rate limit: hourly cap on feedback submissions. DB-backed so it// survives process restarts and works across multiple instances without a@@ -94,11 +112,13 @@ func (h *Handler) CreateFeedback(w http.ResponseWriter, r *http.Request) {"os": clientOS,"user_agent": r.UserAgent(),}+ if req.Context != nil {+ metadata["context"] = req.Context+ }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.+ // The map contains only known JSON-compatible values, but fall through+ // with an empty object rather than 500ing on non-critical metadata.metaBytes = []byte("{}")}@@ -145,3 +165,13 @@ func (h *Handler) CreateFeedback(w http.ResponseWriter, r *http.Request) {CreatedAt: timestampToString(fb.CreatedAt),})}++func validFeedbackContext(context *FeedbackContext) bool {+ if context == nil {+ return true+ }+ return context.Kind == desktopRouteErrorFeedbackContextKind &&+ strings.TrimSpace(context.Trigger) != "" &&+ strings.TrimSpace(context.Error.Name) != "" &&+ strings.TrimSpace(context.Error.Message) != ""+}diff --git a/server/internal/handler/feedback_test.go b/server/internal/handler/feedback_test.goindex 9b3a2b1a21..e4e8da0255 100644--- a/server/internal/handler/feedback_test.go+++ b/server/internal/handler/feedback_test.go@@ -30,6 +30,164 @@ func TestCreateFeedbackHappyPath(t *testing.T) {}}+func TestCreateFeedbackStoresStructuredContext(t *testing.T) {+ clearFeedbackForTestUser(t)++ req := newRequest("POST", "/api/feedback", CreateFeedbackRequest{+ Message: "Desktop route crashed",+ Context: &FeedbackContext{+ Kind: "desktop_route_error",+ Trigger: "route-errorElement",+ Error: FeedbackErrorContext{+ Name: "TypeError",+ Message: "Cannot read properties of undefined",+ Stack: "TypeError: Cannot read properties of undefined",+ },+ },+ })+ 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)+ }++ var metadata []byte+ if err := testPool.QueryRow(+ context.Background(),+ `SELECT metadata FROM feedback WHERE id = $1`,+ parseUUID(resp.ID),+ ).Scan(&metadata); err != nil {+ t.Fatalf("load feedback metadata: %v", err)+ }+ var stored struct {+ Context *FeedbackContext `json:"context"`+ }+ if err := json.Unmarshal(metadata, &stored); err != nil {+ t.Fatalf("decode feedback metadata: %v", err)+ }+ if stored.Context == nil {+ t.Fatal("expected structured context in feedback metadata")+ }+ if stored.Context.Kind != "desktop_route_error" {+ t.Fatalf("context kind = %q, want desktop_route_error", stored.Context.Kind)+ }+ if stored.Context.Trigger != "route-errorElement" {+ t.Fatalf("context trigger = %q, want route-errorElement", stored.Context.Trigger)+ }+ if stored.Context.Error.Name != "TypeError" {+ t.Fatalf("error name = %q, want TypeError", stored.Context.Error.Name)+ }+ if stored.Context.Error.Message != "Cannot read properties of undefined" {+ t.Fatalf(+ "error message = %q, want Cannot read properties of undefined",+ stored.Context.Error.Message,+ )+ }+ if stored.Context.Error.Stack != "TypeError: Cannot read properties of undefined" {+ t.Fatalf(+ "error stack = %q, want TypeError: Cannot read properties of undefined",+ stored.Context.Error.Stack,+ )+ }+}++func TestCreateFeedbackRejectsMalformedContext(t *testing.T) {+ req := newRequest("POST", "/api/feedback", map[string]any{+ "message": "Desktop route crashed",+ "context": "not-an-object",+ })+ 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 TestCreateFeedbackRejectsUnknownContextKind(t *testing.T) {+ req := newRequest("POST", "/api/feedback", CreateFeedbackRequest{+ Message: "Desktop route crashed",+ Context: &FeedbackContext{+ Kind: "arbitrary_diagnostic",+ Trigger: "route-errorElement",+ Error: FeedbackErrorContext{+ Name: "TypeError",+ Message: "Cannot read properties of undefined",+ },+ },+ })+ 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 TestCreateFeedbackRejectsEmptyContextFields(t *testing.T) {+ tests := []struct {+ name string+ context FeedbackContext+ }{+ {+ name: "empty context",+ context: FeedbackContext{},+ },+ {+ name: "trigger",+ context: FeedbackContext{+ Kind: desktopRouteErrorFeedbackContextKind,+ Error: FeedbackErrorContext{+ Name: "TypeError",+ Message: "Cannot read properties of undefined",+ },+ },+ },+ {+ name: "error name",+ context: FeedbackContext{+ Kind: desktopRouteErrorFeedbackContextKind,+ Trigger: "route-errorElement",+ Error: FeedbackErrorContext{+ Name: " ",+ Message: "Cannot read properties of undefined",+ },+ },+ },+ {+ name: "error message",+ context: FeedbackContext{+ Kind: desktopRouteErrorFeedbackContextKind,+ Trigger: "route-errorElement",+ Error: FeedbackErrorContext{+ Name: "TypeError",+ Message: "\n\t",+ },+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ req := newRequest("POST", "/api/feedback", CreateFeedbackRequest{+ Message: "Desktop route crashed",+ Context: &tt.context,+ })+ 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 TestCreateFeedbackEmptyMessage(t *testing.T) {req := newRequest("POST", "/api/feedback", CreateFeedbackRequest{Message: " "})w := httptest.NewRecorder()