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: migrate email sending to email worker service binding (#8)
Genera34b0f1f9ec0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e22e7203d..06bd11560 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -60,8 +60,9 @@ jobs:- name: Create .dev.vars for local bindingsrun: printf 'BETTER_AUTH_SECRET=ci-e2e-secret\nBETTER_AUTH_URL=http://localhost:3000\n' > src/web/.dev.vars- run: pnpm run db:migrate- - name: Start dev server+ - name: Start dev serversrun: |+ pnpm --filter @alook/email-worker dev &pnpm --filter @alook/web dev &until curl -sf http://localhost:3000/api/health; do sleep 2; done- run: pnpm test:e2ediff --git a/package.json b/package.jsonindex 88fcfd7a9..a9959fefd 100644--- a/package.json+++ b/package.json@@ -15,7 +15,7 @@"dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 ALOOK_PROJECT_ROOT=$PWD pnpm --filter @alook/cli dev","dev:email": "pnpm --filter @alook/email-worker dev","dev:ws": "pnpm --filter @alook/ws-do dev",- "dev:send": "node -e \"const a=process.argv.slice(1);const[f,t,s='Test',b='Hello from dev']=a;if(!f||!t){console.error('Usage: pnpm dev:send <from> <to> [subject] [body]');process.exit(1)}fetch('http://localhost:8787/simulate',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({from:f,to:t,subject:s,body:b})}).then(r=>r.json()).then(console.log).catch(e=>console.error('Email worker not running?',e.message))\"",+ "dev:send": "node -e \"const c=require('crypto');const a=process.argv.slice(1);const[f,t,s='Test',b='Hello from dev']=a;if(!f||!t){console.error('Usage: pnpm dev:send <from> <to> [subject] [body]');process.exit(1)}const raw=['From: '+f,'To: '+t,'Subject: '+s,'Message-ID: <'+c.randomUUID()+'@dev.local>','Date: '+new Date().toUTCString(),'MIME-Version: 1.0','Content-Type: text/plain; charset=utf-8','',b].join('\\r\\n');fetch('http://localhost:8787/cdn-cgi/handler/email?from='+encodeURIComponent(f)+'&to='+encodeURIComponent(t),{method:'POST',headers:{'Content-Type':'application/json'},body:raw}).then(r=>{if(r.ok)console.log('Email delivered to worker');else return r.text().then(t=>{throw new Error(t)})}).catch(e=>console.error('Email worker not running?',e.message))\"","test:shared": "pnpm --filter @alook/shared test","test:cli": "pnpm --filter @alook/cli test","test:web": "pnpm --filter @alook/web test",@@ -32,7 +32,7 @@"turbo": "^2.9.6","typescript": "^6.0.2","vitest": "^4.1.4",- "wrangler": "^4.82.2"+ "wrangler": "^4.83.0"},"pnpm": {"onlyBuiltDependencies": [diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f517c37c8..55287fa80 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -18,8 +18,8 @@ importers:specifier: ^4.1.4version: 4.1.4(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:- specifier: ^4.82.2- version: 4.82.2(@cloudflare/[email protected])+ specifier: ^4.83.0+ version: 4.83.0(@cloudflare/[email protected])src/cli:dependencies:@@ -68,8 +68,8 @@ importers:specifier: ^4.1.4version: 4.1.4(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:- specifier: ^4.82.2- version: 4.82.2(@cloudflare/[email protected])+ specifier: ^4.83.0+ version: 4.83.0(@cloudflare/[email protected])src/shared:dependencies:@@ -112,7 +112,7 @@ importers:version: 13.13.0([email protected])'@opennextjs/cloudflare':specifier: ^1.19.1- version: 1.19.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected](@cloudflare/[email protected]))+ version: 1.19.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected](@cloudflare/[email protected]))'@tiptap/extension-color':specifier: ^3.22.3@@ -220,8 +220,8 @@ importers:specifier: ^4.1.4version: 4.1.4(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:- specifier: ^4.82.2- version: 4.82.2(@cloudflare/[email protected])+ specifier: ^4.83.0+ version: 4.83.0(@cloudflare/[email protected])src/ws-do:dependencies:@@ -242,8 +242,8 @@ importers:specifier: ^4.1.4version: 4.1.4(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))wrangler:- specifier: ^4.82.2- version: 4.82.2(@cloudflare/[email protected])+ specifier: ^4.83.0+ version: 4.83.0(@cloudflare/[email protected])packages:@@ -775,32 +775,32 @@ packages:workerd:optional: true- '@cloudflare/[email protected]':- resolution: {integrity: sha512-0sh6xPmCKUfv/lUklP1dfyeKxCuEZGS0HeduxnucL8ECxSgAdWTOD42h/lQTwZCIiWtyHB+ZNB9hsS2Mlf0tMQ==}+ '@cloudflare/[email protected]':+ resolution: {integrity: sha512-dsxaKsQm3LnPGNPEdsRv09QN3Y4DqCw7kX5j6noKqbAtro2jTr95sVlYM1jUxZ5FkOl1f7SXgaKKB9t5H5Nkbg==}engines: {node: '>=16'}cpu: [x64]os: [darwin]- '@cloudflare/[email protected]':- resolution: {integrity: sha512-r2On29gPvlk/eiH/OpeUT23xoB8W8D1PHr8lul5nyxElLqvh3yNxZUnJWrbcOl+ubfrvw7+jFwgopMe17xyf0g==}+ '@cloudflare/[email protected]':+ resolution: {integrity: sha512-+JgSgVA49KyKteHRA1SnonE4Zn5Ei5zdAp5FQMxFmXI8qulZw4Hl7safXxRyK4i9sTO8gl7TFOKO5Q64VPvSDQ==}engines: {node: '>=16'}cpu: [arm64]os: [darwin]- '@cloudflare/[email protected]':- resolution: {integrity: sha512-qWORRcAzPZeHJjrcYBNZTN6Y9l+iZQUz4KBdWbNrM6My4CpNrXS5kErPR373vG//5QPaDGwMXgBqyn9xfzarJQ==}+ '@cloudflare/[email protected]':+ resolution: {integrity: sha512-tU+9pwsqCy8afOVlGtiWrWQc/fedQK4SRm4KPIAt+zOiQWDxWASm6YGBUJis5c648WN80yz47qnmdDi8DQNOcA==}engines: {node: '>=16'}cpu: [x64]os: [linux]- '@cloudflare/[email protected]':- resolution: {integrity: sha512-jQfuHL4mnGDFyomSS3JNs9TpTvCu6Vzz2QSNCfJRstMzTICUFLMc4Vp/xKK+M5xkb0PoAu/G0hHx7jrxB2j+OQ==}+ '@cloudflare/[email protected]':+ resolution: {integrity: sha512-bR9uITnV19r5NQ14xnypi2xHXu2iQvfYV8cVgx0JouFUmWwTEEAwFVojDdssGq93VHX9hr/pi2IRUZeegbYBog==}engines: {node: '>=16'}cpu: [arm64]os: [linux]- '@cloudflare/[email protected]':- resolution: {integrity: sha512-h8q/nbheDqpknY7AAOz19MuQkZAR1/bnoZnKipyeUPXt5No+y6HlTtva9Bohx5Fhc1MW2CX2MQVdb55qtkkqZQ==}+ '@cloudflare/[email protected]':+ resolution: {integrity: sha512-4NuMLlerI0Ijua3Ir8HXQ+qyNvCUDEG5gDco5Om+sAiK6rnWiz+aGoSlbB8W16yW9QAgzCstbmXLiVknUBflfQ==}engines: {node: '>=16'}cpu: [x64]os: [win32]@@ -1471,8 +1471,8 @@ packages:'@napi-rs/[email protected]':resolution: {integrity: sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==}- '@napi-rs/[email protected]':- resolution: {integrity: sha512-xK9sGVbJWYb08+mTJt3/YV24WxvxpXcXtP6B172paPZ+Ts69Re9dAr7lKwJoeIx8OoeuimEiRZ7umkiUVClmmQ==}+ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==}peerDependencies:'@emnapi/core': ^1.7.1'@emnapi/runtime': ^1.7.1@@ -4734,8 +4734,8 @@ packages:resolution: {integrity: sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==}engines: {node: '>=18'}- resolution: {integrity: sha512-94LEU8d+XPVGp18eW4+bu1v7Tnq7srhqWMIsrx2jhSkdbTnGqg1I613R0GKY4eygBYl9MbqXEhzK/bczJb6uMg==}+ resolution: {integrity: sha512-JoExRWN4YBI2luA5BoSMFEgi8rQWXUGzo3mtE+58VXCLV3jj/Xnk5Yeqs/IXWz8Es5GJIaq6BtsixDvAxXSIng==}engines: {node: '>=18.0.0'}hasBin: true@@ -5071,6 +5071,10 @@ packages:resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==}engines: {node: ^10 || ^12 || >=14}+ resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==}+ engines: {node: ^10 || ^12 || >=14}+resolution: {integrity: sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw==}engines: {node: ^10 || ^12 || >=14}@@ -5696,8 +5700,8 @@ packages:resolution: {integrity: sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg==}- resolution: {integrity: sha512-BM/JzwwaRXxrLdElV2Uo6cTLEjhSb3WXboncJamZ15NgUURmvlXvxa6xkwIOILIjPNo9i8ku136ZvWV0Uly8+w==}+ resolution: {integrity: sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==}engines: {node: '>=20.18.1'}@@ -5939,17 +5943,17 @@ packages:resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}engines: {node: '>=0.10.0'}- resolution: {integrity: sha512-T/GRD6Y5vN9g4CnGmOlfST1w7bj+1IjRFvX0K7CodZPJuPVPNPGhz8Wppah0WdT6A7I8Kad3zgZ2OkDdWtENrg==}+ resolution: {integrity: sha512-phyPjRnx+mQDfkhN9ENPioL1L0SdhYs4S0YmJK/xF9Oga+ykNfdSy1MHnsOj8yqnOV96zcVQMx32dJ0r3pq0jQ==}engines: {node: '>=16'}hasBin: true- resolution: {integrity: sha512-SKfW21sTJUkM/Qd8zc9oc8TBkAWHRsXuTxE6XdToC55Ct84pR+IfRdaTjCTuC0dL+KYvauSvSn2rtqS2Ae+Dcw==}+ resolution: {integrity: sha512-gw5g3LCiuAqVWxaoKY6+quE0HzAUEFb/FV3oAlNkE1ttd4XP3FiV91XDkkzUCcdqxS4WjhQvPhIDBNdhEi8P0A==}engines: {node: '>=20.3.0'}hasBin: truepeerDependencies:- '@cloudflare/workers-types': ^4.20260410.1+ '@cloudflare/workers-types': ^4.20260415.1peerDependenciesMeta:'@cloudflare/workers-types':optional: true@@ -7063,25 +7067,25 @@ snapshots:'@cloudflare/[email protected]': {}dependencies:unenv: 2.0.0-rc.24optionalDependencies:- workerd: 1.20260410.1+ workerd: 1.20260415.1- '@cloudflare/[email protected]':+ '@cloudflare/[email protected]':optional: true- '@cloudflare/[email protected]':+ '@cloudflare/[email protected]':optional: true- '@cloudflare/[email protected]':+ '@cloudflare/[email protected]':optional: true- '@cloudflare/[email protected]':+ '@cloudflare/[email protected]':optional: true- '@cloudflare/[email protected]':+ '@cloudflare/[email protected]':optional: true'@cloudflare/[email protected]': {}@@ -7582,7 +7586,7 @@ snapshots:'@tybys/wasm-util': 0.10.1optional: truedependencies:'@emnapi/core': 1.9.2'@emnapi/runtime': 1.9.2@@ -7693,7 +7697,7 @@ snapshots:- aws-crt- supports-color- '@opennextjs/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected](@cloudflare/[email protected]))':+ '@opennextjs/[email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected](@cloudflare/[email protected]))':dependencies:'@ast-grep/napi': 0.40.5'@dotenvx/dotenvx': 1.31.0@@ -7704,7 +7708,7 @@ snapshots:glob: 12.0.0next: 16.2.3(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])ts-tqdm: 0.8.6- wrangler: 4.82.2(@cloudflare/[email protected])+ wrangler: 4.83.0(@cloudflare/[email protected])yargs: 18.0.0transitivePeerDependencies:- aws-crt@@ -7771,7 +7775,7 @@ snapshots:dependencies:'@emnapi/core': 1.9.2'@emnapi/runtime': 1.9.2- '@napi-rs/wasm-runtime': 1.1.3(@emnapi/[email protected])(@emnapi/[email protected])+ '@napi-rs/wasm-runtime': 1.1.4(@emnapi/[email protected])(@emnapi/[email protected])optional: true'@rolldown/[email protected]':@@ -9755,8 +9759,8 @@ snapshots:'@next/eslint-plugin-next': 16.2.3eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))eslint-plugin-react-hooks: 7.0.1([email protected]([email protected]))@@ -9778,7 +9782,7 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.3@@ -9789,22 +9793,22 @@ snapshots:tinyglobby: 0.2.16unrs-resolver: 1.11.1optionalDependencies:- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))+ eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@rtsao/scc': 1.1.0array-includes: 3.1.9@@ -9815,7 +9819,7 @@ snapshots:doctrine: 2.1.0eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))+ eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))hasown: 2.0.2is-core-module: 2.16.1is-glob: 4.0.3@@ -11225,12 +11229,12 @@ snapshots:dependencies:'@cspotcode/source-map-support': 0.8.1sharp: 0.34.5- undici: 7.24.4- workerd: 1.20260410.1+ undici: 7.24.8+ workerd: 1.20260415.1ws: 8.18.0youch: 4.1.0-beta.10transitivePeerDependencies:@@ -11580,6 +11584,12 @@ snapshots:picocolors: 1.1.1source-map-js: 1.2.1+ dependencies:+ nanoid: 3.3.11+ picocolors: 1.1.1+ source-map-js: 1.2.1+dependencies:nanoid: 3.3.11@@ -12432,7 +12442,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}dependencies:@@ -12546,7 +12556,7 @@ snapshots:dependencies:lightningcss: 1.32.0picomatch: 4.0.4- postcss: 8.5.9+ postcss: 8.5.10rolldown: 1.0.0-rc.15tinyglobby: 0.2.16optionalDependencies:@@ -12673,24 +12683,24 @@ snapshots:optionalDependencies:- '@cloudflare/workerd-darwin-64': 1.20260410.1- '@cloudflare/workerd-darwin-arm64': 1.20260410.1- '@cloudflare/workerd-linux-64': 1.20260410.1- '@cloudflare/workerd-linux-arm64': 1.20260410.1- '@cloudflare/workerd-windows-64': 1.20260410.1+ '@cloudflare/workerd-darwin-64': 1.20260415.1+ '@cloudflare/workerd-darwin-arm64': 1.20260415.1+ '@cloudflare/workerd-linux-64': 1.20260415.1+ '@cloudflare/workerd-linux-arm64': 1.20260415.1+ '@cloudflare/workerd-windows-64': 1.20260415.1- [email protected](@cloudflare/[email protected]):+ [email protected](@cloudflare/[email protected]):dependencies:'@cloudflare/kv-asset-handler': 0.4.2- '@cloudflare/unenv-preset': 2.16.0([email protected])([email protected])+ '@cloudflare/unenv-preset': 2.16.0([email protected])([email protected])blake3-wasm: 2.1.5esbuild: 0.27.3- miniflare: 4.20260410.0+ miniflare: 4.20260415.0path-to-regexp: 6.3.0unenv: 2.0.0-rc.24- workerd: 1.20260410.1+ workerd: 1.20260415.1optionalDependencies:'@cloudflare/workers-types': 4.20260414.1fsevents: 2.3.3diff --git a/src/email-worker/package.json b/src/email-worker/package.jsonindex 3465bc804..c0bdf1a7d 100644--- a/src/email-worker/package.json+++ b/src/email-worker/package.json@@ -2,7 +2,21 @@"name": "@alook/email-worker","version": "0.0.1","private": true,- "scripts": { "dev": "wrangler dev --persist-to ../web/.wrangler/state", "deploy": "wrangler deploy", "test": "vitest run", "typecheck": "tsc --noEmit" },- "dependencies": { "@alook/shared": "workspace:*", "nanoid": "^5.1.7" },- "devDependencies": { "vitest": "^4.1.4", "wrangler": "^4.82.2", "typescript": "^6.0.2", "@cloudflare/workers-types": "^4.20260414.1", "@types/node": "^25.6.0" }+ "scripts": {+ "dev": "wrangler dev --persist-to ../web/.wrangler/state",+ "deploy": "wrangler deploy",+ "test": "vitest run",+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "@alook/shared": "workspace:*",+ "nanoid": "^5.1.7"+ },+ "devDependencies": {+ "@cloudflare/workers-types": "^4.20260414.1",+ "@types/node": "^25.6.0",+ "typescript": "^6.0.2",+ "vitest": "^4.1.4",+ "wrangler": "^4.83.0"+ }}diff --git a/src/email-worker/src/__mocks__/cf.ts b/src/email-worker/src/__mocks__/cf.tsindex 827d87dbd..bae078bdd 100644--- a/src/email-worker/src/__mocks__/cf.ts+++ b/src/email-worker/src/__mocks__/cf.ts@@ -14,6 +14,13 @@ export function createMockFetcher() {return { fetcher: { fetch } as unknown as Fetcher, fetch }}+// --- SendEmail Mock ---++export function createMockSendEmail() {+ const send = vi.fn().mockResolvedValue({ messageId: "mock-msg-id" })+ return { sendEmail: { send } as unknown as SendEmail, send }+}+// --- ForwardableEmailMessage Mock ---export interface MockMessageOpts {diff --git a/src/email-worker/src/index.test.ts b/src/email-worker/src/index.test.tsindex 61d7e5e28..79ac71707 100644--- a/src/email-worker/src/index.test.ts+++ b/src/email-worker/src/index.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from "vitest"-import { createMockR2, createMockFetcher, createMockMessage } from "./__mocks__/cf"+import { createMockR2, createMockFetcher, createMockMessage, createMockSendEmail } from "./__mocks__/cf"// Mock nanoid to return predictable IDslet nanoidCounter = 0@@ -9,6 +9,7 @@ vi.mock("nanoid", () => ({// Mock @alook/shared at module level — the handler never touches Drizzleconst mockGetAgentByHandle = vi.fn<(db: unknown, handle: unknown) => unknown>()+const mockGetAgent = vi.fn<(db: unknown, id: unknown, workspaceId: unknown) => unknown>()const mockIsWhitelisted = vi.fn<(db: unknown, agentId: unknown, workspaceId: unknown, email: unknown) => unknown>()const mockGetUser = vi.fn<(db: unknown, id: unknown) => unknown>()const mockCreateDb = vi.fn<(d1: unknown) => Record<string, unknown>>().mockReturnValue({})@@ -30,7 +31,10 @@ vi.mock("@alook/shared", () => {},DEV_WEB_URL: "http://localhost:3000",queries: {- agent: { getAgentByHandle: (db: unknown, handle: unknown) => mockGetAgentByHandle(db, handle) },+ agent: {+ getAgentByHandle: (db: unknown, handle: unknown) => mockGetAgentByHandle(db, handle),+ getAgent: (db: unknown, id: unknown, workspaceId: unknown) => mockGetAgent(db, id, workspaceId),+ },whitelist: { isWhitelisted: (db: unknown, agentId: unknown, workspaceId: unknown, email: unknown) => mockIsWhitelisted(db, agentId, workspaceId, email) },user: { getUser: (db: unknown, id: unknown) => mockGetUser(db, id) },},@@ -71,6 +75,7 @@ function setup(overrides?: {const { bucket, put } = createMockR2()const { fetcher, fetch: wsFetch } = createMockFetcher()+ const { sendEmail } = createMockSendEmail()const { message, setReject, forward, rawText } = createMockMessage(overrides?.messageOpts ?? {from: "[email protected]",@@ -80,7 +85,7 @@ function setup(overrides?: {})- const env = { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher }+ const env = { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail }return { env, message, put, wsFetch, setReject, forward, rawText }}@@ -276,3 +281,240 @@ describe("non-whitelisted path", () => {expect(mockGetUser).not.toHaveBeenCalled()})})++// ─── Group 5: POST /send/otp ───++describe("POST /send/otp", () => {+ function makeOtpRequest(body: Record<string, unknown>) {+ return new Request("http://localhost/send/otp", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ })+ }++ function otpEnv() {+ const { bucket } = createMockR2()+ const { fetcher } = createMockFetcher()+ const { sendEmail, send } = createMockSendEmail()+ return {+ env: { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail },+ send,+ }+ }++ it("sends OTP email via SEND_EMAIL binding", async () => {+ const { env, send } = otpEnv()+ const res = await handler.fetch(+ makeOtpRequest({ to: "[email protected]", subject: "Your code", html: "<p>123456</p>" }),+ env,+ )++ expect(res.status).toBe(200)+ const json = await res.json() as { ok: boolean }+ expect(json.ok).toBe(true)+ expect(send).toHaveBeenCalledOnce()+ expect(send).toHaveBeenCalledWith({+ from: "[email protected]",+ to: "[email protected]",+ subject: "Your code",+ html: "<p>123456</p>",+ })+ })++ it("returns 400 when 'to' is missing", async () => {+ const { env } = otpEnv()+ const res = await handler.fetch(+ makeOtpRequest({ subject: "code", html: "<p>x</p>" }),+ env,+ )+ expect(res.status).toBe(400)+ })++ it("returns 400 when 'subject' is missing", async () => {+ const { env } = otpEnv()+ const res = await handler.fetch(+ makeOtpRequest({ to: "[email protected]", html: "<p>x</p>" }),+ env,+ )+ expect(res.status).toBe(400)+ })+})++// ─── Group 6: POST /send/agent ───++describe("POST /send/agent", () => {+ function makeAgentSendRequest(body: Record<string, unknown>) {+ return new Request("http://localhost/send/agent", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ })+ }++ function agentSendEnv() {+ const { bucket, put } = createMockR2()+ const { fetcher } = createMockFetcher()+ const { sendEmail, send } = createMockSendEmail()+ return {+ env: { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail },+ send,+ put,+ bucket,+ }+ }++ it("sends agent email and stores MIME archive in R2", async () => {+ mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })+ const { env, send, put } = agentSendEnv()++ const res = await handler.fetch(+ makeAgentSendRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "Hello",+ htmlBody: "<p>Hi there</p>",+ }),+ env,+ )++ expect(res.status).toBe(200)+ const json = await res.json() as { ok: boolean; r2Key: string }+ expect(json.ok).toBe(true)+ expect(json.r2Key).toMatch(/^emails\/mock-id-\d+\/raw$/)++ // Verify SEND_EMAIL.send was called with builder+ expect(send).toHaveBeenCalledOnce()+ const sendArg = send.mock.calls[0][0]+ expect(sendArg.from).toBe("[email protected]")+ expect(sendArg.to).toBe("[email protected]")+ expect(sendArg.subject).toBe("Hello")+ expect(sendArg.html).toBe("<p>Hi there</p>")++ // Verify R2 archive+ expect(put).toHaveBeenCalledOnce()+ const [key, body, opts] = put.mock.calls[0]+ expect(key).toMatch(/^emails\/mock-id-\d+\/raw$/)+ expect(opts).toEqual({ httpMetadata: { contentType: "message/rfc822" } })+ expect(body).toContain("From: [email protected]")+ expect(body).toContain("To: [email protected]")+ expect(body).toContain("Subject: Hello")+ expect(body).toContain("Content-Type: text/html; charset=utf-8")+ })++ it("sends agent email with attachments from R2", async () => {+ mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "jarvis" })+ const { env, send, put, bucket } = agentSendEnv()++ const fileContent = new TextEncoder().encode("file content")+ ;(bucket as any).get = vi.fn().mockResolvedValue({+ arrayBuffer: () => Promise.resolve(fileContent.buffer),+ })++ const res = await handler.fetch(+ makeAgentSendRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "With attachment",+ htmlBody: "<p>See attached</p>",+ attachmentKeys: [+ { key: "emails/drafts/x/doc.txt", filename: "doc.txt", contentType: "text/plain" },+ ],+ }),+ env,+ )++ expect(res.status).toBe(200)++ // Verify SEND_EMAIL.send includes attachments with base64 content string+ const sendArg = send.mock.calls[0][0]+ expect(sendArg.attachments).toHaveLength(1)+ expect(sendArg.attachments[0].filename).toBe("doc.txt")+ expect(sendArg.attachments[0].type).toBe("text/plain")+ expect(sendArg.attachments[0].disposition).toBe("attachment")+ expect(typeof sendArg.attachments[0].content).toBe("string")+ expect(sendArg.attachments[0].content).toBe(btoa("file content"))++ // Verify R2 MIME archive contains attachment+ const storedMime = put.mock.calls[0][1] as string+ expect(storedMime).toContain("multipart/mixed")+ expect(storedMime).toContain('Content-Disposition: attachment; filename="doc.txt"')+ expect(storedMime).toContain("Content-Transfer-Encoding: base64")+ })++ it("returns 404 when agent not found in workspace", async () => {+ mockGetAgent.mockResolvedValue(null)+ const { env } = agentSendEnv()++ const res = await handler.fetch(+ makeAgentSendRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "Hello",+ htmlBody: "<p>Hi</p>",+ }),+ env,+ )++ expect(res.status).toBe(404)+ })++ it("returns 400 when agent has no email handle", async () => {+ mockGetAgent.mockResolvedValue({ id: "agent-1", workspaceId: "ws-1", emailHandle: "" })+ const { env } = agentSendEnv()++ const res = await handler.fetch(+ makeAgentSendRequest({+ agentId: "agent-1",+ workspaceId: "ws-1",+ to: "[email protected]",+ subject: "Hello",+ htmlBody: "<p>Hi</p>",+ }),+ env,+ )++ expect(res.status).toBe(400)+ })++ it("returns 400 when required fields are missing", async () => {+ const { env } = agentSendEnv()++ const res = await handler.fetch(+ makeAgentSendRequest({ agentId: "agent-1" }),+ env,+ )++ expect(res.status).toBe(400)+ })+})++// ─── Group 7: fetch() routing ───++describe("fetch() routing", () => {+ function routingEnv() {+ const { bucket } = createMockR2()+ const { fetcher } = createMockFetcher()+ const { sendEmail } = createMockSendEmail()+ return { DB: {} as D1Database, EMAIL_BUCKET: bucket, WEB_SERVICE: fetcher, SEND_EMAIL: sendEmail }+ }++ it("returns 404 for unknown paths", async () => {+ const res = await handler.fetch(+ new Request("http://localhost/unknown", { method: "POST" }),+ routingEnv(),+ )+ expect(res.status).toBe(404)+ })++ it("returns 405 for non-POST methods", async () => {+ const res = await handler.fetch(+ new Request("http://localhost/send/otp", { method: "GET" }),+ routingEnv(),+ )+ expect(res.status).toBe(405)+ })+})diff --git a/src/email-worker/src/index.ts b/src/email-worker/src/index.tsindex 8c8b05870..641e56f36 100644--- a/src/email-worker/src/index.ts+++ b/src/email-worker/src/index.ts@@ -7,6 +7,16 @@ interface EmailEnv {DB: D1DatabaseEMAIL_BUCKET: R2BucketWEB_SERVICE: Fetcher+ SEND_EMAIL: SendEmail+}++function arrayBufferToBase64(buffer: ArrayBuffer): string {+ const bytes = new Uint8Array(buffer)+ let binary = ""+ for (let i = 0; i < bytes.byteLength; i++) {+ binary += String.fromCharCode(bytes[i]!)+ }+ return btoa(binary)}async function notifyWeb(env: EmailEnv, payload: Record<string, unknown>, traceId: string) {@@ -35,57 +45,147 @@ async function notifyWeb(env: EmailEnv, payload: Record<string, unknown>, traceIexport default {async fetch(request: Request, env: EmailEnv): Promise<Response> {- const traceId = request.headers.get("X-Trace-Id") ?? nanoid(12)- const reqLog = log.child({ traceId })const url = new URL(request.url)- if (url.pathname !== "/simulate" || request.method !== "POST") {- return new Response("POST /simulate to send a test email", { status: 404 })+ if (request.method !== "POST") {+ return Response.json({ error: "method not allowed" }, { status: 405 })+ }++ if (url.pathname === "/send/otp") {+ return this.handleSendOtp(request, env)}- const body = await request.json() as { from: string; to: string; subject?: string; body?: string }- if (!body.from || !body.to) {- return new Response("from and to required", { status: 400 })+ if (url.pathname === "/send/agent") {+ return this.handleSendAgent(request, env)+ }++ return Response.json({ error: "not found" }, { status: 404 })+ },++ async handleSendOtp(request: Request, env: EmailEnv): Promise<Response> {+ const body = await request.json() as { to?: string; subject?: string; html?: string }++ if (!body.to || !body.subject) {+ return Response.json({ error: "to and subject are required" }, { status: 400 })}- reqLog.info("simulating email", { from: body.from, to: body.to })-- const raw = [- `From: ${body.from}`,- `To: ${body.to}`,- `Subject: ${body.subject ?? "(test)"}`,- `Date: ${new Date().toUTCString()}`,- "",- body.body ?? "",- ].join("\r\n")-- const rawStream = new ReadableStream({- start(controller) {- controller.enqueue(new TextEncoder().encode(raw))- controller.close()- },+ await env.SEND_EMAIL.send({+ from: "[email protected]",+ to: body.to,+ subject: body.subject,+ html: body.html ?? "",})- const headers = new Headers()- headers.set("subject", body.subject ?? "(test)")+ return Response.json({ ok: true })+ },- const fakeMessage = {- from: body.from,+ async handleSendAgent(request: Request, env: EmailEnv): Promise<Response> {+ const body = await request.json() as {+ agentId?: string+ workspaceId?: string+ to?: string+ subject?: string+ htmlBody?: string+ attachmentKeys?: { key: string; filename: string; contentType: string }[]+ }++ if (!body.agentId || !body.workspaceId || !body.to || !body.subject) {+ return Response.json({ error: "agentId, workspaceId, to, and subject are required" }, { status: 400 })+ }++ const db = createDb(env.DB)+ const agent = await queries.agent.getAgent(db, body.agentId, body.workspaceId)+ if (!agent) {+ return Response.json({ error: "agent not found in workspace" }, { status: 404 })+ }++ if (!agent.emailHandle) {+ return Response.json({ error: "agent has no email handle configured" }, { status: 400 })+ }++ const fromAddress = `${agent.emailHandle}@alook.ai`+ const htmlBody = body.htmlBody ?? ""+ const attachmentKeys = body.attachmentKeys ?? []++ // Fetch attachment content from R2 and convert to base64+ const attachments: { disposition: "attachment"; filename: string; type: string; content: string }[] = []+ for (const att of attachmentKeys) {+ const obj = await env.EMAIL_BUCKET.get(att.key)+ if (!obj) continue+ const buf = await obj.arrayBuffer()+ attachments.push({+ disposition: "attachment" as const,+ filename: att.filename,+ type: att.contentType,+ content: arrayBufferToBase64(buf),+ })+ }++ // Send via CF builder overload (content as base64 string per CF docs)+ const sendPayload: Record<string, unknown> = {+ from: fromAddress,to: body.to,- raw: rawStream,- headers,- setReject(reason: string) { reqLog.warn("rejected", { reason }) },- forward(_to: string) { reqLog.info("forwarded", { forwardTo: _to }); return Promise.resolve() },- } as unknown as ForwardableEmailMessage-- try {- await this.email(fakeMessage, env)- return Response.json({ ok: true })- } catch (e) {- const msg = e instanceof Error ? e.message : String(e)- reqLog.error("simulate error", { err: msg })- return Response.json({ error: msg }, { status: 500 })+ subject: body.subject,+ html: htmlBody,+ }+ if (attachments.length > 0) {+ sendPayload.attachments = attachments+ }+ await env.SEND_EMAIL.send(sendPayload as any)++ // Build raw MIME for R2 archival+ let rawMime: string+ if (attachments.length === 0) {+ rawMime = [+ `From: ${fromAddress}`,+ `To: ${body.to}`,+ `Subject: ${body.subject}`,+ `Date: ${new Date().toUTCString()}`,+ `MIME-Version: 1.0`,+ `Content-Type: text/html; charset=utf-8`,+ "",+ htmlBody,+ ].join("\r\n")+ } else {+ const boundary = `----=_Part_${nanoid(16)}`+ const parts = [+ `From: ${fromAddress}`,+ `To: ${body.to}`,+ `Subject: ${body.subject}`,+ `Date: ${new Date().toUTCString()}`,+ `MIME-Version: 1.0`,+ `Content-Type: multipart/mixed; boundary="${boundary}"`,+ "",+ `--${boundary}`,+ `Content-Type: text/html; charset=utf-8`,+ `Content-Transfer-Encoding: 7bit`,+ "",+ htmlBody,+ ]+ for (const att of attachments) {+ parts.push(+ [+ `--${boundary}`,+ `Content-Type: ${att.type}; name="${att.filename}"`,+ `Content-Disposition: attachment; filename="${att.filename}"`,+ `Content-Transfer-Encoding: base64`,+ "",+ att.content.match(/.{1,76}/g)?.join("\r\n") ?? att.content,+ ].join("\r\n")+ )+ }+ parts.push(`--${boundary}--`)+ rawMime = parts.join("\r\n")}++ // Store MIME archive in R2+ const r2Id = nanoid()+ const r2Key = `emails/${r2Id}/raw`+ await env.EMAIL_BUCKET.put(r2Key, rawMime, {+ httpMetadata: { contentType: "message/rfc822" },+ })++ return Response.json({ ok: true, r2Key })},async email(message: ForwardableEmailMessage, env: EmailEnv): Promise<void> {diff --git a/src/email-worker/wrangler.toml b/src/email-worker/wrangler.tomlindex 4e0a74537..dff1742ae 100644--- a/src/email-worker/wrangler.toml+++ b/src/email-worker/wrangler.toml@@ -24,3 +24,6 @@ bucket_name = "alook-emails"[[services]]binding = "WEB_SERVICE"service = "alook-web"++[[send_email]]+name = "SEND_EMAIL"diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.tsindex 38bd8e9d0..19cc88f38 100644--- a/src/shared/src/constants.ts+++ b/src/shared/src/constants.ts@@ -42,4 +42,4 @@ export const AGENT_HANDLE_MIN_LENGTH = 4;// Local dev URLs (used for service-binding fallbacks)export const DEV_WEB_URL = process.env.ALOOK_SERVER_URL || "http://localhost:3000";export const DEV_WS_DO_URL = process.env.DEV_WS_DO_URL || "http://localhost:8789";-export const DEV_EMAIL_WORKER_URL = process.env.DEV_EMAIL_WORKER_URL || "http://localhost:8788";+export const DEV_EMAIL_WORKER_URL = process.env.DEV_EMAIL_WORKER_URL || "http://localhost:8787";diff --git a/src/web/package.json b/src/web/package.jsonindex 6255d3349..ed379f561 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -59,6 +59,6 @@"tailwindcss": "^4","typescript": "^6.0.2","vitest": "^4.1.4",- "wrangler": "^4.82.2"+ "wrangler": "^4.83.0"}}\ No newline at end of filediff --git a/src/web/src/app/api/email/send/route.test.ts b/src/web/src/app/api/email/send/route.test.tsindex a1dab205b..c6780feb0 100644--- a/src/web/src/app/api/email/send/route.test.ts+++ b/src/web/src/app/api/email/send/route.test.ts@@ -3,19 +3,13 @@ import { NextRequest } from "next/server";const mockGetAgent = vi.fn();const mockCreateEmail = vi.fn();-const mockR2Put = vi.fn();-const mockR2Get = vi.fn();-const mockSendEmailSend = vi.fn();+const mockEmailWorkerFetch = vi.fn();vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({env: {DB: {},- EMAIL_BUCKET: {- put: (...args: unknown[]) => mockR2Put(...args),- get: (...args: unknown[]) => mockR2Get(...args),- },- SEND_EMAIL: { send: (...args: unknown[]) => mockSendEmailSend(...args) },+ EMAIL_WORKER: { fetch: (...args: unknown[]) => mockEmailWorkerFetch(...args) },},})),}));@@ -60,14 +54,15 @@ import { POST } from "./route";describe("POST /api/email/send", () => {beforeEach(() => vi.clearAllMocks());- it("sends an email and returns the created record", async () => {+ it("sends email via EMAIL_WORKER and returns the created record", async () => {mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test-agent" });+ mockEmailWorkerFetch.mockResolvedValue(+ Response.json({ ok: true, r2Key: "emails/abc/raw" }),+ );mockCreateEmail.mockResolvedValue({id: "e1", agentId: "a1", fromEmail: "[email protected]",toEmail: "[email protected]", subject: "Hello",});- mockR2Put.mockResolvedValue(undefined);- mockSendEmailSend.mockResolvedValue({ messageId: "msg1" });const req = new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {method: "POST",@@ -81,24 +76,31 @@ describe("POST /api/email/send", () => {const res = await POST(req, {} as any);expect(res.status).toBe(200);- expect(mockSendEmailSend).toHaveBeenCalled();- expect(mockR2Put).toHaveBeenCalled();- expect(mockCreateEmail).toHaveBeenCalled();-- // Verify single-part message (no boundary)- const r2Content = mockR2Put.mock.calls[0]![1] as string;- expect(r2Content).toContain("Content-Type: text/html; charset=utf-8");- expect(r2Content).not.toContain("multipart");++ // Verify EMAIL_WORKER was called+ expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();+ const [url, init] = mockEmailWorkerFetch.mock.calls[0];+ expect(url).toBe("http://internal/send/agent");+ expect(init.method).toBe("POST");+ const fetchBody = JSON.parse(init.body);+ expect(fetchBody.agentId).toBe("a1");+ expect(fetchBody.to).toBe("[email protected]");+ expect(fetchBody.subject).toBe("Hello");+ expect(fetchBody.htmlBody).toBe("<p>Hi there</p>");+ expect(fetchBody.attachmentKeys).toBeUndefined();++ // Verify DB record created with r2Key from email worker+ expect(mockCreateEmail).toHaveBeenCalledOnce();+ const createArgs = mockCreateEmail.mock.calls[0]![1] as any;+ expect(createArgs.r2Key).toBe("emails/abc/raw");});- it("sends email with attachments as MIME multipart/mixed", async () => {+ it("sends email with attachments via EMAIL_WORKER", async () => {mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test-agent" });+ mockEmailWorkerFetch.mockResolvedValue(+ Response.json({ ok: true, r2Key: "emails/def/raw" }),+ );mockCreateEmail.mockResolvedValue({ id: "e1" });- mockR2Put.mockResolvedValue(undefined);- mockSendEmailSend.mockResolvedValue({ messageId: "msg1" });- mockR2Get.mockResolvedValue({- arrayBuffer: () => Promise.resolve(new TextEncoder().encode("file content").buffer),- });const attachments = [{ key: "emails/drafts/x/doc.txt", filename: "doc.txt", size: 12, contentType: "text/plain" },@@ -118,39 +120,35 @@ describe("POST /api/email/send", () => {const res = await POST(req, {} as any);expect(res.status).toBe(200);- // Verify MIME multipart message stored in R2- const r2Content = mockR2Put.mock.calls[0]![1] as string;- expect(r2Content).toContain("multipart/mixed");- expect(r2Content).toContain("Content-Disposition: attachment; filename=\"doc.txt\"");- expect(r2Content).toContain("Content-Transfer-Encoding: base64");+ // Verify attachmentKeys sent to email worker+ const fetchBody = JSON.parse(mockEmailWorkerFetch.mock.calls[0][1].body);+ expect(fetchBody.attachmentKeys).toEqual([+ { key: "emails/drafts/x/doc.txt", filename: "doc.txt", contentType: "text/plain" },+ ]);- // Verify attachments passed to createEmail+ // Verify full attachments stored in DB recordconst createArgs = mockCreateEmail.mock.calls[0]![1] as any;expect(createArgs.attachments).toBe(JSON.stringify(attachments));});- it("skips missing R2 attachments gracefully", async () => {+ it("returns error when EMAIL_WORKER fails", async () => {mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test-agent" });- mockCreateEmail.mockResolvedValue({ id: "e1" });- mockR2Put.mockResolvedValue(undefined);- mockSendEmailSend.mockResolvedValue({ messageId: "msg1" });- mockR2Get.mockResolvedValue(null); // R2 object not found+ mockEmailWorkerFetch.mockResolvedValue(+ new Response(JSON.stringify({ error: "agent not found" }), { status: 404 }),+ );const req = new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {method: "POST",body: JSON.stringify({agentId: "a1",to: "[email protected]",- subject: "Missing attachment",- htmlBody: "<p>Oops</p>",- attachments: [- { key: "emails/drafts/gone/file.pdf", filename: "file.pdf", size: 100, contentType: "application/pdf" },- ],+ subject: "Hello",+ htmlBody: "<p>Hi</p>",}),});const res = await POST(req, {} as any);- expect(res.status).toBe(200);+ expect(res.status).toBe(404);});it("returns 400 when agent has no emailHandle", async () => {diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.tsindex d649c4cda..3d2089741 100644--- a/src/web/src/app/api/email/send/route.ts+++ b/src/web/src/app/api/email/send/route.ts@@ -1,22 +1,12 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare";-import { createDb, queries } from "@alook/shared";+import { createDb, queries, DEV_EMAIL_WORKER_URL } from "@alook/shared";import type { EmailAttachment } from "@alook/shared";-import { nanoid } from "nanoid";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeJSON, writeError } from "@/lib/middleware/helpers";import { emailToResponse } from "@/lib/api/responses";-function arrayBufferToBase64(buffer: ArrayBuffer): string {- const bytes = new Uint8Array(buffer);- let binary = "";- for (let i = 0; i < bytes.byteLength; i++) {- binary += String.fromCharCode(bytes[i]!);- }- return btoa(binary);-}-export const POST = withAuth(async (req: NextRequest, ctx) => {const ws = await withWorkspaceMember(req, ctx);if (ws instanceof Response) return ws;@@ -49,87 +39,52 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("agent has no email handle configured", 400);}- const fromAddress = `${agent.emailHandle}@alook.ai`;const attachments = body.attachments ?? [];- let raw: string;-- if (attachments.length === 0) {- // Simple single-part message- raw = [- `From: ${fromAddress}`,- `To: ${body.to}`,- `Subject: ${body.subject}`,- `Date: ${new Date().toUTCString()}`,- `MIME-Version: 1.0`,- `Content-Type: text/html; charset=utf-8`,- "",- body.htmlBody || "",- ].join("\r\n");- } else {- // Multipart/mixed with attachments- const boundary = `----=_Part_${nanoid(16)}`;-- const headers = [- `From: ${fromAddress}`,- `To: ${body.to}`,- `Subject: ${body.subject}`,- `Date: ${new Date().toUTCString()}`,- `MIME-Version: 1.0`,- `Content-Type: multipart/mixed; boundary="${boundary}"`,- "",- `--${boundary}`,- `Content-Type: text/html; charset=utf-8`,- `Content-Transfer-Encoding: 7bit`,- "",- body.htmlBody || "",- ];-- const parts: string[] = [];- for (const att of attachments) {- const obj = await cfEnv.EMAIL_BUCKET.get(att.key);- if (!obj) continue;- const buf = await obj.arrayBuffer();- const b64 = arrayBufferToBase64(buf);-- parts.push(- [- `--${boundary}`,- `Content-Type: ${att.contentType}; name="${att.filename}"`,- `Content-Disposition: attachment; filename="${att.filename}"`,- `Content-Transfer-Encoding: base64`,- "",- b64.match(/.{1,76}/g)?.join("\r\n") ?? b64,- ].join("\r\n")- );- }+ // Delegate sending + R2 archival to the email worker+ const emailPayload = JSON.stringify({+ agentId: body.agentId,+ workspaceId: ws.workspaceId,+ to: body.to,+ subject: body.subject,+ htmlBody: body.htmlBody || "",+ attachmentKeys: attachments.length > 0+ ? attachments.map((a) => ({ key: a.key, filename: a.filename, contentType: a.contentType }))+ : undefined,+ });- raw = [...headers, ...parts, `--${boundary}--`].join("\r\n");+ let emailRes: Response;+ try {+ emailRes = await cfEnv.EMAIL_WORKER.fetch("http://internal/send/agent", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: emailPayload,+ });+ } catch {+ // Service binding not connected — fall back to direct URL (local dev)+ emailRes = await fetch(`${DEV_EMAIL_WORKER_URL}/send/agent`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: emailPayload,+ });}- // Store raw email in R2- const r2Id = nanoid();- const r2Key = `emails/${r2Id}/raw`;- await cfEnv.EMAIL_BUCKET.put(r2Key, raw, {- httpMetadata: { contentType: "message/rfc822" },- });+ if (!emailRes.ok) {+ const errBody = await emailRes.text();+ return writeError(`email worker error: ${errBody}`, emailRes.status);+ }- // Send via Cloudflare SendEmail binding- await cfEnv.SEND_EMAIL.send({- from: fromAddress,- to: body.to,- subject: body.subject,- html: body.htmlBody || "",- });+ const emailResult = await emailRes.json() as { ok: boolean; r2Key: string };// Create DB record+ const fromAddress = `${agent.emailHandle}@alook.ai`;const email = await queries.email.createEmail(db, {agentId: body.agentId,workspaceId: ws.workspaceId,fromEmail: fromAddress,toEmail: body.to,subject: body.subject,- r2Key,+ r2Key: emailResult.r2Key,isWhitelisted: false,forwarded: false,htmlBody: body.htmlBody || "",diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex 155e1d348..15b8281df 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -3,7 +3,7 @@ declare namespace Cloudflare {DB: D1DatabaseEMAIL_BUCKET: R2BucketWS_DO_WORKER: Fetcher- SEND_EMAIL: SendEmail+ EMAIL_WORKER: FetcherNEXT_INC_CACHE_R2_BUCKET: R2BucketNEXT_TAG_CACHE_D1: D1DatabaseNEXT_CACHE_DO_QUEUE: DurableObjectNamespacediff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex d5f922b44..d1220dc39 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -1,6 +1,6 @@import { betterAuth } from "better-auth"import { emailOTP } from "better-auth/plugins"-import { createLogger } from "@alook/shared"+import { createLogger, DEV_EMAIL_WORKER_URL } from "@alook/shared"import { getOtpSubject, renderOtpEmail } from "./email-templates"const isProd = process.env.NODE_ENV === "production"@@ -31,12 +31,26 @@ export function createAuth(env: Env) {async sendVerificationOTP({ email, otp, type }) {log.info("sending OTP email", { to: email, type })try {- await env.SEND_EMAIL.send({- from: "[email protected]",+ const otpPayload = JSON.stringify({to: email,subject: getOtpSubject(type),html: renderOtpEmail(otp, type),})+ const fetchOpts = {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: otpPayload,+ }+ let res: Response+ try {+ res = await env.EMAIL_WORKER.fetch("http://internal/send/otp", fetchOpts)+ } catch {+ res = await fetch(`${DEV_EMAIL_WORKER_URL}/send/otp`, fetchOpts)+ }+ if (!res.ok) {+ const errBody = await res.text()+ throw new Error(`EMAIL_WORKER /send/otp failed: ${res.status} ${errBody}`)+ }log.info("OTP email sent", { to: email, type })} catch (err) {log.error("OTP email failed", { to: email, type, err })diff --git a/src/web/src/test/e2e/email.test.ts b/src/web/src/test/e2e/email.test.tsnew file mode 100644index 000000000..65a7d4eb6--- /dev/null+++ b/src/web/src/test/e2e/email.test.ts@@ -0,0 +1,184 @@+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { randomUUID } from "crypto"+import { seedTestData, cleanupTestData, type TestSeed } from "../helpers/seed"+import { tokenRequest } from "../helpers/auth"+import { sql, sqlQuery } from "../helpers/db"++const EMAIL_WORKER_URL = process.env.EMAIL_WORKER_URL ?? "http://localhost:8787"++let seed: TestSeed++beforeAll(() => {+ seed = seedTestData()+})+afterAll(() => cleanupTestData(seed))++/** Build a minimal RFC 5322 email with Message-ID (required by wrangler) */+function rawEmail(from: string, to: string, subject: string, body: string): string {+ const msgId = `<${randomUUID()}@e2e.test>`+ return [+ `From: ${from}`,+ `To: ${to}`,+ `Subject: ${subject}`,+ `Message-ID: ${msgId}`,+ `Date: ${new Date().toUTCString()}`,+ `MIME-Version: 1.0`,+ `Content-Type: text/plain; charset=utf-8`,+ "",+ body,+ ].join("\r\n")+}++/** Poll D1 until at least one email row matches, or timeout */+async function waitForEmail(+ agentId: string,+ fromEmail: string,+ maxMs = 5000,+): Promise<Record<string, unknown> | null> {+ const start = Date.now()+ while (Date.now() - start < maxMs) {+ const rows = sqlQuery<Record<string, unknown>>(+ `SELECT * FROM emails WHERE agent_id = '${agentId}' AND from_email = '${fromEmail}' ORDER BY created_at DESC LIMIT 1`,+ )+ if (rows.length > 0) return rows[0]+ await new Promise((r) => setTimeout(r, 300))+ }+ return null+}++// ─── Receive path ───++describe("email receive (inbound)", () => {+ it("whitelisted sender → DB record with is_whitelisted = 1", async () => {+ const from = `${seed.userId}@test.local` // whitelisted in seed+ const to = `${seed.agentEmailHandle}@alook.ai`+ const subject = "E2E whitelisted test"++ const res = await fetch(+ `${EMAIL_WORKER_URL}/cdn-cgi/handler/email?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: rawEmail(from, to, subject, "Hello from e2e"),+ },+ )+ // wrangler returns 200 for accepted emails+ expect(res.status).toBe(200)++ const row = await waitForEmail(seed.agentId, from)+ expect(row).not.toBeNull()+ expect(row!.subject).toBe(subject)+ expect(row!.is_whitelisted).toBe(1)+ })++ it("non-whitelisted sender → DB record with is_whitelisted = 0", async () => {+ const from = "[email protected]"+ const to = `${seed.agentEmailHandle}@alook.ai`+ const subject = "E2E non-whitelisted test"++ await fetch(+ `${EMAIL_WORKER_URL}/cdn-cgi/handler/email?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: rawEmail(from, to, subject, "Stranger email"),+ },+ )++ const row = await waitForEmail(seed.agentId, from)+ expect(row).not.toBeNull()+ expect(row!.subject).toBe(subject)+ expect(row!.is_whitelisted).toBe(0)+ })++ it("unknown handle → no email record created", async () => {+ const from = "[email protected]"+ const to = "[email protected]"+ const subject = "E2E unknown handle"++ await fetch(+ `${EMAIL_WORKER_URL}/cdn-cgi/handler/email?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: rawEmail(from, to, subject, "Should be rejected"),+ },+ )++ // Small wait to ensure nothing is written+ await new Promise((r) => setTimeout(r, 1000))++ const rows = sqlQuery<Record<string, unknown>>(+ `SELECT * FROM emails WHERE from_email = '${from}' AND subject = '${subject}'`,+ )+ expect(rows).toHaveLength(0)+ })+})++// ─── Send path ───++describe("email send (outbound)", () => {+ it("POST /api/email/send → 200 with r2_key and DB record", async () => {+ const res = await tokenRequest(+ `/api/email/send?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ agentId: seed.agentId,+ to: "[email protected]",+ subject: "E2E send test",+ htmlBody: "<p>Hello from e2e</p>",+ }),+ },+ )+ expect(res.status).toBe(200)++ const data = await res.json() as Record<string, unknown>+ expect(data.r2_key).toBeTruthy()+ expect(data.from_email).toBe(`${seed.agentEmailHandle}@alook.ai`)+ expect(data.to_email).toBe("[email protected]")+ expect(data.subject).toBe("E2E send test")+ })++ it("POST /api/email/send with agent missing emailHandle → 400", async () => {+ // Create a temporary agent without emailHandle+ const tmpAgentId = `ag_tmp_${Date.now()}`+ const now = new Date().toISOString()+ sql(`INSERT INTO agent (id, workspace_id, name, runtime_id, created_at, updated_at) VALUES ('${tmpAgentId}', '${seed.workspaceId}', 'No Handle Agent', '${seed.runtimeId}', '${now}', '${now}')`)++ try {+ const res = await tokenRequest(+ `/api/email/send?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ agentId: tmpAgentId,+ to: "[email protected]",+ subject: "Should fail",+ htmlBody: "<p>No handle</p>",+ }),+ },+ )+ expect(res.status).toBe(400)+ } finally {+ sql(`DELETE FROM agent WHERE id = '${tmpAgentId}'`)+ }+ })++ it("POST /api/email/send missing required fields → 400", async () => {+ const res = await tokenRequest(+ `/api/email/send?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ agentId: seed.agentId }),+ },+ )+ expect(res.status).toBe(400)+ })+})diff --git a/src/web/src/test/helpers/seed.ts b/src/web/src/test/helpers/seed.tsindex 7eec08866..0877b9aeb 100644--- a/src/web/src/test/helpers/seed.ts+++ b/src/web/src/test/helpers/seed.ts@@ -8,6 +8,7 @@ export interface TestSeed {runtimeId: stringdaemonId: stringagentId: string+ agentEmailHandle: string/** Raw machine token (starts with al_) */machineToken: stringmachineTokenId: string@@ -30,6 +31,8 @@ export function seedTestData(): TestSeed {const daemonId = `daemon_${nanoid()}`const machineTokenId = `mt_${nanoid()}`const rawToken = `al_${randomUUID().replace(/-/g, "")}`+ const emailHandle = `e2e-${nanoid()}`+ const whitelistId = `wl_${nanoid()}`const now = new Date().toISOString()const slug = `test-${nanoid()}`@@ -39,10 +42,11 @@ export function seedTestData(): TestSeed {sql(`INSERT INTO member (id, workspace_id, user_id, role, created_at) VALUES ('${memberId}', '${workspaceId}', '${userId}', 'owner', '${now}')`)sql(`INSERT INTO machine (daemon_id, workspace_id, device_info, last_seen_at, created_at, updated_at) VALUES ('${daemonId}', '${workspaceId}', 'test-device', '${now}', '${now}', '${now}')`)sql(`INSERT INTO agent_runtime (id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES ('${runtimeId}', '${workspaceId}', '${daemonId}', 'Test Runtime', 'local', 'claude', 'online', 'test-device', '${now}', '${now}')`)- sql(`INSERT INTO agent (id, workspace_id, name, runtime_id, created_at, updated_at) VALUES ('${agentId}', '${workspaceId}', 'Test Agent', '${runtimeId}', '${now}', '${now}')`)+ sql(`INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES ('${agentId}', '${workspaceId}', 'Test Agent', '${runtimeId}', '${emailHandle}', '${userId}', '${now}', '${now}')`)sql(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES ('${machineTokenId}', '${userId}', '${workspaceId}', '${rawToken}', 'test-token', 'active', '${now}')`)+ sql(`INSERT INTO agent_whitelist (id, agent_id, workspace_id, email, created_at) VALUES ('${whitelistId}', '${agentId}', '${workspaceId}', '${userId}@test.local', '${now}')`)- return { userId, workspaceId, memberId, runtimeId, daemonId, agentId, machineToken: rawToken, machineTokenId }+ return { userId, workspaceId, memberId, runtimeId, daemonId, agentId, agentEmailHandle: emailHandle, machineToken: rawToken, machineTokenId }}/**diff --git a/src/web/wrangler.toml b/src/web/wrangler.tomlindex b64e8a942..9b85d1305 100644--- a/src/web/wrangler.toml+++ b/src/web/wrangler.toml@@ -53,6 +53,7 @@ bucket_name = "alook-emails"binding = "WS_DO_WORKER"service = "alook-ws-do"-# Outbound email sending via Cloudflare Email Routing-[[send_email]]-name = "SEND_EMAIL"+[[services]]+binding = "EMAIL_WORKER"+service = "alook-email-worker"+diff --git a/src/ws-do/package.json b/src/ws-do/package.jsonindex 8af90791f..c4324fab3 100644--- a/src/ws-do/package.json+++ b/src/ws-do/package.json@@ -7,12 +7,14 @@"deploy": "wrangler deploy","test": "vitest run --passWithNoTests"},- "dependencies": { "@alook/shared": "workspace:*" },+ "dependencies": {+ "@alook/shared": "workspace:*"+ },"devDependencies": {- "wrangler": "^4.82.2",- "typescript": "^6.0.2","@cloudflare/workers-types": "^4.20260414.1","@types/node": "^25.6.0",- "vitest": "^4.1.4"+ "typescript": "^6.0.2",+ "vitest": "^4.1.4",+ "wrangler": "^4.83.0"}}