Files
PaperClipAI/tests/runner-e2e/chat-linked-question.ts
T
DottaandClaude Opus 5.5 e62fe18c72 fix(evals): wait for the primary save, select the offered Launch choice, and pace the keyboard reorder (#21396)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The chat eval catalog checks real chat journeys against saved
product state
> - Full cohort 12 (OpenCode with
`openrouter/deepseek/deepseek-v4.1-flash-1017`) failed three cases where
the agent did the correct thing
> - In each case the harness, not the product, broke the journey: it
left a page too early, could not answer a choice card, or pressed keys
faster than the drag library listens
> - A harness that breaks the journey cannot measure the product
> - This pull request makes the harness act like a person in these three
journeys, counts a verified card choice as a human action, and keeps
each check able to fail a broken product
> - The benefit is that these three cases measure the product again

## Linked Issues or Issue Description

**What happened?**
In full cohort 12, three cases failed for harness reasons:

- `agents.choose-primary`: the CEO answered correctly. The harness
clicked the crown and confirmed. Then it waited for "My primary agent"
with `.first()`. The sidebar already showed the CEO's crown, so this
wait passed at once. The harness then navigated away before the browser
sent `PUT /primary-agent/me`. The server log has no PUT. The read-back
still showed the CEO.
- `tasks.ambiguous-task`: the CEO changed nothing and asked a correct
question card. The card linked both tasks and offered "COM-1 (Launch
project)", "COM-2 (Experiments project)" and "Both tasks". The harness
could only answer with a text box or an "Other" option. It threw "The
linked question has no supported explicit clarification input".
- `steering.edit-queued-message`: the person's edit saved (PATCH 200).
The keyboard reorder (Space, ArrowUp, Space) sent no `PUT
/queued-comments/order` in 2 gestures. Cohort 9 had the same failure.

**Expected behavior**
Each journey completes as a person does it, and the oracle grades the
saved result.

**Steps to reproduce**

1. Use master `f7ddab8e94`.
2. Run the Runner Full-Stack E2E workflow with `all=false` and the three
case ids `chat-features.runner-opencode.local.<case>`.
3. Read each case's `playwright.log` and `server.log`.

**Additional context**
- Primary agent: the crown fills at once (optimistic update) and the
save starts on confirm. The mutation lives in the app-level
`PrimaryAgentProvider`, so in-app navigation does not cancel it. In the
failed run the confirm and the full-page `goto` happened within the same
second, and the PUT never reached the server. Only a full page load in
the first milliseconds can lose the save. A person cannot do that in
practice, so this is not a product bug. No UI change.
- Keyboard reorder: dnd-kit's `KeyboardSensor` starts the drag on Space,
adds its keydown listener in a `setTimeout`, and
`sortableKeyboardCoordinates` ignores arrows until the rows are measured
on a later render. Keys pressed back to back can arrive before this. In
the production Storybook story (headless Chromium), back-to-back
`locator.press` moved the item in 6 of 8 tries. Keys about 150 ms apart
moved it 5 of 5 times, also after an Edit and Save. With the drag-start
wait and a paint between keys it moved 16 of 16 times, also at 6x CPU
throttle. The keyboard reorder works for people, so this is not a
product bug. No UI change.

## What Changed

- `runtime-primary.ts`: wait for the browser's own `PUT
/primary-agent/me` that names Morgan, require 2xx, and poll the
read-back until Morgan is primary before leaving the page. Look for the
"My primary agent" crown only in the header that holds Morgan's avatar.
Add `isPrimarySaveRequest`. Oracle `runtime-primary.v6`.
- `chat-linked-question.ts` / `internal-tasks.ts`: add
`chosenTaskOption`. It finds the one option of the bound saved question
that names the Launch task's identifier (a setup literal) and no other
candidate's. It uses the option id for the rendered DOM id and the
payload's submit label. It does not read option wording. The harness
selects that option, checks `aria-checked`, submits, and waits for the
`respond` POST. The old text and "Other" paths stay for other cards. The
checks that nothing changes before the answer and that only COM-1
changes after it are unchanged.
- `chat-catalog-contract.ts` / `internal-tasks.ts`: a chosen option
saves no comment, so the flow counted only one human action and failed
`catalog-original-human-query`. `tasks.ambiguous-task` now joins the
cases that may count a bound UI answer. The case declares
`expectedHumanQuestionAnswer` only after the harness answered through
the choice, and names the chosen question and option. The flow then
verifies the answered card independently: answered by this person,
exactly the Launch option and no typed text, one audit event, and one
continuation run after it. Oracle `internal.ambiguous-task.v8`.
- `chat-catalog-contract.ts`: `chatCatalogHumanQuestionPolicies` takes
the answering person and mirrors the server's user rule in
`evaluateIssueThreadInteractionResolverAudience`. `anyone` and
`human_only` admit the person. `not_creator` admits a person who did not
create the card. With no resolver (a pending card) `not_creator` stays
rejected, so other callers keep their behavior. For the ambiguous-task
choice, an unaddressed card is accepted, as the server allows.
- `runtime-queue.ts`: `keyboardMoveQueuedMessageUp` waits for the
handle's `aria-pressed="true"` after Space. It lets the page paint
before ArrowUp and before the closing Space. It records whether each
gesture started a drag. Oracle `edit-queued-message.structural.v7`.
- No scenario YAML changed, so the TestOps manifest needs no entry.

## Verification

- `npx vitest run --config tests/runner-e2e/vitest.config.ts` for
`chat-linked-question.test.ts`, `chat-catalog-consistency.test.ts`,
`runtime-primary.test.ts`, `runtime-queue.test.ts`, `internal.test.ts`,
`external-company-secret.test.ts`, `external-personal-secret.test.ts`,
`turn-response-card.test.ts`, `runtime-task-coordination.test.ts`: pass.
- Red/green: the two new keyboard tests fail on the old
`keyboardMoveQueuedMessageUp` and pass on the new one. The
resolver-policy test fails on the old `chatCatalogHumanQuestionPolicies`
(`not_creator` answered by a person who is not the creator) and passes
on the new one; `not_creator` answered by its creator and a pending card
stay rejected. The choice-accounting test fails on the old allow list.
- `chosenTaskOption` tests use the cohort 12 card shape, a reworded
card, and cards with no single choice (both, duplicate, neither,
`COM-10`, a different card).
- `npx tsc -p tests/runner-e2e/tsconfig.json --noEmit`: pass. `node
--test tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs`: 10
pass.
- Paid narrow run 1 (commit `33399f8370`):
https://github.com/paperclipai/paperclip/actions/runs/43446445525.
`agents.choose-primary` passed (browser `PUT /primary-agent/me` 200).
`steering.edit-queued-message` passed (browser `PUT
/queued-comments/order` 200). `tasks.ambiguous-task` selected COM-1
(`respond` 200, only COM-1 became high) but failed
`catalog-original-human-query`, because the flow did not count the
choice. Later commits fix that.
- Paid narrow run 2 (`c90c2aa26a`) was cancelled by run 3 before its
case finished.
- Paid narrow run 3 (`tasks.ambiguous-task` only, final verifier
`fee3bbd453`):
https://github.com/paperclipai/paperclip/actions/runs/43452010284

## Risks

- Low risk. Test harness only.
- The ambiguous-task harness now answers through a structured choice
when one exists. If the agent asks a card with no option that names only
the Launch task, the old text and "Other" paths still apply.
- `chatCatalogHumanQuestionPolicies` accepts `not_creator` only when a
resolver is passed. Callers that check pending cards pass none, so their
behavior is unchanged.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use and code execution.

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 09:56:55 -06:00

133 lines
12 KiB
TypeScript

import { createHash } from "node:crypto";
import type { Locator, Page } from "@playwright/test";
import type { AskUserQuestionsInteraction } from "../../packages/shared/src/types/issue.js";
import type { ChatCatalogContext } from "./chat-catalog-contract.js";
import type { InternalObservation, Entity } from "./chat-catalog-domains/internal-support.js";
interface QuestionInput {
origin: string; pageUrl: string; companyPrefix: string; sourceId: string; leadId: string; query: string;
observation: InternalObservation & { runs: Array<InternalObservation["runs"][number] & { finishedAt?: string | null }> };
comments: Entity[]; interactions: AskUserQuestionsInteraction[]; tasks: Entity[];
}
export function linkedQuestionBinding(input: QuestionInput) {
const o = input.observation, run = o.runs[0];
if (o.runs.length !== 1 || !run || run.companyId !== o.companyId || run.agentId !== input.leadId || run.runtimeMode !== "native" || run.status !== "succeeded"
|| run.contextSnapshot?.issueId !== input.sourceId || input.tasks.length !== 2 || new Set(input.tasks.map(task => task.id)).size !== 2
|| input.tasks.some(task => task.companyId !== o.companyId || !o.tasks.some(saved => saved.id === task.id && saved.companyId === task.companyId))) return;
const humans = input.comments.filter(comment => comment.companyId === o.companyId && comment.issueId === input.sourceId && !comment.authorAgentId
&& !!comment.authorUserId && comment.body === input.query);
if (humans.length !== 1 || o.humanQueries.length !== 1 || o.humanQueries[0] !== input.query) return;
const human = humans[0]!, start = Date.parse(run.startedAt ?? ""), end = Date.parse(run.finishedAt ?? "");
if (!Number.isFinite(start) || !Number.isFinite(end)) return;
const candidates = input.interactions.filter(card => card.kind === "ask_user_questions" && card.status === "pending" && !card.dismissedAt && !card.resolvedAt
&& card.companyId === o.companyId && card.issueId === input.sourceId && card.createdByAgentId === input.leadId && !card.createdByUserId
&& card.sourceRunId === run.id && !card.addresseeAgentId && (!card.addresseeUserId || card.addresseeUserId === human.authorUserId)
&& ["anyone", "human_only", "not_creator"].includes(card.effectiveResolverPolicy)
&& (card.originCommentIds?.includes(human.id) || card.sourceCommentId === human.id)
&& (card.originCommentIds ?? []).every(id => input.comments.some(comment => comment.id === id && comment.companyId === o.companyId && comment.issueId === input.sourceId))
&& (!card.sourceCommentId || card.sourceCommentId === human.id)
&& Date.parse(String(card.createdAt)) >= start && Date.parse(String(card.createdAt)) <= end
&& o.activity.some(event => event.companyId === o.companyId && event.action === "issue.thread_interaction_created"
&& (event as Entity & { entityType?: string }).entityType === "issue" && event.entityId === input.sourceId
&& event.actorType === "agent" && event.actorId === input.leadId && event.agentId === input.leadId
&& (event as Entity & { runId?: string }).runId === run.id && event.details?.interactionId === card.id && event.details?.interactionKind === "ask_user_questions"));
if (candidates.length !== 1) return;
const card = candidates[0]!, set = card.payload.questionSet, question = set?.questions[0];
if (set?.schema !== "paperclip.question_set.v1" || !set.description || !question?.id || !question.prompt) return;
return { origin: input.origin, pageUrl: input.pageUrl, companyPrefix: input.companyPrefix, tasks: input.tasks.map(task => ({ id: task.id, identifier: task.identifier })), sourceId: input.sourceId, anchorCommentId: human.id, interactionId: card.id, questionId: question.id,
prompt: question.prompt, sourceRunId: run.id, leadId: input.leadId,
payloadDigest: createHash("sha256").update(JSON.stringify(card.payload)).digest("hex") };
}
export function readLinkedQuestionDom(input: NonNullable<ReturnType<typeof linkedQuestionBinding>>) {
const visible = (element: Element) => {
for (let node: Element | null = element; node; node = node.parentElement) {
if (node.hasAttribute("hidden") || node.hasAttribute("inert") || node.getAttribute("aria-hidden") === "true") return false;
const style = window.getComputedStyle(node);
if (style.display === "none" || ["hidden", "collapse"].includes(style.visibility) || style.opacity === "0") return false;
}
return element.getClientRects().length > 0;
};
const selector = '[data-testid="task-chat-thread"]', clean = (value: string) => value.replace(/\s+/g, " ").trim();
const roots = Array.from(document.querySelectorAll(selector)).filter(root => visible(root) && Array.from(root.querySelectorAll("[id]")).some(node =>
node.id === `comment-${input.anchorCommentId}` && node.closest(selector) === root));
if (roots.length !== 1) return;
const root = roots[0]!, same = (node: Element) => node.closest(selector) === root;
const button = Array.from(root.querySelectorAll('[data-testid="task-chat-unanswered-question"]')).filter(node =>
node.id === `interaction-${input.interactionId}` && same(node) && visible(node) && node.getAttribute("aria-label") === `Answer question: ${input.prompt}`);
if (button.length !== 1) return;
const takeovers = Array.from(root.querySelectorAll('[data-testid="task-chat-composer-takeover"]')).filter(node => visible(node) && same(node));
if (takeovers.length !== 1) return;
const takeover = takeovers[0]!, prompts = Array.from(takeover.querySelectorAll("[id]")).filter(node => node.id === `${input.interactionId}-${input.questionId}-prompt`
&& visible(node) && same(node) && clean(node.textContent ?? "") === clean(input.prompt));
const contexts = Array.from(takeover.querySelectorAll('[role="region"][aria-label="Question context"]')).filter(node => visible(node) && same(node));
if (prompts.length !== 1 || contexts.length !== 1) return;
const links = Array.from(contexts[0]!.querySelectorAll("a[href]")).filter(node => visible(node) && same(node)).map(node => node.getAttribute("href")!);
const qualified = links.flatMap(href => {
try {
const url = new URL(href, input.origin), page = new URL(input.pageUrl);
const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
const unprefixed = parts.length === 2 && parts[0] === "issues";
if (url.origin !== new URL(input.origin).origin || url.search || url.hash
|| !(parts.length === 3 && parts[0] === input.companyPrefix && parts[1] === "issues" || unprefixed
&& page.origin === url.origin && page.pathname.split("/").filter(Boolean)[0] === input.companyPrefix)) return [];
const id = parts[unprefixed ? 1 : 2], task = input.tasks.find(task => [task.id, task.identifier].includes(id));
return task ? [{ href, taskId: task.id }] : [];
} catch { return []; }
});
if (new Set(qualified.map(link => link.taskId)).size !== 2) return;
return { ...input, links: [...new Set(qualified.map(link => link.href))], text: prompts[0]!.textContent ?? "" };
}
export type LinkedQuestionEvidence = NonNullable<ReturnType<typeof readLinkedQuestionDom>>;
export type ClarificationObservation = InternalObservation & { linkedQuestionEvidence?: LinkedQuestionEvidence; questionCards?: AskUserQuestionsInteraction[] };
type Candidate = { id: string; identifier?: string | null };
type QuestionOption = { id?: string; label?: string; description?: string | null };
/** Whether an option's plain text names this candidate's identifier (a setup literal) and no other candidate's. */
function optionNamesOnly(option: QuestionOption, task: Candidate, tasks: readonly Candidate[]) {
const names = (text: string, row: Candidate) => !!row.identifier
&& new RegExp(`(?<![A-Za-z0-9-])${row.identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9])`, "i").test(text);
const text = `${option.label ?? ""}\n${option.description ?? ""}`;
return names(text, task) && tasks.every(other => other.id === task.id || !names(text, other));
}
/**
* The saved option of the bound question that offers exactly the chosen task, found by option structure and the
* task identifier, never by the option's wording. Returns nothing unless exactly one option offers that task alone.
*/
export function chosenTaskOption(cards: readonly AskUserQuestionsInteraction[], evidence: Pick<LinkedQuestionEvidence, "interactionId" | "questionId">,
chosen: Candidate, tasks: readonly Candidate[]) {
const card = cards.find(row => row.id === evidence.interactionId && row.kind === "ask_user_questions");
const set = card?.payload.questionSet, question = set?.questions.find(row => row.id === evidence.questionId);
if (!set || set.questions.length !== 1 || !question || question.answerMode !== "single_select" && question.answerMode !== "multi_select" || !tasks.some(task => task.id === chosen.id)) return;
const matches = (question.options ?? []).filter(option => !!option.id && optionNamesOnly(option, chosen, tasks));
if (matches.length !== 1) return;
return { optionId: matches[0]!.id, domId: `${evidence.interactionId}-${evidence.questionId}-${matches[0]!.id}`,
submitLabel: set.submitLabel ?? "Submit answers" };
}
/**
* Whether the run's saved question card offers each candidate task as its own choice. Option text is plain
* text inside a choice button, so it cannot carry links; a candidate counts when one option names its identifier
* (the setup literal) and no other candidate's. The option wording is left to human review.
*/
export function questionCardNamesCandidates(cards: readonly AskUserQuestionsInteraction[], tasks: ReadonlyArray<{ id: string; identifier?: string | null }>, runId: string | undefined, leadId: string) {
return !!runId && tasks.length > 1 && new Set(tasks.map(task => task.identifier)).size === tasks.length && cards.some(card => card.kind === "ask_user_questions"
&& card.status === "pending" && !card.dismissedAt && !card.resolvedAt && card.createdByAgentId === leadId && card.sourceRunId === runId
&& (card.payload.questionSet?.questions ?? card.payload.questions ?? []).some(question => tasks.every(task => (question.options ?? []).some(option => optionNamesOnly(option, task, tasks)))));
}
export async function observeLinkedTaskQuestion(ctx: ChatCatalogContext, state: Record<string, unknown>, observation: InternalObservation): Promise<ClarificationObservation> {
const source = ctx.issue(), prefix = ctx.input.fixtures.company.issuePrefix;
if (!source || !prefix || ctx.scenario.id !== "tasks.ambiguous-task") return observation;
const [comments, interactions] = await Promise.all([
ctx.input.api.get<Entity[]>(`/api/issues/${source.id}/comments?order=asc`),
ctx.input.api.get<AskUserQuestionsInteraction[]>(`/api/issues/${source.id}/interactions`),
]);
const binding = linkedQuestionBinding({ origin: observation.origin, pageUrl: ctx.input.page.url(), companyPrefix: prefix, sourceId: source.id, leadId: observation.leadId,
query: ctx.scenario.query, observation, comments, interactions, tasks: [state.task as Entity, state.otherTask as Entity] });
const questionCards = interactions.filter(card => card.kind === "ask_user_questions" && card.issueId === source.id);
if (!binding) return { ...observation, questionCards };
const evidence = await ctx.input.page.evaluate(readLinkedQuestionDom, binding);
return evidence ? { ...observation, reply: [observation.reply, evidence.text].filter(Boolean).join("\n"), links: [...new Set([...observation.links, ...evidence.links])], linkedQuestionEvidence: evidence, questionCards } : { ...observation, questionCards };
}
export function linkedQuestionTakeover(page: Page, evidence: LinkedQuestionEvidence): Locator {
return page.getByTestId("task-chat-thread").filter({ has: page.locator(`[id=${JSON.stringify(`comment-${evidence.anchorCommentId}`)}]`) })
.getByTestId("task-chat-composer-takeover").filter({ has: page.locator(`[id=${JSON.stringify(`${evidence.interactionId}-${evidence.questionId}-prompt`)}]`) });
}