mirror of
https://github.com/paperclipai/paperclip
synced 2026-04-25 17:25:15 +02:00
[codex] Add structured issue-thread interactions (#4244)
## Thinking Path > - Paperclip orchestrates AI agents for zero-human companies. > - Operators supervise that work through issues, comments, approvals, and the board UI. > - Some agent proposals need structured board/user decisions, not hidden markdown conventions or heavyweight governed approvals. > - Issue-thread interactions already provide a natural thread-native surface for proposed tasks and questions. > - This pull request extends that surface with request confirmations, richer interaction cards, and agent/plugin/MCP helpers. > - The benefit is that plan approvals and yes/no decisions become explicit, auditable, and resumable without losing the single-issue workflow. ## What Changed - Added persisted issue-thread interactions for suggested tasks, structured questions, and request confirmations. - Added board UI cards for interaction review, selection, question answers, and accept/reject confirmation flows. - Added MCP and plugin SDK helpers for creating interaction cards from agents/plugins. - Updated agent wake instructions, onboarding assets, Paperclip skill docs, and public docs to prefer structured confirmations for issue-scoped decisions. - Rebased the branch onto `public-gh/master` and renumbered branch migrations to `0063` and `0064`; the idempotency migration uses `ADD COLUMN IF NOT EXISTS` for old branch users. ## Verification - `git diff --check public-gh/master..HEAD` - `pnpm exec vitest run packages/adapter-utils/src/server-utils.test.ts packages/mcp-server/src/tools.test.ts packages/shared/src/issue-thread-interactions.test.ts ui/src/lib/issue-thread-interactions.test.ts ui/src/lib/issue-chat-messages.test.ts ui/src/components/IssueThreadInteractionCard.test.tsx ui/src/components/IssueChatThread.test.tsx server/src/__tests__/issue-thread-interaction-routes.test.ts server/src/__tests__/issue-thread-interactions-service.test.ts server/src/services/issue-thread-interactions.test.ts` -> 9 files / 79 tests passed - `pnpm -r typecheck` -> passed, including `packages/db` migration numbering check ## Risks - Medium: this adds a new issue-thread interaction model across db/shared/server/ui/plugin surfaces. - Migration risk is reduced by placing this branch after current master migrations (`0063`, `0064`) and making the idempotency column add idempotent for users who applied the old branch numbering. - UI interaction behavior is covered by component tests, but this PR does not include browser screenshots. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - OpenAI Codex, GPT-5-class coding agent runtime. Exact model ID and context window are not exposed in this Paperclip run; tool use and local shell/code execution were enabled. ## 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 run tests locally and they pass - [x] I have added or updated tests where applicable - [ ] If this change affects the UI, I have included before/after screenshots - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [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,4 +1,5 @@
|
||||
import type {
|
||||
AskUserQuestionsAnswer,
|
||||
Approval,
|
||||
DocumentRevision,
|
||||
FeedbackTargetType,
|
||||
@@ -9,6 +10,7 @@ import type {
|
||||
IssueComment,
|
||||
IssueDocument,
|
||||
IssueLabel,
|
||||
IssueThreadInteraction,
|
||||
IssueWorkProduct,
|
||||
UpsertIssueDocument,
|
||||
} from "@paperclipai/shared";
|
||||
@@ -99,6 +101,24 @@ export const issuesApi = {
|
||||
const qs = params.toString();
|
||||
return api.get<IssueComment[]>(`/issues/${id}/comments${qs ? `?${qs}` : ""}`);
|
||||
},
|
||||
listInteractions: (id: string) =>
|
||||
api.get<IssueThreadInteraction[]>(`/issues/${id}/interactions`),
|
||||
createInteraction: (id: string, data: Record<string, unknown>) =>
|
||||
api.post<IssueThreadInteraction>(`/issues/${id}/interactions`, data),
|
||||
acceptInteraction: (
|
||||
id: string,
|
||||
interactionId: string,
|
||||
data?: { selectedClientKeys?: string[] },
|
||||
) =>
|
||||
api.post<IssueThreadInteraction>(`/issues/${id}/interactions/${interactionId}/accept`, data ?? {}),
|
||||
rejectInteraction: (id: string, interactionId: string, reason?: string) =>
|
||||
api.post<IssueThreadInteraction>(`/issues/${id}/interactions/${interactionId}/reject`, reason ? { reason } : {}),
|
||||
respondToInteraction: (
|
||||
id: string,
|
||||
interactionId: string,
|
||||
data: { answers: AskUserQuestionsAnswer[]; summaryMarkdown?: string | null },
|
||||
) =>
|
||||
api.post<IssueThreadInteraction>(`/issues/${id}/interactions/${interactionId}/respond`, data),
|
||||
getComment: (id: string, commentId: string) =>
|
||||
api.get<IssueComment>(`/issues/${id}/comments/${commentId}`),
|
||||
listFeedbackVotes: (id: string) => api.get<FeedbackVote[]>(`/issues/${id}/feedback-votes`),
|
||||
|
||||
@@ -12,6 +12,10 @@ import {
|
||||
resolveAssistantMessageFoldedState,
|
||||
resolveIssueChatHumanAuthor,
|
||||
} from "./IssueChatThread";
|
||||
import type {
|
||||
AskUserQuestionsInteraction,
|
||||
SuggestTasksInteraction,
|
||||
} from "../lib/issue-thread-interactions";
|
||||
|
||||
const { markdownEditorFocusMock } = vi.hoisted(() => ({
|
||||
markdownEditorFocusMock: vi.fn(),
|
||||
@@ -139,6 +143,78 @@ vi.mock("../hooks/usePaperclipIssueRuntime", () => ({
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
function createSuggestedTasksInteraction(
|
||||
overrides: Partial<SuggestTasksInteraction> = {},
|
||||
): SuggestTasksInteraction {
|
||||
return {
|
||||
id: "interaction-suggest-1",
|
||||
companyId: "company-1",
|
||||
issueId: "issue-1",
|
||||
kind: "suggest_tasks",
|
||||
title: "Suggested follow-up work",
|
||||
summary: "Preview the next issue tree before accepting it.",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: "agent-1",
|
||||
createdByUserId: null,
|
||||
resolvedByAgentId: null,
|
||||
resolvedByUserId: null,
|
||||
createdAt: new Date("2026-04-06T12:02:00.000Z"),
|
||||
updatedAt: new Date("2026-04-06T12:02:00.000Z"),
|
||||
resolvedAt: null,
|
||||
payload: {
|
||||
version: 1,
|
||||
tasks: [
|
||||
{
|
||||
clientKey: "task-1",
|
||||
title: "Prototype the card",
|
||||
},
|
||||
],
|
||||
},
|
||||
result: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createQuestionInteraction(
|
||||
overrides: Partial<AskUserQuestionsInteraction> = {},
|
||||
): AskUserQuestionsInteraction {
|
||||
return {
|
||||
id: "interaction-question-1",
|
||||
companyId: "company-1",
|
||||
issueId: "issue-1",
|
||||
kind: "ask_user_questions",
|
||||
title: "Clarify the phase",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: "agent-1",
|
||||
createdByUserId: null,
|
||||
resolvedByAgentId: null,
|
||||
resolvedByUserId: null,
|
||||
createdAt: new Date("2026-04-06T12:03:00.000Z"),
|
||||
updatedAt: new Date("2026-04-06T12:03:00.000Z"),
|
||||
resolvedAt: null,
|
||||
payload: {
|
||||
version: 1,
|
||||
submitLabel: "Submit answers",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
prompt: "Pick one scope",
|
||||
selectionMode: "single",
|
||||
required: true,
|
||||
options: [
|
||||
{ id: "phase-1", label: "Phase 1" },
|
||||
{ id: "phase-2", label: "Phase 2" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
result: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("IssueChatThread", () => {
|
||||
let container: HTMLDivElement;
|
||||
|
||||
@@ -300,6 +376,165 @@ describe("IssueChatThread", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("invokes the accept callback for pending suggested-task interactions", async () => {
|
||||
const root = createRoot(container);
|
||||
const onAcceptInteraction = vi.fn(async () => undefined);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<MemoryRouter>
|
||||
<IssueChatThread
|
||||
comments={[]}
|
||||
interactions={[createSuggestedTasksInteraction()]}
|
||||
linkedRuns={[]}
|
||||
timelineEvents={[]}
|
||||
liveRuns={[]}
|
||||
onAdd={async () => {}}
|
||||
onAcceptInteraction={onAcceptInteraction}
|
||||
showComposer={false}
|
||||
enableLiveTranscriptPolling={false}
|
||||
/>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
});
|
||||
|
||||
const acceptButton = Array.from(container.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("Accept drafts"),
|
||||
);
|
||||
expect(acceptButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
acceptButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onAcceptInteraction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: "interaction-suggest-1",
|
||||
kind: "suggest_tasks",
|
||||
}),
|
||||
["task-1"],
|
||||
);
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("submits only the selected draft subtree when tasks are manually pruned", async () => {
|
||||
const root = createRoot(container);
|
||||
const onAcceptInteraction = vi.fn(async () => undefined);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<MemoryRouter>
|
||||
<IssueChatThread
|
||||
comments={[]}
|
||||
interactions={[createSuggestedTasksInteraction({
|
||||
payload: {
|
||||
version: 1,
|
||||
tasks: [
|
||||
{
|
||||
clientKey: "root",
|
||||
title: "Root task",
|
||||
},
|
||||
{
|
||||
clientKey: "child",
|
||||
parentClientKey: "root",
|
||||
title: "Child task",
|
||||
},
|
||||
],
|
||||
},
|
||||
})]}
|
||||
linkedRuns={[]}
|
||||
timelineEvents={[]}
|
||||
liveRuns={[]}
|
||||
onAdd={async () => {}}
|
||||
onAcceptInteraction={onAcceptInteraction}
|
||||
showComposer={false}
|
||||
enableLiveTranscriptPolling={false}
|
||||
/>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
});
|
||||
|
||||
const childCheckbox = container.querySelector('[aria-label="Include Child task"]');
|
||||
expect(childCheckbox).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
childCheckbox?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
const acceptButton = Array.from(container.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("Accept selected drafts"),
|
||||
);
|
||||
expect(acceptButton).toBeTruthy();
|
||||
await act(async () => {
|
||||
acceptButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onAcceptInteraction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: "interaction-suggest-1",
|
||||
kind: "suggest_tasks",
|
||||
}),
|
||||
["root"],
|
||||
);
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("submits selected answers for pending question interactions", async () => {
|
||||
const root = createRoot(container);
|
||||
const onSubmitInteractionAnswers = vi.fn(async () => undefined);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<MemoryRouter>
|
||||
<IssueChatThread
|
||||
comments={[]}
|
||||
interactions={[createQuestionInteraction()]}
|
||||
linkedRuns={[]}
|
||||
timelineEvents={[]}
|
||||
liveRuns={[]}
|
||||
onAdd={async () => {}}
|
||||
onSubmitInteractionAnswers={onSubmitInteractionAnswers}
|
||||
showComposer={false}
|
||||
enableLiveTranscriptPolling={false}
|
||||
/>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
});
|
||||
|
||||
const optionButton = Array.from(container.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("Phase 1"),
|
||||
);
|
||||
const submitButton = Array.from(container.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("Submit answers"),
|
||||
);
|
||||
expect(optionButton).toBeTruthy();
|
||||
expect(submitButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
optionButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
await act(async () => {
|
||||
submitButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onSubmitInteractionAnswers).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: "interaction-question-1",
|
||||
kind: "ask_user_questions",
|
||||
}),
|
||||
[{ questionId: "scope", optionIds: ["phase-1"] }],
|
||||
);
|
||||
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders the transcript directly from stable Paperclip messages", () => {
|
||||
const root = createRoot(container);
|
||||
|
||||
|
||||
@@ -45,6 +45,14 @@ import {
|
||||
type IssueChatTranscriptEntry,
|
||||
type SegmentTiming,
|
||||
} from "../lib/issue-chat-messages";
|
||||
import type {
|
||||
AskUserQuestionsAnswer,
|
||||
AskUserQuestionsInteraction,
|
||||
IssueThreadInteraction,
|
||||
RequestConfirmationInteraction,
|
||||
SuggestTasksInteraction,
|
||||
} from "../lib/issue-thread-interactions";
|
||||
import { isIssueThreadInteraction } from "../lib/issue-thread-interactions";
|
||||
import { resolveIssueChatTranscriptRuns } from "../lib/issueChatTranscriptRuns";
|
||||
import type { IssueTimelineAssignee, IssueTimelineEvent } from "../lib/issue-timeline-events";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -67,6 +75,7 @@ import { MarkdownBody } from "./MarkdownBody";
|
||||
import { MarkdownEditor, type MentionOption, type MarkdownEditorRef } from "./MarkdownEditor";
|
||||
import { Identity } from "./Identity";
|
||||
import { InlineEntitySelector, type InlineEntityOption } from "./InlineEntitySelector";
|
||||
import { IssueThreadInteractionCard } from "./IssueThreadInteractionCard";
|
||||
import { AgentIcon } from "./AgentIconPicker";
|
||||
import { restoreSubmittedCommentDraft } from "../lib/comment-submit-draft";
|
||||
import {
|
||||
@@ -114,6 +123,18 @@ interface IssueChatMessageContext {
|
||||
onCancelQueued?: (commentId: string) => void;
|
||||
interruptingQueuedRunId?: string | null;
|
||||
onImageClick?: (src: string) => void;
|
||||
onAcceptInteraction?: (
|
||||
interaction: SuggestTasksInteraction | RequestConfirmationInteraction,
|
||||
selectedClientKeys?: string[],
|
||||
) => Promise<void> | void;
|
||||
onRejectInteraction?: (
|
||||
interaction: SuggestTasksInteraction | RequestConfirmationInteraction,
|
||||
reason?: string,
|
||||
) => Promise<void> | void;
|
||||
onSubmitInteractionAnswers?: (
|
||||
interaction: AskUserQuestionsInteraction,
|
||||
answers: AskUserQuestionsAnswer[],
|
||||
) => Promise<void> | void;
|
||||
}
|
||||
|
||||
const IssueChatCtx = createContext<IssueChatMessageContext>({
|
||||
@@ -211,6 +232,7 @@ interface IssueChatComposerProps {
|
||||
|
||||
interface IssueChatThreadProps {
|
||||
comments: IssueChatComment[];
|
||||
interactions?: IssueThreadInteraction[];
|
||||
feedbackVotes?: FeedbackVote[];
|
||||
feedbackDataSharingPreference?: FeedbackDataSharingPreference;
|
||||
feedbackTermsUrl?: string | null;
|
||||
@@ -256,6 +278,18 @@ interface IssueChatThreadProps {
|
||||
interruptingQueuedRunId?: string | null;
|
||||
stoppingRunId?: string | null;
|
||||
onImageClick?: (src: string) => void;
|
||||
onAcceptInteraction?: (
|
||||
interaction: SuggestTasksInteraction | RequestConfirmationInteraction,
|
||||
selectedClientKeys?: string[],
|
||||
) => Promise<void> | void;
|
||||
onRejectInteraction?: (
|
||||
interaction: SuggestTasksInteraction | RequestConfirmationInteraction,
|
||||
reason?: string,
|
||||
) => Promise<void> | void;
|
||||
onSubmitInteractionAnswers?: (
|
||||
interaction: AskUserQuestionsInteraction,
|
||||
answers: AskUserQuestionsAnswer[],
|
||||
) => Promise<void> | void;
|
||||
composerRef?: Ref<IssueChatComposerHandle>;
|
||||
}
|
||||
|
||||
@@ -1698,7 +1732,14 @@ function IssueChatFeedbackButtons({
|
||||
}
|
||||
|
||||
function IssueChatSystemMessage({ message }: { message: ThreadMessage }) {
|
||||
const { agentMap, currentUserId, userLabelMap } = useContext(IssueChatCtx);
|
||||
const {
|
||||
agentMap,
|
||||
currentUserId,
|
||||
userLabelMap,
|
||||
onAcceptInteraction,
|
||||
onRejectInteraction,
|
||||
onSubmitInteractionAnswers,
|
||||
} = useContext(IssueChatCtx);
|
||||
const custom = message.metadata.custom as Record<string, unknown>;
|
||||
const anchorId = typeof custom.anchorId === "string" ? custom.anchorId : undefined;
|
||||
const runId = typeof custom.runId === "string" ? custom.runId : null;
|
||||
@@ -1717,6 +1758,27 @@ function IssueChatSystemMessage({ message }: { message: ThreadMessage }) {
|
||||
to: IssueTimelineAssignee;
|
||||
}
|
||||
: null;
|
||||
const interaction = isIssueThreadInteraction(custom.interaction)
|
||||
? custom.interaction
|
||||
: null;
|
||||
|
||||
if (custom.kind === "interaction" && interaction) {
|
||||
return (
|
||||
<div id={anchorId}>
|
||||
<div className="py-1.5">
|
||||
<IssueThreadInteractionCard
|
||||
interaction={interaction}
|
||||
agentMap={agentMap}
|
||||
currentUserId={currentUserId}
|
||||
userLabelMap={userLabelMap}
|
||||
onAcceptInteraction={onAcceptInteraction}
|
||||
onRejectInteraction={onRejectInteraction}
|
||||
onSubmitInteractionAnswers={onSubmitInteractionAnswers}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (custom.kind === "event" && actorName) {
|
||||
const isCurrentUser = actorType === "user" && !!currentUserId && actorId === currentUserId;
|
||||
@@ -2077,6 +2139,7 @@ const IssueChatComposer = forwardRef<IssueChatComposerHandle, IssueChatComposerP
|
||||
|
||||
export function IssueChatThread({
|
||||
comments,
|
||||
interactions = [],
|
||||
feedbackVotes = [],
|
||||
feedbackDataSharingPreference = "prompt",
|
||||
feedbackTermsUrl = null,
|
||||
@@ -2118,6 +2181,9 @@ export function IssueChatThread({
|
||||
interruptingQueuedRunId = null,
|
||||
stoppingRunId = null,
|
||||
onImageClick,
|
||||
onAcceptInteraction,
|
||||
onRejectInteraction,
|
||||
onSubmitInteractionAnswers,
|
||||
composerRef,
|
||||
}: IssueChatThreadProps) {
|
||||
const location = useLocation();
|
||||
@@ -2173,6 +2239,7 @@ export function IssueChatThread({
|
||||
() =>
|
||||
buildIssueChatMessages({
|
||||
comments,
|
||||
interactions,
|
||||
timelineEvents,
|
||||
linkedRuns,
|
||||
liveRuns,
|
||||
@@ -2188,6 +2255,7 @@ export function IssueChatThread({
|
||||
}),
|
||||
[
|
||||
comments,
|
||||
interactions,
|
||||
timelineEvents,
|
||||
linkedRuns,
|
||||
liveRuns,
|
||||
@@ -2256,7 +2324,14 @@ export function IssueChatThread({
|
||||
|
||||
useEffect(() => {
|
||||
const hash = location.hash;
|
||||
if (!(hash.startsWith("#comment-") || hash.startsWith("#activity-") || hash.startsWith("#run-"))) return;
|
||||
if (
|
||||
!(
|
||||
hash.startsWith("#comment-")
|
||||
|| hash.startsWith("#activity-")
|
||||
|| hash.startsWith("#run-")
|
||||
|| hash.startsWith("#interaction-")
|
||||
)
|
||||
) return;
|
||||
if (messages.length === 0 || hasScrolledRef.current) return;
|
||||
const targetId = hash.slice(1);
|
||||
const element = document.getElementById(targetId);
|
||||
@@ -2286,6 +2361,9 @@ export function IssueChatThread({
|
||||
onCancelQueued,
|
||||
interruptingQueuedRunId,
|
||||
onImageClick,
|
||||
onAcceptInteraction,
|
||||
onRejectInteraction,
|
||||
onSubmitInteractionAnswers,
|
||||
}),
|
||||
[
|
||||
feedbackVoteByTargetId,
|
||||
@@ -2303,6 +2381,9 @@ export function IssueChatThread({
|
||||
onCancelQueued,
|
||||
interruptingQueuedRunId,
|
||||
onImageClick,
|
||||
onAcceptInteraction,
|
||||
onRejectInteraction,
|
||||
onSubmitInteractionAnswers,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
258
ui/src/components/IssueThreadInteractionCard.test.tsx
Normal file
258
ui/src/components/IssueThreadInteractionCard.test.tsx
Normal file
@@ -0,0 +1,258 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { IssueThreadInteractionCard } from "./IssueThreadInteractionCard";
|
||||
import { ThemeProvider } from "../context/ThemeContext";
|
||||
import { TooltipProvider } from "./ui/tooltip";
|
||||
import {
|
||||
pendingAskUserQuestionsInteraction,
|
||||
commentExpiredRequestConfirmationInteraction,
|
||||
disabledDeclineReasonRequestConfirmationInteraction,
|
||||
failedRequestConfirmationInteraction,
|
||||
pendingRequestConfirmationInteraction,
|
||||
pendingSuggestedTasksInteraction,
|
||||
staleTargetRequestConfirmationInteraction,
|
||||
rejectedSuggestedTasksInteraction,
|
||||
} from "../fixtures/issueThreadInteractionFixtures";
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
vi.mock("@/lib/router", () => ({
|
||||
Link: ({ to, children, className }: { to: string; children: ReactNode; className?: string }) => (
|
||||
<a href={to} className={className}>{children}</a>
|
||||
),
|
||||
}));
|
||||
|
||||
function renderCard(
|
||||
props: Partial<ComponentProps<typeof IssueThreadInteractionCard>> = {},
|
||||
) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
act(() => {
|
||||
root?.render(
|
||||
<TooltipProvider>
|
||||
<ThemeProvider>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={pendingAskUserQuestionsInteraction}
|
||||
{...props}
|
||||
/>
|
||||
</ThemeProvider>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
});
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {
|
||||
act(() => root?.unmount());
|
||||
}
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
describe("IssueThreadInteractionCard", () => {
|
||||
it("exposes pending question options as selectable radio and checkbox controls", () => {
|
||||
const host = renderCard({
|
||||
interaction: pendingAskUserQuestionsInteraction,
|
||||
onSubmitInteractionAnswers: vi.fn(),
|
||||
});
|
||||
|
||||
const singleGroup = host.querySelector('[role="radiogroup"]');
|
||||
expect(singleGroup?.getAttribute("aria-labelledby")).toBe(
|
||||
"interaction-questions-default-collapse-depth-prompt",
|
||||
);
|
||||
|
||||
const radios = [...host.querySelectorAll('[role="radio"]')];
|
||||
expect(radios).toHaveLength(2);
|
||||
expect(radios[0]?.getAttribute("aria-checked")).toBe("false");
|
||||
|
||||
act(() => {
|
||||
(radios[0] as HTMLButtonElement).click();
|
||||
});
|
||||
|
||||
expect(radios[0]?.getAttribute("aria-checked")).toBe("true");
|
||||
expect(radios[1]?.getAttribute("aria-checked")).toBe("false");
|
||||
|
||||
const multiGroup = host.querySelector('[role="group"]');
|
||||
expect(multiGroup?.getAttribute("aria-labelledby")).toBe(
|
||||
"interaction-questions-default-post-submit-summary-prompt",
|
||||
);
|
||||
expect(host.querySelectorAll('[role="checkbox"]')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("makes child tasks explicit in suggested task trees", () => {
|
||||
const host = renderCard({
|
||||
interaction: pendingSuggestedTasksInteraction,
|
||||
});
|
||||
|
||||
expect(host.textContent).toContain("Child task");
|
||||
});
|
||||
|
||||
it("shows an explicit placeholder when a rejected interaction has no reason", () => {
|
||||
const host = renderCard({
|
||||
interaction: {
|
||||
...rejectedSuggestedTasksInteraction,
|
||||
result: { version: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
expect(host.textContent).toContain("No reason provided.");
|
||||
});
|
||||
|
||||
it("requires a decline reason when the request confirmation payload asks for one", async () => {
|
||||
const onRejectInteraction = vi.fn(async () => undefined);
|
||||
const host = renderCard({
|
||||
interaction: pendingRequestConfirmationInteraction,
|
||||
onRejectInteraction,
|
||||
});
|
||||
|
||||
const declineButton = Array.from(host.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("Request revisions"),
|
||||
);
|
||||
expect(declineButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
declineButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
const saveButton = Array.from(host.querySelectorAll("button")).filter((button) =>
|
||||
button.textContent?.includes("Request revisions"),
|
||||
).at(-1);
|
||||
expect(saveButton?.hasAttribute("disabled")).toBe(false);
|
||||
|
||||
await act(async () => {
|
||||
saveButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(host.textContent).toContain("A decline reason is required.");
|
||||
|
||||
const textarea = host.querySelector("textarea") as HTMLTextAreaElement | null;
|
||||
expect(textarea).toBeTruthy();
|
||||
expect(textarea?.getAttribute("aria-invalid")).toBe("true");
|
||||
|
||||
await act(async () => {
|
||||
const valueSetter = Object.getOwnPropertyDescriptor(
|
||||
HTMLTextAreaElement.prototype,
|
||||
"value",
|
||||
)?.set;
|
||||
valueSetter?.call(textarea, "Needs a smaller phase split");
|
||||
textarea!.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
const enabledSaveButton = Array.from(host.querySelectorAll("button")).filter((button) =>
|
||||
button.textContent?.includes("Request revisions"),
|
||||
).at(-1);
|
||||
expect(enabledSaveButton?.hasAttribute("disabled")).toBe(false);
|
||||
await act(async () => {
|
||||
enabledSaveButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onRejectInteraction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ kind: "request_confirmation" }),
|
||||
"Needs a smaller phase split",
|
||||
);
|
||||
});
|
||||
|
||||
it("invokes the confirm callback with pending request confirmations", async () => {
|
||||
const onAcceptInteraction = vi.fn(async () => undefined);
|
||||
const host = renderCard({
|
||||
interaction: pendingRequestConfirmationInteraction,
|
||||
onAcceptInteraction,
|
||||
});
|
||||
|
||||
const confirmButton = Array.from(host.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("Approve plan"),
|
||||
);
|
||||
expect(confirmButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
confirmButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onAcceptInteraction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ kind: "request_confirmation" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("labels accept-only continuation policies in the card header", () => {
|
||||
const host = renderCard({
|
||||
interaction: {
|
||||
...pendingRequestConfirmationInteraction,
|
||||
continuationPolicy: "wake_assignee_on_accept",
|
||||
},
|
||||
});
|
||||
|
||||
expect(host.textContent).toContain("Wakes on confirm");
|
||||
});
|
||||
|
||||
it("renders request confirmation target links and stale-target expiry", () => {
|
||||
const host = renderCard({
|
||||
interaction: staleTargetRequestConfirmationInteraction,
|
||||
});
|
||||
|
||||
const targetLinks = host.querySelectorAll("a");
|
||||
expect(host.textContent).toContain("Expired by target change");
|
||||
expect(host.textContent).toContain("Plan v3");
|
||||
expect(host.textContent).toContain("Plan v4");
|
||||
expect(targetLinks[0]?.getAttribute("href")).toContain("#document-plan");
|
||||
expect(targetLinks[1]?.getAttribute("href")).toContain("#document-plan");
|
||||
expect(host.textContent).not.toContain("Approve plan");
|
||||
});
|
||||
|
||||
it("renders a jump link for confirmations expired by comment", () => {
|
||||
const host = renderCard({
|
||||
interaction: commentExpiredRequestConfirmationInteraction,
|
||||
});
|
||||
|
||||
const jumpLink = Array.from(host.querySelectorAll("a")).find((link) =>
|
||||
link.textContent?.includes("Jump to comment"),
|
||||
);
|
||||
|
||||
expect(jumpLink?.getAttribute("href")).toBe(
|
||||
"#comment-22222222-2222-4222-8222-222222222222",
|
||||
);
|
||||
});
|
||||
|
||||
it("declines immediately when decline reasons are disabled", async () => {
|
||||
const onRejectInteraction = vi.fn(async () => undefined);
|
||||
const host = renderCard({
|
||||
interaction: disabledDeclineReasonRequestConfirmationInteraction,
|
||||
onRejectInteraction,
|
||||
});
|
||||
|
||||
const declineButton = Array.from(host.querySelectorAll("button")).find((button) =>
|
||||
button.textContent?.includes("Keep it"),
|
||||
);
|
||||
expect(declineButton).toBeTruthy();
|
||||
|
||||
await act(async () => {
|
||||
declineButton?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(host.querySelector("textarea")).toBeNull();
|
||||
expect(onRejectInteraction).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ kind: "request_confirmation" }),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it("renders explicit copy for failed request confirmations", () => {
|
||||
const host = renderCard({
|
||||
interaction: failedRequestConfirmationInteraction,
|
||||
});
|
||||
|
||||
expect(host.textContent).toContain(
|
||||
"This request could not be resolved. Try again or create a new request.",
|
||||
);
|
||||
});
|
||||
});
|
||||
1268
ui/src/components/IssueThreadInteractionCard.tsx
Normal file
1268
ui/src/components/IssueThreadInteractionCard.tsx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -681,6 +681,9 @@ function invalidateActivityQueries(
|
||||
if (action === "issue.comment_added") {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.comments(ref), ...invalidationOptions });
|
||||
}
|
||||
if (action?.startsWith("issue.thread_interaction_")) {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.interactions(ref), ...invalidationOptions });
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
|
||||
537
ui/src/fixtures/issueThreadInteractionFixtures.ts
Normal file
537
ui/src/fixtures/issueThreadInteractionFixtures.ts
Normal file
@@ -0,0 +1,537 @@
|
||||
import type { LiveRunForIssue } from "../api/heartbeats";
|
||||
import type {
|
||||
IssueChatComment,
|
||||
IssueChatTranscriptEntry,
|
||||
} from "../lib/issue-chat-messages";
|
||||
import type { IssueTimelineEvent } from "../lib/issue-timeline-events";
|
||||
import type {
|
||||
AskUserQuestionsInteraction,
|
||||
RequestConfirmationInteraction,
|
||||
SuggestTasksInteraction,
|
||||
} from "../lib/issue-thread-interactions";
|
||||
|
||||
export const issueThreadInteractionFixtureMeta = {
|
||||
companyId: "company-storybook",
|
||||
projectId: "project-board-ui",
|
||||
issueId: "issue-thread-interactions",
|
||||
currentUserId: "user-board",
|
||||
} as const;
|
||||
|
||||
function createComment(overrides: Partial<IssueChatComment>): IssueChatComment {
|
||||
const createdAt = overrides.createdAt ?? new Date("2026-04-20T14:00:00.000Z");
|
||||
return {
|
||||
id: "comment-default",
|
||||
companyId: issueThreadInteractionFixtureMeta.companyId,
|
||||
issueId: issueThreadInteractionFixtureMeta.issueId,
|
||||
authorAgentId: null,
|
||||
authorUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
body: "",
|
||||
createdAt,
|
||||
updatedAt: overrides.updatedAt ?? createdAt,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createSuggestTasksInteraction(
|
||||
overrides: Partial<SuggestTasksInteraction>,
|
||||
): SuggestTasksInteraction {
|
||||
return {
|
||||
id: "interaction-suggest-default",
|
||||
companyId: issueThreadInteractionFixtureMeta.companyId,
|
||||
issueId: issueThreadInteractionFixtureMeta.issueId,
|
||||
kind: "suggest_tasks",
|
||||
title: "Suggested issue tree for the first interaction pass",
|
||||
summary:
|
||||
"Draft task creation stays pending until a reviewer accepts it, so the thread can preview structure without mutating the task system.",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: "agent-codex",
|
||||
createdByUserId: null,
|
||||
resolvedByAgentId: null,
|
||||
resolvedByUserId: null,
|
||||
createdAt: new Date("2026-04-20T14:11:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:11:00.000Z"),
|
||||
resolvedAt: null,
|
||||
payload: {
|
||||
version: 1,
|
||||
defaultParentId: "PAP-1709",
|
||||
tasks: [
|
||||
{
|
||||
clientKey: "root-design",
|
||||
title: "Prototype issue-thread interaction cards",
|
||||
description:
|
||||
"Build render-only cards that sit in the issue feed and show suggested tasks before anything is persisted.",
|
||||
priority: "high",
|
||||
assigneeAgentId: "agent-codex",
|
||||
billingCode: "ui-research",
|
||||
labels: ["UI", "interaction"],
|
||||
},
|
||||
{
|
||||
clientKey: "child-stories",
|
||||
parentClientKey: "root-design",
|
||||
title: "Add Storybook coverage for acceptance and rejection states",
|
||||
description:
|
||||
"Cover pending, accepted, rejected, and collapsed-child previews in a fixture-backed story.",
|
||||
priority: "medium",
|
||||
assigneeAgentId: "agent-qa",
|
||||
labels: ["Storybook"],
|
||||
},
|
||||
{
|
||||
clientKey: "child-mixed-thread",
|
||||
parentClientKey: "root-design",
|
||||
title: "Prototype the mixed thread feed",
|
||||
description:
|
||||
"Show comments, activity, live runs, and interaction cards in one chronological feed.",
|
||||
priority: "medium",
|
||||
assigneeAgentId: "agent-codex",
|
||||
labels: ["Issue thread"],
|
||||
},
|
||||
{
|
||||
clientKey: "hidden-follow-up",
|
||||
parentClientKey: "child-mixed-thread",
|
||||
title: "Follow-up polish on spacing and answered summaries",
|
||||
description:
|
||||
"Collapse this under the visible task tree so the preview proves the hidden-descendant treatment.",
|
||||
priority: "low",
|
||||
hiddenInPreview: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
result: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createAskUserQuestionsInteraction(
|
||||
overrides: Partial<AskUserQuestionsInteraction>,
|
||||
): AskUserQuestionsInteraction {
|
||||
return {
|
||||
id: "interaction-questions-default",
|
||||
companyId: issueThreadInteractionFixtureMeta.companyId,
|
||||
issueId: issueThreadInteractionFixtureMeta.issueId,
|
||||
kind: "ask_user_questions",
|
||||
title: "Resolve open UX decisions before Phase 1",
|
||||
summary:
|
||||
"This form stays local until the operator submits it, so the assignee only wakes once after the whole answer set is ready.",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: "agent-codex",
|
||||
createdByUserId: null,
|
||||
resolvedByAgentId: null,
|
||||
resolvedByUserId: null,
|
||||
createdAt: new Date("2026-04-20T14:18:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:18:00.000Z"),
|
||||
resolvedAt: null,
|
||||
payload: {
|
||||
version: 1,
|
||||
title: "Before I wire the persistence layer, which preview behavior do you want?",
|
||||
submitLabel: "Send answers",
|
||||
questions: [
|
||||
{
|
||||
id: "collapse-depth",
|
||||
prompt: "How aggressive should the suggested-task preview collapse descendant work?",
|
||||
helpText:
|
||||
"We need enough context to review the tree without making the feed feel like a project plan.",
|
||||
selectionMode: "single",
|
||||
required: true,
|
||||
options: [
|
||||
{
|
||||
id: "visible-root",
|
||||
label: "Only collapse hidden descendants",
|
||||
description: "Keep top-level and visible child tasks expanded.",
|
||||
},
|
||||
{
|
||||
id: "collapse-all",
|
||||
label: "Collapse all descendants by default",
|
||||
description: "Show only root tasks until the operator expands the tree.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "post-submit-summary",
|
||||
prompt: "What should the answered-state card emphasize after submission?",
|
||||
helpText: "Pick every summary treatment that would help future reviewers.",
|
||||
selectionMode: "multi",
|
||||
required: true,
|
||||
options: [
|
||||
{
|
||||
id: "answers-inline",
|
||||
label: "Inline answer pills",
|
||||
description: "Keep the exact operator choices visible under each question.",
|
||||
},
|
||||
{
|
||||
id: "summary-note",
|
||||
label: "Short markdown summary",
|
||||
description: "Add a compact narrative summary at the bottom of the card.",
|
||||
},
|
||||
{
|
||||
id: "resolver-meta",
|
||||
label: "Resolver metadata",
|
||||
description: "Show who answered and when without opening the raw thread.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
result: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function createRequestConfirmationInteraction(
|
||||
overrides: Partial<RequestConfirmationInteraction>,
|
||||
): RequestConfirmationInteraction {
|
||||
return {
|
||||
id: "interaction-confirmation-default",
|
||||
companyId: issueThreadInteractionFixtureMeta.companyId,
|
||||
issueId: issueThreadInteractionFixtureMeta.issueId,
|
||||
kind: "request_confirmation",
|
||||
title: "Approve the proposed plan",
|
||||
summary:
|
||||
"The assignee is waiting on a direct board decision before continuing from the plan document.",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: "agent-codex",
|
||||
createdByUserId: null,
|
||||
resolvedByAgentId: null,
|
||||
resolvedByUserId: null,
|
||||
createdAt: new Date("2026-04-20T14:30:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:30:00.000Z"),
|
||||
resolvedAt: null,
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Approve the plan and let the assignee start implementation?",
|
||||
acceptLabel: "Approve plan",
|
||||
rejectLabel: "Request revisions",
|
||||
rejectRequiresReason: true,
|
||||
rejectReasonLabel: "Describe the plan changes needed before approval",
|
||||
detailsMarkdown:
|
||||
"This confirmation watches the `plan` document revision so stale approvals are blocked if the plan changes.",
|
||||
supersedeOnUserComment: true,
|
||||
target: {
|
||||
type: "issue_document",
|
||||
issueId: issueThreadInteractionFixtureMeta.issueId,
|
||||
key: "plan",
|
||||
revisionId: "11111111-1111-4111-8111-111111111111",
|
||||
revisionNumber: 3,
|
||||
},
|
||||
},
|
||||
result: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export const pendingSuggestedTasksInteraction = createSuggestTasksInteraction({});
|
||||
|
||||
export const acceptedSuggestedTasksInteraction = createSuggestTasksInteraction({
|
||||
id: "interaction-suggest-accepted",
|
||||
status: "accepted",
|
||||
resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
resolvedAt: new Date("2026-04-20T14:16:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:16:00.000Z"),
|
||||
result: {
|
||||
version: 1,
|
||||
createdTasks: [
|
||||
{
|
||||
clientKey: "root-design",
|
||||
issueId: "issue-created-1",
|
||||
identifier: "PAP-1713",
|
||||
title: "Prototype issue-thread interaction cards",
|
||||
},
|
||||
{
|
||||
clientKey: "child-stories",
|
||||
issueId: "issue-created-2",
|
||||
identifier: "PAP-1714",
|
||||
title: "Add Storybook coverage for acceptance and rejection states",
|
||||
parentIssueId: "issue-created-1",
|
||||
parentIdentifier: "PAP-1713",
|
||||
},
|
||||
{
|
||||
clientKey: "child-mixed-thread",
|
||||
issueId: "issue-created-3",
|
||||
identifier: "PAP-1715",
|
||||
title: "Prototype the mixed thread feed",
|
||||
parentIssueId: "issue-created-1",
|
||||
parentIdentifier: "PAP-1713",
|
||||
},
|
||||
{
|
||||
clientKey: "hidden-follow-up",
|
||||
issueId: "issue-created-4",
|
||||
identifier: "PAP-1716",
|
||||
title: "Follow-up polish on spacing and answered summaries",
|
||||
parentIssueId: "issue-created-3",
|
||||
parentIdentifier: "PAP-1715",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
export const rejectedSuggestedTasksInteraction = createSuggestTasksInteraction({
|
||||
id: "interaction-suggest-rejected",
|
||||
status: "rejected",
|
||||
resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
resolvedAt: new Date("2026-04-20T14:17:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:17:00.000Z"),
|
||||
result: {
|
||||
version: 1,
|
||||
rejectionReason:
|
||||
"Keep the first pass tighter. The hidden follow-on work is useful, but the acceptance story should stay focused on one visible root and one visible child.",
|
||||
},
|
||||
});
|
||||
|
||||
export const pendingAskUserQuestionsInteraction = createAskUserQuestionsInteraction({});
|
||||
|
||||
export const answeredAskUserQuestionsInteraction = createAskUserQuestionsInteraction({
|
||||
id: "interaction-questions-answered",
|
||||
status: "answered",
|
||||
resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
resolvedAt: new Date("2026-04-20T14:24:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:24:00.000Z"),
|
||||
result: {
|
||||
version: 1,
|
||||
answers: [
|
||||
{
|
||||
questionId: "collapse-depth",
|
||||
optionIds: ["visible-root"],
|
||||
},
|
||||
{
|
||||
questionId: "post-submit-summary",
|
||||
optionIds: ["answers-inline", "summary-note", "resolver-meta"],
|
||||
},
|
||||
],
|
||||
summaryMarkdown: [
|
||||
"- Keep visible child tasks expanded when they are part of the main review path.",
|
||||
"- Preserve inline answer chips and resolver metadata in the answered state.",
|
||||
"- Add a short summary note so future reviewers understand the operator's intent without replaying the form.",
|
||||
].join("\n"),
|
||||
},
|
||||
});
|
||||
|
||||
export const pendingRequestConfirmationInteraction = createRequestConfirmationInteraction({});
|
||||
|
||||
export const genericPendingRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-generic-pending",
|
||||
title: "Confirm next step",
|
||||
summary: "The assignee needs a lightweight yes or no before continuing.",
|
||||
continuationPolicy: "none",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Continue with the current approach?",
|
||||
},
|
||||
});
|
||||
|
||||
export const optionalDeclineRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-optional-decline",
|
||||
continuationPolicy: "none",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Use the smaller implementation path?",
|
||||
acceptLabel: "Confirm",
|
||||
rejectLabel: "Decline",
|
||||
rejectRequiresReason: false,
|
||||
declineReasonPlaceholder: "Optional: tell the agent what you'd change.",
|
||||
},
|
||||
});
|
||||
|
||||
export const disabledDeclineReasonRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-no-decline-reason",
|
||||
continuationPolicy: "none",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Close this low-risk follow-up as unnecessary?",
|
||||
acceptLabel: "Close it",
|
||||
rejectLabel: "Keep it",
|
||||
allowDeclineReason: false,
|
||||
},
|
||||
});
|
||||
|
||||
export const acceptedRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-accepted",
|
||||
status: "accepted",
|
||||
resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
resolvedAt: new Date("2026-04-20T14:34:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:34:00.000Z"),
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "accepted",
|
||||
},
|
||||
});
|
||||
|
||||
export const planApprovalAcceptedRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-plan-accepted",
|
||||
status: "accepted",
|
||||
resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
resolvedAt: new Date("2026-04-20T14:34:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:34:00.000Z"),
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Approve the plan and let the assignee start implementation?",
|
||||
acceptLabel: "Approve plan",
|
||||
rejectLabel: "Request changes",
|
||||
rejectRequiresReason: true,
|
||||
declineReasonPlaceholder: "Optional: what would you like revised?",
|
||||
target: {
|
||||
type: "issue_document",
|
||||
issueId: issueThreadInteractionFixtureMeta.issueId,
|
||||
key: "plan",
|
||||
revisionId: "11111111-1111-4111-8111-111111111111",
|
||||
revisionNumber: 4,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "accepted",
|
||||
},
|
||||
});
|
||||
|
||||
export const rejectedRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-rejected",
|
||||
status: "rejected",
|
||||
resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
resolvedAt: new Date("2026-04-20T14:36:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:36:00.000Z"),
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "rejected",
|
||||
reason: "Split the migration and UI work into separate reviewable steps.",
|
||||
},
|
||||
});
|
||||
|
||||
export const rejectedNoReasonRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-rejected-no-reason",
|
||||
status: "rejected",
|
||||
resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
resolvedAt: new Date("2026-04-20T14:37:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:37:00.000Z"),
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "rejected",
|
||||
reason: null,
|
||||
},
|
||||
});
|
||||
|
||||
export const commentExpiredRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-expired-comment",
|
||||
status: "expired",
|
||||
resolvedByUserId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
resolvedAt: new Date("2026-04-20T14:38:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:38:00.000Z"),
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "superseded_by_comment",
|
||||
commentId: "22222222-2222-4222-8222-222222222222",
|
||||
},
|
||||
});
|
||||
|
||||
export const staleTargetRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-expired-target",
|
||||
status: "expired",
|
||||
resolvedByAgentId: "agent-codex",
|
||||
resolvedAt: new Date("2026-04-20T14:40:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:40:00.000Z"),
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Approve the plan and let the assignee start implementation?",
|
||||
acceptLabel: "Approve plan",
|
||||
rejectLabel: "Request revisions",
|
||||
rejectRequiresReason: true,
|
||||
target: {
|
||||
type: "issue_document",
|
||||
issueId: issueThreadInteractionFixtureMeta.issueId,
|
||||
key: "plan",
|
||||
revisionId: "44444444-4444-4444-8444-444444444444",
|
||||
revisionNumber: 4,
|
||||
},
|
||||
},
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "stale_target",
|
||||
staleTarget: {
|
||||
type: "issue_document",
|
||||
issueId: issueThreadInteractionFixtureMeta.issueId,
|
||||
key: "plan",
|
||||
revisionId: "11111111-1111-4111-8111-111111111111",
|
||||
revisionNumber: 3,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const failedRequestConfirmationInteraction = createRequestConfirmationInteraction({
|
||||
id: "interaction-confirmation-failed",
|
||||
status: "failed",
|
||||
updatedAt: new Date("2026-04-20T14:42:00.000Z"),
|
||||
});
|
||||
|
||||
export const issueThreadInteractionComments: IssueChatComment[] = [
|
||||
createComment({
|
||||
id: "comment-thread-board",
|
||||
body: "Pressure-test first-class issue-thread interactions before we touch persistence. I want to see the cards in the real feed, not in a disconnected mock.",
|
||||
createdAt: new Date("2026-04-20T14:02:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:02:00.000Z"),
|
||||
}),
|
||||
createComment({
|
||||
id: "comment-thread-agent",
|
||||
authorAgentId: "agent-codex",
|
||||
authorUserId: null,
|
||||
body: "I found the existing issue chat surface and I am adding prototype-only interaction records so the Storybook review can happen before persistence work.",
|
||||
createdAt: new Date("2026-04-20T14:09:00.000Z"),
|
||||
updatedAt: new Date("2026-04-20T14:09:00.000Z"),
|
||||
runId: "run-thread-interaction",
|
||||
runAgentId: "agent-codex",
|
||||
}),
|
||||
];
|
||||
|
||||
export const issueThreadInteractionEvents: IssueTimelineEvent[] = [
|
||||
{
|
||||
id: "event-thread-checkout",
|
||||
createdAt: new Date("2026-04-20T14:01:00.000Z"),
|
||||
actorType: "user",
|
||||
actorId: issueThreadInteractionFixtureMeta.currentUserId,
|
||||
statusChange: {
|
||||
from: "todo",
|
||||
to: "in_progress",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const issueThreadInteractionLiveRuns: LiveRunForIssue[] = [
|
||||
{
|
||||
id: "run-thread-live",
|
||||
status: "running",
|
||||
invocationSource: "manual",
|
||||
triggerDetail: null,
|
||||
startedAt: "2026-04-20T14:26:00.000Z",
|
||||
finishedAt: null,
|
||||
createdAt: "2026-04-20T14:26:00.000Z",
|
||||
agentId: "agent-codex",
|
||||
agentName: "CodexCoder",
|
||||
adapterType: "codex_local",
|
||||
},
|
||||
];
|
||||
|
||||
export const issueThreadInteractionTranscriptsByRunId = new Map<
|
||||
string,
|
||||
readonly IssueChatTranscriptEntry[]
|
||||
>([
|
||||
[
|
||||
"run-thread-live",
|
||||
[
|
||||
{
|
||||
kind: "assistant",
|
||||
ts: "2026-04-20T14:26:02.000Z",
|
||||
text: "Wiring the prototype interaction cards into the same issue feed that already renders comments and live runs.",
|
||||
},
|
||||
{
|
||||
kind: "thinking",
|
||||
ts: "2026-04-20T14:26:04.000Z",
|
||||
text: "Need to keep the payload shapes local to the UI layer so Phase 0 stays non-persistent.",
|
||||
},
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
export const mixedIssueThreadInteractions = [
|
||||
acceptedSuggestedTasksInteraction,
|
||||
pendingRequestConfirmationInteraction,
|
||||
pendingAskUserQuestionsInteraction,
|
||||
];
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type IssueChatComment,
|
||||
type IssueChatLinkedRun,
|
||||
} from "./issue-chat-messages";
|
||||
import type { SuggestTasksInteraction } from "./issue-thread-interactions";
|
||||
import type { IssueTimelineEvent } from "./issue-timeline-events";
|
||||
import type { LiveRunForIssue } from "../api/heartbeats";
|
||||
|
||||
@@ -51,6 +52,39 @@ function createComment(overrides: Partial<IssueChatComment> = {}): IssueChatComm
|
||||
};
|
||||
}
|
||||
|
||||
function createInteraction(
|
||||
overrides: Partial<SuggestTasksInteraction> = {},
|
||||
): SuggestTasksInteraction {
|
||||
return {
|
||||
id: "interaction-1",
|
||||
companyId: "company-1",
|
||||
issueId: "issue-1",
|
||||
kind: "suggest_tasks",
|
||||
title: "Suggested follow-up work",
|
||||
summary: "Preview the next issue tree before accepting it.",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: "agent-1",
|
||||
createdByUserId: null,
|
||||
resolvedByAgentId: null,
|
||||
resolvedByUserId: null,
|
||||
createdAt: new Date("2026-04-06T12:02:00.000Z"),
|
||||
updatedAt: new Date("2026-04-06T12:02:00.000Z"),
|
||||
resolvedAt: null,
|
||||
payload: {
|
||||
version: 1,
|
||||
tasks: [
|
||||
{
|
||||
clientKey: "task-1",
|
||||
title: "Prototype the card",
|
||||
},
|
||||
],
|
||||
},
|
||||
result: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildAssistantPartsFromTranscript", () => {
|
||||
it("maps assistant text, reasoning, and tool activity while omitting noisy stderr", () => {
|
||||
const result = buildAssistantPartsFromTranscript([
|
||||
@@ -343,6 +377,63 @@ describe("buildIssueChatMessages", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("merges thread interactions into the same chronological feed as comments and runs", () => {
|
||||
const messages = buildIssueChatMessages({
|
||||
comments: [
|
||||
createComment({
|
||||
id: "comment-1",
|
||||
createdAt: new Date("2026-04-06T12:01:00.000Z"),
|
||||
updatedAt: new Date("2026-04-06T12:01:00.000Z"),
|
||||
}),
|
||||
],
|
||||
interactions: [
|
||||
createInteraction({
|
||||
id: "interaction-2",
|
||||
createdAt: new Date("2026-04-06T12:02:00.000Z"),
|
||||
updatedAt: new Date("2026-04-06T12:02:00.000Z"),
|
||||
}),
|
||||
],
|
||||
timelineEvents: [],
|
||||
linkedRuns: [],
|
||||
liveRuns: [
|
||||
{
|
||||
id: "run-live-1",
|
||||
status: "running",
|
||||
invocationSource: "manual",
|
||||
triggerDetail: null,
|
||||
startedAt: "2026-04-06T12:03:00.000Z",
|
||||
finishedAt: null,
|
||||
createdAt: "2026-04-06T12:03:00.000Z",
|
||||
agentId: "agent-1",
|
||||
agentName: "CodexCoder",
|
||||
adapterType: "codex_local",
|
||||
},
|
||||
],
|
||||
transcriptsByRunId: new Map([
|
||||
[
|
||||
"run-live-1",
|
||||
[{ kind: "assistant", ts: "2026-04-06T12:03:01.000Z", text: "Working on it." }],
|
||||
],
|
||||
]),
|
||||
hasOutputForRun: (runId) => runId === "run-live-1",
|
||||
currentUserId: "user-1",
|
||||
});
|
||||
|
||||
expect(messages.map((message) => `${message.role}:${message.id}`)).toEqual([
|
||||
"user:comment-1",
|
||||
"system:interaction:interaction-2",
|
||||
"assistant:run-assistant:run-live-1",
|
||||
]);
|
||||
expect(messages[1]).toMatchObject({
|
||||
metadata: {
|
||||
custom: {
|
||||
kind: "interaction",
|
||||
anchorId: "interaction-interaction-2",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps succeeded runs as assistant messages when transcript output exists", () => {
|
||||
const agentMap = new Map<string, Agent>([["agent-1", createAgent("agent-1", "CodexCoder")]]);
|
||||
const messages = buildIssueChatMessages({
|
||||
|
||||
@@ -10,6 +10,10 @@ import type {
|
||||
import type { Agent, IssueComment } from "@paperclipai/shared";
|
||||
import type { ActiveRunForIssue, LiveRunForIssue } from "../api/heartbeats";
|
||||
import { formatAssigneeUserLabel } from "./assignees";
|
||||
import {
|
||||
buildIssueThreadInteractionSummary,
|
||||
type IssueThreadInteraction,
|
||||
} from "./issue-thread-interactions";
|
||||
import type { IssueTimelineEvent } from "./issue-timeline-events";
|
||||
import {
|
||||
summarizeNotice,
|
||||
@@ -387,6 +391,23 @@ function createTimelineEventMessage(args: {
|
||||
return message;
|
||||
}
|
||||
|
||||
function createInteractionMessage(interaction: IssueThreadInteraction) {
|
||||
const message: ThreadSystemMessage = {
|
||||
id: `interaction:${interaction.id}`,
|
||||
role: "system",
|
||||
createdAt: toDate(interaction.createdAt),
|
||||
content: [{ type: "text", text: buildIssueThreadInteractionSummary(interaction) }],
|
||||
metadata: {
|
||||
custom: {
|
||||
kind: "interaction",
|
||||
anchorId: `interaction-${interaction.id}`,
|
||||
interaction,
|
||||
},
|
||||
},
|
||||
};
|
||||
return message;
|
||||
}
|
||||
|
||||
function runTimestamp(run: IssueChatLinkedRun) {
|
||||
return run.finishedAt ?? run.startedAt ?? run.createdAt;
|
||||
}
|
||||
@@ -738,6 +759,7 @@ function createLiveRunMessage(args: {
|
||||
|
||||
export function buildIssueChatMessages(args: {
|
||||
comments: readonly IssueChatComment[];
|
||||
interactions?: readonly IssueThreadInteraction[];
|
||||
timelineEvents: readonly IssueTimelineEvent[];
|
||||
linkedRuns: readonly IssueChatLinkedRun[];
|
||||
liveRuns: readonly LiveRunForIssue[];
|
||||
@@ -754,6 +776,7 @@ export function buildIssueChatMessages(args: {
|
||||
}) {
|
||||
const {
|
||||
comments,
|
||||
interactions = [],
|
||||
timelineEvents,
|
||||
linkedRuns,
|
||||
liveRuns,
|
||||
@@ -779,6 +802,14 @@ export function buildIssueChatMessages(args: {
|
||||
});
|
||||
}
|
||||
|
||||
for (const interaction of sortByCreated(interactions)) {
|
||||
orderedMessages.push({
|
||||
createdAtMs: toTimestamp(interaction.createdAt),
|
||||
order: 2,
|
||||
message: createInteractionMessage(interaction),
|
||||
});
|
||||
}
|
||||
|
||||
for (const event of sortByCreated(timelineEvents)) {
|
||||
orderedMessages.push({
|
||||
createdAtMs: toTimestamp(event.createdAt),
|
||||
|
||||
150
ui/src/lib/issue-thread-interactions.test.ts
Normal file
150
ui/src/lib/issue-thread-interactions.test.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildIssueThreadInteractionSummary,
|
||||
buildSuggestedTaskTree,
|
||||
collectSuggestedTaskClientKeys,
|
||||
countSuggestedTaskNodes,
|
||||
getQuestionAnswerLabels,
|
||||
} from "./issue-thread-interactions";
|
||||
|
||||
describe("buildSuggestedTaskTree", () => {
|
||||
it("preserves parent-child relationships from client keys", () => {
|
||||
const roots = buildSuggestedTaskTree([
|
||||
{
|
||||
clientKey: "root",
|
||||
title: "Root",
|
||||
},
|
||||
{
|
||||
clientKey: "child",
|
||||
parentClientKey: "root",
|
||||
title: "Child",
|
||||
},
|
||||
{
|
||||
clientKey: "grandchild",
|
||||
parentClientKey: "child",
|
||||
title: "Grandchild",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(roots).toHaveLength(1);
|
||||
expect(roots[0]?.task.clientKey).toBe("root");
|
||||
expect(roots[0]?.children[0]?.task.clientKey).toBe("child");
|
||||
expect(countSuggestedTaskNodes(roots[0]!)).toBe(3);
|
||||
expect(collectSuggestedTaskClientKeys(roots[0]!)).toEqual(["root", "child", "grandchild"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("issue thread interaction helpers", () => {
|
||||
it("summarizes task and question interactions", () => {
|
||||
expect(buildIssueThreadInteractionSummary({
|
||||
id: "interaction-1",
|
||||
companyId: "company-1",
|
||||
issueId: "issue-1",
|
||||
kind: "suggest_tasks",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdAt: "2026-04-06T12:00:00.000Z",
|
||||
updatedAt: "2026-04-06T12:00:00.000Z",
|
||||
payload: {
|
||||
version: 1,
|
||||
tasks: [
|
||||
{ clientKey: "task-1", title: "One" },
|
||||
{ clientKey: "task-2", title: "Two" },
|
||||
],
|
||||
},
|
||||
})).toBe("Suggested 2 tasks");
|
||||
|
||||
expect(buildIssueThreadInteractionSummary({
|
||||
id: "interaction-accepted",
|
||||
companyId: "company-1",
|
||||
issueId: "issue-1",
|
||||
kind: "suggest_tasks",
|
||||
status: "accepted",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdAt: "2026-04-06T12:00:00.000Z",
|
||||
updatedAt: "2026-04-06T12:00:00.000Z",
|
||||
payload: {
|
||||
version: 1,
|
||||
tasks: [
|
||||
{ clientKey: "task-1", title: "One" },
|
||||
{ clientKey: "task-2", title: "Two" },
|
||||
],
|
||||
},
|
||||
result: {
|
||||
version: 1,
|
||||
createdTasks: [{ clientKey: "task-1", issueId: "child-1" }],
|
||||
skippedClientKeys: ["task-2"],
|
||||
},
|
||||
})).toBe("Accepted 1 of 2 tasks");
|
||||
|
||||
expect(buildIssueThreadInteractionSummary({
|
||||
id: "interaction-2",
|
||||
companyId: "company-1",
|
||||
issueId: "issue-1",
|
||||
kind: "ask_user_questions",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdAt: "2026-04-06T12:00:00.000Z",
|
||||
updatedAt: "2026-04-06T12:00:00.000Z",
|
||||
payload: {
|
||||
version: 1,
|
||||
questions: [
|
||||
{
|
||||
id: "question-1",
|
||||
prompt: "Pick one",
|
||||
selectionMode: "single",
|
||||
options: [{ id: "option-1", label: "Option 1" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
})).toBe("Asked 1 question");
|
||||
|
||||
expect(buildIssueThreadInteractionSummary({
|
||||
id: "interaction-answered",
|
||||
companyId: "company-1",
|
||||
issueId: "issue-1",
|
||||
kind: "ask_user_questions",
|
||||
status: "answered",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdAt: "2026-04-06T12:00:00.000Z",
|
||||
updatedAt: "2026-04-06T12:00:00.000Z",
|
||||
payload: {
|
||||
version: 1,
|
||||
questions: [
|
||||
{
|
||||
id: "question-1",
|
||||
prompt: "Pick one",
|
||||
selectionMode: "single",
|
||||
options: [{ id: "option-1", label: "Option 1" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
result: {
|
||||
version: 1,
|
||||
answers: [{ questionId: "question-1", optionIds: ["option-1"] }],
|
||||
},
|
||||
})).toBe("Answered 1 question");
|
||||
});
|
||||
|
||||
it("maps stored option ids back to labels for answered summaries", () => {
|
||||
const labels = getQuestionAnswerLabels({
|
||||
question: {
|
||||
id: "question-1",
|
||||
prompt: "Pick options",
|
||||
selectionMode: "multi",
|
||||
options: [
|
||||
{ id: "option-1", label: "Option 1" },
|
||||
{ id: "option-2", label: "Option 2" },
|
||||
],
|
||||
},
|
||||
answers: [
|
||||
{
|
||||
questionId: "question-1",
|
||||
optionIds: ["option-2", "option-1"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(labels).toEqual(["Option 2", "Option 1"]);
|
||||
});
|
||||
});
|
||||
140
ui/src/lib/issue-thread-interactions.ts
Normal file
140
ui/src/lib/issue-thread-interactions.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
export type {
|
||||
AskUserQuestionsAnswer,
|
||||
AskUserQuestionsInteraction,
|
||||
AskUserQuestionsPayload,
|
||||
AskUserQuestionsQuestion,
|
||||
AskUserQuestionsQuestionOption,
|
||||
AskUserQuestionsResult,
|
||||
IssueThreadInteraction,
|
||||
IssueThreadInteractionActorFields,
|
||||
IssueThreadInteractionBase,
|
||||
IssueThreadInteractionContinuationPolicy,
|
||||
IssueThreadInteractionStatus,
|
||||
RequestConfirmationInteraction,
|
||||
RequestConfirmationIssueDocumentTarget,
|
||||
RequestConfirmationPayload,
|
||||
RequestConfirmationResult,
|
||||
RequestConfirmationTarget,
|
||||
SuggestedTaskDraft,
|
||||
SuggestTasksInteraction,
|
||||
SuggestTasksPayload,
|
||||
SuggestTasksResult,
|
||||
SuggestTasksResultCreatedTask,
|
||||
} from "@paperclipai/shared";
|
||||
import type {
|
||||
AskUserQuestionsAnswer,
|
||||
AskUserQuestionsInteraction,
|
||||
AskUserQuestionsQuestion,
|
||||
IssueThreadInteraction,
|
||||
RequestConfirmationInteraction,
|
||||
SuggestedTaskDraft,
|
||||
SuggestTasksInteraction,
|
||||
SuggestTasksResultCreatedTask,
|
||||
} from "@paperclipai/shared";
|
||||
|
||||
export interface SuggestedTaskTreeNode {
|
||||
task: SuggestedTaskDraft;
|
||||
children: SuggestedTaskTreeNode[];
|
||||
}
|
||||
|
||||
export function isIssueThreadInteraction(
|
||||
value: unknown,
|
||||
): value is IssueThreadInteraction {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const candidate = value as Partial<IssueThreadInteraction>;
|
||||
return typeof candidate.id === "string"
|
||||
&& typeof candidate.companyId === "string"
|
||||
&& typeof candidate.issueId === "string"
|
||||
&& (
|
||||
candidate.kind === "suggest_tasks"
|
||||
|| candidate.kind === "ask_user_questions"
|
||||
|| candidate.kind === "request_confirmation"
|
||||
);
|
||||
}
|
||||
|
||||
export function buildIssueThreadInteractionSummary(
|
||||
interaction: IssueThreadInteraction,
|
||||
) {
|
||||
if (interaction.kind === "suggest_tasks") {
|
||||
const count = interaction.payload.tasks.length;
|
||||
if (interaction.status === "accepted") {
|
||||
const createdCount = interaction.result?.createdTasks?.length ?? 0;
|
||||
const skippedCount = interaction.result?.skippedClientKeys?.length ?? 0;
|
||||
if (skippedCount > 0) {
|
||||
return `Accepted ${createdCount} of ${count} tasks`;
|
||||
}
|
||||
return createdCount === 1 ? "Accepted 1 task" : `Accepted ${createdCount} tasks`;
|
||||
}
|
||||
if (interaction.status === "rejected") {
|
||||
return count === 1 ? "Rejected 1 task" : `Rejected ${count} tasks`;
|
||||
}
|
||||
return count === 1 ? "Suggested 1 task" : `Suggested ${count} tasks`;
|
||||
}
|
||||
|
||||
if (interaction.kind === "request_confirmation") {
|
||||
if (interaction.status === "accepted") return "Confirmed request";
|
||||
if (interaction.status === "rejected") return "Declined request";
|
||||
if (interaction.status === "expired") {
|
||||
const outcome = interaction.result?.outcome;
|
||||
if (outcome === "superseded_by_comment") return "Confirmation expired after comment";
|
||||
if (outcome === "stale_target") return "Confirmation expired after target changed";
|
||||
return "Confirmation expired";
|
||||
}
|
||||
return "Requested confirmation";
|
||||
}
|
||||
|
||||
const count = interaction.payload.questions.length;
|
||||
if (interaction.status === "answered") {
|
||||
return count === 1 ? "Answered 1 question" : `Answered ${count} questions`;
|
||||
}
|
||||
return count === 1 ? "Asked 1 question" : `Asked ${count} questions`;
|
||||
}
|
||||
|
||||
export function buildSuggestedTaskTree(
|
||||
tasks: readonly SuggestedTaskDraft[],
|
||||
): SuggestedTaskTreeNode[] {
|
||||
const nodes = new Map<string, SuggestedTaskTreeNode>();
|
||||
for (const task of tasks) {
|
||||
nodes.set(task.clientKey, { task, children: [] });
|
||||
}
|
||||
|
||||
const roots: SuggestedTaskTreeNode[] = [];
|
||||
for (const task of tasks) {
|
||||
const node = nodes.get(task.clientKey);
|
||||
if (!node) continue;
|
||||
const parentNode = task.parentClientKey ? nodes.get(task.parentClientKey) : null;
|
||||
if (parentNode) {
|
||||
parentNode.children.push(node);
|
||||
continue;
|
||||
}
|
||||
roots.push(node);
|
||||
}
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
export function countSuggestedTaskNodes(node: SuggestedTaskTreeNode): number {
|
||||
return 1 + node.children.reduce((sum, child) => sum + countSuggestedTaskNodes(child), 0);
|
||||
}
|
||||
|
||||
export function collectSuggestedTaskClientKeys(node: SuggestedTaskTreeNode): string[] {
|
||||
return [
|
||||
node.task.clientKey,
|
||||
...node.children.flatMap((child) => collectSuggestedTaskClientKeys(child)),
|
||||
];
|
||||
}
|
||||
|
||||
export function getQuestionAnswerLabels(args: {
|
||||
question: AskUserQuestionsQuestion;
|
||||
answers: readonly AskUserQuestionsAnswer[];
|
||||
}) {
|
||||
const { question, answers } = args;
|
||||
const selectedIds =
|
||||
answers.find((answer) => answer.questionId === question.id)?.optionIds ?? [];
|
||||
const optionLabelById = new Map(
|
||||
question.options.map((option) => [option.id, option.label] as const),
|
||||
);
|
||||
return selectedIds
|
||||
.map((optionId) => optionLabelById.get(optionId))
|
||||
.filter((label): label is string => typeof label === "string");
|
||||
}
|
||||
@@ -45,6 +45,7 @@ export const queryKeys = {
|
||||
["issues", companyId, "execution-workspace", executionWorkspaceId] as const,
|
||||
detail: (id: string) => ["issues", "detail", id] as const,
|
||||
comments: (issueId: string) => ["issues", "comments", issueId] as const,
|
||||
interactions: (issueId: string) => ["issues", "interactions", issueId] as const,
|
||||
feedbackVotes: (issueId: string) => ["issues", "feedback-votes", issueId] as const,
|
||||
attachments: (issueId: string) => ["issues", "attachments", issueId] as const,
|
||||
documents: (issueId: string) => ["issues", "documents", issueId] as const,
|
||||
|
||||
@@ -112,15 +112,20 @@ import {
|
||||
getClosedIsolatedExecutionWorkspaceMessage,
|
||||
isClosedIsolatedExecutionWorkspace,
|
||||
ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
|
||||
type AskUserQuestionsAnswer,
|
||||
type ActivityEvent,
|
||||
type Agent,
|
||||
type FeedbackVote,
|
||||
type Issue,
|
||||
type IssueAttachment,
|
||||
type IssueComment,
|
||||
type IssueThreadInteraction,
|
||||
type RequestConfirmationInteraction,
|
||||
type SuggestTasksInteraction,
|
||||
} from "@paperclipai/shared";
|
||||
|
||||
type CommentReassignment = IssueCommentReassignment;
|
||||
type ActionableIssueThreadInteraction = SuggestTasksInteraction | RequestConfirmationInteraction;
|
||||
type IssueDetailComment = (IssueComment | OptimisticIssueComment) & {
|
||||
runId?: string | null;
|
||||
runAgentId?: string | null;
|
||||
@@ -509,6 +514,7 @@ type IssueDetailChatTabProps = {
|
||||
blockedBy: Issue["blockedBy"];
|
||||
comments: IssueDetailComment[];
|
||||
locallyQueuedCommentRunIds: ReadonlyMap<string, string>;
|
||||
interactions: IssueThreadInteraction[];
|
||||
hasOlderComments: boolean;
|
||||
commentsLoadingOlder: boolean;
|
||||
onLoadOlderComments: () => void;
|
||||
@@ -538,6 +544,15 @@ type IssueDetailChatTabProps = {
|
||||
onCancelQueued: (commentId: string) => void;
|
||||
interruptingQueuedRunId: string | null;
|
||||
onImageClick: (src: string) => void;
|
||||
onAcceptInteraction: (
|
||||
interaction: ActionableIssueThreadInteraction,
|
||||
selectedClientKeys?: string[],
|
||||
) => Promise<void>;
|
||||
onRejectInteraction: (interaction: ActionableIssueThreadInteraction, reason?: string) => Promise<void>;
|
||||
onSubmitInteractionAnswers: (
|
||||
interaction: IssueThreadInteraction,
|
||||
answers: AskUserQuestionsAnswer[],
|
||||
) => Promise<void>;
|
||||
};
|
||||
|
||||
const IssueDetailChatTab = memo(function IssueDetailChatTab({
|
||||
@@ -549,6 +564,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
|
||||
blockedBy,
|
||||
comments,
|
||||
locallyQueuedCommentRunIds,
|
||||
interactions,
|
||||
hasOlderComments,
|
||||
commentsLoadingOlder,
|
||||
onLoadOlderComments,
|
||||
@@ -574,6 +590,9 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
|
||||
onCancelQueued,
|
||||
interruptingQueuedRunId,
|
||||
onImageClick,
|
||||
onAcceptInteraction,
|
||||
onRejectInteraction,
|
||||
onSubmitInteractionAnswers,
|
||||
}: IssueDetailChatTabProps) {
|
||||
const { data: activity } = useQuery({
|
||||
queryKey: queryKeys.issues.activity(issueId),
|
||||
@@ -704,6 +723,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
|
||||
<IssueChatThread
|
||||
composerRef={composerRef}
|
||||
comments={commentsWithRunMeta}
|
||||
interactions={interactions}
|
||||
feedbackVotes={feedbackVotes}
|
||||
feedbackDataSharingPreference={feedbackDataSharingPreference}
|
||||
feedbackTermsUrl={feedbackTermsUrl}
|
||||
@@ -735,6 +755,11 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
|
||||
interruptingQueuedRunId={interruptingQueuedRunId}
|
||||
stoppingRunId={interruptingQueuedRunId}
|
||||
onStopRun={onInterruptQueued}
|
||||
onAcceptInteraction={onAcceptInteraction}
|
||||
onRejectInteraction={onRejectInteraction}
|
||||
onSubmitInteractionAnswers={(interaction, answers) =>
|
||||
onSubmitInteractionAnswers(interaction, answers)
|
||||
}
|
||||
onCancelRun={runningIssueRun
|
||||
? async () => {
|
||||
await onInterruptQueued(runningIssueRun.id);
|
||||
@@ -1006,6 +1031,12 @@ export function IssueDetail() {
|
||||
() => flattenIssueCommentPages(commentPages?.pages),
|
||||
[commentPages?.pages],
|
||||
);
|
||||
const { data: interactions = [] } = useQuery({
|
||||
queryKey: queryKeys.issues.interactions(issueId!),
|
||||
queryFn: () => issuesApi.listInteractions(issueId!),
|
||||
enabled: !!issueId,
|
||||
placeholderData: keepPreviousDataForSameQueryTail<IssueThreadInteraction[]>(issueId ?? "pending"),
|
||||
});
|
||||
|
||||
const { data: attachments, isLoading: attachmentsLoading } = useQuery({
|
||||
queryKey: queryKeys.issues.attachments(issueId!),
|
||||
@@ -1207,10 +1238,12 @@ export function IssueDetail() {
|
||||
const invalidateIssueDetail = useCallback(() => {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId!) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(issueId!) });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.interactions(issueId!) });
|
||||
}, [issueId, queryClient]);
|
||||
const invalidateIssueThreadLazily = useCallback(() => {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.detail(issueId!), refetchType: "inactive" });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.activity(issueId!), refetchType: "inactive" });
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.interactions(issueId!), refetchType: "inactive" });
|
||||
}, [issueId, queryClient]);
|
||||
|
||||
const invalidateIssueRunState = useCallback(() => {
|
||||
@@ -1245,6 +1278,22 @@ export function IssueDetail() {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.sidebarBadges(selectedCompanyId) });
|
||||
}
|
||||
}, [queryClient, selectedCompanyId]);
|
||||
const upsertInteractionInCache = useCallback((interaction: IssueThreadInteraction) => {
|
||||
queryClient.setQueryData<IssueThreadInteraction[] | undefined>(
|
||||
queryKeys.issues.interactions(issueId!),
|
||||
(current) => {
|
||||
const existing = current ?? [];
|
||||
const next = existing.filter((entry) => entry.id !== interaction.id);
|
||||
next.push(interaction);
|
||||
next.sort((left, right) => {
|
||||
const createdAtDelta =
|
||||
new Date(left.createdAt).getTime() - new Date(right.createdAt).getTime();
|
||||
return createdAtDelta === 0 ? left.id.localeCompare(right.id) : createdAtDelta;
|
||||
});
|
||||
return next;
|
||||
},
|
||||
);
|
||||
}, [issueId, queryClient]);
|
||||
|
||||
const applyOptimisticIssueCacheUpdate = useCallback((refs: Iterable<string>, data: Record<string, unknown>) => {
|
||||
queryClient.setQueriesData<Issue>(
|
||||
@@ -1495,6 +1544,89 @@ export function IssueDetail() {
|
||||
}
|
||||
},
|
||||
});
|
||||
const acceptInteraction = useMutation({
|
||||
mutationFn: ({
|
||||
interaction,
|
||||
selectedClientKeys,
|
||||
}: {
|
||||
interaction: ActionableIssueThreadInteraction;
|
||||
selectedClientKeys?: string[];
|
||||
}) => issuesApi.acceptInteraction(issueId!, interaction.id, { selectedClientKeys }),
|
||||
onSuccess: (interaction) => {
|
||||
upsertInteractionInCache(interaction);
|
||||
if (interaction.kind === "suggest_tasks" && resolvedCompanyId && issue?.id) {
|
||||
queryClient.invalidateQueries({ queryKey: queryKeys.issues.listByParent(resolvedCompanyId, issue.id) });
|
||||
}
|
||||
invalidateIssueDetail();
|
||||
invalidateIssueCollections();
|
||||
const createdCount = interaction.kind === "suggest_tasks"
|
||||
? interaction.result?.createdTasks?.length ?? 0
|
||||
: 0;
|
||||
const skippedCount = interaction.kind === "suggest_tasks"
|
||||
? interaction.result?.skippedClientKeys?.length ?? 0
|
||||
: 0;
|
||||
pushToast({
|
||||
title: interaction.kind === "request_confirmation"
|
||||
? "Request confirmed"
|
||||
: skippedCount > 0
|
||||
? `Accepted ${createdCount} draft${createdCount === 1 ? "" : "s"} and skipped ${skippedCount}`
|
||||
: "Suggested tasks accepted",
|
||||
tone: "success",
|
||||
});
|
||||
},
|
||||
onError: (err) => {
|
||||
pushToast({
|
||||
title: "Accept failed",
|
||||
body: err instanceof Error ? err.message : "Unable to accept the suggested tasks",
|
||||
tone: "error",
|
||||
});
|
||||
},
|
||||
});
|
||||
const rejectInteraction = useMutation({
|
||||
mutationFn: ({ interaction, reason }: { interaction: ActionableIssueThreadInteraction; reason?: string }) =>
|
||||
issuesApi.rejectInteraction(issueId!, interaction.id, reason),
|
||||
onSuccess: (interaction) => {
|
||||
upsertInteractionInCache(interaction);
|
||||
invalidateIssueDetail();
|
||||
invalidateIssueCollections();
|
||||
pushToast({
|
||||
title: interaction.kind === "request_confirmation" ? "Request declined" : "Suggestion rejected",
|
||||
tone: "success",
|
||||
});
|
||||
},
|
||||
onError: (err) => {
|
||||
pushToast({
|
||||
title: "Reject failed",
|
||||
body: err instanceof Error ? err.message : "Unable to reject the suggested tasks",
|
||||
tone: "error",
|
||||
});
|
||||
},
|
||||
});
|
||||
const answerInteraction = useMutation({
|
||||
mutationFn: ({
|
||||
interaction,
|
||||
answers,
|
||||
}: {
|
||||
interaction: IssueThreadInteraction;
|
||||
answers: AskUserQuestionsAnswer[];
|
||||
}) => issuesApi.respondToInteraction(issueId!, interaction.id, { answers }),
|
||||
onSuccess: (interaction) => {
|
||||
upsertInteractionInCache(interaction);
|
||||
invalidateIssueDetail();
|
||||
invalidateIssueCollections();
|
||||
pushToast({
|
||||
title: "Answers submitted",
|
||||
tone: "success",
|
||||
});
|
||||
},
|
||||
onError: (err) => {
|
||||
pushToast({
|
||||
title: "Submit failed",
|
||||
body: err instanceof Error ? err.message : "Unable to submit answers",
|
||||
tone: "error",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const addCommentAndReassign = useMutation({
|
||||
mutationFn: ({
|
||||
@@ -2224,6 +2356,21 @@ export function IssueDetail() {
|
||||
const handleInterruptQueuedRun = useCallback(async (runId: string) => {
|
||||
await interruptQueuedComment.mutateAsync(runId);
|
||||
}, [interruptQueuedComment]);
|
||||
const handleAcceptInteraction = useCallback(async (
|
||||
interaction: ActionableIssueThreadInteraction,
|
||||
selectedClientKeys?: string[],
|
||||
) => {
|
||||
await acceptInteraction.mutateAsync({ interaction, selectedClientKeys });
|
||||
}, [acceptInteraction]);
|
||||
const handleRejectInteraction = useCallback(async (interaction: ActionableIssueThreadInteraction, reason?: string) => {
|
||||
await rejectInteraction.mutateAsync({ interaction, reason });
|
||||
}, [rejectInteraction]);
|
||||
const handleSubmitInteractionAnswers = useCallback(async (
|
||||
interaction: IssueThreadInteraction,
|
||||
answers: AskUserQuestionsAnswer[],
|
||||
) => {
|
||||
await answerInteraction.mutateAsync({ interaction, answers });
|
||||
}, [answerInteraction]);
|
||||
|
||||
if (isLoading) return <IssueDetailLoadingState headerSeed={issueHeaderSeed} />;
|
||||
if (error) return <p className="text-sm text-destructive">{error.message}</p>;
|
||||
@@ -2775,6 +2922,7 @@ export function IssueDetail() {
|
||||
blockedBy={issue.blockedBy ?? []}
|
||||
comments={threadComments}
|
||||
locallyQueuedCommentRunIds={locallyQueuedCommentRunIds}
|
||||
interactions={interactions}
|
||||
hasOlderComments={hasOlderComments}
|
||||
commentsLoadingOlder={commentsLoadingOlder}
|
||||
onLoadOlderComments={loadOlderComments}
|
||||
@@ -2800,6 +2948,9 @@ export function IssueDetail() {
|
||||
onCancelQueued={handleCancelQueuedComment}
|
||||
interruptingQueuedRunId={interruptQueuedComment.isPending ? interruptQueuedComment.variables ?? null : null}
|
||||
onImageClick={handleChatImageClick}
|
||||
onAcceptInteraction={handleAcceptInteraction}
|
||||
onRejectInteraction={handleRejectInteraction}
|
||||
onSubmitInteractionAnswers={handleSubmitInteractionAnswers}
|
||||
/>
|
||||
) : null}
|
||||
</TabsContent>
|
||||
|
||||
681
ui/storybook/stories/issue-thread-interactions.stories.tsx
Normal file
681
ui/storybook/stories/issue-thread-interactions.stories.tsx
Normal file
@@ -0,0 +1,681 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { IssueChatThread } from "@/components/IssueChatThread";
|
||||
import { IssueThreadInteractionCard } from "@/components/IssueThreadInteractionCard";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
acceptedSuggestedTasksInteraction,
|
||||
answeredAskUserQuestionsInteraction,
|
||||
acceptedRequestConfirmationInteraction,
|
||||
commentExpiredRequestConfirmationInteraction,
|
||||
failedRequestConfirmationInteraction,
|
||||
genericPendingRequestConfirmationInteraction,
|
||||
issueThreadInteractionComments,
|
||||
issueThreadInteractionEvents,
|
||||
issueThreadInteractionFixtureMeta,
|
||||
issueThreadInteractionLiveRuns,
|
||||
issueThreadInteractionTranscriptsByRunId,
|
||||
mixedIssueThreadInteractions,
|
||||
optionalDeclineRequestConfirmationInteraction,
|
||||
pendingAskUserQuestionsInteraction,
|
||||
pendingRequestConfirmationInteraction,
|
||||
pendingSuggestedTasksInteraction,
|
||||
planApprovalAcceptedRequestConfirmationInteraction,
|
||||
rejectedNoReasonRequestConfirmationInteraction,
|
||||
rejectedRequestConfirmationInteraction,
|
||||
rejectedSuggestedTasksInteraction,
|
||||
staleTargetRequestConfirmationInteraction,
|
||||
} from "@/fixtures/issueThreadInteractionFixtures";
|
||||
import type {
|
||||
AskUserQuestionsAnswer,
|
||||
AskUserQuestionsInteraction,
|
||||
RequestConfirmationInteraction,
|
||||
SuggestTasksInteraction,
|
||||
} from "@/lib/issue-thread-interactions";
|
||||
import { storybookAgentMap } from "../fixtures/paperclipData";
|
||||
|
||||
const boardUserLabels = new Map<string, string>([
|
||||
[issueThreadInteractionFixtureMeta.currentUserId, "Riley Board"],
|
||||
["user-product", "Mara Product"],
|
||||
]);
|
||||
|
||||
function StoryFrame({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="paperclip-story">
|
||||
<main className="paperclip-story__inner space-y-6">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({
|
||||
eyebrow,
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
eyebrow: string;
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="paperclip-story__frame overflow-hidden">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3 border-b border-border px-5 py-4">
|
||||
<div>
|
||||
<div className="paperclip-story__label">{eyebrow}</div>
|
||||
<h2 className="mt-1 text-xl font-semibold">{title}</h2>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-5">{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ScenarioCard({
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
description: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<Card className="shadow-none">
|
||||
<CardHeader>
|
||||
<CardTitle>{title}</CardTitle>
|
||||
<CardDescription>{description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>{children}</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function InteractiveSuggestedTasksCard() {
|
||||
const [interaction, setInteraction] = useState<SuggestTasksInteraction>(
|
||||
pendingSuggestedTasksInteraction,
|
||||
);
|
||||
|
||||
return (
|
||||
<IssueThreadInteractionCard
|
||||
interaction={interaction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
onAcceptInteraction={(_interaction, selectedClientKeys) =>
|
||||
setInteraction({
|
||||
...acceptedSuggestedTasksInteraction,
|
||||
result: {
|
||||
version: 1,
|
||||
createdTasks: (acceptedSuggestedTasksInteraction.result?.createdTasks ?? []).filter((task) =>
|
||||
selectedClientKeys?.includes(task.clientKey) ?? true),
|
||||
skippedClientKeys: pendingSuggestedTasksInteraction.payload.tasks
|
||||
.map((task) => task.clientKey)
|
||||
.filter((clientKey) => !(selectedClientKeys?.includes(clientKey) ?? true)),
|
||||
},
|
||||
})}
|
||||
onRejectInteraction={(_interaction, reason) =>
|
||||
setInteraction({
|
||||
...rejectedSuggestedTasksInteraction,
|
||||
result: {
|
||||
version: 1,
|
||||
...(rejectedSuggestedTasksInteraction.result ?? {}),
|
||||
rejectionReason:
|
||||
reason
|
||||
|| rejectedSuggestedTasksInteraction.result?.rejectionReason
|
||||
|| null,
|
||||
},
|
||||
})}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function buildAnsweredInteraction(
|
||||
answers: AskUserQuestionsAnswer[],
|
||||
): AskUserQuestionsInteraction {
|
||||
const labels = pendingAskUserQuestionsInteraction.payload.questions.flatMap((question) => {
|
||||
const answer = answers.find((entry) => entry.questionId === question.id);
|
||||
if (!answer) return [];
|
||||
return question.options
|
||||
.filter((option) => answer.optionIds.includes(option.id))
|
||||
.map((option) => option.label);
|
||||
});
|
||||
|
||||
return {
|
||||
...answeredAskUserQuestionsInteraction,
|
||||
result: {
|
||||
version: 1,
|
||||
answers,
|
||||
summaryMarkdown: labels.map((label) => `- ${label}`).join("\n"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function InteractiveAskUserQuestionsCard() {
|
||||
const [interaction, setInteraction] = useState<AskUserQuestionsInteraction>(
|
||||
pendingAskUserQuestionsInteraction,
|
||||
);
|
||||
|
||||
return (
|
||||
<IssueThreadInteractionCard
|
||||
interaction={interaction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
onSubmitInteractionAnswers={(_interaction, answers) =>
|
||||
setInteraction(buildAnsweredInteraction(answers))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function InteractiveRequestConfirmationCard() {
|
||||
const [interaction, setInteraction] = useState<RequestConfirmationInteraction>(
|
||||
pendingRequestConfirmationInteraction,
|
||||
);
|
||||
|
||||
return (
|
||||
<IssueThreadInteractionCard
|
||||
interaction={interaction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
onAcceptInteraction={() => setInteraction(acceptedRequestConfirmationInteraction)}
|
||||
onRejectInteraction={(_interaction, reason) =>
|
||||
setInteraction({
|
||||
...rejectedRequestConfirmationInteraction,
|
||||
result: {
|
||||
version: 1,
|
||||
outcome: "rejected",
|
||||
reason: reason || rejectedRequestConfirmationInteraction.result?.reason || null,
|
||||
},
|
||||
})}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AutoOpenDeclineRequestConfirmationCard({
|
||||
interaction,
|
||||
}: {
|
||||
interaction: RequestConfirmationInteraction;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const declineButton = Array.from(ref.current?.querySelectorAll("button") ?? [])
|
||||
.find((button) => button.textContent?.includes(interaction.payload.rejectLabel ?? "Decline"));
|
||||
declineButton?.click();
|
||||
}, [interaction]);
|
||||
|
||||
return (
|
||||
<div ref={ref}>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={interaction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
onAcceptInteraction={() => undefined}
|
||||
onRejectInteraction={() => undefined}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const meta = {
|
||||
title: "Chat & Comments/Issue Thread Interactions",
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Interaction cards for `suggest_tasks`, `ask_user_questions`, and `request_confirmation`, shown both in isolation and inside the real `IssueChatThread` feed.",
|
||||
},
|
||||
},
|
||||
},
|
||||
} satisfies Meta;
|
||||
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const SuggestedTasksPending: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Pending suggested tasks"
|
||||
description="Draft issues are selectable before they become real issues."
|
||||
>
|
||||
<InteractiveSuggestedTasksCard />
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const SuggestedTasksAccepted: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Accepted suggested tasks"
|
||||
description="Created issues are linked back to their original draft rows."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={acceptedSuggestedTasksInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const SuggestedTasksRejected: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Rejected suggested tasks"
|
||||
description="The declined draft stays visible with its rejection note."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={rejectedSuggestedTasksInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const AskUserQuestionsPending: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Pending question form"
|
||||
description="Single- and multi-select questions remain local until submitted."
|
||||
>
|
||||
<InteractiveAskUserQuestionsCard />
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const AskUserQuestionsAnswered: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Answered question form"
|
||||
description="Selected answers and the submitted summary remain attached to the thread."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={answeredAskUserQuestionsInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationPending: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Pending request confirmation"
|
||||
description="A generic confirmation can render without a target or custom labels."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={genericPendingRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
onAcceptInteraction={() => undefined}
|
||||
onRejectInteraction={() => undefined}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationPendingWithTarget: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Pending request confirmation with target"
|
||||
description="The watched plan document renders as a compact target chip."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={pendingRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
onAcceptInteraction={() => undefined}
|
||||
onRejectInteraction={() => undefined}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationPendingDecliningOptional: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Pending optional decline"
|
||||
description="The decline textarea is visible, but a reason is optional."
|
||||
>
|
||||
<AutoOpenDeclineRequestConfirmationCard
|
||||
interaction={optionalDeclineRequestConfirmationInteraction}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationPendingRequireReason: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Pending required decline reason"
|
||||
description="A plan approval waits for an explicit board decision and requires a decline reason."
|
||||
>
|
||||
<InteractiveRequestConfirmationCard />
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationConfirmed: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Confirmed request confirmation"
|
||||
description="The resolved state remains visible without active controls."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={acceptedRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationDeclinedWithReason: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Declined request confirmation"
|
||||
description="The decline reason stays attached to the request in the thread."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={rejectedRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationDeclinedNoReason: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Declined without a reason"
|
||||
description="The card stays compact when no decline reason was provided."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={rejectedNoReasonRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationExpiredByComment: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Expired by comment"
|
||||
description="A board comment superseded the request before resolution."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={commentExpiredRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationExpiredByTargetChange: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Expired by target change"
|
||||
description="The watched plan document moved to a newer revision before approval."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={staleTargetRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationPlanApprovalPending: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Pending plan approval"
|
||||
description="The plan-approval variant keeps the approval labels and target chip visible."
|
||||
>
|
||||
<InteractiveRequestConfirmationCard />
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationPlanApprovalConfirmed: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Confirmed plan approval"
|
||||
description="The resolved plan approval reads as a compact receipt."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={planApprovalAcceptedRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationFailed: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<ScenarioCard
|
||||
title="Failed request confirmation"
|
||||
description="The failed state provides explicit recovery copy."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={failedRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</StoryFrame>
|
||||
),
|
||||
};
|
||||
|
||||
export const RequestConfirmationAccepted = RequestConfirmationConfirmed;
|
||||
export const RequestConfirmationRejected = RequestConfirmationDeclinedWithReason;
|
||||
|
||||
export const ReviewSurface: Story = {
|
||||
render: () => (
|
||||
<StoryFrame>
|
||||
<section className="paperclip-story__frame p-6">
|
||||
<div className="paperclip-story__label">Thread interactions</div>
|
||||
<div className="mt-2 max-w-3xl text-sm leading-6 text-muted-foreground">
|
||||
This review surface pressure-tests the thread interaction kinds directly inside the issue
|
||||
chat surface. The card language leans closer to
|
||||
annotated review sheets than generic admin widgets so the objects feel like first-class work
|
||||
artifacts in the thread.
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Section eyebrow="Suggested Tasks" title="Pending, accepted, and rejected task-tree cards">
|
||||
<div className="grid gap-6 xl:grid-cols-3">
|
||||
<ScenarioCard
|
||||
title="Pending"
|
||||
description="The draft tree stays editable and non-persistent until someone accepts or rejects it."
|
||||
>
|
||||
<InteractiveSuggestedTasksCard />
|
||||
</ScenarioCard>
|
||||
<ScenarioCard
|
||||
title="Accepted"
|
||||
description="Accepted state resolves to created issue links while keeping the original suggestion visible in-thread."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={acceptedSuggestedTasksInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
<ScenarioCard
|
||||
title="Rejected"
|
||||
description="The rejection reason remains attached to the artifact so future reviewers can see why the draft was declined."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={rejectedSuggestedTasksInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section eyebrow="Ask User Questions" title="Pending multi-question form and answered summary">
|
||||
<div className="grid gap-6 xl:grid-cols-2">
|
||||
<ScenarioCard
|
||||
title="Pending"
|
||||
description="Answers stay local across the whole form and only wake the assignee once after final submit."
|
||||
>
|
||||
<InteractiveAskUserQuestionsCard />
|
||||
</ScenarioCard>
|
||||
<ScenarioCard
|
||||
title="Answered"
|
||||
description="The answered state keeps the exact choices visible and adds a compact summary note for later review."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={answeredAskUserQuestionsInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section eyebrow="Request Confirmation" title="Plan approval and compact resolution states">
|
||||
<div className="grid gap-6 xl:grid-cols-2">
|
||||
<ScenarioCard
|
||||
title="Plan approval"
|
||||
description="The pending card links to the watched plan revision and requires a reason when declined."
|
||||
>
|
||||
<InteractiveRequestConfirmationCard />
|
||||
</ScenarioCard>
|
||||
<ScenarioCard
|
||||
title="Accepted"
|
||||
description="Accepted confirmations stay visible as resolved work artifacts."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={acceptedRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
<ScenarioCard
|
||||
title="Rejected"
|
||||
description="Rejected confirmations keep the board's decline reason attached."
|
||||
>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={rejectedRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</ScenarioCard>
|
||||
<ScenarioCard
|
||||
title="Expired states"
|
||||
description="Comment and target-change expiry states are compact and disabled."
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<IssueThreadInteractionCard
|
||||
interaction={commentExpiredRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
<IssueThreadInteractionCard
|
||||
interaction={staleTargetRequestConfirmationInteraction}
|
||||
agentMap={storybookAgentMap}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
/>
|
||||
</div>
|
||||
</ScenarioCard>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section eyebrow="Mixed Feed" title="Interaction cards in the real issue thread">
|
||||
<ScenarioCard
|
||||
title="IssueChatThread composition"
|
||||
description="Comments, timeline events, accepted task suggestions, a pending confirmation, a pending question form, and an active run share the same feed."
|
||||
>
|
||||
<div className="overflow-hidden rounded-[32px] border border-border/70 bg-[linear-gradient(135deg,rgba(14,165,233,0.08),transparent_28%),linear-gradient(180deg,rgba(245,158,11,0.08),transparent_42%),var(--background)] p-5 shadow-[0_30px_80px_rgba(15,23,42,0.10)]">
|
||||
<IssueChatThread
|
||||
comments={issueThreadInteractionComments}
|
||||
interactions={mixedIssueThreadInteractions}
|
||||
timelineEvents={issueThreadInteractionEvents}
|
||||
liveRuns={issueThreadInteractionLiveRuns}
|
||||
transcriptsByRunId={issueThreadInteractionTranscriptsByRunId}
|
||||
hasOutputForRun={(runId) => runId === "run-thread-live"}
|
||||
companyId={issueThreadInteractionFixtureMeta.companyId}
|
||||
projectId={issueThreadInteractionFixtureMeta.projectId}
|
||||
currentUserId={issueThreadInteractionFixtureMeta.currentUserId}
|
||||
userLabelMap={boardUserLabels}
|
||||
agentMap={storybookAgentMap}
|
||||
onAdd={async () => {}}
|
||||
showComposer={false}
|
||||
/>
|
||||
</div>
|
||||
</ScenarioCard>
|
||||
</Section>
|
||||
</StoryFrame>
|
||||
),
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Covers the prototype states called out in [PAP-1709](/PAP/issues/PAP-1709): suggested-task previews, collapsed descendants, rejection reasons, request confirmations, multi-question answers, and a mixed issue thread.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user