fix(connections): name an expired sign-in in connection search (#22211)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for work
> - Agents use connection search to find out if they can use an app, and what a person must do when they cannot
> - When an OAuth provider rejects a refresh token, Paperclip disables the shared connection and records `oauth_reauthorization_required`
> - Connection search then gave only the generic reason "Connection needs attention"
> - Agents could not tell a person the exact action. They had to read large app attention payloads to find the cause
> - This pull request makes connection search name the connection whose sign-in expired and say that a person must reconnect it
> - The benefit is a clear blocker that agents can report in one step, so the connection owner can renew the sign-in sooner

## Linked Issues or Issue Description

**What happened?**
A shared OAuth connection (for example, Sentry) came to the end of its provider grant. Paperclip tried the refresh token. The provider rejected it. Paperclip correctly disabled the connection and set its error to `oauth_reauthorization_required`. After that, `connections_search` returned `state: "needs_user_action"` with the reason "Connection needs attention". Scheduled agent work that needed the app stopped. The agents could not name the cause or the human action from the search result.

**Expected behavior**
Connection search tells the agent that the sign-in for the named connection expired, and that a person who manages the connection must reconnect it.

**Steps to reproduce**
1. Make a shared OAuth tool connection and give an agent access to its tools.
2. Make the provider reject the refresh token (for example, `invalid_grant`). Paperclip sets the connection to draft, disabled, health `error`, and last error `oauth_reauthorization_required`.
3. As the agent, search connections for the app.
4. See the reason "Connection needs attention". It does not say that the sign-in expired.

## What Changed

- `server/src/services/connection-intents.ts`: connection search reads the grants of each matching connection. When a grant in the caller's audience (the organization, the responsible user, or the agent) has status `needs_reauthorization`, and no grant in that audience is active, the reason names that connection. The reason says that the connection must be signed in again, and that a person who manages it must reconnect it on its app page.
- The search uses the same audience rule that protects indexed tool descriptions. A grant of another person does not show the name of that connection.
- The state, `connectionId`, and all access checks do not change.
- `server/src/__tests__/connection-intents-service.test.ts`: add two regression tests. The first test confirms that the healthy connection is `ready`. Then it writes the rows that a rejected refresh writes for an organization grant (grant `needs_reauthorization`, connection `draft` and disabled, no `lastError`), and examines the reason. The second test makes sure that the private connection of another person is not named.

## Verification

- Failing before the fix (in `server/`): `pnpm exec vitest run src/__tests__/connection-intents-service.test.ts -t "must be renewed"`. The shared test failed with `AssertionError: expected 'Review identity and access for this agent' to contain 'Saved sentry'`.
- The private-connection test failed against the first commit of this PR (`lastError` match without an audience check) with `expected 'The sign-in for "Private Sentry of another person" expired. ...' not to contain 'Private Sentry of another person'`.
- Passing after the fix: `connection-intents-service.test.ts` passes (37 of 37).
- Related suites pass: `agent-setup-connection-intents`, `connection-aggregator-fallback`, `satisfied-connection-intents` (168 of 168 with the file above).
- `pnpm run typecheck` in `server/` passes.
- The grant state comes from the refresh writer in `grant-refresh.ts`. Existing tests in `tool-access-service.test.ts` make sure that a rejected refresh sets the grant to `needs_reauthorization`.
- I did not run the full `pnpm verify`.

## Risks

- Low risk. The change only changes the text of one search reason. It does not change state, access decisions, or what agents can call.
- The reason does not use `lastError`, because health checks write display text into that column, and the default refresh path does not write it.
- The member-removal path also sets remaining grants to `needs_reauthorization`. The text "must be signed in again" is correct for that case too.
- I examined the refresh path. Paperclip already tries the refresh token before it marks the grant. This PR does not change that path.
- Out of scope: Paperclip does not send a notification to the connection owner, and the connection request card does not offer to reconnect the existing connection. These need separate changes.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in an agent harness.

## 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
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)




Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-18 15:25:00 -06:00
1 parent c36e791bd9
commit 01d74a52a2
2 files changed
+40 -3

No files matched your search

@@ -1183,6 +1183,38 @@ describeEmbeddedPostgres("connectionIntentService", () => {
responsibleUserId: "grant-user", serviceSlug: "notion" })).resolves.toMatchObject({ id: f.connection.id });
});
it("names a shared connection whose sign-in must be renewed instead of a generic attention reason", async () => {
const f = await accessFixture("sentry");
const [profile] = await db.insert(toolProfiles).values({ companyId: f.company.id, profileKey: randomUUID(), name: "Sentry", defaultAction: "allow", status: "active" }).returning();
await db.insert(toolProfileBindings).values({ companyId: f.company.id, profileId: profile.id, targetType: "agent", targetId: f.agent.id });
const sentry = async () => (await f.service.search(f.claims, "sentry")).results.find(item => item.service === "sentry");
expect(await sentry()).toMatchObject({ state: "ready", connectionId: f.connection.id });
// The rows a rejected refresh writes for an organization grant: the grant
// needs reauthorization and the connection is disabled. lastError is unchanged.
await db.update(connectionGrants).set({ status: "needs_reauthorization" })
.where(eq(connectionGrants.connectionId, f.connection.id));
await db.update(toolConnections).set({ authKind: "oauth", status: "draft", enabled: false })
.where(eq(toolConnections.id, f.connection.id));
const result = await sentry();
expect(result).toMatchObject({ state: "needs_user_action", connectionId: null });
expect(result?.reason).toContain("Saved sentry");
expect(result?.reason).toMatch(/sign in again|signed in again/i);
expect(result?.reason).toMatch(/reconnect/i);
});
it("does not name another person's private connection that must be renewed", async () => {
const f = await accessFixture("sentry");
await db.update(connectionGrants).set({ kind: "user", subjectUserId: "other-user", status: "needs_reauthorization" })
.where(eq(connectionGrants.connectionId, f.connection.id));
await db.delete(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, f.connection.id));
await db.update(toolConnections).set({
name: "Private Sentry of another person", authKind: "oauth", credentialPolicy: "per_user", status: "draft", enabled: false,
}).where(eq(toolConnections.id, f.connection.id));
const result = (await f.service.search(f.claims, "sentry")).results.find(item => item.service === "sentry");
expect(result).toBeDefined();
expect(result?.reason).not.toContain("Private Sentry of another person");
});
it("creates a scoped access card and atomically accepts repeated clicks without granting other agents", async () => {
const f = await accessFixture();
const request = await f.service.request(f.claims, "composio", { connectionId: f.connection.id, toolNames: ["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_MANAGE_CONNECTIONS"] });
+8 -3
View File
@@ -540,12 +540,16 @@ export function connectionIntentService(db: Db) {
&& (aiOnly ? connection.connectionPurpose === "ai" : connection.connectionPurpose !== "ai"));
// Indexed descriptions can contain private workspace metadata, including
// for catalog providers. Check each configured connection's audience first.
const reauthorizationRequired: ToolConnection[] = [];
const catalogs = await Promise.all(matching.map(async (connection) => {
const { grants } = await access.listConnectionGrants(connection.id, run.companyId);
const authorized = grants.some((grant) => grant.status === "active" && (
const audience = grants.filter((grant) =>
grant.kind === "organization" || (grant.kind === "user" && grant.subjectUserId === run.responsibleUserId)
|| (grant.kind === "agent" && grant.subjectAgentId === agent.id)
));
|| (grant.kind === "agent" && grant.subjectAgentId === agent.id));
const authorized = audience.some((grant) => grant.status === "active");
// A rejected refresh marks the grant. Name only connections in this
// caller's audience so the agent can report the exact human action.
if (!authorized && audience.some((grant) => grant.status === "needs_reauthorization")) reauthorizationRequired.push(connection);
const entries = authorized ? await indexedCatalog(connection.id, run.companyId) : [];
authorizedCatalogs.set(connection.id, entries);
return entries;
@@ -581,6 +585,7 @@ export function connectionIntentService(db: Db) {
state: ready ? "ready" : (denied && !isRemoteMcpConnectorId(service)) || !app.available || !app.methods.length ? "unavailable"
: matching.length ? "needs_user_action" : "available",
reason: ready ? "Connection is installed and usable by this agent" : denied ? "Ask the responsible user to grant this agent access with connection_request" : !app.available ? "Connection is disabled or unavailable"
: reauthorizationRequired.length ? `"${reauthorizationRequired[0]!.name}" must be signed in again. A person who manages this connection must reconnect it on its app page`
: matching.some((connection) => isToolConnectionAttentionHealth(connection.healthStatus)) ? "Connection needs attention"
: matching.length ? "Review identity and access for this agent" : "Connect this service to continue",
connectionId: ready?.id ?? null,