Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: harden messenger support email flow

Richie McIlroyc27ff2a3cfc2
diff --git a/apps/web/__tests__/unit/messenger-agent.test.ts b/apps/web/__tests__/unit/messenger-agent.test.ts
index 016dcf976..5629b8b4d 100644
--- a/apps/web/__tests__/unit/messenger-agent.test.ts
+++ b/apps/web/__tests__/unit/messenger-agent.test.ts
@@ -122,7 +122,7 @@ describe("generateMessengerAgentReply", () => {
expect(fetchMock).toHaveBeenCalledTimes(2);
const firstBody = readFetchBody(fetchMock.mock.calls[0] ?? []);
expect(firstBody.model).toBe("claude-sonnet-5");
- expect(firstBody.max_tokens).toBe(350);
+ expect(firstBody.max_tokens).toBe(512);
expect(firstBody.tools?.[0]?.name).toBe("send_support_email");
expect(firstBody.tools?.[0]?.input_schema?.properties?.email).toBe(
undefined,
@@ -133,6 +133,7 @@ describe("generateMessengerAgentReply", () => {
});
const secondBody = readFetchBody(fetchMock.mock.calls[1] ?? []);
+ expect(secondBody.max_tokens).toBe(350);
const toolResultMessage = secondBody.messages?.at(-1);
expect(toolResultMessage?.role).toBe("user");
expect(toolResultMessage?.content).toEqual([
@@ -144,4 +145,76 @@ describe("generateMessengerAgentReply", () => {
},
]);
});
+
+ it("returns a tool error result when the support email tool fails", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ content: [
+ {
+ type: "tool_use",
+ id: "tool-1",
+ name: "send_support_email",
+ input: {
+ subject: "Upload issue",
+ message: "The user cannot upload their recording.",
+ },
+ },
+ ],
+ }),
+ { status: 200 },
+ ),
+ )
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ content: [
+ {
+ type: "text",
+ text: "I couldn't send that to the team right now. Please email [email protected] directly.",
+ },
+ ],
+ }),
+ { status: 200 },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const execute = vi.fn().mockRejectedValue(new Error("provider failed"));
+ const { generateMessengerAgentReply } = await import(
+ "@/lib/messenger/agent"
+ );
+
+ const result = await generateMessengerAgentReply({
+ userIdentity: "Test User <[email protected]>",
+ identityTag: "user:user-123",
+ query: "Please send this to support",
+ history: [
+ {
+ role: "user",
+ content: "Uploads keep failing. Please send this to support.",
+ },
+ ],
+ supportEmailTool: {
+ execute,
+ },
+ });
+
+ expect(result).toBe(
+ "I couldn't send that to the team right now. Please email [email protected] directly.",
+ );
+
+ const secondBody = readFetchBody(fetchMock.mock.calls[1] ?? []);
+ const toolResultMessage = secondBody.messages?.at(-1);
+ expect(toolResultMessage?.content).toEqual([
+ {
+ type: "tool_result",
+ tool_use_id: "tool-1",
+ content: "Failed to send support email.",
+ is_error: true,
+ },
+ ]);
+ });
});
diff --git a/apps/web/__tests__/unit/messenger-support-email.test.ts b/apps/web/__tests__/unit/messenger-support-email.test.ts
index ca609165b..64b48e828 100644
--- a/apps/web/__tests__/unit/messenger-support-email.test.ts
+++ b/apps/web/__tests__/unit/messenger-support-email.test.ts
@@ -2,6 +2,7 @@ import { User } from "@cap/web-domain";
import { beforeEach, describe, expect, it, vi } from "vitest";
const whereMock = vi.hoisted(() => vi.fn());
+const forUpdateMock = vi.hoisted(() => vi.fn());
const valuesMock = vi.hoisted(() => vi.fn());
const sendEmailMock = vi.hoisted(() => vi.fn());
const messengerSupportEmailMock = vi.hoisted(() => vi.fn(() => null));
@@ -10,8 +11,10 @@ const mockDb = vi.hoisted(() => ({
select: vi.fn(() => mockDb),
from: vi.fn(() => mockDb),
where: whereMock,
+ for: forUpdateMock,
insert: vi.fn(() => mockDb),
values: valuesMock,
+ transaction: vi.fn((callback: (tx: unknown) => unknown) => callback(mockDb)),
}));
vi.mock("server-only", () => ({}));
@@ -29,6 +32,9 @@ vi.mock("@cap/database/schema", () => ({
userId: "userId",
createdAt: "createdAt",
},
+ users: {
+ id: "id",
+ },
}));
vi.mock("@cap/database/emails/config", () => ({
@@ -50,11 +56,12 @@ describe("sendMessengerSupportEmail", () => {
beforeEach(() => {
vi.clearAllMocks();
valuesMock.mockResolvedValue(undefined);
+ forUpdateMock.mockResolvedValue([{ id: "user-123" }]);
sendEmailMock.mockResolvedValue(undefined);
});
it("sends support email from account context and records the send", async () => {
- whereMock.mockResolvedValueOnce([{ value: 1 }]);
+ whereMock.mockReturnValueOnce(mockDb).mockResolvedValueOnce([{ value: 1 }]);
const { sendMessengerSupportEmail } = await import(
"@/lib/messenger/support-email"
);
@@ -75,6 +82,7 @@ describe("sendMessengerSupportEmail", () => {
status: "sent",
remainingToday: 0,
});
+ expect(forUpdateMock).toHaveBeenCalledWith("update");
expect(messengerSupportEmailMock).toHaveBeenCalledWith({
userEmail: "[email protected]",
userName: "Test User",
@@ -100,10 +108,16 @@ describe("sendMessengerSupportEmail", () => {
createdAt: new Date("2026-06-30T18:00:00.000Z"),
}),
);
+ const insertCallOrder = valuesMock.mock.invocationCallOrder[0];
+ const sendCallOrder = sendEmailMock.mock.invocationCallOrder[0];
+ if (insertCallOrder === undefined || sendCallOrder === undefined) {
+ throw new Error("Expected insert and send call order");
+ }
+ expect(insertCallOrder).toBeLessThan(sendCallOrder);
});
it("does not send after two support emails in the same UTC day", async () => {
- whereMock.mockResolvedValueOnce([{ value: 2 }]);
+ whereMock.mockReturnValueOnce(mockDb).mockResolvedValueOnce([{ value: 2 }]);
const { sendMessengerSupportEmail } = await import(
"@/lib/messenger/support-email"
);
@@ -127,4 +141,28 @@ describe("sendMessengerSupportEmail", () => {
expect(sendEmailMock).not.toHaveBeenCalled();
expect(valuesMock).not.toHaveBeenCalled();
});
+
+ it("does not send when the audit reservation fails", async () => {
+ whereMock.mockReturnValueOnce(mockDb).mockResolvedValueOnce([{ value: 1 }]);
+ valuesMock.mockRejectedValueOnce(new Error("insert failed"));
+ const { sendMessengerSupportEmail } = await import(
+ "@/lib/messenger/support-email"
+ );
+
+ await expect(
+ sendMessengerSupportEmail({
+ user: {
+ id: User.UserId.make("user-123"),
+ email: "[email protected]",
+ name: "Test User",
+ },
+ conversationId: "conversation-123",
+ subject: "Upload issue",
+ message: "Uploads keep failing.",
+ now: new Date("2026-06-30T18:00:00.000Z"),
+ }),
+ ).rejects.toThrow("insert failed");
+
+ expect(sendEmailMock).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/web/lib/messenger/agent.ts b/apps/web/lib/messenger/agent.ts
index b705d13b8..61ca34fd4 100644
--- a/apps/web/lib/messenger/agent.ts
+++ b/apps/web/lib/messenger/agent.ts
@@ -53,6 +53,7 @@ type AnthropicToolResultBlock = {
const MESSENGER_ANTHROPIC_MODEL = "claude-sonnet-5";
const MESSENGER_MAX_TOKENS = 350;
+const MESSENGER_TOOL_DISPATCH_MAX_TOKENS = 512;
const normalizeContext = (sections: string[]) =>
sections
@@ -227,12 +228,21 @@ const executeSupportEmailToolUse = async ({
};
}
- const result = await supportEmailTool.execute(input);
- return {
- type: "tool_result",
- tool_use_id: toolUse.id,
- content: formatSupportEmailToolResult(result),
- };
+ try {
+ const result = await supportEmailTool.execute(input);
+ return {
+ type: "tool_result",
+ tool_use_id: toolUse.id,
+ content: formatSupportEmailToolResult(result),
+ };
+ } catch {
+ return {
+ type: "tool_result",
+ tool_use_id: toolUse.id,
+ content: "Failed to send support email.",
+ is_error: true,
+ };
+ }
};
const postAnthropicMessages = async ({
@@ -240,6 +250,7 @@ const postAnthropicMessages = async ({
systemPrompt,
messages,
tools,
+ maxTokens = MESSENGER_MAX_TOKENS,
}: {
key: string;
systemPrompt: string;
@@ -248,6 +259,7 @@ const postAnthropicMessages = async ({
content: string | AnthropicResponseBlock[] | AnthropicToolResultBlock[];
}>;
tools?: [typeof supportEmailToolDefinition];
+ maxTokens?: number;
}) => {
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
@@ -259,7 +271,7 @@ const postAnthropicMessages = async ({
body: JSON.stringify({
model: MESSENGER_ANTHROPIC_MODEL,
temperature: 0.65,
- max_tokens: MESSENGER_MAX_TOKENS,
+ max_tokens: maxTokens,
system: systemPrompt,
messages,
tools,
@@ -293,11 +305,16 @@ const callAnthropic = async ({
systemPrompt,
messages: mapHistoryForLlm(history),
tools: supportEmailTool ? [supportEmailToolDefinition] : undefined,
+ maxTokens: supportEmailTool
+ ? MESSENGER_TOOL_DISPATCH_MAX_TOKENS
+ : MESSENGER_MAX_TOKENS,
});
if (!initial) return null;
const toolUses = supportEmailTool
- ? initial.content.filter((block) => block.type === "tool_use")
+ ? initial.content.filter(
+ (block): block is AnthropicToolUseBlock => block.type === "tool_use",
+ )
: [];
if (!supportEmailTool || toolUses.length === 0) {
@@ -339,10 +356,13 @@ const callAnthropic = async ({
});
if (final?.text) return final.text;
- const firstToolResult = toolResults[0]?.content ?? "";
- if (firstToolResult.includes("Support email sent")) {
+ const firstToolResult = toolResults[0];
+ if (firstToolResult?.content.includes("Support email sent")) {
return "Done, I sent that to the team from your account email. We'll follow up with you there.";
}
+ if (firstToolResult?.is_error) {
+ return "I couldn't send that to the team right now. Please email [email protected] directly.";
+ }
return "I couldn't send another support email from your account today. You're limited to 2 per day, but you can still email [email protected] directly.";
};
diff --git a/apps/web/lib/messenger/support-email.ts b/apps/web/lib/messenger/support-email.ts
index 5d3f03fe5..d09b8219f 100644
--- a/apps/web/lib/messenger/support-email.ts
+++ b/apps/web/lib/messenger/support-email.ts
@@ -4,7 +4,7 @@ import { db } from "@cap/database";
import { sendEmail } from "@cap/database/emails/config";
import { MessengerSupportEmail } from "@cap/database/emails/messenger-support-email";
import { nanoId } from "@cap/database/helpers";
-import { messengerSupportEmails } from "@cap/database/schema";
+import { messengerSupportEmails, users } from "@cap/database/schema";
import type { User } from "@cap/web-domain";
import { and, count, eq, gte } from "drizzle-orm";
@@ -50,25 +50,59 @@ export const sendMessengerSupportEmail = async ({
throw new Error("Support email message is empty");
}
- const [row] = await db()
- .select({ value: count() })
- .from(messengerSupportEmails)
- .where(
- and(
- eq(messengerSupportEmails.userId, user.id),
- gte(
- messengerSupportEmails.createdAt,
- getMessengerSupportEmailDayStart(now),
+ const reserved = await db().transaction(async (tx) => {
+ const [lockedUser] = await tx
+ .select({ id: users.id })
+ .from(users)
+ .where(eq(users.id, user.id))
+ .for("update");
+
+ if (!lockedUser) {
+ throw new Error("Support email user not found");
+ }
+
+ const [row] = await tx
+ .select({ value: count() })
+ .from(messengerSupportEmails)
+ .where(
+ and(
+ eq(messengerSupportEmails.userId, user.id),
+ gte(
+ messengerSupportEmails.createdAt,
+ getMessengerSupportEmailDayStart(now),
+ ),
),
- ),
- );
- const sentToday = row?.value ?? 0;
+ );
+ const sentToday = row?.value ?? 0;
+
+ if (sentToday >= MESSENGER_SUPPORT_EMAIL_DAILY_LIMIT) {
+ return {
+ status: "rate_limited" as const,
+ remainingToday: 0 as const,
+ };
+ }
+
+ await tx.insert(messengerSupportEmails).values({
+ id: nanoId(),
+ conversationId,
+ userId: user.id,
+ userEmail: user.email,
+ subject: normalizedSubject,
+ message: normalizedMessage,
+ createdAt: now,
+ });
- if (sentToday >= MESSENGER_SUPPORT_EMAIL_DAILY_LIMIT) {
return {
- status: "rate_limited" as const,
- remainingToday: 0 as const,
+ status: "sent" as const,
+ remainingToday: Math.max(
+ 0,
+ MESSENGER_SUPPORT_EMAIL_DAILY_LIMIT - sentToday - 1,
+ ),
};
+ });
+
+ if (reserved.status === "rate_limited") {
+ return reserved;
}
await sendEmail({
@@ -84,21 +118,5 @@ export const sendMessengerSupportEmail = async ({
fromOverride: SUPPORT_EMAIL_FROM,
});
- await db().insert(messengerSupportEmails).values({
- id: nanoId(),
- conversationId,
- userId: user.id,
- userEmail: user.email,
- subject: normalizedSubject,
- message: normalizedMessage,
- createdAt: now,
- });
-
- return {
- status: "sent" as const,
- remainingToday: Math.max(
- 0,
- MESSENGER_SUPPORT_EMAIL_DAILY_LIMIT - sentToday - 1,
- ),
- };
+ return reserved;
};