Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(workbench): quick-reply buttons in chat (answer recorded on the agent message) (#417)

Call White8f42a303644b
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 43cd00a0e..59b4efc92 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -658,11 +658,19 @@ class ConsolidatedMessageDispatcher:
# workbench media-proxy rewrite (in ``persist_agent_message``)
# can turn them into inline images / file cards. ``persist_text``
# already has them stripped to plain labels for IM delivery.
- avibe_text = (
- process_reply(text, include_quick_replies=quick_replies_on, keep_file_links=True).text
- or persist_text
+ # Also carry the parsed quick-reply labels so the workbench can
+ # render the button group (IM channels render native buttons
+ # from the same ``enhanced.buttons``).
+ avibe_enhanced = process_reply(
+ text, include_quick_replies=quick_replies_on, keep_file_links=True
+ )
+ avibe_text = avibe_enhanced.text or persist_text
+ persist_agent_message(
+ target_context,
+ result_type,
+ avibe_text,
+ quick_replies=[b.text for b in avibe_enhanced.buttons] or None,
)
- persist_agent_message(target_context, result_type, avibe_text)
else:
persist_agent_message(target_context, result_type, persist_text)
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 066d8f171..7ab7f6502 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -133,7 +133,13 @@ _AGENT_TYPE_BY_CANONICAL = {
}
-def persist_agent_message(context: MessageContext, canonical_type: str, text: str) -> None:
+def persist_agent_message(
+ context: MessageContext,
+ canonical_type: str,
+ text: str,
+ *,
+ quick_replies: Optional[list[str]] = None,
+) -> None:
"""Persist one agent output into the workbench ``messages`` store.
Unified across **all** platforms (including avibe, which has no IM mirror)
@@ -201,6 +207,13 @@ def persist_agent_message(context: MessageContext, canonical_type: str, text: st
)
except Exception:
logger.exception("persist_agent_message: media rewrite failed")
+ content: Optional[dict] = {"kind": canonical_type} if canonical_type else None
+ # Quick-reply buttons (avibe result): the trailing ``---\n[label]…``
+ # block was already parsed + stripped upstream; carry the labels in
+ # ``content`` so the workbench renders the button group (IM channels
+ # render their own native buttons from the same parse).
+ if quick_replies:
+ content = {**(content or {}), "quick_replies": list(quick_replies)}
appended_row = _append_quietly(
conn,
scope_id=scope_id,
@@ -212,7 +225,7 @@ def persist_agent_message(context: MessageContext, canonical_type: str, text: st
message_type=message_type,
text=text,
parent_native_message_id=context.thread_id,
- content={"kind": canonical_type} if canonical_type else None,
+ content=content,
)
# Recompute the session's inbox row so the realtime event can patch
# the browser without a refetch. avibe-only: the workbench inbox is
diff --git a/docs/plans/workbench-quick-replies.md b/docs/plans/workbench-quick-replies.md
new file mode 100644
index 000000000..21314b188
--- /dev/null
+++ b/docs/plans/workbench-quick-replies.md
@@ -0,0 +1,102 @@
+# Workbench quick-reply buttons
+
+## Background
+
+IM channels (Slack/Discord/…) already support agent quick-reply buttons: the
+agent appends a `---\n[label] | [label]` block, `core/reply_enhancer.process_reply`
+parses it into structured `EnhancedReply.buttons`, and each IM adapter renders
+native buttons. The avibe **workbench Chat** does not support this yet — the avibe
+result persist path (`core/message_dispatcher`) calls `process_reply(...).text`,
+which **strips** the button block, and the parsed `enhanced.buttons` are only fed
+to the IM delivery path, so for avibe they are discarded.
+
+## Goal
+
+Render the agent's quick-reply buttons at the end of a workbench chat message.
+Interaction (per product):
+
+1. Buttons appear at the end of the agent message.
+2. Clicking one **sends that label as a user message** (normal turn flow).
+3. The clicked button highlights (mint + ✓), the others grey out, and the whole
+ group locks (no further clicks). **This locked/highlighted state persists
+ across reload.**
+
+## Solution (append-only, reuse the server parser)
+
+**Backend** — surface the already-parsed buttons; no new parser, no schema change:
+
+- `core/message_mirror.persist_agent_message(..., quick_replies=None)` — new
+ optional arg; when present, store it in the row's `content.quick_replies`
+ (same JSON `content` field that already carries `attachments`).
+- `core/message_dispatcher` — in the avibe `result` persist branch, capture the
+ `EnhancedReply.buttons` it already computes and pass
+ `quick_replies=[b.text for b in enhanced.buttons]`.
+
+**Choice persistence — recorded on the AGENT message (single source of truth).**
+
+> Design note: an earlier iteration derived the answered state from the *user
+> reply* (its metadata / text). That entity is separate, async, queue-merged,
+> removable and race-prone, so reconstructing "which group is answered, with
+> what" by correlating it back to the agent message was inherently fragile — a
+> string of review findings (queue-merge metadata loss, text concatenation
+> breaking the highlight, queued rows missing from the map, last-wins merges,
+> draft clobbering, no idempotency) were all the *same* root cause: the answer
+> didn't live where it belongs. The answer is a property of the agent message
+> (the question), so we record it there, once.
+
+- The agent message's `content` carries both `quick_replies` (the options) and,
+ once answered, `quick_reply_chosen` (the picked label).
+- Clicking sends the label as a normal user turn via `POST /messages` with
+ `metadata = { quick_reply_for: <agentMessageId> }`. The send endpoint:
+ - rejects early (`{already_answered}`, no turn) if that message already has a
+ `quick_reply_chosen` (idempotent against a stale second tab / missed event);
+ - skips `clear_draft` for a quick-reply send (a side action shouldn't wipe the
+ user's unsent composer draft);
+ - records the choice via `messages_service.set_quick_reply_chosen` **only after
+ the turn is accepted** (started OR queued) — so a failed click stays
+ retriable; `set_quick_reply_chosen` is set-once, so a rare double-dispatch
+ still records one consistent answer.
+
+**Frontend**
+
+- `QuickReplies` (design-system `Button`s): active → clickable; answered → chosen
+ highlighted (mint + ✓), the rest greyed + disabled. Optimistic local lock on
+ click for instant feedback; unlocks if the send resolves `false`; hands control
+ to the authoritative `chosen` once it loads.
+- `MessageRow` reads its OWN message's `content.quick_replies` + `quick_reply_chosen`
+ — no cross-message map, no `queue` scan, no user-reply metadata. The click
+ handler sends the label tagged with `quick_reply_for`.
+
+## Deferred (recorded, intentionally NOT built)
+
+- **"Only the latest agent message's buttons are clickable" (auto-lock older
+ groups when the conversation moves on).** Deferred per product: a user may
+ legitimately want to click a quick-reply from an earlier message. So every
+ unanswered group stays clickable regardless of age; a group locks ONLY once one
+ of its own buttons has been chosen. Revisit if stale-context clicks become a
+ problem.
+
+- **Removing a queued quick-reply leaves the group locked (no auto-unlock).**
+ If a quick-reply is clicked while a turn is running it queues, the choice is
+ recorded, then the user can delete the queued send from the queue strip. The
+ recorded choice is intentionally NOT cleared, so the group stays locked on a
+ choice the agent never received. Accepted per product (owner call): the user
+ deleted it deliberately, quick replies are a convenience layer, and they can
+ always type manually — not worth a clear-on-queue-remove hook for this
+ click-while-busy-then-undo corner.
+
+- **Cross-tab one-shot atomicity.** Idempotency is an early `get_quick_reply_chosen`
+ check + a set-once record after dispatch. Two tabs clicking the same button
+ inside the dispatch window could each start a turn; the set-once keeps the
+ recorded answer consistent. Accepted per product: negligible on a single-user
+ product and the worst case is a duplicate (identical) turn — not worth a
+ claim-before-dispatch + rollback path.
+
+## Evidence layers
+
+- Unit: `process_reply` button parsing already covered; add coverage that the
+ avibe persist path carries `content.quick_replies`.
+- Build: `npm run build`.
+- Manual (regression): agent reply with a `---\n[a]|[b]` block shows buttons;
+ click sends the label + locks/highlights; reload keeps it locked; an older
+ unanswered group is still clickable.
diff --git a/storage/messages_service.py b/storage/messages_service.py
index d6a658569..e283ee946 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -136,6 +136,63 @@ def append(
return _row_to_payload(payload)
+def get_quick_reply_chosen(conn: Connection, session_id: str, message_id: str) -> Optional[str]:
+ """The label already chosen for *message_id*'s quick-reply group, or None.
+
+ The chosen answer is recorded on the AGENT message itself (the question) as
+ the single source of truth for the locked/answered state, so this is one
+ row lookup — no correlating a separate, mergeable user reply. Scoped to
+ *session_id* so a request for one session can't read another's message.
+ """
+ row = conn.execute(
+ select(messages.c.content_json).where(
+ messages.c.id == message_id, messages.c.session_id == session_id
+ )
+ ).first()
+ if not row or not row[0]:
+ return None
+ try:
+ content = json.loads(row[0])
+ except (TypeError, ValueError):
+ return None
+ chosen = content.get("quick_reply_chosen")
+ return chosen if isinstance(chosen, str) and chosen else None
+
+
+def set_quick_reply_chosen(conn: Connection, session_id: str, message_id: str, choice: str) -> bool:
+ """Record *choice* as the answer to *message_id*'s quick-reply group, once.
+
+ Returns True if newly recorded; False if the message has no such option or was
+ already answered (set-once → idempotent). Writing the answer onto the agent
+ message is the root of the design: the lock then derives from that one row and
+ is immune to how the user reply is queued / merged / removed. Scoped to
+ *session_id* so a request for one session can't mutate another's message.
+ """
+ row = conn.execute(
+ select(messages.c.content_json).where(
+ messages.c.id == message_id, messages.c.session_id == session_id
+ )
+ ).first()
+ if not row or not row[0]:
+ return False
+ try:
+ content = json.loads(row[0])
+ except (TypeError, ValueError):
+ return False
+ options = content.get("quick_replies")
+ if not isinstance(options, list) or choice not in options:
+ return False
+ if content.get("quick_reply_chosen"):
+ return False # set-once: already answered
+ content["quick_reply_chosen"] = choice
+ conn.execute(
+ messages.update()
+ .where(messages.c.id == message_id, messages.c.session_id == session_id)
+ .values(content_json=json.dumps(content))
+ )
+ return True
+
+
def list_session_messages(
conn: Connection,
*,
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index b69af4c20..162e17b2c 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -155,6 +155,25 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(persisted_text, "Body")
self.assertNotIn("[Continue]", persisted_text)
+ async def test_avibe_result_persists_quick_replies_for_workbench(self):
+ """avibe carries the parsed quick-reply labels to ``persist_agent_message``
+ (as the ``quick_replies`` kwarg) so the workbench can render the button
+ group; the persisted text still has the trailing block stripped."""
+ controller = _StubController(platform="avibe", reply_enhancements=True)
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(user_id="U1", channel_id="C1", platform="avibe")
+ raw = "Pick one:\n\n---\n[✅ Yes] | [🙅 No]"
+
+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:
+ await dispatcher.emit_agent_message(context, "result", raw)
+
+ persist.assert_called_once()
+ self.assertEqual(persist.call_args.args[1], "result")
+ self.assertEqual(persist.call_args.kwargs.get("quick_replies"), ["✅ Yes", "🙅 No"])
+ # The block is still stripped from the persisted text itself.
+ self.assertNotIn("[✅ Yes]", persist.call_args.args[2])
+ self.assertIn("Pick one", persist.call_args.args[2])
+
async def test_suppressed_delivery_is_not_persisted(self):
"""Suppressed scheduled output is intentionally private — it must NOT
leak into the cross-platform messages history."""
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
index f46c95fa9..d88c4590a 100644
--- a/tests/test_messages_service.py
+++ b/tests/test_messages_service.py
@@ -728,3 +728,47 @@ def test_list_session_messages_tail_returns_recent_window(isolated_state):
assert [m["text"] for m in oldest["messages"]] == ["m0", "m1", "m2"]
assert [m["text"] for m in recent["messages"]] == ["m2", "m3", "m4"]
assert recent["next_after_id"] is None
+
+
+def test_quick_reply_choice_recorded_on_agent_message_once(isolated_state):
+ """The chosen quick-reply is recorded on the AGENT message itself (the single
+ source of truth for the locked/answered state), once, and only for offered
+ options."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "sess_qr")
+ row = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="sess_qr",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Pick one",
+ content={"kind": "result", "quick_replies": ["Yes", "No"]},
+ )
+ mid = row["id"]
+
+ with engine.begin() as conn:
+ assert messages_service.get_quick_reply_chosen(conn, "sess_qr", mid) is None
+ # An option that wasn't offered is rejected.
+ assert messages_service.set_quick_reply_chosen(conn, "sess_qr", mid, "Maybe") is False
+ # A real option records once.
+ assert messages_service.set_quick_reply_chosen(conn, "sess_qr", mid, "Yes") is True
+ assert messages_service.get_quick_reply_chosen(conn, "sess_qr", mid) == "Yes"
+ # Set-once / idempotent: a second answer is rejected and does not overwrite.
+ assert messages_service.set_quick_reply_chosen(conn, "sess_qr", mid, "No") is False
+ assert messages_service.get_quick_reply_chosen(conn, "sess_qr", mid) == "Yes"
+ # Scoped to the session: another session's id must not read/lock this row.
+ assert messages_service.get_quick_reply_chosen(conn, "other_sess", mid) is None
+ assert messages_service.set_quick_reply_chosen(conn, "other_sess", mid, "No") is False
+
+ # The recorded choice is visible through the normal read path (so the UI locks
+ # + highlights on reload).
+ with engine.connect() as conn:
+ loaded = messages_service.list_session_messages(conn, session_id="sess_qr")["messages"]
+ assert loaded[0]["content"].get("quick_reply_chosen") == "Yes"
+ # Unknown message id → no choice, no crash.
+ assert messages_service.get_quick_reply_chosen(conn, "sess_qr", "does-not-exist") is None
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index ab2519300..33a95d0bc 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -20,6 +20,7 @@ import { ImageViewerProvider } from '../ui/image-viewer';
import { Input } from '../ui/input';
import { Markdown } from '../ui/markdown';
import { Composer, type ComposerAttachment } from './Composer';
+import { QuickReplies } from './QuickReplies';
// While a turn is in flight, reconcile the working/Stop state against the
// controller on this cadence (the backend ``GET /turn-state`` is authoritative).
@@ -449,7 +450,7 @@ export const ChatPage: React.FC = () => {
}, [working, syncTurnState]);
const sendMessage = useCallback(
- async (text: string, attachments?: ComposerAttachment[]) => {
+ async (text: string, attachments?: ComposerAttachment[], metadata?: Record<string, unknown>) => {
// NB: no ``working`` guard — sending WHILE a turn runs is the queue
// feature; the backend enqueues it (202) instead of refusing.
const ready = (attachments ?? []).filter((a) => a.status === 'ready');
@@ -462,10 +463,10 @@ export const ChatPage: React.FC = () => {
// stream — we don't hold the response open. ``apiFetch`` attaches the
// CSRF token that ``protect_mutating_ui_requests`` requires under
// remote-access mode (raw ``fetch`` would 403).
- const requestBody =
- ready.length > 0
+ const requestBody = {
+ text,
+ ...(ready.length > 0
? {
- text,
content: {
text,
attachments: ready.map((a) => ({
@@ -478,7 +479,11 @@ export const ChatPage: React.FC = () => {
})),
},
}
- : { text };
+ : {}),
+ // Quick-reply click: tag the user row with the agent message it answers
+ // so the locked/highlighted state can be derived on reload.
+ ...(metadata ? { metadata } : {}),
+ };
const response = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/messages`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -494,6 +499,16 @@ export const ChatPage: React.FC = () => {
setWorking(false);
throw new Error(body?.detail ? String(body.detail) : `HTTP ${response.status}`);
}
+ if (body?.already_answered) {
+ // A duplicate quick-reply the backend already had (stale tab / missed
+ // event): no turn started HERE. Reconcile authoritatively rather than
+ // force-clearing — a genuinely-running turn (e.g. clicking an old group
+ // while a turn runs) must keep its Stop/thinking state. Return false so
+ // the quick-reply group drops its optimistic lock instead of staying
+ // stuck highlighting the rejected choice.
+ syncTurnStateRef.current?.();
+ return false;
+ }
if (body?.queued) {
// Sent while a turn was running → enqueued (shows above the composer
// via queue.updated). A turn IS in flight, so keep working/Stop; don't
@@ -516,6 +531,18 @@ export const ChatPage: React.FC = () => {
[sessionId, appendMessage, refreshQueue, markWorking],
);
+ // A quick-reply click sends the chosen label as a normal user turn, tagged with
+ // the agent message it answers so the group can lock + highlight the choice on
+ // reload (the answered state is derived from this metadata).
+ const handleQuickReply = useCallback(
+ // Send the chosen label as a normal user turn, tagged with the agent message
+ // it answers. The backend records the choice on THAT agent message (the
+ // message text is the label), so the lock derives from one authoritative
+ // field. Returns sendMessage's result so the group can unlock on a failed send.
+ (messageId: string, choice: string) => sendMessage(choice, undefined, { quick_reply_for: messageId }),
+ [sendMessage],
+ );
+
const stopMessage = useCallback(async () => {
if (!sessionId || !working) return;
try {
@@ -732,7 +759,7 @@ export const ChatPage: React.FC = () => {
</div>
)}
- <Transcript messages={messages} session={session} working={working} />
+ <Transcript messages={messages} session={session} working={working} onQuickReply={handleQuickReply} />
<QueueStrip queue={queue} onRemove={removeQueued} onSendNow={sendQueueNow} />
{/* key by session so the composer remounts per session — its draft-seeding
+ local value reset, instead of carrying across sessions (Codex P2). */}
@@ -927,9 +954,10 @@ interface TranscriptProps {
messages: WorkbenchMessage[];
session: WorkbenchSession;
working: boolean;
+ onQuickReply: (messageId: string, choice: string) => boolean | void | Promise<boolean | void>;
}
-const Transcript: React.FC<TranscriptProps> = ({ messages, session, working }) => {
+const Transcript: React.FC<TranscriptProps> = ({ messages, session, working, onQuickReply }) => {
const { t } = useTranslation();
const scrollRef = useRef<HTMLDivElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
@@ -1016,7 +1044,7 @@ const Transcript: React.FC<TranscriptProps> = ({ messages, session, working }) =
<div ref={scrollRef} onScroll={handleScroll} className="min-h-0 flex-1 overflow-y-auto px-4 py-5 md:px-8">
<div ref={contentRef} className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">
{messages.map((message) => (
- <MessageRow key={message.id} message={message} session={session} />
+ <MessageRow key={message.id} message={message} session={session} onQuickReply={onQuickReply} />
))}
{showThinking && <ThinkingBubble session={session} />}
</div>
@@ -1097,7 +1125,11 @@ const harnessLabel = (kind: string | null | undefined, t: (k: string) => string)
}
};
-const MessageRow: React.FC<{ message: WorkbenchMessage; session: WorkbenchSession }> = ({ message, session }) => {
+const MessageRow: React.FC<{
+ message: WorkbenchMessage;
+ session: WorkbenchSession;
+ onQuickReply?: (messageId: string, choice: string) => boolean | void | Promise<boolean | void>;
+}> = ({ message, session, onQuickReply }) => {
const { t } = useTranslation();
// Harness rows are collapsed by default; this tracks the per-row expand state.
const [expanded, setExpanded] = useState(false);
@@ -1116,7 +1148,6 @@ const MessageRow: React.FC<{ message: WorkbenchMessage; session: WorkbenchSessio
// is rewritten inline into the text instead, handled by the Markdown renderer).
const rawAttachments = (message.content as { attachments?: Array<Record<string, unknown>> })?.attachments;
const messageAttachments = Array.isArray(rawAttachments) ? rawAttachments : [];
-
const attachmentsNode = messageAttachments.length > 0 ? (
<div className="mt-2 flex flex-col gap-2">
{messageAttachments.map((att, i) => {
@@ -1138,6 +1169,26 @@ const MessageRow: React.FC<{ message: WorkbenchMessage; session: WorkbenchSessio
</div>
) : null;
+ // Agent quick-reply buttons: the options AND the chosen answer both live on
+ // THIS message's ``content`` (parsed server-side; the chosen answer recorded on
+ // the same message is the single source of truth for the lock — no correlating
+ // a separate user reply). IM channels render native buttons from the same parse.
+ const qr = isAgent
+ ? (message.content as { quick_replies?: unknown; quick_reply_chosen?: unknown } | null)
+ : null;
+ const quickReplyOptions = Array.isArray(qr?.quick_replies)
+ ? qr!.quick_replies.filter((x): x is string => typeof x === 'string' && x.length > 0)
+ : [];
+ const quickReplyChosen = typeof qr?.quick_reply_chosen === 'string' ? qr.quick_reply_chosen : null;
+ const quickRepliesNode =
+ quickReplyOptions.length > 0 && onQuickReply ? (
+ <QuickReplies
+ options={quickReplyOptions}
+ chosen={quickReplyChosen}
+ onChoose={(choice) => onQuickReply(message.id, choice)}
+ />
+ ) : null;
+
// Agent / system replies are markdown; the user's own and harness-triggered
// prompts are shown verbatim as typed/sent.
const bodyNode = message.text ? (
@@ -1239,6 +1290,7 @@ const MessageRow: React.FC<{ message: WorkbenchMessage; session: WorkbenchSessio
{bodyNode}
{attachmentsNode}
</div>
+ {quickRepliesNode}
{time}
</div>
</div>
diff --git a/ui/src/components/workbench/QuickReplies.tsx b/ui/src/components/workbench/QuickReplies.tsx
new file mode 100644
index 000000000..5c18ba6de
--- /dev/null
+++ b/ui/src/components/workbench/QuickReplies.tsx
@@ -0,0 +1,68 @@
+import * as React from 'react';
+import { Check } from 'lucide-react';
+import clsx from 'clsx';
+
+import { Button } from '../ui/button';
+
+// Quick-reply buttons under an agent message — the workbench counterpart of the
+// IM channels' quick replies (parsed from the same trailing ``---\n[label]…``
+// block; see core/reply_enhancer). Clicking one sends its label as a user
+// message and LOCKS the group: the chosen button highlights (mint + ✓), the rest
+// grey out and stop responding. ``chosen`` is the answer recorded on THIS agent
+// message (``content.quick_reply_chosen``) — the single source of truth, so the
+// locked state survives reload and is immune to how the user reply is queued or
+// merged; a local click also locks instantly. There is no "only the latest
+// message is clickable" gate — an older unanswered group stays clickable
+// (deferred by product; see docs/plans/workbench-quick-replies.md).
+export const QuickReplies: React.FC<{
+ options: string[];
+ chosen?: string | null;
+ onChoose: (choice: string) => boolean | void | Promise<boolean | void>;
+}> = ({ options, chosen, onChoose }) => {
+ const [clicked, setClicked] = React.useState<string | null>(null);
+ const selected = clicked ?? chosen ?? null;
+ const locked = selected !== null;
+
+ // Once the authoritative answer arrives (``chosen`` loaded from the agent
+ // message), drop the optimistic lock and let ``chosen`` own the displayed state
+ // so the two never diverge.
+ React.useEffect(() => {
+ if (chosen) setClicked(null);
+ }, [chosen]);
+
+ return (
+ <div className="mt-2 flex flex-wrap gap-2">
+ {options.map((opt, i) => {
+ const isChosen = locked && opt === selected;
+ return (
+ <Button
+ key={`${i}-${opt}`}
+ type="button"
+ variant="secondary"
+ size="sm"
+ disabled={locked}
+ aria-pressed={isChosen}
+ onClick={() => {
+ if (locked) return;
+ setClicked(opt); // optimistic lock
+ // …but if the send never started (network/403), unlock so the user
+ // can retry — there's no other retry path until reload.
+ void Promise.resolve(onChoose(opt)).then((ok) => {
+ if (ok === false) setClicked(null);
+ });
+ }}
+ // Chosen stays full-strength (override the base disabled fade) and
+ // goes mint; the others ride the base ``disabled:opacity-50`` to grey.
+ className={clsx(
+ 'h-auto gap-1.5 whitespace-normal rounded-lg px-3 py-1.5 text-[13px] font-normal',
+ isChosen && 'border-mint/55 bg-mint/15 text-mint hover:bg-mint/15 disabled:opacity-100',
+ )}
+ >
+ {isChosen && <Check className="size-3.5" />}
+ {opt}
+ </Button>
+ );
+ })}
+ </div>
+ );
+};
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 424d1ba0c..aed6a17a4 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3572,11 +3572,21 @@ async def sessions_messages_create(session_id: str):
content = payload.get("content")
if text is None and not content:
return jsonify({"error": "text or content is required"}), 400
+ # A quick-reply click tags the row with the agent message it answers.
+ quick_reply_for = (payload.get("metadata") or {}).get("quick_reply_for")
engine = _projects_engine()
try:
with engine.connect() as conn:
session = workbench_sessions_service.get_session(conn, session_id)
+ # Idempotency: a stale or duplicate quick-reply submit (a second tab, or
+ # one that missed the message.new event) must not start a second turn
+ # for an already-answered group. The answer lives on the agent message.
+ if (
+ quick_reply_for
+ and messages_service.get_quick_reply_chosen(conn, session_id, quick_reply_for) is not None
+ ):
+ return jsonify({"already_answered": True}), 200
except LookupError as err:
return jsonify({"error": str(err)}), 404
@@ -3621,7 +3631,10 @@ async def sessions_messages_create(session_id: str):
author_id=payload.get("author_id"),
author_name=payload.get("author_name"),
)
- messages_service.clear_draft(conn, session_id)
+ # A quick-reply click is a side action, not the user submitting their
+ # composer text — keep any saved draft intact for it.
+ if not quick_reply_for:
+ messages_service.clear_draft(conn, session_id)
workbench_sessions_service.touch_session(conn, session_id)
return row
@@ -3693,6 +3706,13 @@ async def sessions_messages_create(session_id: str):
return jsonify({**published, "dispatch_error": "dispatch_failed", "detail": str(exc)}), 502
status = result.get("status_code", 500)
body = result.get("body") or {}
+ # Quick-reply accepted (turn started OR queued) → record the choice on the
+ # AGENT message as the single source of truth for the locked/answered state.
+ # Only on success, so a failed click stays retriable; ``set_quick_reply_chosen``
+ # is set-once, so a rare double-dispatch still records one consistent answer.
+ if status == 202 and quick_reply_for:
+ with engine.begin() as conn:
+ messages_service.set_quick_reply_chosen(conn, session_id, quick_reply_for, dispatch_text)
if status == 202 and body.get("queued"):
# Enqueued behind a running turn: the controller already promoted the
# row pending→queued, so it stays OUT of the transcript (no