(
workspaceId: string,
opts?: { username?: string }
)
| 16 | * 4. Update workspace.inboxEnabled = true |
| 17 | */ |
| 18 | export async function enableInbox( |
| 19 | workspaceId: string, |
| 20 | opts?: { username?: string } |
| 21 | ): Promise<InboxConfig> { |
| 22 | const inbox = await agentmail.createInbox({ |
| 23 | username: opts?.username, |
| 24 | displayName: 'Sim', |
| 25 | }) |
| 26 | |
| 27 | logger.info('AgentMail createInbox response', { inbox: JSON.stringify(inbox) }) |
| 28 | |
| 29 | if (!inbox?.inbox_id) { |
| 30 | throw new Error('AgentMail createInbox response missing inbox_id') |
| 31 | } |
| 32 | |
| 33 | let webhook: Awaited<ReturnType<typeof agentmail.createWebhook>> | null = null |
| 34 | try { |
| 35 | webhook = await agentmail.createWebhook({ |
| 36 | url: `${getBaseUrl()}/api/webhooks/agentmail`, |
| 37 | eventTypes: ['message.received'], |
| 38 | inboxIds: [inbox.inbox_id], |
| 39 | }) |
| 40 | |
| 41 | await db.insert(mothershipInboxWebhook).values({ |
| 42 | id: generateId(), |
| 43 | workspaceId, |
| 44 | webhookId: webhook.webhook_id, |
| 45 | secret: webhook.secret, |
| 46 | }) |
| 47 | |
| 48 | await db |
| 49 | .update(workspace) |
| 50 | .set({ |
| 51 | inboxEnabled: true, |
| 52 | inboxAddress: inbox.inbox_id, |
| 53 | inboxProviderId: inbox.inbox_id, |
| 54 | updatedAt: new Date(), |
| 55 | }) |
| 56 | .where(eq(workspace.id, workspaceId)) |
| 57 | |
| 58 | logger.info('Inbox enabled', { workspaceId, address: inbox.inbox_id }) |
| 59 | |
| 60 | return { |
| 61 | enabled: true, |
| 62 | address: inbox.inbox_id, |
| 63 | providerId: inbox.inbox_id, |
| 64 | } |
| 65 | } catch (error) { |
| 66 | try { |
| 67 | if (webhook) await agentmail.deleteWebhook(webhook.webhook_id) |
| 68 | await agentmail.deleteInbox(inbox.inbox_id) |
| 69 | await db |
| 70 | .delete(mothershipInboxWebhook) |
| 71 | .where(eq(mothershipInboxWebhook.workspaceId, workspaceId)) |
| 72 | } catch (rollbackError) { |
| 73 | logger.error('Failed to rollback AgentMail resources', { rollbackError }) |
| 74 | } |
| 75 | throw error |
no test coverage detected