mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents need a working model provider connection to run a task. > - A provider can reject a stored credential after the task starts. > - The failed run must ask the responsible user to repair that connection. > - This pull request adds that request directly to the task and reuses Connections sign-in. > - The user can choose an API key or subscription, then continue the task with a fresh session. ## Linked Issues or Issue Description **What happened?** A run that ended with `acpx_auth_required` or another known provider authentication error did not immediately offer an inline way to connect the provider. A repair form could also lock the user to the failed account's sign-in method. **Expected behavior** Show a provider connection card in the task as soon as the authentication failure is saved. Allow the responsible user to connect or repair the provider with any supported sign-in method. Keep the connection name automatic and resume the task after successful setup. **Steps to reproduce** 1. Run a task with a supported provider and an expired or invalid credential. 2. Let the run fail with a provider authentication error. 3. Open the task and attempt to repair the connection. Related work: Refs #13724 and #13726. This change adds the inline task repair flow and method choice. ## What Changed - Classify provider authentication failures and create one connection request for the current task. A persisted blocked classification suppresses automatic retries only after the repair card is created; unsupported providers retain their existing recovery path. - Mark only the attributed, unchanged credential as needing sign-in. Preserve credentials that were refreshed after the failed run started. - Reuse the provider sign-in controls inside the task. Allow API key and subscription choices for Claude, Codex, and Grok. Keep names hidden and generate a default from the user, provider, and method. - Keep the existing account when reconnecting with the same method. Create and select another account when the method changes. Validate updates to explicit agent bindings through the normal agent save path. - Require explicit adoption for legacy agent authentication. Validate in the agent environment, then commit the binding, connection install, audit, and card completion in one transaction. Keep failed setup and account selection visible and retryable. - Add regression tests and update the specification and Connections documentation. ## Verification - Fresh local verification: 199 tests passed across the inline form, provider method selector, default naming, authentication and recovery classifiers, run liveness, OpenAPI routes, database adoption/rollback, and Cursor execution suites. The adoption database suite also passed against disposable Docker PostgreSQL. - Full repository `pnpm build` and `pnpm -r typecheck` passed on the latest commit. Token gates are clean. - Embedded browser: opened real task cards from seeded authentication failures; switched Claude from API key to subscription and back; switched Codex from subscription to API key; confirmed the name field stays hidden. Provider sign-in was not completed with real credentials. - The broad local `pnpm test:run` started before review fixes and was interrupted after the working tree changed; it is not counted as a passing full run. Fresh focused tests passed. CI supplies the full test and browser suite results for the current commit. - CI is green on commit `4b97a4e447045ff3d7516525a187a5d1d21e0d4c`: 54 checks passed and two Storybook checks were skipped by their path rules. The workspace preview job passed on one rerun after a local-server startup timeout; its rerun passed 835 tests. - Greptile is 5/5 on the same commit with no actionable findings and no unresolved review threads. ## Risks - Incorrect authentication classification could prompt for a connection unnecessarily. Tests exclude tool authorization, quota, and unrelated runtime failures. - A method change selects the new personal provider default, which also applies to other agents that use that user's default. Explicit account bindings use the existing permission and runtime validation path. - Credential invalidation must not race with refresh or reconnect. The code compares the saved credential generation and grant update time under locks. - No database migration or new credential storage format is required. ## Model Used OpenAI GPT-6 through Codex. The exact model ID and context window size were not exposed in this session. Capabilities used: reasoning, repository editing, shell commands, database tests, and embedded-browser interaction. ## 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 tests listed 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 - [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 <noreply@paperclip.ing>
584 lines
25 KiB
TypeScript
584 lines
25 KiB
TypeScript
// @vitest-environment jsdom
|
||
|
||
import { act as reactAct, useState, type ReactNode } from "react";
|
||
import { createRoot, type Root } from "react-dom/client";
|
||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||
import type {
|
||
ConnectionIntentInteraction,
|
||
ToolConnection,
|
||
} from "@paperclipai/shared";
|
||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||
import {
|
||
connectedConnectionIntentInteraction,
|
||
issueThreadInteractionFixtureMeta,
|
||
pendingConnectionIntentInteraction,
|
||
retryConnectionIntentInteraction,
|
||
} from "@/fixtures/issueThreadInteractionFixtures";
|
||
import { ConnectionIntentInteractionBody } from "./ConnectionIntentInteractionBody";
|
||
|
||
const credentialRender = vi.hoisted(() => vi.fn());
|
||
const setupOptionsMock = vi.hoisted(() => vi.fn());
|
||
const completeMock = vi.hoisted(() => vi.fn());
|
||
const declineMock = vi.hoisted(() => vi.fn());
|
||
const setPhaseMock = vi.hoisted(() => vi.fn());
|
||
const getAgentMock = vi.hoisted(() => vi.fn());
|
||
const updateAgentMock = vi.hoisted(() => vi.fn());
|
||
const setDefaultMock = vi.hoisted(() => vi.fn());
|
||
vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: { setDefault: (...args: unknown[]) => setDefaultMock(...args) } }));
|
||
const adoptMock = vi.hoisted(() => vi.fn());
|
||
const installMock = vi.hoisted(() => vi.fn());
|
||
vi.mock("@/api/tools", () => ({ toolsApi: {
|
||
getConnectionInstalls: async () => ({ installs: [] }),
|
||
putConnectionInstalls: (...args: unknown[]) => installMock(...args),
|
||
} }));
|
||
|
||
vi.mock("@/api/agents", () => ({ agentsApi: {
|
||
adoptAiConnection: (...args: unknown[]) => adoptMock(...args),
|
||
get: (...args: unknown[]) => getAgentMock(...args),
|
||
update: (...args: unknown[]) => updateAgentMock(...args),
|
||
} }));
|
||
|
||
vi.mock("@/api/connection-intents", () => ({
|
||
connectionIntentsApi: {
|
||
setupOptions: (...args: unknown[]) => setupOptionsMock(...args),
|
||
complete: (...args: unknown[]) => completeMock(...args),
|
||
decline: (...args: unknown[]) => declineMock(...args),
|
||
setPhase: (...args: unknown[]) => setPhaseMock(...args),
|
||
},
|
||
}));
|
||
|
||
vi.mock("@/components/ai-connections/AiConnectionCredentialStep", () => ({
|
||
AiConnectionCredentialStep: (props: { connectionId?: string; name: string; hideName?: boolean; fixedMethod?: boolean; onComplete: (result: {connectionId: string; grantId: string; method: "api_key"}) => void; onCancel: () => void }) => { credentialRender(props); return <div data-testid="shared-ai-credentials">
|
||
{!props.hideName && <span>{props.name}</span>}<span>{String(props.fixedMethod)}</span>
|
||
<button onClick={() => props.onComplete({ connectionId: props.connectionId ?? "new-ai-account", grantId: "grant", method: "api_key" })}>Reconnect selected account</button>
|
||
<button onClick={props.onCancel}>Cancel repair</button>
|
||
</div>; },
|
||
}));
|
||
|
||
vi.mock("./ConnectionSetupFlow", () => ({
|
||
ConnectionSetupFlow: (props: {
|
||
requestedAgentId?: string;
|
||
existingConnections?: ToolConnection[];
|
||
onUseExisting?: (id: string) => Promise<void>;
|
||
onComplete?: (completion: { connectionId: string } | { resolvedByCallback: true }) => void;
|
||
onPhaseChange?: (phase: "needs_retry") => void;
|
||
onCancel?: () => void;
|
||
}) => (
|
||
<div data-testid="shared-connection-setup">
|
||
<span data-testid="requested-agent">{props.requestedAgentId}</span>
|
||
<span data-testid="existing-count">
|
||
{props.existingConnections?.length ?? 0}
|
||
</span>
|
||
{props.existingConnections?.map((connection) => (
|
||
<button
|
||
key={connection.id}
|
||
onClick={() => void props.onUseExisting?.(connection.id)}
|
||
>
|
||
Use {connection.name}
|
||
</button>
|
||
))}
|
||
<button
|
||
onClick={() => props.onComplete?.({ connectionId: "connection-new" })}
|
||
>
|
||
Connect new
|
||
</button>
|
||
<button onClick={() => props.onComplete?.({ resolvedByCallback: true })}>Simulate OAuth callback</button>
|
||
<button onClick={() => props.onPhaseChange?.("needs_retry")}>
|
||
Simulate retry
|
||
</button>
|
||
<button onClick={props.onCancel}>Cancel setup</button>
|
||
</div>
|
||
),
|
||
}));
|
||
|
||
(
|
||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||
|
||
let root: Root | null = null;
|
||
let host: HTMLDivElement | null = null;
|
||
let queryClient: QueryClient;
|
||
|
||
async function act(callback: () => void | Promise<void>) {
|
||
await reactAct(callback);
|
||
}
|
||
|
||
async function flush() {
|
||
await act(async () => {
|
||
await Promise.resolve();
|
||
await new Promise((resolve) => window.setTimeout(resolve, 0));
|
||
});
|
||
}
|
||
|
||
async function waitForAssertion(assertion: () => void, attempts = 20) {
|
||
let lastError: unknown;
|
||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||
try {
|
||
assertion();
|
||
return;
|
||
} catch (error) {
|
||
lastError = error;
|
||
await flush();
|
||
}
|
||
}
|
||
throw lastError;
|
||
}
|
||
|
||
function terminal(
|
||
status: ConnectionIntentInteraction["status"],
|
||
outcome: "declined" | "superseded" | "expired",
|
||
): ConnectionIntentInteraction {
|
||
return {
|
||
...pendingConnectionIntentInteraction,
|
||
id: `interaction-${outcome}`,
|
||
status,
|
||
resolvedAt: new Date("2026-08-26T12:00:00.000Z"),
|
||
result: { version: 1, outcome },
|
||
} as ConnectionIntentInteraction;
|
||
}
|
||
|
||
function renderNode(node: ReactNode) {
|
||
host = document.createElement("div");
|
||
document.body.appendChild(host);
|
||
root = createRoot(host);
|
||
queryClient = new QueryClient({
|
||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||
});
|
||
void act(() => {
|
||
root?.render(
|
||
<QueryClientProvider client={queryClient}>
|
||
{node}
|
||
</QueryClientProvider>,
|
||
);
|
||
});
|
||
return host;
|
||
}
|
||
|
||
function renderBody(
|
||
interaction: ConnectionIntentInteraction = pendingConnectionIntentInteraction,
|
||
currentUserId:
|
||
string | null = issueThreadInteractionFixtureMeta.currentUserId,
|
||
) {
|
||
return renderNode(
|
||
<ConnectionIntentInteractionBody
|
||
interaction={interaction}
|
||
currentUserId={currentUserId}
|
||
addresseeLabel="Carol"
|
||
/>,
|
||
);
|
||
}
|
||
|
||
function button(label: string) {
|
||
return Array.from(document.body.querySelectorAll("button")).find(
|
||
(candidate) => candidate.textContent?.trim() === label || (label === "Connect / Use existing" && candidate.textContent?.trim() === "Connect"),
|
||
) as HTMLButtonElement | undefined;
|
||
}
|
||
|
||
beforeEach(() => {
|
||
setDefaultMock.mockReset();
|
||
getAgentMock.mockReset();
|
||
updateAgentMock.mockReset();
|
||
installMock.mockReset();
|
||
adoptMock.mockReset();
|
||
setupOptionsMock.mockReset();
|
||
completeMock.mockReset();
|
||
declineMock.mockReset();
|
||
setPhaseMock.mockReset();
|
||
setupOptionsMock.mockResolvedValue({
|
||
requestedAgentId:
|
||
pendingConnectionIntentInteraction.payload.requestingAgentId,
|
||
existingConnections: [],
|
||
});
|
||
completeMock.mockResolvedValue({});
|
||
declineMock.mockResolvedValue({});
|
||
setPhaseMock.mockResolvedValue({});
|
||
});
|
||
|
||
afterEach(async () => {
|
||
if (root) await act(() => root?.unmount());
|
||
host?.remove();
|
||
document.body
|
||
.querySelectorAll("[data-radix-focus-guard]")
|
||
.forEach((node) => node.remove());
|
||
root = null;
|
||
host = null;
|
||
});
|
||
|
||
describe("ConnectionIntentInteractionBody states and audience", () => {
|
||
it.each([
|
||
[pendingConnectionIntentInteraction, "Connect"],
|
||
[
|
||
{
|
||
...pendingConnectionIntentInteraction,
|
||
payload: {
|
||
...pendingConnectionIntentInteraction.payload,
|
||
phase: "authorizing",
|
||
},
|
||
},
|
||
"Continue setup",
|
||
],
|
||
[retryConnectionIntentInteraction, "Try again"],
|
||
[connectedConnectionIntentInteraction, "Notion connected"],
|
||
[terminal("rejected", "declined"), "Connection declined"],
|
||
[terminal("expired", "superseded"), "Request superseded"],
|
||
[terminal("expired", "expired"), "Connection request expired"],
|
||
] as const)("renders the %s state", (interaction, expected) => {
|
||
renderBody(interaction as ConnectionIntentInteraction);
|
||
expect(document.body.textContent).toContain(expected);
|
||
});
|
||
|
||
it("shows non-addressees only the waiting state and never loads setup", () => {
|
||
renderBody(pendingConnectionIntentInteraction, "other-user");
|
||
expect(document.body.textContent).toContain("Waiting for Carol");
|
||
expect(button("Connect / Use existing")).toBeUndefined();
|
||
expect(button("Not now")).toBeUndefined();
|
||
expect(setupOptionsMock).not.toHaveBeenCalled();
|
||
expect(document.body.innerHTML).not.toMatch(
|
||
/authorizationUrl|bearer|credential/i,
|
||
);
|
||
});
|
||
});
|
||
|
||
describe("ConnectionIntentInteractionBody dialog behavior", () => {
|
||
it("verifies inline OAuth callback hints against durable server acceptance", async () => {
|
||
const options = { requestedAgentId: pendingConnectionIntentInteraction.payload.requestingAgentId, existingConnections: [], interaction: pendingConnectionIntentInteraction };
|
||
setupOptionsMock.mockResolvedValue(options);
|
||
renderBody();
|
||
await act(() => button("Connect / Use existing")?.click());
|
||
await flush();
|
||
const readsBeforeMessage = setupOptionsMock.mock.calls.length;
|
||
await act(() => button("Simulate OAuth callback")?.click());
|
||
await flush();
|
||
expect(setupOptionsMock.mock.calls.length).toBeGreaterThan(readsBeforeMessage);
|
||
expect(document.querySelector('[role="dialog"]')).not.toBeNull();
|
||
expect(completeMock).not.toHaveBeenCalled();
|
||
setupOptionsMock.mockResolvedValue({ ...options, interaction: connectedConnectionIntentInteraction });
|
||
await act(() => button("Simulate OAuth callback")?.click());
|
||
await waitForAssertion(() => expect(document.querySelector('[role="dialog"]')).toBeNull());
|
||
expect(completeMock).not.toHaveBeenCalled();
|
||
});
|
||
|
||
it("shows loading, then passes existing choices and the locked requesting agent to the shared flow", async () => {
|
||
let resolveSetup!: (value: unknown) => void;
|
||
setupOptionsMock.mockReturnValue(
|
||
new Promise((resolve) => {
|
||
resolveSetup = resolve;
|
||
}),
|
||
);
|
||
renderBody();
|
||
|
||
await act(() => button("Connect / Use existing")?.click());
|
||
expect(document.body.textContent).toContain("Loading connection options…");
|
||
|
||
await act(async () => {
|
||
resolveSetup({
|
||
requestedAgentId: "agent-requesting",
|
||
existingConnections: [
|
||
{ id: "connection-one", name: "Carol's Notion" },
|
||
{ id: "connection-two", name: "Team Notion" },
|
||
],
|
||
});
|
||
});
|
||
await flush();
|
||
|
||
expect(
|
||
document.querySelector('[data-testid="requested-agent"]')?.textContent,
|
||
).toBe("agent-requesting");
|
||
expect(
|
||
document.querySelector('[data-testid="existing-count"]')?.textContent,
|
||
).toBe("2");
|
||
expect(button("Use Carol's Notion")).toBeDefined();
|
||
expect(button("Use Team Notion")).toBeDefined();
|
||
expect(button("Connect new")).toBeDefined();
|
||
});
|
||
|
||
it("keeps a load failure open and recovers through the query retry", async () => {
|
||
setupOptionsMock.mockRejectedValueOnce(new Error("setup unavailable"));
|
||
renderBody();
|
||
await act(() => button("Connect / Use existing")?.click());
|
||
await flush();
|
||
|
||
expect(document.body.textContent).toContain(
|
||
"Couldn’t load connection setup",
|
||
);
|
||
expect(document.body.textContent).toContain("setup unavailable");
|
||
setupOptionsMock.mockResolvedValueOnce({
|
||
requestedAgentId: "agent-requesting",
|
||
existingConnections: [],
|
||
});
|
||
await act(() => button("Try again")?.click());
|
||
await flush();
|
||
expect(
|
||
document.querySelector('[data-testid="shared-connection-setup"]'),
|
||
).not.toBeNull();
|
||
});
|
||
|
||
it("completes an existing connection, closes, restores focus, and invalidates each task query once", async () => {
|
||
setupOptionsMock.mockResolvedValue({
|
||
requestedAgentId: "agent-requesting",
|
||
existingConnections: [{ id: "connection-one", name: "Carol's Notion" }],
|
||
});
|
||
renderBody();
|
||
const trigger = button("Connect / Use existing")!;
|
||
const invalidation = vi.spyOn(queryClient, "invalidateQueries");
|
||
|
||
await act(() => trigger.click());
|
||
await flush();
|
||
await act(() => button("Use Carol's Notion")?.click());
|
||
await flush();
|
||
|
||
expect(completeMock).toHaveBeenCalledWith(
|
||
pendingConnectionIntentInteraction.id,
|
||
"connection-one",
|
||
);
|
||
expect(
|
||
document.querySelector('[data-testid="shared-connection-setup"]'),
|
||
).toBeNull();
|
||
await waitForAssertion(() =>
|
||
expect(document.activeElement).toBe(
|
||
document.querySelector(
|
||
'[data-testid="connection-intent-focus-target"]',
|
||
),
|
||
),
|
||
);
|
||
expect(invalidation).toHaveBeenCalledTimes(2);
|
||
expect(invalidation).toHaveBeenCalledWith({
|
||
queryKey: ["issues", "interactions"],
|
||
});
|
||
expect(invalidation).toHaveBeenCalledWith({
|
||
queryKey: ["issues", "detail"],
|
||
});
|
||
});
|
||
|
||
it("restores focus when completion remounts the intent in a different task host", async () => {
|
||
setupOptionsMock.mockResolvedValue({
|
||
requestedAgentId: "agent-requesting",
|
||
existingConnections: [{ id: "connection-one", name: "Carol's Notion" }],
|
||
});
|
||
const acceptedInteraction = {
|
||
...pendingConnectionIntentInteraction,
|
||
status: "accepted",
|
||
resolvedAt: new Date("2026-08-26T12:00:00.000Z"),
|
||
result: {
|
||
version: 1,
|
||
outcome: "connected",
|
||
connectionId: "connection-one",
|
||
},
|
||
} as ConnectionIntentInteraction;
|
||
let showAcceptedInteraction!: () => void;
|
||
|
||
function RemountingTaskHost() {
|
||
const [interaction, setInteraction] = useState(
|
||
pendingConnectionIntentInteraction,
|
||
);
|
||
showAcceptedInteraction = () => setInteraction(acceptedInteraction);
|
||
return (
|
||
<ConnectionIntentInteractionBody
|
||
key={interaction.status}
|
||
interaction={interaction}
|
||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||
addresseeLabel="Carol"
|
||
/>
|
||
);
|
||
}
|
||
|
||
completeMock.mockImplementation(async () => {
|
||
showAcceptedInteraction();
|
||
return acceptedInteraction;
|
||
});
|
||
renderNode(<RemountingTaskHost />);
|
||
|
||
await act(() => button("Connect / Use existing")?.click());
|
||
await flush();
|
||
await act(() => button("Use Carol's Notion")?.click());
|
||
|
||
await waitForAssertion(() => {
|
||
const target = document.getElementById(
|
||
`connection-intent-focus-target-${acceptedInteraction.id}`,
|
||
);
|
||
expect(document.body.textContent).toContain("Notion connected");
|
||
expect(document.activeElement).toBe(target);
|
||
});
|
||
});
|
||
|
||
it("keeps the dialog open and surfaces completion failures", async () => {
|
||
completeMock.mockRejectedValue(new Error("install commit failed"));
|
||
renderBody();
|
||
await act(() => button("Connect / Use existing")?.click());
|
||
await flush();
|
||
await act(() => button("Connect new")?.click());
|
||
await flush();
|
||
|
||
expect(
|
||
document.querySelector('[data-testid="shared-connection-setup"]'),
|
||
).not.toBeNull();
|
||
expect(
|
||
document.body.querySelector('[role="alert"]')?.textContent,
|
||
).toContain("install commit failed");
|
||
});
|
||
|
||
it("declines once with pending controls disabled and invalidates each task query once", async () => {
|
||
let finishDecline!: () => void;
|
||
declineMock.mockReturnValue(
|
||
new Promise<void>((resolve) => {
|
||
finishDecline = resolve;
|
||
}),
|
||
);
|
||
renderBody();
|
||
const invalidation = vi.spyOn(queryClient, "invalidateQueries");
|
||
const decline = button("Not now")!;
|
||
|
||
await act(() => decline.click());
|
||
await flush();
|
||
expect(decline.disabled).toBe(true);
|
||
decline.click();
|
||
expect(declineMock).toHaveBeenCalledTimes(1);
|
||
await act(async () => finishDecline());
|
||
await flush();
|
||
|
||
expect(invalidation).toHaveBeenCalledTimes(2);
|
||
});
|
||
|
||
it("turns shared-flow retry signals into the server-authored retry phase", async () => {
|
||
renderBody();
|
||
await act(() => button("Connect / Use existing")?.click());
|
||
await flush();
|
||
await act(() => button("Simulate retry")?.click());
|
||
await flush();
|
||
expect(setPhaseMock).toHaveBeenCalledWith(
|
||
pendingConnectionIntentInteraction.id,
|
||
"needs_retry",
|
||
);
|
||
});
|
||
});
|
||
|
||
|
||
describe("AI repair inside the card", () => {
|
||
const interaction: ConnectionIntentInteraction = { ...pendingConnectionIntentInteraction, payload: { ...pendingConnectionIntentInteraction.payload, purpose: "ai" } };
|
||
const connection = { id: "selected-account", name: "My Codex account", provider: "openai", method: "api_key", ownership: "personal", ownerName: "Dotta", status: "revoked" };
|
||
it.each([false, true])("requires atomic validated legacy adoption (validation fails: %s)", async (fails) => {
|
||
const binding = { provider: "openai", method: "subscription", mode: "responsible_user" };
|
||
setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: binding, aiConnectionRequiresAdoption: true });
|
||
if (fails) adoptMock.mockRejectedValue(new Error("Connection test failed"));
|
||
else adoptMock.mockResolvedValue({ ...interaction, status: "accepted" });
|
||
renderBody(interaction); await flush();
|
||
await act(() => button("Fix connection")!.click());
|
||
await act(() => button("Reconnect selected account")!.click());
|
||
expect(adoptMock).not.toHaveBeenCalled();
|
||
expect(document.body.textContent).toContain("This replaces the agent’s existing authentication");
|
||
await act(() => button("Use connection and continue")!.click());
|
||
await flush();
|
||
expect(adoptMock).toHaveBeenCalledWith(interaction.payload.requestingAgentId, interaction.id, "new-ai-account", interaction.companyId);
|
||
expect(updateAgentMock).not.toHaveBeenCalled();
|
||
expect(installMock).not.toHaveBeenCalled();
|
||
expect(completeMock).not.toHaveBeenCalled();
|
||
if (fails) expect(document.querySelector('[role="alert"]')?.textContent).toContain("Connection test failed");
|
||
});
|
||
it.each(["anthropic", "openai"])("connects a missing %s default directly in the task", async (provider) => {
|
||
setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider, method: "api_key", mode: "responsible_user" } });
|
||
completeMock.mockResolvedValue({ ...interaction, status: "accepted" });
|
||
renderBody(interaction); await flush();
|
||
await act(() => button("Fix connection")!.click());
|
||
expect(document.querySelector('[role="dialog"]')).toBeNull();
|
||
expect(document.querySelector('[data-testid="shared-connection-setup"]')).toBeNull();
|
||
expect(document.querySelector('[data-testid="shared-ai-credentials"]')).not.toBeNull();
|
||
expect(credentialRender.mock.lastCall![0]).toMatchObject({ provider, hideName: true, ownership: "personal", agentIds: [interaction.payload.requestingAgentId], allAgents: false });
|
||
expect(credentialRender.mock.lastCall![0].connectionId).toBeUndefined();
|
||
expect(credentialRender.mock.lastCall![0].fixedMethod).toBeUndefined();
|
||
expect(document.body.textContent).toContain("This task can’t run until");
|
||
await act(() => button("Reconnect selected account")!.click());
|
||
expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-ai-account");
|
||
});
|
||
it("reuses authentication inline, preserves the selected account, cancels with focus, and completes", async () => {
|
||
setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: true } });
|
||
completeMock.mockResolvedValue({ ...interaction, status: "accepted" });
|
||
renderBody(interaction);
|
||
await flush();
|
||
await act(() => button("Fix connection")!.click());
|
||
expect(document.querySelector('[role="dialog"]')).toBeNull();
|
||
expect(document.querySelector('[data-testid="ai-connection-inline-repair"]')?.textContent).not.toContain("My Codex account");
|
||
expect(credentialRender.mock.lastCall![0]).toMatchObject({ name: "My Codex account", hideName: true, fixedMethod: false, connectionId: "selected-account" });
|
||
await act(() => button("Cancel repair")!.click());
|
||
await waitForAssertion(() => expect(document.activeElement?.getAttribute("data-testid")).toBe("connection-intent-focus-target"));
|
||
expect(completeMock).not.toHaveBeenCalled();
|
||
await act(() => button("Fix connection")!.click());
|
||
await act(() => button("Reconnect selected account")!.click());
|
||
expect(completeMock).toHaveBeenCalledWith(interaction.id, "selected-account");
|
||
});
|
||
it.each(["responsible_user", "delegated", "shared"] as const)("selects a different authentication method for a %s binding before resuming", async (mode) => {
|
||
const binding = { provider: "openai", method: "api_key", mode, ...(mode !== "responsible_user" ? { connectionId: connection.id, grantId: "old-grant" } : {}) };
|
||
setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: binding, aiRepair: { connection: { ...connection, grantId: "old-grant" }, canReconnect: true } });
|
||
getAgentMock.mockResolvedValue({ id: interaction.payload.requestingAgentId, runtimeConfig: { aiConnection: binding, heartbeat: { enabled: true } } });
|
||
completeMock.mockResolvedValue({ ...interaction, status: "accepted" });
|
||
renderBody(interaction); await flush();
|
||
await act(() => button("Fix connection")!.click());
|
||
await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" }));
|
||
await flush();
|
||
if (mode === "responsible_user") {
|
||
expect(setDefaultMock).toHaveBeenCalledWith(interaction.companyId, "new-grant");
|
||
expect(updateAgentMock).not.toHaveBeenCalled();
|
||
} else {
|
||
expect(updateAgentMock).toHaveBeenCalledWith(interaction.payload.requestingAgentId, { runtimeConfig: { heartbeat: { enabled: true }, aiConnection: { ...binding, method: "subscription", connectionId: "new-subscription", grantId: "new-grant" } } }, interaction.companyId);
|
||
expect(setDefaultMock).not.toHaveBeenCalled();
|
||
}
|
||
expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-subscription");
|
||
});
|
||
it("keeps a failed account switch pending and retries the saved account", async () => {
|
||
setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" }, aiRepair: { connection, canReconnect: true } });
|
||
setDefaultMock.mockRejectedValueOnce(new Error("Could not select this account"));
|
||
renderBody(interaction); await flush();
|
||
await act(() => button("Fix connection")!.click());
|
||
await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" }));
|
||
await flush();
|
||
expect(completeMock).not.toHaveBeenCalled();
|
||
expect(document.querySelector('[role="alert"]')?.textContent).toContain("Could not select this account");
|
||
await act(() => button("Retry using this connection")!.click());
|
||
await flush();
|
||
expect(completeMock).toHaveBeenCalledWith(interaction.id, "new-subscription");
|
||
});
|
||
it("clears an account-selection retry when its setup is abandoned", async () => {
|
||
setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" }, aiRepair: { connection, canReconnect: true } });
|
||
setDefaultMock.mockRejectedValueOnce(new Error("Could not select this account"));
|
||
renderBody(interaction); await flush();
|
||
await act(() => button("Fix connection")!.click());
|
||
await act(() => credentialRender.mock.lastCall![0].onComplete({ connectionId: "new-subscription", grantId: "new-grant", method: "subscription" }));
|
||
await flush();
|
||
expect(button("Retry using this connection")).toBeDefined();
|
||
await act(() => button("Cancel repair")!.click());
|
||
await act(() => button("Fix connection")!.click());
|
||
expect(button("Retry using this connection")).toBeUndefined();
|
||
expect(document.querySelector('[role="alert"]')).toBeNull();
|
||
expect(completeMock).not.toHaveBeenCalled();
|
||
});
|
||
it("keeps a late credential save after cancellation from accepting the request", async () => {
|
||
setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: true } });
|
||
renderBody(interaction); await flush();
|
||
await act(() => button("Fix connection")!.click());
|
||
const abandoned = credentialRender.mock.lastCall![0];
|
||
await act(() => button("Cancel repair")!.click());
|
||
await act(() => button("Fix connection")!.click());
|
||
await act(() => abandoned.onComplete({ connectionId: connection.id, grantId: "grant", method: "api_key" }));
|
||
expect(completeMock).not.toHaveBeenCalled();
|
||
});
|
||
it("offers continuation for the restored account without another login", async () => {
|
||
setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [connection], aiRepair: { connection, canReconnect: true } });
|
||
renderBody(interaction); await flush();
|
||
await act(() => button("Fix connection")!.click());
|
||
expect(document.querySelector('[data-testid="shared-ai-credentials"]')).toBeNull();
|
||
await act(() => button("Continue task")!.click());
|
||
expect(completeMock).toHaveBeenCalledWith(interaction.id, connection.id);
|
||
});
|
||
it("does not let another user reconnect the owner's account", async () => {
|
||
setupOptionsMock.mockResolvedValue({ interaction, existingConnections: [], aiRepair: { connection, canReconnect: false } });
|
||
renderBody(interaction); await flush();
|
||
await act(() => button("Fix connection")!.click());
|
||
expect(document.body.textContent).toContain("Dotta must reconnect My Codex account");
|
||
expect(document.querySelector('[data-testid="shared-ai-credentials"]')).toBeNull();
|
||
});
|
||
it("does not promise to run without credentials when declined", () => {
|
||
renderBody({ ...interaction, status: "rejected" });
|
||
expect(document.body.textContent).toContain("The task still needs a working AI connection");
|
||
expect(document.body.textContent).not.toContain("can continue without it");
|
||
});
|
||
});
|