mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-21 08:22:20 +02:00
## 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 <noreply@paperclip.ing>
605 lines
37 KiB
TypeScript
605 lines
37 KiB
TypeScript
// @vitest-environment jsdom
|
||
import { act } from "react";
|
||
import { createRoot, type Root } from "react-dom/client";
|
||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||
import { MemoryRouter, useLocation } from "react-router-dom";
|
||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||
import { ApiError } from "@/api/client";
|
||
import { EmailEndpointSetup } from "./EmailEndpointSetup";
|
||
|
||
const mocks = vi.hoisted(() => ({ 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 <output data-testid="location" data-search={location.search}>{location.pathname}</output>; }
|
||
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(<QueryClientProvider client={client}><MemoryRouter initialEntries={[
|
||
`/apps/chat/connect?provider=agentmail&agentId=${agentId}${saved ? "&connectionId=account" : ""}${search}`,
|
||
]}><EmailEndpointSetup /><Location /></MemoryRouter></QueryClientProvider>));
|
||
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<HTMLInputElement>(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<HTMLSelectElement>("select")?.value).toBe("organization-account"));
|
||
expect(container.querySelector('input[type="password"]')).toBeNull();
|
||
await click("Continue");
|
||
await vi.waitFor(() => expect(container.querySelector<HTMLSelectElement>("#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<HTMLSelectElement>("select")?.value).toBe("preferred"));
|
||
await act(async () => {
|
||
const picker = container.querySelector<HTMLSelectElement>("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<HTMLSelectElement>("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<HTMLSelectElement>("select")?.value).toBe("");
|
||
expect(container.querySelector<HTMLInputElement>('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<HTMLInputElement>("#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<HTMLSelectElement>("#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<HTMLSelectElement>("#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<HTMLSelectElement>("#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<HTMLInputElement>("#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<HTMLInputElement>("#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<HTMLInputElement>("#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<HTMLInputElement>("#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<HTMLInputElement>("#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<HTMLButtonElement>('#email-agent')!.click());
|
||
await vi.waitFor(() => expect(document.querySelector('[aria-label="Select Support"]')).not.toBeNull());
|
||
await act(async () => document.querySelector<HTMLElement>('[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<HTMLInputElement>("#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<HTMLButtonElement>('#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<HTMLInputElement>("#email-name")?.readOnly).toBe(false);
|
||
expect(container.querySelector<HTMLSelectElement>("#email-domain")?.disabled).toBe(false);
|
||
expect(container.querySelector<HTMLSelectElement>("#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<HTMLOptionElement>('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<HTMLInputElement>('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();
|
||
});
|
||
});
|