fix(chat): keep dismissed task questions in the feed (#15229)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents ask users questions in task chats and Agent Chat.
> - Agent Chat keeps unanswered questions as compact entries in the
feed.
> - Regular task chats still show a pending composer badge after
dismissal.
> - A page reload can also open a dismissed question form again.
> - This pull request applies the same feed behavior to both chat types
and saves dismissal per person and task.
> - Users can continue the chat and return to the original question
later.

## Linked Issues or Issue Description

**What happened?**

Dismissing a question in a regular task chat leaves a pending composer
badge. The question can return after a page reload. The earlier feed
behavior only applied to Agent Chat.

**Expected behavior**

A dismissed question stays in the feed. Its form and pending badge leave
the composer. Reload preserves dismissal. Opening the feed entry
restores the original question and draft answer.

**Steps to reproduce**

1. Open a regular task chat with a pending question.
2. Select an option, then dismiss the form.
3. Reload the page. Check that the composer stays clear.
4. Open the question in the feed. Check that the draft is restored.
5. Submit the answer. Check that the answered receipt appears.

**Paperclip version or commit**

Reproduced on master at `a386a599983519eb1d399f8b770bfccdb2a74762`.

**Deployment mode**

Browser UI in local and authenticated instances. This change does not
depend on the agent adapter.

Related work: Refs #14613, which added the Agent Chat feed behavior.
Refs #9141, which validates real answers on the server. Refs #11434,
which tracks comment-driven changes to interaction state. This PR
changes question presentation only.

## What Changed

- Show compact unanswered question entries in regular task chats.
- Exclude durable questions from composer pending counts and navigation.
- Save dismissal in local storage per person and task. Merge the latest
saved IDs so dismissals from another tab survive reload. A new question
can still open its form.
- Keep the original question pending and answerable. Keep approval and
permission controls.
- Run the question-history regressions in both chat modes. Add reload,
new-question, user/task scope, and stale-tab coverage.
- Share the real-component Storybook fixture. Add a regular task test
drive and an interactive dismissal/answer scenario.
- Update the planning-mode browser test to check a dismissed question in
the feed after reload and on mobile.
- Update the design rules, implementation spec, and preview
instructions.

## Verification

- 329 focused thread, composer, and interaction-card tests pass.
- `pnpm -r typecheck` passes. The UI typecheck also passes after the
review fix.
- `pnpm build` passes for the full repository.
- UI build, Storybook build, and token gates pass. The UI build and
token gates were rerun after the review fix.
- Greptile gives final commit `98f71f221` a 5/5 score. The current-head
check passes, and there are no unresolved review threads.
- All 56 current-head checks are terminal: 54 pass and two conditional
Storybook jobs skip. The CI run includes the full test shards, build,
typecheck, browser tests, aggregate verification gate, and package
canary.
- The stale-tab regression fails in both chat modes before the review
fix and passes after it.
- `pnpm exec playwright test --config tests/e2e/playwright.config.ts
tests/e2e/planning-mode-visual-verification.spec.ts` passes against a
throwaway local server. It checks dismissal, reload, task navigation,
and desktop/mobile planning controls.
- The duplicate local `pnpm test:run` attempt was stopped after the full
CI test suites passed. It did not complete locally.
- Manual browser test: select Green, dismiss, reload, reopen, submit the
saved answer, and inspect the answered receipt. Also send a new message
while the unanswered question remains in the feed. The test drive uses
real UI components with fixture response callbacks.
- To repeat the browser test, run `pnpm storybook`. Open **Chat &
Comments → Task Chat Unanswered Questions → Test Drive**.

## Risks

- Dismissal is a browser-local preference. It does not sync to another
browser or device. Clearing local storage removes it.
- When local storage is unavailable, dismissal lasts for the mounted
thread only.
- Unanswered questions can accumulate in the feed. They stay pending
until answered or resolved through the existing API.
- No database migration, API change, or change to approval permissions.

## Model Used

OpenAI Codex, `gpt-6.1-sol`, with xhigh reasoning, repository editing,
code execution, and browser control. The context-window size is not
exposed in this session.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-10-05 10:55:38 -05:00
1 parent a65ca09508
commit 59015846ae
10 files changed
+234 -101

No files matched your search

+5 -3
View File
@@ -72,8 +72,10 @@ rejection and revision remain available. Live tool reviews keep their own approv
Pending questions, confirmations, and other task-thread inputs appear in a separate
card directly above the ordinary composer. The composer stays available for new
messages while the card is open. Dismissing a card leaves a pending indicator that
can reopen it; resolving or skipping the input removes that indicator.
messages while the card is open. Questions use their compact history entry as the
reminder; dismissing one clears the composer and stays effective after reload for
that person and task. Other inputs keep a pending indicator that can reopen them;
resolving or skipping the input removes that indicator.
## Enforcement (what "compliant" means for the extraction run)
@@ -123,4 +125,4 @@ tokenize motion. Principles — reasoning only; values live in `ui/src/index.css
block collapses the duration/stagger tokens to zero, cascading to every scoped token,
in addition to each animation's own component-level guard.
Agent Chat keeps pending questions as compact “Unanswered question” entries at their original position in history. A newer user message dismisses the old question form without resolving it. Opening the history entry restores the original form and its draft; submitting later uses the same durable question response path. Actual permission reviews retain their permission checks.
Agent Chat and regular task chats keep pending questions as compact “Unanswered question” entries at their original position in history. Dismissing the form or sending a newer user message clears it from the composer without resolving it. Questions never contribute to composer pending counts or navigation. Opening the history entry restores the original form and its draft; submitting later uses the same durable question response path. Actual permission reviews retain their permission checks.
+6
View File
@@ -140,6 +140,12 @@ choices, item verdicts, suggested tasks, tool reviews, runtime questions, and ph
the bottom navigation. The normal message composer remains usable below the
pending card.
Use **Chat & Comments → Task Chat Unanswered Questions → Test Drive** to
try a regular task question: dismiss it, reload, reopen its compact feed entry,
and submit the preserved draft. The composer has no question pending badge.
The demo uses real thread/form components with fixture response callbacks.
The Agent Chat stories share the same component fixture.
Use **Composer → Model and effort picker** to review harness-specific model
choices. Codex uses the curated adapter catalog unless the instance declares
`PAPERCLIP_ADAPTER_MODELS`; general OpenAI API models are not Codex choices.
+7
View File
@@ -1502,6 +1502,13 @@ Required UX behaviors:
- conflict toasts on atomic checkout failure
- no silent background failures; every failed run visible in UI
Regular task chats and Agent Chat keep unanswered questions as compact,
reopenable entries at their original position in the feed. Dismissing a question
or sending a newer message clears its form from the composer without resolving
the saved question. Questions do not contribute to composer pending counts.
Dismissal persists locally for the person and task across reloads; reopening
restores the original form and draft. Approval and permission gates are unchanged.
## 15. Operational Requirements
## 15.1 Environment
@@ -9,25 +9,20 @@ import {
const AGENT_NAME = "CEO";
const TASK_TITLE = "Paperclip onboarding";
/**
* The first task opens with the chief of staff's opening card sitting where
* the composer is. Cancel hands the plain composer back (the card stays
* pending), and the composer is where the mode chip lives.
*
* The card arrives with the interactions fetch, after the composer's first
* paint, so a bare `count()` right after navigation sees no card and skips
* the click; the card then lands on top of the composer and hides the mode
* chip. Wait for the card (or, if it is already dismissed, the pending
* strip it leaves behind) before deciding, and only return once the plain
* composer is back.
*/
/** Wait for the saved question before checking its dismissed presentation. */
async function expectOpeningQuestionDismissed(page: import("@playwright/test").Page) {
await expect(page.getByTestId("task-chat-unanswered-question")).toBeVisible({ timeout: 30_000 });
await expect(page.getByTestId("task-chat-composer-takeover")).toHaveCount(0);
await expect(page.getByTestId("task-chat-pending-input-indicator")).toHaveCount(0);
await expect(page.getByTestId("task-chat-composer-mode")).toBeVisible({ timeout: 30_000 });
}
/** The opening question arrives after the interactions fetch. Dismiss it once. */
async function dismissOpeningCard(page: import("@playwright/test").Page) {
const takeover = page.getByTestId("task-chat-composer-takeover");
const pendingStrip = page.getByTestId("task-chat-pending-input-indicator");
await expect(takeover.or(pendingStrip).first()).toBeVisible({ timeout: 30_000 });
const cancel = takeover.getByRole("button", { name: "Cancel", exact: true });
if (await cancel.count()) await cancel.first().click();
await expect(page.getByTestId("task-chat-composer-mode")).toBeVisible({ timeout: 30_000 });
await expect(takeover).toBeVisible({ timeout: 30_000 });
await takeover.getByRole("button", { name: "Cancel", exact: true }).click();
await expectOpeningQuestionDismissed(page);
}
test("captures planning mode UI for desktop and mobile", async ({ page }) => {
@@ -155,6 +150,8 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => {
await page.goto(issuePath);
await dismissOpeningCard(page);
await page.reload();
await expectOpeningQuestionDismissed(page);
await expect(page.getByText("Plan mode").first()).toBeVisible();
const desktopPlanningToggle = page.getByTestId("task-chat-composer-mode");
await expect(desktopPlanningToggle).toBeVisible();
@@ -174,7 +171,7 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => {
});
await page.goto(issuePath);
await dismissOpeningCard(page);
await expectOpeningQuestionDismissed(page);
await page.getByTestId("task-chat-composer-mode").click();
await expect(page.getByTestId("task-chat-composer-mode")).toHaveCount(0);
await expect(page.getByTestId("task-chat-composer-add")).toBeVisible();
@@ -186,7 +183,7 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => {
await setMode("planning");
await page.setViewportSize({ width: 390, height: 844 });
await page.goto(issuePath);
await dismissOpeningCard(page);
await expectOpeningQuestionDismissed(page);
await expect(page.getByText("Plan mode").first()).toBeVisible();
const mobilePlanningToggle = page.getByTestId("task-chat-composer-mode");
await expect(mobilePlanningToggle).toBeVisible();
+50 -7
View File
@@ -2873,11 +2873,11 @@ describe("TaskChatThread runtime transcript selection", () => {
);
});
describe("Agent Chat unanswered question history", () => {
describe.each([true, false])("Unanswered question history (conversationMode=%s)", conversationMode => {
const old = questionInteraction("old", "Which color?", "2026-08-15T12:00:01Z");
const newer = questionInteraction("new", "Which tone?", "2026-08-15T12:05:00Z");
const movedOn = createLongThreadComments();
const props = { conversationMode: true, issueId: "issue-1", onAdd: async () => {}, onSubmitInteractionAnswers: vi.fn() };
const props = { conversationMode, issueId: "issue-1", currentUserId: "user-board", onAdd: async () => {}, onSubmitInteractionAnswers: vi.fn() };
const takeover = () => container.querySelector('[data-testid="task-chat-composer-takeover"]');
const pendingIndicator = () => container.querySelector<HTMLButtonElement>('[data-testid="task-chat-pending-input-indicator"]');
const dismiss = async () => {
@@ -2989,12 +2989,55 @@ describe("Agent Chat unanswered question history", () => {
expect(container.querySelector('[data-testid="task-chat-unanswered-question"]')).not.toBeNull();
});
it("does not change ordinary task question behavior", async () => {
render(<TaskChatThread {...props} conversationMode={false} comments={movedOn} interactions={[old]} />);
expect(takeover()?.textContent).toContain("Which color?");
expect(container.querySelector('[data-testid="task-chat-unanswered-question"]')).toBeNull();
it.each(["Cancel", "dismiss"])("keeps a fresh question dismissed after remounting (%s)", async action => {
const show = () => render(<TaskChatThread {...props} comments={[]} interactions={[old]} />);
show();
await click("Yes");
if (action === "Cancel") await click("Cancel");
else await dismiss();
flushSync(() => root!.unmount());
root = createRoot(container);
show();
expect(takeover()).toBeNull();
expect(pendingIndicator()).toBeNull();
await act(async () => container.querySelector<HTMLButtonElement>('[aria-label="Answer question: Which color?"]')!.click());
expect(takeover()?.querySelector('[role="radio"][aria-checked="true"]')?.textContent).toContain("Yes");
});
it("shows a newly asked question after dismissing an older one", async () => {
render(<TaskChatThread {...props} comments={[]} interactions={[old]} />);
await dismiss();
expect(pendingIndicator()?.textContent).toContain("1 pending input");
await act(async () => render(<TaskChatThread {...props} comments={[]} interactions={[old, newer]} />));
expect(takeover()?.textContent).toContain("Which tone?");
expect(takeover()?.textContent).not.toContain("Which color?");
expect(container.querySelectorAll('[data-testid="task-chat-unanswered-question"]')).toHaveLength(2);
});
it("preserves a question dismissal saved by another tab", async () => {
render(<TaskChatThread {...props} comments={[]} interactions={[old]} />);
// The other tab saves after this thread has loaded its dismissal state.
localStorage.setItem("paperclip:task-question-dismissals:user-board:issue-1", JSON.stringify([newer.id]));
await dismiss();
flushSync(() => root!.unmount());
root = createRoot(container);
render(<TaskChatThread {...props} comments={[]} interactions={[old, newer]} />);
expect(takeover()).toBeNull();
expect(pendingIndicator()).toBeNull();
expect(container.querySelectorAll('[data-testid="task-chat-unanswered-question"]')).toHaveLength(2);
});
it("scopes dismissal to the person and task", async () => {
const show = (userId: string, issueId: string) => render(<TaskChatThread {...props} currentUserId={userId} issueId={issueId} comments={[]} interactions={[old]} />);
show("user-board", "issue-1");
await dismiss();
flushSync(() => root!.unmount());
root = createRoot(container);
show("another-user", "issue-1");
expect(takeover()).not.toBeNull();
flushSync(() => root!.unmount());
root = createRoot(container);
show("user-board", "issue-2");
expect(takeover()).not.toBeNull();
});
});
+20 -12
View File
@@ -105,6 +105,7 @@ import { TaskChatQueuedMessages } from "@/components/task-chat/TaskChatQueuedMes
import { TaskChatWindowScroll } from "@/components/task-chat/useWindowAutoFollow";
import { useSidebar } from "@/context/SidebarContext";
import { useStreamlinedUiEnabled } from "@/hooks/useStreamlinedUiEnabled";
import { useDismissedTaskQuestions } from "@/hooks/useDismissedTaskQuestions";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
@@ -2475,11 +2476,12 @@ export function TaskChatThread(props: TaskChatThreadProps) {
}
return result;
}, [interactions, pendingRuntimeRequest]);
// Agent Chat questions already have an answerable history card, including
// Questions already have an answerable history card, including
// when the user dismisses a fresh form without sending another message.
const pendingReminderInputs = useMemo(() => pendingComposerInputs.filter(input =>
!(conversationMode && input.kind === "durable" && input.interaction.kind === "ask_user_questions")),
[pendingComposerInputs, conversationMode]);
!(input.kind === "durable" && input.interaction.kind === "ask_user_questions")),
[pendingComposerInputs]);
const { dismissedQuestionIds, dismissQuestion } = useDismissedTaskQuestions(issueId, currentUserId);
const latestUserComment = useMemo(() => comments
.filter(comment => !comment.deletedAt && comment.authorUserId && !comment.authorAgentId && !comment.createdByRunId)
.reduce<(typeof comments)[number] | null>((latest, comment) =>
@@ -2488,10 +2490,10 @@ export function TaskChatThread(props: TaskChatThreadProps) {
// A later message leaves a question answerable in history, without reopening
// its form on every render or reload. Explicit selection can still reopen it.
const currentPendingInputs = useMemo(() => pendingComposerInputs.filter(input =>
!(conversationMode && input.kind === "durable"
&& input.interaction.kind === "ask_user_questions" && latestUserComment
&& toMs(input.interaction.createdAt) < toMs(latestUserComment.createdAt))),
[pendingComposerInputs, conversationMode, latestUserComment]);
!(input.kind === "durable" && input.interaction.kind === "ask_user_questions"
&& (dismissedQuestionIds.has(input.interaction.id) || (latestUserComment
&& toMs(input.interaction.createdAt) < toMs(latestUserComment.createdAt))))),
[pendingComposerInputs, dismissedQuestionIds, latestUserComment]);
const currentPendingKeys = useMemo(() => new Set(currentPendingInputs.map(input => input.key)), [currentPendingInputs]);
const [takeoverMode, setTakeoverMode] = useState<"open" | "normal">("open");
const [selectedPendingKey, setSelectedPendingKey] = useState<string | null>(
@@ -2574,7 +2576,8 @@ export function TaskChatThread(props: TaskChatThreadProps) {
if (assigneeUsesPaperclipRunner) setRunnerSubmissionPending(true);
try {
await onAdd(...args);
if (conversationMode && selectedPendingInput?.kind === "durable" && selectedPendingInput.interaction.kind === "ask_user_questions") {
if (selectedPendingInput?.kind === "durable" && selectedPendingInput.interaction.kind === "ask_user_questions") {
dismissQuestion(selectedPendingInput.interaction.id);
setSelectedPendingKey(null);
setTakeoverMode("normal");
}
@@ -2583,7 +2586,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
throw error;
}
},
[assigneeUsesPaperclipRunner, onAdd, conversationMode, selectedPendingInput],
[assigneeUsesPaperclipRunner, onAdd, selectedPendingInput, dismissQuestion],
);
const optimisticRunnerStartup =
assigneeUsesPaperclipRunner &&
@@ -2670,7 +2673,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
<TaskChatInteractionCard
item={item}
onReviewRequest={reopenToolReview}
showUnansweredQuestion={conversationMode}
showUnansweredQuestion
planDocument={planDocument}
showPlanPreview={
!threadOwnsPlanPreview(
@@ -2711,7 +2714,6 @@ export function TaskChatThread(props: TaskChatThreadProps) {
settledRunIds,
tailRunId,
reopenToolReview,
conversationMode,
],
);
@@ -2770,7 +2772,13 @@ export function TaskChatThread(props: TaskChatThreadProps) {
Boolean(selectedPendingInput.interaction.payload.toolAction),
pendingCount: Math.max(1, pendingReminderInputs.length),
content: takeoverContent,
onDismiss: () => setTakeoverMode("normal"),
onDismiss: () => {
if (selectedPendingInput.kind === "durable" && selectedPendingInput.interaction.kind === "ask_user_questions") {
dismissQuestion(selectedPendingInput.interaction.id);
setSelectedPendingKey(null);
}
setTakeoverMode("normal");
},
onSkip: () => skipPendingInput(selectedPendingInput),
onShowNext: showNextPendingInput,
inlineSkip:
+30
View File
@@ -0,0 +1,30 @@
import { useCallback, useMemo, useState } from "react";
function loadDismissedQuestions(storageKey: string | null): Set<string> {
try {
const value: unknown = JSON.parse(storageKey ? localStorage.getItem(storageKey) ?? "[]" : "[]");
return new Set(Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : []);
} catch {
return new Set();
}
}
/** Presentation preference only: the original question remains answerable. */
export function useDismissedTaskQuestions(issueId?: string | null, userId?: string | null) {
const storageKey = issueId ? `paperclip:task-question-dismissals:${userId ?? "board"}:${issueId}` : null;
const [state, setState] = useState(() => ({ storageKey, ids: loadDismissedQuestions(storageKey) }));
const dismissedQuestionIds = useMemo(() => state.storageKey === storageKey
? state.ids : loadDismissedQuestions(storageKey), [state, storageKey]);
const dismissQuestion = useCallback((interactionId: string) => {
// Another tab may have saved more dismissals since this thread rendered.
const ids = new Set([...loadDismissedQuestions(storageKey), ...dismissedQuestionIds]);
ids.add(interactionId);
try {
if (storageKey) localStorage.setItem(storageKey, JSON.stringify([...ids]));
} catch {
// Keep dismissal effective for this mounted thread when storage is unavailable.
}
setState({ storageKey, ids });
}, [dismissedQuestionIds, storageKey]);
return { dismissedQuestionIds, dismissQuestion };
}
@@ -0,0 +1,61 @@
import { useState } from "react";
import type { AskUserQuestionsInteraction, IssueComment } from "@paperclipai/shared";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { queryKeys } from "@/lib/queryKeys";
import { TaskChatThread } from "@/components/TaskChatThread";
import { pendingAskUserQuestionsInteraction } from "@/fixtures/issueThreadInteractionFixtures";
import { storybookAgentMap } from "./paperclipData";
export const question: AskUserQuestionsInteraction = {
...pendingAskUserQuestionsInteraction,
id: "unanswered-color", title: "Welcome note preference", sourceRunId: "original-run",
createdAt: new Date("2026-04-01T12:01:00Z"),
payload: { version: 1, runtimeRequestId: "color-request", questions: [{ id: "color", prompt: "Which color should the welcome note use?",
selectionMode: "single", required: true, options: [{ id: "blue", label: "Blue" }, { id: "green", label: "Green" }] }] },
};
const otherQuestion: AskUserQuestionsInteraction = {
...question, id: "unanswered-tone", sourceRunId: "second-run", title: "Welcome note tone",
createdAt: new Date("2026-04-01T12:03:00Z"),
payload: { version: 1, questions: [{ id: "tone", prompt: "Which tone should the welcome note use?",
selectionMode: "single", required: true, options: [{ id: "friendly", label: "Friendly" }, { id: "formal", label: "Formal" }] }] },
};
function comment(id: string, body: string, at: string, agent = false): IssueComment {
return { id, companyId: question.companyId, issueId: question.issueId, body, authorType: agent ? "agent" : "user",
authorAgentId: agent ? question.createdByAgentId ?? null : null, authorUserId: agent ? null : "user-board",
presentation: null, metadata: null, createdAt: new Date(at), updatedAt: new Date(at) };
}
export function QuestionChat({ movedOn = false, multiple = false, answered = false, conversationMode = true }: { movedOn?: boolean; multiple?: boolean; answered?: boolean; conversationMode?: boolean }) {
const [queryClient] = useState(() => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
// This conversation has no plan. Keep the real thread's plan query local
// to the fixture rather than requesting an API from the static publisher.
client.setQueryData([...queryKeys.issues.documents(conversationMode ? question.issueId : "task-unanswered-questions-demo"), "plan"], null);
return client;
});
const [interactions, setInteractions] = useState<AskUserQuestionsInteraction[]>([
answered ? { ...question, status: "answered", resolvedAt: new Date("2026-04-01T12:06:00Z"), result: { version: 1, answers: [{ questionId: "color", optionIds: ["blue"] }] } } : question,
...(multiple ? [otherQuestion] : []),
]);
const [comments, setComments] = useState<IssueComment[]>([
comment("start", "Help me plan a welcome note for our garden club.", "2026-04-01T12:00:00Z"),
...(movedOn || multiple || answered ? [
comment("move-on", "Let's leave those choices for later. What can Paperclip tasks track?", "2026-04-01T12:04:00Z"),
comment("reply", "Tasks track ownership, progress, and the work needed to reach a goal.", "2026-04-01T12:05:00Z", true),
] : []),
...(answered ? [comment("late-answer", "Blue it is. I'll use that preference when we return to the welcome note.", "2026-04-01T12:07:00Z", true)] : []),
]);
return <QueryClientProvider client={queryClient}><div className="flex h-screen flex-col bg-background text-foreground">
<TaskChatThread conversationMode={conversationMode} comments={comments} interactions={interactions} issueId={conversationMode ? question.issueId : "task-unanswered-questions-demo"}
issueStatus="in_review" currentUserId="user-board" agentMap={storybookAgentMap} enableLiveTranscriptPolling={false}
threadHeader={<div className="p-4"><h1 className="text-xl font-semibold">{conversationMode ? "Garden club chat" : "Draft the garden club welcome note"}</h1><p className="text-sm text-muted-foreground">Questions can wait. Open an unanswered question in history whenever you're ready.</p></div>}
onAdd={async body => {
setComments(rows => [...rows, comment(`user-${rows.length}`, body, new Date().toISOString()),
comment(`agent-${rows.length}`, "We can come back to that question later. What would you like to work on next?", new Date(Date.now() + 1).toISOString(), true)]);
}}
onSubmitInteractionAnswers={async (interaction, answers) => {
setInteractions(rows => rows.map(row => row.id === interaction.id ? { ...row, status: "answered", resolvedAt: new Date(), result: { version: 1, answers } } : row));
setComments(rows => [...rows, comment(`answer-${rows.length}`, "Thanks, I've received your answer to the earlier question.", new Date().toISOString(), true)]);
}}
/>
</div></QueryClientProvider>;
}
@@ -1,68 +1,10 @@
import { useState } from "react";
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, userEvent, within, waitFor } from "storybook/test";
import type { AskUserQuestionsInteraction, IssueComment } from "@paperclipai/shared";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { queryKeys } from "@/lib/queryKeys";
import { TaskChatThread } from "@/components/TaskChatThread";
import { pendingAskUserQuestionsInteraction } from "@/fixtures/issueThreadInteractionFixtures";
import { storybookAgentMap } from "../fixtures/paperclipData";
import { QuestionChat, question } from "../fixtures/unansweredQuestionChat";
const question: AskUserQuestionsInteraction = {
...pendingAskUserQuestionsInteraction,
id: "unanswered-color", title: "Welcome note preference", sourceRunId: "original-run",
createdAt: new Date("2026-04-01T12:01:00Z"),
payload: { version: 1, runtimeRequestId: "color-request", questions: [{ id: "color", prompt: "Which color should the welcome note use?",
selectionMode: "single", required: true, options: [{ id: "blue", label: "Blue" }, { id: "green", label: "Green" }] }] },
};
const otherQuestion: AskUserQuestionsInteraction = {
...question, id: "unanswered-tone", sourceRunId: "second-run", title: "Welcome note tone",
createdAt: new Date("2026-04-01T12:03:00Z"),
payload: { version: 1, questions: [{ id: "tone", prompt: "Which tone should the welcome note use?",
selectionMode: "single", required: true, options: [{ id: "friendly", label: "Friendly" }, { id: "formal", label: "Formal" }] }] },
};
function comment(id: string, body: string, at: string, agent = false): IssueComment {
return { id, companyId: question.companyId, issueId: question.issueId, body, authorType: agent ? "agent" : "user",
authorAgentId: agent ? question.createdByAgentId ?? null : null, authorUserId: agent ? null : "user-board",
presentation: null, metadata: null, createdAt: new Date(at), updatedAt: new Date(at) };
}
function QuestionChat({ movedOn = false, multiple = false, answered = false }: { movedOn?: boolean; multiple?: boolean; answered?: boolean }) {
const [queryClient] = useState(() => {
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
// This conversation has no plan. Keep the real thread's plan query local
// to the fixture rather than requesting an API from the static publisher.
client.setQueryData([...queryKeys.issues.documents(question.issueId), "plan"], null);
return client;
});
const [interactions, setInteractions] = useState<AskUserQuestionsInteraction[]>([
answered ? { ...question, status: "answered", resolvedAt: new Date("2026-04-01T12:06:00Z"), result: { version: 1, answers: [{ questionId: "color", optionIds: ["blue"] }] } } : question,
...(multiple ? [otherQuestion] : []),
]);
const [comments, setComments] = useState<IssueComment[]>([
comment("start", "Help me plan a welcome note for our garden club.", "2026-04-01T12:00:00Z"),
...(movedOn || multiple || answered ? [
comment("move-on", "Let's leave those choices for later. What can Paperclip tasks track?", "2026-04-01T12:04:00Z"),
comment("reply", "Tasks track ownership, progress, and the work needed to reach a goal.", "2026-04-01T12:05:00Z", true),
] : []),
...(answered ? [comment("late-answer", "Blue it is. I'll use that preference when we return to the welcome note.", "2026-04-01T12:07:00Z", true)] : []),
]);
return <QueryClientProvider client={queryClient}><div className="flex h-screen flex-col bg-background text-foreground">
<TaskChatThread conversationMode comments={comments} interactions={interactions} issueId={question.issueId}
issueStatus="in_review" currentUserId="user-board" agentMap={storybookAgentMap} enableLiveTranscriptPolling={false}
threadHeader={<div className="p-4"><h1 className="text-xl font-semibold">Garden club chat</h1><p className="text-sm text-muted-foreground">Questions can wait. Open an unanswered question in history whenever you're ready.</p></div>}
onAdd={async body => {
setComments(rows => [...rows, comment(`user-${rows.length}`, body, new Date().toISOString()),
comment(`agent-${rows.length}`, "We can come back to that question later. What would you like to work on next?", new Date(Date.now() + 1).toISOString(), true)]);
}}
onSubmitInteractionAnswers={async (interaction, answers) => {
setInteractions(rows => rows.map(row => row.id === interaction.id ? { ...row, status: "answered", resolvedAt: new Date(), result: { version: 1, answers } } : row));
setComments(rows => [...rows, comment(`answer-${rows.length}`, "Thanks, I've received your answer to the earlier question.", new Date().toISOString(), true)]);
}}
/>
</div></QueryClientProvider>;
}
const meta = { title: "Chat & Comments/Agent Chat Unanswered Questions", parameters: { layout: "fullscreen" }, component: QuestionChat,
beforeEach: () => {
localStorage.removeItem(`paperclip:task-question-dismissals:user-board:${question.issueId}`);
for (const key of Object.keys(localStorage)) {
if (key.includes(`paperclip:task-input:${question.issueId}:`)) localStorage.removeItem(key);
}
@@ -0,0 +1,37 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, userEvent, within, waitFor } from "storybook/test";
import { QuestionChat } from "../fixtures/unansweredQuestionChat";
const meta = {
title: "Chat & Comments/Task Chat Unanswered Questions",
parameters: { layout: "fullscreen" },
component: QuestionChat,
args: { conversationMode: false },
} satisfies Meta<typeof QuestionChat>;
export default meta;
type Story = StoryObj<typeof meta>;
// Keep the test-drive story's dismissal preference across actual page reloads.
export const TestDrive: Story = {};
export const MovedOn: Story = { args: { movedOn: true } };
export const MultipleUnanswered: Story = { args: { multiple: true } };
export const AnsweredHistory: Story = { args: { answered: true } };
export const Mobile: Story = { args: { movedOn: true }, globals: { viewport: { value: "mobile", isRotated: false } } };
export const DismissAndAnswerLater: Story = {
beforeEach: () => {
localStorage.removeItem("paperclip:task-question-dismissals:user-board:task-unanswered-questions-demo");
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await waitFor(() => expect(canvas.getByRole("radio", { name: "Green" })).toBeVisible());
await userEvent.click(canvas.getByRole("radio", { name: "Green" }));
await userEvent.click(canvas.getByRole("button", { name: /^Dismiss / }));
await expect(canvas.getByTestId("task-chat-unanswered-question")).toBeVisible();
await expect(canvas.queryByTestId("task-chat-composer-takeover")).not.toBeInTheDocument();
await expect(canvas.queryByTestId("task-chat-pending-input-indicator")).not.toBeInTheDocument();
await userEvent.click(canvas.getByTestId("task-chat-unanswered-question"));
await expect(canvas.getByRole("radio", { name: "Green" })).toBeChecked();
await userEvent.click(canvas.getByRole("button", { name: /^(Send|Submit) answers$/ }));
await waitFor(() => expect(canvas.getByTestId("task-chat-answered-questions-receipt")).toBeVisible());
},
};