mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-26 10:26:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents and boards coordinate through issue-thread interactions (request_confirmation, ask_user_questions, suggest_tasks, …) that wait as `pending` cards until someone resolves them > - Two lifecycle gaps existed: an interaction's creator could not take back a card it no longer stands behind, and interactions left `pending` on issues that reached a terminal status lingered forever as live-looking approval requests > - Stale pending cards mislead humans (they look actionable), distort attention/liveness signals, and in the worst case invite acting on a proposal whose issue is already closed or cancelled > - This pull request adds an explicit withdraw route for pending interactions and automatically expires pending interactions when their issue reaches a terminal status (including a catch-up sweep for issues closed before this change) > - The benefit is that interaction cards now faithfully reflect reality: only genuinely actionable requests stay pending, and creators can retract requests that events have overtaken ## Linked Issues or Issue Description Fixes #5787 Refs #7403 Related prior PRs found while searching for duplicates (all overlap partially; none combine both lifecycle paths or the route-level authorization used here): #6709 and #7312 (creator-withdraw attempts), #8169 (terminal expiry), #8081 and #5137 (generalized cancel/expire endpoints), #6094 (stale confirmation auto-resolve). Related merged context: #9568 (agent cancel for ask_user_questions), #10119 (tolerating legacy `withdrawn_by_creator` result outcomes — the reader side of the outcome this PR writes). ## What Changed - New route `POST /issues/:id/interactions/:interactionId/withdraw` that resolves a `pending` interaction to status `withdrawn` with a structured result (`outcome: "withdrawn"`, optional trimmed `reason`), stamps `resolvedBy*`/`resolvedAt`, touches the issue, logs activity, and emits resolved-interaction telemetry - Withdrawal authorization: board users, the interaction's creator agent, or the issue's current assignee agent (assignees additionally pass the standard issue-mutation gate); task-watchdog runs are explicitly rejected, and authorization-boundary plus low-trust control-plane checks apply - Withdrawing an already-resolved interaction returns `409`; unknown/cross-issue/cross-company interaction ids return `404` - New service method `expirePendingInteractionsForTerminalIssue`: when an issue transitions to a terminal status, all of its `pending` interactions are resolved to `expired` with `outcome: "issue_closed"`, guarded by a `status = 'pending'` predicate so concurrent resolutions are not overwritten - The same expiry runs as a catch-up when interactions are listed on an already-terminal issue, so cards stranded by issues closed before this change also get cleaned up; expired request_confirmations are logged with a distinguishing source - Shared package: new `withdrawIssueThreadInteractionSchema` validator, `WithdrawIssueThreadInteraction` type, and `withdrawn` / `issue_closed` result-outcome support for all interaction kinds (kind-aware result shapes for `ask_user_questions` and `request_item_verdicts`) - UI helper `ui/src/lib/issue-thread-interactions.ts` recognizes the new outcomes for card rendering - Docs: bundled skill API reference updated with the withdraw endpoint - Review follow-up: terminal expiry moved from the HTTP route hooks into `issueService.update`'s status-transition block, so direct service callers (tree control, recovery, pipelines, status cards) expire pending cards too; the list-endpoint catch-up remains for issues closed before this change - Review follow-up: withdrawing or issue-close-expiring a `request_confirmation` also settles its linked `tool_action_requests` row (withdraw -> `cancelled`, issue closed -> `expired`), so a parked tool call cannot stay approvable after its card is gone - Review follow-up: interaction cards render dedicated copy for the new outcomes ("Withdrawn" with the reason, "Expired when issue closed") instead of falling through to superseded-by-comment / stale-target variants; withdrawn plan reviews badge as "Withdrawn" rather than "Changes requested" ## Screenshots Card states rendered from a local ux-lab harness with mocked data ([full gallery](https://pages.paperclip.ing/pr-10251-interaction-withdrawal-cards/)): | Light | Dark | | --- | --- | |  |  | ## Verification - `pnpm --filter @paperclipai/shared build` — clean tsc - `cd server && npx vitest run src/__tests__/issue-thread-interaction-routes.test.ts` — 22 tests pass, including new coverage for: creator-agent withdraw success, non-creator/non-assignee agent 403, watchdog-run 403, double-withdraw 409, and board-user withdraw - `cd server && npx vitest run src/services/issue-thread-interactions.test.ts` — 4 tests pass, including terminal-issue expiry writing `issue_closed` results and leaving already-resolved interactions untouched - `cd ui && pnpm typecheck` — clean - `cd server && npx vitest run src/__tests__/issues-service.test.ts` — includes a new embedded-Postgres test proving a direct `issueService.update` terminal transition expires pending interactions and writes the activity-log entry - `cd ui && npx vitest run src/components/IssueThreadInteractionCard.test.tsx` — 32 tests, including new coverage for withdrawn / issue-closed confirmation and question cards - `cd server && npx tsc --noEmit` — matches the pre-existing repo error baseline exactly (no new errors) - Manual: `POST /issues/:id/interactions/:interactionId/withdraw` with `{"reason":"superseded"}` as the creator agent resolves the card to `withdrawn`; closing an issue with a pending confirmation flips it to `expired` with `outcome: "issue_closed"` ## Risks - Interactions on terminal issues now auto-expire (including retroactively via the list-time catch-up), so consumers that expected to resolve a pending interaction on a closed issue will get `409`; this is the intended semantics and matches how the attention feed already wants to treat dead cards - New result outcomes (`withdrawn`, `issue_closed`) are written to stored results; readers were already made tolerant of these outcome strings in #10119, so mixed-version reads are safe - No schema/migration changes; per-row conditional updates (`status = 'pending'`) avoid clobbering concurrent resolutions - Withdrawal is a new mutation surface, but it is strictly narrower than existing resolve paths (board, creator, or assignee only; watchdog runs blocked) ## Model Used Claude Fable 5 (`claude-fable-5`, Anthropic Mythos-class tier) with extended thinking and agentic tool use (Claude Code harness); commit authored in a Paperclip-managed engineering 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 - [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>
331 lines
13 KiB
TypeScript
331 lines
13 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { getTableName } from "drizzle-orm";
|
|
|
|
const mockCreateChild = vi.fn();
|
|
|
|
vi.mock("./issues.js", () => ({
|
|
issueService: () => ({
|
|
createChild: mockCreateChild,
|
|
}),
|
|
}));
|
|
|
|
type SelectRow = Record<string, unknown>;
|
|
|
|
function createSelectChain(rows: SelectRow[]) {
|
|
return {
|
|
from() {
|
|
return {
|
|
where() {
|
|
return {
|
|
then(callback: (rows: SelectRow[]) => unknown) {
|
|
return Promise.resolve(callback(rows));
|
|
},
|
|
};
|
|
},
|
|
};
|
|
},
|
|
};
|
|
}
|
|
|
|
function createFakeDb(args: {
|
|
interactionRow: Record<string, unknown>;
|
|
parentRows?: SelectRow[];
|
|
}) {
|
|
let interactionRow = { ...args.interactionRow };
|
|
const issueTouches: Array<Record<string, unknown>> = [];
|
|
const interactionUpdates: Array<Record<string, unknown>> = [];
|
|
const toolActionRequestUpdates: Array<Record<string, unknown>> = [];
|
|
let selectCallCount = 0;
|
|
|
|
const db: any = {
|
|
select: vi.fn(() => {
|
|
selectCallCount += 1;
|
|
return createSelectChain(selectCallCount === 1 ? [interactionRow] : (args.parentRows ?? []));
|
|
}),
|
|
update: vi.fn((table: unknown) => ({
|
|
set(values: Record<string, unknown>) {
|
|
return {
|
|
where() {
|
|
if (getTableName(table as never) === "tool_action_requests") {
|
|
toolActionRequestUpdates.push(values);
|
|
return Promise.resolve(undefined);
|
|
}
|
|
if ("status" in values || "result" in values || "resolvedAt" in values) {
|
|
interactionUpdates.push(values);
|
|
interactionRow = { ...interactionRow, ...values };
|
|
return {
|
|
returning: async () => [interactionRow],
|
|
};
|
|
}
|
|
if ("updatedAt" in values) {
|
|
issueTouches.push(values);
|
|
return Promise.resolve(undefined);
|
|
}
|
|
throw new Error(`Unexpected update target: ${String(table)}`);
|
|
},
|
|
};
|
|
},
|
|
})),
|
|
insert: vi.fn(),
|
|
transaction: async (callback: (tx: typeof db) => Promise<void>) => callback(db),
|
|
};
|
|
|
|
return {
|
|
db,
|
|
getInteractionRow: () => interactionRow,
|
|
issueTouches,
|
|
interactionUpdates,
|
|
toolActionRequestUpdates,
|
|
};
|
|
}
|
|
|
|
describe("issueThreadInteractionService", () => {
|
|
beforeEach(() => {
|
|
vi.resetModules();
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
it("create reuses an existing interaction for the same idempotency key", async () => {
|
|
const { issueThreadInteractionService } = await import("./issue-thread-interactions.js");
|
|
|
|
const existingRow = {
|
|
id: "interaction-1",
|
|
companyId: "company-1",
|
|
issueId: "11111111-1111-4111-8111-111111111111",
|
|
kind: "suggest_tasks",
|
|
status: "pending",
|
|
continuationPolicy: "wake_assignee",
|
|
idempotencyKey: "run-1:suggest",
|
|
sourceCommentId: null,
|
|
sourceRunId: "22222222-2222-4222-8222-222222222222",
|
|
title: "Break the work down",
|
|
summary: "Created from the current agent run.",
|
|
createdByAgentId: "agent-1",
|
|
createdByUserId: null,
|
|
resolvedByAgentId: null,
|
|
resolvedByUserId: null,
|
|
payload: {
|
|
version: 1,
|
|
tasks: [{ clientKey: "task-1", title: "One" }],
|
|
},
|
|
result: null,
|
|
resolvedAt: null,
|
|
createdAt: new Date("2026-04-20T10:00:00.000Z"),
|
|
updatedAt: new Date("2026-04-20T10:00:00.000Z"),
|
|
};
|
|
|
|
const db: any = {
|
|
select: vi.fn(() => createSelectChain([existingRow])),
|
|
insert: vi.fn(),
|
|
update: vi.fn(),
|
|
};
|
|
|
|
const svc = issueThreadInteractionService(db as never);
|
|
const created = await svc.create({
|
|
id: "11111111-1111-4111-8111-111111111111",
|
|
companyId: "company-1",
|
|
}, {
|
|
kind: "suggest_tasks",
|
|
idempotencyKey: "run-1:suggest",
|
|
sourceRunId: "22222222-2222-4222-8222-222222222222",
|
|
title: "Break the work down",
|
|
summary: "Created from the current agent run.",
|
|
continuationPolicy: "wake_assignee",
|
|
payload: {
|
|
version: 1,
|
|
tasks: [{ clientKey: "task-1", title: "One" }],
|
|
},
|
|
}, {
|
|
agentId: "agent-1",
|
|
});
|
|
|
|
expect(created.id).toBe("interaction-1");
|
|
expect(created.idempotencyKey).toBe("run-1:suggest");
|
|
expect(db.insert).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("answerQuestions normalizes duplicate option ids and persists answered results", async () => {
|
|
const { issueThreadInteractionService } = await import("./issue-thread-interactions.js");
|
|
|
|
const interactionRow = {
|
|
id: "interaction-2",
|
|
companyId: "company-1",
|
|
issueId: "11111111-1111-4111-8111-111111111111",
|
|
kind: "ask_user_questions",
|
|
status: "pending",
|
|
continuationPolicy: "wake_assignee",
|
|
sourceCommentId: null,
|
|
sourceRunId: null,
|
|
title: null,
|
|
summary: null,
|
|
createdByAgentId: null,
|
|
createdByUserId: "local-board",
|
|
resolvedByAgentId: null,
|
|
resolvedByUserId: null,
|
|
payload: {
|
|
version: 1,
|
|
questions: [
|
|
{
|
|
id: "scope",
|
|
prompt: "Pick one scope",
|
|
selectionMode: "single",
|
|
required: true,
|
|
options: [
|
|
{ id: "phase-1", label: "Phase 1" },
|
|
{ id: "phase-2", label: "Phase 2" },
|
|
],
|
|
},
|
|
{
|
|
id: "extras",
|
|
prompt: "Pick extras",
|
|
selectionMode: "multi",
|
|
options: [
|
|
{ id: "tests", label: "Tests" },
|
|
{ id: "docs", label: "Docs" },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
result: null,
|
|
resolvedAt: null,
|
|
createdAt: new Date("2026-04-20T10:00:00.000Z"),
|
|
updatedAt: new Date("2026-04-20T10:00:00.000Z"),
|
|
};
|
|
const state = createFakeDb({ interactionRow });
|
|
const svc = issueThreadInteractionService(state.db as never);
|
|
|
|
const result = await svc.answerQuestions({
|
|
id: "11111111-1111-4111-8111-111111111111",
|
|
companyId: "company-1",
|
|
}, "interaction-2", {
|
|
answers: [
|
|
{ questionId: "scope", optionIds: ["phase-1"] },
|
|
{ questionId: "extras", optionIds: ["docs", "tests", "docs"] },
|
|
],
|
|
summaryMarkdown: "Phase 1 with tests and docs.",
|
|
}, {
|
|
userId: "local-board",
|
|
});
|
|
|
|
expect(result.status).toBe("answered");
|
|
expect(result.result).toEqual({
|
|
version: 1,
|
|
answers: [
|
|
{ questionId: "scope", optionIds: ["phase-1"] },
|
|
{ questionId: "extras", optionIds: ["docs", "tests"] },
|
|
],
|
|
summaryMarkdown: "Phase 1 with tests and docs.",
|
|
});
|
|
expect(state.interactionUpdates).toHaveLength(1);
|
|
expect(state.issueTouches).toHaveLength(1);
|
|
});
|
|
|
|
it("withdraws a pending interaction with attribution and rejects repeats", async () => {
|
|
const { issueThreadInteractionService } = await import("./issue-thread-interactions.js");
|
|
const interactionRow = {
|
|
id: "interaction-withdraw", companyId: "company-1", issueId: "11111111-1111-4111-8111-111111111111",
|
|
kind: "request_confirmation", status: "pending", continuationPolicy: "wake_assignee",
|
|
sourceCommentId: null, sourceRunId: null, title: null, summary: null,
|
|
createdByAgentId: "agent-1", createdByUserId: null, resolvedByAgentId: null, resolvedByUserId: null,
|
|
payload: { version: 1, prompt: "Proceed?" }, result: null, resolvedAt: null,
|
|
createdAt: new Date("2026-07-25T10:00:00.000Z"), updatedAt: new Date("2026-07-25T10:00:00.000Z"),
|
|
};
|
|
const state = createFakeDb({ interactionRow });
|
|
const svc = issueThreadInteractionService(state.db as never);
|
|
const withdrawn = await svc.withdrawInteraction({ id: interactionRow.issueId, companyId: "company-1" }, interactionRow.id, { reason: "Replanning" }, { agentId: "agent-1" });
|
|
expect(withdrawn.status).toBe("cancelled");
|
|
expect(withdrawn.result).toEqual({ version: 1, outcome: "withdrawn", reason: "Replanning" });
|
|
expect(withdrawn.resolvedByAgentId).toBe("agent-1");
|
|
expect(state.toolActionRequestUpdates).toHaveLength(1);
|
|
expect(state.toolActionRequestUpdates[0]).toMatchObject({ status: "cancelled", resolvedByAgentId: "agent-1" });
|
|
const resolvedState = createFakeDb({ interactionRow: { ...interactionRow, status: "accepted" } });
|
|
const resolvedSvc = issueThreadInteractionService(resolvedState.db as never);
|
|
await expect(resolvedSvc.withdrawInteraction(
|
|
{ id: interactionRow.issueId, companyId: "company-1" },
|
|
interactionRow.id,
|
|
{},
|
|
{ agentId: "agent-1" },
|
|
)).rejects.toMatchObject({ status: 409 });
|
|
});
|
|
|
|
it("refuses withdrawal when the linked tool action is already executing", async () => {
|
|
const { issueThreadInteractionService } = await import("./issue-thread-interactions.js");
|
|
const interactionRow = {
|
|
id: "interaction-executing", companyId: "company-1", issueId: "11111111-1111-4111-8111-111111111111",
|
|
kind: "request_confirmation", status: "pending", continuationPolicy: "wake_assignee",
|
|
sourceCommentId: null, sourceRunId: null, title: null, summary: null,
|
|
createdByAgentId: "agent-1", createdByUserId: null, resolvedByAgentId: null, resolvedByUserId: null,
|
|
payload: { version: 1, prompt: "Proceed?" }, result: null, resolvedAt: null,
|
|
createdAt: new Date("2026-07-25T10:00:00.000Z"), updatedAt: new Date("2026-07-25T10:00:00.000Z"),
|
|
};
|
|
const state = createFakeDb({ interactionRow, parentRows: [{ id: "action-request-1" }] });
|
|
const svc = issueThreadInteractionService(state.db as never);
|
|
await expect(svc.withdrawInteraction(
|
|
{ id: interactionRow.issueId, companyId: "company-1" },
|
|
interactionRow.id,
|
|
{},
|
|
{ agentId: "agent-1" },
|
|
)).rejects.toMatchObject({ status: 409 });
|
|
expect(state.interactionUpdates).toHaveLength(0);
|
|
});
|
|
|
|
it("expires pending interactions when the issue is terminal", async () => {
|
|
const { issueThreadInteractionService } = await import("./issue-thread-interactions.js");
|
|
const interactionRow = {
|
|
id: "interaction-close", companyId: "company-1", issueId: "11111111-1111-4111-8111-111111111111",
|
|
kind: "ask_user_questions", status: "pending", continuationPolicy: "wake_assignee",
|
|
sourceCommentId: null, sourceRunId: null, title: null, summary: null,
|
|
createdByAgentId: "agent-1", createdByUserId: null, resolvedByAgentId: null, resolvedByUserId: null,
|
|
payload: { version: 1, questions: [{ id: "q", prompt: "Q?", selectionMode: "single", options: [{ id: "a", label: "A" }] }] },
|
|
result: null, resolvedAt: null, createdAt: new Date("2026-07-25T10:00:00.000Z"), updatedAt: new Date("2026-07-25T10:00:00.000Z"),
|
|
};
|
|
const state = createFakeDb({ interactionRow });
|
|
const svc = issueThreadInteractionService(state.db as never);
|
|
const expired = await svc.expirePendingInteractionsForTerminalIssue({ id: interactionRow.issueId, companyId: "company-1", status: "done" });
|
|
expect(expired).toHaveLength(1);
|
|
expect(expired[0]?.status).toBe("expired");
|
|
expect(expired[0]?.result).toMatchObject({ version: 1, outcome: "issue_closed", answers: [] });
|
|
expect(state.toolActionRequestUpdates).toHaveLength(0);
|
|
});
|
|
|
|
it("expires the linked tool action request when a terminal issue closes a confirmation card", async () => {
|
|
const { issueThreadInteractionService } = await import("./issue-thread-interactions.js");
|
|
const interactionRow = {
|
|
id: "interaction-tool", companyId: "company-1", issueId: "11111111-1111-4111-8111-111111111111",
|
|
kind: "request_confirmation", status: "pending", continuationPolicy: "wake_assignee",
|
|
sourceCommentId: null, sourceRunId: null, title: null, summary: null,
|
|
createdByAgentId: "agent-1", createdByUserId: null, resolvedByAgentId: null, resolvedByUserId: null,
|
|
payload: {
|
|
version: 1,
|
|
prompt: "Run the parked tool call?",
|
|
toolAction: {
|
|
version: 1,
|
|
actionRequestId: "33333333-3333-4333-8333-333333333333",
|
|
invocationId: "44444444-4444-4444-8444-444444444444",
|
|
toolName: "deploy",
|
|
toolDisplayName: "Deploy",
|
|
connectionId: null,
|
|
applicationId: null,
|
|
appDisplayName: null,
|
|
risk: "write",
|
|
previewMarkdown: "Deploy the current build.",
|
|
argumentsSummaryJson: "{}",
|
|
argumentsHash: "hash-1",
|
|
expiresAt: "2026-07-25T11:00:00.000Z",
|
|
},
|
|
},
|
|
result: null, resolvedAt: null, createdAt: new Date("2026-07-25T10:00:00.000Z"), updatedAt: new Date("2026-07-25T10:00:00.000Z"),
|
|
};
|
|
const state = createFakeDb({ interactionRow });
|
|
const svc = issueThreadInteractionService(state.db as never);
|
|
const expired = await svc.expirePendingInteractionsForTerminalIssue(
|
|
{ id: interactionRow.issueId, companyId: "company-1", status: "cancelled" },
|
|
{ userId: "local-board" },
|
|
);
|
|
expect(expired).toHaveLength(1);
|
|
expect(expired[0]?.result).toMatchObject({ version: 1, outcome: "issue_closed" });
|
|
expect(state.toolActionRequestUpdates).toHaveLength(1);
|
|
expect(state.toolActionRequestUpdates[0]).toMatchObject({ status: "expired", resolvedByUserId: "local-board" });
|
|
});
|
|
});
|