mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-17 13:01:05 +01:00
fix(connections): retire satisfied connection cards on waiting tasks (#21940)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - When an agent needs a service that is not connected, it raises a "Connect" card for the responsible person > - #15856 added a sweep that retires such a card when the connection is usable again, and wakes the agent to continue > - The sweep only checks tasks that are in progress or in review > - A task that is blocked or not yet started keeps its card forever, even after the person reconnects the service > - The card then asks the person to connect a service that is already connected > - This pull request retires those cards too, without waking the agent > - The benefit is that a reconnect clears every card that it satisfies, and people do not see stale connection requests ## Linked Issues or Issue Description **What happened?** A shared Sentry connection lost its authorization. Over three days, agents raised about 40 "Connect Sentry" cards on different tasks. One task's run failed after it raised its card, and the task became blocked. When the person reconnected Sentry, the sweep retired 21 cards on in-progress and in-review tasks. Twelve cards on blocked and todo tasks stayed pending, and they kept asking the person to connect Sentry. **Expected behavior** When the requesting agent can use the connection again, its card is retired on every task that is not done or cancelled. A blocked or unstarted task does not wake because of this. **Steps to reproduce** 1. Have an agent raise a tool connection card on a task. 2. Move the task to `blocked` (for example, its run fails and recovery blocks it). 3. Make the connection usable for the agent. 4. The sweep does not retire the card. It stays pending. Related: #15856 added the sweep. #21355 adds AI repair cards to the same sweep. It does not change which task statuses the sweep checks. ## What Changed - `server/src/services/satisfied-connection-intents.ts`: - The sweep selects pending cards on all tasks that are not `done` or `cancelled`. Before, it selected only `in_progress` and `in_review` tasks. - On `in_progress` and `in_review` tasks, nothing changes. The card is retired and one continuation is saved. - On `backlog`, `todo` and `blocked` tasks, the sweep uses the same access checks (identity, membership, grants, installs, tool policy). It records the same system outcome and audit event. It does not save a continuation and does not notify the delivery worker. The delivery gate wakes only `in_progress` and `in_review` tasks, so a continuation for these tasks could never settle and would keep the worker busy. - `server/src/__tests__/satisfied-connection-intents.test.ts`: two new cases, described below. ## Verification - New tests in `satisfied-connection-intents.test.ts`: - For `blocked`, `todo` and `backlog` tasks: the card is retired with the connection, there is no delivery row, the agent is not woken, the task status does not change, and the delivery worker has no pending work. - A blocked task whose grant is revoked keeps its card pending. After the grant is active again, the next sweep retires it without a delivery row. - Fail before, pass after: with the `master` version of `satisfied-connection-intents.ts`, all 4 new cases fail. With this change, they pass. - `pnpm exec vitest run src/__tests__/connection-management.integration.test.ts src/__tests__/idle-connection-history.test.ts src/__tests__/satisfied-connection-intents.test.ts` (in `server/`): 187 passed. - `pnpm exec vitest run` on the other suites that cover connection cards and their delivery (`connection-intents-service`, `ai-connections`, `agent-setup-connection-intents`, `runner-connection-eval-fixtures`, `server-startup-feedback-export`, `run-dispatch/domain/wake-context`, `execution-blocker-read`, `recovery/reconciliation-run-read`, `chat-interaction-continuation`, `heartbeat/run-state`): 472 passed. - `pnpm exec tsc --noEmit -p .` in `server/` passes. ## Risks - A card on a blocked or unstarted task is retired without a human answer. The person no longer sees it. If the connection breaks again before the task runs, the agent raises a new card in its next run, as it does on active tasks today. - Retiring a card on a waiting task does not wake it. Today, answering a tool card on such a task does not wake it either, so continuation behavior does not change. - The sweep now checks more cards. It still reads at most 50 per pass and rotates past cards that are not ready. - The worker's pending-work check does not change. Cards on waiting tasks are retired by the next sweep that runs for any reason, including at startup. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use and code 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 - [ ] All Paperclip CI gates are green - [ ] 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:
1 parent
ee6922f705
commit
537b0408b3
2 files changed
+34
-5
No files matched your search
@@ -434,6 +434,31 @@ describePostgres("already available connection requests", () => {
|
||||
expect(wakeup).toHaveBeenCalledWith(f.agentId, expect.objectContaining({ requestedByActorType: "system", idempotencyKey: `connection-intent:${f.intent.id}:expired`, contextSnapshot: expect.objectContaining({ refreshTools: true, responsibleUserId: "connection-owner" }) }));
|
||||
});
|
||||
|
||||
it.each(["blocked", "todo", "backlog"] as const)("retires a satisfied card on a %s task without waking its agent", async (status) => {
|
||||
const f = await seed(); const wakeup = vi.fn().mockResolvedValue(null);
|
||||
await db.update(issues).set({ status }).where(eq(issues.id, f.issueId));
|
||||
const worker = connectionIntentDeliveryService(db, { wakeup });
|
||||
await worker.sweepPending();
|
||||
expect((await db.select().from(issueThreadInteractions))[0]).toMatchObject({ status: "expired", resolvedByUserId: null,
|
||||
result: { outcome: "expired", connectionId: f.connection.id } });
|
||||
expect(await db.select().from(connectionIntentDeliveries)).toHaveLength(0);
|
||||
expect(wakeup).not.toHaveBeenCalled();
|
||||
expect((await db.select().from(issues))[0].status).toBe(status);
|
||||
expect(await db.select().from(activityLog)).toEqual([expect.objectContaining({ actorType: "system", action: "issue.thread_interaction_resolved" })]);
|
||||
expect(await worker.hasPending()).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a blocked task's card pending until its connection is usable", async () => {
|
||||
const f = await seed();
|
||||
await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.issueId));
|
||||
await db.update(connectionGrants).set({ status: "revoked" });
|
||||
expect(await satisfiedConnectionIntentService(db).sweepPending()).toMatchObject({ satisfied: 0 });
|
||||
expect((await db.select().from(issueThreadInteractions))[0].status).toBe("pending");
|
||||
await db.update(connectionGrants).set({ status: "active" });
|
||||
expect(await satisfiedConnectionIntentService(db).sweepPending()).toMatchObject({ satisfied: 1 });
|
||||
expect(await db.select().from(connectionIntentDeliveries)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("rechecks access after a restart before it delivers the saved continuation", async () => {
|
||||
const f = await seed();
|
||||
await satisfiedConnectionIntentService(db).sweepPending();
|
||||
|
||||
@@ -3,7 +3,7 @@ import { notifyChatConfirmationResolution } from "./chat-confirmation-notificati
|
||||
import { enqueueTerminalIssueInteractionChatPublications } from "./chat-interaction-publications.js";
|
||||
import { connectionManagementService } from "./connection-management.js";
|
||||
import { chatCredentialEntryGenerations } from "./chat-channels/credentials.js";
|
||||
import { and, asc, eq, gt, inArray, isNull, or } from "drizzle-orm";
|
||||
import { and, asc, eq, gt, inArray, isNull, notInArray, or } from "drizzle-orm";
|
||||
import { approvals, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, toolConnections, companyMemberships, connectionIntentDeliveries, issueApprovals, issueThreadInteractions, issues, type Db } from "@paperclipai/db";
|
||||
import { connectionIntentPayloadSchema } from "@paperclipai/shared";
|
||||
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
|
||||
@@ -128,7 +128,7 @@ export function satisfiedConnectionIntentService(db: Db) {
|
||||
.from(issueThreadInteractions).innerJoin(issues, and(
|
||||
eq(issues.id, issueThreadInteractions.issueId), eq(issues.companyId, issueThreadInteractions.companyId),
|
||||
)).where(and(eq(issueThreadInteractions.kind, "connection_intent"), eq(issueThreadInteractions.status, "pending"),
|
||||
inArray(issues.status, ["in_progress", "in_review"]), isNull(issues.assigneeUserId),
|
||||
notInArray(issues.status, ["done", "cancelled"]), isNull(issues.assigneeUserId),
|
||||
...(afterId ? [gt(issueThreadInteractions.id, afterId)] : [])))
|
||||
.orderBy(asc(issueThreadInteractions.id)).limit(50);
|
||||
// Rotate past unavailable cards so they cannot starve a later ready one.
|
||||
@@ -154,7 +154,9 @@ export function satisfiedConnectionIntentService(db: Db) {
|
||||
eq(companyMemberships.principalId, intent.addresseeUserId),
|
||||
)).for("share");
|
||||
}
|
||||
const connection = await findSatisfiedToolConnection(txDb, task, intent);
|
||||
const continues = ["in_progress", "in_review"].includes(task.status);
|
||||
const connection = continues ? await findSatisfiedToolConnection(txDb, task, intent)
|
||||
: ["done", "cancelled"].includes(task.status) ? null : await findAvailableToolConnection(txDb, task, intent);
|
||||
if (!connection) return false;
|
||||
await notifyIssueReviewState(tx, candidate);
|
||||
const now = new Date();
|
||||
@@ -169,8 +171,10 @@ export function satisfiedConnectionIntentService(db: Db) {
|
||||
const interaction = await issueThreadInteractionService(txDb).getById(retired.id);
|
||||
if (interaction) await enqueueTerminalIssueInteractionChatPublications(txDb, interaction);
|
||||
await tx.update(issues).set({ updatedAt: now }).where(and(eq(issues.id, task.id), eq(issues.companyId, task.companyId)));
|
||||
await tx.insert(connectionIntentDeliveries).values({ interactionId: intent.id, companyId: task.companyId }).onConflictDoNothing();
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.connection);
|
||||
if (continues) {
|
||||
await tx.insert(connectionIntentDeliveries).values({ interactionId: intent.id, companyId: task.companyId }).onConflictDoNothing();
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.connection);
|
||||
}
|
||||
await logActivity(txDb, { companyId: task.companyId, actorType: "system", actorId: "connection-reconciliation",
|
||||
action: "issue.thread_interaction_resolved", entityType: "issue", entityId: task.id,
|
||||
details: { interactionId: intent.id, interactionKind: "connection_intent", status: "expired",
|
||||
|
||||
Reference in new issue
Block a user