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.

code improvements

Pedro Ladeira820f700a183a
diff --git a/apps/web/lib/ai/ai-reward-schema.ts b/apps/web/lib/ai/ai-reward-schema.ts
index 2da250448c..d28e5bce1f 100644
--- a/apps/web/lib/ai/ai-reward-schema.ts
+++ b/apps/web/lib/ai/ai-reward-schema.ts
@@ -207,6 +207,16 @@ export function getAIRewardSchema(event: AIRewardEvent) {
});
}
+export function getAICustomerSourceIds(event: AIRewardEvent) {
+ const optionIds =
+ REWARD_CONDITIONS[event].entities
+ .find(({ id }) => id === "customer")
+ ?.attributes.find(({ id }) => id === "source")
+ ?.options?.map(({ id }) => id) ?? [];
+
+ return CUSTOMER_SOURCES.filter((source) => optionIds.includes(source));
+}
+
/**
* Model structured-output envelope. Keep this free of app-level refinements so
* Output.object can stream/parse JSON even when the model picks a bad attribute;
@@ -227,10 +237,10 @@ export function getAIRewardGenerationSchema(event: AIRewardEvent) {
"When supported is false: brief explanation of what is not supported. When supported is true: null or omit.",
),
unavailableSource: z
- .enum(CUSTOMER_SOURCES)
+ .enum(getAICustomerSourceIds(event))
.nullish()
.describe(
- "When supported is false because the request needs a customer source listed under 'Unavailable option values': that option id. Otherwise null or omit.",
+ "When supported is false because the request needs a customer source listed under 'Unavailable customer sources': that option id. Otherwise null or omit.",
),
reward: buildEventRewardObjectSchema(event)
.nullish()
diff --git a/apps/web/lib/ai/generate-reward.ts b/apps/web/lib/ai/generate-reward.ts
index b5d5c8e0d4..30b3786146 100644
--- a/apps/web/lib/ai/generate-reward.ts
+++ b/apps/web/lib/ai/generate-reward.ts
@@ -20,6 +20,7 @@ import { throwIfNoPermission } from "../actions/throw-if-no-permission";
import {
AI_REWARD_EVENTS,
AIRewardGenerationOutput,
+ getAICustomerSourceIds,
getAIRewardGenerationSchema,
getAIRewardSchema,
} from "./ai-reward-schema";
@@ -32,27 +33,10 @@ const inputSchema = z.object({
function buildSystemPrompt(
event: (typeof AI_REWARD_EVENTS)[number],
- {
- programId,
- installedIntegrationIds,
- }: { programId?: string | null; installedIntegrationIds: string[] },
+ unavailableSources: (ReturnType<typeof getCustomerSourceAvailability> & {
+ id: string;
+ })[],
) {
- // Customer sources this workspace can't use (same rules as the manual builder)
- const unavailableSources = (
- REWARD_CONDITIONS[event].entities
- .find(({ id }) => id === "customer")
- ?.attributes.find(({ id }) => id === "source")?.options ?? []
- )
- .map(({ id }) => ({
- id,
- ...getCustomerSourceAvailability({
- source: id,
- programId: programId ?? undefined,
- installedIntegrationIds,
- }),
- }))
- .filter(({ hidden, missingIntegration }) => hidden || missingIntegration);
-
const entities = REWARD_CONDITIONS[event].entities.map((entity) => {
const attrs = entity.attributes
.map((attr) => {
@@ -188,16 +172,26 @@ export async function generateReward(input: z.infer<typeof inputSchema>) {
};
try {
- const generationSchema = getAIRewardGenerationSchema(event);
- const result = streamText({
- model: anthropic("claude-sonnet-4-6"),
- output: Output.object({ schema: generationSchema }),
- system: buildSystemPrompt(event, {
- programId: workspace.defaultProgramId,
+ const customerSources = getAICustomerSourceIds(event).map((id) => ({
+ id,
+ ...getCustomerSourceAvailability({
+ source: id,
+ programId: workspace.defaultProgramId ?? undefined,
installedIntegrationIds: workspace.installedIntegrations.map(
({ integrationId }) => integrationId,
),
}),
+ }));
+
+ const unavailableSources = customerSources.filter(
+ ({ hidden, missingIntegration }) => hidden || missingIntegration,
+ );
+
+ const generationSchema = getAIRewardGenerationSchema(event);
+ const result = streamText({
+ model: anthropic("claude-sonnet-4-6"),
+ output: Output.object({ schema: generationSchema }),
+ system: buildSystemPrompt(event, unavailableSources),
prompt,
temperature: 0.3,
maxOutputTokens: 2000,
@@ -276,6 +270,33 @@ export async function generateReward(input: z.infer<typeof inputSchema>) {
stream.done();
return;
}
+
+ const invalidSource = rewardParsed.data.modifiers
+ ?.flatMap(({ conditions }) => conditions)
+ .filter(
+ ({ entity, attribute }) =>
+ entity === "customer" && attribute === "source",
+ )
+ .flatMap(({ value }) => [value].flat().map(String))
+ .find((value) => {
+ const source = customerSources.find(({ id }) => id === value);
+ return !source || source.hidden || !!source.missingIntegration;
+ });
+
+ if (invalidSource) {
+ const unsupported: AIRewardGenerationOutput = {
+ supported: false,
+ reason: "This customer source isn't available for this workspace.",
+ unavailableSource: unavailableSources.find(
+ ({ id, missingIntegration }) =>
+ id === invalidSource && missingIntegration,
+ )?.id,
+ reward: null,
+ };
+ stream.update(unsupported);
+ stream.done();
+ return;
+ }
}
stream.done();
diff --git a/apps/web/tests/misc/ai-reward-schema.test.ts b/apps/web/tests/misc/ai-reward-schema.test.ts
index 603788a50b..8fdf31edd2 100644
--- a/apps/web/tests/misc/ai-reward-schema.test.ts
+++ b/apps/web/tests/misc/ai-reward-schema.test.ts
@@ -283,7 +283,7 @@ describe("getAIRewardGenerationSchema — unsupported refusal", () => {
});
it("accepts supported=false with an unavailable customer source", () => {
- const result = schema.safeParse({
+ const result = getAIRewardGenerationSchema("lead").safeParse({
supported: false,
reason: "HubSpot must be installed first.",
unavailableSource: "hubspot",
@@ -292,8 +292,19 @@ describe("getAIRewardGenerationSchema — unsupported refusal", () => {
expect(result.success).toBe(true);
});
+ it("rejects an unavailable customer source the event doesn't offer", () => {
+ for (const event of ["sale", "click"] as const) {
+ const result = getAIRewardGenerationSchema(event).safeParse({
+ supported: false,
+ unavailableSource: "hubspot",
+ reward: null,
+ });
+ expect(result.success).toBe(false);
+ }
+ });
+
it("rejects an unknown unavailable customer source", () => {
- const result = schema.safeParse({
+ const result = getAIRewardGenerationSchema("lead").safeParse({
supported: false,
unavailableSource: "salesforce",
reward: null,