Files
PaperClipAI/ui/src/lib/interaction-resolution-error.ts
T
DottaandPaperclip c67909cb0f fix: keep tool approvals valid through OAuth refresh and delayed review (#20340)
## Thinking Path

> - Paperclip lets people manage agent work and approve app actions.
> - An approval must bind the action that the person reviewed.
> - OAuth access tokens can expire while that person is away.
> - The old target snapshot treated each token refresh as a new
authorization. It also imposed a one-hour review deadline.
> - This pull request separates token renewal from authorization
identity and keeps the human decision durable.
> - Current access, the reviewed arguments, meaningful target changes,
task closure, and execution receipts still control dispatch.
> - People can approve later without repeating a decision after routine
connection maintenance.

## Linked Issues or Issue Description

**What happened?**

A pending app action returned `approved_tool_target_changed` after its
OAuth tokens refreshed. The tool and connection settings were unchanged.
The same card also expired after one hour. A sign-in problem could
discard an accepted decision before provider dispatch.

**Expected behavior**

The original card remains reviewable after routine OAuth refresh and a
server restart. A later approval runs the exact reviewed action once. A
connection repair preserves the decision while Paperclip verifies the
same authorization. Meaningful changes require a new review.

**Steps to reproduce**

1. Connect an OAuth MCP app and configure an action to require approval.
2. Request the action, then refresh its access and refresh tokens before
approving.
3. Approve the original card. Before this change, it returns HTTP 409
even when the authorization is unchanged.
4. Wait more than one hour. Before this change, the card expires without
a task-specific deadline.

**Paperclip version or commit**

Reproduced from master at `76254ead2229`. The final branch is rebased
onto current master.

## What Changed

- Add versioned approval target comparison. New snapshots bind
credential identity epochs, consent, permissions, ownership, connection
configuration, tool contracts, and credential references. Authenticated
OAuth refresh preserves identity. Manual credential replacement does
not.
- Remove the implicit one-hour deadline from ordinary app action
reviews. Keep explicit deadlines and terminal-task expiry. Synchronize
the nullable interaction deadline in shared contracts and UI.
- Keep accepted, undispatched actions when sign-in is required. Show a
saved-approval repair state. Resume on committed connection changes
after target and access revalidation, without an idle retry loop.
- Preserve the existing execution claim, result receipt, and
uncertain-outcome no-replay rules.
- Explain meaningful target changes without inviting the person to retry
the stale card.
- Add a production task-thread Storybook example and document
compatibility and recovery behavior.

## Verification

- Red: production-refresher invalid-grant handling and formal-approval
withdrawal during a sign-in wait also reproduced as failing regressions
before their fixes.
- Red: before implementation, the local OAuth HTTP fixture failed for
both public and confidential clients with `approved_tool_target_changed`
after token refresh.
- Green: the extended fixture passes for public and confidential clients
with personal and shared grants. It covers actual local HTTP token
exchanges, multiple refreshes, a rebuilt gateway, an ended originating
run, approval after 25 hours, duplicate approval, preserved sharing
arguments, sign-in waiting, and event-driven repair. The gateways use
the production OAuth refresher; an invalid refresh preserves the
accepted decision before provider dispatch. Omitted-scope responses
cover equivalent scope-reporting changes. The provider is an isolated
local fixture, not a deployed Notebook service.
- Negative controls refuse changed consent, scopes, tool definition,
destination, and manual credential replacement before provider
execution.
- Existing gateway service, connected-tool acceptance, secret owner,
secret service, unsigned-review queue, and connection-health suites
passed. Explicit-deadline fixtures still prove expiry behavior,
including deadlines on accepted sign-in waits. A withdrawn formal
approval cancels a waiting action before connection recovery.
- Approval card, task-chat, error-copy and target-comparison tests
passed. Server and UI typechecks passed. Token gates and Storybook
catalog checks passed.
- Inspected the new saved-approval repair card in local Storybook using
the production task thread. It shows a reconnect link and no second
approval button or false running state.
- `pnpm verify --explain` returned exit 2 and requested broad CI
coverage. [Full
CI](https://github.com/paperclipai/paperclip/actions/runs/42677855507)
passed on `eb4f1c7caa9ee6e802c314ffc5eadec475a5de0c`, including build,
typecheck/release registry, general and serialized tests, and all eight
browser shards.
- Greptile reviewed the same final head at 5/5. Both findings from the
first review are fixed and their threads resolved; no open follow-ups
remain.

## Risks

- No database migration is needed. The new comparison reuses the vault
identity epoch. Only authenticated OAuth refresh code can preserve that
epoch; HTTP credential-write schemas cannot select that behavior.
- Earlier signed requests keep their original exact-version checks and
saved deadlines. Already-expired cards are not revived. A historical
card whose credentials already changed needs a fresh review.
- A new consent, account, permission set, destination, or manually
replaced credential must not inherit the old authorization. Reconnection
continues automatically only when revalidation proves the same saved
authorization.
- The interaction enrichment now permits a null deadline. Existing
string deadlines remain valid. The web client and shared validator
change together.
- This PR does not deploy to staging or perform a live Notebook
publication.

## Model Used

OpenAI Codex, GPT-6 family, with repository tools, code execution, and
browser inspection. The runtime does not expose the exact model ID,
context-window limit, or reasoning-mode label; those values are not
asserted.

## 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>
2026-11-09 13:46:28 -06:00

176 lines
6.5 KiB
TypeScript

/**
* Plain-language copy for a *failed* issue-thread interaction resolution
* (PAP-17287).
*
* The resolution routes deny with a specific reason — human-only, creator
* excluded, addressee mismatch, a governed action, an already-resolved card.
* Collapsing all of that to `Try again` tells an operator to repeat an action
* that will never succeed, so this module keeps the server's explanation and,
* for an audience denial, follows it with who *can* respond.
*
* Presentation only. Authority is the server's: nothing here decides whether an
* action is permitted, it only explains the answer the server already gave.
*/
import { describeError, errorCopy, isRawErrorCode, isTransientError } from "@/api/errors";
import type { InteractionAudienceDescription } from "./interaction-audience";
/**
* Denials that mean "you are outside this card's resolver audience". Mirrors the
* codes the server's audience evaluator can return
* (`server/src/services/issue-thread-interaction-resolution.ts`), plus the
* scope denial raised before it.
*/
export const INTERACTION_AUDIENCE_DENIAL_CODES = [
"interaction_human_only",
"interaction_creator_excluded",
"interaction_addressee_mismatch",
"interaction_governed_action_denied",
"interaction_run_attribution_required",
"interaction_scope_denied",
] as const;
/**
* Denials that are permanent for a different reason: the card moved on. Retrying
* cannot help, so these lose the retry prompt too.
*/
const INTERACTION_SETTLED_CODES = [
"interaction_not_found",
"interaction_already_resolved",
"interaction_superseded",
"interaction_stale_target",
"interaction_issue_closed",
"approved_tool_target_changed",
"approved_tool_managed_arguments_changed",
] as const;
export type InteractionResolutionFailureKind = "audience_denied" | "settled" | "transient";
export interface InteractionResolutionFailure {
kind: InteractionResolutionFailureKind;
/** Copy for the inline error region. Never invites a retry that cannot work. */
message: string;
/** Server-provided denial code, when the response carried one. */
code: string | null;
}
function record(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: null;
}
/** The server's `code`, from either the top-level field or the details object. */
export function interactionResolutionErrorCode(error: unknown): string | null {
const body = record(record(error)?.body);
if (!body) return null;
if (typeof body.code === "string" && body.code) return body.code;
const details = record(body.details);
return typeof details?.code === "string" && details.code ? details.code : null;
}
function errorStatus(error: unknown): number | null {
const status = record(error)?.status;
return typeof status === "number" ? status : null;
}
/**
* The server's human-readable reason, preserved verbatim apart from
* punctuation. A raw code (`tenant_app_unavailable`) is not a reason.
*/
function serverReason(error: unknown): string | null {
const body = record(record(error)?.body);
const fromBody = typeof body?.error === "string" ? body.error.trim() : "";
const fromError = error instanceof Error ? error.message.trim() : "";
const reason = [fromBody, fromError].find((text) => text && !isRawErrorCode(text));
if (!reason) return null;
// The API writes reasons as bare clauses ("This interaction is human-only").
return /[.!?]$/.test(reason) ? reason : `${reason}.`;
}
export function isInteractionAudienceDenial(error: unknown): boolean {
const code = interactionResolutionErrorCode(error);
if (code) return (INTERACTION_AUDIENCE_DENIAL_CODES as readonly string[]).includes(code);
// A 403 with no code is still an authorization refusal, not a hiccup.
return errorStatus(error) === 403;
}
/** The audience of the card being resolved, as far as this client knows it. */
export type InteractionResolutionAudience = Pick<
InteractionAudienceDescription,
"shortSummary" | "isOpen"
>;
/**
* Classify a rejected resolution and produce the copy to show inline.
*
* `audience` is the effective audience of the card being resolved; when the
* failure is an audience denial *and* that audience is narrower than the open
* default, its short form is appended so the reader learns who can respond
* instead of being told to retry.
*/
export function describeInteractionResolutionFailure(
error: unknown,
audience?: InteractionResolutionAudience | null,
): InteractionResolutionFailure {
const code = interactionResolutionErrorCode(error);
const reason = serverReason(error);
if (isInteractionAudienceDenial(error)) {
// Only a *narrowed* audience has a responder worth naming. Appending the
// open-default clause to a refusal produces copy that refutes itself —
// "You are not in this card's resolver audience. Anyone can respond." —
// which happens whenever the snapshot the client holds is wider than the
// policy the server just enforced (PAP-17289).
const responder = audience && !audience.isOpen && audience.shortSummary
? `${audience.shortSummary}.`
: null;
// Without a code the server has told us only that this is forbidden, not
// *why*. Restate the status; do not invent a resolver-audience cause it
// never claimed.
const coded = code !== null
&& (INTERACTION_AUDIENCE_DENIAL_CODES as readonly string[]).includes(code);
return {
kind: "audience_denied",
code,
message: [
reason
?? (coded
? errorCopy("interaction_audience_denied").body
: errorCopy("interaction_forbidden").body),
responder,
]
.filter(Boolean)
.join(" "),
};
}
if (code && (INTERACTION_SETTLED_CODES as readonly string[]).includes(code)) {
return {
kind: "settled",
code,
message: reason ?? errorCopy("interaction_settled").body,
};
}
// An outage or gateway blip: the server's text is a status line or a raw
// code, so use the shared copy (which already invites a retry).
if (isTransientError(error)) {
return { kind: "transient", code, message: describeError(error).body };
}
return {
kind: "transient",
code,
message: reason ? `${reason} Try again.` : errorCopy("interaction_submit_failed").body,
};
}
/** Convenience for the many call sites that only need the sentence. */
export function interactionResolutionErrorMessage(
error: unknown,
audience?: InteractionResolutionAudience | null,
): string {
return describeInteractionResolutionFailure(error, audience).message;
}