:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): mobile close the dismiss sheet before the write lands (#98248)
Tom Owers7d181bdbc09e
diff --git a/products/desktop/apps/mobile/src/features/inbox/components/DismissReportSheet.test.tsx b/products/desktop/apps/mobile/src/features/inbox/components/DismissReportSheet.test.tsxnew file mode 100644index 000000000000..25b844779528--- /dev/null+++ b/products/desktop/apps/mobile/src/features/inbox/components/DismissReportSheet.test.tsx@@ -0,0 +1,155 @@+import { DISMISSAL_REASON_OPTIONS } from "@posthog/shared";+import { createElement } from "react";+import { act, create, type ReactTestInstance } from "react-test-renderer";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useDismissDraftStore } from "../stores/dismissDraftStore";++const mocks = vi.hoisted(() => ({+ updateState: vi.fn(),+}));++vi.mock("../hooks/useInboxReports", () => ({+ useDismissReport: () => ({+ mutateAsync: (input: unknown) => mocks.updateState(input),+ }),+}));++vi.mock("@/lib/theme", () => ({+ useThemeColors: () => ({ gray: { 9: "#888" }, accent: { 9: "#09f" } }),+}));++vi.mock("expo-haptics", () => ({+ notificationAsync: vi.fn(),+ NotificationFeedbackType: { Success: "success", Error: "error" },+}));++vi.mock("react-native", async () => {+ const actual = await import("react-native-web");+ const { createElement } = await import("react");+ return {+ ...actual,+ Alert: { alert: vi.fn() },+ Platform: {+ OS: "ios",+ select: <T,>(options: { ios?: T; android?: T; default?: T }) =>+ options.ios ?? options.default,+ },+ TextInput: (props: Record<string, unknown>) =>+ createElement("TextInput", props),+ // react-native-web's Modal is portal-based and renders nothing under the+ // node test environment; a pass-through wrapper lets us inspect the tree.+ Modal: (props: { visible?: boolean; children?: unknown }) =>+ props.visible === false+ ? null+ : createElement("Modal", null, props.children as never),+ };+});++import { DismissReportSheet } from "./DismissReportSheet";++const REPORT_ID = "report-1";+const FIRST_REASON = DISMISSAL_REASON_OPTIONS[0];++function renderSheet(visible = true) {+ const onClose = vi.fn();+ const onDismissed = vi.fn();+ let renderer: ReturnType<typeof create> | null = null;+ act(() => {+ renderer = create(+ createElement(DismissReportSheet, {+ visible,+ reportId: REPORT_ID,+ reportTitle: "Report one",+ onClose,+ onDismissed,+ }),+ );+ });+ if (!renderer) throw new Error("Renderer not created");+ return {+ renderer: renderer as ReturnType<typeof create>,+ onClose,+ onDismissed,+ };+}++function pressByLabel(+ renderer: ReturnType<typeof create>,+ label: string,+): void {+ const node: ReactTestInstance = renderer.root.find(+ (n) => n.props?.accessibilityLabel === label,+ );+ act(() => {+ node.props.onPress();+ });+}++function noteInput(renderer: ReturnType<typeof create>): ReactTestInstance {+ return renderer.root.find(+ (n) =>+ typeof n.props?.onChangeText === "function" &&+ n.props?.multiline === true,+ );+}++describe("DismissReportSheet", () => {+ beforeEach(() => {+ mocks.updateState.mockReset();+ useDismissDraftStore.setState({ drafts: {} });+ });++ it("closes and notifies before the request settles", () => {+ mocks.updateState.mockReturnValue(new Promise(() => {}));+ const { renderer, onClose, onDismissed } = renderSheet(true);++ pressByLabel(renderer, `Dismissal reason: ${FIRST_REASON.label}`);+ pressByLabel(renderer, "Confirm dismissal");++ expect(onClose).toHaveBeenCalledTimes(1);+ expect(onDismissed).toHaveBeenCalledWith({+ reason: FIRST_REASON.value,+ note: null,+ });+ expect(mocks.updateState).toHaveBeenCalledTimes(1);+ });++ it("mounts open, prefilled, when a prior failure left a retry draft", () => {+ useDismissDraftStore.setState({+ drafts: {+ [REPORT_ID]: {+ reason: FIRST_REASON.value,+ note: "left over",+ reopen: true,+ errorMessage: "was offline",+ },+ },+ });+ const { renderer } = renderSheet(false);++ expect(noteInput(renderer).props.value).toBe("left over");+ });++ it("reopens with the typed reason and note when the write fails", async () => {+ mocks.updateState.mockRejectedValue(new Error("network down"));+ const { renderer } = renderSheet(true);++ pressByLabel(renderer, `Dismissal reason: ${FIRST_REASON.label}`);+ act(() => {+ noteInput(renderer).props.onChangeText("please retry");+ });++ await act(async () => {+ pressByLabel(renderer, "Confirm dismissal");+ await Promise.resolve();+ });++ const stored = useDismissDraftStore.getState().drafts[REPORT_ID];+ expect(stored).toMatchObject({+ reason: FIRST_REASON.value,+ note: "please retry",+ reopen: true,+ });+ expect(noteInput(renderer).props.value).toBe("please retry");+ });+});diff --git a/products/desktop/apps/mobile/src/features/inbox/components/DismissReportSheet.tsx b/products/desktop/apps/mobile/src/features/inbox/components/DismissReportSheet.tsxindex 56253e4a2ccf..365c6d63e695 100644--- a/products/desktop/apps/mobile/src/features/inbox/components/DismissReportSheet.tsx+++ b/products/desktop/apps/mobile/src/features/inbox/components/DismissReportSheet.tsx@@ -5,9 +5,9 @@ import {} from "@posthog/shared";import * as Haptics from "expo-haptics";import { Check } from "phosphor-react-native";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import {- ActivityIndicator,+ Alert,KeyboardAvoidingView,Modal,Platform,@@ -19,6 +19,7 @@ import {import { useScreenInsets } from "@/hooks/useScreenInsets";import { useThemeColors } from "@/lib/theme";import { useDismissReport } from "../hooks/useInboxReports";+import { useDismissDraftStore } from "../stores/dismissDraftStore";export interface DismissReportResult {reason: DismissalReasonOptionValue;@@ -31,11 +32,7 @@ interface DismissReportSheetProps {reportId: string;reportTitle: string;onClose: () => void;- /**- * Fires after the API confirms the dismissal. The result is passed back so- * callers can route the reason/note through their own analytics — keeping- * this sheet stateless about the surface it was launched from.- */+ /** Fires the moment the user confirms, before the API write settles. */onDismissed: (result: DismissReportResult) => void;}@@ -48,48 +45,80 @@ export function DismissReportSheet({}: DismissReportSheetProps) {const { insets, bottom, sheetContentTop } = useScreenInsets();const themeColors = useThemeColors();+ const draft = useDismissDraftStore((s) => s.drafts[reportId]);+ const setDraft = useDismissDraftStore((s) => s.setDraft);const [reason, setReason] = useState<DismissalReasonOptionValue | null>(null);const [note, setNote] = useState("");- const [error, setError] = useState<string | null>(null);const dismiss = useDismissReport(reportId);+ const sheetVisible = visible || draft?.reopen === true;+ const openTransitionRef = useRef(false);+useEffect(() => {- if (visible) {+ if (!sheetVisible) {+ openTransitionRef.current = false;+ return;+ }+ if (openTransitionRef.current) return;+ openTransitionRef.current = true;+ if (draft?.reopen) {+ setReason(draft.reason);+ setNote(draft.note);+ } else {setReason(null);setNote("");- setError(null);}- }, [visible]);+ }, [sheetVisible, draft]);++ const displayedError = draft?.reopen ? draft.errorMessage : undefined;++ const handleClose = () => {+ setDraft(reportId, undefined);+ onClose();+ };- const handleConfirm = async () => {- if (!reason || dismiss.isPending) return;- setError(null);+ const handleConfirm = () => {+ if (!reason) return;const trimmedNote = note.trim();- try {- await dismiss.mutateAsync({- reason,- note: trimmedNote || undefined,- });- Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);- onDismissed({ reason, note: trimmedNote || null });- } catch (err) {- Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);- setError(- err instanceof Error- ? err.message- : "Could not dismiss this report. Please try again.",- );- }+ const noteOrNull = trimmedNote || null;+ setDraft(reportId, { reason, note: trimmedNote, reopen: false });+ onClose();+ onDismissed({ reason, note: noteOrNull });+ // Use an independently managed promise rather than mutate()'s per-call+ // callbacks: onDismissed above can trigger navigation that unmounts this+ // sheet before the write settles, and per-call mutate callbacks are only+ // fired while the initiating component is still mounted. A plain promise+ // chain has no such dependency, so the draft is always reconciled.+ dismiss.mutateAsync({ reason, note: trimmedNote || undefined }).then(+ () => {+ setDraft(reportId, undefined);+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);+ },+ (err) => {+ const message =+ err instanceof Error+ ? err.message+ : "Could not dismiss this report. Please try again.";+ setDraft(reportId, {+ reason,+ note: trimmedNote,+ reopen: true,+ errorMessage: message,+ });+ Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);+ Alert.alert("Couldn't dismiss report", message);+ },+ );};- const canSubmit = !!reason && !dismiss.isPending;+ const canSubmit = !!reason;return (<Modal- visible={visible}+ visible={sheetVisible}animationType="slide"presentationStyle="pageSheet"- onRequestClose={onClose}+ onRequestClose={handleClose}><KeyboardAvoidingViewclassName="flex-1 bg-background"@@ -100,16 +129,11 @@ export function DismissReportSheet({className="flex-1 bg-background"style={{ paddingTop: sheetContentTop() }}>- {/* Header */}<View className="flex-row items-center justify-between border-gray-6 border-b px-4 pb-3"><Text className="font-semibold text-[18px] text-gray-12">Dismiss report</Text>- <Pressable- onPress={onClose}- hitSlop={12}- disabled={dismiss.isPending}- >+ <Pressable onPress={handleClose} hitSlop={12}><Text className="text-[14px] text-accent-9">Cancel</Text></Pressable></View>@@ -136,6 +160,9 @@ export function DismissReportSheet({<Pressablekey={option.value}onPress={() => setReason(option.value)}+ accessibilityLabel={`Dismissal reason: ${option.label}`}+ accessibilityRole="radio"+ accessibilityState={{ checked: selected }}hitSlop={4}className={`flex-row items-center justify-between px-3 py-3.5 active:bg-gray-3 ${idx > 0 ? "border-gray-5 border-t" : ""@@ -163,19 +190,17 @@ export function DismissReportSheet({multilinenumberOfLines={3}maxLength={4000}- editable={!dismiss.isPending}className="min-h-[88px] rounded-xl bg-gray-2 px-3 py-3 text-[14px] text-gray-12"style={{ textAlignVertical: "top" }}/>- {error && (+ {displayedError && (<Text className="mt-3 text-[13px] text-status-error">- {error}+ {displayedError}</Text>)}</ScrollView>- {/* Sticky submit */}<ViewclassName="border-gray-6 border-t bg-background px-4 pt-3"style={{ paddingBottom: bottom("compact") }}@@ -183,21 +208,18 @@ export function DismissReportSheet({<PressableonPress={handleConfirm}disabled={!canSubmit}+ accessibilityLabel="Confirm dismissal"className={`flex-row items-center justify-center rounded-full px-6 py-3.5 ${canSubmit ? "bg-accent-9 active:opacity-80" : "bg-gray-4"}`}>- {dismiss.isPending ? (- <ActivityIndicator color={themeColors.gray[12]} />- ) : (- <Text- className={`font-semibold text-[15px] ${- canSubmit ? "text-gray-12" : "text-gray-9"- }`}- >- Dismiss & teach the agent- </Text>- )}+ <Text+ className={`font-semibold text-[15px] ${+ canSubmit ? "text-gray-12" : "text-gray-9"+ }`}+ >+ Dismiss & teach the agent+ </Text></Pressable></View></View>diff --git a/products/desktop/apps/mobile/src/features/inbox/stores/dismissDraftStore.ts b/products/desktop/apps/mobile/src/features/inbox/stores/dismissDraftStore.tsnew file mode 100644index 000000000000..db68514fece9--- /dev/null+++ b/products/desktop/apps/mobile/src/features/inbox/stores/dismissDraftStore.ts@@ -0,0 +1,28 @@+import type { DismissalReasonOptionValue } from "@posthog/shared";+import { create } from "zustand";++export interface DismissDraft {+ reason: DismissalReasonOptionValue;+ note: string;+ reopen: boolean;+ errorMessage?: string;+}++interface DismissDraftState {+ drafts: Record<string, DismissDraft | undefined>;+ setDraft: (reportId: string, draft: DismissDraft | undefined) => void;+}++export const useDismissDraftStore = create<DismissDraftState>((set) => ({+ drafts: {},+ setDraft: (reportId, draft) =>+ set((state) => {+ const next = { ...state.drafts };+ if (draft === undefined) {+ delete next[reportId];+ } else {+ next[reportId] = draft;+ }+ return { drafts: next };+ }),+}));