fix(connections): repair stale AI defaults from agent settings (#14916)

## Thinking Path

> - Paperclip manages AI agents and controls the credentials used for
their work.
> - Managed AI connections resolve each responsible user's provider
default.
> - Agent settings created another account but kept the old default
selected.
> - A rejected provider test left the old account marked as connected.
> - Claude ACP reported a typed login failure as a generic
terminal-access error.
> - This pull request repairs the selected account or selects the new
login explicitly.
> - Agents can save and run with the repaired credential, and failed
logins request sign-in.

## Linked Issues or Issue Description

- Fixes #14831.
- Refs #13867. Environment failures remain separate from
credential-health failures.

## What Changed

- Add an agent-settings action to reconnect an unavailable personal
default in place. Keep its connection, grant, default, and agent access.
- State that a new account becomes the user's provider default. Select
its returned grant before changing the agent binding. Keep the actual
sign-in method.
- Show default-update errors and allow retry without another provider
login.
- Show the agent-access choice. Connection managers start with
company-wide access for their own tasks. Other members start with access
for the current agent.
- Use the server's connection-manager permission in the shared list
response. This includes members with a custom management grant.
- Mark credentials as needing attention after an explicit login
rejection in Test or Save. This includes API-key 401 and 403 responses.
Network, quota, and server failures keep the credential health
unchanged.
- Reuse the credential-generation check so an old failure cannot
invalidate a newer reconnect.
- Route Claude's typed provider `access` failure to the existing
login-recovery flow. Replace its generic terminal-access fallback with a
sign-in message.
- Add regression tests and update the AI Connections documentation.

## Verification

- Red: the UI tests failed on the missing reconnect action, unused
returned grant, missing access choice, and lost default-update error.
The server tests failed because rejected credentials stayed connected.
The real ACP fixture returned `acpx_turn_failed` for typed login
failures.
- Green: 156 tests passed across the AI connection, hiring, agent field,
and New Agent suites. All 37 environment-route tests passed. The Claude
ACP authentication fixtures also passed.
- `pnpm check:token-gates` passed.
- `pnpm -r typecheck` passed.
- `pnpm build` passed.
- The full local `pnpm test:run` passed 707 files and 14,503 tests, then
exited with an agent-conversation timeout and embedded PostgreSQL
startup failures in unchanged suites. The isolated conversation and
migration tests passed on rerun. Later local test groups did not run
after this failure.
- [All CI gates
passed](https://github.com/paperclipai/paperclip/actions/runs/37012669356)
on commit `38513dfe2`. This includes the full test matrix, browser
tests, typecheck, build, Runner checks, and canary dry run.
- Greptile reviewed commit `38513dfe2` and returned 5/5 with no open
findings.
- The regression tests use a real embedded database and a real ACP
fixture process. Live provider sign-in requires a valid account and was
not run.

## Risks

- Connecting a new account from agent settings changes the user's
provider default. The dialog states this before sign-in.
- The displayed access choice can allow all company agents to use the
account for its owner's tasks. Reconnect keeps the existing access.
Server permissions still control installs.
- Claude's typed `access` category maps to the provider's
`auth_required` signal. Tool and workspace request failures retain their
existing classification.
- No database migration or provider credential format changes are
required.

## Model Used

- OpenAI GPT-6 through Codex. The exact served model identifier and
context window are not exposed in this session. Capabilities used:
reasoning, repository tools, code editing, and command 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 tests locally and they pass
- [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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-10-02 08:57:52 -05:00
1 parent 408f70e69f
commit e00d10d5d5
16 files changed
+407 -52

No files matched your search

@@ -68,6 +68,87 @@ function hired(response: request.Response) {
}
describe("agent-created hires use managed AI connections", () => {
for (const operation of ["test", "save"] as const) {
it.each([401, 403, 429, 503, null])(`${operation} changes API-key health only for a provider rejection (status: %s)`, async (status) => {
const f = await fixture("anthropic", "api_key");
await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "user", principalId: f.userId, permissionKey: "agents:configure" });
const original = getServerAdapter(f.adapterType);
registerServerAdapter({ ...original, testEnvironment: async () => ({ adapterType: f.adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }) });
const network = vi.spyOn(globalThis, "fetch");
if (status === null) network.mockRejectedValue(new Error("Network unavailable"));
else network.mockResolvedValue(new Response(null, { status }));
try {
const response = operation === "test"
? await request(f.app).post(`/api/companies/${f.companyId}/adapters/${f.adapterType}/test-environment`).send({ agentId: f.agentId, aiConnection: f.binding, adapterConfig: {} })
: await request(f.app).patch(`/api/agents/${f.agentId}`).send({ adapterConfig: { model: "changed-model" } });
expect(response.status, JSON.stringify(response.body)).toBe(operation === "test" ? 200 : 422);
const rejected = status === 401 || status === 403;
expect(await aiConnectionService(db).list(f.companyId, f.userId)).toEqual([expect.objectContaining({ status: rejected ? "needs_attention" : "connected" })]);
} finally { network.mockRestore(); unregisterServerAdapter(f.adapterType); }
});
}
it.each(["test", "save"] as const)("%s marks a hello-test authentication rejection as needing attention and reconnect repairs the same default", async (operation) => {
const f = await fixture("anthropic", "subscription");
await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "user", principalId: f.userId, permissionKey: "agents:configure" });
const original = getServerAdapter(f.adapterType);
registerServerAdapter({ ...original, testEnvironment: async () => ({
adapterType: f.adapterType, status: "fail", testedAt: new Date().toISOString(),
checks: [{ code: "claude_hello_probe_auth_required", level: "error", message: "The account needs sign-in." }],
}) });
try {
const response = operation === "test"
? await request(f.app).post(`/api/companies/${f.companyId}/adapters/${f.adapterType}/test-environment`).send({ agentId: f.agentId, aiConnection: f.binding, adapterConfig: {} })
: await request(f.app).patch(`/api/agents/${f.agentId}`).send({ adapterConfig: { model: "changed-model" } });
expect(response.status, JSON.stringify(response.body)).toBe(operation === "test" ? 200 : 422);
if (operation === "test") expect(response.body.status).toBe("fail");
const service = aiConnectionService(db);
expect(await service.list(f.companyId, f.userId)).toEqual([expect.objectContaining({ id: f.account.connectionId, isDefault: true, status: "needs_attention" })]);
await expect(service.select({ companyId: f.companyId, userId: f.userId, agentId: f.agentId, adapterType: f.adapterType, binding: f.binding })).rejects.toThrow("Reconnect");
const repaired = await service.save(f.companyId, f.userId, {
provider: "anthropic", method: "subscription", name: "Ignored reconnect name", ownership: "personal",
connectionId: f.account.connectionId, allAgents: true, agentIds: [], loginSessionId: "fixture",
}, "repaired-token");
expect(repaired).toEqual(f.account);
expect(await service.list(f.companyId, f.userId)).toEqual([expect.objectContaining({ id: f.account.connectionId, isDefault: true, status: "connected" })]);
const installs = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, f.account.connectionId));
expect(installs).toEqual([expect.objectContaining({ targetType: "agent", targetId: f.agentId })]);
registerServerAdapter({ ...original, testEnvironment: async () => ({
adapterType: f.adapterType, status: "pass", testedAt: new Date().toISOString(),
checks: [{ code: "claude_hello_probe_passed", level: "info", message: "hello" }],
}) });
const saved = await request(f.app).patch(`/api/agents/${f.agentId}`).send({ adapterConfig: { model: "changed-model" } });
expect(saved.status, JSON.stringify(saved.body)).toBe(200);
const runtime = await prepareManagedAiRuntime(db, { companyId: f.companyId, agentId: f.agentId, responsibleUserId: f.userId, adapterType: f.adapterType, binding: f.binding, config: saved.body.adapterConfig });
try {
expect(runtime.attribution.grantId).toBe(f.account.grantId);
expect((runtime.config.env as Record<string, string>).CLAUDE_CODE_OAUTH_TOKEN).toBe("repaired-token");
} finally { await runtime.cleanup(); }
} finally { unregisterServerAdapter(f.adapterType); }
});
it.each([false, true])("a failed environment test preserves connection health for a runtime failure or a newer reconnect (reconnected: %s)", async (reconnected) => {
const f = await fixture("anthropic", "subscription");
await db.insert(principalPermissionGrants).values({ companyId: f.companyId, principalType: "user", principalId: f.userId, permissionKey: "agents:configure" });
const original = getServerAdapter(f.adapterType);
registerServerAdapter({ ...original, testEnvironment: async () => {
if (reconnected) await aiConnectionService(db).save(f.companyId, f.userId, {
provider: "anthropic", method: "subscription", name: "My Claude", ownership: "personal",
connectionId: f.account.connectionId, allAgents: false, agentIds: [f.agentId], loginSessionId: "fixture",
}, "newer-token");
return {
adapterType: f.adapterType, status: "fail", testedAt: new Date().toISOString(),
checks: [{ code: reconnected ? "claude_hello_probe_auth_required" : "claude_cli_not_found", level: "error", message: "Test failed." }],
};
} });
try {
const response = await request(f.app).post(`/api/companies/${f.companyId}/adapters/${f.adapterType}/test-environment`).send({ agentId: f.agentId, aiConnection: f.binding, adapterConfig: {} });
expect(response.status, JSON.stringify(response.body)).toBe(200);
expect(response.body.status).toBe("fail");
expect(await aiConnectionService(db).list(f.companyId, f.userId)).toEqual([expect.objectContaining({ status: "connected" })]);
} finally { unregisterServerAdapter(f.adapterType); }
});
for (const endpoint of ["agent-hires", "agents"]) {
it.each([
["anthropic", "api_key"], ["anthropic", "subscription"],
@@ -116,6 +116,11 @@ vi.mock("../routes/ai-connections.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../routes/ai-connections.js")>()),
validateAiApiKey: mockValidateAiApiKey,
}));
const mockMarkAuthenticationFailed = vi.hoisted(() => vi.fn(async () => undefined));
vi.mock("../services/ai-connections.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../services/ai-connections.js")>()),
aiConnectionService: () => ({ markAuthenticationFailed: mockMarkAuthenticationFailed }),
}));
function mockManagedRuntime(method: "api_key" | "subscription") {
mockPrepareManagedAiRuntime.mockImplementation(
@@ -451,7 +456,10 @@ describe("agent test-environment route", () => {
it("fails adoption of an api_key connection the provider no longer accepts", async () => {
mockManagedRuntime("api_key");
mockValidateAiApiKey.mockRejectedValueOnce(Object.assign(new Error("The provider rejected this API key."), { status: 422 }));
const { unprocessable } = await import("../errors.js");
mockValidateAiApiKey.mockRejectedValueOnce(unprocessable("The provider rejected this API key.", {
code: "ai_connection_api_key_rejected",
}));
const app = await createApp();
const res = await request(app)
.post("/api/companies/company-1/adapters/external_test/test-environment")
@@ -462,6 +470,10 @@ describe("agent test-environment route", () => {
expect(res.status).toBe(200);
expect(res.body.status).toBe("fail");
expect(res.body.checks.map((check: { code: string }) => check.code)).toContain("ai_connection_api_key_rejected");
expect(mockMarkAuthenticationFailed).toHaveBeenCalledWith(expect.objectContaining({
companyId: "company-1",
attribution: expect.objectContaining({ connectionId: "conn-1", grantId: "grant-1" }),
}));
});
it("still fails subscription adoption when no hello probe can run", async () => {
+16 -1
View File
@@ -8,7 +8,7 @@ import { mkdtemp, rm, access, readFile, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { and, eq, sql } from "drizzle-orm";
import { createDb, companies, agents, heartbeatRuns, companyMemberships, connectionGrants, connectionGrantDelegations, connectionGrantMembers, toolConnections, toolConnectionInstalls, aiConnectionDefaults, aiProviderDefaults, adapterAuthSessions, environments, issues, issueThreadInteractions, issueRecoveryActions, connectionIntentDeliveries, agentWakeupRequests, companySecrets } from "@paperclipai/db";
import { createDb, companies, agents, heartbeatRuns, companyMemberships, connectionGrants, connectionGrantDelegations, connectionGrantMembers, toolConnections, toolConnectionInstalls, aiConnectionDefaults, aiProviderDefaults, adapterAuthSessions, environments, issues, issueThreadInteractions, issueRecoveryActions, connectionIntentDeliveries, agentWakeupRequests, companySecrets, principalPermissionGrants } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
import { aiConnectionService } from "../services/ai-connections.js";
import * as executionTarget from "@paperclipai/adapter-utils/execution-target";
@@ -46,6 +46,21 @@ beforeAll(async () => {
afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); });
describe("managed AI connections", () => {
it.each([false, true])("reports the authoritative connection-manager capability for custom grants (manager: %s)", async (manager) => {
const userId = `custom-manager-${manager}`;
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "member" });
if (manager) await db.insert(principalPermissionGrants).values({ companyId, principalType: "user", principalId: userId, permissionKey: "tools:manage_connections" });
const app = express();
app.use((req, _res, next) => {
req.actor = { type: "board", source: "session", userId, companyIds: [companyId], memberships: [{ companyId, status: "active", membershipRole: "member" }] };
next();
});
app.use("/api", aiConnectionRoutes(db));
const response = await request(app).get(`/api/companies/${companyId}/ai-connections`);
expect(response.status).toBe(200);
expect(response.body.canManageConnections).toBe(manager);
});
it.each([
["anthropic", false], ["openai", false], ["anthropic", true], ["openai", true],
] as const)("turns a %s auth failure into one card and resumes after repair (switch method: %s)", async (provider, switchMethod) => {
+22 -4
View File
@@ -3314,7 +3314,24 @@ export function agentRoutes(
});
}
async function testManagedEnvironment(adapterType: string, context: Parameters<ReturnType<typeof requireServerAdapter>["testEnvironment"]>[0], binding: AiConnectionBinding) {
async function testManagedEnvironment(adapterType: string, context: Parameters<ReturnType<typeof requireServerAdapter>["testEnvironment"]>[0], binding: AiConnectionBinding, managed: Awaited<ReturnType<typeof prepareManagedAiRuntime>>, agentId?: string) {
const startedAt = new Date();
const result = await probeManagedEnvironment(adapterType, context, binding);
// A provider rejection invalidates the tested credential generation. A
// missing CLI, unavailable environment, or other runtime error does not.
if (result.status === "fail" && result.checks.some(check =>
check.code === ADAPTER_AUTH_MISSING_CHECK_CODE || /_hello_probe_auth_required$/.test(check.code)
|| check.code === "ai_connection_api_key_rejected",
)) {
await aiConnectionService(db).markAuthenticationFailed({
companyId: context.companyId, agentId, runStartedAt: startedAt,
attribution: { ...managed.attribution, identity: managed.identity },
});
}
return result;
}
async function probeManagedEnvironment(adapterType: string, context: Parameters<ReturnType<typeof requireServerAdapter>["testEnvironment"]>[0], binding: AiConnectionBinding) {
await assertManagedAiProjectAuth(context.config, binding.provider, context.executionTarget);
const result = await requireServerAdapter(adapterType).testEnvironment(context);
if (result.status === "fail") return result;
@@ -3343,7 +3360,8 @@ export function agentRoutes(
result.checks.push({ code: "ai_connection_api_key_reverified", level: "info", message: "The provider verified this API key for adoption." });
} catch (error) {
result.status = "fail";
result.checks.push({ code: "ai_connection_api_key_rejected", level: "error", message: error instanceof HttpError ? error.message : "Could not verify the account. Try again." });
const rejected = error instanceof HttpError && asRecord(error.details)?.code === "ai_connection_api_key_rejected";
result.checks.push({ code: rejected ? "ai_connection_api_key_rejected" : "ai_connection_verification_failed", level: "error", message: error instanceof HttpError ? error.message : "Could not verify the account. Try again." });
}
return result;
}
@@ -3382,7 +3400,7 @@ export function agentRoutes(
try {
if (!target.executionTarget && target.fallbackChecks.length > 0) throw unprocessable("The agent environment is not available for adoption");
managed = await prepareManagedAiRuntime(db, { companyId, agentId, responsibleUserId: userId, adapterType, binding, config, allowUninstalledPersonal: newAgent, allowUninstalledShared, allowLegacyValidation: true });
const result = await testManagedEnvironment(adapterType, { companyId, adapterType, config: managed.config, executionTarget: target.executionTarget, environmentName: target.environmentName }, binding);
const result = await testManagedEnvironment(adapterType, { companyId, adapterType, config: managed.config, executionTarget: target.executionTarget, environmentName: target.environmentName }, binding, managed, agentId);
if (result.status === "fail" || result.checks.some(check => check.code === ADAPTER_AUTH_MISSING_CHECK_CODE)) throw unprocessable("The selected AI connection failed validation in this agent’s environment. Run the agent test to see the failing checks.", {
code: "ai_connection_validation_failed",
checks: result.checks.filter(check => check.level === "error" || check.code === ADAPTER_AUTH_MISSING_CHECK_CODE).map(check => ({ code: check.code, level: check.level })),
@@ -3577,7 +3595,7 @@ export function agentRoutes(
const managed = aiBinding ? await prepareManagedAiRuntime(db, { companyId, agentId: req.body.agentId ?? "", responsibleUserId: responsibleUserForAiRequest(req), adapterType: type, binding: aiBinding, config: effectiveAdapterConfig, allowUninstalledPersonal: !req.body.agentId, allowUninstalledShared: !req.body.agentId && await canInstallSharedAiConnectionForNewAgent(db, req, companyId, aiBinding) }) : null;
let result;
try {
result = managed && aiBinding ? await testManagedEnvironment(type, { companyId, adapterType: type, config: managed.config, executionTarget, environmentName }, aiBinding) : await adapter.testEnvironment({ companyId, adapterType: type, config: effectiveAdapterConfig, executionTarget, environmentName });
result = managed && aiBinding ? await testManagedEnvironment(type, { companyId, adapterType: type, config: managed.config, executionTarget, environmentName }, aiBinding, managed, savedAgentId ?? undefined) : await adapter.testEnvironment({ companyId, adapterType: type, config: effectiveAdapterConfig, executionTarget, environmentName });
if (managed) result.checks.unshift({ code: "ai_connection_tested", level: "info", message: `Tested ${managed.accountName} — ${managed.accountOwnerUserId ? managed.accountOwnerUserId === responsibleUserForAiRequest(req) ? "your personal account" : "the owner’s account authorized for this agent" : "company-shared account"}. Responsible user: ${req.actor.type === "agent" ? responsibleUserForAiRequest(req) ?? "unavailable" : "the signed-in user"}.` });
} finally { await managed?.cleanup(); }
+14 -13
View File
@@ -21,6 +21,7 @@ import {
type AiConnectionLoginIntent,
type AiProvider,
type AiConnectionBinding,
type AiConnectionList,
} from "@paperclipai/shared";
import { assertBoard, assertCompanyAccess, getActorInfo } from "./authz.js";
import { forbidden, notFound, unprocessable } from "../errors.js";
@@ -36,6 +37,14 @@ export function responsibleUserForAiRequest(req: Request): string | null {
: getActorInfo(req).actorId;
}
async function canManageAiConnections(db: Db, req: Request, companyId: string): Promise<boolean> {
const membership = req.actor.memberships?.find((m) => m.companyId === companyId && m.status === "active");
if (membership?.membershipRole === "viewer") return false;
return req.actor.source === "local_implicit" || Boolean(req.actor.isInstanceAdmin)
|| membership?.membershipRole === "owner" || membership?.membershipRole === "admin"
|| await accessService(db).hasPermission(companyId, "user", getActorInfo(req).actorId, "tools:manage_connections");
}
export async function assertAiConnectionCreateAccess(
db: Db,
req: Request,
@@ -76,17 +85,7 @@ export async function assertAiConnectionCreateAccess(
const membership = req.actor.memberships?.find(
(m) => m.companyId === companyId && m.status === "active",
);
const manager =
req.actor.source === "local_implicit" ||
req.actor.isInstanceAdmin ||
membership?.membershipRole === "owner" ||
membership?.membershipRole === "admin" ||
(await accessService(db).hasPermission(
companyId,
"user",
userId,
"tools:manage_connections",
));
const manager = await canManageAiConnections(db, req, companyId);
if (
!input.connectionId &&
!manager &&
@@ -155,7 +154,7 @@ export async function validateAiApiKey(
: { Authorization: `Bearer ${key}` },
});
} catch {
throw unprocessable("Could not verify the account. Try again.");
throw unprocessable("Could not verify the account. Try again.", { code: "ai_connection_verification_failed" });
}
await response.body?.cancel();
if (!response.ok)
@@ -163,6 +162,7 @@ export async function validateAiApiKey(
response.status === 401 || response.status === 403
? "The provider rejected this API key."
: "The provider could not verify this account. Try again.",
{ code: response.status === 401 || response.status === 403 ? "ai_connection_api_key_rejected" : "ai_connection_verification_failed" },
);
}
@@ -216,12 +216,13 @@ export function aiConnectionRoutes(db: Db, options: Parameters<typeof supportsLo
throw unprocessable("Invalid agent ID");
res.json({
currentUserId,
canManageConnections: await canManageAiConnections(db, req, companyId),
connections: await service.list(
companyId,
currentUserId,
agentId as string | undefined,
),
});
} satisfies AiConnectionList);
});
router.get(
"/companies/:companyId/ai-connections/:connectionId/active-runs",
+1 -1
View File
@@ -10355,7 +10355,7 @@ registerCurrentRoute({
method: "get",
path: "/api/companies/{companyId}/ai-connections",
tags: ["ai-connections"],
summary: "List available AI connections and personal defaults",
summary: "List available AI connections, personal defaults, and connection-manager access",
query: z.object({ agentId: z.string().uuid().optional() }),
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 422: r.unprocessable },
});
+3 -3
View File
@@ -778,8 +778,8 @@ export function aiConnectionService(db: Db) {
/** A late failure must never invalidate credentials that were refreshed or reconnected meanwhile. */
async function markAuthenticationFailed(input: {
companyId: string;
runId: string;
agentId: string;
runId?: string;
agentId?: string;
runStartedAt: Date;
attribution: AiConnectionAttribution & { identity: string };
}) {
@@ -812,7 +812,7 @@ export function aiConnectionService(db: Db) {
await tx.update(toolConnections).set({ healthStatus: "error", healthMessage: "Sign in again to restore this AI connection.", updatedAt: new Date() })
.where(eq(toolConnections.id, connection.id));
await logActivity(tx as unknown as Db, {
companyId: input.companyId, actorType: "system", actorId: "heartbeat",
companyId: input.companyId, actorType: "system", actorId: input.runId ? "heartbeat" : "adapter_test",
agentId: input.agentId, runId: input.runId, action: "ai_connection.authentication_failed",
entityType: "tool_connection", entityId: connection.id,
details: { provider: attribution.provider, grantId: grant.id },