Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/web/app/api/outlook/webhook/process-history-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export async function processHistoryItem(
message: {
id: messageId,
threadId: resourceData.conversationId || messageId,
conversationIndex: message.conversationIndex || undefined,
headers: {
from,
to: to.join(","),
Expand Down Expand Up @@ -216,6 +217,7 @@ export async function processHistoryItem(
message: {
id: messageId,
threadId: resourceData.conversationId || messageId,
conversationIndex: message.conversationIndex || undefined,
headers: {
from,
to: to.join(","),
Expand Down Expand Up @@ -280,6 +282,7 @@ async function handleOutbound(
const parsedMessage = {
id: messageId,
threadId: conversationId || messageId,
conversationIndex: message.conversationIndex || undefined,
headers: messageHeaders,
snippet: message.bodyPreview || "",
historyId: message.id || messageId,
Expand Down
17 changes: 14 additions & 3 deletions apps/web/app/api/scheduled-actions/execute/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { markQStashActionAsExecuting } from "@/utils/scheduled-actions/scheduler
import { executeScheduledAction } from "@/utils/scheduled-actions/executor";
import prisma from "@/utils/prisma";
import { ScheduledActionStatus } from "@prisma/client";
import { createEmailProvider } from "@/utils/email/provider";

const logger = createScopedLogger("scheduled-actions-executor");

Expand Down Expand Up @@ -46,7 +47,11 @@ export const POST = verifySignatureAppRouter(
const scheduledAction = await prisma.scheduledAction.findUnique({
where: { id: payload.scheduledActionId },
include: {
emailAccount: true,
emailAccount: {
include: {
account: true,
},
},
executedRule: true,
},
});
Expand Down Expand Up @@ -85,8 +90,14 @@ export const POST = verifySignatureAppRouter(
return new Response("Action already being processed", { status: 200 });
}

// Execute the action
const executionResult = await executeScheduledAction(scheduledAction);
const provider = await createEmailProvider({
emailAccountId: scheduledAction.emailAccountId,
provider: scheduledAction.emailAccount.account.provider,
});
const executionResult = await executeScheduledAction(
scheduledAction,
provider,
);

if (executionResult.success) {
logger.info("Successfully executed QStash scheduled action", {
Expand Down
8 changes: 7 additions & 1 deletion apps/web/utils/ai/choose-rule/match-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { extractEmailAddress } from "@/utils/email";
import { hasIcsAttachment } from "@/utils/parse/calender-event";
import { checkSenderReplyHistory } from "@/utils/reply-tracker/check-sender-reply-history";
import type { EmailProvider } from "@/utils/email/provider";
import { isReplyInThread } from "@/utils/thread";

const logger = createScopedLogger("match-rules");

Expand Down Expand Up @@ -231,7 +232,12 @@ async function findMatchingRuleWithReasons(
matchReasons?: MatchReason[];
reason?: string;
}> {
const isThread = message.isReplyInThread;
const isThread = isReplyInThread(
message.id,
message.threadId,
message.conversationIndex,
);

const { match, matchReasons, potentialMatches } =
await findPotentialMatchingRules({
rules,
Expand Down
1 change: 0 additions & 1 deletion apps/web/utils/mail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export function parseMessage(
...parsed,
subject: parsed.headers?.subject || "",
date: parsed.headers?.date || "",
isReplyInThread: !!(parsed.id && parsed.id !== parsed.threadId),
};
}

Expand Down
10 changes: 4 additions & 6 deletions apps/web/utils/outlook/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const logger = createScopedLogger("outlook/message");
// Cache for folder IDs
let folderIdCache: Record<string, string> | null = null;

function isOutlookReplyInThread(
export function isOutlookReplyInThread(
conversationIndex?: string | undefined,
): boolean {
try {
Expand Down Expand Up @@ -287,9 +287,7 @@ async function convertMessages(
return {
id: message.id || "",
threadId: message.conversationId || "",
isReplyInThread: isOutlookReplyInThread(
message.conversationIndex || "",
),
conversationIndex: message.conversationIndex || undefined,
snippet: message.bodyPreview || "",
textPlain: message.body?.content || "",
textHtml: message.body?.content || "",
Expand Down Expand Up @@ -327,7 +325,7 @@ export async function getMessage(
return {
id: message.id || "",
threadId: message.conversationId || "",
isReplyInThread: isOutlookReplyInThread(message.conversationIndex || ""),
conversationIndex: message.conversationIndex || "",
snippet: message.bodyPreview || "",
textPlain: message.body?.content || "",
textHtml: message.body?.content || "",
Expand Down Expand Up @@ -386,7 +384,7 @@ function parseOutlookMessage(
return {
id: message.id || "",
threadId: message.conversationId || "",
isReplyInThread: atob(message.conversationIndex || "").length > 22,
conversationIndex: message.conversationIndex || "",
snippet: message.bodyPreview || "",
textPlain: message.body?.content || "",
headers: {
Expand Down
50 changes: 22 additions & 28 deletions apps/web/utils/scheduled-actions/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,18 @@ import type { ActionItem, EmailForAction } from "@/utils/ai/types";
import type { ParsedMessage } from "@/utils/types";
import { getMessage } from "@/utils/gmail/message";
import { parseMessage } from "@/utils/mail";
import { createEmailProvider } from "@/utils/email/provider";
import type { EmailProvider } from "@/utils/email/provider";

const logger = createScopedLogger("scheduled-actions-executor");

/**
* Execute a scheduled action
*/
export async function executeScheduledAction(scheduledAction: ScheduledAction) {
export async function executeScheduledAction(
scheduledAction: ScheduledAction,
client: EmailProvider,
) {
logger.info("Executing scheduled action", {
scheduledActionId: scheduledAction.id,
actionType: scheduledAction.actionType,
Expand All @@ -37,16 +42,8 @@ export async function executeScheduledAction(scheduledAction: ScheduledAction) {
throw new Error("Email account not found");
}

// Get Gmail client
const gmail = await getGmailClientWithRefresh({
accessToken: emailAccount.tokens.access_token,
refreshToken: emailAccount.tokens.refresh_token,
expiresAt: emailAccount.tokens.expires_at,
emailAccountId: emailAccount.id,
});

// Validate email still exists and get current state
const emailMessage = await validateEmailState(gmail, scheduledAction);
const emailMessage = await validateEmailState(client, scheduledAction);
if (!emailMessage) {
await markActionCompleted(
scheduledAction.id,
Expand All @@ -71,7 +68,7 @@ export async function executeScheduledAction(scheduledAction: ScheduledAction) {

// Execute the action
const executedAction = await executeDelayedAction({
gmail,
client,
actionItem,
emailMessage,
emailAccount: {
Expand Down Expand Up @@ -108,11 +105,11 @@ export async function executeScheduledAction(scheduledAction: ScheduledAction) {
* Validate that the email still exists and return current state
*/
async function validateEmailState(
gmail: gmail_v1.Gmail,
client: EmailProvider,
scheduledAction: ScheduledAction,
): Promise<EmailForAction | null> {
try {
const message = await getMessage(scheduledAction.messageId, gmail, "full");
const message = await client.getMessage(scheduledAction.messageId);

if (!message) {
logger.info("Email no longer exists", {
Expand All @@ -122,23 +119,18 @@ async function validateEmailState(
return null;
}

// Parse the message to get the correct format
const parsedMessage = parseMessage(message);

// Convert to EmailForAction format
const emailForAction: EmailForAction = {
threadId: parsedMessage.threadId,
id: parsedMessage.id,
headers: parsedMessage.headers,
textPlain: parsedMessage.textPlain || "",
textHtml: parsedMessage.textHtml || "",
attachments: parsedMessage.attachments || [],
internalDate: parsedMessage.internalDate,
threadId: message.threadId,
id: message.id,
headers: message.headers,
textPlain: message.textPlain || "",
textHtml: message.textHtml || "",
attachments: message.attachments || [],
internalDate: message.internalDate,
};

return emailForAction;
} catch (error: unknown) {
// Check for Gmail's standard "not found" error message
if (
error instanceof Error &&
error.message === "Requested entity was not found."
Expand All @@ -158,13 +150,13 @@ async function validateEmailState(
* Execute the delayed action using existing action execution logic
*/
async function executeDelayedAction({
gmail,
client,
actionItem,
emailMessage,
emailAccount,
scheduledAction,
}: {
gmail: gmail_v1.Gmail;
client: EmailProvider;
actionItem: ActionItem;
emailMessage: EmailForAction;
emailAccount: { email: string; userId: string; id: string };
Expand Down Expand Up @@ -210,6 +202,8 @@ async function executeDelayedAction({
snippet: "",
historyId: "",
inline: [],
subject: emailMessage.headers.subject || "",
date: emailMessage.headers.date || new Date().toISOString(),
};

logger.info("Executing delayed action", {
Expand All @@ -220,7 +214,7 @@ async function executeDelayedAction({

// Execute the specific action directly using runActionFunction
await runActionFunction({
gmail,
client,
email: parsedMessage,
action: executedAction,
userEmail: emailAccount.email,
Expand Down
14 changes: 14 additions & 0 deletions apps/web/utils/thread.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { isOutlookReplyInThread } from "@/utils/outlook/message";

// The first message id in a thread is the threadId
export function isReplyInThread(
messageId: string,
threadId: string,
conversationIndex: string | undefined,
): boolean {
if (conversationIndex) {
return isOutlookReplyInThread(conversationIndex);
} else {
return !!(messageId && messageId !== threadId);
}
}
2 changes: 1 addition & 1 deletion apps/web/utils/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export type ThreadWithPayloadMessages = gmail_v1.Schema$Thread & {
export interface ParsedMessage extends gmail_v1.Schema$Message {
id: string;
threadId: string;
isReplyInThread: boolean;
conversationIndex?: string;
labelIds?: string[];
snippet: string;
historyId: string;
Expand Down
Loading