Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(questions): persist ask_user_question and render QuestionCard inline

Yuting Zhong17375869b923
diff --git a/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
index 8b0b69db..78b88e6b 100644
--- a/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
@@ -4,6 +4,7 @@ import { AgentTaskWorkspace } from "@/components/agent-task-workspace";
import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
import { listApprovalsForTask } from "@/server/db/approvals";
+import { listQuestionsForTask } from "@/server/db/questions";
import { getTask, listTasksByAgent, setTaskThreadIfMissing } from "@/server/db/tasks";
import { buildPendingSessionKey, findSessionBySessionId } from "@/server/openclaw/sessions";
import {
@@ -14,7 +15,7 @@ import {
buildTaskKickoffMessage,
generateTaskThreadId,
} from "@/server/orchestration/task-kickoff";
-import type { Approval, Task } from "@/types";
+import type { Approval, Question, Task } from "@/types";
type Props = {
params: Promise<{ agent: string; project: string }>;
@@ -34,6 +35,13 @@ type SelectedBundle = {
* the audit trail for "what did I approve here?".
*/
approvals: Approval[];
+ /**
+ * Every question ever raised on this task via `ask_user_question`,
+ * newest first. The chat view renders the pending one inline so the
+ * user can answer without leaving the task; resolved rows stay as the
+ * audit trail.
+ */
+ questions: Question[];
/**
* Auto-kickoff payload for tasks that haven't started yet. The page
* builds the full assignment brief server-side so the client can just
@@ -110,6 +118,7 @@ async function loadSelectedBundle(
const { events, byteOffset } = readTranscriptTail(agentFullId, threadId, 0);
const approvals = listApprovalsForTask(task.id);
+ const questions = listQuestionsForTask(task.id);
// Only minted for `proposed` tasks. The client uses this to fire the
// first turn via /api/chat (which streams gateway events live), and
@@ -127,6 +136,7 @@ async function loadSelectedBundle(
initialEvents: events,
initialByteOffset: byteOffset,
approvals,
+ questions,
kickoff,
};
}
diff --git a/src/components/agent-task-workspace.test.tsx b/src/components/agent-task-workspace.test.tsx
index fd5478c5..ff0a9146 100644
--- a/src/components/agent-task-workspace.test.tsx
+++ b/src/components/agent-task-workspace.test.tsx
@@ -263,7 +263,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "agent:demo-google-ads:thr-1",
initialEvents: [],
- initialByteOffset: 0, approvals: [], kickoff: null,
+ initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
},
})}
/>,
@@ -287,7 +287,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "agent:demo-google-ads:thr-1",
initialEvents: [],
- initialByteOffset: 0, approvals: [], kickoff: null,
+ initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
},
})}
/>,
@@ -310,7 +310,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "k",
initialEvents: [],
- initialByteOffset: 0, approvals: [], kickoff: null,
+ initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
},
})}
/>,
@@ -331,7 +331,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "k",
initialEvents: [],
- initialByteOffset: 0, approvals: [], kickoff: null,
+ initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
},
})}
/>,
@@ -352,7 +352,7 @@ describe("AgentTaskWorkspace CancelTaskButton", () => {
threadId: "thr",
sessionKey: "k",
initialEvents: [],
- initialByteOffset: 0, approvals: [], kickoff: null,
+ initialByteOffset: 0, approvals: [], questions: [], kickoff: null,
},
})}
/>,
diff --git a/src/components/agent-task-workspace.tsx b/src/components/agent-task-workspace.tsx
index 184914f9..bb619075 100644
--- a/src/components/agent-task-workspace.tsx
+++ b/src/components/agent-task-workspace.tsx
@@ -13,6 +13,7 @@ import {
import { toast } from "sonner";
import { ApprovalCard } from "@/components/approval-card";
+import { QuestionCard } from "@/components/question-card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { LiveTranscript } from "@/components/live-transcript";
@@ -23,10 +24,18 @@ import { cancelTaskAction } from "@/server/actions/tasks";
import { cn } from "@/lib/utils";
import { projectHref } from "@/lib/project-href";
import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
-import type { Approval, Task, TaskStatus } from "@/types";
+import type { Approval, Question, Task, TaskStatus } from "@/types";
const TASK_IN_FLIGHT: TaskStatus[] = ["proposed", "approved", "working", "blocked"];
+// Composer is locked only while the agent is actively running. `blocked`
+// is dormant by design (waiting on approval or an upstream task) — the
+// user must be able to type into it to give context, answer a question
+// the agent posed, or steer the next attempt. Approve/Deny on the
+// ApprovalCard remains the canonical way to resolve the block; the
+// composer is a parallel channel for free-form direction.
+const COMPOSER_LOCKED: TaskStatus[] = ["proposed", "approved", "working"];
+
// `blocked` covers two distinct reasons: waiting on an approval, or
// waiting on another task to finish. The section header stays generic
// ("Blocked") and each row's subline spells out the actual reason —
@@ -64,6 +73,9 @@ type SelectedTaskBundle = {
/** Approvals attached to this task, newest first. Rendered above the
* transcript so the user can act on a pending one without leaving the chat. */
approvals: Approval[];
+ /** Questions attached to this task, newest first. Pending ones render
+ * as a QuestionCard above the transcript. */
+ questions: Question[];
/**
* Set when this task is still in `proposed` and the workspace should
* auto-fire the kickoff via /api/chat on mount. Null once the task has
@@ -293,6 +305,7 @@ function SelectedTaskPanel({
}) {
const router = useRouter();
const isInFlight = TASK_IN_FLIGHT.includes(selected.task.status);
+ const composerLocked = COMPOSER_LOCKED.includes(selected.task.status);
// We refresh the server tree on every in-flight poll so the status
// badge + sidebar in-flight counters track the DB even when nothing
// has landed in the JSONL transcript yet.
@@ -327,10 +340,14 @@ function SelectedTaskPanel({
const liveApprovals = selected.approvals.filter(
(a) => a.status === "pending" || a.status === "revision_requested",
);
+ const openQuestions = selected.questions.filter(
+ (q) => q.status === "pending",
+ );
// When the task is parked in `blocked`, build a short "why" string so
// the LiveTranscript can replace its forward-motion indicator
// ("thinking…", "wrapping up…") with an honest paused-state pill.
- // Two distinct reasons: (a) approval pending (b) gated on another task.
+ // Three distinct reasons: (a) question pending (b) approval pending
+ // (c) gated on another task.
let blockedReason: string | undefined;
if (selected.task.status === "blocked") {
if (selected.task.blocked_by_task_id) {
@@ -338,6 +355,11 @@ function SelectedTaskPanel({
blockedReason = blocker
? `waiting on ${blocker.display_id.toUpperCase()}`
: "waiting on an upstream task";
+ } else if (openQuestions.length > 0) {
+ blockedReason =
+ openQuestions.length === 1
+ ? "waiting on your answer"
+ : `waiting on ${openQuestions.length} answers`;
} else if (liveApprovals.length > 0) {
blockedReason =
liveApprovals.length === 1
@@ -349,8 +371,15 @@ function SelectedTaskPanel({
}
return (
<div className="flex h-full min-h-0 flex-col">
- {liveApprovals.length > 0 && (
+ {(openQuestions.length > 0 || liveApprovals.length > 0) && (
<div className="mx-auto w-full max-w-3xl space-y-3 px-6 pt-4">
+ {openQuestions.map((q) => (
+ <QuestionCard
+ key={q.id}
+ question={q}
+ options={parseOptionsJson(q.options_json)}
+ />
+ ))}
{liveApprovals.map((a) => (
<ApprovalCard key={a.id} approval={a} />
))}
@@ -366,7 +395,7 @@ function SelectedTaskPanel({
sessionKey={selected.sessionKey}
initialEvents={selected.initialEvents}
initialByteOffset={selected.initialByteOffset}
- composerDisabled={isInFlight}
+ composerDisabled={composerLocked}
blockedReason={blockedReason}
onPolled={onPolled}
autoKickoff={selected.kickoff !== null}
@@ -541,6 +570,21 @@ function EmptyRightPane({
);
}
+/** Parse Question.options_json into a string[] in a client-safe way.
+ * Mirrors @/server/db/questions#parseQuestionOptions but avoids importing
+ * the server module from a client component. */
+function parseOptionsJson(json: string): string[] {
+ try {
+ const parsed = JSON.parse(json);
+ if (Array.isArray(parsed) && parsed.every((x) => typeof x === "string")) {
+ return parsed;
+ }
+ } catch {
+ // fall through
+ }
+ return [];
+}
+
function formatRelative(iso: string): string {
const t = Date.parse(iso);
if (!Number.isFinite(t)) return "";
diff --git a/src/components/live-transcript.test.tsx b/src/components/live-transcript.test.tsx
index b01e92ad..2ada6db2 100644
--- a/src/components/live-transcript.test.tsx
+++ b/src/components/live-transcript.test.tsx
@@ -252,6 +252,24 @@ describe("LiveTranscript composer", () => {
expect(textarea.placeholder).toMatch(/CMO is on a task/i);
});
+ it("keeps the composer enabled when the task is blocked and surfaces the paused pill + helper placeholder", () => {
+ render(
+ <LiveTranscript
+ {...defaultProps({
+ composerDisabled: false,
+ blockedReason: "waiting on approval",
+ threadId: "t-blocked",
+ })}
+ />,
+ );
+ const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;
+ expect(textarea).not.toBeDisabled();
+ expect(textarea.placeholder).toMatch(/Reply to CMO/i);
+ // BlockedStatus pill replaces the live working indicator.
+ expect(screen.getByText(/Paused — waiting on approval/)).toBeInTheDocument();
+ expect(screen.queryByText(/^Starting$/)).not.toBeInTheDocument();
+ });
+
it("submitting Shift+Enter inserts a newline and does NOT send", () => {
render(<LiveTranscript {...defaultProps({ threadId: "t-shift" })} />);
const textarea = screen.getByRole("textbox");
diff --git a/src/components/live-transcript.tsx b/src/components/live-transcript.tsx
index 4c664b43..5993515e 100644
--- a/src/components/live-transcript.tsx
+++ b/src/components/live-transcript.tsx
@@ -582,11 +582,15 @@ export function LiveTranscript({
// so the user sees the same anchor whether the agent is mid-call,
// mid-stream, or waiting on the next model token.
//
+ // For `blocked` tasks the composer is enabled (so the user can answer
+ // a question or interject) but the agent is still dormant — render
+ // the BlockedStatus pill so the chat doesn't read as live.
+ //
// (Earlier we hid the indicator once anything pending was rendered.
// That made the chat read as "stuck" the moment streaming started —
// there was no longer any active animation to telegraph "I'm still
// working.")
- const showThinking = sendingChat || composerDisabled;
+ const showThinking = sendingChat || composerDisabled || Boolean(blockedReason);
return (
<div className="flex h-full flex-col">
@@ -601,7 +605,8 @@ export function LiveTranscript({
{rendered.length === 0 &&
!pendingUserMsg &&
!sendingChat &&
- !composerDisabled ? (
+ !composerDisabled &&
+ !blockedReason ? (
<TranscriptEmptyState agentDisplayName={agentDisplayName} />
) : (
<ol className="space-y-4">
@@ -713,7 +718,9 @@ export function LiveTranscript({
placeholder={
composerDisabled
? `${agentDisplayName} is on a task — the transcript updates live`
- : `Message ${agentDisplayName}… (type / for commands)`
+ : blockedReason
+ ? `Reply to ${agentDisplayName} — typing won't resolve the block, but the agent will see your message`
+ : `Message ${agentDisplayName}… (type / for commands)`
}
rows={1}
className="flex min-h-[40px] flex-1 resize-none rounded-xl border bg-background px-3.5 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
@@ -1146,7 +1153,8 @@ function BlockedStatus({ reason }: { reason: string }) {
</div>
<div className="mt-0.5 text-[11px] text-amber-700/80 dark:text-amber-300/70">
The agent will resume automatically when the gating condition
- resolves.
+ resolves. You can also reply below to give context or answer a
+ question.
</div>
</div>
</div>
diff --git a/src/components/question-card.test.tsx b/src/components/question-card.test.tsx
new file mode 100644
index 00000000..1f469ca1
--- /dev/null
+++ b/src/components/question-card.test.tsx
@@ -0,0 +1,199 @@
+// @vitest-environment jsdom
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+
+const answerMock = vi.fn();
+const cancelMock = vi.fn();
+const toastSuccessMock = vi.fn();
+const toastErrorMock = vi.fn();
+const toastInfoMock = vi.fn();
+
+vi.mock("@/server/actions/questions", () => ({
+ answerQuestionAction: (...a: unknown[]) => answerMock(...a),
+ cancelQuestionAction: (...a: unknown[]) => cancelMock(...a),
+}));
+
+vi.mock("sonner", () => ({
+ toast: {
+ success: (...a: unknown[]) => toastSuccessMock(...a),
+ error: (...a: unknown[]) => toastErrorMock(...a),
+ info: (...a: unknown[]) => toastInfoMock(...a),
+ },
+}));
+
+import { QuestionCard } from "./question-card";
+import type { Question } from "@/types";
+
+function makeQuestion(overrides: Partial<Question> = {}): Question {
+ return {
+ id: "q-1",
+ project_slug: "demo",
+ agent_id: "demo-cmo",
+ task_id: "t-1",
+ prompt: "Which channel should we test first?",
+ options_json: JSON.stringify(["Google Ads", "Meta", "TikTok"]),
+ status: "pending",
+ answer_option_index: null,
+ answer_text: null,
+ resolved_by_kind: null,
+ created_at: new Date(Date.now() - 60_000).toISOString(),
+ resolved_at: null,
+ ...overrides,
+ };
+}
+
+beforeEach(() => {
+ answerMock.mockReset();
+ cancelMock.mockReset();
+ toastSuccessMock.mockReset();
+ toastErrorMock.mockReset();
+ toastInfoMock.mockReset();
+});
+
+describe("QuestionCard — pending state", () => {
+ it("renders prompt, agent, status badge, and each option as a radio button", () => {
+ render(
+ <QuestionCard
+ question={makeQuestion()}
+ options={["Google Ads", "Meta", "TikTok"]}
+ />,
+ );
+ expect(screen.getByText("Which channel should we test first?")).toBeInTheDocument();
+ expect(screen.getByText("Question")).toBeInTheDocument();
+ expect(screen.getByText("Needs answer")).toBeInTheDocument();
+ expect(screen.getByText("demo-cmo")).toBeInTheDocument();
+
+ const radios = screen.getAllByRole("radio");
+ expect(radios).toHaveLength(3);
+ expect(radios[0]).toHaveTextContent("Google Ads");
+ expect(radios[2]).toHaveTextContent("TikTok");
+ });
+
+ it("Send is disabled until an option is picked or text is typed", () => {
+ render(
+ <QuestionCard
+ question={makeQuestion()}
+ options={["Google Ads", "Meta"]}
+ />,
+ );
+ const send = screen.getByRole("button", { name: /send answer/i });
+ expect(send).toBeDisabled();
+ fireEvent.click(screen.getByRole("radio", { name: /Meta/ }));
+ expect(send).not.toBeDisabled();
+ });
+
+ it("clicking a selected option deselects it", () => {
+ render(
+ <QuestionCard
+ question={makeQuestion()}
+ options={["Google Ads", "Meta"]}
+ />,
+ );
+ const metaRadio = screen.getByRole("radio", { name: /Meta/ });
+ fireEvent.click(metaRadio);
+ expect(metaRadio).toHaveAttribute("aria-checked", "true");
+ fireEvent.click(metaRadio);
+ expect(metaRadio).toHaveAttribute("aria-checked", "false");
+ expect(screen.getByRole("button", { name: /send answer/i })).toBeDisabled();
+ });
+
+ it("submitting calls answerQuestionAction with the chosen index + text", async () => {
+ answerMock.mockResolvedValue({ ok: true });
+ render(
+ <QuestionCard
+ question={makeQuestion()}
+ options={["Google Ads", "Meta", "TikTok"]}
+ />,
+ );
+ fireEvent.click(screen.getByRole("radio", { name: /Meta/ }));
+ fireEvent.change(screen.getByPlaceholderText(/add nuance|Type your answer/), {
+ target: { value: "Start lean — $200 daily" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /send answer/i }));
+ await waitFor(() => {
+ expect(answerMock).toHaveBeenCalledWith("q-1", {
+ option_index: 1,
+ text: "Start lean — $200 daily",
+ });
+ expect(toastSuccessMock).toHaveBeenCalled();
+ });
+ });
+
+ it("surfaces server errors via toast and does not show success", async () => {
+ answerMock.mockResolvedValue({ ok: false, error: "boom" });
+ render(
+ <QuestionCard
+ question={makeQuestion()}
+ options={["Google Ads"]}
+ />,
+ );
+ fireEvent.click(screen.getByRole("radio", { name: /Google Ads/ }));
+ fireEvent.click(screen.getByRole("button", { name: /send answer/i }));
+ await waitFor(() => {
+ expect(toastErrorMock).toHaveBeenCalledWith("boom");
+ });
+ expect(toastSuccessMock).not.toHaveBeenCalled();
+ });
+
+ it("Dismiss calls cancelQuestionAction and shows the info toast", async () => {
+ cancelMock.mockResolvedValue({ ok: true });
+ render(
+ <QuestionCard
+ question={makeQuestion()}
+ options={["Google Ads"]}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /Dismiss/ }));
+ await waitFor(() => {
+ expect(cancelMock).toHaveBeenCalledWith("q-1");
+ expect(toastInfoMock).toHaveBeenCalled();
+ });
+ });
+
+ it("renders a free-text only mode when no options are supplied", () => {
+ render(
+ <QuestionCard
+ question={makeQuestion({ options_json: "[]" })}
+ options={[]}
+ />,
+ );
+ expect(screen.queryAllByRole("radio")).toHaveLength(0);
+ expect(screen.getByPlaceholderText(/Type your answer/)).toBeInTheDocument();
+ });
+});
+
+describe("QuestionCard — resolved state", () => {
+ it("renders the chosen option + free-text on an answered row", () => {
+ render(
+ <QuestionCard
+ question={makeQuestion({
+ status: "answered",
+ answer_option_index: 1,
+ answer_text: "with $200/day cap",
+ resolved_by_kind: "user",
+ resolved_at: new Date().toISOString(),
+ })}
+ options={["Google Ads", "Meta"]}
+ />,
+ );
+ expect(screen.getByText("Answered")).toBeInTheDocument();
+ expect(screen.getByText("Meta")).toBeInTheDocument();
+ expect(screen.getByText("with $200/day cap")).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /send answer/i })).not.toBeInTheDocument();
+ });
+
+ it("renders 'Dismissed without answer.' on a cancelled row", () => {
+ render(
+ <QuestionCard
+ question={makeQuestion({
+ status: "cancelled",
+ resolved_by_kind: "user",
+ resolved_at: new Date().toISOString(),
+ })}
+ options={["Google Ads"]}
+ />,
+ );
+ expect(screen.getByText("Dismissed")).toBeInTheDocument();
+ expect(screen.getByText(/Dismissed without answer/)).toBeInTheDocument();
+ });
+});
diff --git a/src/components/question-card.tsx b/src/components/question-card.tsx
new file mode 100644
index 00000000..095e1837
--- /dev/null
+++ b/src/components/question-card.tsx
@@ -0,0 +1,243 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { MessageSquareQuote } from "lucide-react";
+import { toast } from "sonner";
+
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent } from "@/components/ui/card";
+import { cn } from "@/lib/utils";
+import {
+ answerQuestionAction,
+ cancelQuestionAction,
+} from "@/server/actions/questions";
+import type { Question } from "@/types";
+
+function timeAgo(iso: string) {
+ const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
+ if (seconds < 60) return `${Math.floor(seconds)}s ago`;
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return `${Math.floor(seconds / 86400)}d ago`;
+}
+
+export type QuestionCardProps = {
+ question: Question;
+ /** Options parsed from question.options_json. Empty array = free-text only. */
+ options: string[];
+};
+
+/**
+ * Renders an open `ask_user_question` row as a structured card above the
+ * task transcript. The user can pick one of the agent-provided options
+ * AND/OR type a free-text answer. Submit fires answerQuestionAction,
+ * which streams a [SYSTEM] wake-up turn to the agent and unblocks the
+ * task. Cancel dismisses without delivering — task stays blocked.
+ *
+ * Mirrors ApprovalCard structurally so the workspace renders a consistent
+ * "what does the agent need from me" stack when both card kinds are open.
+ */
+export function QuestionCard({ question, options }: QuestionCardProps) {
+ const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
+ const [text, setText] = useState("");
+ const [pending, start] = useTransition();
+
+ const actionable = question.status === "pending";
+ const canSubmit = actionable && (selectedIndex != null || text.trim().length > 0);
+
+ function submit() {
+ if (!canSubmit) return;
+ start(async () => {
+ const r = await answerQuestionAction(question.id, {
+ option_index: selectedIndex,
+ text: text.trim() || null,
+ });
+ if (!r.ok) {
+ toast.error(r.error ?? "Failed to send answer");
+ return;
+ }
+ toast.success("Sent — agent is being notified");
+ // No local reset: the server action revalidates and the next render
+ // shows the row with status='answered' (or it disappears from the
+ // open list, depending on the wrapping component).
+ });
+ }
+
+ function dismiss() {
+ start(async () => {
+ const r = await cancelQuestionAction(question.id);
+ if (!r.ok) {
+ toast.error(r.error ?? "Failed to dismiss");
+ return;
+ }
+ toast.info(
+ "Question dismissed. The task stays blocked until the agent or user takes another step.",
+ );
+ });
+ }
+
+ return (
+ <Card
+ className="overflow-hidden"
+ role="region"
+ aria-label={question.prompt}
+ data-status={question.status}
+ >
+ <CardContent className="space-y-3 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-0 flex-1 space-y-1.5">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <Badge variant="outline" className="gap-1 text-[10px]">
+ <MessageSquareQuote className="size-3" />
+ Question
+ </Badge>
+ <Badge
+ variant={actionable ? "default" : "outline"}
+ className="text-[10px]"
+ >
+ {actionable
+ ? "Needs answer"
+ : question.status === "answered"
+ ? "Answered"
+ : "Dismissed"}
+ </Badge>
+ </div>
+ <p className="text-sm font-medium leading-snug whitespace-pre-wrap">
+ {question.prompt}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ Agent <span className="font-mono">{question.agent_id}</span> ·{" "}
+ {timeAgo(question.created_at)}
+ </p>
+ </div>
+ </div>
+
+ {!actionable && (
+ <ResolvedAnswer
+ question={question}
+ options={options}
+ />
+ )}
+
+ {actionable && (
+ <div className="space-y-3">
+ {options.length > 0 && (
+ <div
+ className="grid gap-2"
+ role="radiogroup"
+ aria-label="Suggested answers"
+ >
+ {options.map((opt, idx) => {
+ const selected = idx === selectedIndex;
+ return (
+ <button
+ key={`${opt}-${idx}`}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={() =>
+ setSelectedIndex((cur) => (cur === idx ? null : idx))
+ }
+ disabled={pending}
+ className={cn(
+ "w-full rounded-md border px-3 py-2 text-left text-sm transition-colors outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50",
+ selected
+ ? "border-sky-500/80 bg-sky-500/10 text-sky-950 dark:bg-sky-400/15 dark:text-sky-50"
+ : "border-border/70 hover:border-sky-500/60 hover:bg-sky-500/5",
+ )}
+ >
+ {opt}
+ </button>
+ );
+ })}
+ </div>
+ )}
+
+ <div className="space-y-1.5">
+ <label
+ htmlFor={`q-${question.id}-text`}
+ className="text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground"
+ >
+ {options.length > 0 ? "Or add a comment" : "Your answer"}
+ </label>
+ <textarea
+ id={`q-${question.id}-text`}
+ value={text}
+ onChange={(e) => setText(e.target.value)}
+ rows={3}
+ placeholder={
+ options.length > 0
+ ? "Optional — add nuance to the option you picked, or answer free-form."
+ : "Type your answer…"
+ }
+ disabled={pending}
+ className="w-full resize-y rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50"
+ />
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" onClick={submit} disabled={pending || !canSubmit}>
+ Send answer
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={dismiss}
+ disabled={pending}
+ >
+ Dismiss
+ </Button>
+ </div>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
+
+function ResolvedAnswer({
+ question,
+ options,
+}: {
+ question: Question;
+ options: string[];
+}) {
+ if (question.status === "cancelled") {
+ return (
+ <p className="rounded-md border border-dashed border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
+ Dismissed without answer.
+ </p>
+ );
+ }
+ const chosen =
+ question.answer_option_index != null
+ ? (options[question.answer_option_index] ?? null)
+ : null;
+ const text = question.answer_text?.trim() || null;
+ return (
+ <div className="rounded-md border border-dashed border-border bg-muted/30 p-3 text-xs">
+ <div className="text-[10px] uppercase tracking-wide text-muted-foreground">
+ Answer
+ </div>
+ {chosen && (
+ <p className="mt-1 font-medium leading-relaxed">{chosen}</p>
+ )}
+ {text && (
+ <p
+ className={cn(
+ "whitespace-pre-wrap leading-relaxed",
+ chosen ? "mt-1 text-muted-foreground" : "mt-1",
+ )}
+ >
+ {text}
+ </p>
+ )}
+ {!chosen && !text && (
+ <p className="mt-1 italic text-muted-foreground">
+ (empty answer)
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/src/server/actions/questions.ts b/src/server/actions/questions.ts
new file mode 100644
index 00000000..bb135610
--- /dev/null
+++ b/src/server/actions/questions.ts
@@ -0,0 +1,90 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+import {
+ answerQuestion,
+ cancelQuestion,
+ getQuestion,
+ parseQuestionOptions,
+} from "@/server/db/questions";
+import { wakeTaskOnQuestionResolution } from "@/server/orchestration/question-wakeup";
+
+export type QuestionActionResult = { ok: boolean; error?: string };
+
+export type AnswerQuestionInput = {
+ /** Zero-based index into the original options[]. Null = no option chosen. */
+ option_index?: number | null;
+ /** Free-text answer alongside / instead of an option. Null = no comment. */
+ text?: string | null;
+};
+
+/**
+ * Answer the user's open question. Validates the option index against the
+ * stored options[], writes the answer, then fires the wake-up
+ * fire-and-forget so the agent picks it up on its next turn.
+ */
+export async function answerQuestionAction(
+ id: string,
+ input: AnswerQuestionInput,
+): Promise<QuestionActionResult> {
+ const before = getQuestion(id);
+ if (!before) return { ok: false, error: "Question not found." };
+ if (before.status !== "pending") {
+ return { ok: false, error: `Question is already ${before.status}.` };
+ }
+
+ const trimmedText = input.text?.trim() || null;
+ let optionIndex: number | null = null;
+ if (input.option_index != null) {
+ const options = parseQuestionOptions(before);
+ if (
+ !Number.isInteger(input.option_index) ||
+ input.option_index < 0 ||
+ input.option_index >= options.length
+ ) {
+ return { ok: false, error: "Selected option is out of range." };
+ }
+ optionIndex = input.option_index;
+ }
+
+ if (optionIndex == null && !trimmedText) {
+ return {
+ ok: false,
+ error: "Pick an option or type an answer.",
+ };
+ }
+
+ const after = answerQuestion({
+ id,
+ answer_option_index: optionIndex,
+ answer_text: trimmedText,
+ });
+ if (!after) return { ok: false, error: "Question row vanished." };
+
+ void wakeTaskOnQuestionResolution(after).catch((err) => {
+ console.error("[answer-question-action] wake-up failed:", err);
+ });
+
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
+
+/**
+ * Dismiss the question without delivering an answer. The task STAYS
+ * blocked — the user opted out of resolving here, so the agent is not
+ * woken. The agent / user can take the next step manually (cancel the
+ * task, re-ask, etc.).
+ */
+export async function cancelQuestionAction(
+ id: string,
+): Promise<QuestionActionResult> {
+ const before = getQuestion(id);
+ if (!before) return { ok: false, error: "Question not found." };
+ if (before.status !== "pending") {
+ return { ok: false, error: `Question is already ${before.status}.` };
+ }
+ const after = cancelQuestion(id);
+ if (!after) return { ok: false, error: "Question row vanished." };
+ revalidatePath("/", "layout");
+ return { ok: true };
+}
diff --git a/src/server/db/migrations.ts b/src/server/db/migrations.ts
index b0dab7fa..763efd11 100644
--- a/src/server/db/migrations.ts
+++ b/src/server/db/migrations.ts
@@ -349,6 +349,40 @@ ALTER TABLE projects ADD COLUMN codebase_path TEXT;
ALTER TABLE tasks ADD COLUMN blocked_by_task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_tasks_blocked_by ON tasks(blocked_by_task_id) WHERE blocked_by_task_id IS NOT NULL;
+`,
+ },
+ {
+ name: "009_questions.sql",
+ sql: `
+-- Migration 009: questions table for ask_user_question.
+--
+-- Agents call the ask_user_question MCP tool to surface a structured
+-- question to the user (with optional multiple-choice options). Previously
+-- this only logged an action; now it persists a row, blocks the gating
+-- task, and the UI renders a QuestionCard alongside ApprovalCard. The
+-- user picks an option or types free-text; the wake-up streams the
+-- resolution back to the agent.
+--
+-- Modeled like approvals: one row per question, pending → answered |
+-- cancelled (terminal). No comments table — single-shot Q&A; if the
+-- agent needs more, it asks again.
+
+CREATE TABLE IF NOT EXISTS questions (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ agent_id TEXT NOT NULL,
+ task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
+ prompt TEXT NOT NULL,
+ options_json TEXT NOT NULL DEFAULT '[]',
+ status TEXT NOT NULL CHECK (status IN ('pending','answered','cancelled')),
+ answer_option_index INTEGER,
+ answer_text TEXT,
+ resolved_by_kind TEXT CHECK (resolved_by_kind IN ('user','system')),
+ created_at TEXT NOT NULL,
+ resolved_at TEXT
+);
+CREATE INDEX IF NOT EXISTS idx_questions_pending ON questions(project_slug, status) WHERE status = 'pending';
+CREATE INDEX IF NOT EXISTS idx_questions_task ON questions(task_id) WHERE task_id IS NOT NULL;
`,
},
];
diff --git a/src/server/db/migrations/009_questions.sql b/src/server/db/migrations/009_questions.sql
new file mode 100644
index 00000000..05c0871a
--- /dev/null
+++ b/src/server/db/migrations/009_questions.sql
@@ -0,0 +1,29 @@
+-- Migration 009: questions table for ask_user_question.
+--
+-- Agents call the ask_user_question MCP tool to surface a structured
+-- question to the user (with optional multiple-choice options). Previously
+-- this only logged an action; now it persists a row, blocks the gating
+-- task, and the UI renders a QuestionCard alongside ApprovalCard. The
+-- user picks an option or types free-text; the wake-up streams the
+-- resolution back to the agent.
+--
+-- Modeled like approvals: one row per question, pending → answered |
+-- cancelled (terminal). No comments table — single-shot Q&A; if the
+-- agent needs more, it asks again.
+
+CREATE TABLE IF NOT EXISTS questions (
+ id TEXT PRIMARY KEY,
+ project_slug TEXT NOT NULL REFERENCES projects(slug),
+ agent_id TEXT NOT NULL,
+ task_id TEXT REFERENCES tasks(id) ON DELETE SET NULL,
+ prompt TEXT NOT NULL,
+ options_json TEXT NOT NULL DEFAULT '[]',
+ status TEXT NOT NULL CHECK (status IN ('pending','answered','cancelled')),
+ answer_option_index INTEGER,
+ answer_text TEXT,
+ resolved_by_kind TEXT CHECK (resolved_by_kind IN ('user','system')),
+ created_at TEXT NOT NULL,
+ resolved_at TEXT
+);
+CREATE INDEX IF NOT EXISTS idx_questions_pending ON questions(project_slug, status) WHERE status = 'pending';
+CREATE INDEX IF NOT EXISTS idx_questions_task ON questions(task_id) WHERE task_id IS NOT NULL;
diff --git a/src/server/db/questions.test.ts b/src/server/db/questions.test.ts
new file mode 100644
index 00000000..7ec37c43
--- /dev/null
+++ b/src/server/db/questions.test.ts
@@ -0,0 +1,240 @@
+import Database from "better-sqlite3";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { MIGRATIONS } from "./migrations";
+
+let testDb: Database.Database;
+
+vi.mock("./db", () => ({
+ getDb: () => testDb,
+ getDbPath: () => ":memory:",
+}));
+
+import {
+ answerQuestion,
+ cancelQuestion,
+ createQuestion,
+ getQuestion,
+ listOpenQuestionsForProject,
+ listOpenQuestionsForTask,
+ listQuestionsForTask,
+ parseQuestionOptions,
+} from "./questions";
+
+function applyMigrations(db: Database.Database): void {
+ for (const m of MIGRATIONS) db.exec(m.sql);
+}
+
+function createDb(): Database.Database {
+ const db = new Database(":memory:");
+ db.pragma("foreign_keys = ON");
+ applyMigrations(db);
+ return db;
+}
+
+function seedProject(slug = "acme"): void {
+ testDb
+ .prepare(
+ "INSERT INTO projects (id, slug, display_name, created_at) VALUES (?, ?, ?, ?)",
+ )
+ .run("p-" + slug, slug, slug, "2026-01-01T00:00:00.000Z");
+}
+
+function seedTask(id = "t-1", project_slug = "acme"): string {
+ testDb
+ .prepare(
+ `INSERT INTO tasks
+ (id, project_slug, agent_id, brief, status, created_at, updated_at, display_id)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+ )
+ .run(
+ id,
+ project_slug,
+ `${project_slug}-cmo`,
+ "do the thing",
+ "working",
+ "2026-01-01T00:00:00.000Z",
+ "2026-01-01T00:00:00.000Z",
+ // display_id is globally unique — derive from the task id so multiple
+ // seedTask() calls in one test don't collide.
+ `${project_slug}-${id}`,
+ );
+ return id;
+}
+
+beforeEach(() => {
+ testDb = createDb();
+});
+
+afterEach(() => {
+ testDb.close();
+});
+
+describe("createQuestion", () => {
+ it("persists a pending question with options serialized as JSON", () => {
+ seedProject();
+ const taskId = seedTask();
+ const q = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ task_id: taskId,
+ prompt: "Which channel should we test first?",
+ options: ["Google Ads", "Meta", "TikTok"],
+ });
+ expect(q.id).toMatch(/[0-9a-f-]{36}/);
+ expect(q.status).toBe("pending");
+ expect(q.resolved_at).toBeNull();
+ expect(q.answer_option_index).toBeNull();
+ expect(q.answer_text).toBeNull();
+ expect(parseQuestionOptions(q)).toEqual(["Google Ads", "Meta", "TikTok"]);
+ });
+
+ it("stores an empty options array when none are supplied", () => {
+ seedProject();
+ const q = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ prompt: "Free text only",
+ options: [],
+ });
+ expect(parseQuestionOptions(q)).toEqual([]);
+ });
+});
+
+describe("listOpenQuestionsForTask / listOpenQuestionsForProject", () => {
+ it("filters by status=pending and the right scope", () => {
+ seedProject();
+ const taskA = seedTask("t-a");
+ const taskB = seedTask("t-b");
+ const open = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ task_id: taskA,
+ prompt: "Open on A",
+ options: [],
+ });
+ const other = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ task_id: taskB,
+ prompt: "Open on B",
+ options: [],
+ });
+ const cancelled = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ task_id: taskA,
+ prompt: "Will be cancelled",
+ options: [],
+ });
+ cancelQuestion(cancelled.id);
+
+ const openOnA = listOpenQuestionsForTask(taskA);
+ expect(openOnA.map((q) => q.id)).toEqual([open.id]);
+
+ const allProject = listOpenQuestionsForProject("acme");
+ expect(allProject.map((q) => q.id).sort()).toEqual(
+ [open.id, other.id].sort(),
+ );
+ });
+});
+
+describe("listQuestionsForTask", () => {
+ it("returns every question on the task regardless of status, newest first", () => {
+ seedProject();
+ const taskId = seedTask();
+ const first = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ task_id: taskId,
+ prompt: "First",
+ options: [],
+ });
+ const second = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ task_id: taskId,
+ prompt: "Second",
+ options: [],
+ });
+ cancelQuestion(first.id);
+
+ const rows = listQuestionsForTask(taskId);
+ expect(rows.map((q) => q.id)).toEqual([second.id, first.id]);
+ });
+});
+
+describe("answerQuestion", () => {
+ it("marks the row answered with option_index and text, sets resolved_at", () => {
+ seedProject();
+ const taskId = seedTask();
+ const q = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ task_id: taskId,
+ prompt: "Pick one",
+ options: ["A", "B"],
+ });
+ const after = answerQuestion({
+ id: q.id,
+ answer_option_index: 1,
+ answer_text: "B with caveats",
+ });
+ expect(after).not.toBeNull();
+ expect(after?.status).toBe("answered");
+ expect(after?.answer_option_index).toBe(1);
+ expect(after?.answer_text).toBe("B with caveats");
+ expect(after?.resolved_by_kind).toBe("user");
+ expect(after?.resolved_at).toBeTruthy();
+ });
+
+ it("is a no-op when the row is already terminal (returns null)", () => {
+ seedProject();
+ const q = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ prompt: "Already cancelled",
+ options: [],
+ });
+ cancelQuestion(q.id);
+ const result = answerQuestion({
+ id: q.id,
+ answer_option_index: null,
+ answer_text: "too late",
+ });
+ expect(result).toBeNull();
+ const fresh = getQuestion(q.id);
+ expect(fresh?.status).toBe("cancelled");
+ });
+});
+
+describe("cancelQuestion", () => {
+ it("marks pending → cancelled and is idempotent (second call returns null)", () => {
+ seedProject();
+ const q = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ prompt: "Cancel me",
+ options: [],
+ });
+ const first = cancelQuestion(q.id);
+ expect(first?.status).toBe("cancelled");
+ const again = cancelQuestion(q.id);
+ expect(again).toBeNull();
+ });
+});
+
+describe("parseQuestionOptions", () => {
+ it("returns [] for malformed JSON or non-string entries", () => {
+ seedProject();
+ const q = createQuestion({
+ project_slug: "acme",
+ agent_id: "acme-cmo",
+ prompt: "fine",
+ options: ["x"],
+ });
+ expect(parseQuestionOptions(q)).toEqual(["x"]);
+ expect(parseQuestionOptions({ ...q, options_json: "not json" })).toEqual([]);
+ expect(parseQuestionOptions({ ...q, options_json: "[1, 2]" })).toEqual([]);
+ });
+});
diff --git a/src/server/db/questions.ts b/src/server/db/questions.ts
new file mode 100644
index 00000000..eb13f0df
--- /dev/null
+++ b/src/server/db/questions.ts
@@ -0,0 +1,161 @@
+import { randomUUID } from "node:crypto";
+import { getDb } from "./db";
+import type { Question, QuestionStatus } from "@/types";
+
+export type CreateQuestionInput = {
+ project_slug: string;
+ agent_id: string;
+ task_id?: string | null;
+ prompt: string;
+ /** Multiple-choice hints rendered as buttons. Empty array = free-text only. */
+ options: string[];
+};
+
+export function createQuestion(input: CreateQuestionInput): Question {
+ const db = getDb();
+ const id = randomUUID();
+ const createdAt = new Date().toISOString();
+ db.prepare(
+ `INSERT INTO questions
+ (id, project_slug, agent_id, task_id, prompt, options_json,
+ status, answer_option_index, answer_text, resolved_by_kind,
+ created_at, resolved_at)
+ VALUES (?, ?, ?, ?, ?, ?, 'pending', NULL, NULL, NULL, ?, NULL)`,
+ ).run(
+ id,
+ input.project_slug,
+ input.agent_id,
+ input.task_id ?? null,
+ input.prompt,
+ JSON.stringify(input.options ?? []),
+ createdAt,
+ );
+ return getQuestion(id)!;
+}
+
+export function getQuestion(id: string): Question | null {
+ const db = getDb();
+ const row = db
+ .prepare("SELECT * FROM questions WHERE id = ?")
+ .get(id) as Question | undefined;
+ return row ?? null;
+}
+
+/** Open (pending) questions on a given task, oldest first. Usually 0 or 1. */
+export function listOpenQuestionsForTask(task_id: string): Question[] {
+ const db = getDb();
+ return db
+ .prepare(
+ `SELECT * FROM questions
+ WHERE task_id = ? AND status = 'pending'
+ ORDER BY created_at ASC`,
+ )
+ .all(task_id) as Question[];
+}
+
+/** Every question (any status) anchored to a task, newest first. Audit trail.
+ * `rowid DESC` tiebreaker keeps ordering deterministic when two rows share
+ * a millisecond-resolution `created_at`: SQLite assigns rowid sequentially
+ * per insert, so this falls back to insertion order. */
+export function listQuestionsForTask(task_id: string): Question[] {
+ const db = getDb();
+ return db
+ .prepare(
+ `SELECT * FROM questions
+ WHERE task_id = ?
+ ORDER BY created_at DESC, rowid DESC`,
+ )
+ .all(task_id) as Question[];
+}
+
+/** Project-wide open questions. Used by the future approvals/inbox tab. */
+export function listOpenQuestionsForProject(project_slug: string): Question[] {
+ const db = getDb();
+ return db
+ .prepare(
+ `SELECT * FROM questions
+ WHERE project_slug = ? AND status = 'pending'
+ ORDER BY created_at DESC`,
+ )
+ .all(project_slug) as Question[];
+}
+
+export type AnswerQuestionInput = {
+ id: string;
+ /** Zero-based index into the original options[] when the user clicked
+ * an option. Null when the user only typed free-text. */
+ answer_option_index?: number | null;
+ /** Free-text answer typed by the user. Null when the user only clicked
+ * an option. */
+ answer_text?: string | null;
+};
+
+/**
+ * Conditional UPDATE keyed on status='pending' — returns the post-update
+ * row, or null if the question wasn't pending (already answered /
+ * cancelled / unknown id). Callers use null to detect race-loss and bail
+ * silently.
+ */
+export function answerQuestion(input: AnswerQuestionInput): Question | null {
+ const db = getDb();
+ const resolvedAt = new Date().toISOString();
+ const res = db
+ .prepare(
+ `UPDATE questions
+ SET status = 'answered',
+ answer_option_index = ?,
+ answer_text = ?,
+ resolved_by_kind = 'user',
+ resolved_at = ?
+ WHERE id = ? AND status = 'pending'`,
+ )
+ .run(
+ input.answer_option_index ?? null,
+ input.answer_text ?? null,
+ resolvedAt,
+ input.id,
+ );
+ if (res.changes === 0) return null;
+ return getQuestion(input.id);
+}
+
+export function cancelQuestion(id: string): Question | null {
+ const db = getDb();
+ const resolvedAt = new Date().toISOString();
+ const res = db
+ .prepare(
+ `UPDATE questions
+ SET status = 'cancelled',
+ resolved_by_kind = 'user',
+ resolved_at = ?
+ WHERE id = ? AND status = 'pending'`,
+ )
+ .run(resolvedAt, id);
+ if (res.changes === 0) return null;
+ return getQuestion(id);
+}
+
+/** Convenience: parse options_json into a string[] for the UI/handler. */
+export function parseQuestionOptions(q: Question): string[] {
+ try {
+ const parsed = JSON.parse(q.options_json);
+ if (Array.isArray(parsed) && parsed.every((x) => typeof x === "string")) {
+ return parsed;
+ }
+ } catch {
+ // fall through
+ }
+ return [];
+}
+
+/** Map a question.status string to a human label for badges. */
+export function statusLabel(status: QuestionStatus): string {
+ switch (status) {
+ case "pending":
+ return "Pending";
+ case "answered":
+ return "Answered";
+ case "cancelled":
+ return "Cancelled";
+ }
+}
diff --git a/src/server/mcp-server/tools.ts b/src/server/mcp-server/tools.ts
index 972da0db..297192c2 100644
--- a/src/server/mcp-server/tools.ts
+++ b/src/server/mcp-server/tools.ts
@@ -262,8 +262,14 @@ async function handleAskUserTool(input: unknown): Promise<ToolResult> {
{ project_slug, agent_id },
);
if (!r.ok) return { ok: false, error: r.error };
+ // The task is now parked in `blocked`; the agent should end its turn
+ // and wait for the user's answer to be delivered via a [SYSTEM] wake-up
+ // turn. Surface the question_id so the agent can correlate.
+ const taskClause = r.data.task_id
+ ? ` on task ${r.data.task_id}. The task is now blocked until the user answers; end your turn.`
+ : ".";
return txt(
- `question recorded${r.data.task_id ? ` on task ${r.data.task_id}` : ""}.`,
+ `question ${r.data.question_id} recorded${taskClause}`,
);
}
diff --git a/src/server/orchestration/handlers.test.ts b/src/server/orchestration/handlers.test.ts
index bca09082..ae25e14d 100644
--- a/src/server/orchestration/handlers.test.ts
+++ b/src/server/orchestration/handlers.test.ts
@@ -624,3 +624,78 @@ describe("handleTaskStatus — blocked_by_task_id propagation", () => {
expect(a2.status).toBe("cancelled"); // untouched
});
});
+
+describe("handleAskUser — ask_user_question", () => {
+ it("persists a Question row with parsed options and parks the task in blocked", async () => {
+ const { handleAskUser } = await import("./handlers");
+ const t = createTask({
+ project_slug: "demo",
+ agent_id: "demo-cmo",
+ brief: "x",
+ });
+ const r = handleAskUser(
+ {
+ question: "Which channel first?",
+ task_id: t.id,
+ options: " Google Ads , Meta ,, TikTok ",
+ },
+ { project_slug: "demo", agent_id: "demo-cmo" },
+ );
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.data.question_id).toMatch(/[0-9a-f-]{36}/);
+ expect(r.data.options).toEqual(["Google Ads", "Meta", "TikTok"]);
+
+ // Row persisted with status='pending' and options serialized.
+ const row = testDb
+ .prepare("SELECT status, options_json, task_id FROM questions WHERE id = ?")
+ .get(r.data.question_id) as {
+ status: string;
+ options_json: string;
+ task_id: string | null;
+ };
+ expect(row.status).toBe("pending");
+ expect(row.task_id).toBe(t.id);
+ expect(JSON.parse(row.options_json)).toEqual([
+ "Google Ads",
+ "Meta",
+ "TikTok",
+ ]);
+
+ // Task transitioned to blocked.
+ const taskAfter = testDb
+ .prepare("SELECT status FROM tasks WHERE id = ?")
+ .get(t.id) as { status: string };
+ expect(taskAfter.status).toBe("blocked");
+ });
+
+ it("does not block when there's no task_id (free-standing question)", async () => {
+ const { handleAskUser } = await import("./handlers");
+ const r = handleAskUser(
+ { question: "What's your timezone?" },
+ { project_slug: "demo", agent_id: "demo-cmo" },
+ );
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.data.task_id).toBeNull();
+ const row = testDb
+ .prepare("SELECT task_id FROM questions WHERE id = ?")
+ .get(r.data.question_id) as { task_id: string | null };
+ expect(row.task_id).toBeNull();
+ });
+
+ it("rejects cross-project task references", async () => {
+ const { handleAskUser } = await import("./handlers");
+ const t = createTask({
+ project_slug: "demo",
+ agent_id: "demo-cmo",
+ brief: "x",
+ });
+ const r = handleAskUser(
+ { question: "?", task_id: t.id },
+ { project_slug: "other", agent_id: "other-cmo" },
+ );
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.error).toMatch(/Cross-project/);
+ });
+});
diff --git a/src/server/orchestration/handlers.ts b/src/server/orchestration/handlers.ts
index ce131574..128b7feb 100644
--- a/src/server/orchestration/handlers.ts
+++ b/src/server/orchestration/handlers.ts
@@ -11,6 +11,7 @@ import {
listActionableApprovals,
listApprovalsForTask,
} from "@/server/db/approvals";
+import { createQuestion } from "@/server/db/questions";
import { getDb } from "@/server/db/db";
import { getProject } from "@/server/db/projects";
import {
@@ -371,7 +372,12 @@ export type AskUserInput = {
export function handleAskUser(
input: AskUserInput,
ctx: HandlerContext,
-): HandlerResult<{ question: string; task_id: string | null }> {
+): HandlerResult<{
+ question_id: string;
+ question: string;
+ task_id: string | null;
+ options: string[];
+}> {
let resolvedTaskId: string | null = null;
if (input.task_id) {
const task = getTask(input.task_id);
@@ -386,17 +392,51 @@ export function handleAskUser(
}
resolvedTaskId = task.id;
}
+
+ // Parse comma-separated options into a clean string[] — the tool input
+ // is a comma-separated string for ergonomics in the agent template, but
+ // the DB and UI use a structured array. Drop empties/whitespace so the
+ // UI never renders an empty button.
+ const options = (input.options ?? "")
+ .split(",")
+ .map((s) => s.trim())
+ .filter((s) => s.length > 0);
+
+ const question = createQuestion({
+ project_slug: ctx.project_slug,
+ agent_id: ctx.agent_id,
+ task_id: resolvedTaskId,
+ prompt: input.question,
+ options,
+ });
+
+ // Park the task in `blocked` so the workspace renders the QuestionCard
+ // and the agent doesn't keep running while waiting on a human answer.
+ // Mirrors request_approval's blocking behavior.
+ if (resolvedTaskId) {
+ markTaskBlocked(resolvedTaskId);
+ }
+
logAgentAction({
project_slug: ctx.project_slug,
agent_id: ctx.agent_id,
task_id: resolvedTaskId,
action_type: "ask_user",
summary: input.question,
- payload: { task_id: resolvedTaskId, options: input.options ?? null },
+ payload: {
+ task_id: resolvedTaskId,
+ options,
+ question_id: question.id,
+ },
});
return {
ok: true,
- data: { question: input.question, task_id: resolvedTaskId },
+ data: {
+ question_id: question.id,
+ question: input.question,
+ task_id: resolvedTaskId,
+ options,
+ },
};
}
diff --git a/src/server/orchestration/question-wakeup.ts b/src/server/orchestration/question-wakeup.ts
new file mode 100644
index 00000000..f842d30d
--- /dev/null
+++ b/src/server/orchestration/question-wakeup.ts
@@ -0,0 +1,108 @@
+import {
+ buildPendingSessionKey,
+ findSessionBySessionId,
+} from "@/server/openclaw/sessions";
+import { streamChatViaGateway } from "@/server/openclaw/gateway-client";
+import {
+ parseQuestionOptions,
+} from "@/server/db/questions";
+import { getTask, setTaskThreadIfMissing, unblockTask } from "@/server/db/tasks";
+import type { Question } from "@/types";
+
+import { generateTaskThreadId } from "./task-kickoff";
+
+/**
+ * After the user answers (or cancels) a question raised by ask_user_question,
+ * deliver a [SYSTEM] turn into the task's chat thread so the agent picks up
+ * the resolution on its next turn. Mirrors approval-wakeup.ts.
+ *
+ * - answered → task unblocks, agent receives the question + chosen option +
+ * any free-text comment.
+ * - cancelled → task STAYS blocked (the user dismissed without resolving).
+ * The agent is not woken; the question simply disappears from the
+ * workspace and the task remains parked until the agent / user takes
+ * the next step.
+ *
+ * No-op when the question isn't anchored to a task — free-standing asks
+ * surface only in the project inbox and never park anything.
+ */
+export async function wakeTaskOnQuestionResolution(question: Question): Promise<void> {
+ if (!question.task_id) return;
+ if (question.status === "cancelled") return;
+ if (question.status !== "answered") return;
+
+ const task = getTask(question.task_id);
+ if (!task) return;
+ if (
+ task.status === "done" ||
+ task.status === "failed" ||
+ task.status === "cancelled"
+ ) {
+ return;
+ }
+
+ unblockTask(task.id);
+
+ // Lazy thread mint so a free-floating ask (no prior message) still has
+ // somewhere to deliver the [SYSTEM] turn.
+ let threadId = task.thread_id;
+ if (!threadId) {
+ const minted = setTaskThreadIfMissing(task.id, generateTaskThreadId());
+ if (minted?.thread_id) threadId = minted.thread_id;
+ }
+ if (!threadId) {
+ console.error(`[question-wakeup] no thread_id for task ${task.id}`);
+ return;
+ }
+
+ const known = findSessionBySessionId(task.agent_id, threadId);
+ const sessionKey =
+ known?.sessionKey ?? buildPendingSessionKey(task.agent_id, threadId);
+
+ const message = buildAnswerMessage(question);
+
+ try {
+ for await (const evt of streamChatViaGateway({
+ sessionKey,
+ sessionId: threadId,
+ message,
+ })) {
+ if (evt.kind === "error") throw new Error(evt.message);
+ }
+ } catch (err) {
+ console.error(
+ `[question-wakeup] gateway stream failed for task ${task.id}:`,
+ err,
+ );
+ }
+}
+
+function buildAnswerMessage(question: Question): string {
+ const options = parseQuestionOptions(question);
+ const chosen =
+ question.answer_option_index != null
+ ? (options[question.answer_option_index] ?? null)
+ : null;
+ const note = question.answer_text?.trim() || null;
+
+ // Compose a single "Answer: …" line that's unambiguous no matter how
+ // the user replied: option only, free-text only, or both.
+ let answerLine: string;
+ if (chosen && note) {
+ answerLine = `Answer: ${chosen} — ${note}`;
+ } else if (chosen) {
+ answerLine = `Answer: ${chosen}`;
+ } else if (note) {
+ answerLine = `Answer: ${note}`;
+ } else {
+ answerLine = "Answer: (the user submitted an empty response — re-ask if needed)";
+ }
+
+ return [
+ `[SYSTEM] The user answered question #${question.id.slice(0, 8)}.`,
+ `Question: ${question.prompt}`,
+ answerLine,
+ "",
+ "The task has been unblocked. Continue your work using this answer. End your turn with `submit_task_status` (working / done / failed / blocked) when appropriate.",
+ ].join("\n");
+}
diff --git a/src/server/skills/orchestration-skill.ts b/src/server/skills/orchestration-skill.ts
index baa9c60c..fa67ade0 100644
--- a/src/server/skills/orchestration-skill.ts
+++ b/src/server/skills/orchestration-skill.ts
@@ -53,8 +53,12 @@ call the discovery tool first instead of guessing:
\`blocked\` until resolved; the platform wakes you with the decision.
- \`add_task_comment\` — talk to the CMO (or future-you) on a specific
task. Cross-agent comms log, visible in /activity.
-- \`ask_user_question\` — surface a question to the human. Use sparingly;
- prefer asking the CMO or your own tools first.
+- \`ask_user_question\` — surface a structured question to the human, with
+ optional comma-separated \`options\` rendered as buttons. Setting
+ \`task_id\` parks the task in \`blocked\` until the user answers; the
+ platform wakes you with the answer on the task thread. Use sparingly;
+ prefer asking the CMO or your own tools first. End your turn after
+ calling — don't keep working on a blocked task.
- \`update_task\` — edit title / brief / success criteria on a task you
created. Doesn't change status.
- \`cancel_task\` — mark a task cancelled. Use when work is obsolete.
diff --git a/src/types/index.ts b/src/types/index.ts
index fc3c2ac6..d55bd85b 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -134,6 +134,35 @@ export type Approval = {
resolved_at: string | null;
};
+/** Open question raised by an agent via the `ask_user_question` MCP tool.
+ * Modeled like Approval — a pending row blocks the task; the user answers
+ * (option or free-text) or cancels; the wake-up streams the resolution
+ * back to the agent as a [SYSTEM] message on the task thread. */
+export type QuestionStatus = "pending" | "answered" | "cancelled";
+
+export type Question = {
+ id: string;
+ project_slug: string;
+ agent_id: string;
+ /** Task this question is anchored to. Null for free-standing asks. */
+ task_id: string | null;
+ prompt: string;
+ /** Optional multiple-choice hints rendered as buttons in the UI. JSON
+ * array of strings. Empty array when the agent didn't supply choices. */
+ options_json: string;
+ status: QuestionStatus;
+ /** Zero-based index into options_json[] when the user picked an option.
+ * Null when the user only typed free-text or cancelled. */
+ answer_option_index: number | null;
+ /** Free-text answer the user typed alongside / instead of an option.
+ * Null when the user only clicked an option or cancelled. */
+ answer_text: string | null;
+ /** Who resolved the question — user (typical) vs system (future timeout). */
+ resolved_by_kind: "user" | "system" | null;
+ created_at: string;
+ resolved_at: string | null;
+};
+
export type ApprovalComment = {
id: string;
approval_id: string;