Skip to content

Commit 5fa7771

Browse files
authored
Fix read status for initial Gmail sync (#336)
1 parent a33dcd5 commit 5fa7771

1 file changed

Lines changed: 88 additions & 35 deletions

File tree

‎connectors/google/src/mail/sync.ts‎

Lines changed: 88 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,13 @@
1616
* references back to the concrete connector's spied instance methods — or it
1717
* returns a descriptor and lets the caller own the scheduling.
1818
*/
19-
19+
import { enrichLinkContactsFromGoogle } from "@plotday/google-contacts";
2020
import {
2121
type CreateLinkDraft,
2222
type NoteWriteBackResult,
2323
resolveOutboundReplyRecipients,
2424
} from "@plotday/twister";
25+
import type { Cta } from "@plotday/twister/facets";
2526
import { ActionType } from "@plotday/twister/plot";
2627
import type {
2728
Actor,
@@ -32,18 +33,15 @@ import type {
3233
Thread,
3334
} from "@plotday/twister/plot";
3435
import type { WebhookRequest } from "@plotday/twister/tools/network";
35-
import type { Cta } from "@plotday/twister/facets";
36-
37-
import { enrichLinkContactsFromGoogle } from "@plotday/google-contacts";
3836

3937
import {
38+
type AttachmentData,
4039
GmailApi,
4140
GmailApiError,
42-
UserInfoError,
4341
type GmailMessage,
4442
type GmailThread,
45-
type AttachmentData,
4643
type SyncState,
44+
UserInfoError,
4745
buildForwardMessage,
4846
buildNewEmailMessage,
4947
buildReactionMessage,
@@ -63,7 +61,10 @@ import {
6361
transformGmailThread,
6462
} from "./gmail-api";
6563
import { gmailFacets } from "./gmail-facets";
66-
import { classifySendError, type ClassifiedSendError } from "./gmail-send-errors";
64+
import {
65+
type ClassifiedSendError,
66+
classifySendError,
67+
} from "./gmail-send-errors";
6768

6869
// ---------------------------------------------------------------------------
6970
// Persisted state shapes (shared with the connector)
@@ -508,7 +509,9 @@ export function mergePendingThreads(
508509
const attempts = (attemptsById.get(id) ?? 0) + 1;
509510
if (attempts > MAX_THREAD_FETCH_ATTEMPTS) {
510511
console.error(
511-
`[gmail] giving up on thread ${id} after ${attempts - 1} failed fetch attempts; its change may be lost`
512+
`[gmail] giving up on thread ${id} after ${
513+
attempts - 1
514+
} failed fetch attempts; its change may be lost`
512515
);
513516
continue;
514517
}
@@ -648,7 +651,9 @@ export async function findChannelForMessageFn(
648651
if (!token?.token) continue;
649652
const api = new GmailApi(token.token);
650653
// Probe with minimal format (just confirms the message exists for this auth)
651-
await api.call(`/messages/${messageId}`, { params: { format: "minimal" } });
654+
await api.call(`/messages/${messageId}`, {
655+
params: { format: "minimal" },
656+
});
652657
// Found it — cache and return
653658
await host.set(`gmail:msg-channel:${messageId}`, channelId);
654659
return channelId;
@@ -840,8 +845,9 @@ export async function setupMailboxWebhookFn(
840845
// Seed the incremental cursor so the first webhook has somewhere to
841846
// start. Gmail's watch returns the current historyId; any change after
842847
// this point will appear in history.list from this seed.
843-
const existingIncremental =
844-
await host.get<{ historyId?: string }>("incremental_state");
848+
const existingIncremental = await host.get<{ historyId?: string }>(
849+
"incremental_state"
850+
);
845851
if (!existingIncremental?.historyId) {
846852
await host.set("incremental_state", {
847853
historyId: watchResult.historyId,
@@ -1436,12 +1442,10 @@ export async function processEmailThreadsFn(
14361442
// message (hundreds per pass), which dominated the pass's wall-clock time.
14371443
const messageChannelEntries: [string, unknown][] = transformed.flatMap(
14381444
({ thread, channelId }) =>
1439-
(thread.messages ?? []).map(
1440-
(message): [string, unknown] => [
1441-
`gmail:msg-channel:${message.id}`,
1442-
channelId,
1443-
]
1444-
)
1445+
(thread.messages ?? []).map((message): [string, unknown] => [
1446+
`gmail:msg-channel:${message.id}`,
1447+
channelId,
1448+
])
14451449
);
14461450
if (messageChannelEntries.length > 0) {
14471451
await host.setMany(messageChannelEntries);
@@ -1493,7 +1497,7 @@ async function saveTransformedThread(
14931497
thread.messages?.some((m) => m.labelIds?.includes("UNREAD")) ?? false;
14941498

14951499
if (initialSync) {
1496-
plotThread.unread = false;
1500+
plotThread.unread = isUnread;
14971501
plotThread.archived = false;
14981502
await host.set(`unread:${thread.id}`, isUnread);
14991503
} else {
@@ -2029,7 +2033,10 @@ export async function onNoteCreatedFn(
20292033
attachments: attachments.length > 0 ? attachments : undefined,
20302034
});
20312035

2032-
const sent = await sendWithRetry(() => api.sendMessage(raw, threadId), "reply");
2036+
const sent = await sendWithRetry(
2037+
() => api.sendMessage(raw, threadId),
2038+
"reply"
2039+
);
20332040
if (!sent.ok) {
20342041
// Surface the failure to the user (thread goes unread + "Failed to send"
20352042
// affordance). Do NOT set the idempotency guard, so an explicit retry
@@ -2091,7 +2098,8 @@ export async function sendCalendarEventReplyFn(
20912098
const allowed = new Set<ActorId>(note.accessContacts);
20922099
accessContactEmails = new Set<string>();
20932100
for (const c of thread.accessContacts ?? []) {
2094-
if (allowed.has(c.id) && c.email) accessContactEmails.add(c.email.toLowerCase());
2101+
if (allowed.has(c.id) && c.email)
2102+
accessContactEmails.add(c.email.toLowerCase());
20952103
}
20962104
}
20972105

@@ -2104,9 +2112,16 @@ export async function sendCalendarEventReplyFn(
21042112
});
21052113

21062114
if (to.length === 0 && cc.length === 0 && bcc.length === 0) {
2107-
const choseOthers = (note.accessContacts ?? []).some((id) => id !== note.author.id);
2115+
const choseOthers = (note.accessContacts ?? []).some(
2116+
(id) => id !== note.author.id
2117+
);
21082118
if (choseOthers) {
2109-
return { deliveryError: { code: "no_recipients", message: "This reply had no deliverable recipients." } };
2119+
return {
2120+
deliveryError: {
2121+
code: "no_recipients",
2122+
message: "This reply had no deliverable recipients.",
2123+
},
2124+
};
21102125
}
21112126
return; // private note or empty roster
21122127
}
@@ -2123,7 +2138,10 @@ export async function sendCalendarEventReplyFn(
21232138
const bccHeaders = bcc.map((a) => formatFromHeader(a.address, a.name));
21242139

21252140
const stateKey = `cal-reply:${iCalUID}`;
2126-
const prior = await host.get<{ gmailThreadId: string; seedMessageId: string }>(stateKey);
2141+
const prior = await host.get<{
2142+
gmailThreadId: string;
2143+
seedMessageId: string;
2144+
}>(stateKey);
21272145

21282146
let sentId: string;
21292147
if (!prior) {
@@ -2132,24 +2150,53 @@ export async function sendCalendarEventReplyFn(
21322150
// one in verbatim produces a double-`@` malformed Message-ID. The
21332151
// X-Plot-Event-UID header below still carries the raw iCalUID unchanged
21342152
// — only this synthetic Message-ID needs to be token-safe.
2135-
const seedMessageId = `<plot-cal-${iCalUID.replace(/[^A-Za-z0-9._-]/g, "-")}-${note.id}@plot.day>`;
2153+
const seedMessageId = `<plot-cal-${iCalUID.replace(
2154+
/[^A-Za-z0-9._-]/g,
2155+
"-"
2156+
)}-${note.id}@plot.day>`;
21362157
const raw = buildNewEmailMessage({
2137-
to: toHeaders, cc: ccHeaders, bcc: bccHeaders, from, subject, body: note.content ?? "",
2158+
to: toHeaders,
2159+
cc: ccHeaders,
2160+
bcc: bccHeaders,
2161+
from,
2162+
subject,
2163+
body: note.content ?? "",
21382164
extraHeaders: [`Message-ID: ${seedMessageId}`, uidHeader],
21392165
});
2140-
const sent = await sendWithRetry(() => api.sendNewMessage(raw), "cal-reply");
2141-
if (!sent.ok) return { deliveryError: { code: sent.error.code, message: sent.error.message } };
2166+
const sent = await sendWithRetry(
2167+
() => api.sendNewMessage(raw),
2168+
"cal-reply"
2169+
);
2170+
if (!sent.ok)
2171+
return {
2172+
deliveryError: { code: sent.error.code, message: sent.error.message },
2173+
};
21422174
sentId = sent.result.id;
2143-
await host.set(stateKey, { gmailThreadId: sent.result.threadId, seedMessageId });
2175+
await host.set(stateKey, {
2176+
gmailThreadId: sent.result.threadId,
2177+
seedMessageId,
2178+
});
21442179
await host.set(`sent:${sentId}`, true);
21452180
} else {
21462181
const raw = buildReplyMessage({
2147-
to: toHeaders, cc: ccHeaders, bcc: bccHeaders, from, subject, body: note.content ?? "",
2148-
messageId: prior.seedMessageId, references: prior.seedMessageId,
2182+
to: toHeaders,
2183+
cc: ccHeaders,
2184+
bcc: bccHeaders,
2185+
from,
2186+
subject,
2187+
body: note.content ?? "",
2188+
messageId: prior.seedMessageId,
2189+
references: prior.seedMessageId,
21492190
extraHeaders: [uidHeader],
21502191
});
2151-
const sent = await sendWithRetry(() => api.sendMessage(raw, prior.gmailThreadId), "cal-reply");
2152-
if (!sent.ok) return { deliveryError: { code: sent.error.code, message: sent.error.message } };
2192+
const sent = await sendWithRetry(
2193+
() => api.sendMessage(raw, prior.gmailThreadId),
2194+
"cal-reply"
2195+
);
2196+
if (!sent.ok)
2197+
return {
2198+
deliveryError: { code: sent.error.code, message: sent.error.message },
2199+
};
21532200
sentId = sent.result.id;
21542201
await host.set(`sent:${sentId}`, true);
21552202
}
@@ -2416,7 +2463,11 @@ async function fetchOriginalAttachments(
24162463
const binary = atob(padded);
24172464
const bytes = new Uint8Array(binary.length);
24182465
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
2419-
attachments.push({ fileName: part.fileName, mimeType: part.mimeType, data: bytes });
2466+
attachments.push({
2467+
fileName: part.fileName,
2468+
mimeType: part.mimeType,
2469+
data: bytes,
2470+
});
24202471
} catch (err) {
24212472
console.error(
24222473
`[gmail] onCreateLink(forward): failed to fetch attachment ${part.partId} on message ${messageId}:`,
@@ -2479,7 +2530,8 @@ async function onCreateLinkForwardFn(
24792530
else if (role === "bcc") bcc.push(formatted);
24802531
else to.push(formatted);
24812532
};
2482-
for (const r of draft.recipients ?? []) addRecipient(r.externalAccountId, r.role, r.name);
2533+
for (const r of draft.recipients ?? [])
2534+
addRecipient(r.externalAccountId, r.role, r.name);
24832535
for (const email of draft.inviteEmails ?? []) addRecipient(email, null, null);
24842536

24852537
if (to.length + cc.length + bcc.length === 0) {
@@ -2670,7 +2722,8 @@ export async function onCreateLinkFn(
26702722
else toEmails.push(formatted);
26712723
};
26722724

2673-
for (const r of draft.recipients ?? []) addRecipient(r.externalAccountId, r.role, r.name);
2725+
for (const r of draft.recipients ?? [])
2726+
addRecipient(r.externalAccountId, r.role, r.name);
26742727
for (const email of draft.inviteEmails ?? []) addRecipient(email, null, null);
26752728

26762729
if (toEmails.length + ccEmails.length + bccEmails.length === 0) {

0 commit comments

Comments
 (0)