diff --git a/.github/workflows/cloud-migrator-artifacts.yml b/.github/workflows/cloud-migrator-artifacts.yml index f4da1b25b17..ae00650cd1e 100644 --- a/.github/workflows/cloud-migrator-artifacts.yml +++ b/.github/workflows/cloud-migrator-artifacts.yml @@ -79,7 +79,7 @@ jobs: uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4 with: subject-path: migrator-artifacts/manifest.json - - uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6 + - uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 with: role-to-assume: arn:aws:iam::078455283791:role/paperclip-cloud-migrator-github aws-region: us-east-1 diff --git a/.github/workflows/runner-full-stack-e2e.yml b/.github/workflows/runner-full-stack-e2e.yml index dd8c096b715..0600886144d 100644 --- a/.github/workflows/runner-full-stack-e2e.yml +++ b/.github/workflows/runner-full-stack-e2e.yml @@ -1274,7 +1274,7 @@ jobs: path: runner-e2e-merged-report - name: Exchange GitHub OIDC identity for scoped AWS credentials - uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6 + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 with: role-to-assume: ${{ vars.RUNNER_E2E_HISTORY_AWS_ROLE_ARN }} aws-region: ${{ vars.RUNNER_E2E_HISTORY_AWS_REGION }} diff --git a/.github/workflows/runner-protocol-live-evals.yml b/.github/workflows/runner-protocol-live-evals.yml index 7cedfd602c0..850d30ba5c7 100644 --- a/.github/workflows/runner-protocol-live-evals.yml +++ b/.github/workflows/runner-protocol-live-evals.yml @@ -878,7 +878,7 @@ jobs: path: runner-protocol-trusted-viewer - name: Exchange GitHub OIDC identity for scoped AWS credentials - uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6 + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 with: role-to-assume: ${{ vars.RUNNER_PROTOCOL_EVAL_HISTORY_AWS_ROLE_ARN || vars.RUNNER_E2E_HISTORY_AWS_ROLE_ARN }} aws-region: ${{ vars.RUNNER_PROTOCOL_EVAL_HISTORY_AWS_REGION || vars.RUNNER_E2E_HISTORY_AWS_REGION }} diff --git a/.github/workflows/storybook-deploy.yml b/.github/workflows/storybook-deploy.yml index 6256f70b4aa..1f440d0adc2 100644 --- a/.github/workflows/storybook-deploy.yml +++ b/.github/workflows/storybook-deploy.yml @@ -143,7 +143,7 @@ jobs: name: ${{ needs.build.outputs.artifact_name }} path: storybook-static - name: Assume the Storybook-only uploader role - uses: aws-actions/configure-aws-credentials@e6de054238d6b7531b4efff3b6587d9aade6a06c # v6 + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6 with: role-to-assume: ${{ vars.STORYBOOK_AWS_ROLE_ARN }} aws-region: ${{ vars.STORYBOOK_AWS_REGION }} diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md index 7d0dde2ea5f..ac5b8790419 100644 --- a/doc/SPEC-implementation.md +++ b/doc/SPEC-implementation.md @@ -1724,10 +1724,10 @@ when the run fails, before generic recovery retries. Reconnect preserves account identity and permissions. Compatible legacy agents may explicitly adopt a validated connection inline; late failures must not invalidate newer credentials. -### Experimental task-bound email +### Task-bound email -AgentMail channel connections extend the experimental conversation/task pipeline -with explicit email publication. Each owned inbox/provider thread binds one task; +AgentMail is a default connection and does not require the experimental chat +setting. It extends the conversation/task pipeline with explicit email publication. Each owned inbox/provider thread binds one task; external email senders do not gain board authority. Incoming correspondence uses the assigned agent's normal execution controls. Internal task activity never implicitly sends email. New outgoing conversations create child tasks and durable diff --git a/doc/connections/AGENTMAIL.md b/doc/connections/AGENTMAIL.md index 8310cbe846b..717c3fc9e2a 100644 --- a/doc/connections/AGENTMAIL.md +++ b/doc/connections/AGENTMAIL.md @@ -1,13 +1,38 @@ # AgentMail email connections -AgentMail is an experimental **channel** connection. Enable experimental chat -connections, open Apps → AgentMail, select which humans and agents may use the -credential, then enter an API key. In the saved connection’s Permissions page, -choose **Give an agent an email address**. The three-step wizard selects an agent, -creates or attaches an address, and reviews the setup. Selecting an agent outside -the current allowed list adds that agent when setup completes. Every provider thread in that inbox has one Paperclip task. Subjects are -not identifiers. The same email delivered to two connected inboxes creates two -independent tasks. +AgentMail is a default **channel** connection. Open Connectors → AgentMail; +no experimental setting is required. Setup has two steps: pick the agent, then +pick its email address and create it. For a new connection, the first step also +suggests an accessible saved AgentMail account key, or asks for a new API key. +New credentials default to company-wide human access and only the selected agent. +Reusing a key preserves its grants and other agent installs. The domain dropdown sits +beside the email name and defaults to the first verified custom domain, falling +back to `agentmail.to`. An explicit choice is preserved across reloads. Receiving +mode, sender guidance, and trust settings are under **Advanced options**; an +existing low-trust agent still needs its required work boundary and runtime. +There is no separate review or Permissions detour. Each provider thread in the +inbox becomes one Paperclip task. Subjects are not identifiers. The same email +delivered to two connected inboxes creates two independent tasks. + +**Add connection** starts a fresh setup identity, so an earlier unfinished key +or address cannot silently replace the new form. **Finish setup** on a draft row +resumes that exact inbox with its saved account and request ID, including an +address already allocated before a later provider failure. Cancel and Done +return to Connectors; Email settings opens the inbox settings. The email step +groups the task/thread explanation under **How it Works**. + +After allocation, the address is shown as text with **Finish connecting**. +**Choose a different address** restores the editable name and domain fields with +a new setup identity. The previous inbox stays in AgentMail, and its draft can +still be resumed from Connectors. Retrying never silently creates a replacement. +Changing accounts also opens a new setup URL after saving the replacement key +and retiring the empty draft, so refresh preserves the new account and request. + +Get API keys from [AgentMail's API-key page](https://console.agentmail.to/dashboard/api-keys). +When an agent requests AgentMail in a chat or task, an inline card asks only for +the key. It defaults to company-wide human access and this agent only, then +creates an address (or connects the existing address for an inbox-scoped key). +The agent resumes only after its inbox is usable. Access can be adjusted later on the saved connection’s Permissions page. Setup accepts an AgentMail API key or the saved company credential from another AgentMail connection. Organization and pod keys create an inbox-scoped runtime @@ -15,10 +40,37 @@ key. An existing inbox-scoped key can connect only its own inbox. Credentials are vaulted and resolved by the server; they are not passed to agents. An inbox can have only one non-archived Paperclip endpoint across the instance. +The shared API-key field offers labeled saved credentials and an explicit new-key +choice. The server filters suggestions by company, provider, active secret, and +current-user grants. Scope metadata is saved during key validation; legacy keys +are checked with bounded concurrency under a shared three-second deadline. +No secret values are returned. Use still rechecks authorization and the key. +Organization/pod keys are preferred over inbox-only keys. The same picker is used +by the inline card. Unrelated or unbound secrets are not suggested. + +An inbox-only key is caught on the agent/key step before the email form. Choose +an account key to type a new name and pick a domain, or explicitly choose +**Use the existing inbox instead**. Old locked drafts recover at this key choice. +The selected credential or explicit new-key choice survives refresh without +storing the key text. Failed inline setup offers **Change API key** before any +address is allocated; it retires an empty draft and preserves the replacement +request identity across refresh. +Switching preserves the agent and starts a new setup request. Agent dropdowns +use the shared avatar-aware selector for both options and the selected value. +An already allocated inbox must finish its original setup before changing accounts. + Verified custom domains are selectable after checking the API key. Complete DNS setup in [AgentMail](https://docs.agentmail.to/custom-domains). Paperclip does not register domains or manage DNS. +Debounced address checks search the account's visible inbox list (up to 100 +entries), rather than requesting a not-yet-created inbox by ID. Live testing +found that AgentMail retains negative inbox lookups: an address checked before +creation could return 404 during access-key creation even after the inbox was +created successfully. Listing avoids this failure. A match is taken; absence is +unknown because the address may be outside the returned page or credential scope. +Final creation still handles global address conflicts. + Failed provider requests retain their HTTP status, a fixed operation name, and an allowlisted [AgentMail error code](https://docs.agentmail.to/errors). For example, `create_inbox` with `missing_permission` differs from `limit_exceeded`. @@ -28,11 +80,11 @@ malformed, larger, or stalled responses keep the original HTTP failure. Provider messages, suggested fixes, URLs, inbox identifiers, and credentials are excluded from these diagnostics. These diagnostics do not retry or suppress failures. -The setup and Permissions page warn that an unrestricted inbox can receive mail -from anyone. Configure sender allowlists in AgentMail; Paperclip does not manage +Advanced options and the Permissions page explain that an unrestricted inbox can +receive mail from anyone. Configure sender allowlists in AgentMail; Paperclip does not manage or verify them. AgentMail controls new-message and reply lists separately. The -wizard recommends Paperclip’s existing **Low-trust review** preset and lets the -operator configure a project or root-task boundary. Incoming tasks are placed +setup lets the operator review the agent’s trust settings and configure a project +or root-task boundary for **Low-trust review**. Incoming tasks are placed inside that boundary. Low-trust execution also requires isolated workspaces and an active sandbox environment selected for the agent; setup rejects an unavailable runtime. New inbound tasks request isolated execution. The trust preset itself does not @@ -45,6 +97,21 @@ An explicitly configured workspace strategy still applies and must be usable. Removing the assigned agent’s saved-connection access or revoking its credential grant stops receiving and sending. Connection creation saves the vaulted binding, human grants, and agent access in one database transaction. +The catalog's **Remove connection** action uses the email inbox control API for +AgentMail, including unfinished drafts. It preserves provider inboxes and task +history while disconnecting Paperclip and removing its owned runtime credentials. + +Each inbox has distinct **Settings**, **Access**, **Conversations**, and +**Activity** views. Access reuses the saved account's credential and agent controls, +so changes apply to every inbox using that account. Conversations links email +threads to their tasks; Activity shows the shared delivery and publication feed. +Settings leads with the agent’s email address: click it to copy with confirmation, +or use **View inbox** to open that inbox in AgentMail’s console. It also explains +how email becomes tasks. +Receiving mode, last mail check, and Pause/Resume are grouped below. Reconnect +credentials live in an expandable section, followed by a separate Disconnect +action. Inbox lifecycle controls use the email API, and reconnect opens inbox Settings. +Unconfirmed email delivery is resolved in its task rather than through chat replay. ## Receiving and task lifecycle @@ -111,6 +178,7 @@ All paths below are relative to `/api`: | --- | --- | | Save credential and human/agent access | `POST /companies/:companyId/email/connections` | | Inspect a saved credential | `POST /companies/:companyId/email/connections/:connectionId/inspect` | +| Check an address without creating an inbox (connection manager) | `POST /companies/:companyId/email/connections/:connectionId/check-address` | | List authorized inboxes | `GET /companies/:companyId/email/inboxes` | | Inspect setup credentials (connection manager) | `POST /companies/:companyId/email/inspect` | | Create or attach an inbox (connection manager) | `POST /companies/:companyId/email/inboxes` | @@ -191,9 +259,44 @@ show publication failures and uncertain delivery resolution. Delivery admission, message processing and agent wakeup are separate from provider delivery and model startup; live latency measurements must distinguish those stages. +Setup reads only allowlisted, documented provider error codes from a bounded +response body. An inbox-creation `resource_taken` or `already_exists` error, +including HTTP 403, appears beside the email field as “This email address is +already in use.” Other 403 errors retain permission guidance. Provider messages, +fixes, and links are never forwarded. Existing addresses visible to the saved +account are flagged before submission. The initial name and subsequent edits +trigger a read-only check after a 350 ms pause; changing the name or domain +aborts the previous request and ignores its result. Checks use the saved credential +behind the same company, connection-management, and connector-feature gates. +Taken addresses show clickable alternatives, excluding known conflicts. A failed +creation also remembers that address in the non-secret setup draft. + +[AgentMail's `not_found` response](https://docs.agentmail.to/errors#not_found) +also hides inboxes outside the credential's scope, so a lookup cannot prove +global availability. Missing addresses show that availability is confirmed on +creation and offer alternatives without claiming they are free. Lookup failures +are visible and leave creation available for its authoritative check; known +conflicts and pending checks disable creation. Other taken addresses are reported +when creation is attempted, without leaving the address step. + +Browser refresh preserves non-secret draft fields and the setup request ID; +API keys are never saved in browser storage. Retrying the same setup resumes any +inbox already created before the failure. Drafts are scoped to the agent requested +by the setup link. Once an inbox has been allocated, its agent and address stay +fixed during recovery. A failed progress lookup can be retried in place. + +When the account and inbox share a setup request ID, completion replaces the +account’s untouched initial agent access with the final selected agent. That +default applies only once and only while the original install rows are unchanged. +Later permission edits and retries preserve existing agent or company installs. +Reusing an account from another setup also preserves its existing installs. Both paths use the email +setup permission (`tools:manage_connections`), without an additional agent-edit +permission. + ## Verification and live qualification Deterministic coverage lives in `server/src/__tests__/agentmail-api.test.ts`, +`server/src/__tests__/email-routes-provider-errors.test.ts`, `server/src/__tests__/email-channels.integration.test.ts`, and `tests/e2e/agentmail.spec.ts`. It exercises real database transactions with a fake provider, plus browser setup and explicit task email actions. diff --git a/doc/connections/CONNECTION-SEARCH.md b/doc/connections/CONNECTION-SEARCH.md index dbcb31c816f..9c0630e21e1 100644 --- a/doc/connections/CONNECTION-SEARCH.md +++ b/doc/connections/CONNECTION-SEARCH.md @@ -12,9 +12,16 @@ is shared across the catalog scan. Discovery includes tool, channel/email, and AI methods. Channel methods follow the instance's Chat connectors experimental setting. Each catalog method names its `purpose`. Channel and AI methods include a company-scoped `setupPath` to -their existing setup flow. `connection_request` still creates tool setup cards; -channel discovery does not turn an email inbox into an executable MCP tool or -add channel setup to that card. +their existing setup flow. AgentMail also supports `connection_request`: it +creates an inline API-key card addressed to the responsible user. Search guidance +prefers this card over a setup link or asking for credentials in chat. Other +channel methods continue to use their setup path. + +The AgentMail card grants company-wide human access and installs access only for +the requesting agent. It saves the credential, provisions or connects an inbox, +and completes only after the server verifies that the assigned inbox is usable. +A saved key alone does not make the search result ready. Partial setup can resume +after reload using the same request ID, without duplicating the account or inbox. The agent chooses the relevant match using descriptions and method purposes. It should clarify only when the task remains ambiguous. A search match does not diff --git a/doc/connections/CONNECTOR-PLAYBOOK.md b/doc/connections/CONNECTOR-PLAYBOOK.md index facfb020010..cd2db9348c8 100644 --- a/doc/connections/CONNECTOR-PLAYBOOK.md +++ b/doc/connections/CONNECTOR-PLAYBOOK.md @@ -569,10 +569,10 @@ they do not need a duplicate native wrapper just to supply a skill. **Resolve eligibility from current assignments and access.** An AgentMail account credential alone does not give an agent email capabilities. An active inbox assigned to that agent does, provided both the inbox connection and saved -credential access remain authorized and the experimental chat-connector flag is -on. Other connectors must define an equally concrete assignment rule. Keep every +credential access remain authorized. AgentMail is available by default and does +not depend on the experimental chat-connector flag. Other connectors must define an equally concrete assignment rule. Keep every lookup company-scoped. Revoked grants, disabled connections, removed assignments, -and experimental gates must remove the contribution. Fail closed on lookup errors. +and any applicable experimental gates must remove the contribution. Fail closed on lookup errors. **Install skills transparently through the existing runtime skill path.** Merge system-managed contributions with the agent's chosen skills for each run, without diff --git a/doc/run-log-events.md b/doc/run-log-events.md index 6fd6bd36a25..adcc57ed69c 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -241,6 +241,13 @@ section in the Observability contract. Provider identity diagnostics remain in the local run log. They record the notification method, expected and received thread/turn identifiers, and the classification (root, verified descendant, stale, unrelated informational, or invalid authoritative). They omit the original provider payload and credentials. Repeated informational notices are bounded. +Ignored unrelated Codex notifications use `harness.diagnostic` with code +`codex_unrelated_information`. The payload retains only the bounded provider +method and expected/received thread and turn identifiers. Account updates, skill +changes, and unrelated thread information do not create a provider notice in +chat. Chat also omits the matching notice stored by older runners. Real provider +warnings and errors remain visible. + Recovery lifecycle events retain the original structured failure code, retry attempt, next retry time, and predecessor/successor identifiers. Durable status delivery uses an idempotency marker; delivery grants no provider authority. Failed publication is retried without repeating provider work. These records are not first-party Telemetry. If execution-continuation setup finds that a task no longer exists, is closed, diff --git a/packages/adapter-utils/src/directory-merge-lock.test.ts b/packages/adapter-utils/src/directory-merge-lock.test.ts index c05305fb8d6..a2b71aac55d 100644 --- a/packages/adapter-utils/src/directory-merge-lock.test.ts +++ b/packages/adapter-utils/src/directory-merge-lock.test.ts @@ -10,7 +10,13 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { withDirectoryMergeLock, WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE } from "./workspace-restore-merge.js"; describe("directory merge lock process lifetime", () => { - const loader = fileURLToPath(new URL("../../../cli/node_modules/tsx/dist/cli.mjs", import.meta.url)); + // Load tsx as an --import hook, not tsx's own CLI entry point. The CLI entry + // point re-spawns the evaluated code in a further child process, so killing + // the process this file spawns would leave that further child as an orphan + // that still holds the lock. The --import hook runs the evaluated code in + // the process this file spawns directly, so killing it really does release + // the lock. + const loader = fileURLToPath(new URL("../../../cli/node_modules/tsx/dist/loader.mjs", import.meta.url)); const module = fileURLToPath(new URL("./workspace-restore-merge.ts", import.meta.url)); const directories: string[] = []; const children: ChildProcess[] = []; @@ -38,7 +44,7 @@ describe("directory merge lock process lifetime", () => { } async function holder(target: string, env: NodeJS.ProcessEnv) { - const child = spawn(process.execPath, [loader, "--eval", ` + const child = spawn(process.execPath, ["--import", loader, "--eval", ` import { withDirectoryMergeLock } from ${JSON.stringify(module)}; withDirectoryMergeLock(${JSON.stringify(target)}, async () => { process.send?.("locked"); @@ -63,10 +69,15 @@ describe("directory merge lock process lifetime", () => { return await access(`${lock}.owner.json`).then(() => `${lock}.owner.json`, () => path.join(lock, "owner.json")); } - function expireWait() { - const now = Date.now(); - return vi.spyOn(Date, "now").mockReturnValueOnce(now).mockReturnValue(now + 60_000); - } + // A short real wait budget for a test that asserts a timeout. 200 ms still + // lets the implementation's 50 ms retry interval run at least 4 retries, so + // the timeout is reached because the lock is genuinely held, not because + // the clock was replaced. + const TIMEOUT_ASSERTION_WAIT_MS = 200; + // A short real wait budget for the crash-recovery test, which asserts a + // successful acquisition. It must absorb ordinary scheduling jitter around + // the crash while still resolving well inside the test timeout below. + const CRASH_RECOVERY_WAIT_MS = 5_000; it("recovers a killed holder even when its recorded PID has been reused", async () => { const { target, env, lock } = await fixture(); @@ -77,10 +88,7 @@ describe("directory merge lock process lifetime", () => { const recordPath = await ownerPath(lock); const record = JSON.parse(await readFile(recordPath, "utf8")); await writeFile(recordPath, JSON.stringify({ ...record, pid: process.pid })); - const clock = expireWait(); - try { - await expect(withDirectoryMergeLock(target, async () => "restored", env)).resolves.toBe("restored"); - } finally { clock.mockRestore(); } + await expect(withDirectoryMergeLock(target, async () => "restored", env, undefined, CRASH_RECOVERY_WAIT_MS)).resolves.toBe("restored"); }, 15_000); it("protects a live holder in another process regardless of diagnostic PID or age", async () => { @@ -89,10 +97,7 @@ describe("directory merge lock process lifetime", () => { const recordPath = await ownerPath(lock); await writeFile(recordPath, JSON.stringify({ pid: 2_147_483_647, createdAt: "2000-01-01T00:00:00.000Z" })); const contender = vi.fn(); - const clock = expireWait(); - try { - await expect(withDirectoryMergeLock(target, contender, env)).rejects.toMatchObject({ code: WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE }); - } finally { clock.mockRestore(); } + await expect(withDirectoryMergeLock(target, contender, env, undefined, TIMEOUT_ASSERTION_WAIT_MS)).rejects.toMatchObject({ code: WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE }); expect(contender).not.toHaveBeenCalled(); const exited = once(child, "exit"); child.send("release"); @@ -109,18 +114,12 @@ describe("directory merge lock process lifetime", () => { it("keeps the OS lock when a same-process contender closes its connection", async () => { const { target, env } = await fixture(); await withDirectoryMergeLock(target, async () => { - const clock = expireWait(); - try { - await expect(withDirectoryMergeLock(target, async () => undefined, env)).rejects.toMatchObject({ code: WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE }); - } finally { clock.mockRestore(); } + await expect(withDirectoryMergeLock(target, async () => undefined, env, undefined, TIMEOUT_ASSERTION_WAIT_MS)).rejects.toMatchObject({ code: WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE }); // A same-process test alone cannot prove that the OS lock survived: on // POSIX, closing an unmanaged descriptor can drop process-wide locks. - const result = await promisify(execFile)(process.execPath, [loader, "--eval", ` + const result = await promisify(execFile)(process.execPath, ["--import", loader, "--eval", ` import { withDirectoryMergeLock, WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE } from ${JSON.stringify(module)}; - const now = Date.now(); - let calls = 0; - Date.now = () => now + calls++ * 60_000; - withDirectoryMergeLock(${JSON.stringify(target)}, async () => "entered") + withDirectoryMergeLock(${JSON.stringify(target)}, async () => "entered", undefined, undefined, ${TIMEOUT_ASSERTION_WAIT_MS}) .then(() => { console.error("Entered a live holder's lock"); process.exit(1); }) .catch(error => { if (error.code !== WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE) { console.error(error); process.exit(1); } @@ -162,10 +161,7 @@ describe("directory merge lock process lifetime", () => { await mkdir(lock, { recursive: true }); if (kind !== "missing") await writeFile(path.join(lock, "owner.json"), kind === "malformed" ? "{broken" : JSON.stringify({ pid: 2_147_483_647, createdAt: "2000-01-01T00:00:00.000Z" })); const contender = vi.fn(); - const clock = expireWait(); - try { - await expect(withDirectoryMergeLock(target, contender, env)).rejects.toMatchObject({ code: WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE }); - } finally { clock.mockRestore(); } + await expect(withDirectoryMergeLock(target, contender, env, undefined, TIMEOUT_ASSERTION_WAIT_MS)).rejects.toMatchObject({ code: WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE }); expect(contender).not.toHaveBeenCalled(); expect((await stat(lock)).isDirectory()).toBe(true); }); diff --git a/packages/adapter-utils/src/workspace-restore-merge.ts b/packages/adapter-utils/src/workspace-restore-merge.ts index 6b05b135b90..14c58371b35 100644 --- a/packages/adapter-utils/src/workspace-restore-merge.ts +++ b/packages/adapter-utils/src/workspace-restore-merge.ts @@ -341,9 +341,9 @@ export function describeWorkspaceRestoreFailure(code: WorkspaceRestoreFailureCod } } -async function acquireDirectoryMergeLock(lockDir: string, operation?: DirectoryMergeLockOperation): Promise<() => Promise> { +async function acquireDirectoryMergeLock(lockDir: string, operation?: DirectoryMergeLockOperation, waitMs: number = LOCK_WAIT_MS): Promise<() => Promise> { const startedAt = performance.now(); - const deadline = Date.now() + LOCK_WAIT_MS; + const deadline = Date.now() + waitMs; const databasePath = `${lockDir}.sqlite`; const ownerPath = `${lockDir}.owner.json`; async function waitForLock(diagnosticOwnerPath: string) { @@ -496,13 +496,16 @@ export async function withDirectoryMergeLock( fn: (canonicalTargetDir: string) => Promise, env: NodeJS.ProcessEnv = process.env, diagnosticOperation?: DirectoryMergeLockOperation, + // Test seam only: overrides how long acquisition waits before it reports a + // timeout. Production callers must omit this and keep the real budget. + waitMs: number = LOCK_WAIT_MS, ): Promise { // Canonicalize before we hash or lock: a retargeted symlink must not let the // lock protect one directory while the caller mutates another. const canonicalTargetDir = await fs.realpath(targetDir); const lockRoot = await resolveDirectoryMergeLockRoot(env); const lockKey = createHash("sha256").update(canonicalTargetDir).digest("hex"); - const releaseLock = await acquireDirectoryMergeLock(path.join(lockRoot, `${lockKey}.lock`), diagnosticOperation); + const releaseLock = await acquireDirectoryMergeLock(path.join(lockRoot, `${lockKey}.lock`), diagnosticOperation, waitMs); try { return await fn(canonicalTargetDir); } finally { diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs b/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs index e0eb95f611c..759f5ef4c1b 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs @@ -812,6 +812,25 @@ pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec + { + push( + &mut events, + "harness.diagnostic", + EventPriority::P1, + json!({ + "code": "codex_unrelated_information", + "classification": "unrelated_information", + "providerMethod": params.get("providerMethod").and_then(Value::as_str).map(|value| bounded_text(value, 160)), + "expectedThreadId": params.get("expectedThreadId").and_then(Value::as_str).map(|value| bounded_text(value, 256)), + "receivedThreadId": params.get("receivedThreadId").and_then(Value::as_str).map(|value| bounded_text(value, 256)), + "expectedTurnId": params.get("expectedTurnId").and_then(Value::as_str).map(|value| bounded_text(value, 256)), + "receivedTurnId": params.get("receivedTurnId").and_then(Value::as_str).map(|value| bounded_text(value, 256)), + }), + ) + } "error" | "warning" | "deprecationNotice" | "configWarning" => push( &mut events, "provider.notice.recorded", @@ -1421,6 +1440,68 @@ fn has_rfc_uri_scheme_prefix(value: &str) -> bool { mod tests { use super::*; + #[test] + fn unrelated_information_retains_only_bounded_run_log_diagnostics() { + let events = normalize_codex_notification( + "warning", + &json!({ + "classification": "unrelated_information", + "message": "ignored unrelated provider information", + "providerMethod": "account/updated", + "expectedThreadId": "root", + "receivedThreadId": "x".repeat(300), + "expectedTurnId": "turn-1", + "receivedTurnId": null, + "accessToken": "not-for-the-log", + "planType": "private-account-data", + }), + ); + assert_eq!(events.len(), 1); + assert_eq!(events[0].event_type, "harness.diagnostic"); + assert_eq!(events[0].priority, EventPriority::P1); + assert_eq!( + events[0].payload, + json!({ + "code": "codex_unrelated_information", + "classification": "unrelated_information", + "providerMethod": "account/updated", + "expectedThreadId": "root", + "receivedThreadId": format!("{}…[truncated]", "x".repeat(244)), + "expectedTurnId": "turn-1", + "receivedTurnId": null, + }) + ); + let unicode_events = normalize_codex_notification( + "warning", + &json!({ + "classification": "unrelated_information", + "expectedThreadId": "token=not-for-the-log", + "receivedThreadId": "😀".repeat(300), + }), + ); + assert_eq!( + unicode_events[0].payload["expectedThreadId"], + "token=[REDACTED]" + ); + assert_eq!( + unicode_events[0].payload["receivedThreadId"], + format!("{}…[truncated]", "😀".repeat(244)) + ); + assert_eq!(unicode_events[0].payload["receivedTurnId"], Value::Null); + // Authoritative errors must retain their failure meaning. + assert_eq!( + normalize_codex_notification( + "error", + &json!({ + "classification": "unrelated_information", + "message": "Provider connection failed", + }) + )[0] + .event_type, + "provider.notice.recorded" + ); + } + #[test] fn preserves_codex_notice_text_from_current_and_legacy_payloads() { for method in ["configWarning", "deprecationNotice", "warning"] { diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/codex_provider.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/codex_provider.rs index 601fb383949..9550fb2e95f 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/codex_provider.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/codex_provider.rs @@ -617,6 +617,14 @@ fn codex_account_updates_do_not_interrupt_turns_or_publish_account_details() { assert!(!params.to_string().contains("fixture-login")); assert!(params.get("authMode").is_none()); assert!(params.get("planType").is_none()); + let normalized = normalize_codex_notification(&method, ¶ms); + assert_eq!(normalized.len(), 1); + assert_eq!(normalized[0].event_type, "harness.diagnostic"); + assert_eq!(normalized[0].payload["code"], "codex_unrelated_information"); + assert_eq!( + normalized[0].payload["providerMethod"], + params["providerMethod"] + ); } if method == "turn/completed" { completed = true; diff --git a/packages/paperclip-runner/src/drivers/codex/app-server-transport.test.ts b/packages/paperclip-runner/src/drivers/codex/app-server-transport.test.ts index 739f0212937..96d277dcef3 100644 --- a/packages/paperclip-runner/src/drivers/codex/app-server-transport.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/app-server-transport.test.ts @@ -59,6 +59,14 @@ describe("Codex app-server transport limits", () => { .toBe("Basic API foundation"); }); + it.each(["PAPERCLIP_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY", "CUSTOM_API_KEY"])( + "redacts the complete %s environment value through the shared text helper", + (key) => { + expect(redactCodexDiagnostic(`${key}=private;still-private`)) + .toBe(`${key}=[REDACTED]`); + }, + ); + it("reports restart-safe process-group ownership", async () => { const transport = nodeTransport("process.stdin.resume()", { processGroup: true }); const info = transport.processInfo(); diff --git a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts index 0b06817a53c..7c86f2bb35c 100644 --- a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts +++ b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts @@ -2,6 +2,9 @@ import type { NativeTurnControlCapabilities } from "../../contracts/types.js"; import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; import type { HarnessRuntimeRequestResolution } from "../../contracts/harness-driver.js"; import { githubCredentialEnvironment } from "../../github-credential-environment.js"; +import { redactCodexDiagnostic } from "./diagnostic-redaction.js"; + +export { redactCodexDiagnostic } from "./diagnostic-redaction.js"; export interface CodexRpcNotification { method: string; @@ -243,40 +246,6 @@ export function sanitizedEnvironmentKeys( return Object.keys(createSanitizedCodexEnvironment(source)).sort(); } -export function redactCodexDiagnostic(message: string): string { - return message - .replaceAll(/\u001b\[[0-?]*[ -/]*[@-~]/g, "") - .replace(/Bearer\s+[A-Za-z0-9._~+\/-]+/gi, "Bearer [REDACTED]") - .replace(/Basic\s+([A-Za-z0-9+/=]+)/gi, (match, encoded: string) => { - try { - // Only redact an actual RFC 7617 credential. Treating every word after - // “Basic” as base64 corrupted ordinary question copy such as - // “Basic API” before it entered the Paperclip protocol. - const decoded = Buffer.from(encoded, "base64").toString("utf8"); - return decoded.includes(":") ? "Basic [REDACTED]" : match; - } catch { - return match; - } - }) - .replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi, "$1[REDACTED]@") - .replace( - /([?&](?:api[_-]?key|token|secret|password)=)[^&#\s]+/gi, - "$1[REDACTED]", - ) - .replace( - /(["'](?:api[_-]?key|token|secret|password|authorization)["']\s*:\s*["'])[^"']+/gi, - "$1[REDACTED]", - ) - .replace( - /(api[_-]?key|token|secret|password)\s*[=:]\s*[^\s,;]+/gi, - "$1=[REDACTED]", - ) - .replace( - /(PAPERCLIP_API_KEY|OPENAI_API_KEY|OPENROUTER_API_KEY)=[^\s]+/g, - "$1=[REDACTED]", - ); -} - function proxyContainsCredentials(value: string): boolean { try { const url = new URL(value); diff --git a/packages/paperclip-runner/src/drivers/codex/diagnostic-redaction.ts b/packages/paperclip-runner/src/drivers/codex/diagnostic-redaction.ts new file mode 100644 index 00000000000..856b9365e41 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/codex/diagnostic-redaction.ts @@ -0,0 +1,33 @@ +/** Redact diagnostic text without importing the provider process or its credentials. */ +export function redactCodexDiagnostic(message: string): string { + return message + .replaceAll(/\u001b\[[0-?]*[ -/]*[@-~]/g, "") + .replace(/Bearer\s+[A-Za-z0-9._~+\/-]+/gi, "Bearer [REDACTED]") + .replace(/Basic\s+([A-Za-z0-9+/=]+)/gi, (match, encoded: string) => { + try { + // Only redact an actual RFC 7617 credential. Ordinary prose such as + // “Basic API” must remain readable. + const decoded = Buffer.from(encoded, "base64").toString("utf8"); + return decoded.includes(":") ? "Basic [REDACTED]" : match; + } catch { + return match; + } + }) + .replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi, "$1[REDACTED]@") + .replace( + /([?&](?:api[_-]?key|token|secret|password)=)[^&#\s]+/gi, + "$1[REDACTED]", + ) + .replace( + /(["'](?:api[_-]?key|token|secret|password|authorization)["']\s*:\s*["'])[^"']+/gi, + "$1[REDACTED]", + ) + .replace( + /(api[_-]?key|token|secret|password)\s*[=:]\s*[^\s,;]+/gi, + "$1=[REDACTED]", + ) + .replace( + /((?:[A-Z][A-Z0-9]*_)+API_KEY)=[^\s]+/g, + "$1=[REDACTED]", + ); +} diff --git a/packages/paperclip-runner/src/provider-events.test.ts b/packages/paperclip-runner/src/provider-events.test.ts index c395477b41e..043399c5e50 100644 --- a/packages/paperclip-runner/src/provider-events.test.ts +++ b/packages/paperclip-runner/src/provider-events.test.ts @@ -34,6 +34,48 @@ function envelope( } describe("provider-neutral events", () => { + it("keeps unrelated information as bounded run-log evidence without a provider notice", () => { + const [event] = canonicalProviderEventsFromCodex("warning", { + classification: "unrelated_information", + message: "ignored unrelated provider information", + providerMethod: "account/updated", + expectedThreadId: "root", + receivedThreadId: "x".repeat(300), + expectedTurnId: "turn-1", + receivedTurnId: null, + accessToken: "not-for-the-log", + planType: "private-account-data", + }); + expect(event).toEqual({ + eventType: "harness.diagnostic", + itemId: "provider-item", + payload: { + code: "codex_unrelated_information", + classification: "unrelated_information", + providerMethod: "account/updated", + expectedThreadId: "root", + receivedThreadId: "x".repeat(244) + "…[truncated]", + expectedTurnId: "turn-1", + receivedTurnId: null, + }, + }); + expect(validatePrpEvent(envelope(event)).ok).toBe(true); + const [unicodeEvent] = canonicalProviderEventsFromCodex("warning", { + classification: "unrelated_information", + expectedThreadId: "token=not-for-the-log", + receivedThreadId: "😀".repeat(300), + }); + expect(unicodeEvent.payload).toMatchObject({ + expectedThreadId: "token=[REDACTED]", + receivedThreadId: "😀".repeat(244) + "…[truncated]", + receivedTurnId: null, + }); + expect(canonicalProviderEventsFromCodex("error", { + classification: "unrelated_information", + message: "Provider connection failed", + })[0].eventType).toBe("provider.notice.recorded"); + }); + it("preserves Codex notice summaries with legacy and empty-message fallbacks", () => { for (const method of ["configWarning", "deprecationNotice", "warning"]) { for (const [params, expected] of [ diff --git a/packages/paperclip-runner/src/provider-events.ts b/packages/paperclip-runner/src/provider-events.ts index 360a70c96d5..e163706c53d 100644 --- a/packages/paperclip-runner/src/provider-events.ts +++ b/packages/paperclip-runner/src/provider-events.ts @@ -1,4 +1,5 @@ import { createHash } from "node:crypto"; +import { redactCodexDiagnostic } from "./drivers/codex/diagnostic-redaction.js"; /** * Structural subset of an ACP runtime event consumed by the canonical event @@ -593,6 +594,29 @@ export function canonicalProviderEventsFromCodex( const type = text(item.type); const itemId = safeId(text(item.id, text(params.itemId)), "provider-item"); const completed = method === "item/completed"; + if (method === "warning" && params.classification === "unrelated_information") { + const boundedField = (key: string, limit: number) => { + if (typeof params[key] !== "string") return null; + const characters = [...redactCodexDiagnostic(params[key])]; + const marker = "…[truncated]"; + return characters.length <= limit + ? characters.join("") + : characters.slice(0, limit - marker.length).join("") + marker; + }; + return [{ + eventType: "harness.diagnostic", + itemId, + payload: { + code: "codex_unrelated_information", + classification: "unrelated_information", + providerMethod: boundedField("providerMethod", 160), + expectedThreadId: boundedField("expectedThreadId", 256), + receivedThreadId: boundedField("receivedThreadId", 256), + expectedTurnId: boundedField("expectedTurnId", 256), + receivedTurnId: boundedField("receivedTurnId", 256), + }, + }]; + } if (method === "turn/plan/updated") { const turnPlanId = safeId(text(params.turnId), "turn-plan"); return [ diff --git a/packages/shared/src/app-definitions/agentmail.json b/packages/shared/src/app-definitions/agentmail.json index f4e22e81224..edd0799b198 100644 --- a/packages/shared/src/app-definitions/agentmail.json +++ b/packages/shared/src/app-definitions/agentmail.json @@ -37,7 +37,7 @@ ], "guidanceMd": "Connect an AgentMail API key, then create or select an inbox for your agent. WebSocket receiving works without a public URL.", "consoleLinks": { - "keys": "https://console.agentmail.to", + "keys": "https://console.agentmail.to/dashboard/api-keys", "docs": "https://docs.agentmail.to/inboxes" }, "riskTier": "S3", diff --git a/packages/shared/src/connection-intent-guidance.ts b/packages/shared/src/connection-intent-guidance.ts index 3866243d6ae..3078023901c 100644 --- a/packages/shared/src/connection-intent-guidance.ts +++ b/packages/shared/src/connection-intent-guidance.ts @@ -13,7 +13,7 @@ export const CONNECTION_INTENT_AGENT_GUIDANCE = [ "- Do not use connection tools for arbitrary MCP URLs or unrelated work.", ].join("\n"); -export const CONNECTIONS_SEARCH_TOOL_DESCRIPTION = "Search connections across tool, channel/email, and AI purposes with a service name or a natural-language description (up to 4000 characters). Results tolerate extra words, split names, and small typos. Choose the relevant match using its description, method purpose, and setupPath; tool methods use connection_request. Also discovers verified external aggregator apps. Use first when the user asks to connect a service, or when usable access is uncertain; follow the returned instruction and exact providerQuestion, if any. Do not use for arbitrary MCP URLs. Search is read-only."; +export const CONNECTIONS_SEARCH_TOOL_DESCRIPTION = "Search connections across tool, channel/email, and AI purposes with a service name or a natural-language description (up to 4000 characters). Results tolerate extra words, split names, and small typos. Choose the relevant match using its description and method purpose. Follow the returned instruction to present an inline setup card with connection_request or share the method's setupPath. Also discovers verified external aggregator apps. Use first when the user asks to connect a service, or when usable access is uncertain; follow the returned instruction and exact providerQuestion, if any. Do not use for arbitrary MCP URLs. Search is read-only."; export const CONNECTION_REQUEST_TOOL_DESCRIPTION = "Request the service identifier returned by connections_search as available or needs_user_action. Follow the search instruction; aggregator routes require the saved provider-selection interaction ID. Only this tool creates the real setup card. If user action is needed, finish independent work, then yield without retrying or asking for credentials in comments."; diff --git a/packages/shared/src/feature-catalog.ts b/packages/shared/src/feature-catalog.ts index 2cd27bf5e0f..4ee053e46c6 100644 --- a/packages/shared/src/feature-catalog.ts +++ b/packages/shared/src/feature-catalog.ts @@ -118,7 +118,7 @@ export const INSTANCE_FEATURE_CATALOG: Record; export interface ConnectionIntentSetupOptions { + /** Resume this request's saved AgentMail account after a partial setup. */ + emailSetup?: { credentialConnectionId: string | null; readyConnectionId: string | null }; aiConnection?: import("../ai-connections.js").AiConnectionBinding; /** Legacy authentication stays unchanged until the normal validated agent update succeeds. */ aiConnectionRequiresAdoption?: boolean; diff --git a/packages/shared/src/types/email.ts b/packages/shared/src/types/email.ts index fb158df36ce..556ff6a0dce 100644 --- a/packages/shared/src/types/email.ts +++ b/packages/shared/src/types/email.ts @@ -52,3 +52,17 @@ export interface EmailThreadSummary { messages: EmailMessage[]; publications: EmailPublicationSummary[]; } +/** A missing inbox is not proof of availability: AgentMail hides other accounts. */ +export interface EmailAddressCheckResult { + address: string; + status: "taken" | "unknown"; +} + +/** Metadata only, filtered by provider and the current user's credential grants. */ +export interface EmailCredentialOption { + id: string; + label: string; + scope: "organization" | "pod" | "inbox" | "unavailable"; + inboxId: string | null; + createdAt: string; +} diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 22e5e0ae37a..ef9d2962d29 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -1359,8 +1359,8 @@ export type ConnectionIntentPhase = "requested" | "authorizing" | "needs_retry"; export interface ConnectionIntentPayload { version: 1; upstreamService?: { slug: string; name: string; selectionInteractionId?: string }; - /** Runtime authentication requests cannot be satisfied by tool credentials. */ - purpose?: "ai"; + /** AI authentication and inbox setup cannot be satisfied by tool credentials. */ + purpose?: "ai" | "channel"; serviceSlug: string; serviceName: string; serviceLogoUrl?: string | null; diff --git a/packages/shared/src/validators/email.ts b/packages/shared/src/validators/email.ts index f96bf0f1881..661624d1217 100644 --- a/packages/shared/src/validators/email.ts +++ b/packages/shared/src/validators/email.ts @@ -2,6 +2,12 @@ import { z } from "zod"; const address = z.string().trim().email().max(320); const addresses = z.array(address).max(50); +export const emailAddressCheckSchema = z.object({ + username: z.string().trim().toLowerCase().regex(/^[a-z0-9][a-z0-9._-]*$/).max(64), + domain: z.string().trim().toLowerCase().max(253).regex(/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/), +}).strict(); +export type EmailAddressCheckInput = z.infer; + export const emailEndpointSetupSchema = z .object({ assignedAgentId: z.string().uuid(), diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.ts index c2a1795b3f1..99f1c22f1eb 100644 --- a/packages/shared/src/validators/issue.ts +++ b/packages/shared/src/validators/issue.ts @@ -1111,7 +1111,7 @@ const connectionIntentBrandAssetSchema = z export const connectionIntentPayloadSchema = z .object({ upstreamService: z.object({ slug: z.string().min(1).max(120), name: z.string().min(1).max(160), selectionInteractionId: z.string().guid().optional() }).strict().optional(), - purpose: z.literal("ai").optional(), + purpose: z.enum(["ai", "channel"]).optional(), version: z.literal(1), serviceSlug: z.string().trim().min(1).max(120), serviceName: z.string().trim().min(1).max(160), diff --git a/packages/shared/src/worktree-port-registry.test.ts b/packages/shared/src/worktree-port-registry.test.ts index 28c6c869d8e..ad52c4b3e55 100644 --- a/packages/shared/src/worktree-port-registry.test.ts +++ b/packages/shared/src/worktree-port-registry.test.ts @@ -2,6 +2,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { setTimeout as delay } from "node:timers/promises"; +import { Worker } from "node:worker_threads"; import { afterEach, describe, expect, it } from "vitest"; import { withWorktreePortRegistryLock, @@ -16,12 +17,92 @@ function makeTemporaryRoot(): string { return root; } -function deferred(): { promise: Promise; resolve: () => void } { - let resolve!: () => void; - const promise = new Promise((done) => { - resolve = done; +// Answers the same one-exchange ownership probe protocol the real lock +// heartbeat serves, so a test can hold a lock's "owner is alive and +// responsive" state without a live heartbeat thread touching the lock's +// mtime in the background. This runs on its own worker thread, not the +// main thread, because the code under test blocks the calling thread +// (Atomics.wait) while it waits for a probe answer; a same-thread server +// could never respond to its own blocked caller. +// The worker posts an "owned" message back to the main thread each time it +// answers a probe with "owned". The test waits on that message instead of a +// fixed delay, so the assertion that follows only runs after the probe has +// actually answered at least one ownership check, not merely after some +// wall-clock time. +const FAKE_OWNERSHIP_PROBE_SOURCE = ` +const net = require("node:net"); +const { parentPort, workerData } = require("node:worker_threads"); +const control = new Int32Array(workerData.control); +const server = net.createServer((socket) => { + socket.once("data", (candidate) => { + const answer = candidate.toString("utf8") === workerData.token ? "owned" : "denied"; + if (answer === "owned") parentPort.postMessage("owned"); + socket.end(answer); }); - return { promise, resolve }; +}); +server.once("error", () => { + Atomics.store(control, 0, -1); + Atomics.notify(control, 0); +}); +server.listen(0, "127.0.0.1", () => { + const address = server.address(); + Atomics.store(control, 1, address.port); + Atomics.store(control, 0, 1); + Atomics.notify(control, 0); +}); +parentPort.once("message", () => { + server.close(() => process.exit(0)); +}); +`; + +function startFakeOwnershipProbe(token: string): { + port: number; + waitForOwnedResponse: (timeoutMs?: number) => Promise; + close: () => Promise; +} { + const control = new Int32Array(new SharedArrayBuffer(8)); + const worker = new Worker(FAKE_OWNERSHIP_PROBE_SOURCE, { + eval: true, + execArgv: [], + workerData: { control: control.buffer, token }, + }); + Atomics.wait(control, 0, 0, 5_000); + const port = Atomics.load(control, 1); + if (Atomics.load(control, 0) !== 1 || port <= 0) { + void worker.terminate(); + throw new Error("The fake ownership probe failed to start."); + } + + let ownedResponseSeen = false; + const ownedWaiters: Array<() => void> = []; + worker.on("message", (message: unknown) => { + if (message !== "owned") return; + ownedResponseSeen = true; + for (const resolveWaiter of ownedWaiters.splice(0)) resolveWaiter(); + }); + + return { + port, + // Resolves once the probe has answered "owned" at least once. Falls + // straight through when that has already happened, and otherwise waits + // for the worker's next "owned" message. + waitForOwnedResponse: (timeoutMs = 5_000): Promise => { + if (ownedResponseSeen) return Promise.resolve(); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new Error("Timed out waiting for the fake ownership probe to answer \"owned\".")); + }, timeoutMs); + ownedWaiters.push(() => { + clearTimeout(timer); + resolve(); + }); + }); + }, + close: () => new Promise((resolve) => { + worker.once("exit", () => resolve()); + worker.postMessage("stop"); + }), + }; } afterEach(() => { @@ -34,36 +115,70 @@ describe("worktree port registry lock", () => { it("does not reclaim a stale lock while its fallback ownership probe responds", async () => { const homeDir = makeTemporaryRoot(); const lockPath = path.join(homeDir, ".worktree-port-reservations.lock"); - const firstEntered = deferred(); - const releaseFirst = deferred(); - let secondEntered = false; + const token = "fixed-owner-token"; + const probe = startFakeOwnershipProbe(token); + let probeClosed = false; + const closeProbeOnce = async (): Promise => { + if (probeClosed) return; + probeClosed = true; + await probe.close(); + }; + let second: Promise | undefined; - const first = withWorktreePortRegistryLock(homeDir, async () => { - fs.renameSync(path.join(lockPath, "owner.json"), path.join(lockPath, "owner.unavailable.json")); - const backupOwnerPath = path.join(lockPath, "owner.backup.json"); - const owner = JSON.parse(fs.readFileSync(backupOwnerPath, "utf8")); - fs.writeFileSync(backupOwnerPath, `${JSON.stringify({ - ...owner, - processIdentity: "unavailable-process-identity", - })}\n`); + try { + // Build the contended state directly instead of holding the lock through + // a real withWorktreePortRegistryLock call. A real call starts a live + // heartbeat that rewrites the lock's mtime once a second on a worker + // thread. That refresh runs concurrently with, and can land inside, the + // gap between this test backdating the mtime and reading it back, which + // made the assertion below fail at random under CPU contention. With no + // live heartbeat, nothing touches the mtime until this test says so. + fs.mkdirSync(lockPath); + fs.writeFileSync( + path.join(lockPath, "owner.json"), + `${JSON.stringify({ + version: 1, + pid: process.pid, + // Deliberately wrong, so a reclaim can only be blocked by the probe + // answering "owned" below, not by the process-identity fallback. + processIdentity: "mismatched-process-identity", + probePort: probe.port, + token, + })}\n`, + ); const oldTimestamp = new Date(Date.now() - 10_000); fs.utimesSync(lockPath, oldTimestamp, oldTimestamp); - firstEntered.resolve(); - await releaseFirst.promise; - }); - await firstEntered.promise; - expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeGreaterThan(5_000); + // Nothing refreshes the lock after this point, so its age only grows. + expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeGreaterThan(5_000); - const second = withWorktreePortRegistryLock(homeDir, async () => { - secondEntered = true; - }); - await delay(100); + let secondEntered = false; + second = withWorktreePortRegistryLock(homeDir, async () => { + secondEntered = true; + }); + // Wait for the fake probe to actually answer "owned" before checking + // secondEntered. A fixed delay can fire before the probe worker gets + // scheduled under processor contention, letting the assertion below + // pass without proving the reclaim was blocked by a real "owned" + // answer. + await probe.waitForOwnedResponse(); - expect(secondEntered).toBe(false); - releaseFirst.resolve(); - await Promise.all([first, second]); - expect(secondEntered).toBe(true); + expect(secondEntered).toBe(false); + + // Retire the owner: the probe stops answering, so the next reclaim + // attempt falls through to the process-identity check, which the + // mismatched identity above fails, and the lock is reclaimed. + await closeProbeOnce(); + await second; + expect(secondEntered).toBe(true); + } finally { + // Run this unconditionally. If an assertion above throws, the fake + // probe's worker thread must still stop, and the pending lock attempt + // must still settle, so a failure here does not leak a worker thread + // or leave an unawaited rejection for a later test file to report. + await closeProbeOnce(); + await second?.catch(() => {}); + } }, 10_000); it("refreshes the lease throughout an async critical section", async () => { @@ -71,8 +186,27 @@ describe("worktree port registry lock", () => { const lockPath = path.join(homeDir, ".worktree-port-reservations.lock"); await withWorktreePortRegistryLock(homeDir, async () => { - await delay(5_250); - expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeLessThan(2_000); + // Count refreshes instead of only checking recency. A recency check + // alone tolerates a regressed heartbeat interval: a tick every 3000 ms + // or 4000 ms still keeps the lock's age under the 5000 ms staleness + // threshold at the end of this window, so it would pass. Counting the + // distinct mtimes the lock passes through does not depend on when a + // tick lands, only on how many land, so it still catches a regressed + // interval. + const observedTimestamps = new Set(); + const pollDeadline = Date.now() + 5_250; + while (Date.now() < pollDeadline) { + observedTimestamps.add(fs.statSync(lockPath).mtimeMs); + await delay(100); + } + // A 1000 ms heartbeat interval produces about 6 distinct values here + // (the initial touch plus about 5 refreshes). A regressed 3000 ms + // interval produces only 2, so this catches the regression that a + // recency-only check would miss. + expect(observedTimestamps.size).toBeGreaterThanOrEqual(3); + // The heartbeat's other correctness job is to keep the lock's mtime + // below the staleness threshold (5 seconds) while the lock is held. + expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeLessThan(5_000); }); expect(fs.existsSync(lockPath)).toBe(false); @@ -139,7 +273,10 @@ describe("worktree port registry lock", () => { const oldTimestamp = new Date(Date.now() - 10_000); fs.utimesSync(lockPath, oldTimestamp, oldTimestamp); Atomics.wait(blocker, 0, 0, 1_500); - expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeLessThan(1_250); + // Same reasoning as the async critical-section test above: assert + // against the staleness threshold the heartbeat exists to defend, + // not a tight margin coupled to one heartbeat interval. + expect(Date.now() - fs.statSync(lockPath).mtimeMs).toBeLessThan(5_000); }); expect(fs.existsSync(lockPath)).toBe(false); diff --git a/server/src/__tests__/agentmail-api.test.ts b/server/src/__tests__/agentmail-api.test.ts index 727a11c6f8e..21a17d77108 100644 --- a/server/src/__tests__/agentmail-api.test.ts +++ b/server/src/__tests__/agentmail-api.test.ts @@ -24,6 +24,43 @@ const message = (extra = {}) => ...extra, }); describe("AgentMail protocol boundary", () => { + it("checks the visible inbox list without probing an uncreated address", async () => { + const fetcher = vi.fn(async () => Response.json({ inboxes: [{ inbox_id: "Ralph@agentmail.to" }] })); + await expect(agentmailApi("private-key", fetcher).checkAddress("ralph@agentmail.to")) + .resolves.toEqual({ address: "ralph@agentmail.to", status: "taken" }); + expect(fetcher).toHaveBeenCalledOnce(); + expect(fetcher).toHaveBeenCalledWith("https://api.agentmail.to/v0/inboxes?limit=100", expect.objectContaining({ method: "GET", body: undefined })); + }); + it("never treats an unlisted inbox as proof that an address is available", async () => { + const fetcher = vi.fn(async () => Response.json({ inboxes: [], next_page_token: "more-inboxes" })); + await expect(agentmailApi("private-key", fetcher).checkAddress("ralph@agentmail.to")) + .resolves.toEqual({ address: "ralph@agentmail.to", status: "unknown" }); + }); + it("can create the checked address and its access key when the provider caches missing inbox lookups", async () => { + let created = false; + let negativeLookupCached = false; + const fetcher = vi.fn(async (url: string | URL | Request, init?: RequestInit) => { + const path = new URL(String(url)).pathname; + if (path === "/v0/inboxes" && init?.method === "GET") return Response.json({ inboxes: [] }); + if (path === "/v0/inboxes" && init?.method === "POST") { + created = true; + return Response.json({ inbox_id: "ralph@agentmail.to" }); + } + if (path === "/v0/inboxes/ralph%40agentmail.to" && !created) negativeLookupCached = true; + if (!created || negativeLookupCached) return Response.json({ code: "not_found" }, { status: 404 }); + return Response.json({ api_key: "test-runtime-key", api_key_id: "runtime-id" }); + }); + const api = agentmailApi("test-account-key", fetcher); + await expect(api.checkAddress("ralph@agentmail.to")).resolves.toMatchObject({ status: "unknown" }); + const inbox = await api.createInbox({ username: "ralph" }); + await expect(api.createInboxKey(inbox.inbox_id)).resolves.toMatchObject({ api_key_id: "runtime-id" }); + expect(negativeLookupCached).toBe(false); + }); + it.each([401, 403, 404, 429, 503])("preserves lookup errors (%s) rather than claiming an address is taken or free", async status => { + const fetcher = vi.fn(async () => Response.json({ code: "missing_permission" }, { status })); + await expect(agentmailApi("private-key", fetcher).checkAddress("ralph@agentmail.to")) + .rejects.toMatchObject({ status, operation: "list_inboxes" }); + }); it("verifies the exact raw body and rejects forged or stale Svix signatures", () => { const secret = `whsec_${Buffer.from("a-test-secret-only").toString("base64")}`; const body = JSON.stringify({ @@ -322,6 +359,10 @@ describe("AgentMail protocol boundary", () => { expect(send?.responses).toHaveProperty("202"); const setup = operations.find(o => o.path === "/api/companies/{companyId}/email/inspect"); expect(JSON.stringify(setup?.authorization)).toContain("board"); + const check = operations.find(o => o.path === "/api/companies/{companyId}/email/connections/{connectionId}/check-address"); + expect(check?.requestBody).toBeDefined(); + expect(JSON.stringify(check?.authorization)).toContain("board"); + expect(check?.responses).toHaveProperty("429"); }); }); diff --git a/server/src/__tests__/connection-aggregator-fallback.test.ts b/server/src/__tests__/connection-aggregator-fallback.test.ts index 689a628ae3d..4ccea4c46df 100644 --- a/server/src/__tests__/connection-aggregator-fallback.test.ts +++ b/server/src/__tests__/connection-aggregator-fallback.test.ts @@ -281,17 +281,24 @@ const support = await getEmbeddedPostgresTestSupport(); await instanceSettingsService(db).updateExperimental({ enableChatConnectors: false }); } }); - it("discovers all purposes with truthful setup actions and the chat feature gate", async () => { + it.each([false, true])("discovers AgentMail with truthful setup actions regardless of the chat setting (%s)", async (enabled) => { await resetQuestions(); const service = connectionIntentService(db); - expect((await service.search(claims, "agentmail")).results.some(item => item.service === "agentmail")).toBe(false); - await instanceSettingsService(db).updateExperimental({ enableChatConnectors: true }); + await instanceSettingsService(db).updateExperimental({ enableChatConnectors: enabled }); try { const result = await service.search(claims, "agentmail"); expect(result.results[0]?.methods).toEqual([expect.objectContaining({ key: "email-agent", purpose: "channel", setupPath: `/AGG/apps/chat/connect?provider=agentmail&purpose=chat&agentId=${claims.sub}`, })]); - expect(result.instruction).toContain("setupPath"); + expect(result.instruction).toContain("connection_request"); + const requested = await service.request(claims, "agentmail"); + expect(requested).toMatchObject({ state: "needs_user_action", interactionId: expect.any(String) }); + expect(await service.request(claims, "agentmail")).toMatchObject({ interactionId: requested.interactionId }); + const options = await service.setupOptions(requested.interactionId!); + expect(options.interaction.payload).toMatchObject({ purpose: "channel", serviceSlug: "agentmail", requestingAgentId: claims.sub }); + expect(options.emailSetup).toEqual({ credentialConnectionId: null, readyConnectionId: null }); + await service.decline(requested.interactionId!, "responsible-user"); + await expect(service.request(claims, "agentmail")).rejects.toThrow(/already been resolved/); const browse = await service.search(claims, ""); expect(browse.results.some(item => item.service === "agentmail")).toBe(true); expect(browse.results.some(item => item.service === "anthropic")).toBe(true); diff --git a/server/src/__tests__/email-address-check.test.ts b/server/src/__tests__/email-address-check.test.ts new file mode 100644 index 00000000000..08a13e0e682 --- /dev/null +++ b/server/src/__tests__/email-address-check.test.ts @@ -0,0 +1,82 @@ +import express from "express"; +import request from "supertest"; +import type { Db } from "@paperclipai/db"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { forbidden } from "../errors.js"; +import { errorHandler } from "../middleware/error-handler.js"; +import { emailRoutes } from "../routes/email.js"; +import type { EmailChannelService } from "../services/email-channels.js"; + +const mocks = vi.hoisted(() => ({ credential: vi.fn(), listCredentials: vi.fn(), permission: vi.fn() })); +vi.mock("../services/email-connections.js", () => ({ emailConnectionService: () => ({ credential: mocks.credential, listCredentials: mocks.listCredentials }) })); +vi.mock("../services/access.js", () => ({ accessService: () => ({ hasPermission: mocks.permission }) })); +const companyId = "11111111-1111-4111-8111-111111111111"; +const connectionId = "22222222-2222-4222-8222-222222222222"; +const path = `/api/companies/${companyId}/email/connections/${connectionId}/check-address`; +const input = { username: "ralph", domain: "agentmail.to" }; +function app(actor = { type: "board", source: "local_implicit", userId: "board" } as express.Request["actor"]) { + const instance = express(); + instance.use(express.json()); + instance.use((req, _res, next) => { req.actor = actor; next(); }); + instance.use("/api", emailRoutes({} as Db, {} as EmailChannelService)); + instance.use(errorHandler); + return instance; +} +beforeEach(() => { + vi.resetAllMocks(); + mocks.credential.mockResolvedValue({ value: "private-key" }); + vi.stubGlobal("fetch", vi.fn(async () => Response.json({ inboxes: [{ inbox_id: "ralph@agentmail.to" }] }))); +}); +afterEach(() => vi.unstubAllGlobals()); +describe("AgentMail address checks", () => { + it("lists saved-key metadata with company and manager access checks", async () => { + const listPath = `/api/companies/${companyId}/email/connections`; + mocks.listCredentials.mockResolvedValue([{ id: connectionId, label: "AgentMail account key", scope: "organization" }]); + const response = await request(app()).get(listPath).expect(200); + expect(response.headers["cache-control"]).toBe("no-store"); + expect(mocks.listCredentials).toHaveBeenCalledWith(companyId, expect.objectContaining({ userId: "board" })); + mocks.listCredentials.mockClear(); + await request(app({ type: "agent", agentId: connectionId, companyId })).get(listPath).expect(403); + await request(app({ type: "board", source: "session", userId: "member", companyIds: [] })).get(listPath).expect(404); + await request(app({ type: "board", source: "session", userId: "member", companyIds: [companyId] })).get(listPath).expect(403); + expect(mocks.listCredentials).not.toHaveBeenCalled(); + }); + it("uses the company-scoped saved credential and returns only address status", async () => { + const response = await request(app()).post(path).send({ username: "Ralph", domain: "AgentMail.to" }).expect(200); + expect(response.body).toEqual({ address: "ralph@agentmail.to", status: "taken" }); + expect(response.headers["cache-control"]).toBe("no-store"); + expect(mocks.credential).toHaveBeenCalledWith(companyId, connectionId, expect.objectContaining({ userId: "board" })); + expect(fetch).toHaveBeenCalledWith("https://api.agentmail.to/v0/inboxes?limit=100", expect.objectContaining({ method: "GET" })); + expect(response.text).not.toContain("private-key"); + }); + it.each([ + { username: "bad/name", domain: "agentmail.to" }, + { username: "r".repeat(65), domain: "agentmail.to" }, + { username: "ralph", domain: "https://other.test" }, + { ...input, apiKey: "unexpected" }, + ])("rejects malformed input before reading credentials (%#)", async body => { + await request(app()).post(path).send(body).expect(400); + expect(mocks.credential).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + }); + it("does not allow agents to check addresses", async () => { + await request(app({ type: "agent", agentId: connectionId, companyId })).post(path).send(input).expect(403); + expect(fetch).not.toHaveBeenCalled(); + }); + it("requires company access and connection management permission", async () => { + await request(app({ type: "board", source: "session", userId: "member", companyIds: [] })).post(path).send(input).expect(404); + await request(app({ type: "board", source: "session", userId: "member", companyIds: [companyId] })).post(path).send(input).expect(403); + expect(mocks.credential).not.toHaveBeenCalled(); + }); + it("preserves credential access checks", async () => { + mocks.credential.mockRejectedValueOnce(forbidden("Credential access denied")); + await request(app()).post(path).send(input).expect(403); + expect(fetch).not.toHaveBeenCalled(); + }); + it("surfaces rate limits without copying provider bodies", async () => { + vi.mocked(fetch).mockResolvedValueOnce(Response.json({ code: "rate_limit_exceeded", message: "private-key" }, { status: 429, headers: { "retry-after": "10" } })); + const response = await request(app()).post(path).send(input).expect(429); + expect(response.headers["retry-after"]).toBe("10"); + expect(response.text).not.toContain("private-key"); + }); +}); diff --git a/server/src/__tests__/email-channels.integration.test.ts b/server/src/__tests__/email-channels.integration.test.ts index 3c969b76c61..adcdda01844 100644 --- a/server/src/__tests__/email-channels.integration.test.ts +++ b/server/src/__tests__/email-channels.integration.test.ts @@ -1,3 +1,4 @@ +import { connectionIntentService } from "../services/connection-intents.js"; import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments, annotateConnectorSkills } from "../services/connector-runtime.js"; import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js"; import { renderPaperclipWakePrompt, resolvePaperclipDesiredSkillNames, resolveLegacyPaperclipDesiredSkillNames } from "@paperclipai/adapter-utils/server-utils"; @@ -5,6 +6,7 @@ import express from "express"; import type WebSocket from "ws"; import request from "supertest"; import { issueRoutes } from "../routes/issues.js"; +import { emailRoutes } from "../routes/email.js"; import { errorHandler } from "../middleware/index.js"; import { issueRecoveryActionService } from "../services/issue-recovery-actions.js"; import { randomUUID } from "node:crypto"; @@ -43,6 +45,7 @@ import { issues, authUsers, companyMemberships, + principalPermissionGrants, toolConnections, toolConnectionInstalls, connectionGrants, @@ -59,6 +62,7 @@ import { agentmailMessageSchema, type AgentmailMessage, } from "../services/agentmail-api.js"; +import { accessService } from "../services/access.js"; import { emailConnectionService } from "../services/email-connections.js"; import { toolAccessService } from "../services/tool-access.js"; import { emailSendSchema } from "@paperclipai/shared"; @@ -78,7 +82,7 @@ describe("AgentMail durable email pipeline", () => { database = await startEmbeddedPostgresTestDatabase("paperclip-email-"); db = createDb(database.connectionString); await instanceSettingsService(db).updateExperimental({ - enableChatConnectors: true, + enableChatConnectors: false, }); await db.insert(authUsers).values({ id: "email-board", @@ -178,12 +182,11 @@ describe("AgentMail durable email pipeline", () => { expect((await resolveConnectorAssignments(db, binding))[0].resources).toHaveLength(1); }); - it("removes connector contributions when the experimental gate or credential access is revoked", async () => { + it("keeps AgentMail available with chat disabled and removes contributions when credential access is revoked", async () => { const f = await fixture(); const binding = { companyId: f.companyId, agentId: f.agentId }; await instanceSettingsService(db).updateExperimental({ enableChatConnectors: false }); - try { expect(await resolveConnectorAssignments(db, binding)).toEqual([]); } - finally { await instanceSettingsService(db).updateExperimental({ enableChatConnectors: true }); } + expect((await resolveConnectorAssignments(db, binding)).map(item => item.key)).toEqual(["agentmail"]); const endpoint = await f.service.getEndpoint(f.endpointId); await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, endpoint.connectionId)); expect(await resolveConnectorAssignments(db, binding)).toEqual([]); @@ -981,6 +984,57 @@ describe("AgentMail durable email pipeline", () => { expect(f.wakeup).toHaveBeenCalledTimes(1); }); + it("suggests only same-provider active credentials authorized for this user", async () => { + const f = await fixture(); + const svc = emailConnectionService(db, f.fetcher); + const actor = { userId: "email-board" }; + const own = await svc.connect(f.companyId, { apiKey: "private-key", grantKind: "user", allAgents: false, + agentIds: [], idempotencyKey: randomUUID() }, actor); + const shared = await svc.connect(f.companyId, { apiKey: "shared-key", grantKind: "organization", allAgents: false, + agentIds: [], idempotencyKey: randomUUID() }, actor); + const other = await svc.connect(f.companyId, { apiKey: "other-user-key", grantKind: "user", allAgents: false, + agentIds: [], idempotencyKey: randomUUID() }, { userId: "different-user" }); + const choices = await svc.listCredentials(f.companyId, actor); + expect(choices.map(option => option.id).sort()).toEqual([own.id, shared.id].sort()); + expect(JSON.stringify(choices)).not.toMatch(/private-key|shared-key|other-user-key|secretId|api_key_hash/); + expect(choices[0]).toMatchObject({ scope: "inbox", inboxId: f.address }); + expect((await svc.listCredentials(randomUUID(), actor))).toEqual([]); + await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, own.id)); + await db.update(toolConnections).set({ config: { provider: "different", emailCredential: true } }).where(eq(toolConnections.id, shared.id)); + expect(await svc.listCredentials(f.companyId, actor)).toEqual([]); + expect((await svc.listCredentials(f.companyId, { userId: "different-user" })).map(option => option.id)).toEqual([other.id]); + }); + + it("bounds legacy saved-key discovery and checks slow keys concurrently", async () => { + const f = await fixture(); + const actor = { userId: "email-board" }; + const svc = emailConnectionService(db, f.fetcher); + const ids = []; + for (let i = 0; i < 2; i++) { + const row = await svc.connect(f.companyId, { apiKey: `legacy-key-${i}`, grantKind: "organization", allAgents: false, + agentIds: [], idempotencyKey: randomUUID() }, actor); + ids.push(row.id); + await db.update(toolConnections).set({ config: { provider: "agentmail", emailCredential: true } }).where(eq(toolConnections.id, row.id)); + } + let concurrent = 0, peak = 0; + const signals: AbortSignal[] = []; + const slowFetch = vi.fn(async (_url, init) => { + concurrent++; peak = Math.max(peak, concurrent); + const signal = init!.signal!; signals.push(signal); + try { + return await new Promise((_resolve, reject) => { + if (signal.aborted) reject(new Error("Discovery deadline")); + else signal.addEventListener("abort", () => reject(new Error("Discovery deadline")), { once: true }); + }); + } finally { concurrent--; } + }); + const choices = await emailConnectionService(db, slowFetch).listCredentials(f.companyId, actor); + expect(choices.map(option => option.id).sort()).toEqual(ids.sort()); + expect(choices.every(option => option.scope === "unavailable")).toBe(true); + expect(peak).toBe(2); + expect(signals.every(signal => signal.aborted)).toBe(true); + }, 10_000); + it("saves a scoped credential before inbox setup, preserves personal ownership, and adds the chosen agent", async () => { const f = await fixture(); const svc = emailConnectionService(db, f.fetcher); @@ -1060,6 +1114,214 @@ describe("AgentMail durable email pipeline", () => { ).rejects.toThrow(/revoked/); }); + it.each(["new", "reused"] as const)("finishes a %s account for the final agent with only connection-management permission", async kind => { + const f = await fixture("websocket"); + const actor = { userId: "email-board" }; + await f.service.control(f.endpointId, "remove", actor); + const selectedAgentId = randomUUID(); + await db.insert(agents).values({ id: selectedAgentId, companyId: f.companyId, name: "Final email agent", + role: "engineer", status: "idle", adapterType: "process", permissions: {} }); + await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "user", + principalId: actor.userId, permissionKey: "tools:manage_connections" }); + expect(await accessService(db).hasPermission(f.companyId, "user", actor.userId, "tools:manage_connections")).toBe(true); + expect(await accessService(db).hasPermission(f.companyId, "user", actor.userId, "agent_config:update")).toBe(false); + const requestId = randomUUID(); + const svc = emailConnectionService(db, f.fetcher); + const connection = await svc.connect(f.companyId, { apiKey: "test-key", grantKind: "organization", + allAgents: false, agentIds: [f.agentId], idempotencyKey: kind === "new" ? requestId : randomUUID() }, actor); + const server = express(); + server.use(express.json()); + server.use((req, _res, next) => { + req.actor = { type: "board", source: "session", userId: actor.userId, companyIds: [f.companyId] }; + next(); + }); + server.use("/api", emailRoutes(db, f.service)); + server.use(errorHandler); + const input = { assignedAgentId: selectedAgentId, credentialConnectionId: connection.id, + inboxId: f.address, receiveMode: "websocket", idempotencyKey: requestId }; + const route = `/api/companies/${f.companyId}/email/inboxes`; + // Keep one listener for this journey instead of racing ephemeral listeners + // against Node's HTTP keep-alive socket reuse between requests. + const http = server.listen(0, "127.0.0.1"); + await new Promise((resolve, reject) => { http.once("listening", resolve); http.once("error", reject); }); + try { + const response = await request(http).post(route).send(input).expect(201); + expect(response.body).toMatchObject({ assignedAgentId: selectedAgentId, status: "active", address: f.address }); + await request(http).post(route).send(input).expect(201); + const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id)); + expect(installs.map(i => i.targetId).sort()).toEqual((kind === "new" ? [selectedAgentId] : [f.agentId, selectedAgentId]).sort()); + await expect(svc.assertAgentAccess(f.companyId, connection.id, selectedAgentId)).resolves.toBeUndefined(); + if (kind === "new") await expect(svc.assertAgentAccess(f.companyId, connection.id, f.agentId)).rejects.toThrow(/no longer has access/); + await request(http).post(`/api/companies/${randomUUID()}/email/inboxes`).send(input).expect(404); + } finally { + await new Promise((resolve, reject) => http.close(error => error ? reject(error) : resolve())); + } + }); + + it.each([ + ["before setup", "company"], ["before setup", "agents"], + ["after a failed setup", "company"], ["after a failed setup", "agents"], + ] as const)("preserves permissions edited %s to include %s access", async (when, scope) => { + const f = await fixture("websocket"); + const actor = { userId: "email-board" }; + await f.service.control(f.endpointId, "remove", actor); + const selectedAgentId = randomUUID(), otherAgentId = randomUUID(); + await db.insert(agents).values([selectedAgentId, otherAgentId].map(id => ({ id, companyId: f.companyId, + name: "Email agent", role: "engineer", status: "idle", adapterType: "process", permissions: {} }))); + const requestId = randomUUID(); + const connection = await emailConnectionService(db, f.fetcher).connect(f.companyId, { + apiKey: "test-key", grantKind: "organization", allAgents: false, agentIds: [f.agentId], idempotencyKey: requestId, + }, actor); + const input = { assignedAgentId: selectedAgentId, credentialConnectionId: connection.id, + inboxId: f.address, receiveMode: "websocket" as const, idempotencyKey: requestId }; + if (when === "after a failed setup") { + const provider = vi.mocked(f.fetcher).getMockImplementation()!; + vi.mocked(f.fetcher).mockImplementation(async (url, init) => + decodeURIComponent(new URL(String(url)).pathname) === `/v0/inboxes/${f.address}` + ? new Response(null, { status: 403 }) : provider(url, init)); + await expect(f.service.setup(f.companyId, input, actor)).rejects.toThrow(); + vi.mocked(f.fetcher).mockImplementation(provider); + } + const requestedInstalls = scope === "company" + ? [{ targetType: "company" as const, targetId: f.companyId }] + : [f.agentId, otherAgentId].map(targetId => ({ targetType: "agent" as const, targetId })); + await toolAccessService(db).putConnectionInstalls(connection.id, { installs: requestedInstalls }, { actorType: "user", actorId: actor.userId }); + const before = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id)); + const result = await f.service.setup(f.companyId, input, actor); + expect(result.status).toBe("active"); + const after = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id)); + for (const install of before) expect(after).toContainEqual(install); + expect(after.map(i => i.targetId).sort()).toEqual((scope === "company" ? [f.companyId] : [f.agentId, otherAgentId, selectedAgentId]).sort()); + }); + + it.each(["create_inbox", "create_inbox_key", "address_taken"] as const)("reports a provider rejection during %s and resumes the same setup after correction", async (failedOperation) => { + const f = await fixture("websocket"); + await f.service.control(f.endpointId, "remove", { userId: "email-board" }); + const provider = vi.mocked(f.fetcher).getMockImplementation()!; + let denied = true; + let createdInboxes = 0; + vi.mocked(f.fetcher).mockImplementation(async (url, init) => { + const pathname = new URL(String(url)).pathname; + if (pathname === "/v0/auth/me" && new Headers(init?.headers).get("authorization") === "Bearer organization-test-key") { + return Response.json({ scope_type: "organization", organization_id: "organization" }); + } + if (pathname === "/v0/inboxes" && init?.method === "POST") { + if (failedOperation === "address_taken") { + const body = JSON.parse(String(init.body)); + if (body.username === "ralph") return Response.json({ code: "resource_taken", message: "private provider detail" }, { status: 403 }); + expect(body.username).toBe("ralph-team"); + } + if (denied && failedOperation === "create_inbox") return new Response("private provider denial", { status: 403 }); + createdInboxes++; + return Response.json({ inbox_id: f.address }); + } + if (pathname.endsWith("/api-keys") && init?.method === "POST") { + if (denied && failedOperation === "create_inbox_key") return new Response("private provider denial", { status: 403 }); + return Response.json({ api_key: "test-key", api_key_id: "inbox-runtime-key" }); + } + return provider(url, init); + }); + const account = await emailConnectionService(db, f.fetcher).connect(f.companyId, { + apiKey: "organization-test-key", grantKind: "organization", allAgents: false, + agentIds: [f.agentId], idempotencyKey: randomUUID(), + }, { userId: "email-board" }); + const server = express(); + server.use(express.json()); + server.use((req, _res, next) => { + req.actor = { type: "board", source: "local_implicit", userId: "email-board" }; + next(); + }); + server.use("/api", emailRoutes(db, f.service)); + server.use(errorHandler); + const id = randomUUID(); + const input = { assignedAgentId: f.agentId, credentialConnectionId: account.id, + username: "ralph", domain: "agentmail.to", receiveMode: "websocket", idempotencyKey: id }; + const route = `/api/companies/${f.companyId}/email/inboxes`; + const failure = await request(server).post(route).send(input).expect(failedOperation === "address_taken" ? 409 : 422); + expect(failure.body.error).toContain(failedOperation === "address_taken" ? "already in use" : "AgentMail did not allow Paperclip"); + expect(failure.body.details).toMatchObject({ providerStatus: 403, operation: failedOperation === "address_taken" ? "create_inbox" : failedOperation }); + expect(failure.text).not.toMatch(/private provider denial|organization-test-key|Internal server error/); + const [draft] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, id)); + expect(draft.status).toBe("draft"); + expect(draft.botExternalId).toBe(failedOperation === "create_inbox_key" ? f.address : null); + denied = false; + if (failedOperation === "address_taken") input.username = "ralph-team"; + const connected = await request(server).post(route).send(input).expect(201); + expect(connected.body).toMatchObject({ id, status: "active", address: f.address }); + await request(server).post(route).send(input).expect(201); + expect(createdInboxes).toBe(1); + const endpoints = await db.select().from(chatEndpoints).where(and( + eq(chatEndpoints.companyId, f.companyId), ne(chatEndpoints.status, "archived"), + )); + expect(endpoints.map(endpoint => endpoint.id)).toEqual([id]); + }); + + it.each(["inbox", "organization"] as const)("completes an AgentMail card with a %s key only after its assigned inbox is usable", async (scope) => { + const f = await fixture("websocket"); + const actor = { userId: "email-board" }; + await f.service.control(f.endpointId, "remove", actor); + const provider = vi.mocked(f.fetcher).getMockImplementation()!; + const createdInboxes: unknown[] = []; + vi.mocked(f.fetcher).mockImplementation(async (url, init) => { + const pathname = new URL(String(url)).pathname; + if (pathname === "/v0/auth/me" && new Headers(init?.headers).get("authorization") === "Bearer organization-test-key") { + return Response.json({ scope_type: "organization", organization_id: "organization" }); + } + if (pathname === "/v0/inboxes" && init?.method === "POST") { + createdInboxes.push(JSON.parse(String(init.body))); + return Response.json({ inbox_id: f.address }); + } + if (pathname.endsWith("/api-keys") && init?.method === "POST") { + return Response.json({ api_key: "test-key", api_key_id: "inbox-runtime-key" }); + } + return provider(url, init); + }); + const issue = await issueService(db).create(f.companyId, { title: "Acquire an email address", assigneeAgentId: f.agentId, status: "in_progress" }); + const runId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, + status: "running", responsibleUserId: "email-board", contextSnapshot: { issueId: issue.id } }); + const claims = { sub: f.agentId, company_id: f.companyId, run_id: runId, responsible_user_id: "email-board" }; + const intents = connectionIntentService(db); + const requested = await intents.request(claims, "agentmail"); + const id = requested.interactionId!; + const account = await emailConnectionService(db, f.fetcher).connect(f.companyId, { + apiKey: scope === "organization" ? "organization-test-key" : "test-key", grantKind: "organization", allAgents: false, agentIds: [f.agentId], idempotencyKey: id, + }, actor); + expect((await intents.setupOptions(id)).emailSetup).toEqual({ credentialConnectionId: account.id, readyConnectionId: null }); + expect((await intents.search(claims, "agentmail")).results[0].state).not.toBe("ready"); + await expect(intents.complete(id, account.id, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/); + const inbox = await f.service.setup(f.companyId, { assignedAgentId: f.agentId, + credentialConnectionId: account.id, receiveMode: "websocket", idempotencyKey: id }, actor); + expect(createdInboxes).toEqual(scope === "organization" + ? [{ display_name: "Email agent", client_id: `paperclip-${id}` }] : []); + const retry = await f.service.setup(f.companyId, { assignedAgentId: f.agentId, + credentialConnectionId: account.id, receiveMode: "websocket", idempotencyKey: id }, actor); + expect(retry.connectionId).toBe(inbox.connectionId); + expect(createdInboxes).toHaveLength(scope === "organization" ? 1 : 0); + expect((await intents.setupOptions(id)).emailSetup?.readyConnectionId).toBe(inbox.connectionId); + await expect(intents.complete(id, inbox.connectionId, "someone-else", { canManageOrganizationGrant: true })).rejects.toThrow(/addressed user/); + await expect(intents.complete(id, inbox.connectionId, "email-board")).rejects.toThrow(/connection-management/); + const otherAgentId = randomUUID(); + await db.insert(agents).values({ id: otherAgentId, companyId: f.companyId, name: "Other agent", role: "engineer", status: "idle", adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} }); + await db.update(chatEndpoints).set({ assignedAgentId: otherAgentId }).where(eq(chatEndpoints.id, id)); + await expect(intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/); + await db.update(chatEndpoints).set({ assignedAgentId: f.agentId, status: "paused" }).where(eq(chatEndpoints.id, id)); + await expect(intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/); + await db.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, id)); + const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, account.id)); + expect(grants.map(grant => grant.kind)).toEqual(["organization"]); + const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, account.id)); + expect(installs.map(install => ({ type: install.targetType, id: install.targetId }))).toEqual([{ type: "agent", id: f.agentId }]); + await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, account.id)); + await expect(intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).rejects.toThrow(/active inbox/); + await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.connectionId, account.id)); + const completed = await intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true }); + expect(completed).toMatchObject({ status: "accepted", result: { outcome: "connected", connectionId: inbox.connectionId } }); + expect((await intents.complete(id, inbox.connectionId, "email-board", { canManageOrganizationGrant: true })).id).toBe(id); + expect(await intents.request(claims, "agentmail")).toMatchObject({ state: "ready", interactionId: null, connectionId: inbox.connectionId }); + expect((await intents.search(claims, "agentmail")).results[0]).toMatchObject({ state: "ready", connectionId: inbox.connectionId }); + }); + it("checks AgentMail account and inbox health without local stdio or MCP discovery", async () => { const f = await fixture(); const connection = await emailConnectionService(db, f.fetcher).connect(f.companyId, { diff --git a/server/src/__tests__/email-routes-provider-errors.test.ts b/server/src/__tests__/email-routes-provider-errors.test.ts new file mode 100644 index 00000000000..742c0058ad7 --- /dev/null +++ b/server/src/__tests__/email-routes-provider-errors.test.ts @@ -0,0 +1,113 @@ +import express from "express"; +import request from "supertest"; +import type { Db } from "@paperclipai/db"; +import { describe, expect, it, vi } from "vitest"; +import { forbidden } from "../errors.js"; +import { errorHandler } from "../middleware/error-handler.js"; +import { emailRoutes } from "../routes/email.js"; +import { agentmailApi } from "../services/agentmail-api.js"; +import type { EmailChannelService } from "../services/email-channels.js"; + +const companyId = "11111111-1111-4111-8111-111111111111"; +const agentId = "22222222-2222-4222-8222-222222222222"; +const setupPath = `/api/companies/${companyId}/email/inboxes`; +const setupInput = { + assignedAgentId: agentId, + apiKey: "private-api-key", + username: "ralph", + receiveMode: "websocket", + idempotencyKey: "33333333-3333-4333-8333-333333333333", +}; + +function app(setup: () => Promise) { + const instance = express(); + instance.use(express.json()); + instance.use((req, _res, next) => { + req.actor = { type: "board", source: "local_implicit", userId: "board" }; + next(); + }); + instance.use("/api", emailRoutes({} as Db, { setup, inspect: setup } as unknown as EmailChannelService)); + instance.use(errorHandler); + return instance; +} + +describe("AgentMail provider errors at the HTTP boundary", () => { + it("explains a key-creation 404 without claiming the allocated address is missing", async () => { + const api = agentmailApi("private-api-key", vi.fn(async () => Response.json({ code: "not_found" }, { status: 404 }))); + const response = await request(app(() => api.createInboxKey("ralph@agentmail.to"))) + .post(setupPath).send(setupInput).expect(422); + expect(response.body.error).toBe("AgentMail could not create an access key for this inbox. The email address was saved; try finishing the connection again."); + expect(response.body.details).toMatchObject({ providerStatus: 404, operation: "create_inbox_key" }); + }); + + it.each(["resource_taken", "already_exists"])("identifies %s on inbox creation even when AgentMail returns 403", async (code) => { + const api = agentmailApi("private-api-key", vi.fn(async () => Response.json({ + code, message: "private provider message", fix: "private-api-key", docs: "https://untrusted.invalid", + }, { status: 403 }))); + const response = await request(app(() => api.createInbox({ username: "ralph" }))) + .post(setupPath).send(setupInput).expect(409); + expect(response.body).toMatchObject({ + code: "agentmail_address_taken", error: "This email address is already in use. Choose a different address.", + details: { field: "username", providerStatus: 403, operation: "create_inbox" }, + }); + expect(response.text).not.toMatch(/private|untrusted/); + }); + + it("does not mislabel a taken resource during another operation as a taken address", async () => { + const api = agentmailApi("private-api-key", vi.fn(async () => Response.json({ code: "resource_taken" }, { status: 403 }))); + const response = await request(app(() => api.createInboxKey("ralph@agentmail.to"))) + .post(setupPath).send(setupInput).expect(422); + expect(response.body.code).toBe("agentmail_request_failed"); + expect(response.body.error).not.toContain("already in use"); + }); + + it.each([ + [401, 422, "AgentMail rejected the API key"], + [403, 422, "AgentMail did not allow Paperclip to create the email address"], + [400, 422, "Try a different address"], + [409, 422, "Try a different address"], + [422, 422, "Try a different address"], + [404, 422, "could not find the requested inbox or resource"], + [429, 429, "rate limiting"], + [503, 502, "temporarily unavailable"], + ])("explains provider %i without exposing the provider body", async (providerStatus, status, message) => { + const fetcher = vi.fn(async () => new Response("private provider body and private-api-key", { + status: providerStatus, + headers: { "Retry-After": "12" }, + })); + const api = agentmailApi("private-api-key", fetcher); + const response = await request(app(() => api.createInbox({ username: "ralph" }))) + .post(setupPath).send(setupInput); + expect(response.status).toBe(status); + expect(response.body.error).toContain(message); + expect(response.body.details).toEqual({ + code: "agentmail_request_failed", providerStatus, operation: "create_inbox", + }); + expect(response.text).not.toMatch(/private|Internal server error/); + if (providerStatus === 429) expect(response.headers["retry-after"]).toBe("12"); + }); + + it("explains a denied runtime-key creation without suggesting a different address", async () => { + const api = agentmailApi("private-api-key", vi.fn(async () => new Response(null, { status: 403 }))); + const response = await request(app(() => api.createInboxKey("ralph@agentmail.to"))) + .post(setupPath).send(setupInput).expect(422); + expect(response.body.error).toContain("create an inbox-scoped API key"); + expect(response.body.error).not.toContain("different address"); + expect(response.body.details.operation).toBe("create_inbox_key"); + }); + + it("keeps a rejected provider key distinct from Paperclip session authentication", async () => { + const api = agentmailApi("private-api-key", vi.fn(async () => new Response(null, { status: 401 }))); + const response = await request(app(() => api.whoami())) + .post(`/api/companies/${companyId}/email/inspect`).send({ apiKey: "private-api-key" }).expect(422); + expect(response.body.error).toContain("AgentMail rejected the API key"); + expect(response.body.details.operation).toBe("inspect_key"); + }); + + it("preserves Paperclip authorization errors", async () => { + const response = await request(app(async () => { throw forbidden("Missing permission: tools:manage_connections"); })) + .post(setupPath).send(setupInput).expect(403); + expect(response.body.error).toBe("Missing permission: tools:manage_connections"); + expect(response.body.details).toBeUndefined(); + }); +}); diff --git a/server/src/routes/email.ts b/server/src/routes/email.ts index 937f3bc07ea..8a67356eb9e 100644 --- a/server/src/routes/email.ts +++ b/server/src/routes/email.ts @@ -1,7 +1,8 @@ -import { Router, type Request } from "express"; +import { Router, type ErrorRequestHandler, type Request } from "express"; import { z } from "zod"; import { emailConnectionSchema, + emailAddressCheckSchema, emailEndpointSetupSchema, emailSendSchema, isUuidLike, @@ -11,7 +12,9 @@ import { validate } from "../middleware/validate.js"; import { assertBoard, assertCompanyAccess, hasCompanyAccess } from "./authz.js"; import { emailConnectionService } from "../services/email-connections.js"; import { accessService } from "../services/access.js"; -import { badRequest, forbidden, notFound } from "../errors.js"; +import { badRequest, forbidden, HttpError, notFound } from "../errors.js"; +import { agentmailApi, AgentmailApiError } from "../services/agentmail-api.js"; +import { logger } from "../middleware/logger.js"; import type { EmailChannelService, EmailActor, @@ -25,6 +28,62 @@ function actor(req: Request): EmailActor { localImplicit: req.actor.source === "local_implicit", }; } + +// Provider rejections describe setup/account problems, not Paperclip crashes. +// Only local messages and operation names reach the UI; never forward a body. +const agentmailErrorHandler: ErrorRequestHandler = (error, _req, res, next) => { + if (!(error instanceof AgentmailApiError)) return next(error); + logger.warn({ operation: error.operation, providerStatus: error.status, providerCode: error.providerCode }, "AgentMail request rejected"); + const actions: Partial> = { + request: "complete this request", + inspect_key: "verify the API key", + create_inbox: "create the email address", + create_inbox_key: "create an inbox-scoped API key", + create_webhook: "register the email webhook", + }; + const action = actions[error.operation] ?? "complete this request"; + let status = 422; + let code = "agentmail_request_failed"; + let message: string; + const addressTaken = error.operation === "create_inbox" + && [403, 409, 422].includes(error.status) + && (error.providerCode === "resource_taken" || error.providerCode === "already_exists"); + if (addressTaken) { + status = 409; + code = "agentmail_address_taken"; + message = "This email address is already in use. Choose a different address."; + } else if (error.providerCode === "limit_exceeded") { + message = "Your AgentMail account has reached its resource limit. Free up space or increase your plan’s limit, then try again."; + } else if (error.providerCode === "domain_not_verified") { + message = "Verify this domain in AgentMail before creating an email address, or choose another domain."; + } else if (error.status === 401) { + message = "AgentMail rejected the API key. Check that it is correct and has not been revoked, then reconnect."; + } else if (error.status === 403) { + message = `AgentMail did not allow Paperclip to ${action}. Check your API key permissions and AgentMail account limits, then try again.`; + } else if (error.status === 429) { + status = 429; + res.set("Retry-After", String(Math.ceil(error.retryAfterMs / 1000))); + message = "AgentMail is rate limiting requests. Wait a moment, then try again."; + } else if ([400, 409, 422].includes(error.status) && error.operation === "create_inbox") { + message = "AgentMail could not create this email address. Try a different address and check that its domain is available in your AgentMail account."; + } else if (error.status === 404) { + message = error.operation === "create_inbox_key" + ? "AgentMail could not create an access key for this inbox. The email address was saved; try finishing the connection again." + : "AgentMail could not find the requested inbox or resource. Check that it still exists and that your API key can access it."; + } else if (error.status >= 500) { + status = 502; + message = "AgentMail is temporarily unavailable. Try again in a moment."; + } else { + message = `AgentMail could not ${action}. Check your AgentMail settings, then try again.`; + } + next(new HttpError(status, message, { + code, + providerStatus: error.status, + operation: error.operation, + ...(addressTaken ? { field: "username" } : {}), + })); +}; + export function emailRoutes(db: Db, service: EmailChannelService) { const router = Router(); async function manager(req: Request, companyId: string) { @@ -45,13 +104,19 @@ export function emailRoutes(db: Db, service: EmailChannelService) { ) throw forbidden("Missing permission: tools:manage_connections"); } + router.get("/companies/:companyId/email/connections", async (req, res) => { + const companyId = req.params.companyId as string; + await manager(req, companyId); + res.set("Cache-Control", "no-store").json( + await emailConnectionService(db).listCredentials(companyId, actor(req)), + ); + }); router.post( "/companies/:companyId/email/connections", validate(emailConnectionSchema), async (req, res) => { const companyId = req.params.companyId as string; await manager(req, companyId); - await service.requireEnabled(); res .status(201) .json( @@ -68,7 +133,6 @@ export function emailRoutes(db: Db, service: EmailChannelService) { async (req, res) => { const companyId = req.params.companyId as string; await manager(req, companyId); - await service.requireEnabled(); const saved = await emailConnectionService(db).credential( companyId, req.params.connectionId as string, @@ -79,6 +143,19 @@ export function emailRoutes(db: Db, service: EmailChannelService) { .json(await service.inspect(saved.value)); }, ); + router.post( + "/companies/:companyId/email/connections/:connectionId/check-address", + validate(emailAddressCheckSchema), + async (req, res) => { + const companyId = req.params.companyId as string; + await manager(req, companyId); + const saved = await emailConnectionService(db).credential( + companyId, req.params.connectionId as string, actor(req), + ); + res.set("Cache-Control", "no-store").json(await agentmailApi(saved.value) + .checkAddress(`${req.body.username}@${req.body.domain}`)); + }, + ); router.get("/companies/:companyId/email/inboxes", async (req, res) => { const companyId = req.params.companyId as string; assertCompanyAccess(req, companyId); @@ -229,6 +306,7 @@ export function emailRoutes(db: Db, service: EmailChannelService) { res.json(delivery); }, ); + router.use(agentmailErrorHandler); return router; } export function emailWebhookRoutes(service: EmailChannelService) { diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 0ac375f9e9c..96933027e43 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -12,6 +12,7 @@ import { localAiLoginStartSchema, emailEndpointSetupSchema, emailConnectionSchema, + emailAddressCheckSchema, emailSendSchema, browserUseControlSchema, browserUseSettingsSchema, @@ -1509,8 +1510,10 @@ const BOARD_ONLY_OPERATIONS = new Set([ "POST /api/tool-gateway/action-requests/{id}/decline", "POST /api/companies/{companyId}/email/inspect", "POST /api/companies/{companyId}/email/inboxes", + "GET /api/companies/{companyId}/email/connections", "POST /api/companies/{companyId}/email/connections", "POST /api/companies/{companyId}/email/connections/{connectionId}/inspect", + "POST /api/companies/{companyId}/email/connections/{connectionId}/check-address", "POST /api/email/inboxes/{endpointId}/control", "POST /api/email/inboxes/{endpointId}/reconnect", "POST /api/companies/{companyId}/email/deliveries/{publicationId}/resolve", @@ -2131,7 +2134,25 @@ for (const [method, path, summary, body] of browserUseOperations) { // Explicit task-bound email. Board setup and agent actions share the same vaulted // connection, while automatic chat publication never applies to these endpoints. +registry.registerPath({ + method: "post", + path: "/api/companies/{companyId}/email/connections/{connectionId}/check-address", + tags: ["Email"], + summary: "Check for an existing AgentMail address using a saved credential", + description: "Requires a board connection manager and enabled chat connectors. Read-only: does not create or reserve an inbox. A missing inbox returns unknown because AgentMail hides resources outside the credential scope; it is never proof of availability.", + request: { + params: z.object({ companyId: z.string().uuid(), connectionId: z.string().uuid() }), + body: jsonBody(emailAddressCheckSchema), + }, + responses: { + 200: r.ok(z.object({ address: z.string(), status: z.enum(["taken", "unknown"]) })), + 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, + 422: r.unprocessable, 429: { description: "AgentMail request limit reached; retry later" }, + 502: r.serverError, + }, +}); for (const [method, path, summary, body, success] of [ + ["get", "/api/companies/{companyId}/email/connections", "List accessible saved AgentMail API keys (metadata only)", undefined, 200], ["post", "/api/companies/{companyId}/email/connections", "Save AgentMail credential and access", emailConnectionSchema, 201], ["post", "/api/companies/{companyId}/email/connections/{connectionId}/inspect", "Inspect inboxes using a saved AgentMail credential", undefined, 200], ["get", "/api/companies/{companyId}/email/inboxes", "List authorized AgentMail inboxes", undefined, 200], @@ -2145,7 +2166,7 @@ for (const [method, path, summary, body, success] of [ ["post", "/api/companies/{companyId}/email/deliveries/{publicationId}/resolve", "Resolve uncertain email after checking the provider", z.object({ outcome: z.enum(["sent", "failed"]), providerMessageId: z.string().min(1).max(998).optional() }).strict(), 200], ] as const) { registry.registerPath({ method, path, tags: ["Email"], summary, - description: "Experimental AgentMail channel. Internal comments never send email. Agent sends require assigned inbox and task ownership, active run authority, and configured action policies. Preserve the same idempotencyKey and payload across retries. New conversations create an email child task; replies require conversationId and replyToMessageId. Reply-all is deliberate and never includes Bcc.", + description: "AgentMail email connection. Available without the experimental chat setting. Internal comments never send email. Agent sends require assigned inbox and task ownership, active run authority, and configured action policies. Preserve the same idempotencyKey and payload across retries. New conversations create an email child task; replies require conversationId and replyToMessageId. Reply-all is deliberate and never includes Bcc.", request: { params: z.object(Object.fromEntries([...path.matchAll(/\{([^}]+)\}/g)].map(match => [match[1], z.string().uuid()]))), ...(body ? { body: jsonBody(body) } : {}) }, responses: { [success]: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict }, }); diff --git a/server/src/services/agentmail-api.ts b/server/src/services/agentmail-api.ts index 3d95934af78..5d8ad897d88 100644 --- a/server/src/services/agentmail-api.ts +++ b/server/src/services/agentmail-api.ts @@ -1,6 +1,6 @@ import { z } from "zod"; import { Webhook } from "svix"; -import type { EmailEnvelope } from "@paperclipai/shared"; +import type { EmailAddressCheckResult, EmailEnvelope } from "@paperclipai/shared"; const strings = z.array(z.string()); export const agentmailMessageSchema = z.object({ @@ -284,6 +284,18 @@ export function agentmailApi(apiKey: string, fetchImpl: typeof fetch = fetch) { request, whoami: () => request("/auth/me"), getInbox: (id: string) => request(inboxPath(id)), + checkAddress: async (address: string): Promise => { + // Do not GET a speculative inbox ID. Live AgentMail caches missing inbox + // lookups, so checking a free name can make key creation return 404 after + // the inbox is created. Listing avoids priming that negative lookup. + const { inboxes } = await request<{ inboxes: AgentmailInbox[] }>("/inboxes?limit=100"); + // An absent entry can be outside this page or credential's scope. Only + // creation is authoritative; never claim an unlisted address is free. + return { + address, + status: inboxes.some(inbox => inbox.inbox_id.toLowerCase() === address.toLowerCase()) ? "taken" : "unknown", + }; + }, listInboxes: () => request<{ inboxes: AgentmailInbox[] }>("/inboxes?limit=100"), listDomains: () => diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts index 1a43c5d6e28..34cec954f7f 100644 --- a/server/src/services/connection-intents.ts +++ b/server/src/services/connection-intents.ts @@ -1,3 +1,5 @@ +import { emailChannelService } from "./email-channels.js"; +import { emailConnectionService } from "./email-connections.js"; import { agentService } from "./agents.js"; import { logActivity } from "./activity-log.js"; import { aiConnectionService } from "./ai-connections.js"; @@ -237,7 +239,7 @@ export function connectionIntentService(db: Db) { agentId: string; responsibleUserId: string; serviceSlug: string; - purpose?: "ai"; + purpose?: "ai" | "channel"; inventory?: Awaited>; }) { const managed = input.purpose === "ai" ? await managedAgent(input.companyId, input.agentId, input.serviceSlug) : null; @@ -248,6 +250,11 @@ export function connectionIntentService(db: Db) { } catch (error) { if ([403, 404, 422].includes((error as { status?: number }).status ?? 0)) return null; throw error; } } if (input.purpose === "ai") return null; + if (input.purpose === "channel") { + if (input.serviceSlug !== "agentmail") return null; + const inboxes = await assignedAgentmailInboxes(db, input.companyId, input.agentId); + return inboxes[0] ? access.getConnection(inboxes[0].connectionId, input.companyId) : null; + } const inventory = input.inventory ?? await connectionInventory(input.companyId); const matching = inventory.connections.filter((connection) => sourceSlugForConnection(connection, inventory.applicationsById) === input.serviceSlug @@ -318,11 +325,24 @@ export function connectionIntentService(db: Db) { )); } - async function resolveService(service: string, companyId: string, userId: string, agentId: string, purpose?: "ai") { + // Readiness uses the same credential, feature and assignment checks as the + // runtime's AgentMail tools; it never starts a worker or contacts the provider. + function assignedAgentmailInboxes(database: Db, companyId: string, agentId: string) { + return emailChannelService(database, { heartbeat: { wakeup: async () => { + throw new Error("Connection discovery cannot start an email worker"); + } } }).assignedInboxes(companyId, agentId); + } + + async function resolveService(service: string, companyId: string, userId: string, agentId: string, purpose?: "ai" | "channel") { if (!service.startsWith("connection:")) { const app = getAppStoreDefinition(service); if (!app) throw notFound("Connection service was not found"); - const methods = purpose === "ai" ? getAvailableConnectionMethods(app).filter(method => method.transport === "runtime_auth") : availableToolConnectionMethods(app); + if (purpose === "channel" && service !== "agentmail") { + throw unprocessable("This email connection is not available"); + } + const methods = purpose === "ai" ? getAvailableConnectionMethods(app).filter(method => method.transport === "runtime_auth") + : purpose === "channel" ? getAvailableConnectionMethods(app).filter(method => method.purpose === "channel") + : availableToolConnectionMethods(app); return { ...app, available: app.availability?.available !== false, searchCapabilities: methods.map((method) => `${method.whenToUse} ${method.capabilityProfile?.label ?? ""} ${method.capabilityProfile?.description ?? ""}`).join(" "), @@ -364,7 +384,7 @@ export function connectionIntentService(db: Db) { const candidates: Array<{ item: ConnectionSearchResultItem; score: number; nameScore: number }> = []; const authorizedCatalogs = new Map>>(); const discoveryMethods = (app: (typeof APP_STORE_DEFINITIONS)[number]) => getAvailableConnectionMethods(app) - .filter(method => method.purpose !== "channel" || settings.enableChatConnectors); + .filter(method => method.purpose !== "channel" || app.slug === "agentmail" || settings.enableChatConnectors); const services = [...APP_STORE_DEFINITIONS.filter(app => discoveryMethods(app).length).map((app) => app.slug), ...inventory.connections.filter((connection) => sourceSlugForConnection(connection, inventory.applicationsById)?.startsWith("connection:") @@ -406,7 +426,7 @@ export function connectionIntentService(db: Db) { `${app.description ?? ""} ${app.searchCapabilities} ${catalog.map(tool => `${tool.toolName} ${tool.description ?? ""}`).join(" ")}`); if (!score) continue; const ready = await usableConnectionForAgent({ companyId: run.companyId, agentId: agent.id, - responsibleUserId: run.responsibleUserId!, serviceSlug: service, purpose: aiOnly ? "ai" : undefined, inventory }); + responsibleUserId: run.responsibleUserId!, serviceSlug: service, purpose: aiOnly ? "ai" : service === "agentmail" ? "channel" : undefined, inventory }); const denied = !aiOnly && !ready && matching.length > 0 && await administrativeDenial(run.companyId, agent.id, service, inventory); candidates.push({ score, nameScore, item: { service, name: app.name, description: app.description ?? null, logoUrl: app.branding.logoUrl ?? null, @@ -540,7 +560,7 @@ export function connectionIntentService(db: Db) { function discoverySuggestions(results: ConnectionSearchResultItem[]): ConnectionsSearchResult { return { version: 1, query, results: results.slice(0, 40), - instruction: "Multiple apps match this query. Choose the relevant service and method using descriptions and purposes. For available or needs_user_action results, tool methods use connection_request and channel or AI methods use setupPath. Use ready tools as installed; ready AI authentication applies to the next execution without reconnection. For an aggregator result, search its aggregator.targetService to obtain the provider-choice question and follow that instruction before requesting a connection. Respect unavailable states. Do not treat a search match as provider consent or app authorization." }; + instruction: "Multiple apps match this query. Choose the relevant service and method using descriptions and purposes. For available or needs_user_action results, tool methods and AgentMail use connection_request to show the inline setup card; other channel or AI methods use setupPath. Use ready tools as installed; ready AI authentication applies to the next execution without reconnection. For an aggregator result, search its aggregator.targetService to obtain the provider-choice question and follow that instruction before requesting a connection. Respect unavailable states. Do not treat a search match as provider consent or app authorization." }; } } @@ -550,9 +570,13 @@ export function connectionIntentService(db: Db) { : !suggestions && isRemoteMcpConnectorId(results[0]!.service) && results[0]!.state !== "unavailable" ? `${results[0]!.name} is an external service. When the user explicitly names this provider, disclose that it handles the connection and requests to the requested app; no additional provider-choice question is necessary. ${results[0]!.state === "ready" ? aggregatorContinuationInstruction(results[0]!.service, "The requested app") : "Call connection_request with the returned service identifier and follow its instruction. Provider setup does not yet verify underlying app access."}` : !suggestions && results[0]!.state === "unavailable" ? "This connection is unavailable or administratively restricted. Explain the reason. Do not bypass it using another provider." - : suggestions || results.length > 1 ? "These are ranked connection matches. Choose the relevant service and method using their descriptions and purposes; extra query words need not match. For available or needs_user_action tool methods, call connection_request with the service identifier to present its setup card. For available or needs_user_action channel or AI methods, share the method's setupPath. Use ready tools as installed; ready AI authentication is available for the agent's next execution and does not need reconnection. Respect unavailable states and recorded user choices. Clarify only if the intended service is still ambiguous; unrelated matches are not evidence of support." + : suggestions || results.length > 1 ? "These are ranked connection matches. Choose the relevant service and method using their descriptions and purposes; extra query words need not match. For available or needs_user_action tool methods or AgentMail, call connection_request with the service identifier to present its setup card. For other available or needs_user_action channel or AI methods, share the method's setupPath. Use ready tools as installed; ready AI authentication is available for the agent's next execution and does not need reconnection. Respect unavailable states and recorded user choices. Clarify only if the intended service is still ambiguous; unrelated matches are not evidence of support." : results[0]!.state === "ready" && results[0]!.methods.every(method => method.purpose === "ai") ? "AI authentication is available for this agent's next execution. Do not create another connection request or ask the user to reconnect." + : results[0]!.service === "agentmail" + ? results[0]!.state === "ready" + ? "An active AgentMail inbox is assigned to you. Use agentmail_inboxes to read its address. Do not request another connection." + : "Call connection_request with service agentmail to show the inline API-key card. Do not send a setup link or ask for the key in chat. The card creates an inbox for this agent; wait for completion before claiming an email address." : results[0]!.methods.every(method => method.purpose && method.purpose !== "tool") ? "Choose the method relevant to the task using its purpose and label. Share its setupPath with the user to open the existing channel or AI setup flow. These methods do not use the tool connection_request card. Do not claim tools or an inbox are ready before setup finishes." : results[0]!.state === "ready" ? "Use the installed connection. Do not create another connection request." @@ -615,7 +639,7 @@ export function connectionIntentService(db: Db) { async function request( claims: ConnectionRunClaims, serviceSlug: string, - options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {}, + options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string } = {}, ): Promise { const context = await loadRunContext(claims); return requestWithContext(context, serviceSlug, options); @@ -624,7 +648,7 @@ export function connectionIntentService(db: Db) { async function requestWithContext( context: Awaited>, serviceSlug: string, - options: { purpose?: "ai"; selectionInteractionId?: string; targetService?: string } = {}, + options: { purpose?: "ai" | "channel"; selectionInteractionId?: string; targetService?: string } = {}, ): Promise { const claims = { sub: context.agent.id, company_id: context.run.companyId, run_id: context.run.id, responsible_user_id: context.run.responsibleUserId! }; const route = parseAggregatorRoute(serviceSlug); @@ -653,6 +677,9 @@ export function connectionIntentService(db: Db) { upstreamService = { slug: route.targetService, name: selected.aggregator.targetName, selectionInteractionId: options.selectionInteractionId }; serviceSlug = route.provider; } + // AgentMail has one channel method. Infer it from the server-owned catalog + // identifier instead of asking the model to invent a new tool argument. + if (serviceSlug === "agentmail" && !options.purpose) options = { ...options, purpose: "channel" }; const app = await resolveService(serviceSlug, context.run.companyId, context.run.responsibleUserId!, context.agent.id, options.purpose); if (!app.available || app.methods.length === 0) { throw unprocessable(`Connection service ${serviceSlug} is not available`); @@ -671,10 +698,10 @@ export function connectionIntentService(db: Db) { state: "ready", connectionId: ready.id, interactionId: null, - instruction: isRemoteMcpConnectorId(app.slug) ? aggregatorContinuationInstruction(app.slug, upstreamService?.name ?? "The requested app") : options.purpose === "ai" ? `${app.name} authentication is available for the next execution.` : `${app.name} is connected. Use its installed tools; a native continuation will refresh tools if needed.`, + instruction: isRemoteMcpConnectorId(app.slug) ? aggregatorContinuationInstruction(app.slug, upstreamService?.name ?? "The requested app") : options.purpose === "channel" ? "An active AgentMail inbox is assigned to you. Use agentmail_inboxes to read its address; do not request another connection." : options.purpose === "ai" ? `${app.name} authentication is available for the next execution.` : `${app.name} is connected. Use its installed tools; a native continuation will refresh tools if needed.`, }; } - if (options.purpose !== "ai" && await administrativeDenial(context.run.companyId, context.agent.id, app.slug, await connectionInventory(context.run.companyId))) { + if (!options.purpose && await administrativeDenial(context.run.companyId, context.agent.id, app.slug, await connectionInventory(context.run.companyId))) { throw forbidden("This agent has no permitted actions for this service. Ask an administrator to review tool permissions; reconnecting will not remove a denial."); } const outcomeId = context.run.contextSnapshot?.interactionId; @@ -702,7 +729,7 @@ export function connectionIntentService(db: Db) { sourceRunId: context.run.id, sourceIdentityContextId: context.run.activeIdentityContextId, addresseeUserId: context.run.responsibleUserId!, - idempotencyKey: `connection-intent:${context.run.id}:${context.run.responsibleUserId}:${app.slug}${upstreamService ? `:${upstreamService.slug}` : ""}${options.purpose ? ":ai" : ""}`, + idempotencyKey: `connection-intent:${context.run.id}:${context.run.responsibleUserId}:${app.slug}${upstreamService ? `:${upstreamService.slug}` : ""}${options.purpose ? `:${options.purpose}` : ""}`, }, ); if (interaction.status !== "pending") throw conflict("This connection request has already been resolved. Follow its recorded outcome."); @@ -738,6 +765,25 @@ export function connectionIntentService(db: Db) { const loaded = await loadIntent(interactionId); const payload = connectionIntentPayloadSchema.parse(loaded.interaction.payload); const app = await resolveService(payload.serviceSlug, loaded.issue.companyId, loaded.interaction.addresseeUserId!, payload.requestingAgentId, payload.purpose); + if (payload.purpose === "channel") { + const [saved] = await db.select().from(toolConnections).where(and( + eq(toolConnections.companyId, loaded.issue.companyId), + eq(toolConnections.uid, `agentmail-account-${interactionId}`), + )); + // A retry may recover only this card's account, after checking the + // addressed person's current access. No arbitrary connection is selected. + const credential = saved ? await emailConnectionService(db).get(loaded.issue.companyId, saved.id, { userId: loaded.interaction.addresseeUserId! }) : null; + const inboxes = await assignedAgentmailInboxes(db, loaded.issue.companyId, payload.requestingAgentId); + return { + version: 1, interaction: loaded.interaction, + service: { service: app.slug, name: app.name, description: app.description ?? null, + logoUrl: app.branding.logoUrl ?? null, methods: app.methods, source: app.source, + state: "needs_user_action", connectionId: null }, + existingConnections: [], requestedAgentId: payload.requestingAgentId, + emailSetup: { credentialConnectionId: credential?.id ?? null, + readyConnectionId: inboxes.find(inbox => inbox.id === interactionId)?.connectionId ?? null }, + }; + } let managed = payload.purpose === "ai" ? await managedAgent(loaded.issue.companyId, payload.requestingAgentId, app.slug) : null; if (payload.purpose === "ai" && !managed) { const [source] = await db.select().from(heartbeatRuns).where(and( @@ -873,6 +919,22 @@ export function connectionIntentService(db: Db) { throw conflict("Finish and test this connection before using it for the task"); } + if (payload.purpose === "channel") { + if (payload.serviceSlug !== "agentmail" || !options.canManageOrganizationGrant) { + throw forbidden("AgentMail inbox setup requires connection-management authority"); + } + const inboxes = await assignedAgentmailInboxes(txDb, loaded.issue.companyId, payload.requestingAgentId); + const inbox = inboxes.find(inbox => inbox.connectionId === selectedConnection.id); + if (!inbox?.address) throw conflict("Finish creating an active inbox for the requesting agent before continuing"); + const credentialId = selectedConnection.config?.credentialConnectionId; + if (typeof credentialId !== "string") throw conflict("Use a saved AgentMail account for this inbox"); + await emailConnectionService(txDb).get(loaded.issue.companyId, credentialId, { userId }); + return txInteractions.resolveConnectionIntent(loaded.issue, interactionId, { + version: 1, outcome: "connected", connectionId: selectedConnection.id, + instruction: "Your AgentMail inbox is ready. Use agentmail_inboxes to read its verified address and continue the user's request.", + }, { userId }); + } + if (selectedConnection.connectionPurpose === "channel") throw conflict("An email inbox cannot satisfy a tool connection request"); if (payload.purpose === "ai" && selectedConnection.connectionPurpose !== "ai") throw conflict("Select an AI account for this authentication request"); if (selectedConnection.connectionPurpose === "ai") { if (payload.purpose !== "ai") throw conflict("AI authentication cannot satisfy a tool connection request"); diff --git a/server/src/services/connectors/agentmail.ts b/server/src/services/connectors/agentmail.ts index 8c84c6fd5c4..d0ca2f379f2 100644 --- a/server/src/services/connectors/agentmail.ts +++ b/server/src/services/connectors/agentmail.ts @@ -3,11 +3,10 @@ import type { Db } from "@paperclipai/db"; import { emailSendSchema } from "@paperclipai/shared"; import { emailChannelService } from "../email-channels.js"; import { forbidden, notFound } from "../../errors.js"; -import { instanceSettingsService } from "../instance-settings.js"; const AGENTMAIL_EMAIL_CONTRACT = { description: - "Use an assigned AgentMail inbox for this task. Internal comments and final responses never send email. List inboxes, read the current email thread, explicitly send a new email child task or reply, and inspect delivery. Requires experimental email connections. A send needs a UUID idempotencyKey; preserve it and the identical payload on retry. A reply uses conversationId and replyToMessageId from thread; replyAll defaults false and excludes Bcc. Sending does not close the task.", + "Use an assigned AgentMail inbox for this task. Internal comments and final responses never send email. List inboxes, read the current email thread, explicitly send a new email child task or reply, and inspect delivery. A send needs a UUID idempotencyKey; preserve it and the identical payload on retry. A reply uses conversationId and replyToMessageId from thread; replyAll defaults false and excludes Bcc. Sending does not close the task.", inputSchema: { type: "object", properties: { @@ -118,10 +117,6 @@ export async function executeAgentmailTool( }, value: unknown, ) { - if ( - !(await instanceSettingsService(db).getExperimental()).enableChatConnectors - ) - throw forbidden("Experimental email connections are disabled"); const input = schema.parse(value); // This facade only persists intents/reads. The app's durable email worker owns execution. const service = emailChannelService(db, { diff --git a/server/src/services/email-channels.ts b/server/src/services/email-channels.ts index 0969fecc636..d7d8b08d4c1 100644 --- a/server/src/services/email-channels.ts +++ b/server/src/services/email-channels.ts @@ -129,14 +129,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { let activeTick: Promise | null = null; let timer: ReturnType | undefined; - async function enabled() { - return (await instanceSettingsService(db).getExperimental()) - .enableChatConnectors; - } - async function requireEnabled() { - if (!(await enabled())) - throw forbidden("Enable experimental chat connections first"); - } async function getEndpoint(id: string) { const [row] = await db .select() @@ -620,7 +612,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { input: EmailEndpointSetupInput, actor: EmailActor, ) { - await requireEnabled(); const [agent] = await db .select() .from(agents) @@ -797,6 +788,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { input.credentialConnectionId, agent.id, actor, + input.idempotencyKey, ); } else if (controlKey) await vault(endpoint, "controlKey", controlKey); if (!controlKey) throw badRequest("AgentMail API key required"); @@ -919,7 +911,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { } async function admit(endpoint: Endpoint, value: unknown) { - await requireEnabled(); await active(endpoint); const event = normalizeAgentmailEvent(value); if (!event) return; @@ -1452,7 +1443,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { input: EmailSendInput, actor: EmailActor, ): Promise { - await requireEnabled(); const endpoint = await getEndpoint(input.endpointId); if (endpoint.companyId !== companyId) throw notFound("Email inbox not found"); @@ -1647,7 +1637,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { const input = send.request; let attempted = false; try { - await requireEnabled(); await active(endpoint); const sourceId = input.parentIssueId ?? pub.issueId; await authorize(endpoint, sourceId, send.actor); @@ -2064,11 +2053,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { if (ticking || stopped) return; ticking = true; try { - if (!(await enabled())) { - for (const state of sockets.values()) state.socket.close(); - sockets.clear(); - return; - } const endpoints = await db .select() .from(chatEndpoints) @@ -2272,7 +2256,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { if (endpoint.status === "archived") throw conflict("This inbox is disconnected"); if (action === "resume") { - await requireEnabled(); if (!config.activationAt) throw conflict("Complete inbox setup before resuming"); await agentmailApi(await credential(endpoint), fetchImpl).getInbox( @@ -2368,7 +2351,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { receiveMode: "websocket" | "webhook", actor: EmailActor, ) { - await requireEnabled(); const endpoint = await getEndpoint(id); if (endpoint.status === "archived" || !endpoint.botExternalId) throw conflict("Create a new inbox connection"); @@ -2591,7 +2573,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { }; } async function assignedInboxes(companyId: string, agentId: string) { - if (!(await enabled())) return []; const rows = await db.select().from(chatEndpoints).where(and( eq(chatEndpoints.companyId, companyId), eq(chatEndpoints.assignedAgentId, agentId), eq(chatEndpoints.provider, "agentmail"), eq(chatEndpoints.status, "active"), @@ -2610,7 +2591,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { } return { assignedInboxes, - requireEnabled, authorizeRead, setup, getEndpoint, diff --git a/server/src/services/email-connections.ts b/server/src/services/email-connections.ts index ca272d3b062..70a8b4b1863 100644 --- a/server/src/services/email-connections.ts +++ b/server/src/services/email-connections.ts @@ -8,8 +8,8 @@ import { companySecrets, toolConnectionInstalls, } from "@paperclipai/db"; -import type { EmailConnectionInput } from "@paperclipai/shared"; -import { badRequest, forbidden, notFound } from "../errors.js"; +import type { EmailConnectionInput, EmailCredentialOption } from "@paperclipai/shared"; +import { badRequest, forbidden, HttpError, notFound } from "../errors.js"; import { secretService } from "./secrets.js"; import { toolAccessService } from "./tool-access.js"; import { agentmailApi } from "./agentmail-api.js"; @@ -75,6 +75,56 @@ export function emailConnectionService( } return connection; } + async function listCredentials(companyId: string, actor: EmailActor): Promise { + const connections = await db.select().from(toolConnections).where(and( + eq(toolConnections.companyId, companyId), eq(toolConnections.status, "active"), + eq(toolConnections.enabled, true), + )); + const options: EmailCredentialOption[] = []; + const candidates = connections.filter(connection => connection.config.provider === "agentmail" && connection.config.emailCredential); + // New credentials already have verified scope metadata. Legacy credentials + // get a bounded discovery pass: four workers share one three-second budget. + const deadline = AbortSignal.timeout(3_000); + const discoveryFetch: typeof fetch = (input, init) => fetchImpl(input, { + ...init, signal: init?.signal ? AbortSignal.any([init.signal, deadline]) : deadline, + }); + let next = 0; + await Promise.all(Array.from({ length: Math.min(4, candidates.length) }, async () => { + while (next < candidates.length) { + const connection = candidates[next++]; + try { + await get(companyId, connection.id, actor); + } catch (error) { + if (error instanceof HttpError && [403, 404].includes(error.status)) continue; + throw error; + } + const storedScope = connection.config.emailScope; + let scope: EmailCredentialOption["scope"] = storedScope === "organization" || storedScope === "pod" || storedScope === "inbox" + ? storedScope : "unavailable"; + let inboxId = typeof connection.config.emailInboxId === "string" ? connection.config.emailInboxId : null; + if (scope === "unavailable" && !deadline.aborted) { + try { + const saved = await credential(companyId, connection.id, actor); + if (!deadline.aborted) { + const identity = await agentmailApi(saved.value, discoveryFetch).whoami(); + scope = identity.scope_type; + inboxId = identity.inbox_id ?? null; + } + } catch { + // Never expose a provider body, key, hash, or secret reference. + } + } + options.push({ + id: connection.id, scope, inboxId, createdAt: connection.createdAt.toISOString(), + label: connection.name !== "AgentMail" ? connection.name + : scope === "inbox" ? `AgentMail inbox key${inboxId ? ` · ${inboxId}` : ""}` + : scope === "unavailable" ? "AgentMail key · unavailable" : "AgentMail account key", + }); + } + })); + return options.sort((a, b) => Number(b.scope === "organization" || b.scope === "pod") + - Number(a.scope === "organization" || a.scope === "pod") || b.createdAt.localeCompare(a.createdAt)); + } async function assertAgentAccess( companyId: string, id: string, @@ -126,7 +176,7 @@ export function emailConnectionService( input: EmailConnectionInput, actor: EmailActor, ) { - await agentmailApi(input.apiKey, fetchImpl).whoami(); + const identity = await agentmailApi(input.apiKey, fetchImpl).whoami(); return db.transaction(async (tx) => { const db = tx as unknown as Db; await db.execute( @@ -166,7 +216,7 @@ export function emailConnectionService( actor, ); const secret = await secrets.create(companyId, { - name: `AgentMail account ${randomUUID()}`, + name: `AgentMail ${identity.scope_type === "inbox" ? "inbox" : "account"} API key ${randomUUID().slice(0, 8)}`, provider: "local_encrypted", value: input.apiKey, }); @@ -190,7 +240,7 @@ export function emailConnectionService( credentialPolicy: "shared", enabled: true, status: "active", - config: { provider: "agentmail", emailCredential: true }, + config: { provider: "agentmail", emailCredential: true, emailScope: identity.scope_type, emailInboxId: identity.inbox_id ?? null }, transportConfig: {}, credentialSecretRefs: [ { @@ -241,6 +291,11 @@ export function emailConnectionService( actorSource: actor.localImplicit ? "local_implicit" : "session", }, ); + const initialInstalls = await db.select({ id: toolConnectionInstalls.id }) + .from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, connection.id)); + await db.update(toolConnections).set({ + config: { ...connection.config, emailSetupInitialInstallIds: initialInstalls.map(install => install.id) }, + }).where(eq(toolConnections.id, connection.id)); await logActivity(db, { companyId, actorType: "user", @@ -262,6 +317,7 @@ export function emailConnectionService( id: string, agentId: string, actor: EmailActor, + setupRequestId: string, ) { return db.transaction(async (tx) => { const db = tx as unknown as Db; @@ -275,26 +331,37 @@ export function emailConnectionService( ), ) .for("update"); - await emailConnectionService(db, fetchImpl).get(companyId, id, actor); + const connection = await emailConnectionService(db, fetchImpl).get(companyId, id, actor); const tools = toolAccessService(db); const installs = await db .select() .from(toolConnectionInstalls) .where(eq(toolConnectionInstalls.connectionId, id)); + // Apply the setup default once, only if nobody has edited access since + // saving the key. Install IDs detect removal/re-addition as well as new + // agent/company grants. Later retries always preserve those edits. + const initialIds = connection.config.emailSetupInitialInstallIds; + const ownsInitialAccess = connection.uid === `agentmail-account-${setupRequestId}` && Array.isArray(initialIds); + const replaceInitialAccess = ownsInitialAccess && initialIds.length === installs.length + && installs.every(install => initialIds.includes(install.id)); + if (ownsInitialAccess) { + const { emailSetupInitialInstallIds: _initialIds, ...config } = connection.config; + await db.update(toolConnections).set({ config }).where(eq(toolConnections.id, id)); + } if ( - installs.some( - (i) => i.targetType === "company" || i.targetId === agentId, - ) + replaceInitialAccess + ? installs.length === 1 && installs[0].targetType === "agent" && installs[0].targetId === agentId + : installs.some((i) => i.targetType === "company" || i.targetId === agentId) ) return; await tools.putConnectionInstalls( id, { installs: [ - ...installs.map((i) => ({ + ...(replaceInitialAccess ? [] : installs.map((i) => ({ targetType: i.targetType, targetId: i.targetId, - })), + }))), { targetType: "agent", targetId: agentId }, ], }, @@ -308,12 +375,12 @@ export function emailConnectionService( companyId, actorType: "user", actorId: actor.userId ?? "board", - action: "email.connection.agent_added", + action: replaceInitialAccess ? "email.connection.agents_updated" : "email.connection.agent_added", entityType: "tool_connection", entityId: id, details: { agentId }, }); }); } - return { get, credential, connect, allowAgent, assertAgentAccess }; + return { get, credential, connect, listCredentials, allowAgent, assertAgentAccess }; } diff --git a/tests/e2e/agentmail.spec.ts b/tests/e2e/agentmail.spec.ts index 9af42ffd574..8b87788bda5 100644 --- a/tests/e2e/agentmail.spec.ts +++ b/tests/e2e/agentmail.spec.ts @@ -12,6 +12,11 @@ test("AgentMail setup and email work through the normal task conversation", asyn page, request, }) => { + await page.setViewportSize({ width: 1440, height: 1080 }); + const settings = await request.patch("/api/instance/settings/experimental", { + data: { enableChatConnectors: false }, + }); + expect(settings.ok()).toBeTruthy(); const created = await request.post("/api/companies", { data: { name: `AgentMail browser ${Date.now()}` }, }); @@ -50,7 +55,12 @@ test("AgentMail setup and email work through the normal task conversation", asyn lastError: null, lastSyncAt: new Date().toISOString(), }; + const organizationConnectionId = randomUUID(); let connected = false; + let reservedInbox: typeof inbox | null = null; + const setupRequests: { idempotencyKey: string; username?: string }[] = []; + const addressTakenError = "This email address is already in use. Choose a different address."; + const permissionError = "AgentMail did not allow Paperclip to create an inbox-scoped API key. Check your API key permissions and AgentMail account limits, then try again."; const sends: any[] = []; const conversationId = randomUUID(); const thread = { @@ -79,11 +89,54 @@ test("AgentMail setup and email work through the normal task conversation", asyn publications: [] as any[], }; await page.route("**/api/instance/settings/experimental", (route) => - fulfill(route, { enableChatConnectors: true }), + fulfill(route, { enableChatConnectors: false }), + ); + await page.route(`**/api/companies/${company.id}/tools/connections`, route => + fulfill(route, { connections: [{ + id: organizationConnectionId, name: "AgentMail", status: "active", enabled: true, + config: { provider: "agentmail", emailCredential: true }, createdAt: "2026-09-30T14:00:00Z", + }] }), + ); + await page.route(`**/api/companies/${company.id}/chat-endpoints`, route => + fulfill(route, reservedInbox ? [{ ...reservedInbox, provider: "agentmail", assignedAgentName: agent.name, + providerAccountLabel: reservedInbox.address }] : []), + ); + await page.route(`**/api/tool-connections/${inbox.connectionId}`, route => + fulfill(route, { config: { credentialConnectionId: organizationConnectionId } }), + ); + await page.route(`**/api/tool-connections/${organizationConnectionId}/grants`, route => + fulfill(route, { grants: [{ status: "active", kind: "organization" }], capabilities: { canConfigure: true } }), + ); + await page.route(`**/api/tool-connections/${organizationConnectionId}/installs`, route => + fulfill(route, { installs: [{ targetType: "agent", targetId: agent.id }] }), + ); + await page.route(`**/api/chat-endpoints/${inbox.id}/conversations`, route => + fulfill(route, [{ id: conversationId, externalLabel: "Customer email", issueId: task.id, + issueTitle: task.title, issueIdentifier: task.identifier, state: "active" }]), + ); + await page.route(`**/api/chat-endpoints/${inbox.id}/activity?*`, route => + fulfill(route, { items: [{ id: randomUUID(), kind: "delivery", status: "processed", + summary: "Email received", createdAt: new Date().toISOString() }], nextCursor: null }), ); await page.route("**/api/**/email/**", async (route) => { const url = new URL(route.request().url()), method = route.request().method(); + if (url.pathname.endsWith("/connections") && method === "GET") return fulfill(route, [ + { id: organizationConnectionId, label: "AgentMail account key", scope: "organization", createdAt: "2026-09-30T14:00:00Z" }, + { id: inbox.connectionId, label: "AgentMail inbox key", scope: "inbox", createdAt: "2026-10-01T14:00:00Z" }, + ]); + if (url.pathname.endsWith("/connections") && method === "POST") { + expect(route.request().postDataJSON()).toMatchObject({ apiKey: "inbox-test-key", agentIds: [agent.id], allAgents: false }); + return fulfill(route, { id: inbox.connectionId }, 201); + } + if (url.pathname.endsWith("/check-address")) { + const body = route.request().postDataJSON(); + return fulfill(route, { address: `${body.username}@${body.domain}`, status: body.username === "taken" ? "taken" : "unknown" }); + } + if (url.pathname.endsWith(`/connections/${inbox.connectionId}/inspect`)) + return fulfill(route, { + scope: { scope_type: "inbox" }, inboxes: [{ inbox_id: inbox.address }], domains: [], + }); if (url.pathname.endsWith("/inspect")) return fulfill(route, { scope: { scope_type: "organization" }, @@ -97,11 +150,22 @@ test("AgentMail setup and email work through the normal task conversation", asyn ], }); if (url.pathname.endsWith("/inboxes") && method === "GET") - return fulfill(route, connected ? [inbox] : []); + return fulfill(route, connected ? [inbox] : reservedInbox ? [reservedInbox] : []); if (url.pathname.endsWith("/inboxes") && method === "POST") { const body = route.request().postDataJSON(); expect(body.receiveMode).toBe("websocket"); expect(body.assignedAgentId).toBe(agent.id); + expect(body.credentialConnectionId).toBe(organizationConnectionId); + setupRequests.push(body); + if (setupRequests.length === 1) return fulfill(route, { error: addressTakenError, code: "agentmail_address_taken", + details: { field: "username", providerStatus: 403, operation: "create_inbox" } }, 409); + if (setupRequests.length === 2) { + reservedInbox = { ...inbox, id: body.idempotencyKey, address: `${body.username}@${body.domain}`, status: "draft" }; + return fulfill(route, { + error: permissionError, + details: { code: "agentmail_request_failed", providerStatus: 403, operation: "create_inbox_key" }, + }, 422); + } connected = true; return fulfill(route, inbox, 201); } @@ -129,64 +193,118 @@ test("AgentMail setup and email work through the normal task conversation", asyn provider: "agentmail", setup: { step: "complete" }, capabilities: {}, + assignedAgentName: agent.name, botExternalId: inbox.address, }), ); - await page.goto( - `/${company.issuePrefix}/apps/chat/connect?provider=agentmail&connectionId=${inbox.connectionId}`, - ); + await page.goto(`/${company.issuePrefix}/apps`); + await page.getByRole("button", { name: /^(Connect|Add connection) AgentMail$/ }).click(); await expect( page.getByRole("heading", { name: "Give an agent an email address" }), ).toBeVisible(); - await page.getByRole("combobox").click(); - await page.getByPlaceholder("Search all agents…").fill("Mail agent"); - await page.getByRole("option", { name: "Mail agent" }).click(); - await expect( - page.getByText("Mail agent is not a low-trust agent"), - ).toBeVisible(); - await page.getByRole("button", { name: "Configure low trust" }).click(); + await page.getByLabel("Agent", { exact: true }).click(); + await page.getByPlaceholder("Filter agents").fill("Mail agent"); + await expect(page.getByRole("button", { name: "Select Mail agent", exact: true }).locator('[data-slot="agent-avatar"]')).toBeVisible(); + await page.getByRole("button", { name: "Select Mail agent", exact: true }).click(); + await expect(page.locator('#email-agent [data-slot="agent-avatar"]')).toBeVisible(); + await expect(page.getByLabel("API key", { exact: true })).toHaveValue(organizationConnectionId); + // A deliberately selected restricted key stays at credentials until the user + // chooses a usable account key or explicitly requests that existing inbox. + await page.getByLabel("API key", { exact: true }).selectOption(inbox.connectionId); + await page.getByRole("button", { name: "Continue", exact: true }).click(); + await expect(page.getByText(`That key only connects ${inbox.address}.`, { exact: false })).toBeVisible(); + await expect(page.getByLabel("Mail agent’s email address", { exact: true })).toHaveCount(0); + await page.screenshot({ path: test.info().outputPath("agentmail-inbox-key-recovery.png"), fullPage: true }); + await page.getByLabel("API key", { exact: true }).selectOption(organizationConnectionId); + await page.getByRole("button", { name: "Continue", exact: true }).click(); + const addressField = page.getByLabel("Mail agent’s email address", { exact: true }); + await expect(addressField).toBeEditable(); + await expect(page.getByRole("heading", { name: "How it Works", exact: true })).toBeVisible(); + await expect(page.getByLabel("Email domain", { exact: true })).toHaveValue("verified.example.test"); + await page.getByLabel("Email domain", { exact: true }).selectOption("agentmail.to"); + await expect(page.getByLabel("Email domain", { exact: true })).toHaveValue("agentmail.to"); + await page.getByLabel("Email domain", { exact: true }).selectOption("verified.example.test"); + await addressField.fill("taken"); + await expect(page.getByRole("alert")).toHaveText(addressTakenError); + expect(setupRequests).toHaveLength(0); + await page.getByRole("button", { name: "taken-agent@verified.example.test", exact: true }).click(); + await expect(addressField).toHaveValue("taken-agent"); + await expect(page.getByRole("alert")).toHaveCount(0); + await addressField.fill("mail-agent"); + await expect(page.getByRole("button", { name: "Review email address" })).toHaveCount(0); + await page.getByText("Advanced options", { exact: true }).click(); + await expect(page.getByLabel("Email domain", { exact: true }).locator("option", { hasText: "verified.example.test" })).toHaveCount(1); + await page.getByRole("button", { name: "Review trust settings" }).click(); const trustDialog = page.getByRole("dialog"); - await trustDialog - .getByRole("combobox") - .first() - .selectOption("low_trust_review"); + await trustDialog.getByRole("combobox").first().selectOption("low_trust_review"); await trustDialog.getByRole("combobox").nth(1).selectOption("root_issue"); await trustDialog.getByRole("combobox").nth(2).selectOption(task.id); - await trustDialog - .getByRole("button", { name: "Save trust settings" }) - .click(); + await trustDialog.getByRole("button", { name: "Save trust settings" }).click(); await expect(page.getByText("Low-trust review configured")).toBeVisible(); await page.getByRole("button", { name: "Review trust settings" }).click(); await page.getByRole("dialog").getByRole("combobox").first().selectOption("standard"); await page.getByRole("button", { name: "Save trust settings" }).click(); - await expect(page.getByText("Mail agent is not a low-trust agent")).toBeVisible(); + await expect(trustDialog).not.toBeVisible(); const savedAgent = await (await request.get(`/api/agents/${agent.id}`)).json(); expect(savedAgent.permissions.authorizationPolicy).toEqual({}); - await page.getByRole("button", { name: "Continue", exact: true }).click(); + await expect(page.getByRole("link", { name: "Set up allowlists ↗" })).toHaveAttribute( + "href", "https://docs.agentmail.to/knowledge-base/allowlists-blocklists"); await page.getByText("Advanced options", { exact: true }).click(); - await expect( - page - .getByLabel("Domain", { exact: true }) - .locator("option", { hasText: "verified.example.test" }), - ).toHaveCount(1); - await page.getByRole("radio", { name: "Use an existing inbox" }).click(); - await page.getByLabel("Available inbox").selectOption(inbox.address); - await page.getByRole("button", { name: "Review email address" }).click(); - await expect( - page.getByText("Anyone can email an unrestricted inbox"), - ).toBeVisible(); - await expect( - page.getByRole("link", { name: "Set up allowlists ↗" }), - ).toHaveAttribute( - "href", - "https://docs.agentmail.to/knowledge-base/allowlists-blocklists", - ); - await page - .getByRole("button", { name: "Connect email address", exact: true }) - .click(); - await expect( - page.getByRole("heading", { name: "Your agent’s email is ready" }), - ).toBeVisible(); + await page.getByRole("button", { name: "Create email address", exact: true }).click(); + await expect(page.getByRole("alert")).toHaveText(addressTakenError); + await expect(addressField).toHaveAttribute("aria-invalid", "true"); + await expect(page.getByRole("button", { name: "Create email address", exact: true })).toBeDisabled(); + await page.screenshot({ path: test.info().outputPath("agentmail-address-taken.png"), fullPage: true }); + await addressField.fill("mail-agent-free"); + await expect(page.getByRole("alert")).toHaveCount(0); + await page.reload(); + await expect(addressField).toHaveValue("mail-agent-free"); + await page.getByRole("button", { name: "Create email address", exact: true }).click(); + await expect(page.getByText(permissionError, { exact: true })).toBeVisible(); + await expect(page.getByText("Internal server error", { exact: true })).toHaveCount(0); + await expect(page.getByRole("heading", { name: "Your agent’s email is ready" })).toHaveCount(0); + await page.screenshot({ path: test.info().outputPath("agentmail-permission-denied.png"), fullPage: true }); + await page.getByRole("link", { name: "Connectors", exact: true }).click(); + await page.getByRole("button", { name: "Finish setup", exact: true }).click(); + await expect(page.getByText("mail-agent-free@verified.example.test", { exact: true })).toBeVisible(); + await expect(addressField).toHaveCount(0); + await expect(page.getByRole("button", { name: "Choose a different address", exact: true })).toBeVisible(); + await page.getByRole("button", { name: "Finish connecting", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Your agent’s email is ready" })).toBeVisible(); + expect(setupRequests.map(input => input.username)).toEqual(["mail-agent", "mail-agent-free", undefined]); + expect(setupRequests[2]).toMatchObject({ inboxId: "mail-agent-free@verified.example.test" }); + expect(new Set(setupRequests.map(input => input.idempotencyKey)).size).toBe(1); + await page.getByRole("button", { name: "Email settings", exact: true }).click(); + await expect(page.getByRole("heading", { name: inbox.address, exact: true })).toBeVisible(); + const navigation = page.getByRole("navigation", { name: "Chat connection" }); + await navigation.getByRole("link", { name: "Access", exact: true }).click(); + await expect(page.getByText("Any human in the organization", { exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Reconnect inbox", exact: true })).toHaveCount(0); + await navigation.getByRole("link", { name: "Conversations", exact: true }).click(); + await expect(page.getByRole("list", { name: "Conversations" })).toBeVisible(); + await expect(page.getByRole("link", { name: "Open task", exact: true })).toHaveAttribute("href", `/${company.issuePrefix}/issues/${task.id}`); + await page.reload(); + await expect(page.getByRole("list", { name: "Conversations" })).toBeVisible(); + await navigation.getByRole("link", { name: "Activity", exact: true }).click(); + await expect(page.getByText("Email received", { exact: true })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Connection activity", exact: true })).toBeVisible(); + await page.screenshot({ path: test.info().outputPath("agentmail-management-tabs.png"), fullPage: true }); + await navigation.getByRole("link", { name: "Settings", exact: true }).click(); + await expect(page.getByRole("heading", { name: "Receiving email", exact: true })).toBeVisible(); + const copyAddress = page.getByRole("button", { name: "Copy email address", exact: true }); + await expect(copyAddress).toHaveText(inbox.address); + await page.context().grantPermissions(["clipboard-read", "clipboard-write"]); + await copyAddress.click(); + await expect(page.getByRole("status").filter({ hasText: "Copied!" })).toHaveCSS("opacity", "1"); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(inbox.address); + await expect(page.getByRole("link", { name: "View inbox", exact: true })).toHaveAttribute( + "href", `https://console.agentmail.to/dashboard/inboxes/${encodeURIComponent(inbox.address)}`); + await page.screenshot({ path: test.info().outputPath("agentmail-settings-copy-inbox.png"), fullPage: true }); + await expect(page.getByLabel("New API key", { exact: true })).not.toBeVisible(); + await page.locator("summary").filter({ hasText: "Reconnect inbox" }).click(); + await expect(page.getByLabel("New API key", { exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Reconnect inbox", exact: true })).toBeVisible(); + await page.screenshot({ path: test.info().outputPath("agentmail-settings-reconnect.png"), fullPage: true }); await page.goto(`/${company.issuePrefix}/issues/${task.identifier}`); const email = page.getByRole("article", { name: "Email received", exact: true }); await expect(email).toBeVisible(); diff --git a/tests/e2e/chat-adapters-ui-providers.spec.ts b/tests/e2e/chat-adapters-ui-providers.spec.ts index 7d37d75b4bf..4b8cfca57d9 100644 --- a/tests/e2e/chat-adapters-ui-providers.spec.ts +++ b/tests/e2e/chat-adapters-ui-providers.spec.ts @@ -165,12 +165,13 @@ test.describe.serial("native chat adapter UI", () => { ).toBeVisible(); await page.goto(`/${seed.prefix}/apps/chat/endpoint-github/settings`); await expect(page).toHaveURL(new RegExp(`/${seed.prefix}/apps$`)); - await expect.poll(() => mock.chatEndpointListReads).toBe(0); + await expect.poll(() => mock.chatEndpointListReads).toBeGreaterThan(0); + await expect(page.getByRole("button", { name: "Connect AgentMail", exact: true })).toBeVisible(); expect(mock.createdWithAgentId).toBeNull(); }); for (const enabled of [false, true]) { - test(`Agent Channels: one heading and current experiment gate (${enabled})`, async ({ + test(`Agent Channels: default email surface and experimental providers (${enabled})`, async ({ page, }) => { const github = PROVIDERS.find( @@ -185,21 +186,18 @@ test.describe.serial("native chat adapter UI", () => { name: "Channels", exact: true, }); - if (enabled) { - await expect(page).toHaveURL(/\/channels$/); - await expect(channelsHeading).toHaveCount(1); - await expect(channelsHeading).toBeVisible(); - await expect( - page.getByRole("link", { name: "Connect a channel" }), - ).toBeVisible(); - await expect.poll(() => mock.chatEndpointListReads).toBeGreaterThan(0); - } else { - await expect(page).toHaveURL(/\/overview$/); - await expect(channelsHeading).toHaveCount(0); - await expect( - page.getByRole("link", { name: "Channels", exact: true }), - ).toHaveCount(0); - expect(mock.chatEndpointListReads).toBe(0); + await expect(page).toHaveURL(/\/channels$/); + await expect(channelsHeading).toHaveCount(1); + await expect(channelsHeading).toBeVisible(); + await expect( + page.getByRole("link", { name: "Connect a channel" }), + ).toBeVisible(); + await expect( + page.getByRole("navigation", { name: "Maya navigation" }).getByRole("link", { name: "Channels", exact: true }), + ).toBeVisible(); + await expect.poll(() => mock.chatEndpointListReads).toBeGreaterThan(0); + if (!enabled) { + await expect(page.getByText("Connect AgentMail from Connectors.", { exact: true })).toBeVisible(); } }); } diff --git a/tests/e2e/connection-intents.spec.ts b/tests/e2e/connection-intents.spec.ts index c3dce4e7fff..591ea51e204 100644 --- a/tests/e2e/connection-intents.spec.ts +++ b/tests/e2e/connection-intents.spec.ts @@ -1,6 +1,7 @@ import { expect, test, type APIRequestContext } from "@playwright/test"; import { createServer, type Server } from "node:http"; import { listenOnFetchAllowedPort } from "./fetch-allowed-port"; +import { send } from "./agent-chat.shared"; type Json = Record; type Seed = { companyId: string; prefix: string }; @@ -178,6 +179,76 @@ function escapeRegExp(value: string) { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } +test("AgentMail request shows a durable inline key card in agent chat", async ({ page, request }, testInfo) => { + test.setTimeout(120_000); + const settings = await json(await request.get("/api/instance/settings/experimental")); + try { + await json(await request.patch("/api/instance/settings/experimental", { data: { + enableAgentChat: true, enableChatConnectors: true, enableClassicTaskInterface: false, + } })); + const seed = await newCompany(request); + const agent = await createAgent(request, seed.companyId, "Email requester"); + // Script only the agent's choice of tool; persistence, routes, and UI are real. + const script = ` +const headers = { authorization: "Bearer " + process.env.PAPERCLIP_API_KEY, "content-type": "application/json", "x-paperclip-run-id": process.env.PAPERCLIP_RUN_ID }; +const runResponse = await fetch(process.env.PAPERCLIP_API_URL + "/api/heartbeat-runs/" + process.env.PAPERCLIP_RUN_ID, { headers }); +if (!runResponse.ok) throw new Error(await runResponse.text()); +const run = await runResponse.json(); +if (run.contextSnapshot?.interactionId) process.exit(0); +const post = async (url, body) => { + const response = await fetch(url, { method: "POST", headers: { authorization: "Bearer " + process.env.PAPERCLIP_RUNTIME_TOOLS_TOKEN, "content-type": "application/json" }, body: JSON.stringify(body) }); + if (!response.ok) throw new Error(await response.text()); + return response.json(); +}; +const search = await post(process.env.PAPERCLIP_RUNTIME_TOOLS_CONNECTIONS_SEARCH_URL, { query: "Get yourself an email address with AgentMail" }); +if (!search.results.some(result => result.service === "agentmail") || !search.instruction.includes("connection_request")) throw new Error("AgentMail card was not advertised"); +const result = await post(process.env.PAPERCLIP_RUNTIME_TOOLS_CONNECTION_REQUEST_URL, { service: "agentmail" }); +if (result.state !== "needs_user_action") throw new Error("Expected an inline card"); +`; + await json(await request.patch(`/api/agents/${agent.id}`, { data: { + adapterConfig: { command: process.execPath, args: ["--input-type=module", "-e", script] }, replaceAdapterConfig: true, + } })); + await page.goto(`/${seed.prefix}/chats/${agent.id}`); + await send(page, "Get yourself an email address with AgentMail."); + await waitForAgentRun(request, seed.companyId, agent.id); + const chat = await json<{ id: string }>(await request.get(`/api/companies/${seed.companyId}/chats/${agent.id}`)); + const interactions = await json>( + await request.get(`/api/issues/${chat.id}/interactions`), + ); + expect(interactions).toHaveLength(1); + expect(interactions[0]).toMatchObject({ kind: "connection_intent", status: "pending", addresseeUserId: "local-board", + payload: { purpose: "channel", serviceSlug: "agentmail", requestingAgentId: agent.id } }); + await page.reload(); + const form = page.getByTestId("agentmail-inline-setup"); + await expect(form).toBeVisible(); + await expect(form.locator("input")).toHaveCount(1); + await expect(form.getByLabel("API key")).toHaveAttribute("type", "password"); + await expect(form.getByRole("link", { name: "Get an AgentMail API key" })).toHaveAttribute("href", "https://console.agentmail.to/dashboard/api-keys"); + await expect(form.locator('[role="radiogroup"], [role="combobox"], select')).toHaveCount(0); + await expect(page.getByRole("dialog")).toHaveCount(0); + await expect(form.getByRole("button", { name: "Connect AgentMail" })).toBeDisabled(); + const card = page.getByTestId("connection-intent-focus-target"); + await card.screenshot({ path: testInfo.outputPath("agentmail-inline-card.png") }); + await page.setViewportSize({ width: 390, height: 844 }); + await expect(form).toBeVisible(); + await card.screenshot({ path: testInfo.outputPath("agentmail-inline-card-mobile.png") }); + await form.getByRole("button", { name: "Not now" }).click(); + await expect(form).toHaveCount(0); + await expect.poll(async () => { + const rows = await json>(await request.get(`/api/issues/${chat.id}/interactions`)); + return rows.map(row => row.status); + }).toEqual(["rejected"]); + expect(await json(await request.get(`/api/companies/${seed.companyId}/email/inboxes`))).toEqual([]); + const connections = await json<{ connections: unknown[] }>(await request.get(`/api/companies/${seed.companyId}/tools/connections`)); + expect(connections.connections).toEqual([]); + } finally { + await json(await request.patch("/api/instance/settings/experimental", { data: { + enableAgentChat: settings.enableAgentChat, enableChatConnectors: settings.enableChatConnectors, + enableClassicTaskInterface: settings.enableClassicTaskInterface, + } })); + } +}); + async function waitForAgentRun( request: APIRequestContext, companyId: string, diff --git a/tests/runner-e2e/EVERYDAY-WORKFLOWS.md b/tests/runner-e2e/EVERYDAY-WORKFLOWS.md index 938647cabe3..cec2fe6fb5e 100644 --- a/tests/runner-e2e/EVERYDAY-WORKFLOWS.md +++ b/tests/runner-e2e/EVERYDAY-WORKFLOWS.md @@ -15,6 +15,7 @@ exact execution ID explicitly. | Hire a teammate and use them again | `hire-reuse` | One Morgan QA reporting to the lead, native runner and the same encrypted connection bindings, real child execution, then a second usable delivery from that same agent. | | Decide on an installed service action | `service-approve`, `service-decline` | Assign an authenticated local MCP fixture with Ask first; match its tool action and connection ID; no provider call before approval; exactly one after approval and a verified document; none after decline. | | Decline a new connection | `connection-decline` | Start without service connections; match a Notion connection intent; click Not now; verify the saved rejection, no new connection or repeated request, and an explanation followed by Done. | +| Request an email address | `agentmail-setup` | Enable Chat connectors, ask for an email address, and require a durable AgentMail card for the requesting agent and user. Reload and verify one password field, the direct API-key link, and no access selectors or modal. Decline and verify no connection or repeated request. | | Continue work after a controller restart | `recover-controller` | Observe saved source, persist a user message, restart the isolated controller, and independently test the delivered result. | | Stop work and change direction | `stop-redirect` | Click Stop, send one new request, reload, observe exactly one stored user message and the new answer, and reach Done. | | Create and edit a company skill | `create-skill-studio` | Create one skill through the runner, verify its persisted library entry and activity-feed card, open Skill Studio, save an edit, and verify the edit after returning. Local Codex, local ACPX Claude, and warm Daytona cells are explicit. | @@ -36,8 +37,8 @@ See [controlled recovery tests](../runner-recovery/README.md). ## Matrix and running -The local matrix has nine cases on native Codex `gpt-5.6-sol`, native ACPX Claude -`claude-sonnet-5`, and native Codex `gpt-5.4-mini`: 27 cells. The two core profiles +The local matrix has fourteen cases on native Codex `gpt-5.6-sol`, native ACPX Claude +`claude-sonnet-5`, and native Codex `gpt-5.4-mini`: 42 cells. The two core profiles also declare build/revise, delegation, controller-restart, and skill-creation cases on Daytona: eight cells. Remote runner-process killing is not supported. For remote controller restart, a verified first download supplies the persistence checkpoint; the @@ -200,7 +201,19 @@ identity check. ## External-provider fallback Three explicit local cases cover aggregator routing with the normal production -agent guidance. They add nine local cells; the suite now has 47 cells total. +agent guidance. They add nine local cells. The AgentMail setup case adds three +local cells; the suite now has 50 cells total. + +The AgentMail case uses real model discovery and production interaction/UI paths, +but declines before sending credentials to AgentMail. Its independent grader is +calibrated against missing, duplicate, misaddressed, hidden, and malformed cards. +The email integration suite separately proves credential/inbox creation, access +defaults, assignment checks, and completion using a fixture provider. Neither +test qualifies live AgentMail delivery. Run a bounded local model cell with: + +```sh +pnpm test:e2e:runner -- --id everyday-workflows.runner-codex-mini.local.agentmail-setup --max-automatic-retries 0 +``` - `provider-native`: Jira is supported natively and by aggregators. Require the Jira connection card directly, decline it in the browser, and verify no provider diff --git a/tests/runner-e2e/agentmail-setup-evidence.test.ts b/tests/runner-e2e/agentmail-setup-evidence.test.ts new file mode 100644 index 00000000000..24779c84b29 --- /dev/null +++ b/tests/runner-e2e/agentmail-setup-evidence.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { gradeAgentmailSetup } from "./agentmail-setup-evidence.js"; + +const good = { + interactions: [{ id: "card", kind: "connection_intent", status: "pending", addresseeUserId: "user", + payload: { serviceSlug: "agentmail", purpose: "channel", requestingAgentId: "agent" } }], + agentId: "agent", userId: "user", visible: true, inputTypes: ["password"], + keyLink: "https://console.agentmail.to/dashboard/api-keys", accessSelectorCount: 0, dialogCount: 0, +}; +describe("AgentMail setup oracle", () => { + it("accepts the persisted inline credential form", () => { + expect(gradeAgentmailSetup(good).every(check => check.passed)).toBe(true); + }); + it.each([ + { interactions: [] }, // The original search + prose link failure. + { interactions: [good.interactions[0], good.interactions[0]] }, + { agentId: "another-agent" }, + { userId: "another-user" }, + { visible: false }, + { inputTypes: ["text"] }, + { inputTypes: ["password", "text"] }, + { keyLink: "https://console.agentmail.to" }, + { keyLink: null }, + { accessSelectorCount: 2 }, + { dialogCount: 1 }, + ])("rejects incomplete or misleading evidence: %j", bad => { + expect(gradeAgentmailSetup({ ...good, ...bad }).some(check => !check.passed)).toBe(true); + }); +}); diff --git a/tests/runner-e2e/agentmail-setup-evidence.ts b/tests/runner-e2e/agentmail-setup-evidence.ts new file mode 100644 index 00000000000..fd316519168 --- /dev/null +++ b/tests/runner-e2e/agentmail-setup-evidence.ts @@ -0,0 +1,25 @@ +/** Independent browser + durable-state evidence, never the agent's claim. */ +export function gradeAgentmailSetup(input: { + interactions: Array<{ id: string; kind: string; status: string; addresseeUserId?: string | null; payload?: { serviceSlug?: string; purpose?: string; requestingAgentId?: string } }>; + agentId: string; + userId: string; + visible: boolean; + inputTypes: string[]; + keyLink: string | null; + accessSelectorCount: number; + dialogCount: number; +}) { + const pending = input.interactions.filter(row => row.status === "pending"); + const card = pending[0]; + return [ + { id: "agentmail-durable-request", passed: pending.length === 1 && card?.kind === "connection_intent" + && card.payload?.serviceSlug === "agentmail" && card.payload.purpose === "channel" + && card.payload.requestingAgentId === input.agentId && card.addresseeUserId === input.userId, + detail: "One saved AgentMail inbox request addresses the user for the requesting agent." }, + { id: "agentmail-inline-key-only", passed: input.visible && input.dialogCount === 0 + && input.inputTypes.length === 1 && input.inputTypes[0] === "password" && input.accessSelectorCount === 0, + detail: "The thread shows one password field inline without an access step or modal." }, + { id: "agentmail-direct-key-link", passed: input.keyLink === "https://console.agentmail.to/dashboard/api-keys", + detail: "Credential help opens the exact AgentMail API-key page." }, + ]; +} diff --git a/tests/runner-e2e/catalog.test.ts b/tests/runner-e2e/catalog.test.ts index 5417cfce92d..03f57d44901 100644 --- a/tests/runner-e2e/catalog.test.ts +++ b/tests/runner-e2e/catalog.test.ts @@ -146,10 +146,11 @@ describe("runner E2E catalog", () => { expect(localIntegrityTasks).toHaveLength(2); expect(openRouterBreadthTasks).toHaveLength(3); expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([ - 24, 6, 30, 3, 16, 16, 2, 6, 8, 46, 23, 47, 20, 52, 28, 18, 6, 6, 12, 10, 48, 16, 10, 2, 1, 1, + 24, 6, 30, 3, 16, 16, 2, 6, 8, 46, 23, 50, 20, 52, 28, 18, 6, 6, 12, 10, 48, 16, 10, 2, 1, 1, ]); - expect(validateRunnerCatalog()).toHaveLength(457); - expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(457); + expect(validateRunnerCatalog()).toHaveLength(460); + expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(460); + expect( runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"), ).toHaveLength(48); diff --git a/tests/runner-e2e/catalog.ts b/tests/runner-e2e/catalog.ts index 9b19d0829e2..2a3482aa7ec 100644 --- a/tests/runner-e2e/catalog.ts +++ b/tests/runner-e2e/catalog.ts @@ -1214,11 +1214,11 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [ id: "everyday-workflows", label: "Everyday Paperclip Work", manualOnly: true, description: "Real user requests, useful downloaded work, and durable continuation using production instructions.", groups: ["native"], profiles: everydayProfiles, environments: [localEnvironment, daytonaWarmEnvironment], - tasks: everydayTasks, expectedMatrixSize: 47, + tasks: everydayTasks, expectedMatrixSize: 50, excludedExecutionIds: [...everydayProfiles.flatMap(profile => everydayTasks .filter(task => !["build-revise", "delegate-feedback", "recover-controller", "create-skill-studio"].includes(task.id)) .map(task => `everyday-workflows.${profile.id}.daytona.${task.id}`))], - definitionMetadata: { version: 3, instructions: "production", grading: "outcome-and-invariants", scheduling: "explicit-only" }, + definitionMetadata: { version: 4, instructions: "production", grading: "outcome-and-invariants", scheduling: "explicit-only" }, }, { id: "context-integrity", diff --git a/tests/runner-e2e/everyday-cases.ts b/tests/runner-e2e/everyday-cases.ts index cbc709a073e..51bf0de2ee2 100644 --- a/tests/runner-e2e/everyday-cases.ts +++ b/tests/runner-e2e/everyday-cases.ts @@ -32,6 +32,7 @@ export const SLUGIFY_REVISION = `Add an optional --separator argument that accep export const LATE_REQUIREMENT = `Also support --max-length as a positive integer. Truncate the final slug to that length, then remove any trailing separator. In particular, input " Queue--Ready!! " with --max-length 7 must print "queue-r". Preserve the default behavior.`; const definitions = [ + ["agentmail-setup", "Request an AgentMail inbox in the thread", "I'd like you to acquire an email address with AgentMail and tell me the address once it exists. If I choose Not now, explain that no inbox was created and finish without connecting.", 2], ["provider-decline", "Decline external providers", "Connect HubSpot so you can read my recent contacts. If I choose None for now, explain that you could not retrieve the contacts and finish without connecting.", 2], ["provider-second", "Choose and reuse the second external provider", "Connect HubSpot and read my recent contacts. Report the contact names and verification code returned by the service.", 2], ["provider-native", "Prefer a built-in connection over external providers", "Connect Jira so you can read my recent issues. If I choose Not now, explain that you could not retrieve the issues and finish without connecting.", 2], diff --git a/tests/runner-e2e/everyday-flow.ts b/tests/runner-e2e/everyday-flow.ts index 1fc1a118512..b9f23d1f474 100644 --- a/tests/runner-e2e/everyday-flow.ts +++ b/tests/runner-e2e/everyday-flow.ts @@ -1,3 +1,4 @@ +import { gradeAgentmailSetup } from "./agentmail-setup-evidence.js"; import { expect, type Page } from "@playwright/test"; import { runnerApiToolsEnabled } from "../../server/src/services/native-runtime/runner-api-rollout.js"; import { spawn } from "node:child_process"; @@ -161,7 +162,8 @@ export async function runEverydayFlow(input: Input) { const providerChoice = caseId === "provider-decline" || caseId === "provider-second"; const nativeProviderCase = caseId === "provider-native"; let aggregatorFixture: Awaited> | undefined; - const decliningConnection = caseId === "connection-decline" || nativeProviderCase; + const agentmailSetup = caseId === "agentmail-setup"; + const decliningConnection = caseId === "connection-decline" || nativeProviderCase || agentmailSetup; const declining = decliningConnection || caseId === "service-decline"; let decisionId: string | undefined; let decisionResolvedAt: string | undefined; @@ -549,6 +551,7 @@ export async function runEverydayFlow(input: Input) { "everyday-decisions.ts", "aggregator-fixture.ts", "connection-routing-evidence.ts", + "agentmail-setup-evidence.ts", "everyday-delivery.ts", "everyday-observations.ts", "everyday-artifact.py", @@ -650,6 +653,7 @@ export async function runEverydayFlow(input: Input) { const state = await api.get<{connections:Row[]}>(`/api/companies/${fixtures.company.id}/tools/connections`); initialConnections = state.connections.map(c=>c.id); } + if (agentmailSetup) await api.patch("/api/instance/settings/experimental", { enableChatConnectors: true }); if (decliningConnection) { const state = await api.get<{ connections: Row[] }>( `/api/companies/${fixtures.company.id}/tools/connections`, @@ -952,7 +956,7 @@ export async function runEverydayFlow(input: Input) { interactions.interactions, review ? { kind: "tool", connectionId: review.connectionId } - : { kind: "connection", serviceSlug: nativeProviderCase ? "jira" : "notion" }, + : { kind: "connection", serviceSlug: agentmailSetup ? "agentmail" : nativeProviderCase ? "jira" : "notion" }, ); await expect( page.getByRole("button", { @@ -971,8 +975,28 @@ export async function runEverydayFlow(input: Input) { true, review ? "Tool approval belongs to the installed page service." - : `New connection request is for ${nativeProviderCase ? "Jira" : "Notion"}, without an external-provider question.`, + : `New connection request is for ${agentmailSetup ? "AgentMail" : nativeProviderCase ? "Jira" : "Notion"}, without an external-provider question.`, ); + if (agentmailSetup) { + // Reload proves the card is durable, rather than a transient model UI. + await page.reload(); + const form = page.getByTestId("agentmail-inline-setup"); + await expect(form).toBeVisible(); + const card = page.getByTestId("connection-intent-focus-target").filter({ has: form }); + const rows = await api.get[0]["interactions"]>(`/api/issues/${parent!.id}/interactions`); + const checks = gradeAgentmailSetup({ + // This harness boots a dedicated local_trusted instance. + interactions: rows, agentId: fixtures.agent.id, userId: "local-board", + visible: await form.isVisible(), + inputTypes: await card.locator("input").evaluateAll(inputs => inputs.map(input => input.getAttribute("type") ?? "text")), + keyLink: await form.getByRole("link", { name: "Get an AgentMail API key" }).getAttribute("href"), + accessSelectorCount: await card.locator('[role="radiogroup"], [role="combobox"], select').count(), + dialogCount: await page.getByRole("dialog").count(), + }); + ev.checks.push(...checks); + await input.capture("agentmail-inline-key", "AgentMail API-key card after reload", "agentmail-inline-key.png"); + if (checks.some(result => !result.passed)) throw new Error("AgentMail inline setup evidence failed"); + } if (review) check( "no-call-before-approval", diff --git a/tests/runner-e2e/everyday.test.ts b/tests/runner-e2e/everyday.test.ts index c1322eb7943..3afd8735fa9 100644 --- a/tests/runner-e2e/everyday.test.ts +++ b/tests/runner-e2e/everyday.test.ts @@ -212,7 +212,7 @@ describe("manual everyday workflow catalog", () => { const selected = selectRunnerExecutions( parseRunnerSelectors(["--suite", "everyday-workflows"]), ); - expect(selected).toHaveLength(47); + expect(selected).toHaveLength(50); expect(selected.every((e) => e.profile.generation === "native")).toBe(true); expect( selectRunnerExecutions( diff --git a/ui/src/adapters/paperclip-runner/index.test.ts b/ui/src/adapters/paperclip-runner/index.test.ts index 0f447cb4fea..e4c73548264 100644 --- a/ui/src/adapters/paperclip-runner/index.test.ts +++ b/ui/src/adapters/paperclip-runner/index.test.ts @@ -2,6 +2,33 @@ import { describe, expect, it } from "vitest"; import { paperclipRunnerUIAdapter } from "./index"; describe("paperclip runner transcript projection", () => { + it("omits unrelated provider diagnostics and legacy notices from streaming chat", () => { + const parse = paperclipRunnerUIAdapter.createStdoutParser!().parseLine; + const event = (eventType: string, payload: Record) => parse(JSON.stringify({ + type: "paperclip.prp.event", + event: { eventType, payload }, + }), "2026-10-02T12:00:00.000Z"); + const legacyNotice = { + schema: "paperclip.provider.notice.v1", + severity: "warning", + category: "warning", + summary: "ignored unrelated provider information", + userActionable: true, + }; + expect(event("harness.diagnostic", { code: "codex_unrelated_information" })).toEqual([]); + expect(event("provider.notice.recorded", legacyNotice)).toEqual([]); + expect(event("provider.notice.recorded", { ...legacyNotice, summary: "Repository is not trusted" })) + .toEqual([expect.objectContaining({ family: "provider_notice" })]); + expect(event("provider.notice.recorded", { ...legacyNotice, severity: "error" })) + .toEqual([expect.objectContaining({ family: "provider_notice" })]); + expect(event("provider.notice.recorded", { ...legacyNotice, category: "configWarning" })) + .toEqual([expect.objectContaining({ family: "provider_notice" })]); + expect(event("harness.diagnostic", { code: "provider_identity_failure", message: "Thread mismatch" })) + .toEqual([expect.objectContaining({ kind: "system", text: "Runner: Thread mismatch" })]); + expect(event("item.completed", { kind: "agentMessage", channel: "final", text: "Here is the answer." })) + .toEqual([expect.objectContaining({ kind: "assistant", text: "Here is the answer." })]); + }); + it("renders committed PRP semantic tool items with the existing chat parts", () => { const started = paperclipRunnerUIAdapter.parseStdoutLine(JSON.stringify({ type: "paperclip.prp.event", diff --git a/ui/src/adapters/paperclip-runner/index.ts b/ui/src/adapters/paperclip-runner/index.ts index 6d2ac167b78..ad1f8ef6c52 100644 --- a/ui/src/adapters/paperclip-runner/index.ts +++ b/ui/src/adapters/paperclip-runner/index.ts @@ -2,6 +2,7 @@ import type { PaperclipQuestion, PaperclipQuestionResponse, PaperclipQuestionSet import type { UIAdapterModule } from "../types"; import { parseCodexStdoutLine, buildPaperclipRunnerConfig } from "@paperclipai/adapter-codex-local/ui"; import { CodexLocalConfigFields } from "../codex-local/config-fields"; +import { isRunLogOnlyProviderEvent } from "@/components/transcript/run-log-only-events"; type JsonRecord = Record; @@ -671,6 +672,7 @@ function parsePrpEvent( ): TranscriptEntry[] { const eventType = text(event.eventType); const payload = record(event.payload); + if (isRunLogOnlyProviderEvent(eventType, payload)) return []; const family = eventType.startsWith("plan.") ? "plan" : eventType.startsWith("tool.execution.") ? "tool_execution" : eventType.startsWith("research.") ? "research" diff --git a/ui/src/api/email.ts b/ui/src/api/email.ts index 0afe70a71f8..aeeac285d39 100644 --- a/ui/src/api/email.ts +++ b/ui/src/api/email.ts @@ -1,14 +1,22 @@ import { api } from "./client"; import type { EmailConnectionInput, + EmailCredentialOption, ToolConnection, EmailEndpointSummary, EmailPublicationSummary, EmailThreadSummary, EmailSendInput, EmailEndpointSetupInput, + EmailAddressCheckInput, + EmailAddressCheckResult, } from "@paperclipai/shared"; export const emailApi = { + credentials: (companyId: string) => api.get(`/companies/${companyId}/email/connections`), + checkAddress: (companyId: string, connectionId: string, input: EmailAddressCheckInput, signal?: AbortSignal) => + api.post( + `/companies/${companyId}/email/connections/${connectionId}/check-address`, input, { signal }, + ), connect: (companyId: string, input: EmailConnectionInput) => api.post( `/companies/${companyId}/email/connections`, @@ -29,6 +37,7 @@ export const emailApi = { ), inspect: (companyId: string, apiKey: string) => api.post<{ + scope: { scope_type: string }; inboxes: { inbox_id: string }[]; domains: { domain_id: string; domain: string; status: string }[]; }>(`/companies/${companyId}/email/inspect`, { apiKey }), diff --git a/ui/src/components/AgentContextualSidebar.test.tsx b/ui/src/components/AgentContextualSidebar.test.tsx index 0c0571b938b..7b4eaa5491d 100644 --- a/ui/src/components/AgentContextualSidebar.test.tsx +++ b/ui/src/components/AgentContextualSidebar.test.tsx @@ -34,13 +34,13 @@ vi.mock("./SidebarNavItem", () => ({ })); describe("AgentContextualSidebar", () => { - it.each([false, true])("shows agent Channels only when chat connectors are enabled (%s)", (enabled) => { + it.each([false, true])("keeps Channels available for default email regardless of the chat setting (%s)", (enabled) => { const client = new QueryClient(); client.setQueryData(queryKeys.instance.experimentalSettings, { enableChatConnectors: enabled }); const markup = renderToStaticMarkup( ); - expect(markup.includes('href="/agents/agent/channels"')).toBe(enabled); + expect(markup.includes('href="/agents/agent/channels"')).toBe(true); expect(markup).toContain('href="/agents/agent/tools"'); client.clear(); }); diff --git a/ui/src/components/AgentContextualSidebar.tsx b/ui/src/components/AgentContextualSidebar.tsx index abddd811798..14ab6a27afc 100644 --- a/ui/src/components/AgentContextualSidebar.tsx +++ b/ui/src/components/AgentContextualSidebar.tsx @@ -16,7 +16,6 @@ import { } from "lucide-react"; import { agentsApi } from "@/api/agents"; import { useCompany } from "@/context/CompanyContext"; -import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled"; import { queryKeys } from "@/lib/queryKeys"; import { ContextualSidebarFrame } from "./ContextualSidebarFrame"; import { SidebarNavItem } from "./SidebarNavItem"; @@ -60,7 +59,6 @@ export function AgentContextualSidebar({ labels?: Partial>; }) { const { selectedCompanyId } = useCompany(); - const { enabled: chatConnectorsEnabled } = useChatConnectorsEnabled(); const shouldResolveAgent = !agentId || !agentName; const { data: resolvedAgent } = useQuery({ queryKey: [...queryKeys.agents.detail(agentRef), selectedCompanyId ?? null, "contextual-sidebar"], @@ -97,7 +95,6 @@ export function AgentContextualSidebar({

{section.items - .filter((item) => item.value !== "channels" || chatConnectorsEnabled) .map((item) => { const href = agentDetailHref(agentRef, item.value); return ( diff --git a/ui/src/components/AgentMultiSelect.test.tsx b/ui/src/components/AgentMultiSelect.test.tsx index 82daf825092..81353d0afab 100644 --- a/ui/src/components/AgentMultiSelect.test.tsx +++ b/ui/src/components/AgentMultiSelect.test.tsx @@ -128,6 +128,18 @@ describe("AgentMultiSelect", () => { expect(document.body.querySelector('input[placeholder="Filter agents"]')).toBeNull(); }); + it("uses the same agent avatar in the selected value and every option", async () => { + const agents = [{ id: "agent-1", name: "Ralph" }, { id: "agent-2", name: "Support" }]; + root = createRoot(container); + act(() => root?.render()); + const selected = container.querySelector('[data-slot="agent-avatar"] img')?.getAttribute("src"); + expect(selected).toBeTruthy(); + act(() => container.querySelector("button")?.click()); + await flush(); + expect(document.querySelector('[aria-label="Select Ralph"] [data-slot="agent-avatar"] img')?.getAttribute("src")).toBe(selected); + expect(document.querySelector('[aria-label="Select Support"] [data-slot="agent-avatar"] img')).not.toBeNull(); + }); + it("previews selected agents and stages changes until save", async () => { const onSave = vi.fn(); const agents = Array.from({ length: 6 }, (_, index) => ({ diff --git a/ui/src/components/AgentMultiSelect.tsx b/ui/src/components/AgentMultiSelect.tsx index 5c38fec2c3e..5d14afab69d 100644 --- a/ui/src/components/AgentMultiSelect.tsx +++ b/ui/src/components/AgentMultiSelect.tsx @@ -1,4 +1,4 @@ -import { AgentAvatar } from "@/components/AgentAvatar"; +import { AgentAvatar, type AvatarAgent } from "@/components/AgentAvatar"; import { useEffect, useMemo, useState, type ComponentProps, type ReactNode } from "react"; import { ChevronRight } from "lucide-react"; import { Button } from "@/components/ui/button"; @@ -8,7 +8,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover import { Skeleton } from "@/components/ui/skeleton"; import { cn } from "@/lib/utils"; -export interface AgentMultiSelectOption { +export interface AgentMultiSelectOption extends AvatarAgent { id: string; name: string; title?: string | null; @@ -63,8 +63,9 @@ export function AgentSelect({ className={cn("w-full justify-between", triggerClassName)} disabled={disabled} > - - {selectedAgent?.name ?? placeholder} + + {selectedAgent && } + {selectedAgent?.name ?? placeholder} @@ -94,7 +95,7 @@ export function AgentSelect({ setOpen(false); }} > - + {agent.name} {agent.title ? {agent.title} : null} diff --git a/ui/src/components/ChatConnectorsExperimentalGate.test.tsx b/ui/src/components/ChatConnectorsExperimentalGate.test.tsx index b0feae96f33..ce2741da815 100644 --- a/ui/src/components/ChatConnectorsExperimentalGate.test.tsx +++ b/ui/src/components/ChatConnectorsExperimentalGate.test.tsx @@ -13,14 +13,19 @@ const api = vi.hoisted(() => ({ settings: vi.fn(), list: vi.fn(), binding: vi.fn(), + get: vi.fn(), + provider: null as string | null, + endpointId: undefined as string | undefined, })); vi.mock("@/api/instanceSettings", () => ({ instanceSettingsApi: { getExperimental: api.settings }, })); vi.mock("@/api/chatEndpoints", () => ({ - chatEndpointsApi: { list: api.list, getIssueBinding: api.binding }, + chatEndpointsApi: { list: api.list, getIssueBinding: api.binding, get: api.get }, })); vi.mock("@/lib/router", () => ({ + useParams: () => ({ endpointId: api.endpointId }), + useSearchParams: () => [new URLSearchParams(api.provider ? { provider: api.provider } : {})], Navigate: ({ to }: { to: string }) =>
, Link: ({ to, children }: { to: string; children: React.ReactNode }) => ( {children} @@ -44,6 +49,9 @@ describe("Chat connectors visibility gate", () => { client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); api.settings.mockResolvedValue({ enableChatConnectors: false }); api.list.mockResolvedValue([]); + api.get.mockResolvedValue({ provider: "agentmail" }); + api.provider = null; + api.endpointId = undefined; api.binding.mockResolvedValue(null); }); afterEach(() => { @@ -82,6 +90,20 @@ describe("Chat connectors visibility gate", () => { ).toBe("/apps"); }, ); + it("opens AgentMail setup with the experimental flag disabled", async () => { + api.provider = "agentmail"; + await render(); + expect(container.querySelector("[data-chat-setup]")).not.toBeNull(); + expect(api.get).not.toHaveBeenCalled(); + }); + it.each(["agentmail", "slack"])("admits only default email management when chat is disabled (%s)", async (provider) => { + api.endpointId = "endpoint-1"; + api.get.mockResolvedValue({ provider }); + await render(); + await vi.waitFor(() => expect(api.get).toHaveBeenCalledWith("endpoint-1")); + await vi.waitFor(() => expect(Boolean(container.querySelector("[data-chat-setup]"))).toBe(provider === "agentmail")); + if (provider !== "agentmail") expect(container.querySelector("[data-redirect]")).not.toBeNull(); + }); it("waits without exposing setup, then enables the route after explicit opt-in", async () => { let resolve!: (value: unknown) => void; api.settings.mockReturnValue( @@ -127,9 +149,9 @@ describe("Chat connectors visibility gate", () => { expect(container.querySelector("[data-chat-setup]")).toBeNull(); expect(api.settings).not.toHaveBeenCalled(); }); - it("hides cached agent channels and task bindings without fetching chat data while disabled", async () => { + it("keeps agent email channels available but hides cached experimental chat channels and task bindings", async () => { client.setQueryData(queryKeys.chatEndpoints.list("company-1"), [ - { id: "endpoint-1", assignedAgentId: "agent-1", status: "active" }, + { provider: "slack", id: "endpoint-1", assignedAgentId: "agent-1", status: "active" }, ]); client.setQueryData(["issue-chat-binding", "company-1", "issue-1"], { endpointId: "endpoint-1", @@ -147,8 +169,9 @@ describe("Chat connectors visibility gate", () => { ), ); await flushReact(); - expect(container.innerHTML).toBe(""); - expect(api.list).not.toHaveBeenCalled(); + expect(container.textContent).toContain("Connect AgentMail from Connectors."); + expect(container.querySelector('a[href="/apps/chat/endpoint-1/settings"]')).toBeNull(); + expect(api.list).toHaveBeenCalledWith("company-1"); expect(api.binding).not.toHaveBeenCalled(); }); }); diff --git a/ui/src/components/ChatConnectorsExperimentalGate.tsx b/ui/src/components/ChatConnectorsExperimentalGate.tsx index 91a8c4a3b63..e9b081c56f3 100644 --- a/ui/src/components/ChatConnectorsExperimentalGate.tsx +++ b/ui/src/components/ChatConnectorsExperimentalGate.tsx @@ -1,6 +1,25 @@ import type { ReactNode } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { chatEndpointsApi } from "@/api/chatEndpoints"; +import { queryKeys } from "@/lib/queryKeys"; +import { Button } from "@/components/ui/button"; import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled"; -import { Navigate } from "@/lib/router"; +import { Navigate, useParams, useSearchParams } from "@/lib/router"; + +function DefaultEmailEndpointGate({ endpointId, children }: { endpointId: string; children: ReactNode }) { + const endpoint = useQuery({ + queryKey: queryKeys.chatEndpoints.detail(endpointId), + queryFn: () => chatEndpointsApi.get(endpointId), + }); + if (endpoint.isError) return ( +
+

{endpoint.error.message}

+ +
+ ); + if (!endpoint.data) return null; + return endpoint.data.provider === "agentmail" ? <>{children} : ; +} export function ChatConnectorsExperimentalGate({ children, @@ -8,7 +27,12 @@ export function ChatConnectorsExperimentalGate({ children: ReactNode; }) { const { enabled, loaded } = useChatConnectorsEnabled(); + const [params] = useSearchParams(); + const { endpointId } = useParams<{ endpointId: string }>(); + if (!endpointId && params.get("provider") === "agentmail") return <>{children}; if (!loaded) return null; - if (!enabled) return ; + if (!enabled) return endpointId + ? {children} + : ; return <>{children}; } diff --git a/ui/src/components/EmailMessageCard.tsx b/ui/src/components/EmailMessageCard.tsx index 32a4298870d..be4a083e15f 100644 --- a/ui/src/components/EmailMessageCard.tsx +++ b/ui/src/components/EmailMessageCard.tsx @@ -6,9 +6,8 @@ import type { EmailPublicationSummary, EmailThreadSummary, } from "@paperclipai/shared"; -import { emailApi } from "@/api/email"; +import { useEmailThread } from "@/hooks/useEmailThread"; import { issuesApi } from "@/api/issues"; -import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled"; const EmailContext = createContext(null); export function EmailThreadProvider({ companyId, @@ -19,13 +18,7 @@ export function EmailThreadProvider({ issueId: string; children: ReactNode; }) { - const { enabled } = useChatConnectorsEnabled(); - const thread = useQuery({ - queryKey: ["email-thread", companyId, issueId], - queryFn: () => emailApi.thread(companyId, issueId), - enabled, - refetchInterval: enabled ? 3000 : false, - }); + const thread = useEmailThread(companyId, issueId); return ( {children} diff --git a/ui/src/components/EmailTaskActivity.tsx b/ui/src/components/EmailTaskActivity.tsx index 428a9530856..6f442b1372c 100644 --- a/ui/src/components/EmailTaskActivity.tsx +++ b/ui/src/components/EmailTaskActivity.tsx @@ -1,7 +1,8 @@ import { EmailMessageCard } from "./EmailMessageCard"; import { useState } from "react"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; import { emailApi } from "@/api/email"; +import { useEmailThread } from "@/hooks/useEmailThread"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import type { EmailPublicationSummary } from "@paperclipai/shared"; @@ -18,12 +19,7 @@ export function EmailTaskActivity({ const cache = useQueryClient(); const threadKey = ["email-thread", companyId, issueId]; const queryEnabled = Boolean(companyId && issueId) && !issueId.startsWith("chat:"); - const thread = useQuery({ - queryKey: threadKey, - queryFn: () => emailApi.thread(companyId, issueId), - enabled: queryEnabled, - refetchInterval: 3000, - }); + const thread = useEmailThread(companyId, issueId); if (!queryEnabled) return null; const data = thread.data; const messages = data?.messages.filter((m) => !m.commentId) ?? []; diff --git a/ui/src/components/EmailThreadPolling.test.tsx b/ui/src/components/EmailThreadPolling.test.tsx new file mode 100644 index 00000000000..7af18bf917b --- /dev/null +++ b/ui/src/components/EmailThreadPolling.test.tsx @@ -0,0 +1,75 @@ +// @vitest-environment jsdom + +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { EmailThreadProvider } from "./EmailMessageCard"; +import { EmailTaskActivity } from "./EmailTaskActivity"; + +const api = vi.hoisted(() => ({ thread: vi.fn() })); +vi.mock("@/api/email", () => ({ emailApi: { thread: api.thread } })); + +const emailThread = { issueId: "task-1", messages: [], publications: [] }; + +describe("task email polling", () => { + let container: HTMLDivElement; + let root: Root; + let client: QueryClient; + beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.useFakeTimers(); + api.thread.mockReset(); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + }); + afterEach(async () => { + await act(async () => root.unmount()); + client.clear(); + container.remove(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + async function render(issueId = "task-1") { + await act(async () => { + root.render( + + + + ); + }); + await advance(1); + } + async function advance(ms: number) { + await act(async () => { await vi.advanceTimersByTimeAsync(ms); }); + } + it("stops recurring requests when both task observers find no email thread", async () => { + api.thread.mockResolvedValue(null); + await render(); + expect(api.thread).toHaveBeenCalledTimes(1); + await advance(10_000); + expect(api.thread).toHaveBeenCalledTimes(1); + }); + it("continues refreshing an email task", async () => { + api.thread.mockResolvedValue(emailThread); + await render(); + await advance(6_100); + expect(api.thread.mock.calls.length).toBeGreaterThan(1); + }); + it("can discover a thread after invalidation and resume updates", async () => { + api.thread.mockResolvedValueOnce(null).mockResolvedValue(emailThread); + await render(); + await act(async () => { await client.invalidateQueries({ queryKey: ["email-thread", "company-1", "task-1"] }); }); + await advance(1); + expect(api.thread).toHaveBeenCalledTimes(2); + await advance(3_100); + expect(api.thread.mock.calls.length).toBeGreaterThan(2); + }); + it("does not request email threads for chat conversations", async () => { + await render("chat:agent-1"); + await advance(6_100); + expect(api.thread).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/src/components/chat/AgentChannelsPanel.tsx b/ui/src/components/chat/AgentChannelsPanel.tsx index 216dc9bbbe0..ed4ce716a26 100644 --- a/ui/src/components/chat/AgentChannelsPanel.tsx +++ b/ui/src/components/chat/AgentChannelsPanel.tsx @@ -28,12 +28,11 @@ export function AgentChannelsPanel({ const query = useQuery({ queryKey: queryKeys.chatEndpoints.list(companyId), queryFn: () => chatEndpointsApi.list(companyId), - enabled, + enabled: Boolean(companyId), }); - if (!enabled) return null; const endpoints = (query.data ?? []).filter( (endpoint) => - endpoint.assignedAgentId === agentId && endpoint.status !== "archived", + endpoint.assignedAgentId === agentId && endpoint.status !== "archived" && (endpoint.provider === "agentmail" || enabled), ); return (
@@ -57,8 +56,7 @@ export function AgentChannelsPanel({

No channels connected

- Connect AgentMail, Slack, GitHub Code Review Bot, Discord, Microsoft Teams, or Telegram from - Connectors. + {enabled ? "Connect AgentMail, Slack, GitHub Code Review Bot, Discord, Microsoft Teams, or Telegram from Connectors." : "Connect AgentMail from Connectors."}

} + {changeKey.error &&

{changeKey.error.message}

} + {setup.error &&

{setup.error.message}

} +
+ + +
+ ; +} diff --git a/ui/src/features/connections/ApiKeyCredentialField.tsx b/ui/src/features/connections/ApiKeyCredentialField.tsx new file mode 100644 index 00000000000..741ab22fd93 --- /dev/null +++ b/ui/src/features/connections/ApiKeyCredentialField.tsx @@ -0,0 +1,38 @@ +import { useId } from "react"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; + +/** Providers supply only credentials the current user is authorized to use. + * Values are opaque connection references, never secret values. */ +export function ApiKeyCredentialField({ options, connectionId, onConnectionChange, value, onChange, + disabled, loading, error, providerName, keysUrl, label = "API key" }: { + options: { id: string; label: string; disabled?: boolean }[]; + connectionId: string | null; + onConnectionChange(id: string): void; + value: string; + onChange(value: string): void; + disabled?: boolean; + loading?: boolean; + error?: string; + providerName: string; + keysUrl: string; + label?: string; +}) { + const id = useId(); + const choices = connectionId && !options.some(option => option.id === connectionId) + ? [{ id: connectionId, label: loading ? "Checking saved API key…" : "Previously selected key · unavailable", disabled: true }, ...options] : options; + return
+ + {choices.length > 0 && } + {!connectionId && { onConnectionChange(""); onChange(event.target.value); }} placeholder={`Paste your ${providerName} API key`} />} + {loading &&

Checking saved API keys…

} + {error &&

Could not load saved API keys. {error}

} + Get an {providerName} API key ↗ +
; +} diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx index a8b0a741925..e82db5ccf99 100644 --- a/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx +++ b/ui/src/features/connections/ConnectionIntentInteractionBody.test.tsx @@ -16,6 +16,19 @@ import { } from "@/fixtures/issueThreadInteractionFixtures"; import { ConnectionIntentInteractionBody } from "./ConnectionIntentInteractionBody"; +const emailConnectMock = vi.hoisted(() => vi.fn()); +const emailSetupMock = vi.hoisted(() => vi.fn()); +const emailListMock = vi.hoisted(() => vi.fn()); +const emailControlMock = vi.hoisted(() => vi.fn()); +const emailCredentialsMock = vi.hoisted(() => vi.fn()); +vi.mock("@/api/email", () => ({ emailApi: { + credentials: (...args: unknown[]) => emailCredentialsMock(...args), + list: (...args: unknown[]) => emailListMock(...args), + control: (...args: unknown[]) => emailControlMock(...args), + connect: (...args: unknown[]) => emailConnectMock(...args), + setup: (...args: unknown[]) => emailSetupMock(...args), +} })); + const credentialRender = vi.hoisted(() => vi.fn()); const setupOptionsMock = vi.hoisted(() => vi.fn()); const completeMock = vi.hoisted(() => vi.fn()); @@ -113,12 +126,12 @@ async function flush() { async function waitForAssertion(assertion: () => void, attempts = 20) { let lastError: unknown; for (let attempt = 0; attempt < attempts; attempt += 1) { + await flush(); try { assertion(); return; } catch (error) { lastError = error; - await flush(); } } throw lastError; @@ -175,6 +188,12 @@ function button(label: string) { } beforeEach(() => { + sessionStorage.clear(); + emailCredentialsMock.mockReset().mockResolvedValue([]); + emailListMock.mockReset().mockResolvedValue([]); + emailControlMock.mockReset().mockResolvedValue({}); + emailConnectMock.mockReset().mockResolvedValue({ id: "email-account" }); + emailSetupMock.mockReset().mockResolvedValue({ connectionId: "email-inbox" }); setDefaultMock.mockReset(); getAgentMock.mockReset(); updateAgentMock.mockReset(); @@ -196,6 +215,8 @@ beforeEach(() => { afterEach(async () => { if (root) await act(() => root?.unmount()); + await queryClient.cancelQueries(); + queryClient.clear(); host?.remove(); document.body .querySelectorAll("[data-radix-focus-guard]") @@ -581,3 +602,168 @@ describe("AI repair inside the card", () => { expect(document.body.textContent).not.toContain("can continue without it"); }); }); + +describe("AgentMail inline setup", () => { + const interaction: ConnectionIntentInteraction = { + ...pendingConnectionIntentInteraction, + payload: { ...pendingConnectionIntentInteraction.payload, purpose: "channel", serviceSlug: "agentmail", serviceName: "AgentMail" }, + }; + async function clickReadyButton(label: string) { + await waitForAssertion(() => expect(button(label)?.disabled).toBe(false)); + await act(() => button(label)!.click()); + await flush(); + } + async function enterKey() { + await waitForAssertion(() => expect(document.querySelector('input[type="password"]')).not.toBeNull()); + const input = document.querySelector('input[type="password"]') as HTMLInputElement; + await act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "fixture-api-key"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + } + it("shows only the key inline, saves company access for this agent and completes after inbox setup", async () => { + renderBody(interaction); + await flush(); + expect(document.querySelector('[role="dialog"]')).toBeNull(); + await waitForAssertion(() => expect(document.querySelectorAll("input")).toHaveLength(1)); + expect(document.querySelector('a[href="https://console.agentmail.to/dashboard/api-keys"]')).not.toBeNull(); + expect(document.querySelector('[role="radiogroup"], select')).toBeNull(); + expect(button("Connect AgentMail")?.disabled).toBe(true); + await enterKey(); + await clickReadyButton("Connect AgentMail"); + expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, { + apiKey: "fixture-api-key", grantKind: "organization", allAgents: false, + agentIds: [interaction.payload.requestingAgentId], idempotencyKey: interaction.id, + }); + expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, { + assignedAgentId: interaction.payload.requestingAgentId, credentialConnectionId: "email-account", + receiveMode: "websocket", idempotencyKey: interaction.id, + }); + expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox"); + }); + it("keeps invalid credentials retryable and does not create an inbox or accept the request", async () => { + emailConnectMock.mockRejectedValueOnce(new Error("AgentMail request failed (401)")); + renderBody(interaction); await flush(); await enterKey(); + await clickReadyButton("Connect AgentMail"); + expect(document.querySelector('[role="alert"]')?.textContent).toContain("401"); + expect(emailSetupMock).not.toHaveBeenCalled(); + expect(completeMock).not.toHaveBeenCalled(); + await clickReadyButton("Connect AgentMail"); + expect(completeMock).toHaveBeenCalledTimes(1); + }); + it("retries inbox setup without asking for or saving the key again", async () => { + emailSetupMock.mockRejectedValueOnce(new Error("Inbox setup unavailable")); + renderBody(interaction); await flush(); await enterKey(); + await clickReadyButton("Connect AgentMail"); + expect(completeMock).not.toHaveBeenCalled(); + expect(document.querySelector('input[type="password"]')).toBeNull(); + await clickReadyButton("Finish setup"); + expect(emailConnectMock).toHaveBeenCalledTimes(1); + expect(emailSetupMock).toHaveBeenCalledTimes(2); + expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox"); + }); + it("can choose another key after a saved key fails, retiring an empty draft and preserving the retry identity", async () => { + emailCredentialsMock.mockResolvedValue([{ id: "saved-account", label: "Saved key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]); + emailSetupMock.mockRejectedValueOnce(new Error("Inbox already assigned")) + .mockRejectedValueOnce(new Error("Temporary provider failure")); + emailListMock.mockResolvedValue([{ id: interaction.id, address: null, status: "draft" }]); + renderBody(interaction); await flush(); + await waitForAssertion(() => expect(button("Connect AgentMail")?.disabled).toBe(false)); + expect((document.querySelector("select") as HTMLSelectElement)?.value).toBe("saved-account"); + expect(emailConnectMock).not.toHaveBeenCalled(); + await clickReadyButton("Connect AgentMail"); + expect(emailConnectMock).not.toHaveBeenCalled(); + await clickReadyButton("Change API key"); + expect(emailControlMock).toHaveBeenCalledWith(interaction.id, "remove"); + await enterKey(); + await clickReadyButton("Connect AgentMail"); + const next = emailSetupMock.mock.calls[1][1].idempotencyKey; + expect(next).not.toBe(interaction.id); + expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ idempotencyKey: next })); + expect(sessionStorage.getItem(`paperclip.agentmail-inline:${interaction.companyId}:${interaction.id}`)).not.toContain("fixture-api-key"); + await act(() => root!.unmount()); host!.remove(); queryClient.clear(); + renderBody(interaction); await flush(); + await clickReadyButton("Finish setup"); + expect(emailSetupMock.mock.calls[2][1].idempotencyKey).toBe(next); + expect(emailConnectMock).toHaveBeenCalledTimes(1); + expect(completeMock).toHaveBeenCalledWith(interaction.id, "email-inbox"); + }); + it("does not switch keys after an inbox address is allocated", async () => { + setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "saved-account", readyConnectionId: null } }); + emailListMock.mockResolvedValue([{ id: interaction.id, address: "reserved@example.test", status: "draft" }]); + renderBody(interaction); await flush(); + await clickReadyButton("Change API key"); + expect(document.body.textContent).toContain("reserved@example.test is already reserved"); + expect(emailControlMock).not.toHaveBeenCalled(); + expect(document.querySelector('input[type="password"]')).toBeNull(); + }); + it("recovers the server-saved account when refresh interrupted its response", async () => { + const resumedInteraction = { ...interaction, id: "a381e91e-7127-427d-9d2d-519d4deba89f" }; + sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${resumedInteraction.id}`, JSON.stringify({ + setupRequestId: resumedInteraction.id, credentialId: null, inboxConnectionId: null, selectedCredentialId: "", + })); + setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "server-saved-account", readyConnectionId: null } }); + renderBody(resumedInteraction); await flush(); + expect(document.querySelector('input[type="password"]')).toBeNull(); + await clickReadyButton("Finish setup"); + expect(emailConnectMock).not.toHaveBeenCalled(); + expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ + credentialConnectionId: "server-saved-account", idempotencyKey: resumedInteraction.id, + })); + }); + it("keeps a different saved-key selection when recovering an interrupted save", async () => { + const resumedInteraction = { ...interaction, id: "a381e91e-7127-427d-9d2d-519d4deba89f" }; + sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${resumedInteraction.id}`, JSON.stringify({ + setupRequestId: resumedInteraction.id, credentialId: null, inboxConnectionId: null, selectedCredentialId: "selected-account", + })); + emailCredentialsMock.mockResolvedValue([{ id: "selected-account", label: "My selected key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]); + setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "earlier-account", readyConnectionId: null } }); + renderBody(resumedInteraction); await flush(); + await waitForAssertion(() => expect((document.querySelector('select') as HTMLSelectElement)?.value).toBe("selected-account")); + await clickReadyButton("Connect AgentMail"); + expect(emailConnectMock).not.toHaveBeenCalled(); + expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ + credentialConnectionId: "selected-account", idempotencyKey: resumedInteraction.id, + })); + }); + it("does not restore an abandoned server account after the user changes keys", async () => { + const replacementRequestId = "a381e91e-7127-427d-9d2d-519d4deba89f"; + sessionStorage.setItem(`paperclip.agentmail-inline:${interaction.companyId}:${interaction.id}`, JSON.stringify({ + setupRequestId: replacementRequestId, credentialId: null, inboxConnectionId: null, selectedCredentialId: "", + })); + setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "abandoned-account", readyConnectionId: null } }); + renderBody(interaction); await flush(); await enterKey(); + await clickReadyButton("Connect AgentMail"); + expect(emailConnectMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ idempotencyKey: replacementRequestId })); + expect(emailSetupMock).toHaveBeenCalledWith(interaction.companyId, expect.objectContaining({ + credentialConnectionId: "email-account", idempotencyKey: replacementRequestId, + })); + }); + it("resumes a saved account after reload and retries acceptance without recreating the inbox", async () => { + setupOptionsMock.mockResolvedValue({ existingConnections: [], emailSetup: { credentialConnectionId: "email-account", readyConnectionId: "email-inbox" } }); + completeMock.mockRejectedValueOnce(new Error("Retry completion")); + renderBody(interaction); await flush(); + await clickReadyButton("Continue"); + await clickReadyButton("Continue"); + expect(emailConnectMock).not.toHaveBeenCalled(); + expect(emailSetupMock).not.toHaveBeenCalled(); + expect(completeMock).toHaveBeenCalledTimes(2); + }); + it("declines without provider requests and hides credentials from other viewers", async () => { + renderBody(interaction); await flush(); + await clickReadyButton("Not now"); + expect(declineMock).toHaveBeenCalledWith(interaction.id); + expect(emailConnectMock).not.toHaveBeenCalled(); + expect(emailSetupMock).not.toHaveBeenCalled(); + await act(() => root!.render()); + expect(document.querySelector('input')).toBeNull(); + }); + it("can decline even when inbox setup options fail to load", async () => { + setupOptionsMock.mockRejectedValue(new Error("Email setup is unavailable")); + renderBody(interaction); + await waitForAssertion(() => expect(document.body.textContent).toContain("Email setup is unavailable")); + await clickReadyButton("Not now"); + expect(declineMock).toHaveBeenCalledWith(interaction.id); + expect(emailConnectMock).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx index 17010fd026d..3a7f50c9dbd 100644 --- a/ui/src/features/connections/ConnectionIntentInteractionBody.tsx +++ b/ui/src/features/connections/ConnectionIntentInteractionBody.tsx @@ -9,6 +9,7 @@ import { XCircle, } from "lucide-react"; import type { AiAuthMethod, ConnectionIntentInteraction } from "@paperclipai/shared"; +import { AgentMailIntentSetup } from "./AgentMailIntentSetup"; import { connectionIntentsApi } from "@/api/connection-intents"; import { aiConnectionsApi } from "@/api/ai-connections"; import { agentsApi } from "@/api/agents"; @@ -61,6 +62,7 @@ export function ConnectionIntentInteractionBody({ ); const isPending = interaction.status === "pending"; const isAi = interaction.payload.purpose === "ai"; + const isEmail = interaction.payload.purpose === "channel" && interaction.payload.serviceSlug === "agentmail"; const focusTargetId = `connection-intent-focus-target-${interaction.id}`; const invalidateTask = async ( @@ -410,6 +412,7 @@ export function ConnectionIntentInteractionBody({

{interaction.payload.purpose === "ai" ? "This task can’t run until the agent has a valid AI connection. Connect here and the task will resume automatically." + : isEmail ? "Connect AgentMail to create an email address for this agent." : "Connect your identity or reuse an eligible connection. Access is added only for this agent."}

@@ -423,7 +426,19 @@ export function ConnectionIntentInteractionBody({

) : null} -
+ {isEmail ? setupQuery.isLoading || setupQuery.isError ? <> + {setupContent} + + : { await completeMutation.mutateAsync(connectionId); }} + onDecline={() => declineMutation.mutate()} + declining={declineMutation.isPending} + /> :
{!isAi &&
+
} {isAi && open ?
{inlineContent}
: null} - {completeMutation.isError || + {(!isEmail && completeMutation.isError) || (selectAiAccountMutation.isError && selectAiAccountMutation.variables?.generation === generation) || adoptMutation.isError || declineMutation.isError || diff --git a/ui/src/features/connections/ConnectionSetupFlow.tsx b/ui/src/features/connections/ConnectionSetupFlow.tsx index 7a01867fc7a..548d4a8681e 100644 --- a/ui/src/features/connections/ConnectionSetupFlow.tsx +++ b/ui/src/features/connections/ConnectionSetupFlow.tsx @@ -970,7 +970,7 @@ function StandardConnectionSetupFlow({ // Generic custom URLs remain usable without selecting a hidden provider. const visibleGalleryApps = useMemo( () => (galleryQuery.data?.apps ?? []).filter((app) => memoryConnectorsEnabled || !isMemoryConnectorId(app.slug)).filter((app) => - chatConnectorsEnabled || + app.slug === "agentmail" || chatConnectorsEnabled || !app.methods.some((method) => method.transport === "chat_sdk") || appSupportsToolCatalogSetup(app), ), diff --git a/ui/src/features/connections/useEmailAddressCheck.ts b/ui/src/features/connections/useEmailAddressCheck.ts new file mode 100644 index 00000000000..173b1d84598 --- /dev/null +++ b/ui/src/features/connections/useEmailAddressCheck.ts @@ -0,0 +1,25 @@ +import { useEffect, useState } from "react"; +import type { EmailAddressCheckResult } from "@paperclipai/shared"; +import { emailApi } from "@/api/email"; + +type Check = { key: string; result?: EmailAddressCheckResult; error?: string }; + +/** Debounce reads, abort superseded requests, and never display an old address's result. */ +export function useEmailAddressCheck(companyId: string, connectionId: string, username: string, domain: string, enabled: boolean) { + const key = JSON.stringify([companyId, connectionId, username, domain]); + const [check, setCheck] = useState(); + useEffect(() => { + if (!enabled) return; + const controller = new AbortController(); + const timeout = setTimeout(() => { + void emailApi.checkAddress(companyId, connectionId, { username, domain }, controller.signal) + .then(result => { if (!controller.signal.aborted) setCheck({ key, result }); }) + .catch(error => { + if (!controller.signal.aborted) setCheck({ key, error: error instanceof Error ? error.message : "Could not check this address." }); + }); + }, 350); + return () => { clearTimeout(timeout); controller.abort(); }; + }, [companyId, connectionId, username, domain, key, enabled]); + const current = enabled && check?.key === key ? check : undefined; + return { result: current?.result, error: current?.error, checking: enabled && !current }; +} diff --git a/ui/src/hooks/useEmailThread.ts b/ui/src/hooks/useEmailThread.ts new file mode 100644 index 00000000000..390a2d2d0ac --- /dev/null +++ b/ui/src/hooks/useEmailThread.ts @@ -0,0 +1,13 @@ +import { useQuery } from "@tanstack/react-query"; +import { emailApi } from "@/api/email"; + +export function useEmailThread(companyId: string, issueId: string) { + return useQuery({ + queryKey: ["email-thread", companyId, issueId], + queryFn: () => emailApi.thread(companyId, issueId), + enabled: Boolean(companyId && issueId) && !issueId.startsWith("chat:"), + // A null response identifies an ordinary task. It can still refetch on + // focus or invalidation, but only email tasks need recurring updates. + refetchInterval: (query) => query.state.data === null ? false : 3000, + }); +} diff --git a/ui/src/index.css b/ui/src/index.css index bec5ab10ee9..cac1eb5c35e 100644 --- a/ui/src/index.css +++ b/ui/src/index.css @@ -95,6 +95,10 @@ --file-tree-indent-base: calc(var(--spacing) * 2); --file-tree-indent-step: calc(var(--spacing) * 6); --file-tree-indent-max: 40%; + --native-select-caret-half: calc(var(--spacing) * 1.5); + --native-select-caret-inset: calc(var(--spacing) * 3); + --native-select-caret-stroke: 1.5px; + --native-select-end-padding: calc(var(--spacing) * 9); --radius: 0.5rem; --background: oklch(1 0 0); --foreground: oklch(0.145 0 0); @@ -562,6 +566,31 @@ } } +/* Native single-value dropdowns share one inset caret. Padding alone does not + move the browser's arrow. Keep native menus/keyboard behavior and leave + listboxes and controls with their own appearance-none icon untouched. + This rule is outside layers so per-field px-* utilities cannot erase the + space reserved for the caret. currentColor follows every app theme. */ +select:where(:not([multiple]):not(.appearance-none)):where(:not([size]), [size="0"], [size="1"]) { + appearance: none; + padding-inline-end: var(--native-select-end-padding); + background-image: + linear-gradient(45deg, transparent calc(50% - var(--native-select-caret-stroke) / 2), currentColor calc(50% - var(--native-select-caret-stroke) / 2), currentColor calc(50% + var(--native-select-caret-stroke) / 2), transparent calc(50% + var(--native-select-caret-stroke) / 2)), + linear-gradient(135deg, transparent calc(50% - var(--native-select-caret-stroke) / 2), currentColor calc(50% - var(--native-select-caret-stroke) / 2), currentColor calc(50% + var(--native-select-caret-stroke) / 2), transparent calc(50% + var(--native-select-caret-stroke) / 2)); + background-position: right calc(var(--native-select-caret-inset) + var(--native-select-caret-half)) center, right var(--native-select-caret-inset) center; + background-size: var(--native-select-caret-half) var(--native-select-caret-half); + background-repeat: no-repeat; +} +select:where(:not([multiple]):not(.appearance-none)):where(:not([size]), [size="0"], [size="1"]):dir(rtl) { + background-position: left var(--native-select-caret-inset) center, left calc(var(--native-select-caret-inset) + var(--native-select-caret-half)) center; +} +@media (forced-colors: active) { + select:where(:not([multiple]):not(.appearance-none)):where(:not([size]), [size="0"], [size="1"]) { + appearance: auto; + background-image: none; + } +} + @media (pointer: coarse) { button, [role="button"], diff --git a/ui/src/lib/mention-chips.test.ts b/ui/src/lib/mention-chips.test.ts new file mode 100644 index 00000000000..7d138f5b27f --- /dev/null +++ b/ui/src/lib/mention-chips.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it, vi } from "vitest"; +import { mentionChipInlineStyle } from "./mention-chips"; + +const getAgentIcon = vi.hoisted(() => vi.fn()); +vi.mock("./agent-icons", () => ({ getAgentIcon })); + +describe("agent mention icon compatibility", () => { + const node = [["path", { d: "m16 18 6-6-6-6", key: "code" }]]; + + it.each([ + ["static", { iconNode: node }], + ["legacy", { render: () => ({ props: { iconNode: node } }) }], + ["icon-data", { render: () => ({ props: { icon: { name: "code", size: 24, node } } }) }], + ])("renders an agent mention mask from Lucide's %s format", (name, icon) => { + getAgentIcon.mockReturnValue(icon); + const style = mentionChipInlineStyle({ kind: "agent", agentId: "agent", icon: name }); + const mask = (style as Record)["--paperclip-mention-icon-mask"]; + expect(decodeURIComponent(mask)).toContain(''); + }); +}); diff --git a/ui/src/pages/AgentDetail.tsx b/ui/src/pages/AgentDetail.tsx index 4beff8f0cb1..939e482e9eb 100644 --- a/ui/src/pages/AgentDetail.tsx +++ b/ui/src/pages/AgentDetail.tsx @@ -96,7 +96,6 @@ import { Input } from "@/components/ui/input"; import { RunTranscriptView, type TranscriptMode } from "../components/transcript/RunTranscriptView"; import { AgentToolsTab } from "./AgentToolsTab"; import { AgentChannelsPanel } from "../components/chat/AgentChannelsPanel"; -import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled"; import { appendCapped, LIVE_TRANSCRIPT_RENDER_LIMIT, @@ -769,11 +768,10 @@ export function AgentDetail() { const { setBreadcrumbs } = useBreadcrumbs(); const queryClient = useQueryClient(); const navigate = useNavigate(); - const { enabled: chatConnectorsEnabled, loaded: chatConnectorsLoaded } = useChatConnectorsEnabled(); const [actionError, setActionError] = useState(null); const [dismissedLeftAgentIds, setDismissedLeftAgentIds] = useState>(() => new Set()); const activeView: AgentDetailView = urlRunId ? "run-detail" - : urlTab === "channels" && !chatConnectorsEnabled ? "overview" : parseAgentDetailView(urlTab ?? null); + : parseAgentDetailView(urlTab ?? null); const legacyAuditSection = !urlRunId ? agentLegacyAuditSection(urlTab ?? null) : null; const legacyView = urlRunId ? "runs" @@ -963,13 +961,6 @@ export function AgentDetail() { useEffect(() => { if (!agent) return; - if (!urlRunId && urlTab === "channels") { - if (!chatConnectorsLoaded) return; - if (!chatConnectorsEnabled) { - navigate(agentDetailHref(canonicalAgentRef, "overview"), { replace: true }); - return; - } - } if (urlRunId) { if (routeAgentRef !== canonicalAgentRef) { navigate(`/agents/${canonicalAgentRef}/runs/${urlRunId}`, { replace: true }); @@ -982,7 +973,7 @@ export function AgentDetail() { navigate(agentDetailHref(canonicalAgentRef, canonicalTab), { replace: true }); return; } - }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, legacyAuditSection, navigate, chatConnectorsEnabled, chatConnectorsLoaded]); + }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, legacyAuditSection, navigate]); useEffect(() => { if (!agent?.companyId || agent.companyId === selectedCompanyId) return; diff --git a/ui/src/pages/DesignGuide.tsx b/ui/src/pages/DesignGuide.tsx index 4002febed8b..e09b59d8d85 100644 --- a/ui/src/pages/DesignGuide.tsx +++ b/ui/src/pages/DesignGuide.tsx @@ -1,3 +1,4 @@ +import { AgentMailApiKeyField } from "@/features/connections/AgentMailApiKeyField"; import { TaskBrowserFooter } from "@/components/task-side-panel/TaskBrowserFooter"; import { TaskBrowserActivity } from "@/components/task-side-panel/TaskBrowserActivity"; import type { TaskBrowser } from "@paperclipai/shared"; @@ -494,6 +495,7 @@ function ComposerActionsExample() { } export function DesignGuide() { + const [agentmailDemoKey, setAgentmailDemoKey] = useState(""); const [wizardStep, setWizardStep] = useState(0); const [status, setStatus] = useState("todo"); const [priority, setPriority] = useState("medium"); @@ -1028,6 +1030,7 @@ export function DesignGuide() { {/* SELECT */} {/* ============================================================ */}
+

Native single-value dropdowns share an inset, theme-aware caret and reserve room for it in the base stylesheet. Multiple-selection lists and controls with a custom icon keep their own appearance.

setApiKey(e.target.value)} - placeholder="Paste your AgentMail API key" - /> - - Get a key in AgentMail ↗ - -
-
- - +
} + {step < 2 && resumeId === requestId && inboxes.isSuccess && !pendingEndpoint &&

This email setup could not be found. Return to Connectors and start a new connection.

} + {step < 2 && { setup.reset(); setStep(index as 0 | 1); }} />} + {step === 0 &&
{ event.preventDefault(); if (canContinue) connect.mutate(); }}> +
+ + !["terminated", "pending_approval"].includes(a.status))} + onChange={id => { setAgentId(id); setUsername((agents.data?.find(a => a.id === id)?.name ?? "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").slice(0, 64)); }} /> +
+ {!pendingAddress && { setApiKey(value); connect.reset(); }} disabled={busy} />} + {restrictedInbox &&
+

That key only connects {restrictedInbox}. Choose a saved account key or enter one to create a new address.

+ +
} + {lowTrust && !scoped &&
+

This agent needs a work boundary before it can receive email.

+ +
} + {error &&

{error.message}

} +
+ + +
+ } + {step === 1 &&
{ event.preventDefault(); if (canCreate) setup.mutate(); }}> +
+ + {pendingAddress ? <> +

{pendingAddress}

+

This address was created in AgentMail. Finish connecting it to {chosen?.name}{scopedKey ? "." : ", or choose a different address. The original inbox will stay in AgentMail."}

+ {!scopedKey && } + : addressMode === "new" ? <> +
+ { setUsername(event.target.value.toLowerCase()); setup.reset(); }} /> +
- - )} - {step === 2 && ( -
-

AgentMail is connected

-

- Next, give an agent an email address from Permissions. -

-
- + : } + {scopedKey && !pendingAddress && } + {addressError && } + {checkingNewAddress && !addressError &&

+ {addressCheck.checking ? "Checking address…" : addressCheck.error ? `Could not check this address. ${addressCheck.error}` + : addressCheck.result?.status === "unknown" ? "AgentMail confirms availability when you create the address." : null} +

} + {suggestions.length > 0 &&
+ Try: + {suggestions.map(name => )} +
} + {!scopedKey && !pendingAddress && } +
+ + +

How it Works

+ Incoming email creates tasks for {chosen?.name}. Replies stay in the same task. +
+
+
+ Advanced options +
+ {addressMode === "new" && } +
+ +
-
- )} - {step === 3 && ( - <> -
-

- Who should handle this inbox? -

-

- Incoming email will create tasks assigned to this agent. -

- - - !["terminated", "pending_approval"].includes(a.status), - ) - .map((a) => ({ - key: a.id, - value: a.id, - label: a.name, - icon: a.icon, - })), - }, - ]} - onValueChange={(id, option) => { - setAgentId(id); - setUsername( - option.label - .toLowerCase() - .replace(/[^a-z0-9._-]+/g, "-") - .slice(0, 64), - ); - }} - renderValue={(option) => - option && ( - - - - - - - {option.label} - - ) - } - /> -

- Activating this inbox also adds the agent to this connection’s - allowed agents. -

-
- {trustNotice} - - )} - {step === 4 && ( - <> -
-

- Choose {chosen?.name}’s email address -

- - {addressMode === "new" ? ( -
- -
- setUsername(e.target.value.toLowerCase())} - /> - - @{domain} - -
-
- ) : ( -
- - -
- )} -
- - Advanced options - -
- {addressMode === "new" && ( - <> - - - - Set up a custom domain in AgentMail ↗ - - - )} - - -
-
-
- - )} - {step === 5 && ( - <> - - {trustNotice} -
-

- Ready to start receiving email? -

-

{address}

-

- Assigned to {chosen?.name} ·{" "} - {mode === "websocket" ? "Live connection" : "Signed webhook"} -

-

- New conversations create tasks. Replies stay in the same task. - Task comments stay internal. -

-
- - )} - {step === 6 && ( -
-

- - Receiving email for {chosen?.name} -

-

{setup.data?.address}

- - -
- )} - {step >= 3 && step <= 5 && ( -
- - +
+

{lowTrust && scoped ? "Low-trust review configured" : "Manage which tasks and tools this agent can access."}

+ +
- )} - {error && ( -

- {error.message} -

- )} + + {error &&

{error.message}

} + {inspected.isPending &&

Loading email options…

} +
+ + +
+ } + {step === 2 &&
+

{setup.data?.address}

+

{chosen?.name} can now receive email at this address.

+
+ +
+
} @@ -616,8 +497,7 @@ export function EmailEndpointSetup() { -
- ); +
; } export function EmailConnectionInboxes({ @@ -697,9 +577,11 @@ export function EmailConnectionInboxes({ export function EmailEndpointSettings({ endpointId, companyId, + assignedAgentName, }: { endpointId: string; companyId: string; + assignedAgentName: string; }) { const cache = useQueryClient(); const query = useQuery({ @@ -712,6 +594,10 @@ export function EmailEndpointSettings({ ); const [removed, setRemoved] = useState(false); const [replacementKey, setReplacementKey] = useState(""); + const [reconnectOpen, setReconnectOpen] = useState(false); + useEffect(() => { + if (inbox?.lastError) setReconnectOpen(true); + }, [inbox?.lastError]); const [receiveMode, setReceiveMode] = useState<"websocket" | "webhook" | "">( "", ); @@ -746,83 +632,118 @@ export function EmailEndpointSettings({

); return ( -
-

{inbox.address}

-

- {inbox.status} ·{" "} - {inbox.receiveMode === "websocket" ? "Live connection" : "Webhook"} -

-

- Last mail check: {inbox.lastSyncAt ? new Date(inbox.lastSyncAt).toLocaleString() : "Not checked yet"} -

-

- Each email conversation is a task. Task comments stay internal; use - Email reply to send. -

- {inbox.lastError && ( -

- {inbox.lastError} +

+
+

{assignedAgentName}’s email address

+
+

+ {inbox.address ? ( + + {inbox.address} + + ) : "Email inbox"} +

+ {inbox.address && ( + + View inbox + )} +
+ {inbox.status === "active" && inbox.address && ( +

+ Send an email to this address to start a task with {assignedAgentName}. +

+ )} +
+ + +

How it Works

+

+ Incoming email creates tasks for {assignedAgentName}. Replies stay in the same task. + Task comments stay internal; use Email reply to send an email.

- )} -
- - -
-
- - setReplacementKey(e.target.value)} - /> - - - -
- {reconnect.error && ( -

- {reconnect.error.message} -

- )} - {control.error && ( -

- {control.error.message} -

- )} +
+ +
+
+
+

Receiving email

+ {(inbox.status !== "active" || inbox.lastError) && ( + + )} +
+ {["active", "paused"].includes(inbox.status) && ( + + )} +
+ {inbox.status === "paused" && ( +

Receiving is paused. Resume to receive new email.

+ )} +
+
+
Receiving mode
+
{inbox.receiveMode === "websocket" ? "Live connection" : "Webhook"}
+
+
+
Last mail check
+
{inbox.lastSyncAt ? formatDateTime(inbox.lastSyncAt) : "Not checked yet"}
+
+
+ {inbox.lastError &&

{inbox.lastError}

} + {control.error && control.variables !== "remove" && ( +

{control.error.message}

+ )} +
+ +
setReconnectOpen(event.currentTarget.open)} className="border-t border-border pt-5"> + Reconnect inbox +
+

+ Replace the API key or change how this inbox receives email. The email address and task history stay the same. +

+ +
+ + +
+ {reconnect.error &&

{reconnect.error.message}

} + {reconnect.isSuccess &&

Inbox reconnected.

} +
+ +
+
+
+ +
+
+
+

Disconnect inbox

+

Stop receiving email in Paperclip. The inbox stays in AgentMail.

+
+ +
+ {control.error && control.variables === "remove" && ( +

{control.error.message}

+ )} +
); } diff --git a/ui/storybook/stories/agentmail-onboarding.stories.tsx b/ui/storybook/stories/agentmail-onboarding.stories.tsx index 4e50ecf15a4..30607a45286 100644 --- a/ui/storybook/stories/agentmail-onboarding.stories.tsx +++ b/ui/storybook/stories/agentmail-onboarding.stories.tsx @@ -1,1283 +1,212 @@ -import { useMemo, useState, type ReactNode } from "react"; +import { useEffect, useState } from "react"; import type { Meta, StoryObj } from "@storybook/react-vite"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { - AlertTriangle, - ArrowLeft, - ArrowRight, - Check, - ChevronRight, - Copy, - Mail, - Plus, - ShieldCheck, -} from "lucide-react"; -import { expect, userEvent, within } from "storybook/test"; -import { AccessStep } from "@/features/connections/ConnectionSetupFlow"; -import { ConnectorCard } from "@/pages/apps/Browse"; -import { AppLogo } from "@/pages/apps/AppLogo"; -import { Button } from "@/components/ui/button"; -import { SearchableSelect } from "@/components/SearchableSelect"; -import { AgentIcon } from "@/components/AgentIconPicker"; -import { Avatar, AvatarFallback } from "@/components/ui/avatar"; -import type { AgentPermissions } from "@paperclipai/shared"; -import { TrustPresetSection } from "@/components/TrustPresetSection"; -import { - buildPermissionsForTrustPreset, - getTrustPreset, - getLowTrustBoundary, - lowTrustBoundaryHasScope, - setSingleLowTrustBoundaryTarget, -} from "@/lib/trust-policy-ui"; -import { - Dialog, - DialogContent, - DialogHeader, - DialogTitle, - DialogDescription, - DialogFooter, -} from "@/components/ui/dialog"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { RadioCardGroup } from "@/components/ui/radio-card"; -import { queryKeys } from "@/lib/queryKeys"; -import { cn } from "@/lib/utils"; +import { expect, userEvent, waitFor, within } from "storybook/test"; +import { EmailEndpointSetup } from "@/pages/apps/chat/EmailEndpointSetup"; +import { ChatSetupSidebar } from "@/components/chat/ChatSetupNavigation"; +import { ChatSetupSidebarProvider } from "@/context/ChatSetupSidebarContext"; +import { useCompany } from "@/context/CompanyContext"; +import { useLocation, useNavigate } from "@/lib/router"; import { storybookAgents } from "../fixtures/paperclipData"; -// An interactive design proposal. State is local: no credentials or inboxes are created. -type Screen = - | "catalog" - | "access" - | "key" - | "connected" - | "permissions" - | "agent" - | "address" - | "review" - | "ready"; const COMPANY = "company-storybook"; -const agents = storybookAgents.map((agent, i) => ({ - ...agent, - name: ["Support", "Operations", "Research"][i] ?? agent.name, +const CONNECTION = "agentmail-storybook-account"; +const OTHER_ACCOUNT = "agentmail-storybook-organization"; +const ADDRESS_TAKEN = "This email address is already in use. Choose a different address."; +const agents = storybookAgents.map((agent, index) => ({ + ...agent, name: ["Ralph", "Support", "Research"][index] ?? agent.name, + permissions: {}, })); -const selectClass = - "w-full rounded-md border border-input bg-background px-3 py-2 text-sm"; -const connectionSteps = ["Access", "API key", "Connected"]; -const addressSteps = ["Agent", "Email address", "Review"]; -function NumberedSteps({ - labels, - current, - onBack, -}: { - labels: string[]; - current: number; - onBack: (step: number) => void; -}) { - return ( - - ); -} -function Fact({ label, children }: { label: string; children: ReactNode }) { - return ( -
-
{label}
-
{children}
+// Render the production setup. Only the API is simulated; no real keys or inboxes. +function AgentMailJourney({ savedConnection = true }: { savedConnection?: boolean }) { + const navigate = useNavigate(); + const { pathname } = useLocation(); + const { selectedCompanyId } = useCompany(); + const [ready, setReady] = useState(false); + useEffect(() => { + if (ready) return; + navigate(`/apps/chat/connect?provider=agentmail${savedConnection ? `&connectionId=${CONNECTION}` : ""}`, { replace: true }); + setReady(true); + }, [navigate, savedConnection, ready]); + if (!ready || !selectedCompanyId) return null; + if (!pathname.endsWith("/apps/chat/connect")) return
Setup complete.
; + return +
+
+
- ); -} -function AgentMailJourney({ - initial = "catalog", - existing = false, - advanced = false, - invalidKey = false, - senderStatus = "anyone", - trustDefault = "standard", - policyUnknown = false, -}: { - initial?: Screen; - existing?: boolean; - advanced?: boolean; - invalidKey?: boolean; - senderStatus?: "managed" | "anyone"; - trustDefault?: "standard" | "low_trust_review" | "unscoped"; - policyUnknown?: boolean; -}) { - const client = useMemo(() => { - const queryClient = new QueryClient({ - defaultOptions: { queries: { staleTime: Infinity, retry: false } }, - }); - queryClient.setQueryData(queryKeys.agents.list(COMPANY), agents); - return queryClient; - }, []); - const initialPermissions = () => - trustDefault === "standard" - ? buildPermissionsForTrustPreset({}, "standard") - : trustDefault === "unscoped" - ? buildPermissionsForTrustPreset({}, "low_trust_review") - : setSingleLowTrustBoundaryTarget( - buildPermissionsForTrustPreset({}, "low_trust_review"), - COMPANY, - { type: "project", id: "email-work" }, - ); - const [permissions, setPermissions] = useState< - Record> - >(() => - Object.fromEntries(agents.map((agent) => [agent.id, initialPermissions()])), - ); - const [trustDialog, setTrustDialog] = useState(false); - const [draftPermissions, setDraftPermissions] = useState< - Partial - >({}); - const [screen, setScreen] = useState(initial); - const [connected, setConnected] = useState( - !["catalog", "access", "key"].includes(initial), - ); - const [humanAccess, setHumanAccess] = useState< - "user" | "organization" | "agent" - >("user"); - const [agentAccess, setAgentAccess] = useState<"specific" | "all">( - "specific", - ); - const [selectedAgents, setSelectedAgents] = useState( - new Set([agents[0]!.id]), - ); - const [apiKey, setApiKey] = useState(""); - const [error, setError] = useState( - invalidKey - ? "This key couldn’t be verified. Check that it’s an active AgentMail API key and try again." - : "", - ); - const [agentId, setAgentId] = useState(agents[0]!.id); - const [addressMode, setAddressMode] = useState(existing ? "existing" : "new"); - const [username, setUsername] = useState("support"); - const [domain, setDomain] = useState("agentmail.to"); - const [existingAddress, setExistingAddress] = useState( - "support-team@agentmail.to", - ); - const [receiveMode, setReceiveMode] = useState("websocket"); - const [copied, setCopied] = useState(false); - const [hasInbox, setHasInbox] = useState(initial === "ready"); - const chosenAgent = agents.find((agent) => agent.id === agentId) ?? agents[0]; - const [addedAgentName, setAddedAgentName] = useState(null); - const address = - addressMode === "existing" ? existingAddress : `${username}@${domain}`; - const wizard = ["agent", "address", "review"].includes(screen); - const agentPermissions = permissions[agentId]; - const lowTrust = getTrustPreset(agentPermissions) === "low_trust_review"; - const scoped = lowTrustBoundaryHasScope( - getLowTrustBoundary(agentPermissions), - ); - const openTrust = () => { - setDraftPermissions(agentPermissions ?? {}); - setTrustDialog(true); - }; - const senderSummary = policyUnknown - ? "Not verified" - : senderStatus === "anyone" - ? "Unrestricted" - : "Managed in AgentMail"; - const canActivate = !lowTrust || scoped; - const trustNotice = ( -
-
- {lowTrust && scoped ? ( - - ) : ( - - )} -
-

- {lowTrust - ? scoped - ? "Low-trust review configured" - : "Low trust needs a work boundary" - : `${chosenAgent?.name} is not a low-trust agent`} -

-

- {lowTrust - ? scoped - ? "Email tasks must stay inside this agent’s configured work boundary. Output is quarantined for trusted review." - : "Choose a project or task boundary before activating email." - : "Email can contain malicious instructions. We recommend Low-trust review to limit the agent’s access to Paperclip work."} -

-
-
- -
- ); - const inboxNotice = ( -
-
- {senderStatus === "managed" && !policyUnknown ? ( - - ) : ( - - )} -
-

- {policyUnknown - ? "Sender restrictions haven’t been verified" - : senderStatus === "anyone" - ? "Anyone can email this agent" - : "Sender restrictions are managed in AgentMail"} -

-

- {senderStatus === "anyone" || policyUnknown - ? "Unrestricted email can create tasks and trigger agent work. Set up an allowlist in AgentMail to limit who can contact this inbox." - : "Review your inbox’s allowlists and blocklists in AgentMail. Allowed email can still contain malicious instructions."} -

-

- AgentMail controls new messages and replies separately. Check both - lists. -

-
-
- -
- ); - const humanLabel = - humanAccess === "organization" ? "Any human in the organization" : "Just me"; - const agentLabel = - agentAccess === "all" - ? "Any agent" - : agents - .filter((agent) => selectedAgents.has(agent.id)) - .map((agent) => agent.name) - .join(", "); - const validAddress = - addressMode === "existing" - ? !!existingAddress - : /^[a-z0-9][a-z0-9._-]*$/.test(username); - const go = (next: Screen) => { - setError(""); - setScreen(next); - }; - const beginAddress = () => { - if (chosenAgent) { - setAgentId(chosenAgent.id); - setUsername(chosenAgent.name.toLowerCase()); - } - go("agent"); - }; - const footer = ( - back: Screen, - next: Screen, - label = "Continue", - disabled = false, - ) => ( -
- - -
- ); - - return ( - -
-
- - Design preview · sample data · nothing is connected or sent - - -
-
- - - {screen === "catalog" ? ( -
-
-

Apps

-

- Connect the tools your people and agents use. -

-
-
- go(connected ? "permissions" : "access")} - onRequestRemove={() => {}} - chatConnectorsEnabled - /> -
-
- ) : screen === "permissions" ? ( -
-
- -
-

AgentMail

-

- - Connected · Company email -

-
-
-
- Permissions -
-
-
- -
-
-

- {hasInbox - ? "Give another agent an inbox" - : "Your connection is ready. Give an agent an inbox."} -

-

- Each agent gets an address. Each email conversation becomes - a task. -

-
- -
- {hasInbox && ( -
-

Email addresses

-
-
-

{address}

-

- {chosenAgent?.name} ·{" "} - {receiveMode === "websocket" - ? "Live connection" - : "Webhook"} -

-
- - - Receiving email - -
-
- {senderSummary} - - {lowTrust ? "Low-trust review" : "Standard"} - -
- {inboxNotice} - {!lowTrust && trustNotice} -
- )} -
-
-

Connection access

- -
-
- {humanLabel} - - {agentLabel || "No agents selected"} - - - AgentMail API key · Saved in vault - -
-
-
- ) : ( -
-
-
-
- -

- {wizard - ? "Give an agent an email address" - : screen === "ready" - ? "Your agent’s email is ready" - : "Connect AgentMail"} -

-
-

- {wizard - ? "Using your saved AgentMail connection." - : screen === "ready" - ? "New email conversations will become tasks for your agent." - : "Connect once, then assign email addresses to your agents."} -

-
- -
- {wizard ? ( - - go((["agent", "address", "review"] as Screen[])[i]!) - } - /> - ) : ( - screen !== "ready" && ( - go(i === 0 ? "access" : "key")} - /> - ) - )} - - {screen === "access" && ( - go(connected ? "permissions" : "catalog")} - onContinue={() => go(connected ? "permissions" : "key")} - /> - )} - {screen === "key" && ( -
{ - e.preventDefault(); - if (!apiKey.trim()) { - setError("Enter an API key to continue."); - return; - } - if (apiKey.trim() === "invalid") { - setError( - "This key couldn’t be verified. Check that it’s an active AgentMail API key and try again.", - ); - return; - } - setApiKey(""); - setConnected(true); - go("connected"); - }} - > -
-
-

- Add your AgentMail API key -

-
-
- - { - setApiKey(e.target.value); - setError(""); - }} - aria-invalid={!!error} - aria-describedby={ - error ? "preview-key-error" : undefined - } - /> - {error && ( - - )} -
- - Get a key in AgentMail ↗ - -
-
- - -
-
- )} - {screen === "connected" && ( -
-
- -
-

- AgentMail is connected -

-

- Your credential is saved. Next, give an agent an email - address from Permissions. -

-
-
-
- {humanLabel} - {agentLabel} - None assigned yet -
-
- -
-
- )} - {screen === "agent" && ( - <> -
-
-

- Who should handle this inbox? -

-

- Incoming email will create tasks assigned to this agent. -

-
-
- - ({ - key: agent.id, - value: agent.id, - label: agent.name, - icon: agent.icon, - })), - }, - ]} - onValueChange={(value, option) => { - setAgentId(value); - setUsername(option.label.toLowerCase()); - if ( - agentAccess !== "all" && - !selectedAgents.has(value) - ) { - setSelectedAgents( - (current) => new Set([...current, value]), - ); - setAddedAgentName(option.label); - } else setAddedAgentName(null); - }} - renderValue={(option) => - option && ( - - - - - - - {option.label} - - ) - } - renderOption={(option) => ( - - - - - - - {option.label} - - )} - /> -
-

- {addedAgentName - ? `${addedAgentName} added to this connection’s allowed agents.` - : "Choosing an agent also gives them access to this connection."} -

-
- {trustNotice} - {footer( - "permissions", - "address", - "Continue", - !chosenAgent || (lowTrust && !scoped), - )} - - )} - {screen === "address" && ( - <> -
-
-

- Choose {chosenAgent?.name}’s email address -

-

- Create an address or attach an inbox already in - AgentMail. -

-
- - {addressMode === "new" ? ( -
- -
- - setUsername(e.target.value.toLowerCase()) - } - className="min-w-0 border-0 shadow-none focus-visible:ring-0" - /> - - @{domain} - -
-

- Suggested from the agent’s name. You can change it. -

-
- ) : ( -
- - -

- Only unassigned inboxes accessible to this credential - are available. -

-
- )} -
- - Advanced options - -
- {addressMode === "new" && ( -
- - - - Set up another domain in AgentMail ↗ - -
- )} - - {receiveMode === "webhook" && ( -

- Paperclip registers and verifies the webhook at your - server’s public address. This preview assumes HTTPS - is configured. -

- )} -
-
-
- {inboxNotice} - {footer( - "agent", - "review", - "Review email address", - !validAddress, - )} - - )} - {screen === "review" && ( - <> - {inboxNotice} - {trustNotice} -
-
-

- Ready to start receiving email? -

-

- {addressMode === "new" - ? "We’ll create this inbox in AgentMail and assign it to your agent." - : "We’ll attach this inbox to your agent. Existing mail stays in AgentMail."} -

-
-
- -

- {address} -

-
-
- {chosenAgent?.name} - AgentMail · Company email - {senderSummary} - - - {lowTrust ? "Low-trust review" : "Standard"} - - - {receiveMode === "websocket" - ? "Live connection" - : "Signed webhook"} - -
-
-

- New conversations create tasks. Replies stay in the same - task. -

-

- Task comments stay internal. Sending email is an - explicit action. -

-

- Receiving starts now. Older mail is added only when - needed for a new reply. -

-
-
-
- - -
- - )} - {screen === "ready" && ( -
-
- - Receiving email for {chosenAgent?.name} -
- {inboxNotice} -

- New email: {senderSummary} · Agent trust:{" "} - {lowTrust ? "Low-trust review" : "Standard"} -

-
-

{address}

- -
-
-

- Try it with a test email -

-

- Send a message from an allowed sender. A new task will - appear for {chosenAgent?.name}, ready for an explicit - email reply. -

-

- This is a design preview; this sample address hasn’t been - created. -

-
- -
- )} -
- )} -
-
- - - - Trust settings · {chosenAgent?.name} - - Changes apply to all of this agent’s work. Use a dedicated email - agent if its other tasks need broader access. - - - -

- Low trust limits Paperclip access; it does not sandbox the runtime. - Review filesystem, tool, and secret access separately. -

- - - - -
-
-
- ); +
; } +type Scenario = { noSavedKeys?: boolean; scopedKey?: boolean; missingBoundary?: boolean; denySetup?: boolean; initialTaken?: boolean; noCustomDomain?: boolean; checkFailed?: boolean }; const meta = { title: "Connections/AgentMail setup", component: AgentMailJourney, parameters: { layout: "fullscreen" }, - args: { initial: "catalog" }, + args: { savedConnection: true }, + beforeEach(context) { + const scenario = (context.parameters.agentmailScenario ?? {}) as Scenario; + sessionStorage.removeItem(`paperclip.agentmail-setup:${COMPANY}:${CONNECTION}:choose`); + sessionStorage.removeItem(`paperclip.agentmail-setup:${COMPANY}:new:choose`); + const fixtureAgents = agents.map(agent => ({ ...agent, permissions: scenario.missingBoundary ? { trustPreset: "low_trust_review" } : {} })); + const original = window.fetch; + window.fetch = async (input, init) => { + const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, location.origin); + const method = init?.method ?? "GET"; + const body = init?.body ? JSON.parse(String(init.body)) : {}; + if (url.pathname === `/api/companies/${COMPANY}/agents`) return Response.json(fixtureAgents); + if (url.pathname === `/api/companies/${COMPANY}/tools/connections`) return Response.json({ connections: [{ + id: OTHER_ACCOUNT, name: "AgentMail", status: "active", enabled: true, + config: { provider: "agentmail", emailCredential: true }, createdAt: "2026-09-30T14:00:00Z", + }] }); + const agent = fixtureAgents.find(agent => url.pathname === `/api/agents/${agent.id}` || url.pathname === `/api/agents/${agent.id}/permissions`); + if (agent) { + if (method === "PATCH") agent.permissions = body; + return Response.json({ ...agent, access: { canAssignTasks: false } }); + } + if (url.pathname.endsWith("/email/connections") && method === "GET") return Response.json(scenario.noSavedKeys ? [] : [ + { id: OTHER_ACCOUNT, label: "AgentMail account key", scope: "organization", createdAt: "2026-09-30T14:00:00Z" }, + { id: CONNECTION, label: scenario.scopedKey ? "AgentMail inbox key · support@agentmail.to" : "AgentMail account key", + scope: scenario.scopedKey ? "inbox" : "organization", createdAt: "2026-10-01T14:00:00Z" }, + ]); + if (url.pathname.endsWith("/email/inspect") && body.apiKey === "invalid-key") + return Response.json({ error: "AgentMail rejected the API key. Check it and try again." }, { status: 422 }); + if (url.pathname.endsWith("/email/connections") && method === "POST") { + if (body.apiKey === "invalid-key") return Response.json({ error: "AgentMail rejected the API key. Check it and try again." }, { status: 422 }); + if (body.grantKind !== "organization" || body.allAgents !== false || body.agentIds.length !== 1) { + return Response.json({ error: "Unexpected access defaults in preview." }, { status: 422 }); + } + return Response.json({ id: CONNECTION }, { status: 201 }); + } + if (url.pathname.endsWith("/email/inspect") || [CONNECTION, OTHER_ACCOUNT].some(id => url.pathname.endsWith(`/email/connections/${id}/inspect`))) { + const restricted = scenario.scopedKey && url.pathname.includes(CONNECTION); + return Response.json({ + scope: { scope_type: restricted ? "inbox" : "organization" }, + inboxes: restricted ? [{ inbox_id: "support@agentmail.to" }] : [{ inbox_id: "support@agentmail.to" }, { inbox_id: "help@paperclip.example" }], + domains: restricted || scenario.noCustomDomain ? [] : [{ domain_id: "custom-domain", domain: "paperclip.example", status: "VERIFIED" }], + }); + } + if ([CONNECTION, OTHER_ACCOUNT].some(id => url.pathname.endsWith(`/email/connections/${id}/check-address`))) { + if (scenario.checkFailed) return Response.json({ error: "AgentMail is rate limiting requests. Wait a moment, then try again." }, { status: 429 }); + return Response.json({ address: `${body.username}@${body.domain}`, + status: body.username === "taken" || (scenario.initialTaken && body.username === "ralph") ? "taken" : "unknown" }); + } + if (url.pathname.endsWith("/email/inboxes")) { + if (method === "GET") return Response.json([]); + if (body.username === "taken") return Response.json({ error: ADDRESS_TAKEN, code: "agentmail_address_taken", + details: { field: "username", providerStatus: 403, operation: "create_inbox" } }, { status: 409 }); + if (scenario.denySetup) return Response.json({ error: "AgentMail did not allow Paperclip to create the email address. Check your API key permissions and AgentMail account limits, then try again." }, { status: 422 }); + return Response.json({ id: body.idempotencyKey, connectionId: "storybook-inbox-connection", companyId: COMPANY, + assignedAgentId: body.assignedAgentId, address: body.inboxId ?? `${body.username}@${body.domain}`, status: "active", receiveMode: body.receiveMode }, { status: 201 }); + } + return original(input, init); + }; + return () => { window.fetch = original; }; + }, } satisfies Meta; export default meta; type Story = StoryObj; -export const Walkthrough: Story = { name: "Start here · Full walkthrough" }; -export const CatalogCard: Story = { name: "01 · Apps catalog card" }; -export const ConnectionAccess: Story = { - name: "02 · Humans and agents", - args: { initial: "access" }, + +const chooseAgent: NonNullable = async ({ canvasElement }) => { + const canvas = within(canvasElement); + const picker = await canvas.findByLabelText("Agent"); + await waitFor(() => expect(picker).toBeEnabled()); + await userEvent.click(picker); + const page = within(canvasElement.ownerDocument.body); + await userEvent.type(page.getByPlaceholderText("Filter agents"), "Ralph"); + await userEvent.click(await page.findByRole("button", { name: "Select Ralph" })); }; -export const ApiKey: Story = { name: "03 · API key", args: { initial: "key" } }; -export const ConnectionReady: Story = { - name: "04 · Connection ready", - args: { initial: "connected" }, +const chooseAddress: NonNullable = async context => { + await chooseAgent(context); + const canvas = within(context.canvasElement); + await waitFor(() => expect(canvas.getByRole("button", { name: "Continue" })).toBeEnabled()); + await userEvent.click(canvas.getByRole("button", { name: "Continue" })); + await expect(await canvas.findByLabelText("Ralph’s email address")).toHaveValue("ralph"); }; -export const Permissions: Story = { - name: "05 · Permissions", - args: { initial: "permissions" }, -}; -export const ChooseAgent: Story = { - name: "06 · Choose an agent", - args: { initial: "agent" }, -}; -export const ChooseAddress: Story = { - name: "07 · Choose an address", - args: { initial: "address" }, -}; -export const ExistingInbox: Story = { - name: "07b · Attach existing inbox", - args: { initial: "address", existing: true }, -}; -export const AdvancedOptions: Story = { - name: "07c · Advanced options", - args: { initial: "address", advanced: true }, -}; -export const Review: Story = { - name: "08 · Review and activate", - args: { initial: "review" }, -}; -export const Ready: Story = { - name: "09 · Email address ready", - args: { initial: "ready" }, -}; -export const InvalidKey: Story = { - name: "Error · Invalid API key", - args: { initial: "key", invalidKey: true }, -}; -export const TestedWalkthrough: Story = { - name: "Verification · Complete journey", - play: async ({ canvasElement }) => { - const canvas = within(canvasElement); - await userEvent.click( - canvas.getByRole("button", { name: "Connect AgentMail" }), - ); - await userEvent.click(canvas.getByRole("button", { name: "Continue" })); - await userEvent.type( - canvas.getByLabelText("API key", { exact: true }), - "sample-preview-key", - ); - await userEvent.click( - canvas.getByRole("button", { name: "Connect AgentMail" }), - ); - await userEvent.click( - canvas.getByRole("button", { name: "Open permissions" }), - ); - await userEvent.click( - canvas.getByRole("button", { name: "Give an agent an email address" }), - ); - await userEvent.click(canvas.getByRole("button", { name: "Continue" })); - await userEvent.click( - canvas.getByRole("button", { name: "Review email address" }), - ); - await userEvent.click( - canvas.getByRole("button", { name: "Create email address" }), - ); - await expect( - canvas.getByRole("heading", { name: "Your agent’s email is ready" }), - ).toBeVisible(); - await userEvent.click( - canvas.getByRole("button", { name: "Back to permissions" }), - ); - await expect( - canvas.getByText("Receiving email", { exact: true }), - ).toBeVisible(); - }, +const takenAddress: NonNullable = async context => { + await chooseAddress(context); + const canvas = within(context.canvasElement); + await userEvent.clear(canvas.getByLabelText("Ralph’s email address")); + await userEvent.type(canvas.getByLabelText("Ralph’s email address"), "taken"); + await expect(await canvas.findByRole("alert")).toHaveTextContent(ADDRESS_TAKEN); + await expect(canvas.getByLabelText("Ralph’s email address")).toHaveAttribute("aria-invalid", "true"); }; -export const SearchAllAgents: Story = { - name: "06b · Search and grant agent access", - args: { initial: "agent" }, - play: async ({ canvasElement }) => { - const canvas = within(canvasElement); - await userEvent.click(canvas.getByRole("combobox")); - const page = within(canvasElement.ownerDocument.body); - await userEvent.type( - page.getByPlaceholderText("Search all agents…"), - "Research", - ); - await userEvent.click(page.getByRole("option", { name: "Research" })); - await expect(canvas.getByRole("status")).toHaveTextContent( - "Research added to this connection’s allowed agents.", - ); - await userEvent.click(canvas.getByRole("button", { name: "Cancel" })); - await expect(canvas.getByText("Support, Research")).toBeVisible(); - }, -}; - -export const PublicInboxWarning: Story = { - name: "Controls · Public inbox warning", - args: { initial: "review", senderStatus: "anyone" }, -}; -export const LowTrustAgent: Story = { - name: "Controls · Low-trust agent", - args: { initial: "agent", trustDefault: "low_trust_review" }, -}; -export const MissingTrustBoundary: Story = { - name: "Controls · Low trust needs a boundary", - args: { initial: "agent", trustDefault: "unscoped" }, -}; -export const UnknownSenderPolicy: Story = { - name: "Controls · Could not verify restrictions", - args: { initial: "review", existing: true, policyUnknown: true }, -}; -export const ManagedSenderPolicy: Story = { - name: "Controls · Managed in AgentMail", - args: { - initial: "review", - senderStatus: "managed", - trustDefault: "low_trust_review", - }, -}; -export const VerifySenderControls: Story = { - name: "Verification · Email safety guidance", - args: { initial: "review" }, - play: async ({ canvasElement }) => { - const canvas = within(canvasElement); - await expect(canvas.getByText("Anyone can email this agent")).toBeVisible(); - await expect( - canvas.getByRole("link", { name: "Set up allowlists ↗" }), - ).toHaveAttribute( - "href", - "https://docs.agentmail.to/knowledge-base/allowlists-blocklists", - ); - await expect( - canvas.getByText("Support is not a low-trust agent"), - ).toBeVisible(); - await userEvent.click( - canvas.getByRole("button", { name: "Configure low trust" }), - ); - const page = within(canvasElement.ownerDocument.body); - await expect(page.getByRole("dialog")).toBeVisible(); - await expect( - page.getByText( - "Changes apply to all of this agent’s work. Use a dedicated email agent if its other tasks need broader access.", - ), - ).toBeVisible(); - const dialog = within(page.getByRole("dialog")); - await userEvent.selectOptions( - dialog.getAllByRole("combobox")[0]!, - "low_trust_review", - ); - await expect( - dialog.getByRole("button", { name: "Save trust settings" }), - ).toBeDisabled(); - await userEvent.selectOptions( - dialog.getAllByRole("combobox")[2]!, - "email-work", - ); - await userEvent.click( - dialog.getByRole("button", { name: "Save trust settings" }), - ); - await expect(canvas.getByText("Low-trust review configured")).toBeVisible(); - await expect(canvas.getByText("Anyone can email this agent")).toBeVisible(); - }, -}; +export const Walkthrough: Story = { name: "Start here · Pick agent, pick email" }; +export const ChooseAgent: Story = { name: "01 · Pick an agent" }; +export const ChooseAddress: Story = { name: "02 · Pick their email", play: chooseAddress }; +export const AddressTaken: Story = { name: "Error · Email address already in use", play: takenAddress }; +export const InitialAddressTaken: Story = { name: "Initial name taken · Click an alternative", parameters: { agentmailScenario: { initialTaken: true } }, play: async context => { + await chooseAddress(context); + const canvas = within(context.canvasElement); + await expect(await canvas.findByRole("alert")).toHaveTextContent(ADDRESS_TAKEN); + await expect(canvas.getByRole("button", { name: "ralph-agent@paperclip.example" })).toBeVisible(); +} }; +export const SharedDomain: Story = { name: "No custom domain · Shared AgentMail domain", parameters: { agentmailScenario: { noCustomDomain: true } }, play: chooseAddress }; +export const LookupUnavailable: Story = { name: "Address lookup temporarily unavailable", parameters: { agentmailScenario: { checkFailed: true } }, play: chooseAddress }; +export const ExistingInbox: Story = { name: "Use an existing inbox", play: async context => { + await chooseAddress(context); + await userEvent.click(within(context.canvasElement).getByRole("button", { name: "Use an existing inbox" })); +} }; +export const InboxScopedKey: Story = { name: "Inbox-only key · Choose an account key", args: { savedConnection: false }, + parameters: { agentmailScenario: { scopedKey: true } }, play: async context => { + await chooseAgent(context); + const canvas = within(context.canvasElement); + await userEvent.selectOptions(await canvas.findByLabelText("API key"), CONNECTION); + await userEvent.click(canvas.getByRole("button", { name: "Continue" })); + await expect(await canvas.findByText(/That key only connects support@agentmail.to/)).toBeVisible(); + await expect(canvas.queryByLabelText("Ralph’s email address")).not.toBeInTheDocument(); + } }; +export const SwitchScopedAccount: Story = { name: "Inbox-only key · Switch to an editable address", args: { savedConnection: false }, + parameters: { agentmailScenario: { scopedKey: true } }, play: async context => { + await InboxScopedKey.play!(context); + const canvas = within(context.canvasElement); + await userEvent.selectOptions(await canvas.findByLabelText("API key"), OTHER_ACCOUNT); + await userEvent.click(canvas.getByRole("button", { name: "Continue" })); + await waitFor(() => expect(canvas.getByLabelText("Email domain")).toHaveValue("paperclip.example")); + await userEvent.clear(canvas.getByLabelText("Ralph’s email address")); + await userEvent.type(canvas.getByLabelText("Ralph’s email address"), "ralph-mail"); + await expect(canvas.getByLabelText("Ralph’s email address")).toHaveValue("ralph-mail"); + } }; +export const SavedApiKey: Story = { name: "Saved account key · Suggested automatically", args: { savedConnection: false }, play: chooseAddress }; +export const AdvancedOptions: Story = { name: "Advanced · Email settings", play: async context => { + await chooseAddress(context); + await userEvent.click(within(context.canvasElement).getByText("Advanced options")); +} }; +export const MissingTrustBoundary: Story = { name: "Existing low-trust agent · Work boundary required", + parameters: { agentmailScenario: { missingBoundary: true } }, play: chooseAgent }; +export const NewConnection: Story = { name: "First time · API key alongside the agent", args: { savedConnection: false }, parameters: { agentmailScenario: { noSavedKeys: true } } }; +export const InvalidKey: Story = { name: "Error · Invalid API key", args: { savedConnection: false }, parameters: { agentmailScenario: { noSavedKeys: true } }, play: async context => { + await chooseAgent(context); + const canvas = within(context.canvasElement); + await userEvent.type(canvas.getByLabelText("API key"), "invalid-key"); + await userEvent.click(canvas.getByRole("button", { name: "Continue" })); + await expect(await canvas.findByRole("alert")).toHaveTextContent("AgentMail rejected the API key"); +} }; +export const ProviderDenied: Story = { name: "Error · Provider permission denied", parameters: { agentmailScenario: { denySetup: true } }, play: async context => { + await chooseAddress(context); + await waitFor(() => expect(within(context.canvasElement).getByRole("button", { name: "Create email address" })).toBeEnabled()); + await userEvent.click(within(context.canvasElement).getByRole("button", { name: "Create email address" })); + await expect(await within(context.canvasElement).findByRole("alert")).toHaveTextContent("AgentMail did not allow"); +} }; +export const Ready: Story = { name: "Done · Email ready", play: async context => { + await chooseAddress(context); + const canvas = within(context.canvasElement); + await waitFor(() => expect(canvas.getByRole("button", { name: "Create email address" })).toBeEnabled()); + await userEvent.click(canvas.getByRole("button", { name: "Create email address" })); + await expect(await canvas.findByRole("heading", { name: "Your agent’s email is ready" })).toBeVisible(); +} }; +export const Mobile: Story = { name: "Mobile · Pick their email", globals: { viewport: { value: "mobile1", isRotated: false } }, parameters: { waitForViewport: true }, play: chooseAddress }; +export const TestedWalkthrough: Story = { name: "Verification · Correct a taken address and finish", play: async context => { + await takenAddress(context); + const canvas = within(context.canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "taken-agent@paperclip.example" })); + await expect(canvas.getByLabelText("Ralph’s email address")).toHaveValue("taken-agent"); + await expect(canvas.queryByRole("alert")).not.toBeInTheDocument(); + await waitFor(() => expect(canvas.getByRole("button", { name: "Create email address" })).toBeEnabled()); + await userEvent.click(canvas.getByRole("button", { name: "Create email address" })); + await expect(await canvas.findByRole("heading", { name: "Your agent’s email is ready" })).toBeVisible(); + await expect(canvas.getByText("taken-agent@paperclip.example", { exact: true })).toBeVisible(); + await userEvent.click(canvas.getByRole("button", { name: "Done" })); + await expect(await canvas.findByText("Setup complete.")).toBeVisible(); +} }; diff --git a/ui/storybook/stories/agentmail-settings.stories.tsx b/ui/storybook/stories/agentmail-settings.stories.tsx new file mode 100644 index 00000000000..0d22f49ddcb --- /dev/null +++ b/ui/storybook/stories/agentmail-settings.stories.tsx @@ -0,0 +1,81 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { expect, userEvent, within } from "storybook/test"; +import { EmailEndpointSettings } from "@/pages/apps/chat/EmailEndpointSetup"; +import type { EmailEndpointSummary } from "@paperclipai/shared"; + +const COMPANY = "company-storybook"; +const ENDPOINT = "agentmail-settings-preview"; +const meta = { + title: "Connections/AgentMail settings", + component: EmailEndpointSettings, + parameters: { layout: "padded" }, + args: { endpointId: ENDPOINT, companyId: COMPANY, assignedAgentName: "Ralph" }, + beforeEach(context) { + let inbox: EmailEndpointSummary = { + id: ENDPOINT, companyId: COMPANY, connectionId: "preview-account", assignedAgentId: "ralph", + address: "ralph@paperclip.example", status: "active", receiveMode: "websocket", + lastSyncAt: "2026-10-02T12:40:00Z", lastError: null, + ...context.parameters.inbox, + }; + const original = window.fetch; + window.fetch = async (input, init) => { + const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, location.origin); + if (url.pathname === `/api/companies/${COMPANY}/email/inboxes`) return Response.json([inbox]); + if (url.pathname === `/api/email/inboxes/${ENDPOINT}/control`) { + const { action } = JSON.parse(String(init?.body)); + inbox = { ...inbox, status: action === "pause" ? "paused" : action === "remove" ? "archived" : "active" }; + return Response.json(inbox); + } + if (url.pathname === `/api/email/inboxes/${ENDPOINT}/reconnect`) { + const { receiveMode } = JSON.parse(String(init?.body)); + inbox = { ...inbox, status: "active", receiveMode, lastError: null }; + return Response.json(inbox); + } + return original(input, init); + }; + return () => { window.fetch = original; }; + }, +} satisfies Meta; +export default meta; +type Story = StoryObj; + +export const Receiving: Story = { play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + const copyAddress = await canvas.findByRole("button", { name: "Copy email address" }); + await expect(copyAddress).toHaveTextContent("ralph@paperclip.example"); + await expect(canvas.getByRole("link", { name: "View inbox" })).toHaveAttribute( + "href", "https://console.agentmail.to/dashboard/inboxes/ralph%40paperclip.example"); +} }; +export const Paused: Story = { parameters: { inbox: { status: "paused" } }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(await canvas.findByRole("button", { name: "Resume" })).toBeVisible(); + await expect(canvas.queryByText(/Send an email to this address to start a task/)).not.toBeInTheDocument(); +} }; +export const AddressNotAssigned: Story = { parameters: { inbox: { status: "draft", address: null, lastSyncAt: null } }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(await canvas.findByRole("heading", { name: "Email inbox" })).toBeVisible(); + await expect(canvas.queryByRole("button", { name: "Copy email address" })).not.toBeInTheDocument(); + await expect(canvas.queryByRole("link", { name: "View inbox" })).not.toBeInTheDocument(); + await expect(canvas.queryByText(/Send an email to this address to start a task/)).not.toBeInTheDocument(); +} }; +export const NeedsAttention: Story = { parameters: { inbox: { status: "revoked", lastError: "AgentMail rejected the API key. Reconnect this inbox with a valid key." } }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(await canvas.findByText("Access revoked")).toBeVisible(); + await expect(canvas.queryByRole("button", { name: "Resume" })).not.toBeInTheDocument(); + await expect(canvas.getByLabelText("New API key")).toBeVisible(); +} }; +export const Webhook: Story = { parameters: { inbox: { receiveMode: "webhook", lastSyncAt: null } } }; +export const LongAddress: Story = { parameters: { inbox: { address: "ralph-customer-support-and-operations@paperclip.example" } } }; +export const Mobile: Story = { globals: { viewport: { value: "mobile1", isRotated: false } }, parameters: { waitForViewport: true } }; +export const Reconnect: Story = { play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await canvas.findByRole("heading", { name: "ralph@paperclip.example" }); + const disclosure = canvas.getByText("Reconnect inbox", { selector: "summary" }); + await expect(canvas.queryByLabelText("New API key")).not.toBeVisible(); + await userEvent.click(disclosure); + await expect(canvas.getByLabelText("New API key")).toBeVisible(); + await expect(canvas.getByRole("link", { name: /Get an AgentMail API key/ })).toHaveAttribute("href", "https://console.agentmail.to/dashboard/api-keys"); + await userEvent.type(canvas.getByLabelText("New API key"), "storybook-placeholder-key"); + await userEvent.click(canvas.getByRole("button", { name: "Reconnect inbox" })); + await expect(await canvas.findByText("Inbox reconnected.")).toBeVisible(); +} }; diff --git a/ui/storybook/stories/in-feed-connections.stories.tsx b/ui/storybook/stories/in-feed-connections.stories.tsx index 0f0df58c764..455c5c85e3a 100644 --- a/ui/storybook/stories/in-feed-connections.stories.tsx +++ b/ui/storybook/stories/in-feed-connections.stories.tsx @@ -31,7 +31,7 @@ const connection = { createdByAgentId: null, createdByUserId: "user-board", createdAt: new Date("2026-09-07"), updatedAt: new Date("2026-09-07"), } satisfies ToolConnection; -type Scenario = { ai?: boolean; missingAiAccount?: "anthropic" | "openai"; ownerOnly?: boolean; checking?: boolean; count?: number; loading?: boolean; loadError?: boolean; completeError?: boolean; submitting?: boolean; denied?: boolean }; +type Scenario = { email?: boolean; ai?: boolean; missingAiAccount?: "anthropic" | "openai"; ownerOnly?: boolean; checking?: boolean; count?: number; loading?: boolean; loadError?: boolean; completeError?: boolean; submitting?: boolean; denied?: boolean }; const meta: Meta = { title: "Connections/In-task connections", parameters: { layout: "padded" }, @@ -45,7 +45,7 @@ const meta: Meta = { channel.on("unhandledErrorsWhilePlaying", reportPlayError); const original = window.fetch; const scenario = (parameters.connectionScenario ?? {}) as Scenario; - let current = structuredClone(scenario.missingAiAccount ? missingAiInteraction(scenario.missingAiAccount) : scenario.ai ? aiPending : pending); + let current = structuredClone(scenario.email ? emailPending : scenario.missingAiAccount ? missingAiInteraction(scenario.missingAiAccount) : scenario.ai ? aiPending : pending); window.fetch = async (input, init) => { const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, window.location.origin); if (scenario.missingAiAccount) { @@ -65,6 +65,14 @@ const meta: Meta = { apps: CONNECTABLE_APP_DEFINITIONS.filter((app) => ["notion", "github", "posthog", "zapier"].includes(app.slug)), capabilities: { canCreateOrganizationGrant: true, canSetCompanyInstall: true }, }); + if (scenario.email && url.pathname.endsWith("/email/connections") && init?.method === "POST") { + return scenario.completeError + ? Response.json({ error: "This key could not be verified. Check it and try again." }, { status: 422 }) + : Response.json({ id: connection.id }); + } + if (scenario.email && url.pathname.endsWith("/email/inboxes") && init?.method === "POST") { + return Response.json({ connectionId: connection.id }); + } if (scenario.ai && url.pathname.endsWith("/ai-connections") && init?.method === "POST") return scenario.completeError ? Response.json({ error: "This key could not be verified. Check it and try again." }, { status: 422 }) : Response.json({ connectionId: aiAccount.id, grantId: aiAccount.grantId }); @@ -76,12 +84,13 @@ const meta: Meta = { return Response.json({ version: 1, interaction: current, requestedAgentId: pending.payload.requestingAgentId, service: { service: "notion", name: "Notion", state: "available", methods: [] }, ...(scenario.ai ? { aiConnection: { provider: scenario.missingAiAccount ?? "openrouter", method: "api_key", mode: "responsible_user" }, ...(scenario.missingAiAccount ? {} : { aiRepair: { connection: aiAccount, canReconnect: !scenario.ownerOnly } }) } : {}), + ...(scenario.email ? { emailSetup: { credentialConnectionId: null, readyConnectionId: null } } : {}), existingConnections: Array.from({ length: scenario.count ?? 0 }, (_, i) => ({ ...connection, id: `${connection.id.slice(0, -1)}${i}`, name: i ? "Team Notion workspace" : connection.name })), }); } if (scenario.submitting) return new Promise(() => {}); if (scenario.completeError || scenario.denied) return Response.json({ error: scenario.denied ? "You no longer have permission to share this connection." : "Connection has no permitted tools. Review action permissions and try again." }, { status: scenario.denied ? 403 : 409 }); - if (url.pathname.endsWith("decline")) current = { ...declined, id: pending.id }; + if (url.pathname.endsWith("decline")) current = { ...declined, id: pending.id, payload: current.payload }; else if (url.pathname.endsWith("complete")) current = { ...connected, id: pending.id, payload: current.payload }; else if (url.pathname.endsWith("phase")) current = { ...current, payload: { ...current.payload, phase: "needs_retry" } }; return Response.json(current); @@ -118,6 +127,30 @@ const reuse: Story["play"] = async (context) => { await userEvent.click(await within(document.body).findByRole("button", { name: /My Notion workspace/ })); }; +const emailPending: ConnectionIntentInteraction = { + ...pending, + payload: { ...pending.payload, serviceSlug: "agentmail", serviceName: "AgentMail", + serviceLogoUrl: "/brands/agentmail.svg", purpose: "channel" }, +}; +export const AgentMailInline = card(emailPending, { email: true }); +export const AgentMailNarrow: Story = { + ...AgentMailInline, globals: { viewport: { value: "mobile1", isRotated: false } }, +}; +const enterEmailKey: Story["play"] = async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.type(await canvas.findByLabelText("API key"), "storybook-fixture-key"); + await userEvent.click(canvas.getByRole("button", { name: "Connect AgentMail" })); +}; +export const AgentMailConnected: Story = { + ...AgentMailInline, + play: async context => { + await enterEmailKey!(context); + await expect(await within(context.canvasElement).findByText("AgentMail connected")).toBeVisible(); + }, +}; +export const AgentMailInvalidKey: Story = { + ...card(emailPending, { email: true, completeError: true }), play: enterEmailKey, +}; export const NewConnection = card(); export const EligibleReuse = card(pending, { count: 1 }); export const Authorizing = card(authorizing); diff --git a/ui/storybook/stories/primitives-coverage.stories.tsx b/ui/storybook/stories/primitives-coverage.stories.tsx index f305ae9805e..164f97f9361 100644 --- a/ui/storybook/stories/primitives-coverage.stories.tsx +++ b/ui/storybook/stories/primitives-coverage.stories.tsx @@ -84,6 +84,30 @@ export default meta; type Story = StoryObj; +export const NativeSelects: Story = { + render: () => +
+ {(["Default", "Disabled", "Long value", "Right to left"] as const).map(label => )} + + +
+
, +}; + function StoryFrame({ children }: { children: React.ReactNode }) { return (