Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(web): trigger welcome automation after signup contact sync (#981)
Generd68fe6059c77
diff --git a/src/web/src/lib/resend-contacts.test.ts b/src/web/src/lib/resend-contacts.test.tsindex db3d5baf2..e82b5c400 100644--- a/src/web/src/lib/resend-contacts.test.ts+++ b/src/web/src/lib/resend-contacts.test.ts@@ -58,13 +58,14 @@ describe("Resend contact lifecycle with the official SDK", () => {expect(logs.warn).not.toHaveBeenCalled()})- it("creates a definitely missing contact with the exact segment and no subscription reset", async () => {+ it("creates a missing contact with name and segment before sending its signup event", async () => {fetchMock.mockResolvedValueOnce(providerError(404, "not_found")).mockResolvedValueOnce(response({ id: "new-contact", object: "contact" }))+ .mockResolvedValueOnce(response({ object: "event", event: "new_signup" }))await expect(syncResendSignupContact(env, user)).resolves.toBeUndefined()- expect(fetchMock).toHaveBeenCalledTimes(2)+ expect(fetchMock).toHaveBeenCalledTimes(3)expect(requestAt(0)).toEqual({url: `https://api.resend.com/contacts/${user.email}`, method: "GET", body: undefined,})@@ -72,6 +73,10 @@ describe("Resend contact lifecycle with the official SDK", () => {url: "https://api.resend.com/contacts", method: "POST",body: { email: user.email, first_name: user.name, segments: [{ id: segmentId }] },})+ expect(requestAt(2)).toEqual({+ url: "https://api.resend.com/events/send", method: "POST",+ body: { event: "new_signup", contact_id: "new-contact" },+ })expect(logs.warn).not.toHaveBeenCalled()})@@ -79,10 +84,11 @@ describe("Resend contact lifecycle with the official SDK", () => {fetchMock.mockResolvedValueOnce(existingContact(unsubscribed)).mockResolvedValueOnce(response({ id: "contact-1", object: "contact" })).mockResolvedValueOnce(response({ id: segmentId }))+ if (!unsubscribed) fetchMock.mockResolvedValueOnce(response({ object: "event", event: "new_signup" }))await expect(syncResendSignupContact(env, user)).resolves.toBeUndefined()- expect(fetchMock).toHaveBeenCalledTimes(3)+ expect(fetchMock).toHaveBeenCalledTimes(unsubscribed ? 3 : 4)expect(requestAt(1)).toEqual({url: "https://api.resend.com/contacts/contact-1", method: "PATCH",body: { first_name: user.name },@@ -91,9 +97,65 @@ describe("Resend contact lifecycle with the official SDK", () => {url: `https://api.resend.com/contacts/contact-1/segments/${segmentId}`,method: "POST", body: undefined,})+ if (!unsubscribed) {+ expect(requestAt(3)).toEqual({+ url: "https://api.resend.com/events/send", method: "POST",+ body: { event: "new_signup", contact_id: "contact-1" },+ })+ }expect(logs.warn).not.toHaveBeenCalled()})+ it.each(["create", "segment"] as const)("waits for %s success before sending the event", async (stage) => {+ let complete!: (value: Response) => void+ const pending = new Promise<Response>((resolve) => { complete = resolve })+ fetchMock.mockResolvedValueOnce(stage === "create" ? providerError(404, "not_found") : existingContact())+ if (stage === "segment") fetchMock.mockResolvedValueOnce(response({ id: "contact-1" }))+ fetchMock.mockReturnValueOnce(pending)+ .mockResolvedValueOnce(response({ object: "event", event: "new_signup" }))++ const work = syncResendSignupContact(env, user)+ const beforeEvent = stage === "create" ? 2 : 3+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(beforeEvent))+ expect(fetchMock.mock.calls.some(([url]) => String(url).endsWith("/events/send"))).toBe(false)++ complete(response({ id: stage === "create" ? "new-contact" : segmentId }))+ await expect(work).resolves.toBeUndefined()+ expect(fetchMock).toHaveBeenCalledTimes(beforeEvent + 1)+ expect(requestAt(beforeEvent).body).toEqual({+ event: "new_signup", contact_id: stage === "create" ? "new-contact" : "contact-1",+ })+ })++ it.each([422, 429, 500])("logs an event rejection (%i) without retrying or failing signup sync", async (status) => {+ fetchMock.mockResolvedValueOnce(existingContact())+ .mockResolvedValueOnce(response({ id: "contact-1" }))+ .mockResolvedValueOnce(response({ id: segmentId }))+ .mockResolvedValueOnce(providerError(status))++ await expect(syncResendSignupContact(env, user)).resolves.toBeUndefined()++ expect(fetchMock).toHaveBeenCalledTimes(4)+ expect(requestAt(3).url).toBe("https://api.resend.com/events/send")+ expect(logs.warn.mock.calls).toEqual([+ ["resend_contact_sync_failed", { action: "signup", stage: "event", errorCategory: "provider_error", statusCode: status }],+ ])+ })++ it("contains an uncertain event network failure without retrying", async () => {+ fetchMock.mockResolvedValueOnce(providerError(404, "not_found"))+ .mockResolvedValueOnce(response({ id: "new-contact" }))+ .mockRejectedValueOnce(new Error(privateError))++ await expect(syncResendSignupContact(env, user)).resolves.toBeUndefined()++ expect(fetchMock).toHaveBeenCalledTimes(3)+ expect(requestAt(2).url).toBe("https://api.resend.com/events/send")+ expect(logs.warn.mock.calls).toEqual([+ ["resend_contact_sync_failed", { action: "signup", stage: "event", errorCategory: "provider_error" }],+ ])+ })+it.each([[429, "rate_limit_exceeded"], [404, "validation_error"]])("does not create after an uncertain lookup error (%i %s)", async (status, name) => {fetchMock.mockResolvedValueOnce(providerError(status, name))diff --git a/src/web/src/lib/resend-contacts.ts b/src/web/src/lib/resend-contacts.tsindex 1b762c431..33096006f 100644--- a/src/web/src/lib/resend-contacts.ts+++ b/src/web/src/lib/resend-contacts.ts@@ -5,7 +5,7 @@ const log = createLogger({ service: "resend-contacts" })const NEW_SIGNUPS_SEGMENT_ID = "6701946e-a7e2-442b-8fa5-aba379a81248"type ContactAction = "signup" | "account-deletion"-type ContactStage = "lookup" | "create" | "update" | "segment"+type ContactStage = "lookup" | "create" | "update" | "segment" | "event"function logProviderFailure(action: ContactAction,@@ -31,6 +31,7 @@ export async function syncResendSignupContact(try {const resend = new Resend(env.RESEND_API_KEY)const contact = await resend.contacts.get({ email: user.email })+ let contactId: stringif (contact.error) {if (contact.error.name !== "not_found" || contact.error.statusCode !== 404) {logProviderFailure("signup", stage, contact.error.statusCode)@@ -42,22 +43,34 @@ export async function syncResendSignupContact(firstName: user.name,segments: [{ id: NEW_SIGNUPS_SEGMENT_ID }],})- if (created.error) logProviderFailure("signup", stage, created.error.statusCode)- return+ if (created.error) {+ logProviderFailure("signup", stage, created.error.statusCode)+ return+ }+ contactId = created.data.id+ } else {+ stage = "update"+ const updated = await resend.contacts.update({ id: contact.data.id, firstName: user.name })+ if (updated.error) {+ logProviderFailure("signup", stage, updated.error.statusCode)+ return+ }+ stage = "segment"+ const added = await resend.contacts.segments.add({+ contactId: contact.data.id,+ segmentId: NEW_SIGNUPS_SEGMENT_ID,+ })+ if (added.error) {+ logProviderFailure("signup", stage, added.error.statusCode)+ return+ }+ if (contact.data.unsubscribed) return+ contactId = contact.data.id}- stage = "update"- const updated = await resend.contacts.update({ id: contact.data.id, firstName: user.name })- if (updated.error) {- logProviderFailure("signup", stage, updated.error.statusCode)- return- }- stage = "segment"- const added = await resend.contacts.segments.add({- contactId: contact.data.id,- segmentId: NEW_SIGNUPS_SEGMENT_ID,- })- if (added.error) logProviderFailure("signup", stage, added.error.statusCode)+ stage = "event"+ const sent = await resend.events.send({ event: "new_signup", contactId })+ if (sent.error) logProviderFailure("signup", stage, sent.error.statusCode)} catch {log.warn("resend_contact_sync_failed", { action: "signup", stage, errorCategory: "exception" })}diff --git a/src/web/test-runtime/resend-contacts.runtime.test.ts b/src/web/test-runtime/resend-contacts.runtime.test.tsindex 84a579886..d8c3a6fbd 100644--- a/src/web/test-runtime/resend-contacts.runtime.test.ts+++ b/src/web/test-runtime/resend-contacts.runtime.test.ts@@ -14,10 +14,11 @@ afterEach(() => {})describe("official Resend SDK in workerd", () => {- it("loads the SDK and creates a contact within the original execution context", async () => {+ it("creates a contact and sends its signup event within the original execution context", async () => {const fetchMock = vi.fn<typeof fetch>().mockResolvedValueOnce(Response.json({ name: "not_found", statusCode: 404, message: "Missing contact" }, { status: 404 })).mockResolvedValueOnce(Response.json({ id: "runtime-contact", object: "contact" }))+ .mockResolvedValueOnce(Response.json({ object: "event", event: "new_signup" }))vi.stubGlobal("fetch", fetchMock)const context = createExecutionContext()context.waitUntil(syncResendSignupContact(env, user))@@ -25,11 +26,41 @@ describe("official Resend SDK in workerd", () => {expect(await response.text()).toBe("created")await waitOnExecutionContext(context)- expect(fetchMock).toHaveBeenCalledTimes(2)+ expect(fetchMock).toHaveBeenCalledTimes(3)expect(fetchMock.mock.calls[1]?.[0]).toBe("https://api.resend.com/contacts")expect(JSON.parse(fetchMock.mock.calls[1]?.[1]?.body as string)).toEqual({email: user.email, first_name: user.name, segments: [{ id: segmentId }],})+ expect(fetchMock.mock.calls[2]?.[0]).toBe("https://api.resend.com/events/send")+ expect(JSON.parse(fetchMock.mock.calls[2]?.[1]?.body as string)).toEqual({+ event: "new_signup", contact_id: "runtime-contact",+ })+ })++ it("contains a failed signup event within waitUntil without retrying or logging private data", async () => {+ const privateError = `${user.email} ${user.name} ${env.RESEND_API_KEY}`+ const fetchMock = vi.fn<typeof fetch>()+ .mockResolvedValueOnce(Response.json({ id: "runtime-contact", unsubscribed: false }))+ .mockResolvedValueOnce(Response.json({ id: "runtime-contact" }))+ .mockResolvedValueOnce(Response.json({ id: segmentId }))+ .mockResolvedValueOnce(Response.json({ name: "application_error", statusCode: 500, message: privateError }, { status: 500 }))+ vi.stubGlobal("fetch", fetchMock)+ const log = vi.spyOn(console, "log")+ const error = vi.spyOn(console, "error")+ const context = createExecutionContext()+ context.waitUntil(syncResendSignupContact(env, user))+ await expect(waitOnExecutionContext(context)).resolves.toBeUndefined()+ expect(fetchMock).toHaveBeenCalledTimes(4)+ expect(fetchMock.mock.calls[3]?.[0]).toBe("https://api.resend.com/events/send")+ expect(error).not.toHaveBeenCalled()+ expect(log).toHaveBeenCalledOnce()+ expect(JSON.parse(log.mock.calls[0]?.[0] as string)).toMatchObject({+ service: "resend-contacts", msg: "resend_contact_sync_failed", action: "signup",+ stage: "event", errorCategory: "provider_error", statusCode: 500,+ })+ for (const value of [user.email, user.name, env.RESEND_API_KEY]) {+ expect(JSON.stringify(log.mock.calls)).not.toContain(value)+ }})it("contains unsubscribe provider failure without leaking its body or email through console", async () => {