Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
313 changes: 313 additions & 0 deletions dashboard/e2e/run-questions.spec.ts

Large diffs are not rendered by default.

39 changes: 36 additions & 3 deletions dashboard/src/app/runs/detail/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@
import { useConfirm } from "@/components/confirm-dialog";
import { Callout } from "@/components/callout";
import { InlineMarkdown, Markdown } from "@/components/markdown";
import { buttonClass, dangerButton, focusRing, primaryButton, secondaryButton } from "@/components/ui";
import { buttonClass, dangerButton, focusRing, fullWidthOnPhone, primaryButton, secondaryButton } from "@/components/ui";
import { Page, PageHeader, SectionHeading } from "@/components/page";
import { RunStatusBadge, runCanClose, runCloseIsLikely, runIsLive, runStatusLabel } from "@/components/run-status";
import { CloseRunDialog } from "@/components/close-run-dialog";
import { Chip, Time, formatDuration as sharedDuration, formatMs } from "@/components/list";
import { usePaletteActions, type PageAction } from "@/components/command-palette";
import type { CloseRunRequest } from "@/lib/api";
import { TeamAgentAsks } from "./team-asks";
import { RunAnswered, RunQuestions } from "./run-questions";
import { AsksHistory, WaitingOnYou, useRunApprovals } from "./agent-asks";
import { WorkUsedLine } from "@/components/work-used";
import { HelpLink } from "@/components/support";
Expand Down Expand Up @@ -443,7 +444,7 @@
if (idx > max) max = idx;
});
return max;
}, [run?.current_pass, run?.pass_history]);

Check warning on line 447 in dashboard/src/app/runs/detail/page.tsx

View workflow job for this annotation

GitHub Actions / Lint & Build

React Hook useMemo has a missing dependency: 'run'. Either include it or remove the dependency array

if (!runId) {
return (
Expand Down Expand Up @@ -690,7 +691,8 @@
</OutcomeCard>
);
} else {
const look: { tone: OutcomeTone; title: string; body: React.ReactNode; actions?: React.ReactNode } =
// `body` is one sentence; `content` is a block of its own (a form, a list).
const look: { tone: OutcomeTone; title: string; body: React.ReactNode; content?: React.ReactNode; actions?: React.ReactNode } =
run.status === "merged"
? { tone: "success", title: "Done. The change was merged.", body: "The pull request is merged, so the change is in.", actions: openPrButtons("secondary") }
: done
Expand All @@ -707,13 +709,43 @@
}
: run.status === "awaiting_ci"
? { tone: "waiting", title: "Waiting for the automated checks", body: "The change is ready. Coderhelm fixes the checks if they fail, then hands it over for review.", actions: openPrButtons("secondary") }
: run.status === "needs_input"
: run.status === "needs_input" && run.questions?.length
? {
tone: "waiting",
title: "Coderhelm needs your answer",
body: null,
content: (
<RunQuestions
run={run}
canAnswer={canAct}
limitTitle={limitTitle}
retry={
canAct && canRetry ? (
<button type="button" onClick={retry} disabled={busy !== null || tokensExceeded} title={limitTitle} className={`${secondaryButton} ${fullWidthOnPhone}`}>
{busy === "retry" ? "Starting…" : "Retry"}
</button>
) : undefined
}
onAnswered={fetchRun}
/>
),
actions: undefined,
}
: run.status === "needs_input"
? {
tone: "waiting",
title: "Coderhelm needs more detail",
body: run.error ? <span className="whitespace-pre-wrap [overflow-wrap:anywhere]">{sanitizeError(run.error)}</span> : "Add the missing detail to the ticket, then retry.",
actions: retryButton,
}
: run.status === "retried" && run.answers?.length
? {
tone: "neutral",
title: "Answered. Coderhelm is continuing in a new run.",
body: null,
content: <RunAnswered run={run} />,
actions: undefined,
}
: run.status === "needs_outside_change"
? { tone: "attention", title: "The fix is a change outside the code", body: "The code works as designed. What to change, and where, is below.", actions: undefined }
: run.status === "cancelled"
Expand All @@ -734,6 +766,7 @@
outcome = (
<OutcomeCard tone={look.tone} title={look.title} testId="run-outcome" actions={look.actions}>
{look.body && <p>{look.body}</p>}
{look.content}
</OutcomeCard>
);
}
Expand Down
222 changes: 222 additions & 0 deletions dashboard/src/app/runs/detail/run-questions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
"use client";

import { useId, useRef, useState } from "react";
import Link from "next/link";
import { api, ApiError, type RunAnswer, type RunDetail, type RunQuestion } from "@/lib/api";
import { buttonClass, fullWidthOnPhone, inputClass, linkButton, primaryButton } from "@/components/ui";
import { ExternalLinkIcon } from "@/components/icons";
import { Time } from "@/components/list";
import { useToast } from "@/components/toast";

// A run that stopped to ask: its questions in plain words, each with why it
// matters, and (for people who may start runs) one answer box per question.
// Sending posts the answers on the ticket as a reply from the person and
// starts the work again with them; the gateway refuses a run that moved on.

/** The longest answer the gateway takes. */
const MAX_ANSWER = 4000;

function ticketWord(source?: string) {
return source === "jira" ? "Jira ticket" : "issue";
}

function TicketLink({ href, children }: { href: string; children: React.ReactNode }) {
return (
<a href={href} target="_blank" rel="noopener noreferrer" className={`${linkButton} gap-1`}>
{children}
<ExternalLinkIcon />
<span className="sr-only"> (opens in a new tab)</span>
</a>
);
}

/** Words for a failed send. The gateway's own sentence when it sent one. */
function sendError(e: unknown): string {
if (e instanceof ApiError) {
if (e.status === 403) return "Only members can answer a run's questions. Ask an admin for member access.";
if (e.status === 429) return "The monthly token limit is reached, so no new work can start.";
if (e.message && e.status !== 500) return e.message;
}
return "Your answer wasn't sent. Try again in a moment.";
}

export function RunQuestions({
run,
canAnswer,
limitTitle,
retry,
onAnswered,
}: {
run: RunDetail;
/** The person may start runs (member and up) and no limit is reached. */
canAnswer: boolean;
/** Why sending is off, when a monthly limit is reached. */
limitTitle?: string;
/** The Retry button, for a ticket edited directly. */
retry?: React.ReactNode;
/** After sending, or when the run moved on: read the run again. */
onAnswered: () => void;
}) {
const questions: RunQuestion[] = run.questions ?? [];
const [answers, setAnswers] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const firstBox = useRef<HTMLTextAreaElement>(null);
const errorId = useId();
const { toast } = useToast();
const many = questions.length > 1;
const where = ticketWord(run.ticket_source);
const written = questions.filter((q) => (answers[q.id] ?? "").trim());

const send = async (e: React.FormEvent) => {
e.preventDefault();
if (!written.length) {
setError(many ? "Write an answer to at least one question." : "Write your answer first.");
firstBox.current?.focus();
return;
}
setBusy(true);
setError(null);
try {
const r = await api.answerRun(
run.run_id,
written.map((q) => ({ question_id: q.id, answer: answers[q.id].trim() })),
);
toast(
r.posted
? `Sent. Your answer is on the ${where} and Coderhelm is continuing.`
: `Coderhelm is continuing with your answer. It couldn't post it on the ${where}.`,
);
onAnswered();
} catch (err) {
if (err instanceof ApiError && err.status === 409) {
toast(err.message, "error");
onAnswered();
} else {
setError(sendError(err));
}
} finally {
setBusy(false);
}
};

return (
<form onSubmit={send} noValidate aria-label="Coderhelm's questions" className="space-y-3 pt-1" data-testid="run-questions">
<p>
{many ? `It stopped to ask ${questions.length} questions.` : "It stopped to ask one question."}{" "}
{canAnswer ? "Answer here and it carries on." : `Ask someone with member access to answer here, or reply on the ${where}.`}
</p>
<ol className="space-y-3">
{questions.map((q, i) => {
const boxId = `answer-${run.run_id}-${q.id}`;
return (
<li key={q.id} data-testid="run-question" className="min-w-0 rounded-lg border border-zinc-800 bg-zinc-950/40 p-3">
<p className="font-medium text-zinc-100 [overflow-wrap:anywhere]">
{many && <span className="tabular-nums text-zinc-400">{i + 1}. </span>}
{q.question}
</p>
{q.why && <p className="mt-1 text-zinc-400 [overflow-wrap:anywhere]" data-testid="run-question-why">{q.why}</p>}
{canAnswer && (
<div className="mt-3">
<label htmlFor={boxId} className="mb-1 block text-sm font-medium text-zinc-200">
{many ? `Your answer to question ${i + 1}` : "Your answer"}
</label>
{!!q.suggestions?.length && (
<div
className="mb-2 flex flex-wrap items-center gap-2"
aria-label={q.decision ? "Choices" : "Possible answers Coderhelm found"}
role="group"
>
<span className="text-xs text-zinc-400">{q.decision ? "Choose:" : "Possible answers:"}</span>
{q.suggestions.map((s) => (
<button
key={s}
type="button"
onClick={() => {
setAnswers((a) => ({ ...a, [q.id]: s }));
setError(null);
}}
aria-pressed={answers[q.id] === s}
className={`${buttonClass(q.decision && answers[q.id] === s ? "primary" : "secondary", "sm")}`}
>
{s}
</button>
))}
</div>
)}
<textarea
id={boxId}
ref={i === 0 ? firstBox : undefined}
rows={3}
maxLength={MAX_ANSWER}
value={answers[q.id] ?? ""}
onChange={(e) => {
setAnswers((a) => ({ ...a, [q.id]: e.target.value }));
if (error) setError(null);
}}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) e.currentTarget.form?.requestSubmit();
}}
aria-describedby={error ? errorId : undefined}
aria-invalid={error && !written.length ? true : undefined}
disabled={busy}
placeholder={many ? "Leave blank if you don't know" : "Type your answer"}
className={`${inputClass} min-h-20 resize-y`}
/>
</div>
)}
</li>
);
})}
</ol>
{error && (
<p id={errorId} role="alert" className="text-sm text-red-400">
{error}
</p>
)}
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
{canAnswer && (
<button type="submit" disabled={busy || !!limitTitle} title={limitTitle} className={`${primaryButton} ${fullWidthOnPhone}`}>
{busy ? "Sending…" : many ? "Send answers and continue" : "Send answer and continue"}
</button>
)}
{retry}
{run.questions_url && <TicketLink href={run.questions_url}>See it on the ticket</TicketLink>}
</div>
{canAnswer && (
<p className="text-xs text-zinc-400">
Your answer is posted on the {where} as a reply from you. Changed the {where} instead? Retry reads it again.
</p>
)}
</form>
);
}

/** A run whose questions were answered here: what was asked and answered, and where the work went on. */
export function RunAnswered({ run }: { run: RunDetail }) {
const answers: RunAnswer[] = run.answers ?? [];
return (
<div className="space-y-3 pt-1" data-testid="run-answered">
<dl className="space-y-3">
{answers.map((a) => (
<div key={a.question_id} className="min-w-0 rounded-lg border border-zinc-800 bg-zinc-950/40 p-3">
<dt className="text-zinc-400 [overflow-wrap:anywhere]">{a.question}</dt>
<dd className="mt-1 whitespace-pre-wrap text-zinc-100 [overflow-wrap:anywhere]">{a.answer}</dd>
<dd className="mt-1 text-xs text-zinc-400">
{a.author || "A teammate"}
{a.answered_at ? <> · <Time iso={a.answered_at} /></> : null}
</dd>
</div>
))}
</dl>
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
{run.continued_run_id && (
<Link href={`/runs/detail?id=${encodeURIComponent(run.continued_run_id)}`} className={`${primaryButton} ${fullWidthOnPhone}`}>
Open the run that continued
</Link>
)}
{run.answers_url && <TicketLink href={run.answers_url}>See the reply on the ticket</TicketLink>}
</div>
</div>
);
}
6 changes: 5 additions & 1 deletion dashboard/src/lib/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// Nothing here runs; it is checked by the compiler only.

import type { OpenApiFields } from "./openapi-fields";
import type { Plan, Run, RunDetail, Task, api } from "./api";
import type { AnswerRunResult, Plan, Run, RunAnswer, RunDetail, RunQuestion, Task, api } from "./api";

type Answer<K extends keyof typeof api> = Awaited<ReturnType<(typeof api)[K]>>;

Expand All @@ -20,6 +20,10 @@ type None<T extends never> = T;
export type RunsPageContract = None<Undocumented<Answer<"listRuns">, "RunsPage">>;
export type RunListContract = None<Undocumented<Run, "RunSummary">>;
export type RunContract = None<Undocumented<RunDetail, "Run">>;
// What a run asked, the answers given in Coderhelm, and answering.
export type RunQuestionContract = None<Undocumented<RunQuestion, "RunQuestion">>;
export type RunAnswerContract = None<Undocumented<RunAnswer, "RunAnswer">>;
export type AnswerRunContract = None<Undocumented<AnswerRunResult, "AnswerRunResult">>;

// Plans and their tasks (the plan pages and the runs they start).
export type PlansPageContract = None<Undocumented<Answer<"listPlans">, "PlansPage">>;
Expand Down
47 changes: 47 additions & 0 deletions dashboard/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,11 @@ export const api = {
}>(`/api/runs/${id}/agent-log`),
retryRun: (id: string) =>
request<{ status: string }>(`/api/runs/${id}/retry`, { method: "POST" }),
answerRun: (id: string, answers: { question_id: string; answer: string }[]) =>
request<AnswerRunResult>(`/api/runs/${id}/answer`, {
method: "POST",
body: JSON.stringify({ answers }),
}),
resetRun: (id: string) =>
request<{ status: string }>(`/api/runs/${id}/reset`, { method: "POST" }),
reReviewRun: (id: string) =>
Expand Down Expand Up @@ -1824,6 +1829,48 @@ export interface RunDetail extends Run {
close_reason?: string | null;
/** The status it had when it was closed. */
closed_from?: string | null;
/** What the run asked when it stopped to wait on a person (`needs_input`). */
questions?: RunQuestion[];
/** The comment with those questions on the ticket or issue. */
questions_url?: string | null;
/** Answers people gave to them in Coderhelm. */
answers?: RunAnswer[];
/** The reply with the answers on the ticket or issue. */
answers_url?: string | null;
/** The run that picked the answers up. */
continued_run_id?: string | null;
}

/** A question a run asked a person. */
export interface RunQuestion {
id: string;
question: string;
/** Why it matters: what it blocks. */
why?: string | null;
/** Candidate answers the run found in the code or the data; the choices when `decision` is set. */
suggestions?: string[];
/** Set when the question is a choice Coderhelm records on the ticket (e.g. an open pull request: work on it, or open its own). */
decision?: string | null;
}

/** An answer given in Coderhelm to a run's question. */
export interface RunAnswer {
question_id: string;
question: string;
answer: string;
/** Who answered, as the ticket shows them. */
author: string;
answered_at: string;
}

/** What answering a run's questions did. */
export interface AnswerRunResult {
status: string;
/** The run that continues the work. */
run_id: string;
/** Whether the answers were posted on the ticket or issue. */
posted: boolean;
comment_url?: string | null;
}

export interface PassTrace {
Expand Down
Loading
Loading