diff --git a/DESIGN.md b/DESIGN.md index ef852568573..b658bbcb92f 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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 diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index ef9d2962d29..a1d8411f338 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -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; diff --git a/server/src/__tests__/issue-thread-interactions-service.test.ts b/server/src/__tests__/issue-thread-interactions-service.test.ts index 67ccf1213d2..f04a02ac59b 100644 --- a/server/src/__tests__/issue-thread-interactions-service.test.ts +++ b/server/src/__tests__/issue-thread-interactions-service.test.ts @@ -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(); diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index 7c7cd643a3c..764d1db9040 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -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 { + 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(); + 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 ( diff --git a/ui/src/components/AttentionInteractionResolver.test.tsx b/ui/src/components/AttentionInteractionResolver.test.tsx new file mode 100644 index 00000000000..96ef9a9dbd9 --- /dev/null +++ b/ui/src/components/AttentionInteractionResolver.test.tsx @@ -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 }) => {children}, +})); + +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( + + + + + , + )); + await act(async () => { await vi.advanceTimersByTimeAsync(1); }); + const approve = () => container.querySelector('[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(); + } +}); diff --git a/ui/src/components/AttentionInteractionResolver.tsx b/ui/src/components/AttentionInteractionResolver.tsx index 21135ce9e61..29df40a1584 100644 --- a/ui/src/components/AttentionInteractionResolver.tsx +++ b/ui/src/components/AttentionInteractionResolver.tsx @@ -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(() => { diff --git a/ui/src/components/InteractionPreparationNotice.tsx b/ui/src/components/InteractionPreparationNotice.tsx new file mode 100644 index 00000000000..2a746009e36 --- /dev/null +++ b/ui/src/components/InteractionPreparationNotice.tsx @@ -0,0 +1,10 @@ +import { Loader2 } from "lucide-react"; + +export function InteractionPreparationNotice() { + return ( +
+ + Preparing approval… +
+ ); +} diff --git a/ui/src/components/IssueThreadInteractionCard.test.tsx b/ui/src/components/IssueThreadInteractionCard.test.tsx index 47b923e5bbe..b7f33fcd1b1 100644 --- a/ui/src/components/IssueThreadInteractionCard.test.tsx +++ b/ui/src/components/IssueThreadInteractionCard.test.tsx @@ -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('[data-testid="confirmation-actions"] button')!; + expect(approve.disabled).toBe(true); + await act(() => approve.click()); + expect(onAcceptInteraction).not.toHaveBeenCalled(); + const reject = [...host.querySelectorAll("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({ diff --git a/ui/src/components/IssueThreadInteractionCard.tsx b/ui/src/components/IssueThreadInteractionCard.tsx index d839990ffc1..1983e2fc275 100644 --- a/ui/src/components/IssueThreadInteractionCard.tsx +++ b/ui/src/components/IssueThreadInteractionCard.tsx @@ -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 (
+ {preparingApproval ? : null}
{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()} diff --git a/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx b/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx index 6450f488c4a..e0e84d6c0f3 100644 --- a/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx +++ b/ui/src/components/task-chat/TaskChatCompactInteractionCard.tsx @@ -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({
) : null} + {preparingApproval ? : null} {rejecting ? ( <> @@ -1037,7 +1041,7 @@ function ConfirmationCard({
) : null} + {preparingApproval ? : null} {rejecting ? ( <> @@ -1273,7 +1279,7 @@ function CheckboxConfirmationCard({