fix(interactions): wait for workspace readiness before enabling approval (#14893)

## Thinking Path

> - Paperclip lets people manage AI agents and review their work.
> - Task confirmations must use the work produced by their source run.
> - The server blocks approval while that run still needs to sync its
workspace.
> - The card currently enables approval before that check can pass, so
an ordinary click produces an error.
> - This PR exposes the existing readiness check and shows “Preparing
approval…” with acceptance disabled.
> - The card refreshes itself and enables approval when the source
workspace settles.

## Linked Issues or Issue Description

**What happened?**

A confirmation appears while its source run is still preparing or
syncing its workspace. Its enabled approval button returns a conflict
asking the user to retry after syncing.

**Steps to reproduce**

1. Run an agent in an isolated workspace.
2. Have it create a confirmation before workspace finalization
completes.
3. Click the approval button while the source workspace is still active.

**Expected behavior**

The card explains that approval is preparing. Acceptance becomes
available automatically when the same server check permits it. Reject
and revise remain available.

Related work: #10770 handles this conflict after a click with retries.
#9520 proposes changing the workspace acceptance barrier. This PR
preserves that barrier and exposes readiness before the click, including
in compact task chat. It preserves the terminal-finalize behavior from
#10099.

## What Changed

- Add an optional, read-only `acceptanceBlocker` to interaction
responses. Readiness uses the existing source-run workspace predicate,
with one check per pending source run.
- Disable acceptance and show a shared preparation notice in classic and
compact confirmation cards, including checkbox and secret-binding
confirmations.
- Refresh preparing cards every two seconds in task detail, attention,
pipelines, and Skill Studio. Restore each surface's previous polling
cadence when preparation clears.
- Preserve live tool reviews, questions, rejection, revision, and the
server acceptance barrier. No automatic acceptance occurs.
- Document the preparation state and cover readiness, terminal sync
outcomes, unrelated runs, historical cards, and automatic refresh.

## Verification

- Focused service, card, query-refresh, and helper tests: 217 passed
across five files.
- `pnpm -r typecheck`: passed.
- `pnpm build`: passed.
- `pnpm build-storybook`: passed.
- `pnpm check:token-gates`: passed.
- `pnpm test:run`: incomplete locally. Stopped after about 17 minutes
once it reproduced seven existing environment failures: two Slack tests
and two email tests lack ancestor-directory skill fixtures; three
company-skills tests fail on macOS runtime-cache staging permissions.
These are outside this change. The full CI test matrix passed.
- CI: all 53 checks passed; two optional Storybook jobs were skipped.
The branch has no conflicts with `master`.
- Greptile: 5/5 on commit `8a6f216d8d`, with no review threads.
- Reviewed added lines and new files for credentials, private URLs,
internal task references, user paths, and run artifacts. None found.

## Risks

- No database migration or change to acceptance authorization. Readiness
is advisory; the server still enforces its existing gate at acceptance.
- An open preparing card adds a read every two seconds. This cadence
stops after readiness clears; historical cards add no workspace checks.
- Failed or stale finalization retains the existing server behavior.
This PR does not change recovery policy.

## Model Used

OpenAI GPT-6 through Codex. The exact serving model ID and
context-window size are not exposed in this session. Used reasoning,
repository inspection, tool execution, and automated tests. No
sub-agents.

## 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 (217 focused tests; full
local-suite limitations are recorded above)
- [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:
Devin FoleyandPaperclip authored and GitHub committed 2026-10-02 13:08:25 -07:00
1 parent 806af230b6
commit 144083fd48
16 files changed
+338 -13

No files matched your search

+4
View File
@@ -66,6 +66,10 @@ paused.” and “Resume this task to send a message.” with a “Resume task
Subtrees use “Subtree is paused.” and “Resume subtree.” The takeover cannot be
dismissed, retains drafts, and hides message inputs until the pause is released.
Confirmations whose source work is still syncing show “Preparing approval…” and
disable acceptance until the server reports readiness. Refresh that state automatically;
rejection and revision remain available. Live tool reviews keep their own approval flow.
Pending questions, confirmations, and other task-thread inputs appear in a separate
card directly above the ordinary composer. The composer stays available for new
messages while the card is open. Dismissing a card leaves a pending indicator that
+2
View File
@@ -1516,6 +1516,8 @@ export interface IssueThreadInteractionBase extends IssueThreadInteractionActorF
summary?: string | null;
status: IssueThreadInteractionStatus;
continuationPolicy: IssueThreadInteractionContinuationPolicy;
/** Read-time acceptance gate; omitted when no workspace preparation is pending. */
acceptanceBlocker?: "workspace_sync_pending";
/** @deprecated Read requestedResolverPolicy. Kept for API compatibility. */
resolverPolicy: IssueThreadInteractionCanonicalResolverPolicy;
requestedResolverPolicy: IssueThreadInteractionCanonicalResolverPolicy;
@@ -4474,6 +4474,96 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
};
}
it.each(["request_confirmation", "request_checkbox_confirmation"] as const)(
"projects %s readiness until its source workspace settles",
async (kind) => {
const { companyId, executionWorkspaceId, issueId, interactionId, sourceRunId, foreignRunId } =
await seedAcceptGateFixture({ kind, sourceRunStatus: "running" });
// A source run without workspace operations needs no sync barrier.
expect((await interactionsSvc.listForIssue(issueId))[0].acceptanceBlocker).toBeUndefined();
await db.insert(workspaceOperations).values({
companyId, executionWorkspaceId, heartbeatRunId: sourceRunId,
phase: "worktree_prepare", status: "succeeded",
});
const assertPreparing = async () => {
const expected = { id: interactionId, status: "pending", acceptanceBlocker: "workspace_sync_pending" };
expect((await interactionsSvc.listForIssue(issueId))[0]).toMatchObject(expected);
expect(await interactionsSvc.getById(interactionId)).toMatchObject(expected);
expect(await interactionsSvc.getForIssue({ id: issueId, companyId }, interactionId)).toMatchObject(expected);
};
await assertPreparing();
const [finalize] = await db.insert(workspaceOperations).values({
companyId, executionWorkspaceId, heartbeatRunId: sourceRunId,
phase: "workspace_finalize", status: "running",
}).returning();
await assertPreparing();
await db.update(workspaceOperations).set({ status: "succeeded" }).where(eq(workspaceOperations.id, finalize.id));
await db.insert(workspaceOperations).values({
companyId, executionWorkspaceId, heartbeatRunId: foreignRunId,
phase: "worktree_prepare", status: "succeeded",
});
expect((await interactionsSvc.listForIssue(issueId))[0].acceptanceBlocker).toBeUndefined();
expect((await interactionsSvc.getById(interactionId))?.acceptanceBlocker).toBeUndefined();
expect((await interactionsSvc.getForIssue({ id: issueId, companyId }, interactionId)).acceptanceBlocker).toBeUndefined();
},
);
it.each(["failed", "skipped", "stale"])("does not keep preparing after a %s finalize", async (outcome) => {
const { companyId, executionWorkspaceId, issueId, sourceRunId } =
await seedAcceptGateFixture({ sourceRunStatus: "failed" });
await db.insert(workspaceOperations).values({
companyId, executionWorkspaceId, heartbeatRunId: sourceRunId,
phase: "workspace_finalize", status: outcome === "stale" ? "running" : outcome,
});
expect((await interactionsSvc.listForIssue(issueId))[0].acceptanceBlocker).toBeUndefined();
});
it.each(["accepted", "rejected", "cancelled", "expired"])("does not project a blocker on %s history", async (status) => {
const { companyId, executionWorkspaceId, issueId, interactionId, sourceRunId } = await seedAcceptGateFixture();
await db.insert(workspaceOperations).values({
companyId, executionWorkspaceId, heartbeatRunId: sourceRunId,
phase: "worktree_prepare", status: "succeeded",
});
await db.update(issueThreadInteractions).set({ status }).where(eq(issueThreadInteractions.id, interactionId));
expect((await interactionsSvc.listForIssue(issueId))[0].acceptanceBlocker).toBeUndefined();
expect((await interactionsSvc.getById(interactionId))?.acceptanceBlocker).toBeUndefined();
});
it("does not project a blocker for confirmations expired by task closure", async () => {
const { companyId, executionWorkspaceId, issueId, sourceRunId } = await seedAcceptGateFixture();
await db.insert(workspaceOperations).values({
companyId, executionWorkspaceId, heartbeatRunId: sourceRunId,
phase: "worktree_prepare", status: "succeeded",
});
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
const [interaction] = await interactionsSvc.listForIssue(issueId);
expect(interaction.status).toBe("expired");
expect(interaction.acceptanceBlocker).toBeUndefined();
});
it.each(["toolAction", "ask_user_questions"])(
"keeps live %s decisions available while the workspace is active",
async (kind) => {
const { companyId, executionWorkspaceId, issueId, interactionId, sourceRunId } =
await seedAcceptGateFixture({ sourceRunStatus: "running" });
await db.insert(workspaceOperations).values({
companyId, executionWorkspaceId, heartbeatRunId: sourceRunId,
phase: "worktree_prepare", status: "succeeded",
});
const payload = kind === "ask_user_questions"
? { version: 1, questions: [{ id: "question", prompt: "Which option?", selectionMode: "single", options: [{ id: "first", label: "First" }] }] }
: { version: 1, prompt: "Allow this action?", [kind]: { version: 1, actionRequestId: randomUUID(), invocationId: randomUUID(), toolName: "example.write",
toolDisplayName: "Write", connectionId: randomUUID(), applicationId: randomUUID(),
appDisplayName: "Example", risk: "write", previewMarkdown: "Write one row", argumentsSummaryJson: "{}",
argumentsHash: "hash", expiresAt: "2099-01-01T00:00:00.000Z" } };
await db.update(issueThreadInteractions).set({
kind: kind === "ask_user_questions" ? kind : "request_confirmation", payload,
}).where(eq(issueThreadInteractions.id, interactionId));
expect((await interactionsSvc.listForIssue(issueId))[0].acceptanceBlocker).toBeUndefined();
expect((await interactionsSvc.getById(interactionId))?.acceptanceBlocker).toBeUndefined();
},
);
it("allows request_confirmation accept when the source run finalized but a foreign run is mid-flight", async () => {
const { companyId, executionWorkspaceId, issueId, goalId, interactionId, sourceRunId, foreignRunId } =
await seedAcceptGateFixture();
@@ -1997,6 +1997,53 @@ export function issueThreadInteractionService(
.then((rows) => rows[0] ?? null);
}
// Readiness is a projection, not durable interaction state. Use the same
// source-run predicate as accept so another run cannot hold a ready card back.
async function withAcceptanceReadiness(
interactions: IssueThreadInteraction[],
issueWorkspace?: { companyId: string; executionWorkspaceId: string | null },
): Promise<IssueThreadInteraction[]> {
const guarded = interactions.filter((interaction) =>
interaction.status === "pending"
&& interaction.sourceRunId
&& (interaction.kind === "request_checkbox_confirmation"
|| (interaction.kind === "request_confirmation"
// Tool reviews resolve through their own route while the originating
// run may be waiting for the user's decision.
&& !interaction.payload.toolAction)),
);
if (guarded.length === 0) return interactions;
const workspace = issueWorkspace ?? await db
.select({
companyId: issues.companyId,
executionWorkspaceId: issues.executionWorkspaceId,
})
.from(issues)
.where(and(
eq(issues.id, guarded[0].issueId),
eq(issues.companyId, guarded[0].companyId),
))
.then((rows) => rows[0]);
if (!workspace?.executionWorkspaceId) return interactions;
// Only pending confirmations need checks, once per source run even if that
// run produced several cards. Historical interactions add no queries.
const { companyId, executionWorkspaceId } = workspace;
const sourceRunIds = [...new Set(guarded.map((interaction) => interaction.sourceRunId!))];
const pendingRunIds = new Set<string>();
await Promise.all(sourceRunIds.map(async (runId) => {
if (!await runWorkspaceIsFinalized(db, companyId, executionWorkspaceId, runId)) {
pendingRunIds.add(runId);
}
}));
const guardedIds = new Set(guarded.map((interaction) => interaction.id));
return interactions.map((interaction) =>
guardedIds.has(interaction.id) && pendingRunIds.has(interaction.sourceRunId!)
? { ...interaction, acceptanceBlocker: "workspace_sync_pending" }
: interaction,
);
}
async function getForIssue(
issue: { id: string; companyId: string },
interactionId: string,
@@ -2013,7 +2060,7 @@ export function issueThreadInteractionService(
) {
throw interactionNotFoundError();
}
return hydrateInteraction(current);
return (await withAcceptanceReadiness([hydrateInteraction(current)]))[0];
}
async function assertIssueWorkspaceFinalizedForAccept(args: {
@@ -2972,7 +3019,7 @@ export function issueThreadInteractionService(
};
},
listForIssue: async (issueId: string) => {
const [rows, issueStatus] = await Promise.all([
const [rows, issue] = await Promise.all([
db
.select()
.from(issueThreadInteractions)
@@ -2982,16 +3029,20 @@ export function issueThreadInteractionService(
asc(issueThreadInteractions.id),
),
db
.select({ status: issues.status })
.select({
status: issues.status,
companyId: issues.companyId,
executionWorkspaceId: issues.executionWorkspaceId,
})
.from(issues)
.where(eq(issues.id, issueId))
.then((issueRows) => issueRows[0]?.status ?? null),
.then((issueRows) => issueRows[0]),
]);
return rows.map((row) =>
const interactions = rows.map((row) =>
hydrateInteraction(
issueStatus &&
isTerminalIssueStatus(issueStatus) &&
issue &&
isTerminalIssueStatus(issue.status) &&
row.status === "pending"
? {
...row,
@@ -3002,6 +3053,7 @@ export function issueThreadInteractionService(
: row,
),
);
return withAcceptanceReadiness(interactions, issue);
},
getById: async (interactionId: string) => {
@@ -3011,7 +3063,7 @@ export function issueThreadInteractionService(
.where(eq(issueThreadInteractions.id, interactionId))
.then((rows) => rows[0] ?? null);
return row ? hydrateInteraction(row) : null;
return row ? (await withAcceptanceReadiness([hydrateInteraction(row)]))[0] : null;
},
recordSecretProposalExecutionResult: async (
@@ -0,0 +1,66 @@
// @vitest-environment jsdom
import { act, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, expect, it, vi } from "vitest";
import { issuesApi } from "../api/issues";
import { pendingRequestConfirmationInteraction } from "../fixtures/issueThreadInteractionFixtures";
import { ThemeProvider } from "../context/ThemeContext";
import { TooltipProvider } from "./ui/tooltip";
import { AttentionInteractionResolver } from "./AttentionInteractionResolver";
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
vi.mock("@/lib/router", () => ({
Link: ({ children }: { children: ReactNode }) => <span>{children}</span>,
}));
vi.mock("../api/issues", () => ({
issuesApi: { listInteractions: vi.fn(), acceptInteraction: vi.fn() },
}));
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
});
it("refreshes a preparing approval automatically, then stops polling without accepting it", async () => {
vi.useFakeTimers();
const interaction = pendingRequestConfirmationInteraction;
vi.mocked(issuesApi.listInteractions)
.mockResolvedValueOnce([{ ...interaction, acceptanceBlocker: "workspace_sync_pending" }])
.mockResolvedValue([interaction]);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
try {
await act(async () => root.render(
<QueryClientProvider client={client}>
<TooltipProvider><ThemeProvider>
<AttentionInteractionResolver
companyId={interaction.companyId}
issueId={interaction.issueId}
interactionId={interaction.id}
/>
</ThemeProvider></TooltipProvider>
</QueryClientProvider>,
));
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
const approve = () => container.querySelector<HTMLButtonElement>('[data-testid="confirmation-actions"] button')!;
expect(approve().disabled).toBe(true);
expect(container.textContent).toContain("Preparing approval…");
await act(async () => { await vi.advanceTimersByTimeAsync(2_001); });
expect(issuesApi.listInteractions).toHaveBeenCalledTimes(2);
expect(approve().disabled).toBe(false);
expect(container.textContent).not.toContain("Preparing approval…");
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
expect(issuesApi.listInteractions).toHaveBeenCalledTimes(2);
expect(issuesApi.acceptInteraction).not.toHaveBeenCalled();
} finally {
await act(async () => root.unmount());
container.remove();
client.clear();
}
});
@@ -5,6 +5,7 @@ import type { Agent } from "@paperclipai/shared";
import { issuesApi } from "../api/issues";
import { queryKeys } from "../lib/queryKeys";
import {
interactionReadinessRefetchInterval,
isIssueThreadInteraction,
type AskUserQuestionsAnswer,
type AskUserQuestionsInteraction,
@@ -61,6 +62,7 @@ export function AttentionInteractionResolver({
queryKey: queryKeys.issues.interactions(issueId),
queryFn: () => issuesApi.listInteractions(issueId),
enabled: !!issueId,
refetchInterval: (query) => interactionReadinessRefetchInterval(query.state.data),
});
const interaction = useMemo<IssueThreadInteraction | null>(() => {
@@ -0,0 +1,10 @@
import { Loader2 } from "lucide-react";
export function InteractionPreparationNotice() {
return (
<div role="status" className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 aria-hidden className="h-4 w-4 animate-spin" />
Preparing approval…
</div>
);
}
@@ -22,6 +22,7 @@ import {
failedRequestConfirmationInteraction,
failedToolActionInteraction,
pendingRequestConfirmationInteraction,
pendingRequestCheckboxConfirmationInteraction,
pendingToolActionDestructiveInteraction,
pendingToolActionWriteInteraction,
issueThreadInteractionFixtureMeta,
@@ -582,6 +583,26 @@ describe("IssueThreadInteractionCard", () => {
);
});
it.each([
pendingRequestConfirmationInteraction,
pendingRequestCheckboxConfirmationInteraction,
pendingSecretProposalInteraction,
])("keeps $kind approval disabled while preparing without disabling rejection", async (fixture) => {
const onAcceptInteraction = vi.fn();
const host = renderCard({
interaction: { ...fixture, acceptanceBlocker: "workspace_sync_pending" },
onAcceptInteraction,
onRejectInteraction: vi.fn(),
});
expect(host.querySelector('[role="status"]')?.textContent).toContain("Preparing approval…");
const approve = host.querySelector<HTMLButtonElement>('[data-testid="confirmation-actions"] button')!;
expect(approve.disabled).toBe(true);
await act(() => approve.click());
expect(onAcceptInteraction).not.toHaveBeenCalled();
const reject = [...host.querySelectorAll<HTMLButtonElement>("button")].find((button) => ["Reject", "Revise…", "Add reason…"].includes(button.textContent ?? ""));
expect(reject?.disabled).toBe(false);
});
it("invokes the confirm callback with pending request confirmations", async () => {
const onAcceptInteraction = vi.fn(async () => undefined);
const host = renderCard({
@@ -6,6 +6,7 @@ import { formatAssigneeUserLabel } from "../lib/assignees";
import { describeInteractionAudience, type InteractionAudienceDescription } from "../lib/interaction-audience";
import { interactionResolutionErrorMessage } from "../lib/interaction-resolution-error";
import {
isInteractionPreparingApproval,
buildSuggestedTaskTree,
collectSuggestedTaskClientKeys,
countSuggestedTaskNodes,
@@ -30,6 +31,7 @@ import {
type SuggestedTaskTreeNode,
} from "../lib/issue-thread-interactions";
import { cn, formatDateTime, formatShortDate } from "../lib/utils";
import { InteractionPreparationNotice } from "./InteractionPreparationNotice";
import { InteractionAudienceLine } from "./InteractionAudienceLine";
import { MarkdownBody, type MarkdownExternalReferenceMap } from "./MarkdownBody";
import { Button } from "./ui/button";
@@ -2027,6 +2029,7 @@ function RequestSecretProposalCard({
reasonPlaceholder={interaction.payload.declineReasonPlaceholder ?? "Optional: explain why this binding should not be created."}
working={working}
actionError={actionError}
preparingApproval={isInteractionPreparingApproval(interaction)}
canApprove={Boolean(onAcceptInteraction)}
canReject={Boolean(onRejectInteraction)}
onApprove={() => void handleAccept()}
@@ -2077,6 +2080,7 @@ function ConfirmationActionRow({
working,
actionError,
approveDisabled = false,
preparingApproval = false,
canApprove,
canReject,
onApprove,
@@ -2100,6 +2104,7 @@ function ConfirmationActionRow({
working: "accept" | "reject" | null;
actionError: string | null;
approveDisabled?: boolean;
preparingApproval?: boolean;
canApprove: boolean;
canReject: boolean;
onApprove: () => void;
@@ -2137,6 +2142,7 @@ function ConfirmationActionRow({
return (
<div className="space-y-3">
{preparingApproval ? <InteractionPreparationNotice /> : null}
<div
data-testid="confirmation-actions"
data-mobile-layout={stackActionsOnMobile ? "stacked" : "inline"}
@@ -2151,7 +2157,7 @@ function ConfirmationActionRow({
size="sm"
variant={revising ? "outline" : approveVariant}
className={stackActionsOnMobile ? "col-span-2 w-full sm:col-auto sm:w-auto" : undefined}
disabled={!canApprove || working !== null || approveDisabled}
disabled={!canApprove || working !== null || approveDisabled || preparingApproval}
onClick={onApprove}
>
{working === "accept" ? (
@@ -2637,6 +2643,7 @@ function RequestConfirmationCard({
reasonPlaceholder={reasonPlaceholder}
working={working}
actionError={actionError}
preparingApproval={isInteractionPreparingApproval(interaction)}
canApprove={Boolean(onAcceptInteraction)}
canReject={Boolean(onRejectInteraction)}
onApprove={() => void handleAccept()}
@@ -3054,6 +3061,7 @@ function RequestCheckboxConfirmationCard({
reasonPlaceholder={reasonPlaceholder}
working={working}
actionError={actionError}
preparingApproval={isInteractionPreparingApproval(interaction)}
canApprove={Boolean(onAcceptInteraction)}
canReject={Boolean(onRejectInteraction)}
onApprove={() => void handleAccept()}
@@ -26,6 +26,7 @@ import type {
PaperclipQuestionResponse,
PaperclipQuestionSet,
} from "@paperclipai/adapter-utils";
import { InteractionPreparationNotice } from "@/components/InteractionPreparationNotice";
import { IssueThreadInteractionCard } from "@/components/IssueThreadInteractionCard";
import { ConnectionIntentInteractionBody } from "@/features/connections/ConnectionIntentInteractionBody";
import { MarkdownBody } from "@/components/MarkdownBody";
@@ -42,6 +43,7 @@ import {
saveStructuredDraft,
} from "@/lib/composer-draft";
import {
isInteractionPreparingApproval,
buildIssueThreadInteractionSummary,
buildSuggestedTaskTree,
collectSuggestedTaskClientKeys,
@@ -813,6 +815,7 @@ function ConfirmationCard({
onUploadImage?: SharedInteractionProps["onUploadImage"];
mentions?: MentionOption[];
}) {
const preparingApproval = isInteractionPreparingApproval(interaction);
const [rejecting, setRejecting] = useState(false);
const [reason, setReason] = useState(() =>
draftKey ? loadStructuredDraft(draftKey, "") : "",
@@ -986,6 +989,7 @@ function ConfirmationCard({
</div>
) : null}
<InteractionActionError message={actionError} />
{preparingApproval ? <InteractionPreparationNotice /> : null}
<ActionRow>
{rejecting ? (
<>
@@ -1037,7 +1041,7 @@ function ConfirmationCard({
<Button
type="button"
size="sm"
disabled={working !== null || !onAcceptInteraction}
disabled={working !== null || preparingApproval || !onAcceptInteraction}
onClick={() => void resolve("accept")}
>
{working === "accept" ? (
@@ -1081,6 +1085,7 @@ function CheckboxConfirmationCard({
[],
),
);
const preparingApproval = isInteractionPreparingApproval(interaction);
const [rejecting, setRejecting] = useState(false);
const [reason, setReason] = useState(restored?.reason ?? "");
const [filter, setFilter] = useState("");
@@ -1225,6 +1230,7 @@ function CheckboxConfirmationCard({
</div>
) : null}
<InteractionActionError message={actionError} />
{preparingApproval ? <InteractionPreparationNotice /> : null}
<ActionRow hint={countHint}>
{rejecting ? (
<>
@@ -1273,7 +1279,7 @@ function CheckboxConfirmationCard({
<Button
type="button"
size="sm"
disabled={working !== null || !validCount || !onAcceptInteraction}
disabled={working !== null || preparingApproval || !validCount || !onAcceptInteraction}
onClick={() => void resolve("accept")}
>
{working === "accept" ? (
@@ -302,6 +302,40 @@ describe("TaskChatInteractionCard", () => {
);
});
it.each([createRequestConfirmation(), pendingRequestCheckboxConfirmationInteraction])(
"enables $kind acceptance when preparation clears on the same mounted card",
async (fixture) => {
const onAcceptInteraction = vi.fn();
const onRejectInteraction = vi.fn();
const render = (preparing: boolean) => flushSync(() => root.render(
<TooltipProvider><ThemeProvider>
<TaskChatInteractionCard
item={interactionItem({ ...fixture, acceptanceBlocker: preparing ? "workspace_sync_pending" : undefined })}
presentation="takeover"
onAcceptInteraction={onAcceptInteraction}
onRejectInteraction={onRejectInteraction}
/>
</ThemeProvider></TooltipProvider>,
));
const approve = () => [...container.querySelectorAll<HTMLButtonElement>("button")].find((button) =>
button.textContent === (fixture.payload.acceptLabel ?? "Approve"),
)!;
render(true);
expect(container.querySelector('[role="status"]')?.textContent).toContain("Preparing approval…");
expect(approve().disabled).toBe(true);
await act(async () => approve().click());
expect(onAcceptInteraction).not.toHaveBeenCalled();
expect([...container.querySelectorAll<HTMLButtonElement>("button")].find((button) =>
button.textContent === (fixture.payload.rejectLabel ?? "Reject"),
)?.disabled).toBe(false);
render(false);
expect(container.textContent).not.toContain("Preparing approval…");
expect(approve().disabled).toBe(false);
await act(async () => approve().click());
expect(onAcceptInteraction).toHaveBeenCalledTimes(1);
},
);
it("puts the primary CTA at the right edge of the compact action row", () => {
flushSync(() => {
root.render(
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
import { pendingRequestConfirmationInteraction } from "../fixtures/issueThreadInteractionFixtures";
import {
buildAnsweredQuestionsDeliveryText,
buildIssueThreadInteractionSummary,
@@ -10,6 +11,7 @@ import {
getRequestConfirmationTargetHref,
getQuestionAnswerLabels,
interactionReplacesComposerSkip,
interactionReadinessRefetchInterval,
isDegenerateAskUserQuestions,
isSupersededByNewerSiblingInteraction,
shouldHideInteractionCard,
@@ -713,3 +715,14 @@ describe("isSupersededByNewerSiblingInteraction", () => {
expect(shouldHideInteractionCard(degenerate)).toBe(true);
});
});
describe("interaction readiness polling", () => {
it("uses a fast cadence only for pending preparation and preserves the idle fallback", () => {
const preparing = { ...pendingRequestConfirmationInteraction, acceptanceBlocker: "workspace_sync_pending" as const };
expect(interactionReadinessRefetchInterval([preparing], 20_000)).toBe(2_000);
expect(interactionReadinessRefetchInterval([pendingRequestConfirmationInteraction], 20_000)).toBe(20_000);
expect(interactionReadinessRefetchInterval([{ ...preparing, status: "expired" }])).toBe(false);
expect(interactionReadinessRefetchInterval(undefined)).toBe(false);
});
});
+13
View File
@@ -58,6 +58,19 @@ import type {
SuggestTasksResultCreatedTask,
} from "@paperclipai/shared";
export function isInteractionPreparingApproval(interaction: IssueThreadInteraction): boolean {
return interaction.status === "pending"
&& interaction.acceptanceBlocker === "workspace_sync_pending";
}
/** Poll only while an approval is preparing; retain each surface's idle cadence. */
export function interactionReadinessRefetchInterval(
interactions: IssueThreadInteraction[] | undefined,
fallback: number | false = false,
): number | false {
return interactions?.some(isInteractionPreparingApproval) ? 2_000 : fallback;
}
export interface SuggestedTaskTreeNode {
task: SuggestedTaskDraft;
children: SuggestedTaskTreeNode[];
+2 -1
View File
@@ -297,6 +297,7 @@ import { copyTextToClipboard } from "../lib/clipboard";
import { buildIssuePropertiesPanelKey } from "../lib/issue-properties-panel-key";
import { openSkillPanelState, shouldSuppressTaskPanelUntilPlan } from "../lib/task-side-panel-state";
import {
interactionReadinessRefetchInterval,
buildAnsweredQuestionsDeliveryText,
buildIssueThreadInteractionSummary,
} from "../lib/issue-thread-interactions";
@@ -3156,7 +3157,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS
enabled: !!issueId,
// A review can be committed between the initial fetch and live-socket
// subscription. Reconcile even after its originating run has ended.
refetchInterval: 20_000,
refetchInterval: (query) => interactionReadinessRefetchInterval(query.state.data, 20_000),
placeholderData: keepPreviousDataForSameQueryTail<IssueThreadInteraction[]>(
issueId ?? "pending",
),
+2
View File
@@ -1,3 +1,4 @@
import { interactionReadinessRefetchInterval } from "@/lib/issue-thread-interactions";
import { AgentAvatar } from "@/components/AgentAvatar";
import { useCallback, useEffect, useMemo, useState, type FormEvent, type ReactNode } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
@@ -2085,6 +2086,7 @@ export function PipelineItemDetailView({ pipelineId, caseId }: { pipelineId: str
queryKey: conversationIssueId ? queryKeys.issues.interactions(conversationIssueId) : ["pipeline-item", caseId, "missing-conversation-interactions"],
queryFn: () => issuesApi.listInteractions(conversationIssueId!),
enabled: Boolean(conversationIssueId),
refetchInterval: (query) => interactionReadinessRefetchInterval(query.state.data),
});
const { data: agents } = useQuery({
queryKey: conversationCompanyId ? queryKeys.agents.list(conversationCompanyId) : ["agents", "pipeline-item", "none"],
+2 -1
View File
@@ -1,3 +1,4 @@
import { interactionReadinessRefetchInterval } from "@/lib/issue-thread-interactions";
import { SkillBinaryFile } from "../components/SkillBinaryFile";
import { SkillSourceProvenance } from "../components/SkillSourceProvenance";
import { AgentIdentity } from "@/components/AgentIdentity";
@@ -3336,7 +3337,7 @@ function InteractionSection({
queryKey: ["skill-studio", "interactions", harnessIssueId],
queryFn: () => issuesApi.listInteractions(harnessIssueId!),
enabled: Boolean(harnessIssueId && hasInlineAnswerable),
refetchInterval: hasInlineAnswerable ? POLL_MS : false,
refetchInterval: (query) => interactionReadinessRefetchInterval(query.state.data, hasInlineAnswerable ? POLL_MS : false),
});
const fullById = useMemo(
() => new Map((fullQuery.data ?? []).map((i) => [i.id, i])),