From 479debe9e31a204f0a16a92205b1a2e1742a404b Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Fri, 2 Oct 2026 07:47:01 -0700
Subject: [PATCH 1/5] build(deps): bump aws-actions/configure-aws-credentials
from 6.2.3 to 6.3.0 (#12966)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Bumps
[aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials)
from 6.2.3 to 6.3.0.
Release notes
Sourced from aws-actions/configure-aws-credentials's
releases .
v6.3.0
6.3.0
(2026-09-11)
Features
v6.2.4
6.2.4
(2026-08-31)
Bug Fixes
account-ids handling, mask proxy as secret in logs (#1943 )
(aa65264 )
skip backoff sleep after the final retryAndBackoff attempt (#1937 )
(3852440 )
Changelog
Sourced from aws-actions/configure-aws-credentials's
changelog .
Changelog
All notable changes to this project will be documented in this file.
See standard-version
for commit guidelines.
6.3.0
(2026-09-11)
Features
6.2.4
(2026-08-31)
Bug Fixes
account-ids handling, mask proxy as secret in logs (#1943 )
(aa65264 )
skip backoff sleep after the final retryAndBackoff attempt (#1937 )
(3852440 )
6.2.3
(2026-07-22)
Bug Fixes
attach git credentials before Tag Major Version push (#1877 )
(9ae780b )
PackedPolicyTooLarge detection in STS tags (#1899 )
(fa8d6a5 )
6.2.2
(2026-07-07)
Miscellaneous Chores
6.2.1
(2026-06-26)
Bug Fixes
enforce allowed-account-ids on all auth paths (#1847 )
(4d281fb )
6.2.0
(2026-06-01)
Features
add additional session tags by default (#1775 )
(e0ba768 )
add more retry logic and better logging (#1764 )
(540d0c1 )
add regex validation to role-session-name (#1765 )
(e354499 )
Allow custom session tags to be passed when assuming a role (#1759 )
(61f50f6 )
expose run id in STS client user-agent (#1774 )
(29d1be3 )
... (truncated)
Commits
e125382
chore(main): release 6.3.0 (#1963 )
438100a
chore: add link to GH security docs (#1962 )
e92ebcc
chore: Update dist
57b8365
feat: add translate-env-variables option (#1961 )
cc49fa7
chore(docs): README main branch guidance (#1960 )
866cb16
chore(deps-dev): bump smol-toml from 1.7.0 to 1.7.2 (#1958 )
6782cb1
chore(deps-dev): bump generate-license-file from 4.2.4 to 4.2.5 (#1951 )
c20509a
chore: Update dist
7a41fc6
chore(deps): bump @aws-sdk/client-sts from 3.1121.0 to
3.1127.0 (#1954 )
726b713
chore(deps-dev): bump @biomejs/biome from 2.5.11 to 2.5.12
(#1957 )
Additional commits viewable in compare
view
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
.github/workflows/cloud-migrator-artifacts.yml | 2 +-
.github/workflows/runner-full-stack-e2e.yml | 2 +-
.github/workflows/runner-protocol-live-evals.yml | 2 +-
.github/workflows/storybook-deploy.yml | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
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 }}
From ec3bacc9bde71c6f8f97126540fc6fc635a8cfab Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Fri, 2 Oct 2026 09:59:34 -0500
Subject: [PATCH 2/5] fix(chat): hide ignored provider information (#14929)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task and agent chats show agent progress and problems that need
attention.
> - Codex also sends account, skill, and unrelated thread notifications.
> - The runner correctly ignores that information but reports it as a
warning.
> - Chat then shows an internal diagnostic as an actionable provider
notice.
> - This pull request keeps the diagnostic in run logs and removes it
from chat.
> - Real provider warnings, errors, and agent replies remain visible.
## Linked Issues or Issue Description
**What happened?**
Chat showed “Received a provider update” and a warning with the text
“ignored
unrelated provider information”. Its details said “User Actionable: Yes”
even
though no user action was needed. Saved conversations retained the same
noise.
**Expected behavior**
Keep ignored provider information in the run log. Do not show it as chat
activity
or a user warning. Preserve real warnings and errors.
**Steps to reproduce**
1. Start a conversation with the native Codex runner.
2. Have the provider send an account update, skill change, or unrelated
thread
notification during the turn.
3. Inspect live chat and reload its saved history.
The regression tests also reproduce the old stored notice without a live
account.
**Paperclip version or commit**
Source implementation on master at `e00d10d5d`. The duplicate search
found no
open PR for this fix. Related prior work: #13109 improved
provider-notice
presentation. #12367 added Codex thread normalization. This change
addresses
the internal information that those paths still projected as chat
warnings.
**Deployment mode**
Native Paperclip Runner with the Codex app-server provider. The issue
was seen
in hosted chat and can be reproduced with local provider fixtures.
## What Changed
- Map ignored unrelated Codex information to `harness.diagnostic` in the
Rust
and TypeScript normalizers.
- Retain a bounded allowlist of redacted provider method and thread/turn
identifiers.
- Use the same Unicode character limit and truncation marker in both
normalizers.
- Share the text redactor through a pure helper. Keep provider
connection code
out of the standalone demo's source closure.
- Omit that diagnostic and the matching legacy notice from live chat.
- Omit the matching legacy notice from saved chat history.
- Test diagnostic retention, account-notification integration, live and
saved
chat, and continued visibility of real warnings, errors, and replies.
- Document the local run-log event and historical display behavior.
## Verification
- Passed: 68 tests in the two affected UI transcript suites.
- Passed: 60 TypeScript tests across provider events, transport
behavior, and
the standalone demo boundary.
- Passed: 13 Rust provider-event tests and the Codex
account-notification
integration test.
- Passed: `pnpm check:token-gates` and Cargo formatting checks.
- Passed: full `pnpm build` and `pnpm -r typecheck`. After the review
fix,
the provider package build, typecheck, and both provider-event suites
passed again.
- Full local `pnpm test:run` failed: 608 files / 10,904 tests passed, 30
server
suites failed, and 104 files / 4,012 tests were skipped. Most failures
were
embedded PostgreSQL startup errors. Two tests timed out in
`heartbeat-comment-wake-batching` and
`workspace-git-snapshot-streaming`.
PostgreSQL startup also failed in `heartbeat-run-event-sequencing` and
`native-finalization-migration`. These server files are unchanged by
this PR.
Isolated heartbeat reruns were skipped locally. The stable test script
stopped
after this general-server group, so later groups did not run locally.
- The original review thread is resolved. Greptile is 5/5 on current
head
`683dab7cce57187c57e84c83f5e9da4ad75c9c04`.
- All current-head CI gates passed, including the full
server/chat/workspace
test matrix, Rust and TypeScript runner suites, browser E2E, build,
typecheck,
and release canary. [CI
run](https://github.com/paperclipai/paperclip/actions/runs/37021330663).
- Replay the exact old warning in either transcript adapter. It must
produce
no chat row. A genuine provider warning or error must still produce a
row.
## Risks
- Low risk. The display filter matches one diagnostic code or the
complete
legacy warning shape. Other provider notices remain visible.
- New ignored-information events use the existing harness-diagnostic
event
type. They retain diagnostic evidence without original account payloads.
- No database migration, API permission, provider execution, or recovery
behavior changes. This affects the local run log, not Telemetry or
OpenTelemetry exports.
## Model Used
OpenAI Codex, GPT-6. The exact backend model ID and context-window size
are
not exposed in this session. Used reasoning, repository inspection, code
editing, tool use, and test execution.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run the affected tests locally and they pass (the broad
local run has PostgreSQL startup errors and timeouts documented above;
the full CI matrix passed)
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip
---
doc/run-log-events.md | 7 ++
.../crates/runner-core/src/provider_events.rs | 81 +++++++++++++++++++
.../runner-core/tests/codex_provider.rs | 8 ++
.../codex/app-server-transport.test.ts | 8 ++
.../src/drivers/codex/app-server-transport.ts | 37 +--------
.../src/drivers/codex/diagnostic-redaction.ts | 33 ++++++++
.../src/provider-events.test.ts | 42 ++++++++++
.../paperclip-runner/src/provider-events.ts | 24 ++++++
.../adapters/paperclip-runner/index.test.ts | 27 +++++++
ui/src/adapters/paperclip-runner/index.ts | 2 +
.../transcript/native-run-events.test.ts | 25 ++++++
.../transcript/native-run-events.ts | 2 +
.../transcript/run-log-only-events.ts | 16 ++++
13 files changed, 278 insertions(+), 34 deletions(-)
create mode 100644 packages/paperclip-runner/src/drivers/codex/diagnostic-redaction.ts
create mode 100644 ui/src/components/transcript/run-log-only-events.ts
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/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/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/components/transcript/native-run-events.test.ts b/ui/src/components/transcript/native-run-events.test.ts
index 754bd43348a..7fba1ff24ca 100644
--- a/ui/src/components/transcript/native-run-events.test.ts
+++ b/ui/src/components/transcript/native-run-events.test.ts
@@ -73,6 +73,31 @@ function runResult(summary: string): Record {
}
describe("provider notice presentation", () => {
+ it("omits unrelated information from saved chat without removing warnings or responses", () => {
+ const legacyNotice = {
+ schema: "paperclip.provider.notice.v1",
+ noticeId: "codex-warning",
+ severity: "warning",
+ category: "warning",
+ summary: "ignored unrelated provider information",
+ userActionable: true,
+ };
+ const entries = nativeRunEventsToTranscript([
+ event(1, "provider.notice.recorded", legacyNotice),
+ event(2, "harness.diagnostic", { code: "codex_unrelated_information" }),
+ event(3, "provider.notice.recorded", { ...legacyNotice, summary: "Repository is not trusted" }),
+ event(4, "provider.notice.recorded", { ...legacyNotice, severity: "error" }),
+ event(5, "provider.notice.recorded", { ...legacyNotice, category: "configWarning" }),
+ event(6, "item.completed", { kind: "agentMessage", channel: "final", text: "Here is the answer." }),
+ ]);
+ expect(entries).toMatchObject([
+ { kind: "provider_activity", summary: "Repository is not trusted" },
+ { kind: "provider_activity", status: "failed", summary: legacyNotice.summary },
+ { kind: "provider_activity", summary: legacyNotice.summary },
+ { kind: "assistant", text: "Here is the answer." },
+ ]);
+ });
+
it("preserves notice text as a notice rather than a synthetic tool call", () => {
const entries = nativeRunEventsToTranscript([
event(1, "provider.notice.recorded", {
diff --git a/ui/src/components/transcript/native-run-events.ts b/ui/src/components/transcript/native-run-events.ts
index fcc4bb13e98..954a3ce7856 100644
--- a/ui/src/components/transcript/native-run-events.ts
+++ b/ui/src/components/transcript/native-run-events.ts
@@ -1,5 +1,6 @@
import type { HeartbeatRunEvent } from "@paperclipai/shared";
import type { TranscriptEntry } from "@/adapters";
+import { isRunLogOnlyProviderEvent } from "./run-log-only-events";
function record(value: unknown): Record | null {
return value && typeof value === "object" && !Array.isArray(value)
@@ -810,6 +811,7 @@ export function nativeRunEventsToTranscript(events: readonly HeartbeatRunEvent[]
// Notices are provider diagnostics, not tool calls. Preserve their message
// and category for the shared notice row instead of serializing an input blob.
if (event.eventType === "provider.notice.recorded" && payload.schema === "paperclip.provider.notice.v1") {
+ if (isRunLogOnlyProviderEvent(event.eventType, payload)) continue;
entries.push({
kind: "provider_activity",
ts,
diff --git a/ui/src/components/transcript/run-log-only-events.ts b/ui/src/components/transcript/run-log-only-events.ts
new file mode 100644
index 00000000000..7f51548e40b
--- /dev/null
+++ b/ui/src/components/transcript/run-log-only-events.ts
@@ -0,0 +1,16 @@
+/** Internal provider bookkeeping belongs in run logs, including older notice records. */
+export function isRunLogOnlyProviderEvent(
+ eventType: string,
+ payload: Record,
+): boolean {
+ if (eventType === "harness.diagnostic") {
+ return payload.code === "codex_unrelated_information";
+ }
+ // Older runners dropped the classification when converting this diagnostic
+ // into a notice. Match its complete notice shape so real warnings stay visible.
+ return eventType === "provider.notice.recorded"
+ && payload.schema === "paperclip.provider.notice.v1"
+ && payload.severity === "warning"
+ && payload.category === "warning"
+ && payload.summary === "ignored unrelated provider information";
+}
From 6c1a75da4989b23306c865238757a6f1396641c1 Mon Sep 17 00:00:00 2001
From: Dotta <34892728+cryppadotta@users.noreply.github.com>
Date: Fri, 2 Oct 2026 10:01:15 -0500
Subject: [PATCH 3/5] feat(connections): make AgentMail a default connection
with inline setup (#14772)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Connections give agents access to external services.
> - AgentMail needs both a saved key and an inbox assigned to the agent.
> - Chat requests offered a setup link instead of an inline card and
could treat a saved key as complete.
> - Inbox setup also hid address conflicts behind a generic server error
and a separate review step.
> - This pull request makes AgentMail a default connection, adds the
inline card, reduces setup to two steps, and shows conflicts beside the
address.
> - Shared native dropdown styles also give every caret a consistent
inset.
## Linked Issues or Issue Description
**What happened?**
AgentMail requests in chat did not show a usable inline connection card.
Manual setup required extra screens, ignored saved account keys, and
could trap new-address setup in a locked inbox dropdown. Agent selectors
omitted the avatar from the selected value. A taken address could
produce an HTTP 403 from AgentMail and appear as an internal server
error. Native dropdown arrows also touched the right edge of their
fields.
**Expected behavior**
Make AgentMail available as a default connection. Ask for the API key
inline, with a direct link to its provider page. Default human access to
the company and agent access to the requesting agent. Resume the agent
only after an assigned inbox is active. Manual setup should ask for an
agent and email address, then finish. Address checks should run as the
user types. Taken addresses should show clickable alternatives. A domain
dropdown beside the name should prefer a verified custom domain. Setup
should suggest authorized saved AgentMail keys and show agent avatars in
the picker and selected value.
**Steps to reproduce**
1. Ask an agent to connect AgentMail when it has no assigned inbox.
2. Check that an inline API-key card appears and links to the provider's
API-key page.
3. Open AgentMail setup, choose an agent, and request an address that is
already taken.
4. Correct the inline error, refresh, and finish setup with the same
request ID.
5. Inspect native dropdown carets in light, dark, disabled, and
right-to-left states.
Uses the bounded provider-error parser merged in #14768. Related work:
#13256 introduced AgentMail; #14725 expanded connection search.
## What Changed
- Stop recurring email queries for tasks that have no email thread.
Share the query between the thread provider and activity view. Keep
email-task updates and invalidation-based discovery.
- Make AgentMail available without the experimental chat setting. Keep
the catalog, setup and management routes, agent Channels tab, task email
feed, receiving worker, and agent tools available by default. Other
experimental chat providers stay gated.
- Make the email address and copy icon a single clickable action with
the shared Copied! confirmation. Add View inbox linking directly to the
matching AgentMail console inbox, with the address encoded as one URL
path segment.
- Reorganize inbox Settings around the copyable email address, usage
instructions, and receiving status. Move reconnect credentials into a
disclosure and separate the Disconnect action. Add production Settings
stories for active, paused, unassigned-address, revoked, webhook,
long-address, mobile, and reconnect states. Show repair controls when
the inbox has an error. Keep usage instructions tied to an active inbox
with an address.
- Add AgentMail channel intents and an inline key field with the direct
API-key URL.
- Keep setup and retry state tied to the interaction. Require an active
inbox for completion. Preserve company and agent access checks.
- Reduce manual setup to agent selection and email selection. Put the
domain dropdown beside the address and default to a verified custom
domain. Preserve explicit choices across reloads. Keep receiving
settings under Advanced options.
- Check the initial address and edits after a 350 ms pause. Abort
superseded requests and ignore stale responses. Show clickable
suggestions and retain known creation conflicts across reloads.
- Add a company-scoped, manager-only address check using the saved
credential. Search the visible inbox list instead of fetching an
uncreated inbox: live AgentMail retains negative lookups that can break
subsequent access-key creation. Unlisted addresses remain unknown;
creation is authoritative.
- Suggest labeled saved AgentMail keys in both manual setup and the
inline card. Filter by company, provider, active credential, and
current-user grants on the server. Prefer an account key and preserve
the selected key or an explicit new-key choice across refresh. Use
verified scope metadata and bounded concurrent checks for legacy keys.
Never return secret values.
- Catch an inbox-only key before the email step. Allow its existing
inbox only after an explicit choice. Recover old locked drafts at the
key picker. Save the replacement key before retiring an empty draft,
then use a new setup URL so refresh preserves the switched account; stop
if cleanup fails. Preserve already allocated addresses and their
original accounts.
- Use the shared AgentSelect in email setup. Show the canonical agent
avatar in each option and the selected value, including other consumers
of the shared component. Add regression coverage for legacy and current
Lucide agent-mention icon formats.
- Start each catalog Add connection with a fresh setup identity. Honor
Finish setup's exact draft/account/address instead of resuming an
unrelated browser draft. Return Cancel and Done to Connectors and Email
settings to the inbox. Group the task/thread explanation in a How it
Works card.
- Route AgentMail catalog removal through the email inbox control API,
including unfinished drafts. Refresh both the catalog and inbox views.
- Render each inbox management tab separately. Access uses the saved
account grants and agent controls; Conversations and Activity use the
shared persisted email feed. Activity lifecycle actions use the email
API. Reconnect returns to inbox Settings. Conversation failures show a
retry instead of a false empty state. Email delivery recovery stays in
the task.
- Map documented provider address conflicts to a field error. Preserve
actionable messages for other failures.
- Preserve non-secret draft fields across refresh, scoped to the
requested agent. Never save API keys in browser storage. Resume partial
inbox creation with the original agent, address, and request ID.
- Show an already-created address with explicit retry and new-address
recovery instead of locked inputs. Preserve the original inbox and
resumable draft when choosing another address. Distinguish runtime-key
404 errors and log safe provider status/operation/code.
- Apply final agent access once within email setup authorization for a
new account whose original installs are unchanged. Preserve later
permission edits and reused account installs. Support in-place retry of
progress loading.
- Let a failed inline setup change keys after retiring an empty draft.
Persist its replacement setup identity without storing secrets. Recover
a server-saved account when refresh interrupts the save response, while
preserving intentional account changes.
- Render the production setup in Storybook and add error, recovery, and
mobile states.
- Inset native select carets in shared CSS. Preserve custom icons,
listboxes, keyboard behavior, and forced-color controls.
- Add browser regression coverage and an AgentMail Product E2E case with
persisted-state and rendered-card evidence.
## Verification
- Full `pnpm -r typecheck`, `pnpm build`, `pnpm check:token-gates`, and
`git diff --check` passed after the default-availability change.
- All 485 focused tests passed. These cover setup, management, catalog
and route gates, connection intents, email authorization, Cursor
execution, and the OpenAPI contract. All 39 email integration tests run
with the experimental chat setting off.
- The shared polling change passed four behavioral tests, UI typecheck
and build, and token gates.
- `tests/e2e/agentmail.spec.ts` passed with the actual server setting
off. This full-stack browser test uses simulated provider responses. It
covers catalog entry, saved keys, editable address and domain controls,
creation, conflicts, retry, all management tabs, clipboard feedback, the
provider link, and task email rendering.
- In the live local browser, Add connection reached the editable email
step with the saved account key. The verified custom domain was selected
by default. Both domain choices worked. The existing inbox Settings page
remained available. Both active inboxes completed new mail checks with
the setting off. No new provider inbox or email message was created for
this pass.
- Earlier live provider acceptance covered creation on a verified custom
domain, Finish connecting on the reported draft, successful mail checks
after refresh, and catalog removal of disposable draft and active
connections. Clicking the email address copied the exact address and
showed Copied!. View inbox opened the same inbox in AgentMail’s console.
No email messages were sent.
- Production setup and Settings Storybook builds and interactions
passed. Settings states include active, paused, unassigned, revoked,
webhook, long-address, mobile, and reconnect. Receiving and
revoked-access stories had zero accessibility violations.
- Full local `pnpm test:run` on an earlier revision completed with
14,709 passing, 87 skipped, and four transient failures. All four failed
cases passed in focused reruns without product changes. That serial full
local command was not repeated after each follow-up. The latest-head
full CI suite is the final test gate.
- CI found an obsolete browser assertion that hid every channel when the
flag was off. Updated it to keep AgentMail and the Channels surface
visible while preserving the GitHub chat route gates. All 11 provider
browser tests passed locally after scoping the Channels selector to the
agent sidebar. Two initial local attempts stopped at temporary Postgres
initialization. The passing run used a separate disposable database on
the existing local Postgres server; it was removed after the test.
- Updated the remaining sidebar and aggregator discovery assertions for
default AgentMail availability. Ordinary task fixtures now return no
email thread. All 128 sidebar/task-page tests and all 42 aggregator
tests passed locally.
- Latest head `b42bb4cd5cc9f2d01a99ab8026832d5a956ea85f`: full CI
passed, with 54 successful checks including Snyk and two intentional
Storybook skips. The CI run is
https://github.com/paperclipai/paperclip/actions/runs/37020833647. A
fresh Greptile review scored 5/5 with no unresolved threads. Live model
evaluations and inbound/outbound email delivery were not run.
## Risks
- AgentMail no longer needs experimental opt-in. Setup still requires a
human to connect an account and assign an inbox. Inline setup creates an
inbox after a human submits a new or saved key. Company access, agent
access, inbox assignment, and completion checks remain enforced.
- AgentMail read APIs cannot prove global address availability. The
visible-list check is bounded to 100 entries and cannot see inboxes
outside the key’s scope. The UI reports this limitation, suggests
alternatives without claiming they are free, and keeps final creation
conflicts inline. Lookup outages show an error without preventing the
authoritative creation attempt.
- Native select CSS affects the whole app. Custom-icon selects and
multi-row lists are excluded. Forced-color mode keeps the browser caret.
- Saved-key discovery uses stored verified scope metadata and checks
authorized legacy credentials concurrently within a shared three-second
deadline. Provider outages mark legacy choices unavailable; users can
still enter another key. Final use rechecks authorization and provider
access.
- No database migration or transport default change. Live connection
remains the default.
## Model Used
OpenAI Codex, GPT-6, with reasoning, tool use, and code execution. The
exact served model ID and context-window size are not exposed in this
session.
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass (focused suites; full-suite
limitation documented above)
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green (latest head
`b42bb4cd5cc9f2d01a99ab8026832d5a956ea85f`)
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
(latest head `b42bb4cd5cc9f2d01a99ab8026832d5a956ea85f`)
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip
---
doc/SPEC-implementation.md | 6 +-
doc/connections/AGENTMAIL.md | 127 +-
doc/connections/CONNECTION-SEARCH.md | 13 +-
doc/connections/CONNECTOR-PLAYBOOK.md | 6 +-
.../shared/src/app-definitions/agentmail.json | 2 +-
.../shared/src/connection-intent-guidance.ts | 2 +-
packages/shared/src/feature-catalog.ts | 2 +-
.../shared/src/types/connection-intent.ts | 4 +-
packages/shared/src/types/email.ts | 14 +
packages/shared/src/types/issue.ts | 4 +-
packages/shared/src/validators/email.ts | 6 +
packages/shared/src/validators/issue.ts | 2 +-
server/src/__tests__/agentmail-api.test.ts | 41 +
.../connection-aggregator-fallback.test.ts | 15 +-
.../src/__tests__/email-address-check.test.ts | 82 +
.../email-channels.integration.test.ts | 270 ++-
.../email-routes-provider-errors.test.ts | 113 ++
server/src/routes/email.ts | 86 +-
server/src/routes/openapi.ts | 23 +-
server/src/services/agentmail-api.ts | 14 +-
server/src/services/connection-intents.ts | 86 +-
server/src/services/connectors/agentmail.ts | 7 +-
server/src/services/email-channels.ts | 22 +-
server/src/services/email-connections.ts | 93 +-
tests/e2e/agentmail.spec.ts | 206 ++-
tests/e2e/chat-adapters-ui-providers.spec.ts | 32 +-
tests/e2e/connection-intents.spec.ts | 71 +
tests/runner-e2e/EVERYDAY-WORKFLOWS.md | 19 +-
.../agentmail-setup-evidence.test.ts | 29 +
tests/runner-e2e/agentmail-setup-evidence.ts | 25 +
tests/runner-e2e/catalog.test.ts | 6 +-
tests/runner-e2e/catalog.ts | 4 +-
tests/runner-e2e/everyday-cases.ts | 1 +
tests/runner-e2e/everyday-flow.ts | 30 +-
tests/runner-e2e/everyday.test.ts | 2 +-
ui/src/api/email.ts | 9 +
.../AgentContextualSidebar.test.tsx | 4 +-
ui/src/components/AgentContextualSidebar.tsx | 3 -
ui/src/components/AgentMultiSelect.test.tsx | 12 +
ui/src/components/AgentMultiSelect.tsx | 11 +-
.../ChatConnectorsExperimentalGate.test.tsx | 33 +-
.../ChatConnectorsExperimentalGate.tsx | 28 +-
ui/src/components/EmailMessageCard.tsx | 11 +-
ui/src/components/EmailTaskActivity.tsx | 10 +-
ui/src/components/EmailThreadPolling.test.tsx | 75 +
ui/src/components/chat/AgentChannelsPanel.tsx | 8 +-
.../connections/AgentMailApiKeyField.tsx | 15 +
.../connections/AgentMailCredentialField.tsx | 30 +
.../connections/AgentMailIntentSetup.tsx | 115 ++
.../connections/ApiKeyCredentialField.tsx | 38 +
.../ConnectionIntentInteractionBody.test.tsx | 188 ++-
.../ConnectionIntentInteractionBody.tsx | 21 +-
.../connections/ConnectionSetupFlow.tsx | 2 +-
.../connections/useEmailAddressCheck.ts | 25 +
ui/src/hooks/useEmailThread.ts | 13 +
ui/src/index.css | 29 +
ui/src/lib/mention-chips.test.ts | 20 +
ui/src/pages/AgentDetail.tsx | 13 +-
ui/src/pages/DesignGuide.tsx | 14 +-
ui/src/pages/InstanceExperimentalSettings.tsx | 2 +-
ui/src/pages/IssueDetail.test.tsx | 4 +
ui/src/pages/IssueDetail.tsx | 2 +-
ui/src/pages/apps/Browse.test.tsx | 43 +-
ui/src/pages/apps/Browse.tsx | 37 +-
ui/src/pages/apps/app-connect-policy.test.ts | 1 +
ui/src/pages/apps/app-connect-policy.ts | 2 +-
.../ChatEndpointDetail.agentmail.test.tsx | 118 ++
ui/src/pages/apps/chat/ChatEndpointDetail.tsx | 80 +-
.../apps/chat/EmailEndpointSetup.test.tsx | 604 +++++++
ui/src/pages/apps/chat/EmailEndpointSetup.tsx | 1057 ++++++------
.../stories/agentmail-onboarding.stories.tsx | 1455 +++--------------
.../stories/agentmail-settings.stories.tsx | 81 +
.../stories/in-feed-connections.stories.tsx | 39 +-
.../stories/primitives-coverage.stories.tsx | 24 +
74 files changed, 3645 insertions(+), 2096 deletions(-)
create mode 100644 server/src/__tests__/email-address-check.test.ts
create mode 100644 server/src/__tests__/email-routes-provider-errors.test.ts
create mode 100644 tests/runner-e2e/agentmail-setup-evidence.test.ts
create mode 100644 tests/runner-e2e/agentmail-setup-evidence.ts
create mode 100644 ui/src/components/EmailThreadPolling.test.tsx
create mode 100644 ui/src/features/connections/AgentMailApiKeyField.tsx
create mode 100644 ui/src/features/connections/AgentMailCredentialField.tsx
create mode 100644 ui/src/features/connections/AgentMailIntentSetup.tsx
create mode 100644 ui/src/features/connections/ApiKeyCredentialField.tsx
create mode 100644 ui/src/features/connections/useEmailAddressCheck.ts
create mode 100644 ui/src/hooks/useEmailThread.ts
create mode 100644 ui/src/lib/mention-chips.test.ts
create mode 100644 ui/src/pages/apps/chat/ChatEndpointDetail.agentmail.test.tsx
create mode 100644 ui/src/pages/apps/chat/EmailEndpointSetup.test.tsx
create mode 100644 ui/storybook/stories/agentmail-settings.stories.tsx
diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md
index 8a5d7fdd013..f980ee7ca05 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/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 9660136a2e1..f2c404a3bd8 100644
--- a/packages/shared/src/feature-catalog.ts
+++ b/packages/shared/src/feature-catalog.ts
@@ -111,7 +111,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/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 d320a5c170e..1ef26262c71 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,
@@ -1508,8 +1509,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",
@@ -2128,7 +2131,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],
@@ -2142,7 +2163,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 3bf098ded5b..b22f2e227a1 100644
--- a/tests/runner-e2e/catalog.test.ts
+++ b/tests/runner-e2e/catalog.test.ts
@@ -136,10 +136,10 @@ describe("runner E2E catalog", () => {
expect(localIntegrityTasks).toHaveLength(2);
expect(openRouterBreadthTasks).toHaveLength(3);
expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([
- 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,
+ 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(433);
- expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(433);
+ expect(validateRunnerCatalog()).toHaveLength(436);
+ expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(436);
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 baf09395651..b94cf60b708 100644
--- a/tests/runner-e2e/catalog.ts
+++ b/tests/runner-e2e/catalog.ts
@@ -1186,11 +1186,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/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}
+
void endpoint.refetch()}>Retry
+
+ );
+ 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."}
Open Connectors
diff --git a/ui/src/features/connections/AgentMailApiKeyField.tsx b/ui/src/features/connections/AgentMailApiKeyField.tsx
new file mode 100644
index 00000000000..773664c92dd
--- /dev/null
+++ b/ui/src/features/connections/AgentMailApiKeyField.tsx
@@ -0,0 +1,15 @@
+import { getAppStoreDefinition } from "@paperclipai/shared";
+import { ApiKeyCredentialField } from "./ApiKeyCredentialField";
+
+export const AGENTMAIL_API_KEYS_URL = getAppStoreDefinition("agentmail")!.methods[0]!.consoleLinks!.keys!;
+
+export function AgentMailApiKeyField({ value, onChange, disabled = false, label = "API key" }: {
+ value: string;
+ onChange(value: string): void;
+ disabled?: boolean;
+ label?: string;
+}) {
+ return {}} value={value} onChange={onChange}
+ disabled={disabled} label={label} />;
+}
diff --git a/ui/src/features/connections/AgentMailCredentialField.tsx b/ui/src/features/connections/AgentMailCredentialField.tsx
new file mode 100644
index 00000000000..a00e8f8b42e
--- /dev/null
+++ b/ui/src/features/connections/AgentMailCredentialField.tsx
@@ -0,0 +1,30 @@
+import { useEffect } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { emailApi } from "@/api/email";
+import { formatDateTime } from "@/lib/utils";
+import { ApiKeyCredentialField } from "./ApiKeyCredentialField";
+import { AGENTMAIL_API_KEYS_URL } from "./AgentMailApiKeyField";
+
+export function AgentMailCredentialField({ companyId, connectionId, onConnectionChange, value, onChange, disabled }: {
+ companyId: string;
+ connectionId: string | null;
+ onConnectionChange(id: string): void;
+ value: string;
+ onChange(value: string): void;
+ disabled?: boolean;
+}) {
+ const saved = useQuery({ queryKey: ["email-credentials", companyId],
+ queryFn: () => emailApi.credentials(companyId), staleTime: 60_000, retry: false });
+ useEffect(() => {
+ // Null means untouched; an explicit new-key choice must survive refreshes
+ // and slow responses. Inbox-only keys cannot create a new email address.
+ if (connectionId !== null || value || !saved.isSuccess) return;
+ const preferred = saved.data.find(option => option.scope === "organization" || option.scope === "pod");
+ if (preferred) onConnectionChange(preferred.id);
+ }, [connectionId, value, saved.isSuccess, saved.data, onConnectionChange]);
+ return ({ id: option.id, disabled: option.scope === "unavailable",
+ label: `${option.label} · saved ${formatDateTime(option.createdAt)}` }))}
+ connectionId={connectionId} onConnectionChange={onConnectionChange} value={value} onChange={onChange}
+ disabled={disabled} loading={saved.isFetching} error={saved.error?.message} />;
+}
diff --git a/ui/src/features/connections/AgentMailIntentSetup.tsx b/ui/src/features/connections/AgentMailIntentSetup.tsx
new file mode 100644
index 00000000000..2b82e2f7656
--- /dev/null
+++ b/ui/src/features/connections/AgentMailIntentSetup.tsx
@@ -0,0 +1,115 @@
+import { useEffect, useState } from "react";
+import { useMutation } from "@tanstack/react-query";
+import { isUuidLike } from "@paperclipai/shared";
+import { emailApi } from "@/api/email";
+import { Button } from "@/components/ui/button";
+import { AgentMailCredentialField } from "./AgentMailCredentialField";
+
+interface InlineEmailDraft {
+ setupRequestId: string;
+ credentialId: string | null;
+ inboxConnectionId: string | null;
+ selectedCredentialId: string | null;
+}
+function readDraft(key: string): InlineEmailDraft | null {
+ try {
+ const value = JSON.parse(sessionStorage.getItem(key) ?? "null");
+ return value && isUuidLike(value.setupRequestId) && ["credentialId", "inboxConnectionId", "selectedCredentialId"]
+ .every(field => value[field] === null || typeof value[field] === "string") ? value : null;
+ } catch { return null; }
+}
+
+/** Same account and inbox APIs as Apps; task setup fixes the access defaults. */
+export function AgentMailIntentSetup({ companyId, agentId, requestId, savedCredentialId, readyConnectionId, onComplete, onDecline, declining = false }: {
+ companyId: string;
+ agentId: string;
+ requestId: string;
+ savedCredentialId?: string | null;
+ readyConnectionId?: string | null;
+ onComplete(connectionId: string): Promise;
+ onDecline(): void;
+ declining?: boolean;
+}) {
+ const draftKey = `paperclip.agentmail-inline:${companyId}:${requestId}`;
+ const [draft] = useState(() => readDraft(draftKey));
+ const [setupRequestId, setSetupRequestId] = useState(draft?.setupRequestId ?? requestId);
+ const [apiKey, setApiKey] = useState("");
+ // A refresh can interrupt the response after the server has saved the key.
+ // Recover that account unless the user selected another key or started a
+ // different setup after the interrupted request.
+ const [credentialId, setCredentialId] = useState(draft?.credentialId
+ ?? (!draft || (draft.setupRequestId === requestId && !draft.selectedCredentialId) ? savedCredentialId ?? null : null));
+ const [selectedCredentialId, setSelectedCredentialId] = useState(draft?.selectedCredentialId ?? null);
+ const [inboxConnectionId, setInboxConnectionId] = useState(readyConnectionId ?? draft?.inboxConnectionId ?? null);
+ useEffect(() => {
+ try { sessionStorage.setItem(draftKey, JSON.stringify({ setupRequestId, credentialId, inboxConnectionId, selectedCredentialId })); }
+ catch { /* Keep setup usable without browser storage. */ }
+ }, [draftKey, setupRequestId, credentialId, inboxConnectionId, selectedCredentialId]);
+ const changeKey = useMutation({
+ mutationFn: async (pendingRequestId: string) => {
+ const pending = (await emailApi.list(companyId)).find(inbox => inbox.id === pendingRequestId && inbox.status !== "archived");
+ if (pending?.address) throw new Error(`The address ${pending.address} is already reserved. Finish setup with its saved key.`);
+ if (pending) await emailApi.control(pending.id, "remove");
+ },
+ onSuccess: () => {
+ setSetupRequestId(crypto.randomUUID());
+ setCredentialId(null);
+ setSelectedCredentialId("");
+ setApiKey("");
+ setup.reset();
+ },
+ });
+ const setup = useMutation({
+ mutationFn: async (submitted: { accountId: string | null; apiKey: string; requestId: string; inboxId: string | null }) => {
+ let connectionId = submitted.inboxId;
+ if (!connectionId) {
+ let accountId = submitted.accountId;
+ if (!accountId) {
+ const account = await emailApi.connect(companyId, {
+ apiKey: submitted.apiKey, grantKind: "organization", allAgents: false,
+ agentIds: [agentId], idempotencyKey: submitted.requestId,
+ });
+ accountId = account.id;
+ setCredentialId(accountId);
+ setApiKey("");
+ }
+ setCredentialId(accountId);
+ const inbox = await emailApi.setup(companyId, {
+ assignedAgentId: agentId, credentialConnectionId: accountId,
+ receiveMode: "websocket", idempotencyKey: submitted.requestId,
+ });
+ connectionId = inbox.connectionId;
+ setInboxConnectionId(connectionId);
+ }
+ // Only the server's completed intent may resume the task. A saved API key
+ // alone is not an inbox, and failures remain retryable in this same form.
+ await onComplete(connectionId);
+ try { sessionStorage.removeItem(draftKey); } catch { /* Optional draft storage. */ }
+ },
+ });
+ return ;
+}
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
+
{label}
+ {choices.length > 0 &&
onConnectionChange(event.target.value)}>
+ {choices.map(option => {option.label} )}
+ Enter a new API key
+ }
+ {!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}
+
declineMutation.mutate()}>Not now
+ > :
{ 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.
@@ -2297,7 +2300,8 @@ export function DesignGuide() {
the full-page Apps setup; this card owns only audience, dialog, and task refresh behavior.
Pending connections stay in the timeline beside a usable composer. The independently
addressable Connections/In-task connections stories cover access, OAuth recovery, narrow
- layouts, completion, and historical outcomes.
+ layouts, completion, and historical outcomes. AgentMail uses an inline API-key field
+ with fixed access defaults; its field and direct key-page link are shared with Apps setup.
+
+ AgentMail setup has two steps: pick an agent, then pick an email address. Ask for the API key alongside the agent only when needed. Keep address errors beside the field and additional settings under Advanced options.
+ Preview only. This field does not save or submit a credential.
+
+
+
Design-system wrapper over react-resizable-panels {" "}
diff --git a/ui/src/pages/InstanceExperimentalSettings.tsx b/ui/src/pages/InstanceExperimentalSettings.tsx
index 8fc3a2c6410..0d8bd95e366 100644
--- a/ui/src/pages/InstanceExperimentalSettings.tsx
+++ b/ui/src/pages/InstanceExperimentalSettings.tsx
@@ -342,7 +342,7 @@ export function InstanceExperimentalSettings() {
toggleMutation.mutate({ enableChatConnectors: checked })}
disabled={toggleMutation.isPending}
diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx
index b785be44371..a45a721f358 100644
--- a/ui/src/pages/IssueDetail.test.tsx
+++ b/ui/src/pages/IssueDetail.test.tsx
@@ -172,6 +172,10 @@ vi.mock("../api/issues", async (importOriginal) => {
return { ...actual, issuesApi: Object.assign(actual.issuesApi, mockIssuesApi) };
});
+vi.mock("../api/email", () => ({
+ emailApi: { thread: vi.fn().mockResolvedValue(null) },
+}));
+
vi.mock("../api/activity", () => ({
activityApi: mockActivityApi,
}));
diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx
index 672a89738cf..be09ccbd6ac 100644
--- a/ui/src/pages/IssueDetail.tsx
+++ b/ui/src/pages/IssueDetail.tsx
@@ -7805,7 +7805,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
onOpenSkill={handleOpenSkill}
browsers={browserQuery.data}
onOpenBrowser={(id) => { setOpenBrowserId(id); if (isMobile) setMobilePropsOpen(true); else openTaskSidePanel(); }}
- threadHeader={<>{taskChatThreadHeader}{instanceExperimentalSettings?.enableChatConnectors && }>}
+ threadHeader={<>{taskChatThreadHeader} >}
issueBrief={
// Suppress the seeded-description bubble for the onboarding first
// task: its description is agent instructions, not something the
diff --git a/ui/src/pages/apps/Browse.test.tsx b/ui/src/pages/apps/Browse.test.tsx
index 603078e382b..35ab90ed2ff 100644
--- a/ui/src/pages/apps/Browse.test.tsx
+++ b/ui/src/pages/apps/Browse.test.tsx
@@ -18,9 +18,11 @@ const navigateMock = vi.hoisted(() => vi.fn());
const setBreadcrumbsMock = vi.hoisted(() => vi.fn());
const experimentalMock = vi.hoisted(() => vi.fn());
const chatSetupMock = vi.hoisted(() => vi.fn());
+const emailControlMock = vi.hoisted(() => vi.fn());
const chatListMock = vi.hoisted(() => vi.fn());
vi.mock("@/api/instanceSettings", () => ({ instanceSettingsApi: { getExperimental: experimentalMock } }));
vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: { list: chatListMock, setup: chatSetupMock } }));
+vi.mock("@/api/email", () => ({ emailApi: { control: emailControlMock } }));
vi.mock("@/api/tools", () => ({
toolsApi: {
@@ -137,6 +139,7 @@ describe("Connectors landing page", () => {
experimentalMock.mockResolvedValue({ enableChatConnectors: true });
chatListMock.mockResolvedValue([]);
chatSetupMock.mockReset().mockResolvedValue({ status: "archived" });
+ emailControlMock.mockReset().mockResolvedValue({ status: "archived" });
listGalleryMock.mockResolvedValue({
apps: [
galleryEntry({
@@ -349,17 +352,20 @@ describe("Connectors landing page", () => {
it("defaults to tools-only GitHub and hides chat-only catalog and existing chat accounts", async () => {
experimentalMock.mockResolvedValue({});
- listGalleryMock.mockResolvedValue({ apps: ["github", "github-code-review-bot", "discord", "telegram", "microsoft-teams"].map(getAppStoreDefinition) });
+ listGalleryMock.mockResolvedValue({ apps: ["agentmail", "github", "github-code-review-bot", "discord", "telegram", "microsoft-teams"].map(getAppStoreDefinition) });
listApplicationsMock.mockResolvedValue({ applications: [application({
id: "chat-app", type: "chat", name: "Private bot", applicationKey: "chat:github:endpoint-1", metadata: { purpose: "channel" },
})] });
await renderBrowse();
- expect(chatListMock).not.toHaveBeenCalled();
+ expect(chatListMock).toHaveBeenCalledWith("company-1");
expect(container.querySelector('[data-app-slug="github"]')).not.toBeNull();
for (const slug of ["github-code-review-bot", "discord", "telegram", "microsoft-teams", "slack"]) {
expect(container.querySelector(`[data-app-slug="${slug}"]`)).toBeNull();
}
expect(container.textContent).not.toContain("Private bot");
+ expect(container.querySelector('[data-app-slug="agentmail"]')).not.toBeNull();
+ await act(() => void container.querySelector('button[aria-label="Connect AgentMail"]')!.click());
+ expect(navigateMock.mock.lastCall?.[0]).toContain("/apps/chat/connect?provider=agentmail");
expect(container.textContent).not.toContain("Chat with agents");
await act(() => void container.querySelector('button[aria-label="Add key GitHub"]')!.click());
expect(navigateMock).toHaveBeenLastCalledWith("/apps/connect?source=github");
@@ -460,6 +466,7 @@ describe("Connectors landing page", () => {
),
).map((row) => row.dataset.appSlug),
).toEqual([
+ "agentmail",
"discord",
"github-code-review-bot",
"imessage-photon",
@@ -642,6 +649,19 @@ describe("Connectors landing page", () => {
);
});
+ it("starts each AgentMail Add connection with a distinct setup identity", async () => {
+ chatListMock.mockResolvedValue([{ id: "chat-draft", provider: "agentmail", status: "draft", assignedAgentName: "Ralph" }]);
+ await renderBrowse();
+ const add = container.querySelector('button[aria-label="Add connection AgentMail"]')!;
+ await act(() => add.click());
+ const first = new URL(navigateMock.mock.lastCall![0], "http://localhost");
+ expect(first.pathname).toBe("/apps/chat/connect");
+ expect(first.searchParams.get("provider")).toBe("agentmail");
+ expect(first.searchParams.get("setupId")).toMatch(/^[0-9a-f-]{36}$/);
+ await act(() => add.click());
+ expect(navigateMock.mock.lastCall![0]).not.toBe(first.pathname + first.search);
+ });
+
it.each(["slack", "discord", "telegram", "github", "microsoft-teams", "agentmail", "imessage-photon"])(
"puts Manage and removal in the %s chat menu while keeping draft setup visible",
async (provider) => {
@@ -665,23 +685,34 @@ describe("Connectors landing page", () => {
},
);
- it.each(["active", "draft"])("confirms chat removal for %s connections and refreshes the list", async (status) => {
- chatListMock.mockResolvedValue([{ id: "chat-1", provider: "slack", status, assignedAgentName: "CEO" }]);
+ it.each([
+ ["slack", "Slack", "active"], ["slack", "Slack", "draft"],
+ ["agentmail", "AgentMail", "active"], ["agentmail", "AgentMail", "draft"],
+ ])("confirms %s removal for %s %s connections and refreshes the list", async (provider, providerName, status) => {
+ chatListMock.mockResolvedValue([{ id: "chat-1", provider, status, assignedAgentName: "CEO" }]);
const client = await renderBrowse();
const invalidate = vi.spyOn(client, "invalidateQueries");
- await act(() => void container.querySelector('button[aria-label="Manage CEO Slack connection"]')!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })));
+ await act(() => void container.querySelector(`button[aria-label="Manage CEO ${providerName} connection"]`)!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })));
await flushReact();
const remove = Array.from(document.querySelectorAll('[role="menuitem"]')).find((item) => item.textContent?.trim() === "Remove connection");
await act(() => remove!.click());
await flushReact();
expect(chatSetupMock).not.toHaveBeenCalled();
+ expect(emailControlMock).not.toHaveBeenCalled();
expect(document.body.textContent).toContain("Existing Paperclip tasks and conversation history remain available.");
chatListMock.mockResolvedValue([]);
await act(() => Array.from(document.querySelectorAll("button")).find((button) => button.textContent?.trim() === "Remove connection")!.click());
await flushReact();
- expect(chatSetupMock).toHaveBeenCalledWith("chat-1", { action: "remove" });
+ if (provider === "agentmail") {
+ expect(emailControlMock).toHaveBeenCalledWith("chat-1", "remove");
+ expect(chatSetupMock).not.toHaveBeenCalled();
+ } else {
+ expect(chatSetupMock).toHaveBeenCalledWith("chat-1", { action: "remove" });
+ expect(emailControlMock).not.toHaveBeenCalled();
+ }
expect(archiveConnectionMock).not.toHaveBeenCalled();
expect(invalidate).toHaveBeenCalledWith({ queryKey: queryKeys.chatEndpoints.list("company-1") });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ["email-inboxes", "company-1"] });
expect(container.textContent).not.toContain("CEO");
});
diff --git a/ui/src/pages/apps/Browse.tsx b/ui/src/pages/apps/Browse.tsx
index aeb71f444aa..c1177433249 100644
--- a/ui/src/pages/apps/Browse.tsx
+++ b/ui/src/pages/apps/Browse.tsx
@@ -38,6 +38,7 @@ import { useBreadcrumbs } from "@/context/BreadcrumbContext";
import { useToast } from "@/context/ToastContext";
import { queryKeys } from "@/lib/queryKeys";
import { toolsApi } from "@/api/tools";
+import { emailApi } from "@/api/email";
import {
chatEndpointsApi,
type ChatEndpoint,
@@ -109,13 +110,11 @@ type ConnectionState = {
};
type ConnectionRemovalTarget = {
- kind?: "chat";
id: string;
accountName: string;
providerName: string;
remainingConnectionCount: number;
-
-};
+} & ({ kind: "chat"; provider: ChatProvider } | { kind?: undefined });
// Temporary, page-only hold until Google OAuth verification is approved.
// Keep definitions, direct setup/management routes, and runtime access intact.
@@ -232,7 +231,7 @@ function connectorAction(
title?: string;
} {
const applicationId = row.applications[0]?.id ?? null;
- const chatHref = chatConnectorsEnabled
+ const chatHref = (row.slug === "agentmail" || chatConnectorsEnabled)
? chatConnectHref(
row.slug,
row.entry ? connectHrefFor(row.entry) : null,
@@ -331,7 +330,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
const chatEndpointsQuery = useQuery({
queryKey: queryKeys.chatEndpoints.list(selectedCompanyId ?? "__none__"),
queryFn: () => chatEndpointsApi.list(selectedCompanyId!),
- enabled: !!selectedCompanyId && chatConnectorsEnabled,
+ enabled: !!selectedCompanyId,
});
const userDirectoryQuery = useQuery({
queryKey: queryKeys.access.companyUserDirectory(
@@ -343,12 +342,17 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
const removeConnection = useMutation({
mutationFn: async (target: ConnectionRemovalTarget) => {
if (target.kind === "chat") {
- await chatEndpointsApi.setup(target.id, { action: "remove" });
+ if (target.provider === "agentmail") {
+ await emailApi.control(target.id, "remove");
+ } else {
+ await chatEndpointsApi.setup(target.id, { action: "remove" });
+ }
} else {
await toolsApi.archiveConnection(target.id);
}
},
onSuccess: (_connection, target) => {
+ queryClient.invalidateQueries({ queryKey: ["email-inboxes", selectedCompanyId!] });
queryClient.invalidateQueries({
queryKey: queryKeys.chatEndpoints.list(selectedCompanyId!),
});
@@ -387,7 +391,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
if (!memoryConnectorsEnabled && isMemoryConnectorId(appDefinitionSlug(entry))) return false;
const definition = getAppStoreDefinition(appDefinitionSlug(entry));
return (
- chatConnectorsEnabled ||
+ appDefinitionSlug(entry) === "agentmail" || chatConnectorsEnabled ||
!definition?.methods.some((method) => method.purpose === "channel") ||
appSupportsToolCatalogSetup(definition)
);
@@ -436,7 +440,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
slug,
name: appDefinitionName(entry),
description:
- !chatConnectorsEnabled && chatProviderForSlug(slug)
+ !chatConnectorsEnabled && slug !== "agentmail" && chatProviderForSlug(slug)
? appCopyFor(slug).tagline
: appDefinitionDescription(entry),
brandKey: slug,
@@ -449,6 +453,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
});
}
const nativeChatApps = [
+ { slug: "agentmail", name: "AgentMail", description: "Give agents email inboxes and handle each conversation as a task." },
{ slug: "imessage-photon", name: "iMessage Photon", description: "Message agents and share photos from Apple Messages with a dedicated Photon number." },
{
slug: "slack",
@@ -480,7 +485,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
"Chat with agents from Telegram direct messages, groups, and topics.",
},
] as const;
- for (const item of chatConnectorsEnabled ? nativeChatApps : []) {
+ for (const item of nativeChatApps.filter(item => item.slug === "agentmail" || chatConnectorsEnabled)) {
if (rowsBySlug.has(item.slug)) continue;
rowsBySlug.set(item.slug, {
key: `native-chat:${item.slug}`,
@@ -563,9 +568,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
});
}
- for (const endpoint of chatConnectorsEnabled
- ? (chatEndpointsQuery.data ?? [])
- : []) {
+ for (const endpoint of (chatEndpointsQuery.data ?? []).filter(endpoint => endpoint.provider === "agentmail" || chatConnectorsEnabled)) {
if (endpoint.status === "archived") continue;
let target = [...rowsBySlug.values()].find(
(row) => chatProviderForSlug(row.slug) === endpoint.provider,
@@ -654,12 +657,12 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
galleryQuery.isLoading ||
applicationsQuery.isLoading ||
connectionsQuery.isLoading ||
- (chatConnectorsEnabled && chatEndpointsQuery.isLoading);
+ chatEndpointsQuery.isLoading;
const loadFailed =
galleryQuery.isError ||
applicationsQuery.isError ||
connectionsQuery.isError ||
- (chatConnectorsEnabled && chatEndpointsQuery.isError);
+ chatEndpointsQuery.isError;
const nothingMatches = visibleRows.length === 0 && !showCustomConnector;
return (
@@ -696,7 +699,7 @@ export function Browse({ renderAccountDetails = (connection) => connection.conne
void galleryQuery.refetch();
void applicationsQuery.refetch();
void connectionsQuery.refetch();
- if (chatConnectorsEnabled) void chatEndpointsQuery.refetch();
+ void chatEndpointsQuery.refetch();
}}
>
Try again
@@ -836,7 +839,8 @@ export function ConnectorCard({
disabled={!action.href}
title={action.title}
onClick={() => {
- if (action.href) onNavigate(action.href);
+ if (action.href) onNavigate(row.slug === "agentmail"
+ ? `${action.href}&setupId=${crypto.randomUUID()}` : action.href);
}}
aria-label={`${action.label} ${row.name}`}
>
@@ -932,6 +936,7 @@ export function ConnectorCard({
variant="destructive"
onSelect={() => onRequestRemove({
kind: "chat",
+ provider: endpoint.provider,
id: endpoint.id,
accountName: `${endpoint.assignedAgentName} · ${row.name}`,
providerName: row.name,
diff --git a/ui/src/pages/apps/app-connect-policy.test.ts b/ui/src/pages/apps/app-connect-policy.test.ts
index a11c224f411..5756946ae54 100644
--- a/ui/src/pages/apps/app-connect-policy.test.ts
+++ b/ui/src/pages/apps/app-connect-policy.test.ts
@@ -87,6 +87,7 @@ describe("app connect policy", () => {
it("retains GitHub tools but denies chat-only deep links while chat connectors are disabled", () => {
expect(canEnterAppsConnect(new URLSearchParams("source=github"))).toBe(true);
+ expect(canEnterAppsConnect(new URLSearchParams("source=agentmail"))).toBe(true);
for (const source of ["discord", "telegram", "microsoft-teams"]) {
expect(canEnterAppsConnect(new URLSearchParams({ source })), source).toBe(false);
expect(canEnterAppsConnect(new URLSearchParams({ source, reconnect: "connection-1" })), source).toBe(false);
diff --git a/ui/src/pages/apps/app-connect-policy.ts b/ui/src/pages/apps/app-connect-policy.ts
index 089ceb8b9e1..60dfbea7ed4 100644
--- a/ui/src/pages/apps/app-connect-policy.ts
+++ b/ui/src/pages/apps/app-connect-policy.ts
@@ -77,5 +77,5 @@ export function canEnterAppsConnect(
// setup. Admit only known providers here; the setup flow then proves the
// exact reconnect target is visible to the selected company before rendering.
if (getConnectableAppDefinition(source) && searchParams.get("reconnect")?.trim()) return true;
- return chatConnectorsEnabled ? appSupportsCatalogSetup(entry) : appSupportsToolCatalogSetup(entry);
+ return source === "agentmail" || chatConnectorsEnabled ? appSupportsCatalogSetup(entry) : appSupportsToolCatalogSetup(entry);
}
diff --git a/ui/src/pages/apps/chat/ChatEndpointDetail.agentmail.test.tsx b/ui/src/pages/apps/chat/ChatEndpointDetail.agentmail.test.tsx
new file mode 100644
index 00000000000..16b0d1cfe9b
--- /dev/null
+++ b/ui/src/pages/apps/chat/ChatEndpointDetail.agentmail.test.tsx
@@ -0,0 +1,118 @@
+// @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 { ChatEndpointDetail } from "./ChatEndpointDetail";
+import { queryKeys } from "@/lib/queryKeys";
+import { TooltipProvider } from "@/components/ui/tooltip";
+
+const mocks = vi.hoisted(() => ({
+ tab: "settings", get: vi.fn(), conversations: vi.fn(), activity: vi.fn(), setup: vi.fn(),
+ control: vi.fn(), getConnection: vi.fn(), grants: vi.fn(), installs: vi.fn(), agents: vi.fn(),
+ navigate: vi.fn(),
+}));
+vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: {
+ get: mocks.get, listConversations: mocks.conversations, listActivityPage: mocks.activity, setup: mocks.setup,
+} }));
+vi.mock("@/api/email", () => ({ emailApi: { control: mocks.control } }));
+vi.mock("@/api/tools", () => ({ toolsApi: {
+ getConnection: mocks.getConnection, listConnectionGrants: mocks.grants, getConnectionInstalls: mocks.installs,
+} }));
+vi.mock("@/api/agents", () => ({ agentsApi: { list: mocks.agents } }));
+vi.mock("./EmailEndpointSetup", () => ({ EmailEndpointSettings: () => Email settings }));
+vi.mock("@/context/BreadcrumbContext", () => ({ useBreadcrumbs: () => ({ setBreadcrumbs: () => {} }) }));
+vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ pushToast: () => {} }) }));
+vi.mock("@/lib/router", () => ({
+ useParams: () => ({ endpointId: "inbox", tab: mocks.tab }), useNavigate: () => mocks.navigate,
+ Link: ({ children, to, ...props }: React.ComponentProps<"a"> & { to: string }) => {children} ,
+ Navigate: () => null,
+}));
+
+describe("AgentMail connection management tabs", () => {
+ let root: Root;
+ let container: HTMLDivElement;
+ let client: QueryClient;
+ const endpoint = { id: "inbox", companyId: "company", connectionId: "runtime", provider: "agentmail",
+ assignedAgentId: "ralph", assignedAgentName: "Ralph", botExternalId: "ralph@example.test",
+ allowUnlinkedPeople: false, status: "active", setup: { step: "complete" } };
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.tab = "settings";
+ mocks.get.mockResolvedValue(endpoint);
+ mocks.getConnection.mockResolvedValue({ id: "runtime", companyId: "company", config: { credentialConnectionId: "account" } });
+ mocks.grants.mockResolvedValue({ grants: [{ status: "active", kind: "organization" }], capabilities: { canConfigure: true } });
+ mocks.installs.mockResolvedValue({ installs: [{ targetType: "agent", targetId: "ralph" }] });
+ mocks.agents.mockResolvedValue([{ id: "ralph", name: "Ralph", status: "idle" }]);
+ mocks.conversations.mockResolvedValue([]);
+ mocks.activity.mockResolvedValue({ items: [], nextCursor: null });
+ mocks.control.mockResolvedValue({ id: "inbox", companyId: "company", status: "paused" });
+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);
+ client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
+ });
+ afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); });
+ const settle = () => act(async () => { await new Promise(resolve => setTimeout(resolve, 20)); });
+ async function render(tab: string) {
+ mocks.tab = tab;
+ await act(async () => root.render( ));
+ await vi.waitFor(() => {
+ expect(container.textContent?.trim().length).toBeGreaterThan(0);
+ expect(container.textContent).not.toMatch(/Loading (connection|access|conversations|activity)…/);
+ }, { timeout: 3000 });
+ }
+ async function click(label: string) {
+ const button = [...container.querySelectorAll("button")].find(node => node.textContent?.trim() === label);
+ expect(button).toBeDefined(); await act(async () => button!.click());
+ await vi.waitFor(() => expect(button!.disabled).toBe(false), { timeout: 3000 });
+ await settle();
+ }
+ it("renders settings only on Settings and loads the saved credential on Access", async () => {
+ await render("settings"); expect(container.textContent).toContain("Email settings");
+ await render("access");
+ expect(container.textContent).not.toContain("Email settings");
+ expect(container.textContent).toContain("Any human in the organization");
+ expect(container.textContent).toContain("Ralph");
+ expect(mocks.grants).toHaveBeenCalledWith("account"); expect(mocks.installs).toHaveBeenCalledWith("account");
+ expect(mocks.grants).not.toHaveBeenCalledWith("runtime");
+ });
+ it("shows an access failure rather than editable controls when the credential cannot load", async () => {
+ mocks.getConnection.mockRejectedValue(new Error("Offline")); await render("access");
+ expect(container.querySelector('[role="alert"]')?.textContent).toContain("could not be loaded");
+ expect(container.querySelector('[role="radiogroup"]')).toBeNull(); expect(mocks.grants).not.toHaveBeenCalled();
+ });
+ it("uses inbox-local access for a legacy inbox with no saved account", async () => {
+ mocks.getConnection.mockResolvedValue({ id: "runtime", config: {} }); await render("access");
+ expect(mocks.grants).toHaveBeenCalledWith("runtime");
+ });
+ it("loads email conversations and links their tasks", async () => {
+ mocks.conversations.mockResolvedValue([{ id: "thread", externalLabel: "Customer question", issueId: "task", issueTitle: "Help customer", state: "active" }]);
+ await render("conversations"); expect(container.textContent).toContain("Customer question");
+ expect(container.querySelector('a[href="/issues/task"]')).not.toBeNull();
+ expect(container.textContent).not.toContain("Email settings"); expect(mocks.conversations).toHaveBeenCalledWith("inbox");
+ });
+ it("gives an email-specific empty state and reports conversation load errors", async () => {
+ await render("conversations"); expect(container.textContent).toContain("Send an email");
+ client.removeQueries({ queryKey: queryKeys.chatEndpoints.conversations("inbox") });
+ mocks.conversations.mockRejectedValue(new Error("Offline")); await render("conversations");
+ expect(container.querySelector('[role="alert"]')?.textContent).toContain("Conversations could not be loaded");
+ expect(container.textContent).not.toContain("No email conversations yet");
+ mocks.conversations.mockResolvedValue([]); await click("Try again"); expect(container.textContent).toContain("Send an email");
+ });
+ it("loads activity and routes pause through the email API without replacing cached chat detail with an email summary", async () => {
+ mocks.activity.mockImplementation(async () => {
+ // Query completion can follow the initial endpoint render, especially
+ // while the complete UI suite is running. Wait for data, not a short sleep.
+ await new Promise(resolve => setTimeout(resolve, 100));
+ return { items: [{ id: "delivery", kind: "delivery", status: "failed", summary: "Email received", createdAt: "2026-10-01T00:00:00Z", replayable: true,
+ resolutionActions: ["retry_anyway"] }, { id: "publication", kind: "publication", status: "delivery_unknown", summary: "Email send unconfirmed",
+ createdAt: "2026-10-01T00:00:00Z", resolutionActions: ["mark_delivered", "retry_anyway", "cancel"] }], nextCursor: null };
+ });
+ await render("activity"); expect(container.textContent).toContain("Email received");
+ expect(container.textContent).not.toContain("Email settings"); expect(container.textContent).not.toContain("Replay");
+ expect([...container.querySelectorAll("button")].some(button => button.textContent?.trim() === "Resolve")).toBe(false);
+ expect(container.querySelector('a[href="/apps/chat/inbox/conversations"]')).not.toBeNull();
+ await click("Pause"); expect(mocks.control).toHaveBeenCalledWith("inbox", "pause"); expect(mocks.setup).not.toHaveBeenCalled();
+ expect(client.getQueryData(queryKeys.chatEndpoints.detail("inbox"))).toMatchObject({ provider: "agentmail", assignedAgentName: "Ralph" });
+ await click("Reconnect"); expect(mocks.navigate).toHaveBeenCalledWith("/apps/chat/inbox/settings");
+ });
+});
diff --git a/ui/src/pages/apps/chat/ChatEndpointDetail.tsx b/ui/src/pages/apps/chat/ChatEndpointDetail.tsx
index 245d2f26b44..3203d0207ec 100644
--- a/ui/src/pages/apps/chat/ChatEndpointDetail.tsx
+++ b/ui/src/pages/apps/chat/ChatEndpointDetail.tsx
@@ -7,6 +7,9 @@ import { agentAvatarUrl } from "@/lib/agent-avatar-url";
import { resolveAgentAppearance } from "@paperclipai/shared";
import { GitHubBotManagement, GitHubReviews } from "./GitHubBotManagement";
import { EmailEndpointSettings } from "./EmailEndpointSetup";
+import { EmailConnectionAccess } from "@/components/EmailConnectionAccess";
+import { emailApi } from "@/api/email";
+import { toolsApi } from "@/api/tools";
import { useEffect, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
@@ -279,7 +282,8 @@ export function ChatEndpointDetail() {
);
- if (endpoint.provider === "agentmail") return ;
+ if (endpoint.provider === "agentmail" && activeTab === "settings")
+ return ;
const setupIncomplete =
endpoint.setup?.step !== "complete" &&
["draft", "verifying", "attention", "revoked"].includes(endpoint.status);
@@ -292,7 +296,7 @@ export function ChatEndpointDetail() {
{endpoint.assignedAgentName} in {providerNames[endpoint.provider]}
- {endpoint.providerAccountLabel ?? "Chat connection"}
+ {endpoint.providerAccountLabel ?? (endpoint.provider === "agentmail" ? endpoint.botExternalId ?? "Email connection" : "Chat connection")}
{endpoint.provider === "imessage-photon" && endpoint.botExternalId && endpoint.photonAllocation !== "shared" && (
@@ -329,7 +333,8 @@ export function ChatEndpointDetail() {
)}
{activeTab === "reviews" && endpoint.provider === "github" &&
}
{activeTab === "access" && endpoint.provider === "github" &&
}
-{activeTab === "access" && endpoint.provider !== "github" && (
+{activeTab === "access" && endpoint.provider === "agentmail" &&
}
+{activeTab === "access" && endpoint.provider !== "github" && endpoint.provider !== "agentmail" && (
toolsApi.getConnection(endpoint.connectionId!),
+ enabled: Boolean(endpoint.connectionId),
+ });
+ const agents = useQuery({
+ queryKey: queryKeys.agents.list(endpoint.companyId),
+ queryFn: () => agentsApi.list(endpoint.companyId),
+ });
+ if (!endpoint.connectionId || agents.isError || connection.isError) return (
+
+
Connection access could not be loaded.
+
{ void agents.refetch(); void connection.refetch(); }}>Try again
+
+ );
+ if (agents.isPending || connection.isPending) return Loading access…
;
+ const sourceId = connection.data.config?.credentialConnectionId;
+ const credentialId = typeof sourceId === "string" ? sourceId : endpoint.connectionId;
+ return
+ Access
+ {credentialId !== endpoint.connectionId && These settings apply to the saved AgentMail account and all inboxes using it.
}
+
+ ;
+}
+
function Settings({
endpointId,
endpoint,
@@ -744,10 +775,16 @@ function Conversations({
Conversations
- {rows.length === 0 ? (
+ {query.isPending ? Loading conversations…
: query.isError ? (
+
+
Conversations could not be loaded.
+
void query.refetch()}>Try again
+
+ ) : rows.length === 0 ? (
- No conversations yet. Address the agent in an enabled destination to
- start one.
+ {provider === "agentmail"
+ ? "No email conversations yet. Send an email to this agent’s address to start one."
+ : "No conversations yet. Address the agent in an enabled destination to start one."}
) : (
@@ -877,20 +914,25 @@ function Activity({
}),
});
const lifecycle = useMutation({
- mutationFn: (action: "pause" | "resume" | "remove") =>
- chatEndpointsApi.setup(endpointId, { action }),
+ mutationFn: async (action: "pause" | "resume" | "remove") =>
+ endpoint.provider === "agentmail"
+ ? emailApi.control(endpointId, action)
+ : chatEndpointsApi.setup(endpointId, { action }),
onSuccess: async (next, action) => {
await queryClient.invalidateQueries({
queryKey: queryKeys.chatEndpoints.list(next.companyId),
});
+ if (endpoint.provider === "agentmail") {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["email-inboxes", next.companyId] }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.chatEndpoints.detail(endpointId) }),
+ ]);
+ }
if (action === "remove") {
navigate("/apps");
return;
}
- queryClient.setQueryData(
- queryKeys.chatEndpoints.detail(endpointId),
- next,
- );
+ if (endpoint.provider !== "agentmail") queryClient.setQueryData(queryKeys.chatEndpoints.detail(endpointId), next);
pushToast({
title: action === "pause" ? "Connection paused" : "Connection resumed",
tone: "success",
@@ -1034,7 +1076,9 @@ function Activity({
disabled={lifecycle.isPending}
onClick={() =>
navigate(
- `/apps/chat/connect?provider=${endpoint.provider}&purpose=chat&resume=${endpoint.id}${status === "draft" || status === "verifying" ? "" : "&reconnect=1"}`,
+ endpoint.provider === "agentmail" && status !== "draft" && status !== "verifying"
+ ? `/apps/chat/${endpoint.id}/settings`
+ : `/apps/chat/connect?provider=${endpoint.provider}&purpose=chat&resume=${endpoint.id}${status === "draft" || status === "verifying" ? "" : "&reconnect=1"}`,
)
}
>
@@ -1067,6 +1111,12 @@ function Activity({
Recent activity
+ {endpoint.provider === "agentmail" && rows.some((item) => item.kind === "publication" && item.status === "delivery_unknown") && (
+
+ Review unconfirmed email delivery in the{" "}
+ conversation’s task.
+
+ )}
{query.isLoading && (
@@ -1122,7 +1172,7 @@ function Activity({
)}
- {isReplayEligible(item) && (
+ {endpoint.provider !== "agentmail" && isReplayEligible(item) && (
)}
- {isResolutionEligible(item) && (
+ {endpoint.provider !== "agentmail" && isResolutionEligible(item) && (
({ companyId: "company" as string | null, listAgents: vi.fn(), connect: vi.fn(), credentials: vi.fn(), control: vi.fn(), inspectNew: vi.fn(), inspect: vi.fn(), checkAddress: vi.fn(), setup: vi.fn(), listInboxes: vi.fn(), listConnections: vi.fn(), getConnection: vi.fn(), putInstalls: vi.fn() }));
+vi.mock("@/lib/router", async () => import("react-router-dom"));
+vi.mock("@/context/CompanyContext", () => ({ useCompany: () => ({ selectedCompanyId: mocks.companyId }) }));
+vi.mock("@/components/chat/ChatSetupNavigation", () => ({ ChatSetupNavigation: () => null }));
+vi.mock("@/api/agents", () => ({ agentsApi: { list: mocks.listAgents } }));
+vi.mock("@/api/tools", () => ({ toolsApi: { putConnectionInstalls: mocks.putInstalls, listConnections: mocks.listConnections, getConnection: mocks.getConnection } }));
+vi.mock("@/api/email", () => ({ emailApi: { credentials: mocks.credentials, control: mocks.control, inspect: mocks.inspectNew, connect: mocks.connect, inspectSaved: mocks.inspect, checkAddress: mocks.checkAddress, setup: mocks.setup, list: mocks.listInboxes } }));
+
+let container: HTMLDivElement;
+let root: Root;
+let client: QueryClient;
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} });
+ mocks.companyId = "company";
+ sessionStorage.clear();
+ mocks.listAgents.mockResolvedValue([{ id: "ralph", name: "Ralph", status: "idle", permissions: {} }]);
+ mocks.credentials.mockResolvedValue([]);
+ mocks.inspectNew.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [], domains: [] });
+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [], domains: [] });
+ mocks.checkAddress.mockImplementation(async (_company, _connection, { username, domain }) => ({ address: `${username}@${domain}`, status: "unknown" }));
+ mocks.listInboxes.mockResolvedValue([]);
+ mocks.listConnections.mockResolvedValue({ connections: [] });
+ mocks.connect.mockResolvedValue({ id: "account" });
+ mocks.setup.mockResolvedValue({ id: "endpoint", address: "ralph-team@agentmail.to", connectionId: "inbox" });
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+afterEach(async () => {
+ await act(async () => root.unmount());
+ client?.clear();
+ container.remove();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+function Location() { const location = useLocation(); return {location.pathname} ; }
+async function mount(saved = true, waitForCompany = true, agentId = "ralph", search = "") {
+ client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
+ await act(async () => root.render( ));
+ if (waitForCompany) await vi.waitFor(() => expect(container.textContent).toContain(agentId === "support" ? "Support" : "Ralph"));
+}
+function button(name: string) {
+ const value = [...document.querySelectorAll("button")].find(button => button.textContent?.trim() === name);
+ expect(value).toBeDefined();
+ return value!;
+}
+async function click(name: string) {
+ if (name === "Create email address") await vi.waitFor(() => expect(button(name).disabled).toBe(false));
+ await act(async () => button(name).click());
+}
+async function fill(selector: string, value: string) {
+ await act(async () => {
+ const input = document.querySelector(selector)!;
+ expect(input).not.toBeNull();
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+describe("AgentMail two-step setup", () => {
+ it("starts a fresh catalog connection without adopting a previous draft's key or email step", async () => {
+ sessionStorage.setItem("paperclip.agentmail-setup:company:new:ralph", JSON.stringify({
+ connectionId: "old-inbox-key", step: 1, agentId: "ralph", requestId: crypto.randomUUID(),
+ addressMode: "existing", inboxId: "locked@agentmail.to",
+ }));
+ const setupId = crypto.randomUUID();
+ await mount(false, true, "ralph", `&setupId=${setupId}`);
+ expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ expect(mocks.inspect).not.toHaveBeenCalled();
+ await fill('input[type="password"]', "organization-test-key");
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());
+ expect(mocks.connect).toHaveBeenCalledWith("company", expect.objectContaining({ idempotencyKey: setupId }));
+ expect(container.textContent).toContain("How it Works");
+ expect(container.querySelector('[data-testid="location"]')?.textContent).toBe("/apps/chat/connect");
+ });
+
+ it("resumes the catalog's exact reserved inbox with its original account and request ID", async () => {
+ const requestId = crypto.randomUUID();
+ mocks.listInboxes.mockResolvedValue([{
+ id: requestId, connectionId: "inbox-connection", assignedAgentId: "ralph",
+ address: "reserved@paperclip.example", status: "draft", receiveMode: "websocket",
+ }]);
+ mocks.getConnection.mockResolvedValue({ config: { credentialConnectionId: "original-account" } });
+ await mount(false, true, "", `&resume=${requestId}`);
+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));
+ expect(mocks.inspect).toHaveBeenCalledWith("company", "original-account");
+ expect(container.textContent).toContain("reserved@paperclip.example");
+ expect(container.querySelector("#email-name")).toBeNull();
+ await click("Finish connecting");
+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({
+ idempotencyKey: requestId, credentialConnectionId: "original-account", inboxId: "reserved@paperclip.example",
+ }));
+ expect(mocks.connect).not.toHaveBeenCalled();
+ });
+
+ it("blocks a missing resume target rather than creating another inbox", async () => {
+ await mount(false, true, "ralph", `&resume=${crypto.randomUUID()}`);
+ await vi.waitFor(() => expect(container.textContent).toContain("This email setup could not be found"));
+ expect(button("Create email address").disabled).toBe(true);
+ expect(mocks.connect).not.toHaveBeenCalled();
+ expect(mocks.setup).not.toHaveBeenCalled();
+ });
+
+ it("honors Finish setup when an older client saved a replacement under the original resume key", async () => {
+ const requestId = crypto.randomUUID();
+ sessionStorage.setItem(`paperclip.agentmail-setup:company:${requestId}:ralph`, JSON.stringify({
+ connectionId: "wrong-account", agentId: "someone-else", requestId: crypto.randomUUID(), username: "replacement",
+ }));
+ mocks.listInboxes.mockResolvedValue([{ id: requestId, connectionId: "original-inbox", assignedAgentId: "ralph", address: "original@agentmail.to", status: "draft", receiveMode: "websocket" }]);
+ mocks.getConnection.mockResolvedValue({ config: { credentialConnectionId: "original-account" } });
+ await mount(false, true, "ralph", `&resume=${requestId}`);
+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));
+ await click("Finish connecting");
+ expect(mocks.setup).toHaveBeenLastCalledWith("company", expect.objectContaining({
+ credentialConnectionId: "original-account", inboxId: "original@agentmail.to", assignedAgentId: "ralph", idempotencyKey: requestId,
+ }));
+ });
+
+ it("returns Cancel to Connectors rather than the credential permissions page", async () => {
+ await mount();
+ await click("Cancel");
+ expect(container.querySelector('[data-testid="location"]')?.textContent).toBe("/apps");
+ });
+
+ it.each(["Done", "Email settings"])("sends %s to its email destination after completion", async action => {
+ await mount();
+ await click("Continue");
+ await click("Create email address");
+ await vi.waitFor(() => expect(container.textContent).toContain("Your agent’s email is ready"));
+ await click(action);
+ expect(container.querySelector('[data-testid="location"]')?.textContent)
+ .toBe(action === "Done" ? "/apps" : "/apps/chat/endpoint/settings");
+ });
+
+ it("suggests an accessible account key and opens the editable email form without saving another secret", async () => {
+ mocks.credentials.mockResolvedValue([
+ { id: "inbox-key", label: "Inbox key", scope: "inbox", createdAt: "2026-10-01T14:00:00Z" },
+ { id: "organization-account", label: "AgentMail account key", scope: "organization", createdAt: "2026-09-30T14:00:00Z" },
+ ]);
+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [],
+ domains: [{ domain: "paperclip.example", status: "VERIFIED" }] });
+ await mount(false);
+ await vi.waitFor(() => expect(container.querySelector("select")?.value).toBe("organization-account"));
+ expect(container.querySelector('input[type="password"]')).toBeNull();
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-domain")?.value).toBe("paperclip.example"));
+ await fill("#email-name", "ralph-mail");
+ await click("Create email address");
+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({
+ credentialConnectionId: "organization-account", username: "ralph-mail", domain: "paperclip.example",
+ }));
+ expect(mocks.connect).not.toHaveBeenCalled();
+ expect(mocks.putInstalls).not.toHaveBeenCalled();
+ });
+
+ it.each(["alternate", ""])("preserves the selected key choice across refresh (%s)", async selection => {
+ mocks.credentials.mockResolvedValue([
+ { id: "preferred", label: "Preferred account", scope: "organization", createdAt: "2026-10-01T14:00:00Z" },
+ { id: "alternate", label: "Other account", scope: "organization", createdAt: "2026-09-30T14:00:00Z" },
+ ]);
+ await mount(false);
+ await vi.waitFor(() => expect(container.querySelector("select")?.value).toBe("preferred"));
+ await act(async () => {
+ const picker = container.querySelector("select")!;
+ picker.value = selection; picker.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ await act(async () => root.unmount()); client.clear(); root = createRoot(container);
+ await mount(false);
+ await vi.waitFor(() => expect(container.querySelector("select")?.value).toBe(selection));
+ if (!selection) expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ else {
+ await click("Continue");
+ await vi.waitFor(() => expect(mocks.inspect).toHaveBeenCalledWith("company", "alternate"));
+ }
+ });
+
+ it("does not replace a newly entered key when saved-key discovery finishes later", async () => {
+ let resolve!: (options: unknown[]) => void;
+ mocks.credentials.mockReturnValue(new Promise(value => { resolve = value; }));
+ await mount(false);
+ await fill('input[type="password"]', "new-account-key");
+ await act(async () => resolve([{ id: "saved", label: "AgentMail account key", scope: "organization", createdAt: "2026-10-01T14:00:00Z" }]));
+ await vi.waitFor(() => expect(container.querySelector("select")).not.toBeNull());
+ expect(container.querySelector("select")?.value).toBe("");
+ expect(container.querySelector('input[type="password"]')?.value).toBe("new-account-key");
+ await click("Continue");
+ await vi.waitFor(() => expect(mocks.connect).toHaveBeenCalledWith("company", expect.objectContaining({ apiKey: "new-account-key" })));
+ });
+
+ it("catches a pasted inbox key before the email step and requires an explicit existing-inbox choice", async () => {
+ mocks.inspectNew.mockResolvedValue({ scope: { scope_type: "inbox" }, inboxes: [{ inbox_id: "locked@agentmail.to" }], domains: [] });
+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "inbox" }, inboxes: [{ inbox_id: "locked@agentmail.to" }], domains: [] });
+ await mount(false);
+ await fill('input[type="password"]', "inbox-secret");
+ await click("Continue");
+ await vi.waitFor(() => expect(container.textContent).toContain("That key only connects locked@agentmail.to"));
+ expect(container.querySelector("#email-existing")).toBeNull();
+ expect(mocks.connect).not.toHaveBeenCalled();
+ await click("Use the existing inbox instead");
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-existing")).not.toBeNull());
+ await click("Connect email address");
+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ inboxId: "locked@agentmail.to" }));
+ });
+
+ it("keeps an already reserved inbox tied to its original account", async () => {
+ const requestId = crypto.randomUUID();
+ sessionStorage.setItem("paperclip.agentmail-setup:company:account:ralph", JSON.stringify({
+ connectionId: "account", agentId: "ralph", step: 1, requestId,
+ }));
+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "inbox" }, inboxes: [{ inbox_id: "locked@agentmail.to" }], domains: [] });
+ mocks.listInboxes.mockResolvedValue([{ id: requestId, assignedAgentId: "ralph", address: "locked@agentmail.to", status: "error" }]);
+ await mount();
+ await vi.waitFor(() => expect(container.textContent).toContain("This address was created in AgentMail"));
+ expect(container.textContent).not.toContain("Change AgentMail account");
+ await click("Finish connecting");
+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({
+ credentialConnectionId: "account", idempotencyKey: requestId, inboxId: "locked@agentmail.to",
+ })));
+ });
+
+ it("recovers an old locked draft at the key choice, with a new setup identity", async () => {
+ const originalRequestId = crypto.randomUUID();
+ const draftKey = "paperclip.agentmail-setup:company:account:ralph";
+ sessionStorage.setItem(draftKey, JSON.stringify({ connectionId: "account", agentId: "ralph", step: 1, requestId: originalRequestId }));
+ mocks.inspect.mockImplementation(async (_company, id) => ({
+ scope: { scope_type: id === "account" ? "inbox" : "organization" },
+ inboxes: [{ inbox_id: "locked@agentmail.to" }], domains: [],
+ }));
+ mocks.connect.mockResolvedValue({ id: "replacement-account" });
+ await mount();
+ await vi.waitFor(() => expect(container.textContent).toContain("That key only connects"));
+ await fill('input[type="password"]', "replacement-secret");
+ expect(sessionStorage.getItem(draftKey)).not.toContain("replacement-secret");
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());
+ const replacementRequest = mocks.connect.mock.calls[0][1];
+ expect(replacementRequest).toMatchObject({ apiKey: "replacement-secret", agentIds: ["ralph"], grantKind: "organization", allAgents: false });
+ expect(replacementRequest.idempotencyKey).not.toBe(originalRequestId);
+ const nextSearch = container.querySelector('[data-testid="location"]')!.getAttribute("data-search")!;
+ await act(async () => root.unmount());
+ client.clear(); root = createRoot(container);
+ await mount(false, true, "ralph", nextSearch.replace(/^\?/, "&"));
+ await click("Create email address");
+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({
+ credentialConnectionId: "replacement-account", idempotencyKey: replacementRequest.idempotencyKey, username: "ralph",
+ })));
+ expect(mocks.connect).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([false, true])("preserves an account switch from a resumed unallocated draft across refresh (%s cleanup failure)", async cleanupFails => {
+ const requestId = crypto.randomUUID();
+ const draftKey = `paperclip.agentmail-setup:company:${requestId}:ralph`;
+ sessionStorage.setItem(draftKey, JSON.stringify({
+ connectionId: "account", agentId: "ralph", step: 1, requestId,
+ }));
+ mocks.listInboxes.mockResolvedValue([{ id: requestId, assignedAgentId: "ralph", address: null, status: "draft" }]);
+ mocks.inspect.mockImplementation(async (_company, id) => ({ scope: { scope_type: id === "account" ? "inbox" : "organization" }, inboxes: [{ inbox_id: "locked@agentmail.to" }], domains: [] }));
+ mocks.connect.mockResolvedValue({ id: "replacement" });
+ mocks.control.mockImplementation(async () => {
+ if (cleanupFails) throw new Error("Draft cleanup failed");
+ mocks.listInboxes.mockResolvedValue([]);
+ });
+ await mount(true, true, "ralph", `&resume=${requestId}`);
+ await vi.waitFor(() => expect(container.textContent).toContain("That key only connects"));
+ await fill('input[type="password"]', "new-account-key");
+ await click("Continue");
+ await vi.waitFor(() => expect(mocks.control).toHaveBeenCalledWith(requestId, "remove"));
+ if (cleanupFails) {
+ await vi.waitFor(() => expect(container.textContent).toContain("Draft cleanup failed"));
+ expect(mocks.connect).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(sessionStorage.getItem(draftKey)!).requestId).toBe(requestId);
+ expect(container.querySelector('[data-testid="location"]')!.getAttribute("data-search")).toContain(`resume=${requestId}`);
+ return;
+ }
+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());
+ expect(mocks.connect.mock.invocationCallOrder[0]).toBeLessThan(mocks.control.mock.invocationCallOrder[0]);
+ const nextSearch = container.querySelector('[data-testid="location"]')!.getAttribute("data-search")!;
+ const nextId = new URLSearchParams(nextSearch).get("setupId")!;
+ expect(nextId).not.toBe(requestId);
+ expect(nextSearch).not.toContain("resume=");
+ await act(async () => root.unmount());
+ client.clear(); root = createRoot(container);
+ await mount(false, true, "ralph", nextSearch.replace(/^\?/, "&"));
+ await click("Create email address");
+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ credentialConnectionId: "replacement", idempotencyKey: nextId, username: "ralph" }));
+ });
+
+ it("checks the initial address and debounces edits while ignoring stale responses", async () => {
+ await mount();
+ vi.useFakeTimers();
+ await click("Continue");
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(container.textContent).toContain("Checking address");
+ expect(button("Create email address").disabled).toBe(true);
+ await act(async () => { await vi.advanceTimersByTimeAsync(350); });
+ expect(mocks.checkAddress).toHaveBeenLastCalledWith("company", "account", { username: "ralph", domain: "agentmail.to" }, expect.any(AbortSignal));
+ let resolveOld!: (result: unknown) => void;
+ mocks.checkAddress.mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; }));
+ await fill("#email-name", "ralph-old");
+ await act(async () => { await vi.advanceTimersByTimeAsync(350); });
+ const oldSignal = mocks.checkAddress.mock.calls[1][3] as AbortSignal;
+ await fill("#email-name", "ralph-n");
+ await act(async () => { await vi.advanceTimersByTimeAsync(200); });
+ await fill("#email-name", "ralph-new");
+ expect(oldSignal.aborted).toBe(true);
+ await act(async () => { resolveOld({ address: "ralph-old@agentmail.to", status: "taken" }); });
+ expect(container.querySelector("#email-address-error")).toBeNull();
+ await act(async () => { await vi.advanceTimersByTimeAsync(349); });
+ expect(mocks.checkAddress).toHaveBeenCalledTimes(2);
+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });
+ expect(mocks.checkAddress).toHaveBeenCalledTimes(3);
+ expect(mocks.checkAddress.mock.calls[2][2].username).toBe("ralph-new");
+ expect(container.textContent).toContain("confirms availability when you create");
+ expect(container.textContent).not.toContain("is available");
+ });
+
+ it("offers clickable alternatives for a taken initial address and checks the selection", async () => {
+ mocks.checkAddress.mockResolvedValueOnce({ address: "ralph@agentmail.to", status: "taken" });
+ await mount();
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-address-error")?.textContent).toContain("already in use"));
+ expect(button("Create email address").disabled).toBe(true);
+ await click("ralph-agent@agentmail.to");
+ expect(container.querySelector("#email-name")?.value).toBe("ralph-agent");
+ expect(container.querySelector("#email-address-error")).toBeNull();
+ await vi.waitFor(() => expect(mocks.checkAddress).toHaveBeenLastCalledWith("company", "account", { username: "ralph-agent", domain: "agentmail.to" }, expect.any(AbortSignal)));
+ expect(mocks.setup).not.toHaveBeenCalled();
+ });
+
+ it("defaults to a verified custom domain beside the name and preserves an explicit selection on reload", async () => {
+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [], domains: [
+ { domain_id: "pending", domain: "pending.example", status: "PENDING" },
+ { domain_id: "custom", domain: "paperclip.example", status: "VERIFIED" },
+ ] });
+ await mount();
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-domain")?.value).toBe("paperclip.example"));
+ expect(container.querySelector("#email-domain")?.closest("details")).toBeNull();
+ expect(container.querySelector('option[value="pending.example"]')).toBeNull();
+ await act(async () => {
+ const select = container.querySelector("#email-domain")!;
+ select.value = "agentmail.to";
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ await vi.waitFor(() => expect(mocks.checkAddress).toHaveBeenLastCalledWith("company", "account", { username: "ralph", domain: "agentmail.to" }, expect.any(AbortSignal)));
+ await act(async () => root.unmount());
+ client.clear();
+ root = createRoot(container);
+ await mount();
+ await vi.waitFor(() => expect(container.querySelector("#email-domain")?.value).toBe("agentmail.to"));
+ });
+
+ it("shows lookup failures without mislabeling the address taken or blocking creation", async () => {
+ mocks.checkAddress.mockRejectedValue(new Error("AgentMail is rate limiting requests."));
+ await mount();
+ await click("Continue");
+ await vi.waitFor(() => expect(container.textContent).toContain("Could not check this address"));
+ expect(container.querySelector("#email-address-error")).toBeNull();
+ expect(button("Create email address").disabled).toBe(false);
+ });
+ it("restores saved progress after the company loads without overwriting the draft", async () => {
+ const key = "paperclip.agentmail-setup:company:account:ralph";
+ const requestId = crypto.randomUUID();
+ const draft = JSON.stringify({ connectionId: "account", step: 1, agentId: "ralph", username: "ralph-team", requestId });
+ sessionStorage.setItem(key, draft);
+ mocks.companyId = null;
+ await mount(true, false);
+ expect(container.textContent).toContain("Loading email setup");
+ expect(sessionStorage.getItem(key)).toBe(draft);
+ mocks.companyId = "company";
+ await mount();
+ await vi.waitFor(() => expect(container.querySelector("#email-name")?.value).toBe("ralph-team"));
+ await click("Create email address");
+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ username: "ralph-team", idempotencyKey: requestId })));
+ });
+
+ it("creates from the email field without a review step and keeps advanced settings collapsed", async () => {
+ await mount();
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-name")?.value).toBe("ralph"));
+ expect(container.querySelector("details")?.open).toBe(false);
+ expect(container.textContent).not.toContain("Review email address");
+ await click("Create email address");
+ await vi.waitFor(() => expect(container.textContent).toContain("Your agent’s email is ready"));
+ expect(mocks.connect).not.toHaveBeenCalled();
+ expect(mocks.putInstalls).not.toHaveBeenCalled();
+ expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ assignedAgentId: "ralph", username: "ralph", domain: "agentmail.to", receiveMode: "websocket" }));
+ expect(sessionStorage.getItem("paperclip.agentmail-setup:company:account:ralph")).toBeNull();
+ });
+
+ it("shows a taken address beside the field, clears it on editing, and resumes the same request after reload", async () => {
+ mocks.setup.mockRejectedValueOnce(new ApiError("This email address is already in use. Choose a different address.", 409, { code: "agentmail_address_taken" }));
+ await mount();
+ await click("Continue");
+ await click("Create email address");
+ await vi.waitFor(() => expect(container.querySelector("#email-name")?.getAttribute("aria-invalid")).toBe("true"));
+ expect(container.querySelector("#email-address-error")?.textContent).toContain("already in use");
+ expect(button("Create email address").disabled).toBe(true);
+ const firstRequest = mocks.setup.mock.calls[0][1];
+ await fill("#email-name", "");
+ expect(container.querySelector("#email-name")?.value).toBe("");
+ await fill("#email-name", "ralph-team");
+ expect(container.querySelector("#email-address-error")).toBeNull();
+ await act(async () => root.unmount());
+ client.clear();
+ root = createRoot(container);
+ await mount();
+ await vi.waitFor(() => expect(container.querySelector("#email-name")?.value).toBe("ralph-team"));
+ await click("Create email address");
+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledTimes(2));
+ expect(mocks.setup.mock.calls[1][1]).toMatchObject({ username: "ralph-team", idempotencyKey: firstRequest.idempotencyKey });
+ });
+
+ it("asks for one API key with the direct link and saves the requested access defaults", async () => {
+ await mount(false);
+ expect(container.querySelector('a[href="https://console.agentmail.to/dashboard/api-keys"]')).not.toBeNull();
+ expect(container.querySelectorAll('input[type="password"]')).toHaveLength(1);
+ expect(container.querySelectorAll('input[type="radio"]')).toHaveLength(0);
+ await fill('input[type="password"]', "private-test-key");
+ expect(sessionStorage.getItem("paperclip.agentmail-setup:company:new:ralph")).not.toContain("private-test-key");
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());
+ expect(mocks.connect).toHaveBeenCalledWith("company", expect.objectContaining({ apiKey: "private-test-key", grantKind: "organization", allAgents: false, agentIds: ["ralph"] }));
+ expect(container.querySelector('input[type="password"]')).toBeNull();
+ expect(sessionStorage.getItem("paperclip.agentmail-setup:company:new:ralph")).not.toContain("private-test-key");
+ });
+
+ it("flags an address already present in the connected account before submission", async () => {
+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [{ inbox_id: "ralph@agentmail.to" }], domains: [] });
+ await mount();
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-address-error")?.textContent).toContain("already in use"));
+ expect(button("Create email address").disabled).toBe(true);
+ expect(mocks.setup).not.toHaveBeenCalled();
+ await click("Use an existing inbox");
+ expect(container.querySelector("#email-existing")).not.toBeNull();
+ });
+
+ it("does not restore another requested agent's new-account draft", async () => {
+ sessionStorage.setItem("paperclip.agentmail-setup:company:new:ralph", JSON.stringify({
+ agentId: "ralph", step: 1, connectionId: "ralph-account", username: "ralph", requestId: crypto.randomUUID(),
+ }));
+ mocks.listAgents.mockResolvedValue([
+ { id: "ralph", name: "Ralph", status: "idle", permissions: {} },
+ { id: "support", name: "Support", status: "idle", permissions: {} },
+ ]);
+ await mount(false, true, "support");
+ expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ await fill('input[type="password"]', "new-key");
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-name")?.value).toBe("support"));
+ expect(mocks.connect).toHaveBeenCalledWith("company", expect.objectContaining({ agentIds: ["support"] }));
+ expect(mocks.inspect).not.toHaveBeenCalledWith("company", "ralph-account");
+ });
+
+ it("submits the final agent with the original setup request after changing agents and reloading", async () => {
+ mocks.listAgents.mockResolvedValue([
+ { id: "ralph", name: "Ralph", status: "idle", permissions: {} },
+ { id: "support", name: "Support", status: "idle", permissions: {} },
+ ]);
+ await mount(false);
+ await fill('input[type="password"]', "new-key");
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());
+ await click("Back");
+ await act(async () => container.querySelector('#email-agent')!.click());
+ await vi.waitFor(() => expect(document.querySelector('[aria-label="Select Support"]')).not.toBeNull());
+ await act(async () => document.querySelector('[aria-label="Select Support"]')!.click());
+ await act(async () => root.unmount());
+ client.clear();
+ root = createRoot(container);
+ await mount(false, false);
+ await vi.waitFor(() => expect(button("Continue").disabled).toBe(false));
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-name")?.value).toBe("support"));
+ // Access is updated by email setup, without a separate agent-config permission.
+ expect(mocks.putInstalls).not.toHaveBeenCalled();
+ expect(mocks.connect).toHaveBeenCalledTimes(1);
+ await click("Create email address");
+ await vi.waitFor(() => expect(mocks.setup).toHaveBeenCalledWith("company", expect.objectContaining({ assignedAgentId: "support", idempotencyKey: mocks.connect.mock.calls[0][1].idempotencyKey })));
+ });
+
+ it.each(["new", "existing"])("resumes its allocated %s inbox after a provider failure and reload", async addressMode => {
+ const requestId = crypto.randomUUID();
+ sessionStorage.setItem("paperclip.agentmail-setup:company:account:ralph", JSON.stringify({
+ connectionId: "account", agentId: "ralph", step: 1, username: "ralph", inboxId: "ralph@agentmail.to", addressMode, requestId,
+ }));
+ const endpoint = { id: requestId, assignedAgentId: "ralph", address: "ralph@agentmail.to", status: "draft" };
+ // Creation succeeds before a later runtime-key request fails.
+ mocks.setup.mockImplementationOnce(async () => {
+ mocks.listInboxes.mockResolvedValue([endpoint]);
+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [{ inbox_id: endpoint.address }], domains: [] });
+ throw new ApiError("Could not create runtime key", 502, {});
+ });
+ await mount();
+ await vi.waitFor(() => expect(button(addressMode === "new" ? "Create email address" : "Connect email address").disabled).toBe(false));
+ await click(addressMode === "new" ? "Create email address" : "Connect email address");
+ await vi.waitFor(() => expect(container.textContent).toContain("Could not create runtime key"));
+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));
+ await act(async () => root.unmount());
+ client.clear();
+ root = createRoot(container);
+ await mount();
+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));
+ expect(container.querySelector("#email-address-error")).toBeNull();
+ expect(container.textContent).toContain(endpoint.address);
+ expect(container.querySelector("#email-name")).toBeNull();
+ expect(container.querySelector("#email-existing")).toBeNull();
+ await click("Back");
+ expect(container.querySelector('#email-agent')?.disabled).toBe(true);
+ await click("Continue");
+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));
+ await click("Finish connecting");
+ await vi.waitFor(() => expect(container.textContent).toContain("Your agent’s email is ready"));
+ expect(mocks.setup).toHaveBeenLastCalledWith("company", expect.objectContaining({ inboxId: endpoint.address, assignedAgentId: "ralph", idempotencyKey: requestId }));
+ });
+
+ it("lets a failed setup choose another address without deleting or reusing its allocated inbox", async () => {
+ const requestId = crypto.randomUUID();
+ const draftKey = `paperclip.agentmail-setup:company:${requestId}:ralph`;
+ sessionStorage.setItem(draftKey, JSON.stringify({ connectionId: "account", agentId: "ralph", step: 1, requestId }));
+ mocks.listInboxes.mockResolvedValue([{ id: requestId, assignedAgentId: "ralph", address: "reserved@paperclip.example", status: "draft" }]);
+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [{ inbox_id: "reserved@paperclip.example" }], domains: [{ domain_id: "custom", domain: "paperclip.example", status: "VERIFIED" }] });
+ await mount(true, true, "ralph", `&resume=${requestId}`);
+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));
+ await click("Choose a different address");
+ expect(container.querySelector("#email-name")?.readOnly).toBe(false);
+ expect(container.querySelector("#email-domain")?.disabled).toBe(false);
+ expect(container.querySelector("#email-domain")?.value).toBe("paperclip.example");
+ await fill("#email-name", "another-address");
+ const nextSearch = container.querySelector('[data-testid="location"]')!.getAttribute("data-search")!;
+ const nextRequestId = new URLSearchParams(nextSearch).get("setupId")!;
+ expect(nextRequestId).not.toBe(requestId);
+ expect(JSON.parse(sessionStorage.getItem(draftKey)!).requestId).toBe(requestId);
+ await act(async () => root.unmount());
+ client.clear();
+ root = createRoot(container);
+ await mount(true, true, "ralph", `&setupId=${nextRequestId}`);
+ await click("Create email address");
+ expect(mocks.setup).toHaveBeenLastCalledWith("company", expect.objectContaining({
+ username: "another-address", domain: "paperclip.example", idempotencyKey: nextRequestId,
+ }));
+ expect(mocks.control).not.toHaveBeenCalled();
+ await act(async () => root.unmount());
+ client.clear();
+ root = createRoot(container);
+ await mount(true, true, "ralph", `&resume=${requestId}`);
+ await vi.waitFor(() => expect(button("Finish connecting").disabled).toBe(false));
+ await click("Finish connecting");
+ expect(mocks.setup).toHaveBeenLastCalledWith("company", expect.objectContaining({
+ inboxId: "reserved@paperclip.example", idempotencyKey: requestId,
+ }));
+ });
+
+ it("does not treat another setup's allocated address as its own retry", async () => {
+ mocks.inspect.mockResolvedValue({ scope: { scope_type: "organization" }, inboxes: [{ inbox_id: "ralph@agentmail.to" }], domains: [] });
+ mocks.listInboxes.mockResolvedValue([{ id: crypto.randomUUID(), assignedAgentId: "ralph", address: "ralph@agentmail.to", status: "draft" }]);
+ await mount();
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-address-error")?.textContent).toContain("already in use"));
+ expect(button("Create email address").disabled).toBe(true);
+ await click("Use an existing inbox");
+ const option = container.querySelector('option[value="ralph@agentmail.to"]');
+ expect(option?.disabled).toBe(true);
+ expect(mocks.setup).not.toHaveBeenCalled();
+ });
+
+ it("retries loading setup progress without losing the entered key or reloading", async () => {
+ mocks.listInboxes.mockRejectedValueOnce(new Error("Service unavailable"));
+ await mount(false);
+ await fill('input[type="password"]', "private-test-key");
+ await vi.waitFor(() => expect(container.textContent).toContain("Could not load email setup progress"));
+ expect(button("Continue").disabled).toBe(true);
+ await click("Retry loading inboxes");
+ await vi.waitFor(() => expect(button("Continue").disabled).toBe(false));
+ expect(container.querySelector('input[type="password"]')?.value).toBe("private-test-key");
+ await click("Continue");
+ await vi.waitFor(() => expect(container.querySelector("#email-name")).not.toBeNull());
+ expect(mocks.listInboxes).toHaveBeenCalledTimes(2);
+ expect(mocks.putInstalls).not.toHaveBeenCalled();
+ });
+
+ it("preserves the existing low-trust work-boundary gate", async () => {
+ mocks.listAgents.mockResolvedValue([{ id: "ralph", name: "Ralph", status: "idle", permissions: { trustPreset: "low_trust_review" } }]);
+ await mount();
+ expect(container.textContent).toContain("needs a work boundary");
+ expect(button("Continue").disabled).toBe(true);
+ expect(mocks.setup).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/pages/apps/chat/EmailEndpointSetup.tsx b/ui/src/pages/apps/chat/EmailEndpointSetup.tsx
index 527d140313f..a1d16547893 100644
--- a/ui/src/pages/apps/chat/EmailEndpointSetup.tsx
+++ b/ui/src/pages/apps/chat/EmailEndpointSetup.tsx
@@ -1,11 +1,17 @@
+import { isUuidLike } from "@paperclipai/shared";
+import { ApiError } from "@/api/client";
+import { AgentMailCredentialField } from "@/features/connections/AgentMailCredentialField";
+import { AgentMailApiKeyField } from "@/features/connections/AgentMailApiKeyField";
+import { useEmailAddressCheck } from "@/features/connections/useEmailAddressCheck";
import { ChatSetupNavigation } from "@/components/chat/ChatSetupNavigation";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
ArrowLeft,
ArrowRight,
Check,
- AlertTriangle,
+ Copy,
+ ExternalLink,
Mail,
} from "lucide-react";
import { useCompany } from "@/context/CompanyContext";
@@ -18,11 +24,11 @@ import { emailApi } from "@/api/email";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-import { RadioCardGroup } from "@/components/ui/radio-card";
-import { Avatar, AvatarFallback } from "@/components/ui/avatar";
-import { AgentIcon } from "@/components/AgentIconPicker";
-import { SearchableSelect } from "@/components/SearchableSelect";
-import { AccessStep } from "@/features/connections/ConnectionSetupFlow";
+import { Card, CardHeader, CardDescription } from "@/components/ui/card";
+import { CopyText } from "@/components/CopyText";
+import { StatusBadge } from "@/components/StatusBadge";
+import { formatDateTime } from "@/lib/utils";
+import { AgentSelect } from "@/components/AgentMultiSelect";
import { TrustPresetSection } from "@/components/TrustPresetSection";
import { EmailSafetyNotice } from "@/components/EmailSafetyNotice";
import {
@@ -46,524 +52,399 @@ import type {
const selectClass =
"w-full rounded-md border border-input bg-background px-3 py-2 text-sm";
+interface EmailSetupDraft {
+ connectionId: string; step: 0 | 1; agentId: string; requestId: string;
+ addressMode: "new" | "existing"; inboxId: string; username: string; domain: string;
+ mode: "websocket" | "webhook";
+ domainSelected: boolean;
+ takenAddresses: string[];
+ allowInboxKey: boolean;
+ selectedCredentialId: string | null;
+}
+function readEmailSetupDraft(key: string): Partial {
+ try {
+ const value = JSON.parse(sessionStorage.getItem(key) ?? "{}");
+ if (!value || typeof value !== "object") return {};
+ const draft: Partial = {};
+ for (const field of ["connectionId", "agentId", "inboxId", "username", "domain"] as const) {
+ if (typeof value[field] === "string") draft[field] = value[field];
+ }
+ if (value.step === 0 || value.step === 1) draft.step = value.step;
+ if (typeof value.requestId === "string" && isUuidLike(value.requestId)) draft.requestId = value.requestId;
+ if (value.addressMode === "new" || value.addressMode === "existing") draft.addressMode = value.addressMode;
+ if (value.mode === "websocket" || value.mode === "webhook") draft.mode = value.mode;
+ if (value.selectedCredentialId === null || typeof value.selectedCredentialId === "string") draft.selectedCredentialId = value.selectedCredentialId;
+ if (typeof value.allowInboxKey === "boolean") draft.allowInboxKey = value.allowInboxKey;
+ if (typeof value.domainSelected === "boolean") draft.domainSelected = value.domainSelected;
+ if (Array.isArray(value.takenAddresses)) draft.takenAddresses = value.takenAddresses
+ .filter((address: unknown): address is string => typeof address === "string" && address.length <= 320).slice(-20);
+ return draft;
+ } catch { return {}; }
+}
+
export function EmailEndpointSetup() {
const { selectedCompanyId } = useCompany();
+ const [params] = useSearchParams();
+ if (!selectedCompanyId) return Loading email setup…
;
+ return ;
+}
+
+function EmailEndpointSetupForm({ companyId }: { companyId: string }) {
const [params] = useSearchParams();
const navigate = useNavigate();
const cache = useQueryClient();
- const companyId = selectedCompanyId ?? "";
- const [connectionId, setConnectionId] = useState(
- params.get("connectionId") ?? "",
- );
- const [step, setStep] = useState(params.get("connectionId") ? 3 : 0);
- const [agentId, setAgentId] = useState(params.get("agentId") ?? "");
- const [grantKind, setGrantKind] = useState<"user" | "organization" | "agent">(
- "user",
- );
- const [agentAccess, setAgentAccess] = useState<"specific" | "all">(
- "specific",
- );
- const [agentIds, setAgentIds] = useState>(
- new Set(params.get("agentId") ? [params.get("agentId")!] : []),
- );
+ const resumeId = params.get("resume");
+ const setupId = params.get("setupId");
+ const draftKey = `paperclip.agentmail-setup:${companyId}:${resumeId ?? setupId ?? params.get("connectionId") ?? "new"}:${params.get("agentId") ?? "choose"}`;
+ const [draft] = useState(() => {
+ const saved = readEmailSetupDraft(draftKey);
+ // A Finish setup link always names its original inbox, including when an
+ // older client accidentally stored a replacement under that resume key.
+ return resumeId && saved.requestId && saved.requestId !== resumeId ? {} : saved;
+ });
+ const [connectionId, setConnectionId] = useState(draft.connectionId ?? params.get("connectionId") ?? "");
+ const [step, setStep] = useState<0 | 1 | 2>(draft.step ?? (resumeId ? 1 : 0));
+ const [agentId, setAgentId] = useState(draft.agentId ?? params.get("agentId") ?? "");
const [apiKey, setApiKey] = useState("");
- const [requestId] = useState(() => crypto.randomUUID());
- const [addressMode, setAddressMode] = useState("new");
- const [inboxId, setInboxId] = useState("");
- const [username, setUsername] = useState("");
- const [domain, setDomain] = useState("agentmail.to");
- const [mode, setMode] = useState<"websocket" | "webhook">("websocket");
+ const [selectedCredentialId, setSelectedCredentialId] = useState(draft.selectedCredentialId !== undefined ? draft.selectedCredentialId : connectionId || null);
+ const [restrictedInbox, setRestrictedInbox] = useState("");
+ const [allowInboxKey, setAllowInboxKey] = useState(draft.allowInboxKey ?? false);
+ const [requestId] = useState(() => draft.requestId ?? resumeId ?? (setupId && isUuidLike(setupId) ? setupId : crypto.randomUUID()));
+ const [addressMode, setAddressMode] = useState<"new" | "existing">(draft.addressMode ?? "new");
+ const [inboxId, setInboxId] = useState(draft.inboxId ?? "");
+ const [username, setUsername] = useState(draft.username ?? "");
+ const [domain, setDomain] = useState(draft.domain ?? "agentmail.to");
+ const [domainSelected, setDomainSelected] = useState(draft.domainSelected ?? (!!draft.domain && draft.domain !== "agentmail.to"));
+ const [takenAddresses, setTakenAddresses] = useState(draft.takenAddresses ?? []);
+ const [mode, setMode] = useState<"websocket" | "webhook">(draft.mode ?? "websocket");
const [trustOpen, setTrustOpen] = useState(false);
const [permissions, setPermissions] = useState>({});
- const agents = useQuery({
- queryKey: queryKeys.agents.list(companyId),
- queryFn: () => agentsApi.list(companyId),
- enabled: !!companyId,
- });
- const projects = useQuery({
- queryKey: queryKeys.projects.list(companyId),
- queryFn: () => projectsApi.list(companyId),
- enabled: !!companyId && trustOpen,
- });
- const boundaryIssues = useQuery({
- queryKey: ["email-boundary-issues", companyId],
- queryFn: () => issuesApi.list(companyId),
- enabled: !!companyId && trustOpen,
- });
- const chosen = agents.data?.find((a) => a.id === agentId);
+ const suggestedUsername = useRef(false);
+ useEffect(() => {
+ if (!companyId) return;
+ // Save progress, never the API key. The same request ID resumes partial setup.
+ try {
+ if (step === 2) sessionStorage.removeItem(draftKey);
+ else sessionStorage.setItem(draftKey, JSON.stringify({ connectionId, step, agentId,
+ requestId, addressMode, inboxId, username, domain, domainSelected, takenAddresses, mode, allowInboxKey, selectedCredentialId }));
+ } catch { /* Setup remains usable when browser storage is unavailable. */ }
+ }, [companyId, draftKey, connectionId, step, agentId, requestId, addressMode, inboxId, username, domain, domainSelected, takenAddresses, mode, allowInboxKey, selectedCredentialId]);
+ const agents = useQuery({ queryKey: queryKeys.agents.list(companyId),
+ queryFn: () => agentsApi.list(companyId), enabled: !!companyId });
+ const projects = useQuery({ queryKey: queryKeys.projects.list(companyId),
+ queryFn: () => projectsApi.list(companyId), enabled: !!companyId && trustOpen });
+ const boundaryIssues = useQuery({ queryKey: ["email-boundary-issues", companyId],
+ queryFn: () => issuesApi.list(companyId), enabled: !!companyId && trustOpen });
+ const chosen = agents.data?.find(a => a.id === agentId);
const lowTrust = getTrustPreset(chosen?.permissions) === "low_trust_review";
- const scoped = lowTrustBoundaryHasScope(
- getLowTrustBoundary(chosen?.permissions),
- );
- const inspected = useQuery({
- queryKey: ["email-credential-inspect", companyId, connectionId],
+ const scoped = lowTrustBoundaryHasScope(getLowTrustBoundary(chosen?.permissions));
+ const inspected = useQuery({ queryKey: ["email-credential-inspect", companyId, connectionId],
queryFn: () => emailApi.inspectSaved(companyId, connectionId),
- enabled: !!companyId && !!connectionId && step >= 3,
+ enabled: !!companyId && !!connectionId, retry: false });
+ const inboxes = useQuery({ queryKey: ["email-inboxes", companyId],
+ queryFn: () => emailApi.list(companyId), enabled: !!companyId });
+ // A provider failure can leave an inbox allocated under this request. Resume
+ // that exact endpoint; its agent and address are already fixed server-side.
+ const pendingEndpoint = inboxes.data?.find(i => i.id === requestId && i.status !== "archived");
+ const pendingAddress = pendingEndpoint?.address;
+ const resumeAccount = useQuery({
+ queryKey: ["email-resume-account", companyId, pendingEndpoint?.connectionId],
+ queryFn: () => toolsApi.getConnection(pendingEndpoint!.connectionId),
+ enabled: !!resumeId && requestId === resumeId && !!pendingEndpoint && !connectionId,
retry: false,
});
- const inboxes = useQuery({
- queryKey: ["email-inboxes", companyId],
- queryFn: () => emailApi.list(companyId),
- enabled: !!companyId,
- });
- const scopedKey = inspected.data?.scope.scope_type === "inbox";
useEffect(() => {
- if (scopedKey) {
+ if (!resumeId || !pendingEndpoint || connectionId || !resumeAccount.isSuccess) return;
+ const savedAccount = resumeAccount.data?.config?.credentialConnectionId;
+ if (typeof savedAccount === "string") setConnectionId(savedAccount);
+ else setStep(0);
+ setMode(pendingEndpoint.receiveMode);
+ }, [resumeId, pendingEndpoint, connectionId, resumeAccount.isSuccess, resumeAccount.data]);
+ useEffect(() => {
+ if (pendingEndpoint) setAgentId(pendingEndpoint.assignedAgentId);
+ }, [pendingEndpoint]);
+ const scopedKey = inspected.data?.scope.scope_type === "inbox";
+ const customDomains = [...new Set(inspected.data?.domains
+ .filter(d => d.status === "VERIFIED" && d.domain.toLowerCase() !== "agentmail.to")
+ .map(d => d.domain.toLowerCase()) ?? [])];
+ const defaultDomain = customDomains[0] ?? "agentmail.to";
+ useEffect(() => {
+ if (inspected.isSuccess && !domainSelected && !pendingAddress) setDomain(defaultDomain);
+ }, [inspected.isSuccess, domainSelected, pendingAddress, defaultDomain]);
+ useEffect(() => {
+ if (!scopedKey || !inboxes.isSuccess) return;
+ if (pendingAddress || allowInboxKey) {
setAddressMode("existing");
setInboxId(inspected.data?.inboxes[0]?.inbox_id ?? "");
+ } else if (step === 1) {
+ // Old drafts must recover at the key choice, not return to a locked form.
+ setRestrictedInbox(inspected.data?.inboxes[0]?.inbox_id ?? "this inbox");
+ setSelectedCredentialId(null);
+ setStep(0);
}
- }, [scopedKey, inspected.data]);
+ }, [scopedKey, inspected.data, inboxes.isSuccess, pendingAddress, allowInboxKey, step]);
+ useEffect(() => {
+ if (chosen && !suggestedUsername.current) {
+ suggestedUsername.current = true;
+ if (!username) setUsername(chosen.name.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").slice(0, 64));
+ }
+ }, [chosen, username]);
const connect = useMutation({
- mutationFn: () =>
- emailApi.connect(companyId, {
- apiKey,
- grantKind: grantKind === "organization" ? "organization" : "user",
- allAgents: agentAccess === "all",
- agentIds: [...agentIds],
- idempotencyKey: requestId,
- }),
- onSuccess: (result) => {
+ mutationFn: async () => {
+ if (pendingAddress) return true;
+ const details = selectedCredentialId
+ ? await emailApi.inspectSaved(companyId, selectedCredentialId)
+ : await emailApi.inspect(companyId, apiKey.trim());
+ if (details.scope.scope_type === "inbox" && !allowInboxKey) {
+ setRestrictedInbox(details.inboxes[0]?.inbox_id ?? "this inbox");
+ return false;
+ }
+ const changingAccount = !!connectionId && selectedCredentialId !== connectionId;
+ const nextRequestId = changingAccount ? crypto.randomUUID() : requestId;
+ let id = selectedCredentialId;
+ if (!id) {
+ const result = await emailApi.connect(companyId, {
+ apiKey: apiKey.trim(), grantKind: "organization", allAgents: false,
+ agentIds: [agentId], idempotencyKey: nextRequestId,
+ });
+ id = result.id;
+ }
+ cache.setQueryData(["email-credential-inspect", companyId, id], details);
+ setSelectedCredentialId(id);
setApiKey("");
- setConnectionId(result.id);
- setStep(2);
- void cache.invalidateQueries({
- queryKey: queryKeys.tools.connections(companyId),
- });
+ void cache.invalidateQueries({ queryKey: ["email-credentials", companyId] });
+ void cache.invalidateQueries({ queryKey: queryKeys.tools.connections(companyId) });
+ if (changingAccount) {
+ // Save the replacement credential before retiring the original draft.
+ // A failed save/cleanup leaves the original URL recoverable; a completed
+ // switch gets its own URL so refreshing cannot revive an archived draft.
+ if (pendingEndpoint) {
+ await emailApi.control(pendingEndpoint.id, "remove");
+ await cache.invalidateQueries({ queryKey: ["email-inboxes", companyId] });
+ }
+ openDraft({
+ connectionId: id, selectedCredentialId: id, agentId, step: 1,
+ requestId: nextRequestId, addressMode: details.scope.scope_type === "inbox" ? "existing" : "new",
+ inboxId: details.scope.scope_type === "inbox" ? details.inboxes[0]?.inbox_id ?? "" : "",
+ username, domain: "agentmail.to", domainSelected: false, takenAddresses: [], mode, allowInboxKey,
+ });
+ return false;
+ }
+ setConnectionId(id);
+ setRestrictedInbox("");
+ setAddressMode(details.scope.scope_type === "inbox" ? "existing" : "new");
+ if (details.scope.scope_type === "inbox") setInboxId(details.inboxes[0]?.inbox_id ?? "");
+ return true;
},
+ onSuccess: ready => { if (ready) setStep(1); },
});
- const agentDetail = useQuery({
- queryKey: queryKeys.agents.detail(agentId),
- queryFn: () => agentsApi.get(agentId),
- enabled: !!agentId && trustOpen,
- });
+ function selectCredential(id: string) {
+ setSelectedCredentialId(id);
+ setApiKey("");
+ setRestrictedInbox("");
+ setAllowInboxKey(false);
+ setDomainSelected(false);
+ setTakenAddresses([]);
+ connect.reset();
+ }
+ const agentDetail = useQuery({ queryKey: queryKeys.agents.detail(agentId),
+ queryFn: () => agentsApi.get(agentId), enabled: !!agentId && trustOpen });
const trust = useMutation({
- mutationFn: () =>
- agentsApi.updatePermissions(
- agentId,
- {
- ...permissions,
- canCreateAgents: permissions.canCreateAgents ?? false,
- canCreateSkills: permissions.canCreateSkills ?? true,
- canAssignTasks: agentDetail.data?.access?.canAssignTasks ?? false,
- },
- companyId,
- ),
+ mutationFn: () => agentsApi.updatePermissions(agentId, {
+ ...permissions,
+ canCreateAgents: permissions.canCreateAgents ?? false,
+ canCreateSkills: permissions.canCreateSkills ?? true,
+ canAssignTasks: agentDetail.data?.access?.canAssignTasks ?? false,
+ }, companyId),
onSuccess: () => {
setTrustOpen(false);
- void cache.invalidateQueries({
- queryKey: queryKeys.agents.list(companyId),
- });
+ void cache.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });
},
});
const setup = useMutation({
- mutationFn: () =>
- emailApi.setup(companyId, {
- assignedAgentId: agentId,
- credentialConnectionId: connectionId,
- ...(addressMode === "existing" ? { inboxId } : { username, domain }),
- receiveMode: mode,
- idempotencyKey: requestId,
- }),
+ mutationFn: () => emailApi.setup(companyId, {
+ assignedAgentId: agentId, credentialConnectionId: connectionId,
+ ...(pendingAddress ? { inboxId: pendingAddress } : addressMode === "existing" ? { inboxId } : { username, domain }),
+ receiveMode: mode, idempotencyKey: requestId,
+ }),
+ onError: async (error) => {
+ if (error instanceof ApiError && (error.body as { code?: string } | null)?.code === "agentmail_address_taken") {
+ setTakenAddresses(previous => [...new Set([...previous, `${username}@${domain}`.toLowerCase()])].slice(-20));
+ }
+ await cache.invalidateQueries({ queryKey: ["email-inboxes", companyId] });
+ },
onSuccess: () => {
void cache.invalidateQueries({ queryKey: ["email-inboxes", companyId] });
- void cache.invalidateQueries({
- queryKey: queryKeys.tools.connectionInstalls(connectionId),
- });
- setStep(6);
+ void cache.invalidateQueries({ queryKey: queryKeys.chatEndpoints.list(companyId) });
+ void cache.invalidateQueries({ queryKey: queryKeys.tools.connections(companyId) });
+ void cache.invalidateQueries({ queryKey: queryKeys.tools.connectionInstalls(connectionId) });
+ setStep(2);
},
});
- const address =
- addressMode === "existing" ? inboxId : `${username}@${domain}`;
- const labels =
- step < 3
- ? ["Access", "API key", "Connected"]
- : ["Agent", "Email address", "Review"];
- const current = step < 3 ? step : Math.min(step - 3, 2);
- const error = connect.error ?? setup.error ?? inspected.error ?? agents.error;
- const trustNotice = chosen && (
-
-
- {lowTrust && scoped ? (
-
- ) : (
-
- )}
- {lowTrust
- ? scoped
- ? "Low-trust review configured"
- : "Low trust needs a work boundary"
- : `${chosen.name} is not a low-trust agent`}
-
-
- {lowTrust
- ? "Email tasks stay inside the configured project or root task boundary. Output is quarantined for trusted review."
- : "Email can contain malicious instructions. We recommend Low-trust review to limit the agent’s access to Paperclip work."}
-
-
Low-trust execution also requires isolated workspaces and an active sandbox environment in the agent’s runtime settings.
-
{
- setPermissions(chosen.permissions);
- setTrustOpen(true);
- }}
- >
- {lowTrust ? "Review trust settings" : "Configure low trust"}
+ const address = pendingAddress ?? (addressMode === "existing" ? inboxId : `${username}@${domain}`);
+ const knownAddresses = new Set([...takenAddresses, ...(inspected.data?.inboxes.map(i => i.inbox_id.toLowerCase()) ?? [])]);
+ const checkingNewAddress = step === 1 && addressMode === "new" && !pendingAddress && !scopedKey;
+ const knownAddress = checkingNewAddress && knownAddresses.has(address.toLowerCase());
+ const validUsername = /^[a-z0-9][a-z0-9._-]*$/.test(username) && username.length <= 64;
+ const addressCheck = useEmailAddressCheck(companyId, connectionId, username, domain,
+ checkingNewAddress && validUsername && !!inspected.data && !knownAddress);
+ const addressTaken = knownAddress || addressCheck.result?.status === "taken";
+ const suggestions = checkingNewAddress && validUsername && (addressTaken || addressCheck.result?.status === "unknown")
+ ? ["-agent", "-team", `-${requestId.slice(0, 6)}`]
+ .map(suffix => `${username.slice(0, 64 - suffix.length)}${suffix}`)
+ .filter(name => !knownAddresses.has(`${name}@${domain}`)) : [];
+ const assignedInbox = addressMode === "existing" && inboxes.data?.some(i => i.id !== requestId && i.address === address && i.status !== "archived");
+ const addressError = addressTaken ? "This email address is already in use. Choose a different address."
+ : assignedInbox ? "This inbox is already assigned to an agent." : null;
+ const error = connect.error ?? (!addressTaken ? setup.error : null) ?? resumeAccount.error ?? inspected.error ?? agents.error;
+ const busy = connect.isPending || setup.isPending;
+ const identityReady = inboxes.isSuccess && (!resumeId || requestId !== resumeId || !!pendingEndpoint) && (!pendingEndpoint || pendingEndpoint.assignedAgentId === agentId);
+ const canContinue = identityReady && !!chosen && !busy && !(lowTrust && !scoped) && (!!pendingAddress || !!selectedCredentialId || !!apiKey.trim());
+ const canCreate = identityReady && !!chosen && !busy && !!inspected.data && !(lowTrust && !scoped) && !addressError && !addressCheck.checking
+ && (!!pendingAddress || (addressMode === "existing" ? !!inboxId : validUsername));
+ const openTrust = () => { if (chosen) { setPermissions(chosen.permissions); setTrustOpen(true); } };
+ const leave = () => navigate(`/apps/chat/${setup.data?.id ?? pendingEndpoint?.id}/settings`);
+ const cancel = () => { try { sessionStorage.removeItem(draftKey); } catch {} navigate("/apps"); };
+ function openDraft(nextDraft: EmailSetupDraft & { requestId: string; connectionId: string }) {
+ try {
+ sessionStorage.setItem(`paperclip.agentmail-setup:${companyId}:${nextDraft.requestId}:${agentId}`, JSON.stringify(nextDraft));
+ } catch { /* The new link still restores the agent and saved account. */ }
+ navigate(`/apps/chat/connect?${new URLSearchParams({ provider: "agentmail", purpose: "chat", setupId: nextDraft.requestId, agentId, connectionId: nextDraft.connectionId })}`);
+ }
+ const chooseAnotherAddress = () => {
+ // Preserve the allocated inbox and its resumable setup. A different address
+ // must use a new provider client_id, never silently rename a retry.
+ const nextRequestId = crypto.randomUUID();
+ openDraft({
+ connectionId, selectedCredentialId: connectionId, agentId, step: 1,
+ requestId: nextRequestId, addressMode: "new", username: "", inboxId: "",
+ domain: pendingAddress?.slice(pendingAddress.lastIndexOf("@") + 1) ?? domain,
+ domainSelected: true, takenAddresses, mode, allowInboxKey: false,
+ });
+ };
+ return
+
+ {step === 2 ? "Your agent’s email is ready" : "Give an agent an email address"}
+
+ {step < 2 && inboxes.isError &&
+
Could not load email setup progress. {inboxes.error.message}
+
{ void inboxes.refetch(); }}>
+ {inboxes.isFetching ? "Loading…" : "Retry loading inboxes"}
-
- );
- return (
-
-
-
- {step < 3
- ? "Connect AgentMail"
- : step === 6
- ? "Your agent’s email is ready"
- : "Give an agent an email address"}
-
-
- navigate(
- connectionId ? `/apps/${connectionId}/permissions` : "/apps",
- )
- }
- >
- {step === 6 ? "Close" : "Cancel"}
-
-
-
setStep(step < 3 ? index : index + 3)}
- />
- {step === 0 && (
- navigate("/apps")}
- onContinue={() => setStep(1)}
- submitLabel="Continue"
- />
- )}
- {step === 1 && (
-