Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

add jev checker

Pedro Ladeira2262f8fd6a41
diff --git a/apps/web/lib/ai/review-reward-tooltip.ts b/apps/web/lib/ai/review-reward-tooltip.ts
index d5caf3622d..93428c9983 100644
--- a/apps/web/lib/ai/review-reward-tooltip.ts
+++ b/apps/web/lib/ai/review-reward-tooltip.ts
@@ -11,60 +11,113 @@ import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";
import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";
import { CONDITION_OPERATOR_LABELS } from "@/lib/zod/schemas/rewards";
import { anthropic } from "@ai-sdk/anthropic";
-import { generateText, Output } from "ai";
+import { experimental_evaluate as evaluate, generateText, Output } from "ai";
import { throwIfNoPermission } from "../actions/throw-if-no-permission";
import {
reviewRewardTooltipInputSchema,
reviewRewardTooltipOutputSchema,
+ TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR,
type ReviewRewardTooltipModifier,
type TooltipSuggestion,
} from "./review-reward-tooltip-schema";
-export async function reviewRewardTooltipConsistency(
+export async function screenRewardTooltipContradiction(
input: unknown,
-): Promise<{ suggestions: TooltipSuggestion[] }> {
+): Promise<{ flagged: boolean | null }> {
try {
- const parsedInput = reviewRewardTooltipInputSchema.safeParse(input);
- if (!parsedInput.success) {
- return { suggestions: [] };
+ const authorized = await authorizeRewardTooltipReview(input);
+ if (!authorized) {
+ return { flagged: false };
}
- const session = await getSession();
- if (!session?.user.id) {
- return { suggestions: [] };
+ const tooltip = stripRewardTooltipMarkdown(authorized.data.tooltip);
+ if (!tooltip) {
+ return { flagged: false };
}
- const workspaceId = normalizeWorkspaceId(parsedInput.data.workspaceId);
- const workspace = await prisma.project.findUnique({
- where: { id: workspaceId },
- include: {
- users: {
- where: { userId: session.user.id },
- select: { role: true },
+ await assertRateLimit({
+ policy: RATELIMIT_POLICIES.aiRewardTooltipScreen,
+ identifier: [authorized.userId, authorized.workspaceId],
+ });
+
+ const { event, modifiers } = authorized.data;
+ const result = await evaluate({
+ model: "typesafe-ai/jev",
+ state: {
+ event,
+ tooltip,
+ conditions: serializeConditions(modifiers),
+ },
+ questions: {
+ contradicts: {
+ type: "boolean",
+ instructions:
+ "Would a partner who only read the tooltip be surprised by an existing condition?",
+ criteria: {
+ true: {
+ meaning:
+ "Yes only when an existing condition clearly contradicts the tooltip. One strong mismatch is enough. Use a low probability when unsure.",
+ matches_any: [
+ "The tooltip says minimum, at least, or that a threshold qualifies, but the condition uses a strict greater-than or less-than that excludes that boundary.",
+ "The tooltip says more than, over, or above, but the condition includes the boundary.",
+ "The tooltip names a different operator or threshold than an existing condition, clearly enough that a partner would expect a different eligibility rule.",
+ ],
+ },
+ false: {
+ meaning:
+ "No when the tooltip and the existing conditions agree, or when the reading is ambiguous.",
+ even_if: [
+ "The tooltip is shorter than the config or omits extra filters such as country, product, or metadata.",
+ "The wording is informal and does not clearly specify a different operator or threshold.",
+ "The tooltip never mentions a condition that still exists in the config.",
+ ],
+ },
+ },
+ },
+ },
+ providerOptions: {
+ gateway: {
+ zeroDataRetention: true,
},
},
});
- if (!workspace?.users?.length) {
- return { suggestions: [] };
+ const answer = result.answers.contradicts;
+ if (answer?.type !== "boolean") {
+ return { flagged: null };
}
- throwIfNoPermission({
- role: workspace.users[0].role,
- requiredRoles: ["owner", "member"],
- });
+ return {
+ flagged:
+ Number.isFinite(answer.probability) &&
+ answer.probability > TOOLTIP_SUGGESTION_CONFIDENCE_FLOOR,
+ };
+ } catch (error) {
+ console.error("[screenRewardTooltipContradiction]", error);
+ return { flagged: null };
+ }
+}
+
+export async function reviewRewardTooltipConsistency(
+ input: unknown,
+): Promise<{ suggestions: TooltipSuggestion[] }> {
+ try {
+ const authorized = await authorizeRewardTooltipReview(input);
+ if (!authorized) {
+ return { suggestions: [] };
+ }
await assertRateLimit({
policy: RATELIMIT_POLICIES.aiRewardTooltipReview,
- identifier: [session.user.id, workspaceId],
+ identifier: [authorized.userId, authorized.workspaceId],
});
- const tooltip = stripRewardTooltipMarkdown(parsedInput.data.tooltip);
+ const tooltip = stripRewardTooltipMarkdown(authorized.data.tooltip);
if (!tooltip) {
return { suggestions: [] };
}
- const { event, modifiers } = parsedInput.data;
+ const { event, modifiers } = authorized.data;
const { output } = await generateText({
model: anthropic("claude-haiku-4-5"),
@@ -95,6 +148,44 @@ export async function reviewRewardTooltipConsistency(
}
}
+async function authorizeRewardTooltipReview(input: unknown) {
+ const parsedInput = reviewRewardTooltipInputSchema.safeParse(input);
+ if (!parsedInput.success) {
+ return null;
+ }
+
+ const session = await getSession();
+ if (!session?.user.id) {
+ return null;
+ }
+
+ const workspaceId = normalizeWorkspaceId(parsedInput.data.workspaceId);
+ const workspace = await prisma.project.findUnique({
+ where: { id: workspaceId },
+ include: {
+ users: {
+ where: { userId: session.user.id },
+ select: { role: true },
+ },
+ },
+ });
+
+ if (!workspace?.users?.length) {
+ return null;
+ }
+
+ throwIfNoPermission({
+ role: workspace.users[0].role,
+ requiredRoles: ["owner", "member"],
+ });
+
+ return {
+ userId: session.user.id,
+ workspaceId,
+ data: parsedInput.data,
+ };
+}
+
function buildSystemPrompt(event: string) {
return `You review whether partner-facing reward tooltip copy contradicts the structured reward conditions.
@@ -125,14 +216,8 @@ Not contradictions:
- Informal wording that does not clearly specify a different operator or threshold.`;
}
-function buildUserPrompt({
- tooltip,
- modifiers,
-}: {
- tooltip: string;
- modifiers: ReviewRewardTooltipModifier[];
-}) {
- const serialized = modifiers
+function serializeConditions(modifiers: ReviewRewardTooltipModifier[]) {
+ return modifiers
.map((modifier, modifierIndex) => {
const conditions = modifier.conditions
.map((condition, conditionIndex) => {
@@ -152,14 +237,22 @@ function buildUserPrompt({
return `Group ${modifierIndex} (${modifier.operator}):\n${conditions}`;
})
.join("\n");
+}
+function buildUserPrompt({
+ tooltip,
+ modifiers,
+}: {
+ tooltip: string;
+ modifiers: ReviewRewardTooltipModifier[];
+}) {
return `Tooltip:
"""
${tooltip}
"""
Conditions:
-${serialized}
+${serializeConditions(modifiers)}
Write the reason for a non-technical user. Use the operator labels in parentheses, not the raw operator keys.`;
}
diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.ts
index ba38167c00..9fb35f18cf 100644
--- a/apps/web/lib/upstash/ratelimit-policies.ts
+++ b/apps/web/lib/upstash/ratelimit-policies.ts
@@ -121,6 +121,12 @@ export const RATELIMIT_POLICIES = {
keyPrefix: "rl:ai:reward:tooltip-review",
},
+ aiRewardTooltipScreen: {
+ attempts: 60,
+ window: "1 m",
+ keyPrefix: "rl:ai:reward:tooltip-screen",
+ },
+
// Keyed on workspace + user so one actor cannot exhaust the workspace quota
forwardDnsInstructions: {
attempts: 10,
diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
index 2289868299..d610d5bb57 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -9,6 +9,7 @@ import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";
import { ReferralRewardConfig } from "@/lib/partner-referrals/types";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";
+import { applyTooltipSuggestion } from "@/lib/rewards/validate-tooltip-suggestion";
import useGroup from "@/lib/swr/use-group";
import useProgram from "@/lib/swr/use-program";
import { useRewards } from "@/lib/swr/use-rewards";
@@ -30,6 +31,7 @@ import { X } from "@/ui/shared/icons";
import {
Button,
Gift,
+ LoadingSpinner,
MoneyBills2,
Pen2,
Sheet,
@@ -76,6 +78,10 @@ import { PartnerReferralRewardBuilder } from "./partner-referral-reward-builder"
import { RewardIconSquare } from "./reward-icon-square";
import { RewardPreviewCard } from "./reward-preview-card";
import { REWARD_TYPES, RewardsLogic } from "./rewards-logic";
+import {
+ RewardTooltipConsistencyContext,
+ useRewardTooltipConsistency,
+} from "./use-reward-tooltip-consistency";
interface RewardSheetProps {
setIsOpen: Dispatch<SetStateAction<boolean>>;
@@ -378,6 +384,26 @@ function RewardSheetContent({
const { canCreateReferralReward, canUseAdvancedRewardLogic } =
getPlanCapabilities(plan);
+ const consistency = useRewardTooltipConsistency({
+ workspaceId,
+ event: selectedEvent,
+ tooltipDescription,
+ modifiers,
+ onApply: (suggestion) => {
+ const conditionKey =
+ `modifiers.${suggestion.modifierIndex}.conditions.${suggestion.conditionIndex}` as const;
+ const current = getValues(conditionKey);
+
+ if (!current) return;
+
+ setValue(
+ conditionKey,
+ applyTooltipSuggestion(current, suggestion.suggested),
+ { shouldDirty: true },
+ );
+ },
+ });
+
const isAiRewardEvent =
selectedEvent !== "referral" && selectedEvent !== "custom";
const aiEvent = isAiRewardEvent ? selectedEvent : "sale";
@@ -575,289 +601,297 @@ function RewardSheetContent({
)}
{isAiRewardEvent ? (
<AIRewardPreviewFrame builder={aiBuilder}>
- <RewardSheetCard
- title={
- <div className="w-full">
- <div className="flex min-w-0 items-center justify-between">
- <div className="flex min-w-0 items-center gap-2.5">
- <RewardIconSquare icon={MoneyBills2} />
- <span className="leading-relaxed">
- Pay{" "}
- {selectedEvent === "sale" && (
- <>
- a{" "}
- <InlineBadgePopover text={capitalize(type)}>
- <InlineBadgePopoverMenu
- selectedValue={type}
- onSelect={(value) =>
+ <RewardTooltipConsistencyContext.Provider value={consistency}>
+ <RewardSheetCard
+ title={
+ <div className="w-full">
+ <div className="flex min-w-0 items-center justify-between">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <RewardIconSquare icon={MoneyBills2} />
+ <span className="leading-relaxed">
+ Pay{" "}
+ {selectedEvent === "sale" && (
+ <>
+ a{" "}
+ <InlineBadgePopover text={capitalize(type)}>
+ <InlineBadgePopoverMenu
+ selectedValue={type}
+ onSelect={(value) =>
+ setValue(
+ "type",
+ value as RewardStructure,
+ {
+ shouldDirty: true,
+ },
+ )
+ }
+ items={REWARD_TYPES}
+ />
+ </InlineBadgePopover>{" "}
+ {type === "percentage" && "of "}
+ </>
+ )}
+ <InlineBadgePopover
+ text={
+ amount != null && !isNaN(amount)
+ ? constructRewardAmount({
+ type,
+ maxDuration,
+ amountInCents:
+ type === "flat"
+ ? amount * 100
+ : undefined,
+ amountInPercentage:
+ type === "percentage"
+ ? amount
+ : undefined,
+ })
+ : "amount"
+ }
+ invalid={amount == null || isNaN(amount)}
+ >
+ <AmountInput />
+ </InlineBadgePopover>{" "}
+ per {selectedEvent}
+ {selectedEvent === "sale" && (
+ <>
+ {" "}
+ <InlineBadgePopover
+ text={
+ maxDuration === 0
+ ? "one time"
+ : maxDuration === Infinity
+ ? "for the customer's lifetime"
+ : `for ${maxDuration} ${pluralize("month", Number(maxDuration))}`
+ }
+ >
+ <DurationPopoverContent
+ value={Number(maxDuration)}
+ onChange={(value) =>
+ setValue("maxDuration", value, {
+ shouldDirty: true,
+ })
+ }
+ presetDurations={RECURRING_MAX_DURATIONS.filter(
+ (v) => v !== 0 && v !== 1,
+ )}
+ />
+ </InlineBadgePopover>
+ </>
+ )}
+ {modifiers?.length ? (
+ <> for all other {selectedEvent}s</>
+ ) : null}
+ {flags?.rewardSpendLimit ? (
+ <>
+ {", "}with{" "}
+ <InlineBadgePopover
+ text={
+ spendLimitEnabled
+ ? "a spend limit of"
+ : "no spend limit"
+ }
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={
+ spendLimitEnabled ? "limit" : "none"
+ }
+ onSelect={(value) => {
+ if (value === "none") {
+ setValue("spendLimitAmount", null, {
+ shouldDirty: true,
+ });
+ setValue("spendLimitInterval", null, {
+ shouldDirty: true,
+ });
+ } else {
+ setValue(
+ "spendLimitInterval",
+ spendLimitInterval ?? "allTime",
+ {
+ shouldDirty: true,
+ },
+ );
+ }
+ }}
+ items={[
+ {
+ text: "no spend limit",
+ value: "none",
+ },
+ {
+ text: "a spend limit of",
+ value: "limit",
+ },
+ ]}
+ />
+ </InlineBadgePopover>{" "}
+ {spendLimitEnabled ? (
+ <>
+ <InlineBadgePopover
+ text={
+ spendLimitAmount != null &&
+ !isNaN(spendLimitAmount)
+ ? currencyFormatter(
+ spendLimitAmount * 100,
+ {
+ trailingZeroDisplay:
+ "stripIfInteger",
+ },
+ )
+ : "amount"
+ }
+ invalid={
+ spendLimitAmount == null ||
+ isNaN(spendLimitAmount)
+ }
+ >
+ <SpendLimitAmountInput />
+ </InlineBadgePopover>{" "}
+ <InlineBadgePopover
+ text={
+ spendLimitInterval === "allTime"
+ ? "all-time"
+ : `per ${spendLimitInterval}`
+ }
+ >
+ <InlineBadgePopoverMenu
+ selectedValue={
+ spendLimitInterval ?? "allTime"
+ }
+ onSelect={(value) =>
+ setValue(
+ "spendLimitInterval",
+ value as any,
+ {
+ shouldDirty: true,
+ },
+ )
+ }
+ items={[
+ {
+ text: "all-time",
+ value: "allTime",
+ },
+ { text: "per day", value: "day" },
+ { text: "per week", value: "week" },
+ {
+ text: "per month",
+ value: "month",
+ },
+ ]}
+ />
+ </InlineBadgePopover>
+ </>
+ ) : null}
+ </>
+ ) : null}
+ </span>
+ </div>
+ <Tooltip
+ content={"Add a custom reward description"}
+ disabled={description !== null}
+ >
+ <div className="shrink-0">
+ <Button
+ variant="secondary"
+ className={cn(
+ "size-7 p-0",
+ description !== null && "text-blue-600",
+ )}
+ icon={<Pen2 className="size-3.5" />}
+ onClick={() =>
+ setValue(
+ "description",
+ description === null ? "" : null,
+ { shouldDirty: true },
+ )
+ }
+ />
+ </div>
+ </Tooltip>
+ </div>
+ <motion.div
+ initial={false}
+ transition={{ ease: "easeInOut", duration: 0.2 }}
+ animate={{
+ height: description !== null ? "auto" : 0,
+ opacity: description !== null ? 1 : 0,
+ }}
+ className="-mx-2.5 overflow-hidden"
+ >
+ <div className="pt-2.5">
+ <div className="border-border-subtle flex min-w-0 items-center gap-2.5 border-t px-2.5 pt-2.5">
+ <RewardIconSquare icon={Gift} />
+ <span className="min-w-0 grow leading-relaxed">
+ Shown as{" "}
+ <InlineBadgePopover
+ text={description || "Reward description"}
+ invalid={!description}
+ >
+ <InlineBadgePopoverInput
+ value={description ?? ""}
+ onChange={(e) =>
setValue(
- "type",
- value as RewardStructure,
+ "description",
+ (e.target as HTMLInputElement).value,
{
shouldDirty: true,
},
)
}
- items={REWARD_TYPES}
+ className="sm:w-80"
+ maxLength={REWARD_DESCRIPTION_MAX_LENGTH}
/>
</InlineBadgePopover>{" "}
- {type === "percentage" && "of "}
- </>
- )}
- <InlineBadgePopover
- text={
- amount != null && !isNaN(amount)
- ? constructRewardAmount({
- type,
- maxDuration,
- amountInCents:
- type === "flat"
- ? amount * 100
- : undefined,
- amountInPercentage:
- type === "percentage"
- ? amount
- : undefined,
- })
- : "amount"
- }
- invalid={amount == null || isNaN(amount)}
- >
- <AmountInput />
- </InlineBadgePopover>{" "}
- per {selectedEvent}
- {selectedEvent === "sale" && (
- <>
- {" "}
+ with the tooltip{" "}
<InlineBadgePopover
- text={
- maxDuration === 0
- ? "one time"
- : maxDuration === Infinity
- ? "for the customer's lifetime"
- : `for ${maxDuration} ${pluralize("month", Number(maxDuration))}`
- }
+ text={tooltipDescription || "Reward tooltip"}
+ showOptional={!tooltipDescription}
+ buttonClassName="min-w-0 max-w-full"
+ contentClassName="truncate"
>
- <DurationPopoverContent
- value={Number(maxDuration)}
+ <InlineBadgePopoverRichTextArea
+ value={tooltipDescription ?? ""}
onChange={(value) =>
- setValue("maxDuration", value, {
+ setValue("tooltipDescription", value, {
shouldDirty: true,
})
}
- presetDurations={RECURRING_MAX_DURATIONS.filter(
- (v) => v !== 0 && v !== 1,
- )}
- />
- </InlineBadgePopover>
- </>
- )}
- {modifiers?.length ? (
- <> for all other {selectedEvent}s</>
- ) : null}
- {flags?.rewardSpendLimit ? (
- <>
- {", "}with{" "}
- <InlineBadgePopover
- text={
- spendLimitEnabled
- ? "a spend limit of"
- : "no spend limit"
- }
- >
- <InlineBadgePopoverMenu
- selectedValue={
- spendLimitEnabled ? "limit" : "none"
+ className="sm:w-80"
+ maxLength={
+ REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH
}
- onSelect={(value) => {
- if (value === "none") {
- setValue("spendLimitAmount", null, {
- shouldDirty: true,
- });
- setValue("spendLimitInterval", null, {
- shouldDirty: true,
- });
- } else {
- setValue(
- "spendLimitInterval",
- spendLimitInterval ?? "allTime",
- {
- shouldDirty: true,
- },
- );
- }
- }}
- items={[
- {
- text: "no spend limit",
- value: "none",
- },
- {
- text: "a spend limit of",
- value: "limit",
- },
- ]}
/>
- </InlineBadgePopover>{" "}
- {spendLimitEnabled ? (
- <>
- <InlineBadgePopover
- text={
- spendLimitAmount != null &&
- !isNaN(spendLimitAmount)
- ? currencyFormatter(
- spendLimitAmount * 100,
- {
- trailingZeroDisplay:
- "stripIfInteger",
- },
- )
- : "amount"
- }
- invalid={
- spendLimitAmount == null ||
- isNaN(spendLimitAmount)
- }
- >
- <SpendLimitAmountInput />
- </InlineBadgePopover>{" "}
- <InlineBadgePopover
- text={
- spendLimitInterval === "allTime"
- ? "all-time"
- : `per ${spendLimitInterval}`
- }
- >
- <InlineBadgePopoverMenu
- selectedValue={
- spendLimitInterval ?? "allTime"
- }
- onSelect={(value) =>
- setValue(
- "spendLimitInterval",
- value as any,
- {
- shouldDirty: true,
- },
- )
- }
- items={[
- {
- text: "all-time",
- value: "allTime",
- },
- { text: "per day", value: "day" },
- { text: "per week", value: "week" },
- {
- text: "per month",
- value: "month",
- },
- ]}
- />
- </InlineBadgePopover>
- </>
- ) : null}
- </>
- ) : null}
- </span>
- </div>
- <Tooltip
- content={"Add a custom reward description"}
- disabled={description !== null}
- >
- <div className="shrink-0">
- <Button
- variant="secondary"
- className={cn(
- "size-7 p-0",
- description !== null && "text-blue-600",
- )}
- icon={<Pen2 className="size-3.5" />}
- onClick={() =>
- setValue(
- "description",
- description === null ? "" : null,
- { shouldDirty: true },
- )
- }
- />
+ </InlineBadgePopover>
+ {consistency.status === "reviewing" && (
+ <span className="ml-1.5 inline-flex items-center gap-1 align-middle text-xs font-medium text-neutral-500">
+ <LoadingSpinner className="size-3" />
+ Reviewing
+ </span>
+ )}
+ </span>
+ <Button
+ variant="outline"
+ className="size-6 shrink-0 p-0"
+ icon={<X className="size-3" strokeWidth={2} />}
+ onClick={() => {
+ setValue("description", null, {
+ shouldDirty: true,
+ });
+ setValue("tooltipDescription", null, {
+ shouldDirty: true,
+ });
+ }}
+ />
+ </div>
</div>
- </Tooltip>
+ </motion.div>
</div>
- <motion.div
- initial={false}
- transition={{ ease: "easeInOut", duration: 0.2 }}
- animate={{
- height: description !== null ? "auto" : 0,
- opacity: description !== null ? 1 : 0,
- }}
- className="-mx-2.5 overflow-hidden"
- >
- <div className="pt-2.5">
- <div className="border-border-subtle flex min-w-0 items-center gap-2.5 border-t px-2.5 pt-2.5">
- <RewardIconSquare icon={Gift} />
- <span className="min-w-0 grow leading-relaxed">
- Shown as{" "}
- <InlineBadgePopover
- text={description || "Reward description"}
- invalid={!description}
- >
- <InlineBadgePopoverInput
- value={description ?? ""}
- onChange={(e) =>
- setValue(
- "description",
- (e.target as HTMLInputElement).value,
- {
- shouldDirty: true,
- },
- )
- }
- className="sm:w-80"
- maxLength={REWARD_DESCRIPTION_MAX_LENGTH}
- />
- </InlineBadgePopover>{" "}
- with the tooltip{" "}
- <InlineBadgePopover
- text={tooltipDescription || "Reward tooltip"}
- showOptional={!tooltipDescription}
- buttonClassName="min-w-0 max-w-full"
- contentClassName="truncate"
- >
- <InlineBadgePopoverRichTextArea
- value={tooltipDescription ?? ""}
- onChange={(value) =>
- setValue("tooltipDescription", value, {
- shouldDirty: true,
- })
- }
- className="sm:w-80"
- maxLength={
- REWARD_TOOLTIP_DESCRIPTION_MAX_LENGTH
- }
- />
- </InlineBadgePopover>
- </span>
- <Button
- variant="outline"
- className="size-6 shrink-0 p-0"
- icon={<X className="size-3" strokeWidth={2} />}
- onClick={() => {
- setValue("description", null, {
- shouldDirty: true,
- });
- setValue("tooltipDescription", null, {
- shouldDirty: true,
- });
- }}
- />
- </div>
- </div>
- </motion.div>
- </div>
- }
- content={<RewardsLogic isDefaultReward={false} />}
- />
+ }
+ content={<RewardsLogic isDefaultReward={false} />}
+ />
+ </RewardTooltipConsistencyContext.Provider>
</AIRewardPreviewFrame>
) : (
<RewardSheetCard
diff --git a/apps/web/ui/partners/rewards/rewards-logic.tsx b/apps/web/ui/partners/rewards/rewards-logic.tsx
index c3ba5620a5..96163227be 100644
--- a/apps/web/ui/partners/rewards/rewards-logic.tsx
+++ b/apps/web/ui/partners/rewards/rewards-logic.tsx
@@ -2,10 +2,7 @@
import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";
import { getPlanCapabilities } from "@/lib/plan-capabilities";
-import {
- applyTooltipSuggestion,
- suggestionTouchesField,
-} from "@/lib/rewards/validate-tooltip-suggestion";
+import { suggestionTouchesField } from "@/lib/rewards/validate-tooltip-suggestion";
import { SUBMITTED_LEADS_ENABLED_PROGRAM_IDS } from "@/lib/submitted-leads/constants";
import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
@@ -69,11 +66,7 @@ import {
SuggestedFixBadge,
SuggestedFixPopoverHost,
} from "./suggested-fix-popover";
-import {
- RewardTooltipConsistencyContext,
- useRewardTooltipConsistency,
- useRewardTooltipConsistencyContext,
-} from "./use-reward-tooltip-consistency";
+import { useRewardTooltipConsistencyContext } from "./use-reward-tooltip-consistency";
export const REWARD_TYPES = [
{
@@ -91,33 +84,9 @@ export function RewardsLogic({
}: {
isDefaultReward: boolean;
}) {
- const { plan, id: workspaceId } = useWorkspace();
+ const { plan } = useWorkspace();
const { control, getValues, setValue } = useAddEditRewardForm();
- const [event, tooltipDescription, modifiers] = useWatch({
- control,
- name: ["event", "tooltipDescription", "modifiers"],
- });
-
- const consistency = useRewardTooltipConsistency({
- workspaceId,
- event,
- tooltipDescription,
- modifiers,
- onApply: (suggestion) => {
- const conditionKey =
- `modifiers.${suggestion.modifierIndex}.conditions.${suggestion.conditionIndex}` as const;
- const current = getValues(conditionKey);
-
- if (!current) return;
-
- setValue(
- conditionKey,
- applyTooltipSuggestion(current, suggestion.suggested),
- { shouldDirty: true },
- );
- },
- });
const {
fields: modifierFields,
@@ -129,7 +98,7 @@ export function RewardsLogic({
});
return (
- <RewardTooltipConsistencyContext.Provider value={consistency}>
+ <>
<SuggestedFixPopoverHost />
<div
className={cn(
@@ -185,7 +154,7 @@ export function RewardsLogic({
variant={isDefaultReward ? "primary" : "secondary"}
/>
</div>
- </RewardTooltipConsistencyContext.Provider>
+ </>
);
}
diff --git a/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts b/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
index f3b2bbb71a..c843e3913a 100644
--- a/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
+++ b/apps/web/ui/partners/rewards/use-reward-tooltip-consistency.ts
@@ -4,7 +4,10 @@ import {
AI_REWARD_EVENTS,
type AIRewardEvent,
} from "@/lib/ai/ai-reward-schema";
-import { reviewRewardTooltipConsistency } from "@/lib/ai/review-reward-tooltip";
+import {
+ reviewRewardTooltipConsistency,
+ screenRewardTooltipContradiction,
+} from "@/lib/ai/review-reward-tooltip";
import type {
ReviewRewardTooltipModifier,
TooltipSuggestion,
@@ -31,7 +34,13 @@ import {
const DEBOUNCE_MS = 200;
const HIDE_MS = 300;
-const reviewCache = new Map<string, TooltipSuggestion[]>();
+
+type TooltipReviewStatus = "idle" | "reviewing";
+
+const reviewCache = new Map<
+ string,
+ { flagged: boolean; suggestions: TooltipSuggestion[] }
+>();
export function tooltipSuggestionPageKey({
modifierIndex,
@@ -46,6 +55,7 @@ export function tooltipSuggestionPageKey({
}
type RewardTooltipConsistencyValue = {
+ status: TooltipReviewStatus;
suggestions: TooltipSuggestion[];
pages: TooltipSuggestionPage[];
activeIndex: number;
@@ -102,6 +112,7 @@ export function useRewardTooltipConsistency({
onApply?: (suggestion: TooltipSuggestion) => void;
}): RewardTooltipConsistencyValue {
const [suggestions, setSuggestions] = useState<TooltipSuggestion[]>([]);
+ const [status, setStatus] = useState<TooltipReviewStatus>("idle");
const [activeIndex, setActiveIndex] = useState(0);
const [open, setOpen] = useState(false);
const [dismissedKeys, setDismissedKeys] = useState<string[]>([]);
@@ -138,20 +149,58 @@ export function useRewardTooltipConsistency({
if (!cacheKey || !workspaceId || !isAiRewardEvent(event)) {
setSuggestions([]);
+ setStatus("idle");
setActiveIndex(0);
return;
}
const cached = reviewCache.get(cacheKey);
if (cached) {
- setSuggestions(cached);
+ setSuggestions(cached.suggestions);
+ setStatus("idle");
setActiveIndex(0);
return;
}
setSuggestions([]);
+ setStatus("idle");
setActiveIndex(0);
const timeout = window.setTimeout(async () => {
+ let flagged: boolean | null = null;
+
+ try {
+ const screen = await screenRewardTooltipContradiction({
+ workspaceId,
+ event,
+ tooltip,
+ modifiers: serializedModifiers,
+ });
+
+ if (requestId !== requestIdRef.current) {
+ return;
+ }
+
+ flagged = screen.flagged;
+ } catch {
+ if (requestId !== requestIdRef.current) {
+ return;
+ }
+
+ flagged = null;
+ }
+
+ if (flagged === false) {
+ reviewCache.set(cacheKey, { flagged: false, suggestions: [] });
+ setSuggestions([]);
+ setStatus("idle");
+ setActiveIndex(0);
+ return;
+ }
+
+ if (flagged === true) {
+ setStatus("reviewing");
+ }
+
try {
const result = await reviewRewardTooltipConsistency({
workspaceId,
@@ -165,8 +214,9 @@ export function useRewardTooltipConsistency({
}
const next = result.suggestions ?? [];
- reviewCache.set(cacheKey, next);
+ reviewCache.set(cacheKey, { flagged: true, suggestions: next });
setSuggestions(next);
+ setStatus("idle");
setActiveIndex(0);
} catch {
if (requestId !== requestIdRef.current) {
@@ -174,6 +224,7 @@ export function useRewardTooltipConsistency({
}
setSuggestions([]);
+ setStatus("idle");
setActiveIndex(0);
}
}, DEBOUNCE_MS);
@@ -363,6 +414,7 @@ export function useRewardTooltipConsistency({
}, [dismissAll, hide]);
return {
+ status,
suggestions: visibleSuggestions,
pages,
activeIndex,