Skip to content

: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.

feat(desktop): add daily report limit control to Self-driving config (#86718)

posthog[bot]2af66ca04000
diff --git a/products/desktop/apps/mobile/src/app/settings/index.tsx b/products/desktop/apps/mobile/src/app/settings/index.tsx
index 9cc91eb2186a..caaf4dcdc791 100644
--- a/products/desktop/apps/mobile/src/app/settings/index.tsx
+++ b/products/desktop/apps/mobile/src/app/settings/index.tsx
@@ -18,6 +18,7 @@ import {
type ThemePreference,
usePreferencesStore,
} from "@/features/preferences/stores/preferencesStore";
+import { DailyReportLimitRow } from "@/features/settings/components/DailyReportLimitRow";
import { DebugInfoSection } from "@/features/settings/components/DebugInfoSection";
import { FloatingSettingsHeader } from "@/features/settings/components/FloatingSettingsHeader";
import { SettingsRow } from "@/features/settings/components/SettingsRow";
@@ -465,6 +466,7 @@ export default function SettingsScreen() {
{/* Inbox */}
<SettingsSection title="Inbox">
+ <DailyReportLimitRow />
<SettingsRow
label="Reviewed reports"
description={`${decidedCount} report${decidedCount === 1 ? "" : "s"} reviewed in tinder mode`}
diff --git a/products/desktop/apps/mobile/src/features/inbox/hooks/useSignalTeamConfig.ts b/products/desktop/apps/mobile/src/features/inbox/hooks/useSignalTeamConfig.ts
new file mode 100644
index 000000000000..3501a431607d
--- /dev/null
+++ b/products/desktop/apps/mobile/src/features/inbox/hooks/useSignalTeamConfig.ts
@@ -0,0 +1,41 @@
+import type { SignalTeamConfig } from "@posthog/shared/domain-types";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useAuthStore } from "@/features/auth";
+import { getPostHogApiClient } from "@/lib/posthogApiClient";
+
+function teamConfigKey(projectId: number | null) {
+ return ["signals", "team-config", projectId] as const;
+}
+
+export function useSignalTeamConfig() {
+ const { projectId, oauthAccessToken } = useAuthStore();
+
+ // The backend lazily creates the singleton, so a read never means "no config".
+ // Let auth/5xx/network failures surface as query errors instead of a false
+ // no-cap state.
+ return useQuery<SignalTeamConfig>({
+ queryKey: teamConfigKey(projectId),
+ queryFn: () => getPostHogApiClient().getSignalTeamConfig(),
+ enabled: !!projectId && !!oauthAccessToken,
+ staleTime: 30_000,
+ });
+}
+
+/** Save (`number`) or clear (`null`) the per-project daily report cap. */
+export function useUpdateMaxReportsPerDay() {
+ const { projectId } = useAuthStore();
+ const queryClient = useQueryClient();
+
+ return useMutation<SignalTeamConfig, Error, number | null>({
+ mutationFn: (limit) =>
+ getPostHogApiClient().updateSignalTeamConfig({
+ max_reports_per_day: limit,
+ }),
+ onSuccess: (fresh) => {
+ queryClient.setQueryData<SignalTeamConfig>(
+ teamConfigKey(projectId),
+ fresh,
+ );
+ },
+ });
+}
diff --git a/products/desktop/apps/mobile/src/features/settings/components/DailyReportLimitRow.tsx b/products/desktop/apps/mobile/src/features/settings/components/DailyReportLimitRow.tsx
new file mode 100644
index 000000000000..ad58653769b6
--- /dev/null
+++ b/products/desktop/apps/mobile/src/features/settings/components/DailyReportLimitRow.tsx
@@ -0,0 +1,205 @@
+import { Text } from "@components/text";
+import {
+ dailyReportLimitFieldValue,
+ describeDailyReportLimit,
+ parseDailyReportLimit,
+} from "@posthog/core/inbox/dailyReportLimit";
+import { CaretRight } from "phosphor-react-native";
+import { useState } from "react";
+import {
+ ActivityIndicator,
+ KeyboardAvoidingView,
+ Platform,
+ Pressable,
+ TextInput,
+ View,
+} from "react-native";
+import { SheetContainer } from "@/components/SheetContainer";
+import {
+ useSignalTeamConfig,
+ useUpdateMaxReportsPerDay,
+} from "@/features/inbox/hooks/useSignalTeamConfig";
+import { useThemeColors } from "@/lib/theme";
+
+export function DailyReportLimitRow() {
+ const themeColors = useThemeColors();
+ const { data: config, isLoading, isError } = useSignalTeamConfig();
+ const updateLimit = useUpdateMaxReportsPerDay();
+ const [sheetOpen, setSheetOpen] = useState(false);
+ const [draft, setDraft] = useState("");
+ const [error, setError] = useState<string | null>(null);
+
+ const status = describeDailyReportLimit(config);
+ const savedValue = dailyReportLimitFieldValue(config);
+ // A failed background refetch keeps the cached config while flipping isError,
+ // so only treat the case with no cached config as a hard error. Otherwise a
+ // transient failure would hide a known cap and block editing a value the user
+ // can still read from cache.
+ const showLoadError = isError && config === undefined;
+ const rightLabel = showLoadError
+ ? "—"
+ : status.limit === null
+ ? "No limit"
+ : String(status.limit);
+
+ // Reset the field from the saved value when the sheet opens (an event, not a
+ // prop-sync effect).
+ const openSheet = () => {
+ setDraft(savedValue);
+ setError(null);
+ setSheetOpen(true);
+ };
+
+ const save = async (limit: number | null) => {
+ setError(null);
+ try {
+ await updateLimit.mutateAsync(limit);
+ setSheetOpen(false);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : "Failed to save the limit.");
+ }
+ };
+
+ const handleSave = () => {
+ const parsed = parseDailyReportLimit(draft);
+ if (!parsed.ok) {
+ setError(parsed.error);
+ return;
+ }
+ void save(parsed.value);
+ };
+
+ return (
+ <>
+ <Pressable
+ onPress={openSheet}
+ disabled={isLoading || showLoadError}
+ className={`active:bg-gray-2 ${isLoading || showLoadError ? "opacity-50" : ""}`}
+ >
+ <View className="flex-row items-center gap-3 border-gray-5 border-b px-4 py-3">
+ <View className="min-w-0 flex-1">
+ <Text className="font-medium text-[15px] text-gray-12">
+ Daily report limit
+ </Text>
+ <Text
+ className={`mt-0.5 text-[12px] leading-snug ${showLoadError ? "text-status-error" : "text-gray-10"}`}
+ >
+ {showLoadError
+ ? "Couldn't load the limit. Try again later."
+ : status.usageText}
+ </Text>
+ {!showLoadError && status.reachedText ? (
+ <Text className="mt-0.5 text-[12px] text-status-warning leading-snug">
+ {status.reachedText}
+ </Text>
+ ) : null}
+ </View>
+ <View className="shrink-0 flex-row items-center gap-2">
+ <Text className="text-[14px] text-gray-11">{rightLabel}</Text>
+ <CaretRight size={14} color={themeColors.gray[10]} />
+ </View>
+ </View>
+ </Pressable>
+
+ <DailyReportLimitSheet
+ open={sheetOpen}
+ draft={draft}
+ error={error}
+ isSaving={updateLimit.isPending}
+ hasSavedValue={savedValue !== ""}
+ onChangeDraft={(text) => {
+ setDraft(text);
+ setError(null);
+ }}
+ onClose={() => setSheetOpen(false)}
+ onSave={handleSave}
+ onClear={() => void save(null)}
+ />
+ </>
+ );
+}
+
+interface DailyReportLimitSheetProps {
+ open: boolean;
+ draft: string;
+ error: string | null;
+ isSaving: boolean;
+ hasSavedValue: boolean;
+ onChangeDraft: (text: string) => void;
+ onClose: () => void;
+ onSave: () => void;
+ onClear: () => void;
+}
+
+function DailyReportLimitSheet({
+ open,
+ draft,
+ error,
+ isSaving,
+ hasSavedValue,
+ onChangeDraft,
+ onClose,
+ onSave,
+ onClear,
+}: DailyReportLimitSheetProps) {
+ const themeColors = useThemeColors();
+
+ return (
+ <SheetContainer open={open} onClose={onClose}>
+ <KeyboardAvoidingView
+ behavior={Platform.OS === "ios" ? "padding" : undefined}
+ >
+ <View className="gap-3 px-4 pt-2 pb-2">
+ <Text className="font-semibold text-[16px] text-gray-12">
+ Daily report limit
+ </Text>
+ <Text className="text-[13px] text-gray-10 leading-snug">
+ Cap how many new reports reach the inbox each day. Leave the field
+ empty for no limit.
+ </Text>
+
+ <TextInput
+ value={draft}
+ onChangeText={onChangeDraft}
+ keyboardType="number-pad"
+ placeholder="No limit"
+ placeholderTextColor={themeColors.gray[9]}
+ editable={!isSaving}
+ className="rounded-lg border border-gray-6 bg-gray-2 px-3 py-2.5 text-[15px] text-gray-12"
+ />
+
+ {error ? (
+ <Text className="text-[12.5px] text-status-error">{error}</Text>
+ ) : null}
+
+ <View className="flex-row gap-2">
+ <Pressable
+ onPress={onSave}
+ disabled={isSaving}
+ className={`flex-1 flex-row items-center justify-center rounded-lg bg-accent-9 py-3 ${isSaving ? "opacity-60" : "active:opacity-80"}`}
+ >
+ {isSaving ? (
+ <ActivityIndicator size="small" color={themeColors.gray[1]} />
+ ) : (
+ <Text className="font-semibold text-[15px] text-gray-1">
+ Save
+ </Text>
+ )}
+ </Pressable>
+ {hasSavedValue ? (
+ <Pressable
+ onPress={onClear}
+ disabled={isSaving}
+ className={`flex-row items-center justify-center rounded-lg border border-gray-6 px-4 py-3 ${isSaving ? "opacity-60" : "active:bg-gray-2"}`}
+ >
+ <Text className="font-semibold text-[15px] text-gray-12">
+ Clear
+ </Text>
+ </Pressable>
+ ) : null}
+ </View>
+ </View>
+ </KeyboardAvoidingView>
+ </SheetContainer>
+ );
+}
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index 75d2d27b3029..393df2aa9440 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -4695,6 +4695,7 @@ export class PostHogAPIClient {
default_autostart_priority: string;
default_slack_notification_channel: string | null;
autostart_base_branches: Record<string, string>;
+ max_reports_per_day: number | null;
}>,
): Promise<SignalTeamConfig> {
const teamId = await this.getTeamId();
diff --git a/products/desktop/packages/core/src/inbox/dailyReportLimit.test.ts b/products/desktop/packages/core/src/inbox/dailyReportLimit.test.ts
new file mode 100644
index 000000000000..dab93ad2995f
--- /dev/null
+++ b/products/desktop/packages/core/src/inbox/dailyReportLimit.test.ts
@@ -0,0 +1,88 @@
+import type { SignalTeamConfig } from "@posthog/shared/types";
+import { describe, expect, it } from "vitest";
+import {
+ dailyReportLimitFieldValue,
+ describeDailyReportLimit,
+ parseDailyReportLimit,
+} from "./dailyReportLimit";
+
+function config(overrides: Partial<SignalTeamConfig> = {}): SignalTeamConfig {
+ return {
+ id: "config-1",
+ default_autostart_priority: "P2",
+ max_reports_per_day: null,
+ reports_generated_today: 0,
+ daily_report_limit_reached: false,
+ created_at: "2026-08-20T00:00:00Z",
+ updated_at: "2026-08-20T00:00:00Z",
+ ...overrides,
+ } as SignalTeamConfig;
+}
+
+describe("parseDailyReportLimit", () => {
+ it.each([
+ ["saves a positive integer", "5", { ok: true, value: 5 }],
+ ["trims surrounding whitespace", " 12 ", { ok: true, value: 12 }],
+ ["clears on empty input", "", { ok: true, value: null }],
+ ["clears on whitespace-only input", " ", { ok: true, value: null }],
+ ])("%s", (_name, input, expected) => {
+ expect(parseDailyReportLimit(input)).toEqual(expected);
+ });
+
+ it.each([["0"], ["-3"], ["2.5"], ["ten"], ["9999999999999"]])(
+ "rejects %s",
+ (input) => {
+ const result = parseDailyReportLimit(input);
+ expect(result.ok).toBe(false);
+ },
+ );
+});
+
+describe("describeDailyReportLimit", () => {
+ it("reports no limit when the cap is unset", () => {
+ const status = describeDailyReportLimit(
+ config({ max_reports_per_day: null }),
+ );
+ expect(status.limit).toBeNull();
+ expect(status.reached).toBe(false);
+ expect(status.reachedText).toBeNull();
+ expect(status.usageText).toContain("No daily limit");
+ });
+
+ it("shows the server count against the cap", () => {
+ const status = describeDailyReportLimit(
+ config({ max_reports_per_day: 10, reports_generated_today: 3 }),
+ );
+ expect(status.today).toBe(3);
+ expect(status.usageText).toBe("3 of 10 reports used today.");
+ });
+
+ it("explains the pause when the limit is reached", () => {
+ const status = describeDailyReportLimit(
+ config({
+ max_reports_per_day: 2,
+ reports_generated_today: 2,
+ daily_report_limit_reached: true,
+ }),
+ );
+ expect(status.reached).toBe(true);
+ expect(status.reachedText).toContain("midnight in the project's timezone");
+ });
+
+ it("treats a missing config as no limit", () => {
+ const status = describeDailyReportLimit(null);
+ expect(status.limit).toBeNull();
+ expect(status.usageText).toContain("No daily limit");
+ });
+});
+
+describe("dailyReportLimitFieldValue", () => {
+ it.each([
+ ["empty when unlimited", null, ""],
+ ["the cap as text when set", 7, "7"],
+ ])("%s", (_name, limit, expected) => {
+ expect(
+ dailyReportLimitFieldValue(config({ max_reports_per_day: limit })),
+ ).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/core/src/inbox/dailyReportLimit.ts b/products/desktop/packages/core/src/inbox/dailyReportLimit.ts
new file mode 100644
index 000000000000..2c376555ca02
--- /dev/null
+++ b/products/desktop/packages/core/src/inbox/dailyReportLimit.ts
@@ -0,0 +1,94 @@
+import type { SignalTeamConfig } from "@posthog/shared/types";
+
+/** Ceiling matches the backend int4 column max, so an over-range value is rejected before the request. */
+const MAX_DAILY_REPORT_LIMIT = 2147483647;
+
+export type DailyReportLimitParseResult =
+ | { ok: true; value: number | null }
+ | { ok: false; error: string };
+
+/**
+ * Turn the text field into a value for `max_reports_per_day`. Empty text clears
+ * the cap (`null`). Anything else must be a whole number from 1 to the column
+ * ceiling; otherwise the parse fails with copy the caller can show.
+ */
+export function parseDailyReportLimit(
+ input: string,
+): DailyReportLimitParseResult {
+ const trimmed = input.trim();
+ if (trimmed === "") {
+ return { ok: true, value: null };
+ }
+
+ if (!/^\d+$/.test(trimmed)) {
+ return {
+ ok: false,
+ error:
+ "Enter a whole number of 1 or more, or leave it empty for no limit.",
+ };
+ }
+
+ const value = Number(trimmed);
+ if (value < 1 || value > MAX_DAILY_REPORT_LIMIT) {
+ return {
+ ok: false,
+ error:
+ "Enter a whole number of 1 or more, or leave it empty for no limit.",
+ };
+ }
+
+ return { ok: true, value };
+}
+
+export interface DailyReportLimitStatus {
+ /** The saved cap, or `null` when reports are unlimited. */
+ limit: number | null;
+ /** Reports that first reached the inbox today. `0` when there is no cap. */
+ today: number;
+ /** True when the cap is reached and new reports are paused until local midnight. */
+ reached: boolean;
+ /** One-line summary of today's usage, shown under the field. */
+ usageText: string;
+ /** Message shown when the cap is reached; `null` otherwise. */
+ reachedText: string | null;
+}
+
+/**
+ * Read a team config into the display state for the daily-limit control. The
+ * count and reached flag come from the server, so this is a pure projection.
+ */
+export function describeDailyReportLimit(
+ config: SignalTeamConfig | null | undefined,
+): DailyReportLimitStatus {
+ const limit = config?.max_reports_per_day ?? null;
+ const today = config?.reports_generated_today ?? 0;
+ const reached = config?.daily_report_limit_reached ?? false;
+
+ if (limit === null) {
+ return {
+ limit,
+ today: 0,
+ reached: false,
+ usageText: "No daily limit. Reports reach the inbox as they are found.",
+ reachedText: null,
+ };
+ }
+
+ return {
+ limit,
+ today,
+ reached,
+ usageText: `${today} of ${limit} report${limit === 1 ? "" : "s"} used today.`,
+ reachedText: reached
+ ? "Daily limit reached. New reports pause until midnight in the project's timezone."
+ : null,
+ };
+}
+
+/** The saved cap as text for the input field; empty string when unlimited. */
+export function dailyReportLimitFieldValue(
+ config: SignalTeamConfig | null | undefined,
+): string {
+ const limit = config?.max_reports_per_day ?? null;
+ return limit === null ? "" : String(limit);
+}
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index 2e173697bcc7..5270ff6732a1 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -1018,6 +1018,12 @@ export interface SignalTeamConfig {
/** Team-wide default `channel_id|#channel-name` target for inbox notifications. `null` = no team default. */
default_slack_notification_channel?: string | null;
autostart_base_branches?: Record<string, string> | null;
+ /** Daily cap on new reports reaching the inbox, counted per project-timezone day. `null` = unlimited. */
+ max_reports_per_day?: number | null;
+ /** Reports that first became visible today. `0` when there is no cap. Read-only. */
+ reports_generated_today?: number;
+ /** Whether the cap is reached, pausing new reports until local midnight. `false` when there is no cap. Read-only. */
+ daily_report_limit_reached?: boolean;
created_at: string;
updated_at: string;
}
diff --git a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx
index 27f21a89486a..460f006c22cf 100644
--- a/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx
+++ b/products/desktop/packages/ui/src/features/inbox/components/ConfigureAgentsSection.tsx
@@ -39,6 +39,7 @@ import {
import { toastError } from "@posthog/ui/features/notifications/errorDetails";
import { ScoutsFleetSection } from "@posthog/ui/features/scouts/components/ScoutsFleetSection";
import { SettingsSubsection } from "@posthog/ui/features/settings/components/SettingsSubsection";
+import { DailyReportLimitSettings } from "@posthog/ui/features/settings/sections/DailyReportLimitSettings";
import { GitHubIntegrationSection } from "@posthog/ui/features/settings/sections/GitHubIntegrationSection";
import { SlackInboxNotificationsSettings } from "@posthog/ui/features/settings/sections/SlackInboxNotificationsSettings";
import {
@@ -83,6 +84,9 @@ export function ConfigureAgentsSection() {
handleSetup,
handleSetupComplete,
handleSetupCancel,
+ teamConfig,
+ teamConfigLoading,
+ handleUpdateMaxReportsPerDay,
userAutonomyConfig,
userAutonomyConfigLoading,
} = useSignalSourceManager();
@@ -193,6 +197,11 @@ export function ConfigureAgentsSection() {
</Box>
</Tooltip>
)}
+ <DailyReportLimitSettings
+ config={teamConfig}
+ onSave={handleUpdateMaxReportsPerDay}
+ isLoading={teamConfigLoading}
+ />
</SettingsSubsection>
<SettingsSubsection
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useSignalSourceManager.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useSignalSourceManager.ts
index 0780f8b7fe1b..3015da78d0b9 100644
--- a/products/desktop/packages/ui/src/features/inbox/hooks/useSignalSourceManager.ts
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useSignalSourceManager.ts
@@ -43,6 +43,7 @@ export function useSignalSourceManager() {
handleUpdateTeamSlackChannel: teamMutations.handleUpdateTeamSlackChannel,
handleUpdateAutostartBaseBranches:
teamMutations.handleUpdateAutostartBaseBranches,
+ handleUpdateMaxReportsPerDay: teamMutations.handleUpdateMaxReportsPerDay,
// User autonomy
userAutonomyConfig,
diff --git a/products/desktop/packages/ui/src/features/inbox/hooks/useSignalTeamConfigMutations.ts b/products/desktop/packages/ui/src/features/inbox/hooks/useSignalTeamConfigMutations.ts
index 0b81f4bdaf88..163987994e0f 100644
--- a/products/desktop/packages/ui/src/features/inbox/hooks/useSignalTeamConfigMutations.ts
+++ b/products/desktop/packages/ui/src/features/inbox/hooks/useSignalTeamConfigMutations.ts
@@ -100,9 +100,38 @@ export function useSignalTeamConfigMutations() {
[client, queryClient],
);
+ const handleUpdateMaxReportsPerDay = useCallback(
+ async (limit: number | null) => {
+ if (!client) return;
+ try {
+ // Write the server's fresh config back so today's count and the reached
+ // flag update alongside the new cap.
+ const fresh = await client.updateSignalTeamConfig({
+ max_reports_per_day: limit,
+ });
+ // Cancel any in-flight config fetch first (the desktop client refetches
+ // this query on window focus) so a stale GET can't resolve after this
+ // write and clobber the fresh cap.
+ await queryClient.cancelQueries({ queryKey: TEAM_CONFIG_QUERY_KEY });
+ queryClient.setQueryData<SignalTeamConfig | null>(
+ TEAM_CONFIG_QUERY_KEY,
+ fresh,
+ );
+ } catch (error: unknown) {
+ const message =
+ error instanceof Error
+ ? error.message
+ : "Failed to update daily report limit";
+ toast.error(message);
+ }
+ },
+ [client, queryClient],
+ );
+
return {
handleUpdateAutostartPriority,
handleUpdateTeamSlackChannel,
handleUpdateAutostartBaseBranches,
+ handleUpdateMaxReportsPerDay,
};
}
diff --git a/products/desktop/packages/ui/src/features/settings/sections/DailyReportLimitSettings.tsx b/products/desktop/packages/ui/src/features/settings/sections/DailyReportLimitSettings.tsx
new file mode 100644
index 000000000000..a4773f5b1dd7
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/settings/sections/DailyReportLimitSettings.tsx
@@ -0,0 +1,163 @@
+import {
+ dailyReportLimitFieldValue,
+ describeDailyReportLimit,
+ parseDailyReportLimit,
+} from "@posthog/core/inbox/dailyReportLimit";
+import { Button, Input, Text } from "@posthog/quill";
+import type { SignalTeamConfig } from "@posthog/shared/types";
+import { useState } from "react";
+
+interface DailyReportLimitSettingsProps {
+ config: SignalTeamConfig | null | undefined;
+ /** Persist the cap; `null` clears it. Resolves once the server responds. */
+ onSave: (limit: number | null) => Promise<void>;
+ isLoading?: boolean;
+ disabled?: boolean;
+}
+
+/**
+ * Per-project daily cap on new reports reaching the inbox. Saving a whole number
+ * sets the cap; clearing the field removes it. Today's count and the paused state
+ * come from the server config.
+ */
+export function DailyReportLimitSettings({
+ config,
+ onSave,
+ isLoading = false,
+ disabled = false,
+}: DailyReportLimitSettingsProps) {
+ const savedValue = dailyReportLimitFieldValue(config);
+ const [draft, setDraft] = useState(savedValue);
+ const [syncedValue, setSyncedValue] = useState(savedValue);
+ const [error, setError] = useState<string | null>(null);
+ const [isSaving, setIsSaving] = useState(false);
+
+ // Re-sync the field when the server value actually changes (a refresh, a
+ // successful save, or another surface's save) so it shows through instead of
+ // being masked. Deriving during render — rather than an effect keyed on
+ // isSaving — leaves a failed save's typed draft in place, since a failure
+ // does not change the server value.
+ if (savedValue !== syncedValue && !isSaving) {
+ setSyncedValue(savedValue);
+ setDraft(savedValue);
+ }
+
+ const status = describeDailyReportLimit(config);
+ const isDirty = draft.trim() !== savedValue;
+ const controlsDisabled = disabled || isLoading || isSaving;
+
+ const handleSave = async () => {
+ const parsed = parseDailyReportLimit(draft);
+ if (!parsed.ok) {
+ setError(parsed.error);
+ return;
+ }
+ setError(null);
+ setIsSaving(true);
+ try {
+ await onSave(parsed.value);
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ const handleClear = async () => {
+ setDraft("");
+ setError(null);
+ setIsSaving(true);
+ try {
+ await onSave(null);
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-2 border-(--gray-5) border-t border-dashed pt-3">
+ <div className="flex flex-col gap-1">
+ <Text className="font-medium text-(--gray-12) text-sm">
+ Daily report limit
+ </Text>
+ <Text className="text-(--gray-11) text-[13px]">
+ Cap how many new reports reach the inbox each day. Leave the field
+ empty for no limit.
+ </Text>
+ </div>
+
+ {isLoading ? (
+ <div className="h-[32px] w-[220px] animate-pulse rounded bg-gray-3" />
+ ) : (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-[120px]">
+ <Input
+ type="number"
+ min={1}
+ step={1}
+ inputMode="numeric"
+ placeholder="No limit"
+ aria-label="Daily report limit"
+ aria-describedby={
+ error ? "daily-report-limit-error" : undefined
+ }
+ value={draft}
+ disabled={controlsDisabled}
+ data-attr="daily-report-limit-input"
+ onChange={(e) => {
+ setDraft(e.currentTarget.value);
+ setError(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && isDirty) {
+ e.preventDefault();
+ void handleSave();
+ }
+ }}
+ />
+ </div>
+ <Button
+ size="sm"
+ disabled={controlsDisabled || !isDirty}
+ loading={isSaving}
+ data-attr="daily-report-limit-save"
+ onClick={() => void handleSave()}
+ >
+ Save
+ </Button>
+ {savedValue !== "" ? (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={controlsDisabled}
+ data-attr="daily-report-limit-clear"
+ onClick={() => void handleClear()}
+ >
+ Clear
+ </Button>
+ ) : null}
+ </div>
+
+ {error ? (
+ <Text
+ id="daily-report-limit-error"
+ role="alert"
+ className="text-(--red-11) text-[12.5px]"
+ >
+ {error}
+ </Text>
+ ) : (
+ <Text className="text-(--gray-11) text-[12.5px]">
+ {status.usageText}
+ </Text>
+ )}
+
+ {status.reachedText ? (
+ <Text className="text-(--orange-11) text-[12.5px]">
+ {status.reachedText}
+ </Text>
+ ) : null}
+ </>
+ )}
+ </div>
+ );
+}