Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5149: add agent-generated Chat quick actions (#5766)

Jiayuan Zhang0fdc38704edc
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
index 2fb248d9c4..5f43d6f01a 100644
--- a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
@@ -239,7 +239,11 @@ export default function ChatTab() {
);
const handleSend = useCallback(
- async (content: string, attachmentIds: string[] = []) => {
+ async (
+ content: string,
+ attachmentIds: string[] = [],
+ options: { clearDraft?: boolean } = {},
+ ) => {
if (!currentAgent) return;
const isNewSession = !activeSessionId;
@@ -278,7 +282,9 @@ export default function ChatTab() {
created_at: result.created_at,
});
qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
- clearDraft(sessionId);
+ if (options.clearDraft !== false) {
+ clearDraft(sessionId);
+ }
} catch (err) {
qc.setQueryData<ChatMessage[]>(chatKeys.messages(sessionId), (old) =>
old ? old.filter((m) => m.id !== optimistic.id) : old,
@@ -397,6 +403,10 @@ export default function ChatTab() {
hasSessions={sessions.length > 0}
agentName={currentAgent?.name}
onPickPrompt={(text) => setDraft(draftKey, text)}
+ onQuickAction={(action) =>
+ handleSend(action.prompt, [], { clearDraft: false })
+ }
+ quickActionsDisabled={sending || disabled}
pendingTask={pendingTask}
liveTaskMessages={liveTaskMessages}
availability={presenceAvailability}
diff --git a/apps/mobile/components/chat/chat-message-list.tsx b/apps/mobile/components/chat/chat-message-list.tsx
index d391f1459a..e1558121cc 100644
--- a/apps/mobile/components/chat/chat-message-list.tsx
+++ b/apps/mobile/components/chat/chat-message-list.tsx
@@ -40,6 +40,7 @@
* `startRenderingFromBottom` (initial paint at bottom, no setTimeout
* hacks). Cell recycling also keeps scroll-up smooth.
*/
+import { useState } from "react";
import { ActivityIndicator, Pressable, View } from "react-native";
import { FlashList } from "@shopify/flash-list";
import { Ionicons } from "@expo/vector-icons";
@@ -47,6 +48,7 @@ import { useQuery } from "@tanstack/react-query";
import type {
ChatMessage,
ChatPendingTask,
+ ChatQuickAction,
TaskMessagePayload,
} from "@multica/core/types";
import type { AgentAvailability } from "@multica/core/agents";
@@ -82,6 +84,9 @@ interface Props {
* (or focuses the composer with the text) — empty state stays neutral
* about send vs. preview. */
onPickPrompt: (text: string) => void;
+ /** Send a persisted assistant follow-up without first copying it into draft. */
+ onQuickAction?: (action: ChatQuickAction) => void | Promise<unknown>;
+ quickActionsDisabled?: boolean;
/** Server-authoritative pending-task snapshot for the active session.
* Used to render the live timeline + status line as the last item in
* the message stream, mirroring web's
@@ -101,6 +106,8 @@ export function ChatMessageList({
hasSessions,
agentName,
onPickPrompt,
+ onQuickAction,
+ quickActionsDisabled = false,
pendingTask,
liveTaskMessages,
availability,
@@ -172,7 +179,13 @@ export function ChatMessageList({
key={messages[0]?.id ?? "empty"}
data={messages}
keyExtractor={(m) => m.id}
- renderItem={({ item }) => <MessageRow message={item} />}
+ renderItem={({ item }) => (
+ <MessageRow
+ message={item}
+ onQuickAction={onQuickAction}
+ quickActionsDisabled={quickActionsDisabled}
+ />
+ )}
ItemSeparatorComponent={MessageSeparator}
ListFooterComponent={
showLiveSection ? (
@@ -226,7 +239,15 @@ function MessageSeparator() {
return <View style={{ height: 12 }} />;
}
-function MessageRow({ message }: { message: ChatMessage }) {
+function MessageRow({
+ message,
+ onQuickAction,
+ quickActionsDisabled,
+}: {
+ message: ChatMessage;
+ onQuickAction?: (action: ChatQuickAction) => void | Promise<unknown>;
+ quickActionsDisabled: boolean;
+}) {
const isUser = message.role === "user";
const isFailure = !!message.failure_reason;
const isSelecting = useChatSelectStore(
@@ -294,6 +315,8 @@ function MessageRow({ message }: { message: ChatMessage }) {
message={message}
isSelecting={isSelecting}
longPress={longPress}
+ onQuickAction={onQuickAction}
+ quickActionsDisabled={quickActionsDisabled}
/>
);
}
@@ -316,10 +339,14 @@ function AssistantRow({
message,
isSelecting,
longPress,
+ onQuickAction,
+ quickActionsDisabled,
}: {
message: ChatMessage;
isSelecting: boolean;
longPress: ReturnType<typeof useChatMessageLongPress>;
+ onQuickAction?: (action: ChatQuickAction) => void | Promise<unknown>;
+ quickActionsDisabled: boolean;
}) {
// Read the cached timeline if any. `enabled` (in taskMessagesOptions) is
// gated on isTaskMessageTaskId — optimistic id prefixes never fetch, so
@@ -366,12 +393,87 @@ function AssistantRow({
) : null}
</View>
);
- if (isSelecting) return body;
- return (
+ const messageBody = isSelecting ? body : (
<Pressable onLongPress={longPress.onLongPress} delayLongPress={500}>
{body}
</Pressable>
);
+ if (!onQuickAction || (message.quick_actions?.length ?? 0) === 0) {
+ return messageBody;
+ }
+ return (
+ <View className="gap-2">
+ {messageBody}
+ <QuickActions
+ actions={message.quick_actions ?? []}
+ disabled={quickActionsDisabled}
+ onSelect={onQuickAction}
+ />
+ </View>
+ );
+}
+
+function QuickActions({
+ actions,
+ disabled,
+ onSelect,
+}: {
+ actions: ChatQuickAction[];
+ disabled: boolean;
+ onSelect: (action: ChatQuickAction) => void | Promise<unknown>;
+}) {
+ const [submitting, setSubmitting] = useState(false);
+ const blocked = disabled || submitting;
+
+ const handleSelect = async (action: ChatQuickAction) => {
+ if (blocked) return;
+ setSubmitting(true);
+ try {
+ await onSelect(action);
+ } catch {
+ // The send path rolls back its optimistic message. Keep the action usable
+ // so a transient request failure can be retried.
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ <View
+ className="flex-row flex-wrap gap-2 pt-0.5"
+ accessibilityLabel="Suggested follow-ups"
+ >
+ {actions.slice(0, 3).map((action, index) => (
+ <Pressable
+ key={`${action.label}-${index}`}
+ accessibilityRole="button"
+ accessibilityState={{ disabled: blocked }}
+ disabled={blocked}
+ onPress={() => void handleSelect(action)}
+ className={cn(
+ "min-h-10 max-w-full flex-row items-center gap-1 rounded-full border px-3 active:opacity-70",
+ action.primary
+ ? "border-primary/30 bg-primary/10"
+ : "border-border bg-background",
+ blocked && "opacity-50",
+ )}
+ >
+ <Text
+ numberOfLines={1}
+ className={cn(
+ "shrink text-sm font-medium",
+ action.primary ? "text-primary" : "text-foreground",
+ )}
+ >
+ {action.label}
+ </Text>
+ {action.primary ? (
+ <Text className="text-sm font-medium text-primary">↗</Text>
+ ) : null}
+ </Pressable>
+ ))}
+ </View>
+ );
}
// Persistent caption rendered under the assistant bubble / failure bubble
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.test.ts b/apps/mobile/data/realtime/chat-ws-updaters.test.ts
index f20b1169c6..480a270591 100644
--- a/apps/mobile/data/realtime/chat-ws-updaters.test.ts
+++ b/apps/mobile/data/realtime/chat-ws-updaters.test.ts
@@ -1,13 +1,20 @@
import { describe, expect, it, vi } from "vitest";
-import { QueryClient } from "@tanstack/react-query";
-import type { ChatDonePayload, ChatMessage } from "@multica/core/types";
+import { QueryClient, QueryObserver } from "@tanstack/react-query";
+import type {
+ ChatDonePayload,
+ ChatMessage,
+ ChatQuickActionsPayload,
+} from "@multica/core/types";
// chat-ws-updaters imports chatKeys from data/queries/chat, which transitively
// imports the native fetch client. Mock it so the Node test never loads RN
// modules — chatKeys itself is a pure key factory and needs nothing from api.
vi.mock("@/data/api", () => ({ api: {} }));
-import { applyChatDoneToCache } from "./chat-ws-updaters";
+import {
+ applyChatDoneToCache,
+ applyChatQuickActionsToCache,
+} from "./chat-ws-updaters";
import { chatKeys } from "@/data/queries/chat";
const SESSION = "session-1";
@@ -61,6 +68,20 @@ describe("applyChatDoneToCache", () => {
});
});
+ it("carries quick actions into the instant mobile bubble", () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(SESSION), []);
+ const quickActions = [
+ { label: "Build a checklist", prompt: "Build the complete checklist", primary: true },
+ ];
+
+ applyChatDoneToCache(qc, donePayload({ quick_actions: quickActions }));
+
+ expect(
+ qc.getQueryData<ChatMessage[]>(chatKeys.messages(SESSION))?.[0]?.quick_actions,
+ ).toEqual(quickActions);
+ });
+
it("does not duplicate an echoed message on reconnect", () => {
const qc = new QueryClient();
const existing: ChatMessage = {
@@ -78,3 +99,120 @@ describe("applyChatDoneToCache", () => {
expect(qc.getQueryData<ChatMessage[]>(chatKeys.messages(SESSION))).toHaveLength(1);
});
});
+
+function assistantMsg(over: Partial<ChatMessage> = {}): ChatMessage {
+ return {
+ id: "msg-1",
+ chat_session_id: SESSION,
+ role: "assistant",
+ content: "here is the plan",
+ task_id: "task-1",
+ created_at: "2026-07-09T00:00:00Z",
+ ...over,
+ };
+}
+
+function quickActionsPayload(
+ over: Partial<ChatQuickActionsPayload> = {},
+): ChatQuickActionsPayload {
+ return {
+ chat_session_id: SESSION,
+ task_id: "task-1",
+ message_id: "msg-1",
+ quick_actions: [
+ { label: "Draft it", prompt: "Draft the complete plan", primary: true },
+ ],
+ ...over,
+ };
+}
+
+describe("applyChatQuickActionsToCache", () => {
+ it("patches the async supplement onto the targeted assistant message", async () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(SESSION), [assistantMsg()]);
+
+ await applyChatQuickActionsToCache(qc, quickActionsPayload());
+
+ expect(
+ qc.getQueryData<ChatMessage[]>(chatKeys.messages(SESSION))?.[0]?.quick_actions,
+ ).toEqual([
+ { label: "Draft it", prompt: "Draft the complete plan", primary: true },
+ ]);
+ });
+
+ it("only patches the message whose id matches, leaving others untouched", async () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(SESSION), [
+ assistantMsg({ id: "msg-0", content: "earlier turn" }),
+ assistantMsg(),
+ ]);
+
+ await applyChatQuickActionsToCache(qc, quickActionsPayload());
+
+ const msgs = qc.getQueryData<ChatMessage[]>(chatKeys.messages(SESSION));
+ expect(msgs?.[0]?.quick_actions).toBeUndefined();
+ expect(msgs?.[1]?.quick_actions).toHaveLength(1);
+ });
+
+ it("empty supplement is a terminal no-op (no chips added)", async () => {
+ const qc = new QueryClient();
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(SESSION), [assistantMsg()]);
+
+ await applyChatQuickActionsToCache(qc, quickActionsPayload({ quick_actions: [] }));
+
+ expect(
+ qc.getQueryData<ChatMessage[]>(chatKeys.messages(SESSION))?.[0]?.quick_actions,
+ ).toBeUndefined();
+ });
+
+ // Regression (MUL-5149): the chat:done invalidate can leave a messages
+ // refetch in flight that read the row before the actions were persisted. If
+ // it resolves AFTER the supplement patch, it must not overwrite the patched
+ // actions — the supplement cancels the in-flight refetch first. staleTime is
+ // Infinity, so an overwrite would be permanent.
+ it("a stale chat:done refetch resolving after the supplement cannot overwrite it", async () => {
+ const qc = new QueryClient();
+ // Settled post-chat:done state: assistant present, no actions yet.
+ const staleRows = [assistantMsg()];
+ qc.setQueryData<ChatMessage[]>(chatKeys.messages(SESSION), staleRows);
+
+ // An active observer (a mounted chat screen) whose refetch we hold open, so
+ // it is genuinely in flight when the supplement lands.
+ let releaseRefetch: ((rows: ChatMessage[]) => void) | undefined;
+ const observer = new QueryObserver<ChatMessage[]>(qc, {
+ queryKey: chatKeys.messages(SESSION),
+ queryFn: () =>
+ new Promise<ChatMessage[]>((resolve) => {
+ releaseRefetch = resolve;
+ }),
+ staleTime: Infinity,
+ gcTime: Infinity,
+ retry: false,
+ });
+ const unsub = observer.subscribe(() => {});
+
+ // chat:done's invalidate kicks off the refetch (not awaited — it is held).
+ void qc.invalidateQueries({ queryKey: chatKeys.messages(SESSION) });
+ await vi.waitFor(() => {
+ expect(qc.getQueryState(chatKeys.messages(SESSION))?.fetchStatus).toBe(
+ "fetching",
+ );
+ expect(typeof releaseRefetch).toBe("function");
+ });
+
+ await applyChatQuickActionsToCache(qc, quickActionsPayload());
+
+ // The now-cancelled refetch finally resolves with the actions-less rows.
+ releaseRefetch?.(staleRows);
+ await vi.waitFor(() => {
+ expect(qc.getQueryState(chatKeys.messages(SESSION))?.fetchStatus).toBe("idle");
+ });
+
+ expect(
+ qc.getQueryData<ChatMessage[]>(chatKeys.messages(SESSION))?.[0]?.quick_actions,
+ ).toEqual([
+ { label: "Draft it", prompt: "Draft the complete plan", primary: true },
+ ]);
+ unsub();
+ });
+});
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.ts
index b1a286e1db..e76561a5c4 100644
--- a/apps/mobile/data/realtime/chat-ws-updaters.ts
+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts
@@ -24,6 +24,7 @@ import type {
ChatDonePayload,
ChatMessage,
ChatPendingTask,
+ ChatQuickActionsPayload,
ChatSession,
ChatSessionDeletedPayload,
TaskMessagePayload,
@@ -113,12 +114,16 @@ export function applyChatDoneToCache(
qc: QueryClient,
payload: ChatDonePayload,
) {
- if (payload.message_id && payload.content != null && payload.created_at) {
+ if (
+ payload.message_id &&
+ (payload.content != null || (payload.quick_actions?.length ?? 0) > 0) &&
+ payload.created_at
+ ) {
const assistantMsg: ChatMessage = {
id: payload.message_id,
chat_session_id: payload.chat_session_id,
role: "assistant",
- content: payload.content,
+ content: payload.content ?? "",
task_id: payload.task_id,
created_at: payload.created_at,
elapsed_ms: payload.elapsed_ms ?? null,
@@ -126,6 +131,9 @@ export function applyChatDoneToCache(
// renders its notice inline; missing → "message" for older servers
// (MUL-4351).
message_kind: payload.message_kind ?? "message",
+ ...(payload.quick_actions !== undefined
+ ? { quick_actions: payload.quick_actions }
+ : {}),
};
qc.setQueryData<ChatMessage[]>(
chatKeys.messages(payload.chat_session_id),
@@ -147,6 +155,52 @@ export function applyChatDoneToCache(
qc.setQueryData(chatKeys.pendingTask(payload.chat_session_id), {});
}
+/**
+ * Apply a `chat:quick_actions` supplement to the messages cache.
+ *
+ * The daemon generates quick actions in a background pass AFTER the turn
+ * finishes, so they arrive on their own event well after `chat:done` already
+ * invalidated + refetched the messages list (which came back with none). With
+ * `staleTime: Infinity` nothing refetches again, so without this patch an
+ * active mobile session would never render async-generated quick actions until
+ * a manual pull-to-refresh or refocus.
+ *
+ * Patch the identified assistant message's `quick_actions` in place. The
+ * payload's list is already server-validated, so — like web — this only
+ * patches; no invalidate (mobile's cellular "patch over invalidate" rule). An
+ * empty/missing list is terminal ("no suggestions this turn") and a no-op:
+ * the message already renders no chips.
+ *
+ * Mirrors web's `applyChatQuickActionsToCache` in
+ * packages/core/realtime/use-realtime-sync.ts. Mobile has a single flat
+ * messages cache and no pending-placeholder marker, so it patches only that
+ * one cache.
+ */
+export async function applyChatQuickActionsToCache(
+ qc: QueryClient,
+ payload: ChatQuickActionsPayload,
+) {
+ const actions = payload.quick_actions ?? [];
+ if (actions.length === 0) return;
+ // chat:done's invalidate may still have a messages refetch in flight that
+ // read the assistant row BEFORE the daemon persisted these actions. Cancel it
+ // first so its actions-less response can't land after — and overwrite — the
+ // patch below. The messages query is staleTime: Infinity, so such an overwrite
+ // would never self-heal (MUL-5149 stale-refetch race). Cancel before
+ // setQueryData: cancelQueries reverts to the pre-fetch state, so patching
+ // first would be undone by the revert.
+ await qc.cancelQueries({
+ queryKey: chatKeys.messages(payload.chat_session_id),
+ });
+ qc.setQueryData<ChatMessage[]>(
+ chatKeys.messages(payload.chat_session_id),
+ (old) =>
+ old?.map((m) =>
+ m.id === payload.message_id ? { ...m, quick_actions: actions } : m,
+ ),
+ );
+}
+
// =====================================================
// Pending task (ChatPendingTask keyed by sessionId)
// =====================================================
diff --git a/apps/mobile/data/realtime/use-chat-session-realtime.ts b/apps/mobile/data/realtime/use-chat-session-realtime.ts
index f687f9bf5c..60f539701d 100644
--- a/apps/mobile/data/realtime/use-chat-session-realtime.ts
+++ b/apps/mobile/data/realtime/use-chat-session-realtime.ts
@@ -9,6 +9,8 @@
* Events handled:
* - chat:message → invalidate messages + pendingTask
* - chat:done → patch messages inline + clear pendingTask
+ * - chat:quick_actions → patch the async quick-actions supplement
+ * onto the assistant message
* - task:queued / dispatch → seed / promote pendingTask
* - task:cancelled → clear pendingTask
* - task:completed → no-op for messages (chat:done already
@@ -28,6 +30,7 @@ import { useWSSubscriptions } from "@/lib/use-ws-subscriptions";
import {
appendTaskMessage,
applyChatDoneToCache,
+ applyChatQuickActionsToCache,
clearPendingTask,
promotePendingTaskToRunning,
seedPendingTaskFromQueued,
@@ -64,6 +67,13 @@ export function useChatSessionRealtime(
if (!isMine(payload)) return;
applyChatDoneToCache(qc, payload);
}),
+ // The daemon's background suggestion pass lands here, after chat:done
+ // already refetched an actions-less message list. Patch the actions in
+ // directly — staleTime is Infinity, so nothing would refetch them.
+ ws.on("chat:quick_actions", (payload) => {
+ if (!isMine(payload)) return;
+ void applyChatQuickActionsToCache(qc, payload);
+ }),
ws.on("task:queued", (payload) => {
if (!isMine(payload)) return;
seedPendingTaskFromQueued(qc, payload);
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index 6a7c7536ba..41f2671742 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -279,6 +279,15 @@ export const ChatMessageSchema: z.ZodType<ChatMessage> = z.object({
attachments: z.array(AttachmentSchema).optional(),
failure_reason: z.string().nullable().optional(),
elapsed_ms: z.number().nullable().optional(),
+ message_kind: z.enum(["message", "no_response"]).catch("message").optional(),
+ // One malformed optional suggestion must not erase an otherwise valid
+ // conversation. The server validates these too; this is mixed-version and
+ // corrupted-cache defense at the mobile boundary.
+ quick_actions: z.array(z.object({
+ label: z.string(),
+ prompt: z.string(),
+ primary: z.boolean().optional(),
+ }).loose()).catch([]).optional().default([]),
}).loose();
export const ChatMessageListSchema = z.array(ChatMessageSchema).default([]);
diff --git a/e2e/quick-actions.spec.ts b/e2e/quick-actions.spec.ts
new file mode 100644
index 0000000000..429bcc4cd4
--- /dev/null
+++ b/e2e/quick-actions.spec.ts
@@ -0,0 +1,152 @@
+import "./env";
+
+import { expect, test } from "@playwright/test";
+import pg from "pg";
+
+import { createTestApi } from "./helpers";
+import type { TestApiClient } from "./fixtures";
+
+const DATABASE_URL =
+ process.env.DATABASE_URL ??
+ "postgres://multica:multica@localhost:5432/multica?sslmode=disable";
+
+test("renders assistant quick actions and sends the hidden prompt", async ({
+ page,
+}) => {
+ const api: TestApiClient = await createTestApi();
+ const db = new pg.Client(DATABASE_URL);
+ await db.connect();
+
+ let sessionId: string | null = null;
+ let agentId: string | null = null;
+ let runtimeId: string | null = null;
+
+ try {
+ const workspace = (await api.getWorkspaces())[0];
+ if (!workspace) throw new Error("E2E workspace missing");
+ api.setWorkspaceId(workspace.id);
+ api.setWorkspaceSlug(workspace.slug);
+
+ const user = await db.query<{ id: string }>(
+ `SELECT id::text FROM "user" WHERE email = $1 LIMIT 1`,
+ [api.getEmail()],
+ );
+ const userId = user.rows[0]?.id;
+ if (!userId) throw new Error("E2E user missing");
+
+ const runtime = await db.query<{ id: string }>(
+ `INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider, status,
+ device_info, metadata, last_seen_at
+ )
+ VALUES ($1, NULL, $2, 'cloud', 'e2e_quick_actions', 'online', $3, '{}'::jsonb, now())
+ RETURNING id::text`,
+ [workspace.id, `Quick actions ${Date.now()}`, "Quick actions E2E"],
+ );
+ runtimeId = runtime.rows[0]!.id;
+
+ const agent = await db.query<{ id: string }>(
+ `INSERT INTO agent (
+ workspace_id, name, description, instructions, runtime_mode,
+ runtime_config, runtime_id, visibility, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, 'Launch Copilot', 'Plans focused launches', '', 'cloud',
+ '{}'::jsonb, $2, 'workspace', 1, $3)
+ RETURNING id::text`,
+ [workspace.id, runtimeId, userId],
+ );
+ agentId = agent.rows[0]!.id;
+
+ const session = await db.query<{ id: string }>(
+ `INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)
+ VALUES ($1, $2, $3, 'Plan a focused launch', 'active')
+ RETURNING id::text`,
+ [workspace.id, agentId, userId],
+ );
+ sessionId = session.rows[0]!.id;
+
+ await db.query(
+ `INSERT INTO chat_message (
+ chat_session_id, role, content, created_at, quick_actions
+ )
+ VALUES
+ ($1, 'user', 'Help me plan a focused product launch.', now() - interval '1 second', '[]'::jsonb),
+ ($1, 'assistant', $2, now(), $3::jsonb)`,
+ [
+ sessionId,
+ "Start with one audience, one promise, and one proof point. Then build a two-week launch around a single measurable activation goal.",
+ JSON.stringify([
+ {
+ label: "Draft the launch brief",
+ prompt:
+ "Draft a focused launch brief with one audience, one promise, one proof point, and one activation goal.",
+ primary: true,
+ },
+ {
+ label: "Build the two-week checklist",
+ prompt: "Build a detailed two-week checklist for this launch.",
+ },
+ {
+ label: "Define the activation metric",
+ prompt: "Define a measurable activation metric for this launch.",
+ },
+ ]),
+ ],
+ );
+
+ const token = api.getToken();
+ if (!token) throw new Error("E2E token missing");
+ await page.addInitScript(
+ ({ authToken, activeSessionId }) => {
+ localStorage.setItem("multica_token", authToken);
+ localStorage.setItem("multica:chat:activeSessionId", activeSessionId);
+ localStorage.setItem("multica:chat:isOpen", "false");
+ },
+ { authToken: token, activeSessionId: sessionId },
+ );
+
+ await page.setViewportSize({ width: 1440, height: 960 });
+ await page.goto(`/${workspace.slug}/chat?session=${sessionId}`, {
+ waitUntil: "domcontentloaded",
+ });
+
+ const primaryAction = page.getByRole("button", {
+ name: "Draft the launch brief",
+ });
+ await expect(primaryAction).toBeVisible({ timeout: 30_000 });
+ await expect(
+ page.getByRole("button", { name: "Build the two-week checklist" }),
+ ).toBeVisible();
+ await expect(
+ page.getByRole("button", { name: "Define the activation metric" }),
+ ).toBeVisible();
+
+ if (process.env.QUICK_ACTIONS_SCREENSHOT_PATH) {
+ await page.screenshot({
+ path: process.env.QUICK_ACTIONS_SCREENSHOT_PATH,
+ fullPage: true,
+ });
+ }
+
+ await primaryAction.click();
+ await expect(
+ page.getByText(
+ "Draft a focused launch brief with one audience, one promise, one proof point, and one activation goal.",
+ { exact: true },
+ ),
+ ).toBeVisible({ timeout: 15_000 });
+ await expect(primaryAction).toBeDisabled();
+ } finally {
+ if (sessionId) {
+ await db.query(`DELETE FROM agent_task_queue WHERE chat_session_id = $1`, [
+ sessionId,
+ ]);
+ await db.query(`DELETE FROM chat_session WHERE id = $1`, [sessionId]);
+ }
+ if (agentId) await db.query(`DELETE FROM agent WHERE id = $1`, [agentId]);
+ if (runtimeId)
+ await db.query(`DELETE FROM agent_runtime WHERE id = $1`, [runtimeId]);
+ await db.end();
+ await api.cleanup();
+ }
+});
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 41ff193dc1..631ec5e8d7 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -1183,8 +1183,26 @@ describe("ApiClient", () => {
it("falls back to the legacy full-list endpoint when the paged route 404s", async () => {
const legacy = [
- { id: "m1", role: "user", content: "hi", created_at: "2026-06-01T00:00:00Z" },
- { id: "m2", role: "assistant", content: "yo", created_at: "2026-06-01T00:00:01Z" },
+ {
+ id: "m1",
+ chat_session_id: "session-1",
+ role: "user",
+ content: "hi",
+ task_id: null,
+ created_at: "2026-06-01T00:00:00Z",
+ quick_actions: [],
+ },
+ {
+ id: "m2",
+ chat_session_id: "session-1",
+ role: "assistant",
+ content: "yo",
+ task_id: "task-1",
+ created_at: "2026-06-01T00:00:01Z",
+ quick_actions: [
+ { label: "Continue", prompt: "Continue with the next step", primary: true },
+ ],
+ },
];
const fetchMock = vi
.fn()
@@ -1205,6 +1223,36 @@ describe("ApiClient", () => {
expect(page).toEqual({ messages: legacy, limit: 50, has_more: false, next_cursor: null });
});
+ it("keeps a valid reply when its optional quick actions are malformed", async () => {
+ const malformed = [{
+ id: "m1",
+ chat_session_id: "session-1",
+ role: "assistant",
+ content: "safe reply",
+ task_id: "task-1",
+ created_at: "2026-06-01T00:00:00Z",
+ quick_actions: [{ label: 42, prompt: false }],
+ }];
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse(malformed, 200)));
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.listChatMessages("session-1")).resolves.toEqual([
+ expect.objectContaining({ content: "safe reply", quick_actions: [] }),
+ ]);
+ });
+
+ it("falls back to an empty page for a malformed paged response", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(jsonResponse({ messages: "broken" }, 200)),
+ );
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(
+ client.listChatMessagesPage("session-1", { limit: 25 }),
+ ).resolves.toEqual({ messages: [], limit: 25, has_more: false, next_cursor: null });
+ });
+
it("does NOT fall back on a cursor request — a 404 there propagates", async () => {
const fetchMock = vi
.fn()
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 5dbb8fbbbc..1e8677b825 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -187,6 +187,8 @@ import {
AttachmentResponseSchema,
CancelTaskResponseSchema,
ChatDraftRestoresResponseSchema,
+ ChatMessageListSchema,
+ ChatMessagesPageSchema,
ChildIssuesResponseSchema,
CommentsListSchema,
CommentTriggerPreviewSchema,
@@ -207,6 +209,7 @@ import {
EMPTY_AGENT_TEMPLATE_SUMMARY_LIST,
EMPTY_APP_CONFIG,
EMPTY_ATTACHMENT,
+ EMPTY_CHAT_MESSAGE_LIST,
EMPTY_CLOUD_RUNTIME_NODE,
EMPTY_CLOUD_RUNTIME_NODE_LIST,
EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE,
@@ -2204,6 +2207,26 @@ export class ApiClient {
await this.fetch(`/api/chat/sessions/${id}`, { method: "DELETE" });
}
+ // Refresh the quick-action suggestions for a session's latest assistant turn.
+ // Fire-and-forget: the server enqueues a background regeneration pass and the
+ // refreshed pills arrive over the chat:quick_actions realtime event, so the
+ // caller anchors its pending placeholder on the turn it already knows rather
+ // than on this response.
+ // Refresh the quick actions for the given assistant turn. Sends the message
+ // id the caller is refreshing so the server can atomically confirm it is still
+ // the session's latest turn (409 otherwise) — that keeps the client's pending
+ // marker aligned with the turn chat:quick_actions will resolve, with no
+ // response reconciliation needed even under a WS-before-HTTP race (MUL-5149).
+ async regenerateChatQuickActions(
+ sessionId: string,
+ messageId: string,
+ ): Promise<void> {
+ await this.fetch(`/api/chat/sessions/${sessionId}/quick-actions/regenerate`, {
+ method: "POST",
+ body: JSON.stringify({ message_id: messageId }),
+ });
+ }
+
async updateChatSession(
id: string,
data: { title: string } | { project_id: string | null },
@@ -2245,7 +2268,10 @@ export class ApiClient {
}
async listChatMessages(sessionId: string): Promise<ChatMessage[]> {
- return this.fetch(`/api/chat/sessions/${sessionId}/messages`);
+ const raw: unknown = await this.fetch(`/api/chat/sessions/${sessionId}/messages`);
+ return parseWithFallback(raw, ChatMessageListSchema, EMPTY_CHAT_MESSAGE_LIST, {
+ endpoint: "GET /api/chat/sessions/:id/messages",
+ });
}
async listChatMessagesPage(
@@ -2259,9 +2285,17 @@ export class ApiClient {
query.set("before_id", params.before.id);
}
try {
- return await this.fetch(
+ const raw: unknown = await this.fetch(
`/api/chat/sessions/${sessionId}/messages/page?${query.toString()}`,
);
+ return parseWithFallback(
+ raw,
+ ChatMessagesPageSchema,
+ { messages: [], limit, has_more: false, next_cursor: null },
+ {
+ endpoint: "GET /api/chat/sessions/:id/messages/page",
+ },
+ );
} catch (err) {
// Deployment-order compatibility: a backend deployed before this endpoint
// existed returns 404 for the unknown route. Fall back to the legacy
@@ -2283,11 +2317,21 @@ export class ApiClient {
sessionId: string,
content: string,
attachmentIds?: string[],
+ options?: { quickActionsEnabled?: boolean },
): Promise<SendChatMessageResponse> {
- const body: { content: string; attachment_ids?: string[] } = { content };
+ const body: {
+ content: string;
+ attachment_ids?: string[];
+ quick_actions_enabled?: boolean;
+ } = { content };
if (attachmentIds && attachmentIds.length > 0) {
body.attachment_ids = attachmentIds;
}
+ // Only an explicit false is sent: absent means enabled server-side, so
+ // older payload shapes keep generating suggestions unchanged.
+ if (options?.quickActionsEnabled === false) {
+ body.quick_actions_enabled = false;
+ }
return this.fetch(`/api/chat/sessions/${sessionId}/messages`, {
method: "POST",
body: JSON.stringify(body),
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 9aeb1b41a8..47c9f74fc1 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -14,6 +14,7 @@ import type {
BillingTopupsPage,
BillingTransactionsPage,
CancelTaskResponse,
+ ChatMessage,
ChatDraftRestoresResponse,
Comment,
CreateAgentFromTemplateResponse,
@@ -402,6 +403,41 @@ const AttachmentSchema = z.object({
id: z.string(),
}).loose();
+const ChatQuickActionSchema = z.object({
+ label: z.string(),
+ prompt: z.string(),
+ primary: z.boolean().optional(),
+}).loose();
+
+export const ChatMessageSchema = z.object({
+ id: z.string(),
+ chat_session_id: z.string(),
+ role: z.enum(["user", "assistant"]).catch("assistant"),
+ content: z.string().default(""),
+ task_id: z.string().nullable().default(null),
+ created_at: z.string().default(""),
+ attachments: z.array(AttachmentSchema).optional(),
+ failure_reason: z.string().nullable().optional(),
+ elapsed_ms: z.number().nullable().optional(),
+ message_kind: z.enum(["message", "no_response"]).catch("message").optional(),
+ // Optional additive data degrades independently: a malformed suggestion
+ // must not hide the assistant reply that contains it.
+ quick_actions: z.array(ChatQuickActionSchema).catch([]).optional().default([]),
+}).loose();
+
+export const ChatMessageListSchema = z.array(ChatMessageSchema).default([]);
+export const EMPTY_CHAT_MESSAGE_LIST: ChatMessage[] = [];
+
+export const ChatMessagesPageSchema = z.object({
+ messages: z.array(ChatMessageSchema).default([]),
+ limit: z.number().default(50),
+ has_more: z.boolean().default(false),
+ next_cursor: z.object({
+ created_at: z.string(),
+ id: z.string(),
+ }).loose().nullable().optional(),
+}).loose();
+
// Standalone attachment lookup (`GET /api/attachments/{id}`) is the source of
// truth for click-time download URLs. The two fields the download flow opens
// in a new tab — `download_url` and `url` — must be strings, otherwise we'd
diff --git a/packages/core/chat/mutations.ts b/packages/core/chat/mutations.ts
index 4d1959fbab..d30b717f8c 100644
--- a/packages/core/chat/mutations.ts
+++ b/packages/core/chat/mutations.ts
@@ -1,9 +1,14 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api } from "../api";
import { useWorkspaceId } from "../hooks";
-import { chatKeys, sortChatSessions } from "./queries";
+import { chatKeys, sortChatSessions, QUICK_ACTIONS_PENDING_TIMEOUT_MS } from "./queries";
import { createLogger } from "../logger";
-import type { ChatSession, ChatPinnedAgent, ChatDraftRestoresResponse } from "../types";
+import type {
+ ChatSession,
+ ChatPinnedAgent,
+ ChatDraftRestoresResponse,
+ ChatQuickActionsPendingState,
+} from "../types";
const logger = createLogger("chat.mut");
@@ -367,3 +372,48 @@ export function useDeleteChatSession() {
},
});
}
+
+/**
+ * Refresh the quick-action suggestions for a session's latest assistant turn
+ * (MUL-5149). Optimistically raises the pending marker for that turn — its pills
+ * go inert and the refresh icon spins — and rolls it back on failure. The
+ * refreshed pills arrive over the chat:quick_actions realtime event, which
+ * clears the marker (applyChatQuickActionsToCache). Never retried: a refresh is
+ * an explicit, quota-spending user action.
+ */
+export function useRegenerateChatQuickActions() {
+ const qc = useQueryClient();
+
+ return useMutation({
+ mutationFn: ({ sessionId, messageId }: { sessionId: string; messageId: string }) =>
+ api.regenerateChatQuickActions(sessionId, messageId),
+ onMutate: ({ sessionId, messageId }) => {
+ const previous = qc.getQueryData<ChatQuickActionsPendingState | null>(
+ chatKeys.quickActionsPending(sessionId),
+ );
+ // The server confirms messageId IS the latest turn (else 409 → onError
+ // rollback), so the marker's message_id is guaranteed to match the
+ // chat:quick_actions that resolves it — no ack reconciliation needed.
+ // task_id is unknown here and unused for resolution (applyChatQuickActionsToCache
+ // matches on message_id).
+ qc.setQueryData<ChatQuickActionsPendingState | null>(
+ chatKeys.quickActionsPending(sessionId),
+ {
+ message_id: messageId,
+ task_id: "",
+ expires_at: Date.now() + QUICK_ACTIONS_PENDING_TIMEOUT_MS,
+ },
+ );
+ return { previous, sessionId };
+ },
+ onError: (error, _vars, ctx) => {
+ logger.error("regenerateChatQuickActions.error", { error });
+ if (ctx) {
+ qc.setQueryData<ChatQuickActionsPendingState | null>(
+ chatKeys.quickActionsPending(ctx.sessionId),
+ ctx.previous ?? null,
+ );
+ }
+ },
+ });
+}
diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.ts
index 63ca4a0c6b..19177af58e 100644
--- a/packages/core/chat/queries.ts
+++ b/packages/core/chat/queries.ts
@@ -1,7 +1,20 @@
import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";
import { api } from "../api";
import type { TaskMessagePayload } from "../types/events";
-import type { ChatSession } from "../types/chat";
+import type {
+ ChatQuickActionsFailureState,
+ ChatQuickActionsPendingState,
+ ChatSession,
+} from "../types/chat";
+
+/**
+ * How long a quick-actions pending marker may stay unresolved before a client
+ * gives up and clears it (MUL-5149). Used to stamp the marker's absolute
+ * `expires_at` deadline at creation, and by `useQuickActionsPendingTimeout` to
+ * clear it — a shared deadline survives chat-surface switches instead of
+ * re-arming a fresh window on each remount.
+ */
+export const QUICK_ACTIONS_PENDING_TIMEOUT_MS = 30_000;
// NOTE on workspace scoping:
// `wsId` is used only as part of queryKey for cache isolation per workspace.
@@ -21,6 +34,14 @@ export const chatKeys = {
messagesPage: (sessionId: string) => [...chatKeys.messagesPageAll(), sessionId] as const,
pendingTaskAll: () => ["chat", "pending-task"] as const,
pendingTask: (sessionId: string) => [...chatKeys.pendingTaskAll(), sessionId] as const,
+ /** Client-only marker: this session's last turn awaits a quick-actions supplement. */
+ quickActionsPendingAll: () => ["chat", "quick-actions-pending"] as const,
+ quickActionsPending: (sessionId: string) =>
+ [...chatKeys.quickActionsPendingAll(), sessionId] as const,
+ /** Client-only signal: this session's last refresh regeneration failed. */
+ quickActionsFailureAll: () => ["chat", "quick-actions-failure"] as const,
+ quickActionsFailure: (sessionId: string) =>
+ [...chatKeys.quickActionsFailureAll(), sessionId] as const,
draftRestoresAll: () => ["chat", "draft-restores"] as const,
/** Durable deferred-cancellation draft restores for a session (#5219). */
draftRestores: (sessionId: string) => [...chatKeys.draftRestoresAll(), sessionId] as const,
@@ -227,3 +248,32 @@ export function hasPendingChatTasksOptions(wsId: string) {
staleTime: Infinity,
});
}
+
+/**
+ * Client-only cache entry: written by the realtime layer (chat:done raises
+ * it, chat:quick_actions resolves it), never fetched from the server —
+ * `enabled: false` keeps the queryFn from ever running; observers still
+ * re-render on setQueryData.
+ */
+export function chatQuickActionsPendingOptions(sessionId: string) {
+ return queryOptions({
+ queryKey: chatKeys.quickActionsPending(sessionId),
+ queryFn: async (): Promise<ChatQuickActionsPendingState | null> => null,
+ enabled: false,
+ staleTime: Infinity,
+ });
+}
+
+/**
+ * Client-only cache entry mirroring {@link chatQuickActionsPendingOptions}:
+ * the realtime layer writes it off a failed chat:quick_actions, a view reads
+ * it once to toast "couldn't refresh," then clears it. Never fetched.
+ */
+export function chatQuickActionsFailureOptions(sessionId: string) {
+ return queryOptions({
+ queryKey: chatKeys.quickActionsFailure(sessionId),
+ queryFn: async (): Promise<ChatQuickActionsFailureState | null> => null,
+ enabled: false,
+ staleTime: Infinity,
+ });
+}
diff --git a/packages/core/chat/store.test.ts b/packages/core/chat/store.test.ts
index cacb1c9b81..f3d1ea19a8 100644
--- a/packages/core/chat/store.test.ts
+++ b/packages/core/chat/store.test.ts
@@ -308,6 +308,33 @@ describe("chat store — applied draft-restore ledger", () => {
});
});
+describe("chat store — quick actions preference", () => {
+ it("defaults ON when no preference is stored", () => {
+ const store = createChatStore({ storage: memStorage() });
+ expect(store.getState().quickActionsEnabled).toBe(true);
+ });
+
+ it("honours an explicit stored 'false' preference (opt-out)", () => {
+ const storage = memStorage();
+ storage.setItem("multica:chat:quickActionsEnabled", "false");
+ const store = createChatStore({ storage });
+ expect(store.getState().quickActionsEnabled).toBe(false);
+ });
+
+ it("persists toggles through the setter", () => {
+ const storage = memStorage();
+ const store = createChatStore({ storage });
+
+ store.getState().setQuickActionsEnabled(false);
+ expect(store.getState().quickActionsEnabled).toBe(false);
+ expect(storage.getItem("multica:chat:quickActionsEnabled")).toBe("false");
+
+ store.getState().setQuickActionsEnabled(true);
+ expect(store.getState().quickActionsEnabled).toBe(true);
+ expect(storage.getItem("multica:chat:quickActionsEnabled")).toBe("true");
+ });
+});
+
// Coordinator-owned upload lifecycle in the draft slots (MUL-5181 L2).
describe("chat store — draft upload ops", () => {
const ATTACHMENTS_KEY = "multica:chat:draft-attachments";
diff --git a/packages/core/chat/store.ts b/packages/core/chat/store.ts
index 2bfba088b7..dee2ded469 100644
--- a/packages/core/chat/store.ts
+++ b/packages/core/chat/store.ts
@@ -74,6 +74,13 @@ const OPEN_KEY = "multica:chat:isOpen";
* be turned off from the Settings → Chat tab.
*/
const FLOATING_KEY = "multica:chat:floatingChatEnabled";
+/**
+ * Settings → Chat preference: render agent follow-up suggestion chips under
+ * assistant replies. Persisted globally like FLOATING_KEY; missing key =
+ * default ON. Display-only for now — the daemon still generates suggestions
+ * either way (known debt: a server-side preference could skip that call).
+ */
+const QUICK_ACTIONS_KEY = "multica:chat:quickActionsEnabled";
function readDrafts(storage: StorageAdapter, key: string): Record<string, string> {
const raw = storage.getItem(key);
@@ -304,6 +311,8 @@ export interface ChatState {
isOpen: boolean;
/** Settings preference: is the floating chat window available at all. */
floatingChatEnabled: boolean;
+ /** Settings preference: render follow-up suggestion chips in chat. */
+ quickActionsEnabled: boolean;
activeSessionId: string | null;
selectedAgentId: string | null;
/** Project context for the next session. Existing sessions remain bound to
@@ -325,6 +334,7 @@ export interface ChatState {
setOpen: (open: boolean) => void;
toggle: () => void;
setFloatingChatEnabled: (enabled: boolean) => void;
+ setQuickActionsEnabled: (enabled: boolean) => void;
setActiveSession: (id: string | null) => void;
setSelectedAgentId: (id: string) => void;
setSelectedProjectId: (id: string | null) => void;
@@ -379,6 +389,7 @@ export function createChatStore(options: ChatStoreOptions) {
// turned it off ("false") from the Settings → Chat tab. A missing key
// (new user) resolves to enabled.
const initialFloatingEnabled = storage.getItem(FLOATING_KEY) !== "false";
+ const initialQuickActionsEnabled = storage.getItem(QUICK_ACTIONS_KEY) !== "false";
const initialAgentId = storage.getItem(wsKey(AGENT_STORAGE_KEY));
const initialDraftSlots = loadDraftSlots(
@@ -391,6 +402,7 @@ export function createChatStore(options: ChatStoreOptions) {
const store = create<ChatState>((set, get) => ({
isOpen: initialIsOpen,
floatingChatEnabled: initialFloatingEnabled,
+ quickActionsEnabled: initialQuickActionsEnabled,
activeSessionId: storage.getItem(wsKey(SESSION_STORAGE_KEY)),
selectedAgentId: initialAgentId,
selectedProjectId: storage.getItem(wsKey(PROJECT_STORAGE_KEY)),
@@ -420,6 +432,11 @@ export function createChatStore(options: ChatStoreOptions) {
set(enabled ? { floatingChatEnabled: true } : { floatingChatEnabled: false, isOpen: false });
if (!enabled) storage.setItem(OPEN_KEY, "false");
},
+ setQuickActionsEnabled: (enabled) => {
+ logger.info("setQuickActionsEnabled", { to: enabled });
+ storage.setItem(QUICK_ACTIONS_KEY, String(enabled));
+ set({ quickActionsEnabled: enabled });
+ },
setActiveSession: (id) => {
logger.info("setActiveSession", { from: get().activeSessionId, to: id });
if (id) {
diff --git a/packages/core/chat/use-quick-actions-pending-timeout.ts b/packages/core/chat/use-quick-actions-pending-timeout.ts
new file mode 100644
index 0000000000..06ba94b21b
--- /dev/null
+++ b/packages/core/chat/use-quick-actions-pending-timeout.ts
@@ -0,0 +1,46 @@
+import { useEffect } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { chatKeys, QUICK_ACTIONS_PENDING_TIMEOUT_MS } from "./queries";
+import type { ChatQuickActionsPendingState } from "../types/chat";
+
+/**
+ * Clears a session's `quickActionsPending` marker from the query cache when no
+ * chat:quick_actions supplement resolves it before the marker's own deadline
+ * (MUL-5149). Unlike a component-local timer, this drops the REAL cache state,
+ * so the pill spinner / skeleton stops AND a later refresh — even after closing
+ * and reopening chat — starts clean instead of re-reading a stuck marker.
+ *
+ * The deadline is `marker.expires_at` (absolute), NOT a fresh window per mount:
+ * switching between the floating chat and the chat tab unmounts one host and
+ * mounts the other, and a per-mount timer would restart the full wait each time,
+ * letting a lost event strand the marker indefinitely. Reading the stored
+ * deadline means a remount waits only the remaining time. The final clear is
+ * message-scoped so it never wipes a newer turn's marker.
+ *
+ * Mount once per surface that reads the marker (chat page / floating window).
+ */
+export function useQuickActionsPendingTimeout(
+ sessionId: string | null,
+ pending: ChatQuickActionsPendingState | null,
+): void {
+ const qc = useQueryClient();
+ const messageId = pending?.message_id ?? null;
+ const expiresAt = pending?.expires_at ?? null;
+ useEffect(() => {
+ if (!sessionId || !messageId) return;
+ const clear = () =>
+ qc.setQueryData<ChatQuickActionsPendingState | null>(
+ chatKeys.quickActionsPending(sessionId),
+ (current) =>
+ current && current.message_id === messageId ? null : current,
+ );
+ // Remaining time to this marker's absolute deadline; an old marker without
+ // one falls back to a full window. Already-past deadlines clear next tick.
+ const remaining =
+ expiresAt != null
+ ? expiresAt - Date.now()
+ : QUICK_ACTIONS_PENDING_TIMEOUT_MS;
+ const timer = setTimeout(clear, Math.max(0, remaining));
+ return () => clearTimeout(timer);
+ }, [qc, sessionId, messageId, expiresAt]);
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index b055626df2..d3ecfb987a 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -53,6 +53,7 @@
"./chat": "./chat/index.ts",
"./chat/queries": "./chat/queries.ts",
"./chat/mutations": "./chat/mutations.ts",
+ "./chat/use-quick-actions-pending-timeout": "./chat/use-quick-actions-pending-timeout.ts",
"./chat/unread": "./chat/unread.ts",
"./runtimes": "./runtimes/index.ts",
"./runtimes/queries": "./runtimes/queries.ts",
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.ts
index 63cf3b11ae..c571ac34a2 100644
--- a/packages/core/realtime/use-realtime-sync.test.ts
+++ b/packages/core/realtime/use-realtime-sync.test.ts
@@ -1,4 +1,8 @@
-import { QueryClient, type InfiniteData } from "@tanstack/react-query";
+import {
+ QueryClient,
+ QueryObserver,
+ type InfiniteData,
+} from "@tanstack/react-query";
import { afterEach, describe, expect, it, vi } from "vitest";
import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
@@ -19,6 +23,7 @@ import type {
import {
applyChatCancelFinalizedToCache,
applyChatDoneToCache,
+ applyChatQuickActionsToCache,
applyChatSessionUpdatedToCache,
applyWorkspaceUpdatedToCache,
handleInboxNew,
@@ -110,6 +115,20 @@ describe("applyChatDoneToCache", () => {
expect(msgs?.[1]?.message_kind).toBe("no_response");
});
+ it("carries quick actions on the inline assistant message", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage()]);
+ const quickActions = [
+ { label: "Draft it", prompt: "Draft the full brief", primary: true },
+ ];
+
+ applyChatDoneToCache(qc, donePayload({ quick_actions: quickActions }));
+
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)?.[1]?.quick_actions).toEqual(
+ quickActions,
+ );
+ });
+
it("does not duplicate a replayed chat done event", () => {
const qc = createQueryClient();
const assistant: ChatMessage = {
@@ -868,3 +887,150 @@ describe("handleInboxNew", () => {
expect(webBanners).toHaveLength(0);
});
});
+
+describe("chat quick-actions supplement flow", () => {
+ const pendingMarkerKey = chatKeys.quickActionsPending(sessionId);
+
+ it("chat:done raises the pending marker when the daemon declared a supplement", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage()]);
+ applyChatDoneToCache(qc, donePayload({ quick_actions_pending: true }));
+ expect(qc.getQueryData(pendingMarkerKey)).toEqual({
+ message_id: "msg-assistant",
+ task_id: taskId,
+ // Absolute give-up deadline stamped at raise time (MUL-5149); its exact
+ // value tracks the wall clock, so assert presence, not a fixed number.
+ expires_at: expect.any(Number),
+ });
+ });
+
+ it("chat:done clears the marker when no supplement was declared (older daemons)", () => {
+ const qc = createQueryClient();
+ qc.setQueryData(pendingMarkerKey, { message_id: "stale", task_id: "old" });
+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage()]);
+ applyChatDoneToCache(qc, donePayload());
+ expect(qc.getQueryData(pendingMarkerKey)).toBeNull();
+ });
+
+ it("chat:quick_actions patches the message in both caches and resolves the marker", async () => {
+ const qc = createQueryClient();
+ const assistant: ChatMessage = {
+ id: "msg-assistant",
+ chat_session_id: sessionId,
+ role: "assistant",
+ content: "done",
+ task_id: taskId,
+ created_at: "2026-05-13T05:00:02Z",
+ };
+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage(), assistant]);
+ qc.setQueryData<InfiniteData<ChatMessagesPage>>(chatKeys.messagesPage(sessionId), {
+ pages: [{ messages: [assistant], limit: 50, has_more: false, next_cursor: null }],
+ pageParams: [null],
+ });
+ qc.setQueryData(pendingMarkerKey, { message_id: "msg-assistant", task_id: taskId });
+
+ const actions = [{ label: "Next", prompt: "Do the next thing", primary: true }];
+ await applyChatQuickActionsToCache(qc, {
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-assistant",
+ quick_actions: actions,
+ });
+
+ const messages = qc.getQueryData<ChatMessage[]>(messagesKey);
+ expect(messages?.at(-1)?.quick_actions).toEqual(actions);
+ const pages = qc.getQueryData<InfiniteData<ChatMessagesPage>>(
+ chatKeys.messagesPage(sessionId),
+ );
+ expect(pages?.pages[0]?.messages[0]?.quick_actions).toEqual(actions);
+ expect(qc.getQueryData(pendingMarkerKey)).toBeNull();
+ });
+
+ it("an empty supplement resolves the marker without touching messages", async () => {
+ const qc = createQueryClient();
+ const assistant: ChatMessage = {
+ id: "msg-assistant",
+ chat_session_id: sessionId,
+ role: "assistant",
+ content: "done",
+ task_id: taskId,
+ created_at: "2026-05-13T05:00:02Z",
+ quick_actions: [{ label: "Keep", prompt: "Keep me" }],
+ };
+ qc.setQueryData<ChatMessage[]>(messagesKey, [assistant]);
+ qc.setQueryData(pendingMarkerKey, { message_id: "msg-assistant", task_id: taskId });
+
+ await applyChatQuickActionsToCache(qc, {
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-assistant",
+ quick_actions: [],
+ });
+
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)?.[0]?.quick_actions).toEqual([
+ { label: "Keep", prompt: "Keep me" },
+ ]);
+ expect(qc.getQueryData(pendingMarkerKey)).toBeNull();
+ });
+
+ // Regression (MUL-5149): the chat:done invalidate can leave a messages refetch
+ // in flight that read the row before the actions were persisted. If that
+ // refetch resolves AFTER the chat:quick_actions patch, it must not overwrite
+ // the freshly-patched actions — the supplement cancels the in-flight refetch
+ // first. staleTime: Infinity means an overwrite would be permanent.
+ it("a stale chat:done refetch resolving after the supplement cannot overwrite it", async () => {
+ const qc = createQueryClient();
+ const assistant: ChatMessage = {
+ id: "msg-assistant",
+ chat_session_id: sessionId,
+ role: "assistant",
+ content: "done",
+ task_id: taskId,
+ created_at: "2026-05-13T05:00:02Z",
+ };
+ // Settled post-chat:done state: assistant present, no actions yet.
+ const staleRows = [userMessage(), assistant];
+ qc.setQueryData<ChatMessage[]>(messagesKey, staleRows);
+
+ // An active observer (a mounted chat screen) whose refetch we hold open, so
+ // it is genuinely in flight when the supplement lands.
+ let releaseRefetch: ((rows: ChatMessage[]) => void) | undefined;
+ const observer = new QueryObserver<ChatMessage[]>(qc, {
+ queryKey: messagesKey,
+ queryFn: () =>
+ new Promise<ChatMessage[]>((resolve) => {
+ releaseRefetch = resolve;
+ }),
+ staleTime: Infinity,
+ gcTime: Infinity,
+ retry: false,
+ });
+ const unsub = observer.subscribe(() => {});
+
+ // chat:done's invalidate kicks off the refetch (not awaited — it is held).
+ void qc.invalidateQueries({ queryKey: messagesKey });
+ await vi.waitFor(() => {
+ expect(qc.getQueryState(messagesKey)?.fetchStatus).toBe("fetching");
+ expect(typeof releaseRefetch).toBe("function");
+ });
+
+ const actions = [{ label: "Next", prompt: "Do the next thing", primary: true }];
+ await applyChatQuickActionsToCache(qc, {
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-assistant",
+ quick_actions: actions,
+ });
+
+ // The now-cancelled refetch finally resolves with the actions-less rows.
+ releaseRefetch?.(staleRows);
+ await vi.waitFor(() => {
+ expect(qc.getQueryState(messagesKey)?.fetchStatus).toBe("idle");
+ });
+
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)?.at(-1)?.quick_actions).toEqual(
+ actions,
+ );
+ unsub();
+ });
+});
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 788d4e3903..6474776e19 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -48,7 +48,12 @@ import {
type SystemNotificationPayload,
} from "../platform/system-notification";
import type { Workspace } from "../types/workspace";
-import { chatKeys, mergeTaskMessagesBySeq, sortChatSessions } from "../chat/queries";
+import {
+ chatKeys,
+ mergeTaskMessagesBySeq,
+ sortChatSessions,
+ QUICK_ACTIONS_PENDING_TIMEOUT_MS,
+} from "../chat/queries";
import { useChatStore } from "../chat";
import { resolvePostAuthDestination, useHasOnboarded } from "../paths";
import type {
@@ -86,6 +91,9 @@ import type {
TaskFailedPayload,
TaskCancelledPayload,
ChatDonePayload,
+ ChatQuickActionsPayload,
+ ChatQuickActionsPendingState,
+ ChatQuickActionsFailureState,
ChatCancelFinalizedPayload,
ChatMessage,
ChatPendingTask,
@@ -135,12 +143,12 @@ export function applyChatDoneToCache(
const taskId = payload.task_id;
const messageId = payload.message_id;
const content = payload.content;
- if (messageId && content !== undefined) {
+ if (messageId && (content !== undefined || (payload.quick_actions?.length ?? 0) > 0)) {
const assistant: ChatMessage = {
id: messageId,
chat_session_id: sessionId,
role: "assistant",
- content,
+ content: content ?? "",
task_id: taskId,
created_at: payload.created_at ?? new Date().toISOString(),
elapsed_ms: payload.elapsed_ms ?? null,
@@ -148,6 +156,9 @@ export function applyChatDoneToCache(
// without waiting for the reconciling refetch (MUL-4351). Missing →
// "message" for older servers.
message_kind: payload.message_kind ?? "message",
+ ...(payload.quick_actions !== undefined
+ ? { quick_actions: payload.quick_actions }
+ : {}),
};
qc.setQueryData<ChatMessage[] | undefined>(
chatKeys.messages(sessionId),
@@ -165,12 +176,96 @@ export function applyChatDoneToCache(
}
// Replacement is in the messages list now; safe to drop pending.
qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ // Raise/clear the quick-actions placeholder marker. Kept OUTSIDE the
+ // message caches deliberately: the authoritative refetch below replaces
+ // those, and a flag stored on the message would vanish with it. Explicit
+ // `=== true` — older servers omit the field entirely.
+ qc.setQueryData<ChatQuickActionsPendingState | null>(
+ chatKeys.quickActionsPending(sessionId),
+ payload.quick_actions_pending === true && messageId
+ ? {
+ message_id: messageId,
+ task_id: taskId,
+ expires_at: Date.now() + QUICK_ACTIONS_PENDING_TIMEOUT_MS,
+ }
+ : null,
+ );
// Authoritative refetch reconciles redaction / migrations / clients
// that took the fallback branch above.
invalidateChatMessageQueries(qc, sessionId);
qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
}
+/**
+ * Apply a chat:quick_actions supplement: patch the identified assistant
+ * message's quick_actions in both message caches and resolve the pending
+ * placeholder. An empty/missing list is terminal ("no suggestions this
+ * turn") — the placeholder still resolves.
+ *
+ * `payload.failed` marks a resolution whose regeneration failed: the carried
+ * actions are the turn's UNCHANGED prior pills, so the patch is a no-op, but a
+ * failure signal is raised for a view to toast — otherwise an explicit refresh
+ * that failed would look identical to one that succeeded with the same
+ * suggestions (MUL-5149 review).
+ */
+export async function applyChatQuickActionsToCache(
+ qc: QueryClient,
+ payload: ChatQuickActionsPayload,
+) {
+ const sessionId = payload.chat_session_id;
+ const actions = payload.quick_actions ?? [];
+ const patch = (m: ChatMessage): ChatMessage =>
+ m.id === payload.message_id ? { ...m, quick_actions: actions } : m;
+ if (actions.length > 0) {
+ // chat:done's invalidate may still have a messages refetch in flight that
+ // read the assistant row BEFORE the daemon persisted these actions. Cancel
+ // it first so its actions-less response can't land after — and overwrite —
+ // the patch below. Both message caches are staleTime: Infinity, so such an
+ // overwrite would never self-heal (MUL-5149 stale-refetch race). Cancelling
+ // before setQueryData is required: cancelQueries reverts to the pre-fetch
+ // state, so patching first would be undone by the revert.
+ await Promise.all([
+ qc.cancelQueries({ queryKey: chatKeys.messages(sessionId) }),
+ qc.cancelQueries({ queryKey: chatKeys.messagesPage(sessionId) }),
+ ]);
+ qc.setQueryData<ChatMessage[] | undefined>(
+ chatKeys.messages(sessionId),
+ (old) => old?.map(patch),
+ );
+ qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(
+ chatKeys.messagesPage(sessionId),
+ (old) =>
+ old
+ ? {
+ ...old,
+ pages: old.pages.map((page) => ({
+ ...page,
+ messages: page.messages.map(patch),
+ })),
+ }
+ : old,
+ );
+ }
+ // Resolve the marker only when it belongs to THIS message: a late
+ // supplement for turn N must not clear the marker turn N+1's chat:done
+ // just raised (near-unreachable — the daemon cancels stale passes — but
+ // the guard costs one comparison).
+ qc.setQueryData<ChatQuickActionsPendingState | null>(
+ chatKeys.quickActionsPending(sessionId),
+ (current) =>
+ current && current.message_id !== payload.message_id ? current : null,
+ );
+ // Raise a one-shot failure signal on an explicit refresh whose regeneration
+ // failed. A view consumes it to toast and clears it; the `at` nonce keeps a
+ // repeat failure on the same turn from being deduped away.
+ if (payload.failed === true) {
+ qc.setQueryData<ChatQuickActionsFailureState | null>(
+ chatKeys.quickActionsFailure(sessionId),
+ { message_id: payload.message_id, at: Date.now() },
+ );
+ }
+}
+
function patchLatestChatMessagePage(
old: InfiniteData<ChatMessagesPage> | undefined,
message: ChatMessage,
@@ -778,7 +873,7 @@ export function useRealtimeSync(
"subscriber:added", "subscriber:removed",
"daemon:heartbeat",
// Chat events are handled explicitly below; do not double-invalidate.
- "chat:message", "chat:done", "chat:cancel_finalized", "chat:session_read",
+ "chat:message", "chat:done", "chat:quick_actions", "chat:cancel_finalized", "chat:session_read",
"chat:session_deleted", "chat:session_updated",
// task:message stays out of the prefix path because it fires per
// streamed message during a long run — invalidating the snapshot on
@@ -1179,6 +1274,19 @@ export function useRealtimeSync(
invalidateSessionLists();
});
+ // Late quick-actions supplement from the daemon's background suggestion
+ // pass — patches the finished turn's message in place; no invalidate
+ // needed (the payload is authoritative and tiny).
+ const unsubChatQuickActions = ws.on("chat:quick_actions", (p) => {
+ const payload = p as ChatQuickActionsPayload;
+ chatWsLogger.info("chat:quick_actions (global)", {
+ task_id: payload.task_id,
+ chat_session_id: payload.chat_session_id,
+ count: payload.quick_actions?.length ?? 0,
+ });
+ void applyChatQuickActionsToCache(qc, payload);
+ });
+
// Deferred cancellation outcome (#5219): the server settles the
// empty/non-empty judgment only after the daemon's transcript flush, so
// this event arrives seconds after the cancel HTTP response — nothing
@@ -1414,6 +1522,7 @@ export function useRealtimeSync(
unsubTaskMessage();
unsubChatMessage();
unsubChatDone();
+ unsubChatQuickActions();
unsubChatCancelFinalized();
unsubTaskQueued();
unsubTaskDispatch();
diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.ts
index c0a069ac63..5d66e92456 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -15,6 +15,49 @@ export interface ChatPinnedAgent {
*/
export type ChatMessageKind = "message" | "no_response";
+/**
+ * A concise follow-up offered by an assistant reply. `label` is rendered in
+ * the UI while `prompt` is the full text sent back to the agent. At most one
+ * action should be primary; clients still render safely if an older or future
+ * server sends more than one.
+ */
+export interface ChatQuickAction {
+ label: string;
+ prompt: string;
+ primary?: boolean;
+}
+
+/**
+ * Client-only marker (never persisted, never fetched) that the identified
+ * turn's quick-actions supplement is still in flight — drives the pill
+ * skeleton between chat:done and chat:quick_actions.
+ */
+export interface ChatQuickActionsPendingState {
+ message_id: string;
+ task_id: string;
+ /**
+ * Absolute epoch-ms deadline after which a client gives up waiting for the
+ * chat:quick_actions supplement and clears this marker. Stored on the marker
+ * (not as a component timer) so switching chat surfaces — which unmounts and
+ * remounts the timeout hook — resumes the SAME deadline instead of re-arming
+ * a fresh window each time (MUL-5149 review).
+ */
+ expires_at: number;
+}
+
+/**
+ * Client-only signal (never persisted, never fetched) that an explicit refresh's
+ * background regeneration FAILED — the daemon suggestion pass never completed, so
+ * the turn's pills are unchanged. Set by the realtime layer off a failed
+ * chat:quick_actions and consumed once by a view to toast "couldn't refresh"
+ * before clearing itself. `at` is a per-event nonce so a second failure re-fires
+ * even when the message_id repeats (MUL-5149 review).
+ */
+export interface ChatQuickActionsFailureState {
+ message_id: string;
+ at: number;
+}
+
/** Preview of a session's most recent message, for the IM-style list. */
export interface ChatLastMessage {
content: string;
@@ -108,6 +151,8 @@ export interface ChatMessage {
* servers and on user messages; treat a missing value as "message".
*/
message_kind?: ChatMessageKind;
+ /** Up to three server-validated follow-ups generated with this reply. */
+ quick_actions?: ChatQuickAction[];
}
export interface ChatMessagesCursor {
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index d0fe0d9bd6..58f659b83b 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -57,6 +57,7 @@ export type WSEventType =
| "issue_reaction:removed"
| "chat:message"
| "chat:done"
+ | "chat:quick_actions"
| "chat:cancel_finalized"
| "chat:session_read"
| "chat:session_deleted"
@@ -383,6 +384,34 @@ export interface ChatDonePayload {
* populated alongside this even for a no_response turn.
*/
message_kind?: import("./chat").ChatMessageKind;
+ /** Server-validated follow-ups attached to the persisted assistant reply. */
+ quick_actions?: import("./chat").ChatQuickAction[];
+ /**
+ * The daemon will follow up with a chat:quick_actions supplement for this
+ * turn — render a placeholder. Never true alongside populated
+ * quick_actions; absent on older servers/daemons.
+ */
+ quick_actions_pending?: boolean;
+}
+
+/**
+ * chat:quick_actions — supplements a finished turn with the follow-up
+ * suggestions from the daemon's background pass. An empty list is terminal:
+ * "no suggestions this turn", resolve any placeholder.
+ */
+export interface ChatQuickActionsPayload {
+ chat_session_id: string;
+ task_id: string;
+ message_id: string;
+ quick_actions?: import("./chat").ChatQuickAction[];
+ /**
+ * The regeneration behind an explicit refresh failed: the actions carried
+ * here are the turn's UNCHANGED prior pills, sent only to resolve the pending
+ * spinner. Clients surface a "couldn't refresh" notice rather than treating
+ * them as freshly generated. Absent/false on the normal success path and on
+ * older servers.
+ */
+ failed?: boolean;
}
/**
@@ -515,6 +544,7 @@ export interface WSEventPayloadMap {
"activity:created": ActivityCreatedPayload;
"chat:message": ChatMessageEventPayload;
"chat:done": ChatDonePayload;
+ "chat:quick_actions": ChatQuickActionsPayload;
"chat:cancel_finalized": ChatCancelFinalizedPayload;
"chat:session_read": ChatSessionReadPayload;
"chat:session_deleted": ChatSessionDeletedPayload;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 4ea45dd461..5a8940f4a6 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -112,6 +112,9 @@ export type {
ChatLastMessage,
ChatPinnedAgent,
ChatMessage,
+ ChatQuickAction,
+ ChatQuickActionsPendingState,
+ ChatQuickActionsFailureState,
ChatMessagesPage,
ChatPendingTask,
PendingChatTaskItem,
diff --git a/packages/views/chat/chat-page.test.tsx b/packages/views/chat/chat-page.test.tsx
index 8c14cb7103..1a654eb037 100644
--- a/packages/views/chat/chat-page.test.tsx
+++ b/packages/views/chat/chat-page.test.tsx
@@ -1,6 +1,7 @@
// @vitest-environment jsdom
import { StrictMode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import type { Agent } from "@multica/core/types";
@@ -202,13 +203,18 @@ function renderPage(search: string, { strict = false } = {}) {
};
// A fresh element per render — reusing one element object lets React bail
// out of re-rendering, which would make the rerender-based tests vacuous.
+ // ChatPage reads the client-only quick-actions pending marker via useQuery,
+ // so the page needs a QueryClient like it has in the real app shell.
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const makeUi = () => {
const page = (
- <I18nProvider locale="en" resources={TEST_RESOURCES}>
- <NavigationProvider value={navigation}>
- <ChatPage />
- </NavigationProvider>
- </I18nProvider>
+ <QueryClientProvider client={qc}>
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <NavigationProvider value={navigation}>
+ <ChatPage />
+ </NavigationProvider>
+ </I18nProvider>
+ </QueryClientProvider>
);
return strict ? <StrictMode>{page}</StrictMode> : page;
};
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index 80227e7e10..fa467fbaba 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -13,6 +13,11 @@ import {
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
import { useWorkspacePaths } from "@multica/core/paths";
import { useChatStore } from "@multica/core/chat";
+import { chatQuickActionsPendingOptions } from "@multica/core/chat/queries";
+import { useRegenerateChatQuickActions } from "@multica/core/chat/mutations";
+import { useQuickActionsPendingTimeout } from "@multica/core/chat/use-quick-actions-pending-timeout";
+import { useQuickActionsFailureToast } from "./components/use-quick-actions-failure-toast";
+import { useQuery } from "@tanstack/react-query";
import type { Agent, ChatSession } from "@multica/core/types";
import { PageHeader } from "../layout/page-header";
import { useNavigation } from "../navigation";
@@ -54,6 +59,15 @@ export function ChatPage() {
const isMobile = useIsMobile();
const c = useChatController({ isActive: true });
+ const { data: quickActionsPending = null } = useQuery(
+ chatQuickActionsPendingOptions(c.activeSessionId ?? ""),
+ );
+ // Drop a stuck pending marker (dead daemon / failed supplement) so the pill
+ // spinner stops and a later refresh starts clean (MUL-5149).
+ useQuickActionsPendingTimeout(c.activeSessionId ?? null, quickActionsPending);
+ // Toast when an accepted refresh later fails in the daemon (async half).
+ useQuickActionsFailureToast(c.activeSessionId ?? null);
+ const regenerateQuickActions = useRegenerateChatQuickActions();
const urlSession = searchParams.get("session") || null;
const urlAgent = searchParams.get("agent") || null;
@@ -246,6 +260,19 @@ export function ChatPage() {
hasOlderMessages={c.hasOlderMessages}
isFetchingOlderMessages={c.isFetchingOlderMessages}
onLoadOlderMessages={() => void c.fetchOlderMessages()}
+ onQuickAction={(action) => c.handleSend(action.prompt)}
+ quickActionsDisabled={
+ !!c.pendingTaskId || c.isSessionArchived || c.isAgentArchived || c.noAgent
+ }
+ onRegenerateQuickActions={(message) =>
+ c.activeSessionId
+ ? regenerateQuickActions.mutateAsync({
+ sessionId: c.activeSessionId,
+ messageId: message.id,
+ })
+ : undefined
+ }
+ quickActionsPendingMessageId={quickActionsPending?.message_id ?? null}
/>
) : (
<EmptyState agent={c.activeAgent} />
diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsx
index ba4fe386eb..ecc0cf030b 100644
--- a/packages/views/chat/components/chat-message-list.test.tsx
+++ b/packages/views/chat/components/chat-message-list.test.tsx
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
-import { act, render, screen } from "@testing-library/react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@multica/core/i18n/react";
import { chatKeys } from "@multica/core/chat/queries";
@@ -164,6 +164,144 @@ describe("ChatMessageList live timeline (MUL-3960 regression)", () => {
expect(await screen.findByText("Draft ready.")).toBeInTheDocument();
expect(screen.queryByText(/Hidden protocol/)).not.toBeInTheDocument();
});
+
+ it("hides a partial quick-actions protocol footer while text streams", async () => {
+ const qc = new QueryClient();
+ qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
+ taskMsg(0, "text", {
+ content:
+ "Draft ready.\n```quick-actions\n[{\"label\":\"Hidden suggestion\"",
+ }),
+ ]);
+
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={qc}>
+ <ChatMessageList
+ messages={[]}
+ pendingTask={{ task_id: TASK_ID, status: "running" }}
+ availability="online"
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+
+ expect(await screen.findByText("Draft ready.")).toBeInTheDocument();
+ expect(screen.queryByText(/Hidden suggestion/)).not.toBeInTheDocument();
+ });
+});
+
+describe("ChatMessageList quick actions", () => {
+ it("renders up to three suggestions and sends the hidden prompt", async () => {
+ const qc = new QueryClient();
+ const onQuickAction = vi.fn();
+ const quickActions = [
+ { label: "Draft the brief", prompt: "Draft the complete launch brief", primary: true },
+ { label: "Make a checklist", prompt: "Create a two-week launch checklist" },
+ { label: "Define success", prompt: "Define the activation success metric" },
+ ];
+
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={qc}>
+ <ChatMessageList
+ messages={[{
+ id: "assistant-1",
+ chat_session_id: "session-1",
+ role: "assistant",
+ content: "The plan is ready.",
+ task_id: null,
+ created_at: "2026-07-22T00:00:00Z",
+ quick_actions: quickActions,
+ }]}
+ pendingTask={null}
+ availability="online"
+ onQuickAction={onQuickAction}
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+
+ expect(await screen.findByRole("button", { name: "Draft the brief" })).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Make a checklist" })).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Define success" })).toBeEnabled();
+ fireEvent.click(screen.getByRole("button", { name: "Draft the brief" }));
+ expect(onQuickAction).toHaveBeenCalledWith(quickActions[0]);
+ });
+
+ it("disables suggestions while another reply is running", async () => {
+ const qc = new QueryClient();
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={qc}>
+ <ChatMessageList
+ messages={[{
+ id: "assistant-1",
+ chat_session_id: "session-1",
+ role: "assistant",
+ content: "Ready.",
+ task_id: null,
+ created_at: "2026-07-22T00:00:00Z",
+ quick_actions: [{ label: "Continue", prompt: "Continue" }],
+ }]}
+ pendingTask={null}
+ availability="online"
+ onQuickAction={vi.fn()}
+ quickActionsDisabled
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+
+ expect(await screen.findByRole("button", { name: "Continue" })).toBeDisabled();
+ });
+});
+
+describe("ChatMessageList quick actions skeleton", () => {
+ const assistantMessage = {
+ id: "assistant-1",
+ chat_session_id: "session-1",
+ role: "assistant" as const,
+ content: "The plan is ready.",
+ task_id: null,
+ created_at: "2026-07-22T00:00:00Z",
+ };
+
+ it("renders pill skeletons for the message awaiting its supplement", () => {
+ const qc = new QueryClient();
+ const { container } = render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={qc}>
+ <ChatMessageList
+ messages={[assistantMessage]}
+ pendingTask={null}
+ availability="online"
+ onQuickAction={vi.fn()}
+ quickActionsPendingMessageId="assistant-1"
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+ expect(container.querySelectorAll(".rounded-full[aria-hidden] , [aria-hidden] .rounded-full").length).toBeGreaterThan(0);
+ expect(screen.queryByRole("button", { name: /suggested/i })).toBeNull();
+ });
+
+ it("shows no skeleton for other messages or without onQuickAction", () => {
+ const qc = new QueryClient();
+ const { container } = render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={qc}>
+ <ChatMessageList
+ messages={[assistantMessage]}
+ pendingTask={null}
+ availability="online"
+ quickActionsPendingMessageId="assistant-1"
+ />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+ expect(container.querySelector("[aria-hidden] .rounded-full")).toBeNull();
+ });
});
describe("ChatMessageList failure copy (MUL-5370 regression)", () => {
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index 38611ef2b0..c1dae6be41 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -17,7 +17,16 @@ import {
TooltipTrigger,
TooltipContent,
} from "@multica/ui/components/ui/tooltip";
-import { ChevronRight, ChevronDown, Brain, AlertCircle, AlertTriangle, Copy } from "lucide-react";
+import {
+ ChevronRight,
+ ChevronDown,
+ Brain,
+ AlertCircle,
+ AlertTriangle,
+ ArrowUpRight,
+ Copy,
+ RotateCw,
+} from "lucide-react";
import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
import { isTaskMessageTaskId, taskMessagesOptions } from "@multica/core/chat/queries";
import { RichContent } from "../../rich-content";
@@ -29,6 +38,7 @@ import { resolveFailureReasonKey } from "@multica/core/agents";
import type {
ChatMessage,
ChatPendingTask,
+ ChatQuickAction,
TaskMessagePayload,
} from "@multica/core/types";
import type { ChatTimelineItem } from "@multica/core/chat";
@@ -37,6 +47,7 @@ import { TaskStatusPill } from "./task-status-pill";
import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";
import { formatElapsedMs } from "../lib/format";
import { splitTimeline, extractCopyText } from "../lib/copy-text";
+import { stripChatQuickActionsProtocol } from "../lib/quick-actions";
import { useT } from "../../i18n";
// ─── Public component ────────────────────────────────────────────────────
@@ -56,6 +67,22 @@ interface ChatMessageListProps {
onLoadOlderMessages?: () => void;
/** Transform assistant task text for embedded chat protocols before render/copy. */
transformContent?: (content: string) => string;
+ /** Send the full hidden prompt behind an assistant follow-up chip. */
+ onQuickAction?: (action: ChatQuickAction) => void | Promise<unknown>;
+ quickActionsDisabled?: boolean;
+ /**
+ * Regenerate the follow-up suggestions for the session's latest assistant
+ * turn (the "refresh" affordance, MUL-5149). Only offered on that turn —
+ * regeneration resumes the newest provider state, so an older turn's pills
+ * can't be refreshed in place.
+ */
+ onRegenerateQuickActions?: (message: ChatMessage) => void | Promise<unknown>;
+ /**
+ * Message currently awaiting its quick-actions supplement (client-only
+ * marker raised by chat:done or a refresh) — renders pill skeletons under
+ * that reply until chat:quick_actions resolves it.
+ */
+ quickActionsPendingMessageId?: string | null;
}
// ─── Virtuoso chrome ─────────────────────────────────────────────────────
@@ -116,6 +143,10 @@ function ChatListHeader({ context }: { context?: ChatListContext }) {
// The Footer now carries only the status pill — task chrome, not content. The
// live timeline moved into a real row so it can keep its identity when the
// task completes (see ChatRenderItem).
+//
+// The container always renders (even with no pill) so the list keeps a
+// constant bottom inset: without it the last row's own py-2 was the only gap
+// between the final reply (and its follow-up pills) and the composer.
function ChatListFooter({ context }: { context?: ChatListContext }) {
if (!context) return null;
if (!context.showStatusPill || !context.pendingTask) return null;
@@ -144,6 +175,10 @@ export function ChatMessageList({
isFetchingOlderMessages = false,
onLoadOlderMessages,
transformContent,
+ onQuickAction,
+ quickActionsDisabled = false,
+ onRegenerateQuickActions,
+ quickActionsPendingMessageId = null,
}: ChatMessageListProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const [scrollContainerEl, setScrollContainerEl] = useState<HTMLDivElement | null>(null);
@@ -158,6 +193,17 @@ export function ChatMessageList({
const pendingTaskId = pendingTask?.task_id ?? null;
+ // The session's newest assistant turn — the only one whose quick actions can
+ // be refreshed (regeneration resumes the newest provider state). Computed off
+ // the persisted list so the affordance tracks the real tail, not a live row.
+ const latestAssistantMessageId = useMemo(() => {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const m = messages[i];
+ if (m && m.role === "assistant" && m.task_id) return m.id;
+ }
+ return null;
+ }, [messages]);
+
// Once the assistant message for this pending task has landed in the
// messages list, AssistantMessage owns its rendering — suppress the live
// timeline (and pill) to avoid rendering the same content in two places
@@ -260,6 +306,11 @@ export function ChatMessageList({
item={item}
isPending={!!pendingTaskId && item.taskId === pendingTaskId}
transformContent={transformContent}
+ onQuickAction={onQuickAction}
+ quickActionsDisabled={quickActionsDisabled}
+ onRegenerateQuickActions={onRegenerateQuickActions}
+ latestAssistantMessageId={latestAssistantMessageId}
+ quickActionsPendingMessageId={quickActionsPendingMessageId}
/>
</div>
)}
@@ -318,10 +369,20 @@ const MessageBubble = memo(function MessageBubble({
item,
isPending,
transformContent,
+ onQuickAction,
+ quickActionsDisabled,
+ onRegenerateQuickActions,
+ latestAssistantMessageId,
+ quickActionsPendingMessageId,
}: {
item: ChatRenderItem;
isPending: boolean;
transformContent?: (content: string) => string;
+ onQuickAction?: (action: ChatQuickAction) => void | Promise<unknown>;
+ quickActionsDisabled: boolean;
+ onRegenerateQuickActions?: (message: ChatMessage) => void | Promise<unknown>;
+ latestAssistantMessageId: string | null;
+ quickActionsPendingMessageId: string | null;
}) {
// The live row and the persisted assistant row both land here under one key,
// and both render <AssistantMessage> — same component type, same position —
@@ -332,6 +393,8 @@ const MessageBubble = memo(function MessageBubble({
taskId={item.taskId}
isPending={isPending}
transformContent={transformContent}
+ onQuickAction={onQuickAction}
+ quickActionsDisabled={quickActionsDisabled}
/>
);
}
@@ -369,6 +432,11 @@ const MessageBubble = memo(function MessageBubble({
message={message}
isPending={isPending}
transformContent={transformContent}
+ onQuickAction={onQuickAction}
+ quickActionsDisabled={quickActionsDisabled}
+ onRegenerateQuickActions={onRegenerateQuickActions}
+ canRegenerateQuickActions={message.id === latestAssistantMessageId}
+ quickActionsPending={quickActionsPendingMessageId === message.id}
/>
);
});
@@ -395,11 +463,21 @@ function AssistantMessage({
message,
isPending,
transformContent,
+ onQuickAction,
+ quickActionsDisabled,
+ onRegenerateQuickActions,
+ canRegenerateQuickActions = false,
+ quickActionsPending = false,
}: {
taskId: string | null;
message?: ChatMessage;
isPending: boolean;
transformContent?: (content: string) => string;
+ onQuickAction?: (action: ChatQuickAction) => void | Promise<unknown>;
+ quickActionsDisabled: boolean;
+ onRegenerateQuickActions?: (message: ChatMessage) => void | Promise<unknown>;
+ canRegenerateQuickActions?: boolean;
+ quickActionsPending?: boolean;
}) {
const canFetchTaskMessages = isTaskMessageTaskId(taskId);
@@ -475,6 +553,21 @@ function AssistantMessage({
timeline={timeline}
isPending={isPending}
/>
+ {onQuickAction && (message.quick_actions?.length ?? 0) > 0 ? (
+ <QuickActions
+ actions={message.quick_actions ?? []}
+ disabled={quickActionsDisabled || isPending}
+ onSelect={onQuickAction}
+ onRegenerate={
+ onRegenerateQuickActions && canRegenerateQuickActions
+ ? () => onRegenerateQuickActions(message)
+ : undefined
+ }
+ pending={quickActionsPending}
+ />
+ ) : onQuickAction && quickActionsPending ? (
+ <QuickActionsSkeleton />
+ ) : null}
</>
)}
</div>
@@ -485,14 +578,171 @@ function transformTimeline(
timeline: ChatTimelineItem[],
transformContent?: (content: string) => string,
): ChatTimelineItem[] {
- if (!transformContent) return timeline;
return timeline.map((item) =>
item.type === "text" && item.content
- ? { ...item, content: transformContent(item.content) }
+ ? {
+ ...item,
+ content: transformContent
+ ? transformContent(stripChatQuickActionsProtocol(item.content))
+ : stripChatQuickActionsProtocol(item.content),
+ }
: item,
);
}
+function QuickActions({
+ actions,
+ disabled,
+ onSelect,
+ onRegenerate,
+ pending = false,
+}: {
+ actions: ChatQuickAction[];
+ disabled: boolean;
+ onSelect: (action: ChatQuickAction) => void | Promise<unknown>;
+ /** Present only on the session's latest turn — re-runs the suggestion pass. */
+ onRegenerate?: () => void | Promise<unknown>;
+ /**
+ * The turn is awaiting a supplement (a refresh is in flight): its old pills
+ * stay visible but inert, and the refresh icon spins until chat:quick_actions
+ * lands. Distinct from the local `regenerating` guard, which only covers the
+ * click → HTTP-ack window before the pending marker is observed.
+ */
+ pending?: boolean;
+}) {
+ const { t } = useT("chat");
+ const [submitting, setSubmitting] = useState(false);
+ const [regenerating, setRegenerating] = useState(false);
+ // The pending marker is the single source of truth: chat:quick_actions clears
+ // it on success, and useQuickActionsPendingTimeout clears it from the query
+ // cache if no supplement ever arrives. So `pending` going false is what stops
+ // the spinner — no component-local "expired" flag that only masks the UI while
+ // the cache stays stuck (MUL-5149 review).
+ const blocked = disabled || submitting || regenerating || pending;
+
+ const handleSelect = async (action: ChatQuickAction) => {
+ if (blocked) return;
+ setSubmitting(true);
+ try {
+ await onSelect(action);
+ } catch {
+ // The send path owns user-facing error feedback and optimistic rollback.
+ // Re-enable the chip so a transient failure can be retried.
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const handleRegenerate = async () => {
+ if (blocked || !onRegenerate) return;
+ setRegenerating(true);
+ try {
+ await onRegenerate();
+ } catch {
+ // The caller's mutation rolls the pending marker back; surface a toast so
+ // the silent re-enable isn't mistaken for "no suggestions this time".
+ toast.error(t(($) => $.message_list.quick_actions_regenerate_failed));
+ } finally {
+ setRegenerating(false);
+ }
+ };
+
+ const regenerateLabel = t(($) => $.message_list.quick_actions_regenerate);
+
+ return (
+ <div className="mt-2 border-t border-border/40 pt-2 animate-in fade-in slide-in-from-bottom-1 duration-300">
+ <div className="flex flex-wrap items-center gap-2" aria-label="Suggested follow-ups">
+ <QuickActionsHeading />
+ {actions.slice(0, 3).map((action, index) => (
+ // The whole pill previews its hidden prompt on hover: clicking
+ // sends a message the user has never seen, in their name — the
+ // tooltip flips that from commit-then-learn to learn-then-commit.
+ <Tooltip key={`${action.label}-${index}`}>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant={action.primary ? "brandSubtle" : "outline"}
+ size="sm"
+ className="max-w-full rounded-full px-3"
+ disabled={blocked}
+ onClick={() => void handleSelect(action)}
+ />
+ }
+ >
+ <span className="truncate">{action.label}</span>
+ {action.primary ? <ArrowUpRight aria-hidden="true" /> : null}
+ </TooltipTrigger>
+ <TooltipContent side="top" className="max-w-sm whitespace-pre-wrap break-words">
+ {action.prompt}
+ </TooltipContent>
+ </Tooltip>
+ ))}
+ {onRegenerate ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="shrink-0 rounded-full text-faint-foreground hover:text-foreground"
+ disabled={blocked}
+ aria-label={regenerateLabel}
+ onClick={() => void handleRegenerate()}
+ />
+ }
+ >
+ <RotateCw
+ aria-hidden="true"
+ className={
+ pending || regenerating ? "animate-spin" : undefined
+ }
+ />
+ </TooltipTrigger>
+ <TooltipContent side="top">{regenerateLabel}</TooltipContent>
+ </Tooltip>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+// Light inline prefix label for the follow-up pill row — the row sits below
+// the reply footer ("Replied in Xs · Copy") behind a faint top border, so
+// the pills read as a labelled next-steps strip, not part of the reply body.
+// shrink-0 keeps the label whole at the row start when narrow widths wrap
+// the pills.
+function QuickActionsHeading() {
+ const { t } = useT("chat");
+ return (
+ <span className="shrink-0 text-caption text-muted-foreground">
+ {t(($) => $.message_list.quick_actions_heading)}
+ </span>
+ );
+}
+
+// Pill-shaped placeholders shown between chat:done (which declared a pending
+// supplement) and chat:quick_actions. Widths are staggered so the row reads
+// as "buttons coming", not a loading bar. aria-hidden: nothing actionable to
+// announce yet.
+function QuickActionsSkeleton() {
+ // No local timeout: the shared pending marker drives visibility, and
+ // useQuickActionsPendingTimeout clears it from the query cache if no
+ // chat:quick_actions ever resolves it — so this unmounts on its own instead
+ // of only hiding itself while the cache stays stuck (MUL-5149 review).
+ return (
+ <div className="mt-2 border-t border-border/40 pt-2 animate-in fade-in duration-300">
+ <div className="flex flex-wrap items-center gap-2" aria-hidden="true">
+ <QuickActionsHeading />
+ <Skeleton className="h-8 w-24 rounded-full" />
+ <Skeleton className="h-8 w-32 rounded-full" />
+ <Skeleton className="h-8 w-28 rounded-full" />
+ </div>
+ </div>
+ );
+}
+
// Muted, localized notice shown in place of assistant text when a turn
// completed with no reply (message_kind === "no_response"). Explains the empty
// turn instead of rendering a blank bubble (MUL-4351).
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 413661b2d5..bad1d73233 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -43,11 +43,15 @@ import {
import {
useCreateChatSession,
useMarkChatSessionRead,
+ useRegenerateChatQuickActions,
useSetChatSessionArchived,
useSetChatSessionProject,
useUpdateChatSession,
} from "@multica/core/chat/mutations";
import { useChatStore } from "@multica/core/chat";
+import { chatQuickActionsPendingOptions } from "@multica/core/chat/queries";
+import { useQuickActionsPendingTimeout } from "@multica/core/chat/use-quick-actions-pending-timeout";
+import { useQuickActionsFailureToast } from "./use-quick-actions-failure-toast";
import { removeChatMessageFromCaches } from "@multica/core/realtime";
import { useChatDraftRestore } from "./use-chat-draft-restore";
import { useChatInputFocus } from "./use-chat-input-focus";
@@ -107,6 +111,15 @@ export function ChatWindow() {
const wsId = useWorkspaceId();
const isOpen = useChatStore((s) => s.isOpen);
const activeSessionId = useChatStore((s) => s.activeSessionId);
+ const { data: quickActionsPending = null } = useQuery(
+ chatQuickActionsPendingOptions(activeSessionId ?? ""),
+ );
+ // Drop a stuck pending marker (dead daemon / failed supplement) so the pill
+ // spinner stops and a later refresh starts clean (MUL-5149).
+ useQuickActionsPendingTimeout(activeSessionId ?? null, quickActionsPending);
+ // Toast when an accepted refresh later fails in the daemon (async half).
+ useQuickActionsFailureToast(activeSessionId ?? null);
+ const regenerateQuickActions = useRegenerateChatQuickActions();
const selectedAgentId = useChatStore((s) => s.selectedAgentId);
const selectedProjectId = useChatStore((s) => s.selectedProjectId);
const setOpen = useChatStore((s) => s.setOpen);
@@ -482,7 +495,9 @@ export function ChatWindow() {
// the draft for retry (ChatInput never cleared it).
let result;
try {
- result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);
+ result = await api.sendChatMessage(sessionId, finalContent, attachmentIds, {
+ quickActionsEnabled: useChatStore.getState().quickActionsEnabled,
+ });
} catch (err) {
apiLogger.error("sendChatMessage.error", { sessionId, err });
toast.error(t(($) => $.input.send_failed_toast));
@@ -829,6 +844,19 @@ export function ChatWindow() {
hasOlderMessages={!!hasOlderMessages}
isFetchingOlderMessages={isFetchingOlderMessages}
onLoadOlderMessages={() => void fetchOlderMessages()}
+ onQuickAction={(action) => handleSend(action.prompt)}
+ quickActionsDisabled={
+ !!pendingTaskId || isSessionArchived || isAgentArchived || noAgent
+ }
+ onRegenerateQuickActions={(message) =>
+ activeSessionId
+ ? regenerateQuickActions.mutateAsync({
+ sessionId: activeSessionId,
+ messageId: message.id,
+ })
+ : undefined
+ }
+ quickActionsPendingMessageId={quickActionsPending?.message_id ?? null}
/>
) : (
<EmptyState
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 87530ad580..3890f37c70 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -539,7 +539,9 @@ export function useChatController(opts?: { isActive?: boolean }) {
// the draft for retry (ChatInput never cleared it).
let result;
try {
- result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);
+ result = await api.sendChatMessage(sessionId, finalContent, attachmentIds, {
+ quickActionsEnabled: useChatStore.getState().quickActionsEnabled,
+ });
} catch (err) {
apiLogger.error("sendChatMessage.error", { sessionId, err });
// Invoke permission can be revoked mid-session; the send is refused with
diff --git a/packages/views/chat/components/use-quick-actions-failure-toast.ts b/packages/views/chat/components/use-quick-actions-failure-toast.ts
new file mode 100644
index 0000000000..250c52e0bf
--- /dev/null
+++ b/packages/views/chat/components/use-quick-actions-failure-toast.ts
@@ -0,0 +1,45 @@
+import { useEffect } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ chatKeys,
+ chatQuickActionsFailureOptions,
+} from "@multica/core/chat/queries";
+import type { ChatQuickActionsFailureState } from "@multica/core/types";
+import { toast } from "sonner";
+import { useT } from "../../i18n";
+
+/**
+ * Surfaces a toast when a session's explicit quick-actions refresh fails
+ * asynchronously — the HTTP call was accepted but the daemon's regeneration
+ * never produced suggestions, so the turn's pills are unchanged (MUL-5149). The
+ * failure arrives over chat:quick_actions with failed=true, which
+ * applyChatQuickActionsToCache turns into a one-shot client-only signal; this
+ * hook consumes it and clears it. The synchronous HTTP-failure path (409 busy,
+ * network) already toasts from QuickActions.handleRegenerate, so this covers
+ * only the async half — without it, a failed refresh would look identical to a
+ * successful one whose suggestions happened not to change.
+ *
+ * A stable toast id keyed on the failure nonce collapses duplicates when both
+ * chat surfaces (floating window + chat tab) are mounted and each runs this
+ * hook against the same signal. Mount once per surface that reads the marker.
+ */
+export function useQuickActionsFailureToast(sessionId: string | null): void {
+ const qc = useQueryClient();
+ const { t } = useT("chat");
+ const { data: failure = null } = useQuery(
+ chatQuickActionsFailureOptions(sessionId ?? ""),
+ );
+
+ useEffect(() => {
+ if (!sessionId || !failure) return;
+ toast.error(t(($) => $.message_list.quick_actions_regenerate_failed), {
+ id: `qa-refresh-fail:${sessionId}:${failure.at}`,
+ });
+ // Clear only this exact signal so a newer failure raised in the same tick
+ // is not swallowed.
+ qc.setQueryData<ChatQuickActionsFailureState | null>(
+ chatKeys.quickActionsFailure(sessionId),
+ (current) => (current && current.at === failure.at ? null : current),
+ );
+ }, [qc, t, sessionId, failure]);
+}
diff --git a/packages/views/chat/lib/quick-actions.test.ts b/packages/views/chat/lib/quick-actions.test.ts
new file mode 100644
index 0000000000..156e7d409b
--- /dev/null
+++ b/packages/views/chat/lib/quick-actions.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { stripChatQuickActionsProtocol } from "./quick-actions";
+
+describe("stripChatQuickActionsProtocol", () => {
+ it("strips complete and partial trailing protocol blocks", () => {
+ expect(
+ stripChatQuickActionsProtocol(
+ "Answer.\n```quick-actions\n[{\"label\":\"Continue\"}]\n```",
+ ),
+ ).toBe("Answer.");
+ expect(
+ stripChatQuickActionsProtocol(
+ "Answer.\r\n```quick-actions\r\n[{\"label\":",
+ ),
+ ).toBe("Answer.");
+ });
+
+ it("leaves ordinary content untouched", () => {
+ expect(stripChatQuickActionsProtocol("Answer with `quick-actions` inline."))
+ .toBe("Answer with `quick-actions` inline.");
+ expect(
+ stripChatQuickActionsProtocol(
+ "Example:\n```quick-actions\n[]\n```\nMore explanation.",
+ ),
+ ).toBe("Example:\n```quick-actions\n[]\n```\nMore explanation.");
+ });
+});
diff --git a/packages/views/chat/lib/quick-actions.ts b/packages/views/chat/lib/quick-actions.ts
new file mode 100644
index 0000000000..dcf1cd3da9
--- /dev/null
+++ b/packages/views/chat/lib/quick-actions.ts
@@ -0,0 +1,27 @@
+/**
+ * Hide the reserved agent-to-server quick-action footer while a response is
+ * still streaming. Persisted message content is already stripped server-side;
+ * this closes the short window where an incomplete JSON fence could otherwise
+ * flash in the live timeline.
+ */
+export function stripChatQuickActionsProtocol(content: string): string {
+ const matches = [
+ ...content.matchAll(/(?:^|\r?\n)```quick-actions(?:\r?\n|$)/g),
+ ];
+ const match = matches.at(-1);
+ if (!match || match.index == null) return content;
+
+ const footerStart = match.index;
+ const bodyStart = footerStart + match[0].length;
+ const closingFence = /\r?\n```/.exec(content.slice(bodyStart));
+ if (closingFence) {
+ const afterFence = content.slice(
+ bodyStart + closingFence.index + closingFence[0].length,
+ );
+ // Once later prose arrives, this was an ordinary example in the reply,
+ // not the reserved trailing footer.
+ if (afterFence.trim() !== "") return content;
+ }
+
+ return content.slice(0, footerStart).trimEnd();
+}
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 2b2ef55d59..b5e51458fe 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -61,7 +61,10 @@
"copy_action": "Copy",
"copied_toast": "Copied",
"copy_failed_toast": "Copy failed",
- "loading_older": "Loading older messages…"
+ "loading_older": "Loading older messages…",
+ "quick_actions_heading": "Follow-up questions",
+ "quick_actions_regenerate": "Regenerate suggestions",
+ "quick_actions_regenerate_failed": "Couldn't refresh suggestions. Please try again."
},
"session_history": {
"untitled": "Untitled",
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 345d440efe..cff65b5b00 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -145,7 +145,10 @@
"chat": {
"floating_title": "Floating window",
"floating_label": "Floating chat window",
- "floating_hint": "Show the floating chat button in the corner of every page. Off by default — turn it on to summon chat anywhere; when off, Chat lives only in this tab."
+ "floating_hint": "Show the floating chat button in the corner of every page. Off by default — turn it on to summon chat anywhere; when off, Chat lives only in this tab.",
+ "quick_actions_title": "Suggested follow-ups",
+ "quick_actions_label": "Generate suggested follow-ups",
+ "quick_actions_hint": "Generate up to three follow-up suggestions after each agent reply. When off, messages sent from this device no longer trigger generation; existing suggestions stay visible."
},
"issue": {
"description": "Choose which fields each create dialog keeps on its toolbar. Hidden fields stay available from the ⋯ menu and reappear while they hold a value.",
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index 76ff5c6946..270bd5bbdf 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -58,7 +58,10 @@
"copy_action": "コピー",
"copied_toast": "コピーしました",
"copy_failed_toast": "コピーに失敗しました",
- "loading_older": "古いメッセージを読み込み中…"
+ "loading_older": "古いメッセージを読み込み中…",
+ "quick_actions_heading": "フォローアップ質問",
+ "quick_actions_regenerate": "候補を再生成",
+ "quick_actions_regenerate_failed": "候補を再生成できませんでした。もう一度お試しください。"
},
"session_history": {
"untitled": "無題",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 5d46cfea04..e0cdb67d78 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -108,7 +108,10 @@
"send_error": "送信には Enter または Mod+Enter のみ使用できます。",
"unsafe_error": "このキーは文字入力や基本的なキーボード操作と競合します。",
"send_enter_hint": "Shift+Enterで段落の挿入、リストの継続、コードブロック内の改行ができます。",
- "categories": { "general": "一般", "navigation": "ナビゲーション" },
+ "categories": {
+ "general": "一般",
+ "navigation": "ナビゲーション"
+ },
"actions": {
"openSearch": { "label": "検索を開く", "description": "どこからでも検索やコマンドを実行します。" },
"createIssue": { "label": "Issueを作成", "description": "優先するissue作成フローを開きます。" },
@@ -142,7 +145,10 @@
"chat": {
"floating_title": "フローティングウィンドウ",
"floating_label": "フローティングチャット",
- "floating_hint": "すべてのページの隅にフローティングチャットボタンを表示します。デフォルトはオフ——オンにするとどこからでもチャットを呼び出せます。オフのときは専用タブでのみ利用できます。"
+ "floating_hint": "すべてのページの隅にフローティングチャットボタンを表示します。デフォルトはオフ——オンにするとどこからでもチャットを呼び出せます。オフのときは専用タブでのみ利用できます。",
+ "quick_actions_title": "おすすめアクション",
+ "quick_actions_label": "おすすめアクションを生成",
+ "quick_actions_hint": "エージェントの返信ごとに、次の操作の候補を最大3件生成します。オフにすると、このデバイスから送信したメッセージでは生成されなくなります。既存の候補は引き続き表示されます。"
},
"issue": {
"description": "各作成ダイアログのツールバーに常時表示するフィールドを選択します。非表示のフィールドは ⋯ メニューから引き続き使用でき、値がある間は自動的に表示されます。",
@@ -269,7 +275,11 @@
"empty": "{{scope}} ラベルはまだありません",
"no_results": "一致するラベルがありません",
"save_failed": "ラベルを保存できませんでした",
- "actions": { "open": "{{name}} の操作", "edit": "編集", "delete": "削除" },
+ "actions": {
+ "open": "{{name}} の操作",
+ "edit": "編集",
+ "delete": "削除"
+ },
"editor": {
"create_title": "新しいラベル",
"edit_title": "ラベルを編集",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index 288d8f85d5..60b67332aa 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -58,7 +58,10 @@
"copy_action": "복사",
"copied_toast": "복사했습니다",
"copy_failed_toast": "복사 실패",
- "loading_older": "이전 메시지를 불러오는 중…"
+ "loading_older": "이전 메시지를 불러오는 중…",
+ "quick_actions_heading": "후속 질문",
+ "quick_actions_regenerate": "제안 다시 생성",
+ "quick_actions_regenerate_failed": "제안을 다시 생성하지 못했습니다. 다시 시도해 주세요."
},
"session_history": {
"untitled": "제목 없음",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index db174d2bb8..dbdc875554 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -108,7 +108,10 @@
"send_error": "보내기는 Enter 또는 Mod+Enter만 사용할 수 있습니다.",
"unsafe_error": "이 키는 텍스트 입력이나 기본 키보드 탐색을 방해합니다.",
"send_enter_hint": "Shift+Enter로 단락을 삽입하거나 목록을 이어가고 코드 블록에서 줄을 바꿀 수 있습니다.",
- "categories": { "general": "일반", "navigation": "탐색" },
+ "categories": {
+ "general": "일반",
+ "navigation": "탐색"
+ },
"actions": {
"openSearch": { "label": "검색 열기", "description": "어디서나 검색하고 명령을 실행합니다." },
"createIssue": { "label": "Issue 만들기", "description": "선호하는 issue 만들기 흐름을 엽니다." },
@@ -142,7 +145,10 @@
"chat": {
"floating_title": "플로팅 창",
"floating_label": "플로팅 채팅 창",
- "floating_hint": "모든 페이지 모서리에 플로팅 채팅 버튼을 표시합니다. 기본값은 꺼짐 — 켜면 어디서나 채팅을 불러올 수 있고, 꺼면 채팅은 이 탭에서만 사용할 수 있습니다."
+ "floating_hint": "모든 페이지 모서리에 플로팅 채팅 버튼을 표시합니다. 기본값은 꺼짐 — 켜면 어디서나 채팅을 불러올 수 있고, 꺼면 채팅은 이 탭에서만 사용할 수 있습니다.",
+ "quick_actions_title": "추천 작업",
+ "quick_actions_label": "추천 작업 생성",
+ "quick_actions_hint": "에이전트가 답변할 때마다 후속 작업 추천을 최대 3개 생성합니다. 끄면 이 기기에서 보낸 메시지는 더 이상 생성을 트리거하지 않으며, 기존 추천은 계속 표시됩니다."
},
"issue": {
"description": "각 생성 방식의 툴바에 항상 표시할 필드를 선택합니다. 숨긴 필드는 ⋯ 메뉴에서 계속 사용할 수 있으며, 값이 있는 동안에는 자동으로 표시됩니다.",
@@ -269,7 +275,11 @@
"empty": "{{scope}} 레이블이 없습니다",
"no_results": "일치하는 레이블이 없습니다",
"save_failed": "레이블을 저장하지 못했습니다",
- "actions": { "open": "{{name}} 작업", "edit": "편집", "delete": "삭제" },
+ "actions": {
+ "open": "{{name}} 작업",
+ "edit": "편집",
+ "delete": "삭제"
+ },
"editor": {
"create_title": "새 레이블",
"edit_title": "레이블 편집",
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index 9c1c352a13..ef63277e51 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -58,7 +58,10 @@
"copy_action": "复制",
"copied_toast": "已复制",
"copy_failed_toast": "复制失败",
- "loading_older": "正在加载更早的消息…"
+ "loading_older": "正在加载更早的消息…",
+ "quick_actions_heading": "后续提问",
+ "quick_actions_regenerate": "重新生成建议",
+ "quick_actions_regenerate_failed": "无法重新生成建议,请重试。"
},
"session_history": {
"untitled": "无标题",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 3985f807cb..08a098963d 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -145,7 +145,10 @@
"chat": {
"floating_title": "悬浮窗",
"floating_label": "悬浮聊天窗",
- "floating_hint": "在每个页面右下角显示悬浮聊天按钮。默认关闭——打开后可随处召唤聊天;关闭时,聊天只在此标签页中可用。"
+ "floating_hint": "在每个页面右下角显示悬浮聊天按钮。默认关闭——打开后可随处召唤聊天;关闭时,聊天只在此标签页中可用。",
+ "quick_actions_title": "推荐操作",
+ "quick_actions_label": "生成推荐操作",
+ "quick_actions_hint": "智能体每次回复后自动生成最多三个后续操作建议。关闭后,本设备发送的消息不再触发生成;已有的建议仍会显示。"
},
"issue": {
"description": "选择各创建方式的工具栏中常驻显示的字段。隐藏的字段仍可从 ⋯ 菜单使用,有值时会自动显示。",
diff --git a/packages/views/settings/components/chat-tab.tsx b/packages/views/settings/components/chat-tab.tsx
index 6ece764fae..24afb5d472 100644
--- a/packages/views/settings/components/chat-tab.tsx
+++ b/packages/views/settings/components/chat-tab.tsx
@@ -22,6 +22,8 @@ export function ChatTab() {
const { t } = useT("settings");
const enabled = useChatStore((s) => s.floatingChatEnabled);
const setEnabled = useChatStore((s) => s.setFloatingChatEnabled);
+ const quickActionsEnabled = useChatStore((s) => s.quickActionsEnabled);
+ const setQuickActionsEnabled = useChatStore((s) => s.setQuickActionsEnabled);
return (
<SettingsTab title={t(($) => $.page.tabs.chat)}>
@@ -44,6 +46,25 @@ export function ChatTab() {
</SettingsRow>
</SettingsCard>
</SettingsSection>
+ <SettingsSection title={t(($) => $.chat.quick_actions_title)}>
+ <SettingsCard>
+ <SettingsRow
+ label={t(($) => $.chat.quick_actions_label)}
+ description={t(($) => $.chat.quick_actions_hint)}
+ >
+ <Switch
+ checked={quickActionsEnabled}
+ onCheckedChange={(checked) => {
+ setQuickActionsEnabled(checked);
+ toast.success(t(($) => $.auto_save.toast_saved), {
+ id: "settings-auto-save",
+ });
+ }}
+ aria-label={t(($) => $.chat.quick_actions_label)}
+ />
+ </SettingsRow>
+ </SettingsCard>
+ </SettingsSection>
</SettingsTab>
);
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 375bb80a5c..abab0168bf 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -855,6 +855,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/tasks/{taskId}/wait-local-directory", h.MarkTaskWaitingLocalDirectory)
r.Post("/tasks/{taskId}/progress", h.ReportTaskProgress)
r.Post("/tasks/{taskId}/complete", h.CompleteTask)
+ r.Post("/tasks/{taskId}/quick-actions", h.SupplementTaskQuickActions)
r.Post("/tasks/{taskId}/fail", h.FailTask)
r.Post("/tasks/{taskId}/usage", h.ReportTaskUsage)
r.Post("/tasks/{taskId}/messages", h.ReportTaskMessages)
@@ -1432,6 +1433,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Patch("/archive", h.SetChatSessionArchived)
r.Delete("/", h.DeleteChatSession)
r.Post("/messages", h.SendChatMessage)
+ // Explicit "refresh" of a turn's quick actions: re-runs the
+ // daemon suggestion pass for the latest assistant reply (MUL-5149).
+ r.Post("/quick-actions/regenerate", h.RegenerateChatQuickActions)
r.Get("/messages", h.ListChatMessages)
r.Get("/messages/page", h.ListChatMessagesPage)
r.Get("/pending-task", h.GetPendingChatTask)
diff --git a/server/internal/daemon/chat_suggest.go b/server/internal/daemon/chat_suggest.go
new file mode 100644
index 0000000000..a5fe66190f
--- /dev/null
+++ b/server/internal/daemon/chat_suggest.go
@@ -0,0 +1,236 @@
+package daemon
+
+import (
+ "context"
+ "log/slog"
+ "strings"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+// chatSuggestTimeout bounds the follow-up suggestion pass. The pass runs in
+// the background after the completion callback, so it no longer delays the
+// user's turn — the bound just keeps a hung provider from pinning a session's
+// suggest slot (and the client-side placeholder) for long.
+const chatSuggestTimeout = 20 * time.Second
+
+// chatSuggestPrompt is the entire instruction set for the suggestion pass.
+// Unlike the retired runtime-brief section, this is the turn's ONLY task:
+// dedicated single-instruction calls follow output formats reliably where
+// "when useful, also append X" instructions buried in a long brief decay over
+// a conversation (MUL-5149 follow-up; see PR discussion for the field data).
+const chatSuggestPrompt = `This is an automated system request, not a user message. Never mention it or its output in future replies.
+
+Based on the conversation so far, produce exactly 3 follow-up actions the user is likely to want next. Write them in the same language the user has been writing in. Each action needs:
+- "label": short button text (a few words)
+- "prompt": the complete message to send on the user's behalf when clicked (self-contained, imperative)
+- "primary": true on exactly one action, the one you most recommend
+
+Output ONLY a JSON array, no prose, no code fences:
+[{"label":"...","prompt":"...","primary":true}]
+
+Only when the conversation truly offers nothing worth following up on, output [].`
+
+// chatSuggestHandle wraps the cancel func in a comparable pointer so a
+// finishing job only deregisters itself (CompareAndDelete), never a newer
+// job that replaced it.
+type chatSuggestHandle struct{ cancel context.CancelFunc }
+
+// cancelPendingChatSuggest aborts an in-flight suggestion pass for the given
+// chat session. Called when a new turn starts on that session: two resumed
+// provider invocations must not race on one session, and suggestions for a
+// superseded turn are stale anyway.
+func (d *Daemon) cancelPendingChatSuggest(sessionID string) {
+ if v, ok := d.chatSuggestCancels.LoadAndDelete(sessionID); ok {
+ v.(*chatSuggestHandle).cancel()
+ }
+}
+
+// chatSuggestJob builds the deferred suggestion pass for a completed direct
+// chat turn. reportTaskResult invokes it (on its own goroutine) only after
+// the completion callback succeeded — the supplement targets the assistant
+// row that callback writes, and the user's next turn must never wait on this.
+//
+// mainUsage is the main turn's per-model usage: the server's task_usage
+// upsert REPLACES counts per (task, provider, model), so the job must
+// re-report merged totals, not the suggest delta alone.
+func (d *Daemon) chatSuggestJob(task Task, backend agent.Backend, opts agent.ExecOptions, providerSessionID string, mainUsage map[string]agent.TokenUsage, provider string, taskLog *slog.Logger) func() {
+ return func() {
+ ctx, cancel := context.WithCancel(context.Background())
+ handle := &chatSuggestHandle{cancel: cancel}
+ d.chatSuggestCancels.Store(task.ChatSessionID, handle)
+ defer func() {
+ cancel()
+ d.chatSuggestCancels.CompareAndDelete(task.ChatSessionID, handle)
+ }()
+
+ raw, usage, _ := d.runChatSuggestPass(ctx, backend, opts, providerSessionID, taskLog)
+ if ctx.Err() != nil {
+ // A newer turn on this session cancelled us: its user message
+ // supersedes these suggestions. Skip the supplement — the client
+ // placeholder for the old turn resolves via its own timeout.
+ taskLog.Debug("chat suggest pass cancelled by newer turn")
+ return
+ }
+
+ reportCtx, reportCancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer reportCancel()
+ if len(usage) > 0 {
+ merged := mergeUsage(mainUsage, usage)
+ entries := make([]TaskUsageEntry, 0, len(merged))
+ for model, u := range merged {
+ if u.InputTokens == 0 && u.OutputTokens == 0 && u.CacheReadTokens == 0 && u.CacheWriteTokens == 0 {
+ continue
+ }
+ entries = append(entries, TaskUsageEntry{
+ Provider: provider,
+ Model: model,
+ InputTokens: u.InputTokens,
+ OutputTokens: u.OutputTokens,
+ CacheReadTokens: u.CacheReadTokens,
+ CacheWriteTokens: u.CacheWriteTokens,
+ })
+ }
+ if err := d.client.ReportTaskUsage(reportCtx, task.ID, entries); err != nil {
+ taskLog.Warn("chat suggest usage report failed", "error", err)
+ }
+ }
+ // Always send the supplement — an empty raw resolves the client's
+ // pending placeholder with "no suggestions this turn".
+ if err := d.client.SupplementTaskQuickActions(reportCtx, task.ID, raw); err != nil {
+ taskLog.Warn("chat suggest supplement failed", "error", err)
+ }
+ }
+}
+
+// runChatQuickActionsRegenerate services an on-demand quick-actions refresh
+// (MUL-5149). Unlike the deferred chatSuggestJob (which trails a real reply),
+// this IS the whole task: it resumes the target turn's provider session, runs
+// only the suggestion prompt, and supplements the target turn's assistant row
+// via the same server path (SupplementTaskQuickActions → chat:quick_actions) as
+// the automatic pass. It writes no assistant message: an empty completed result
+// on a task with no chat_input_task_id routes through the server's chat "no row"
+// branch, so no reply bubble appears and the session resume pointer is left
+// untouched (matching the automatic pass, which never advances it either).
+func (d *Daemon) runChatQuickActionsRegenerate(ctx context.Context, task Task, backend agent.Backend, opts agent.ExecOptions, provider string, taskLog *slog.Logger) (TaskResult, error) {
+ taskLog.Info("chat quick-actions regenerate",
+ "target_task", shortID(task.RegenerateQuickActionsFor),
+ "resume", opts.ResumeSessionID != "",
+ )
+ raw, usage, ok := d.runChatSuggestPass(ctx, backend, opts, opts.ResumeSessionID, taskLog)
+
+ // Report the pass's own token spend on this regenerate task (its own row —
+ // no merge with a main turn, there isn't one). Same shape as chatSuggestJob.
+ // Reported on every outcome — a failed pass still burned tokens.
+ var usageEntries []TaskUsageEntry
+ for model, u := range usage {
+ if u.InputTokens == 0 && u.OutputTokens == 0 && u.CacheReadTokens == 0 && u.CacheWriteTokens == 0 {
+ continue
+ }
+ usageEntries = append(usageEntries, TaskUsageEntry{
+ Provider: provider,
+ Model: model,
+ InputTokens: u.InputTokens,
+ OutputTokens: u.OutputTokens,
+ CacheReadTokens: u.CacheReadTokens,
+ CacheWriteTokens: u.CacheWriteTokens,
+ })
+ }
+
+ if !ok {
+ // The provider pass itself FAILED (didn't start / didn't complete /
+ // timed out) — distinct from a completed pass that produced no
+ // suggestions. Do NOT supplement: an empty raw would silently rebroadcast
+ // the old pills as if the refresh succeeded. Report failure so FailTask →
+ // resolveFailedRegenerateQuickActions broadcasts a FAILED
+ // chat:quick_actions and the user gets feedback (MUL-5149 review §3).
+ return TaskResult{
+ Status: "blocked",
+ FailureReason: "quick_actions_generation_failed",
+ Usage: usageEntries,
+ }, nil
+ }
+
+ // Generation succeeded (raw may be an empty list — a genuine "no new
+ // suggestions" that keeps the existing pills). Supplement the target turn.
+ reportCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := d.client.SupplementTaskQuickActions(reportCtx, task.RegenerateQuickActionsFor, raw); err != nil {
+ // The supplement never landed, so no chat:quick_actions resolved the
+ // client's refresh spinner. Report failure (never retried, writes no
+ // visible turn — see FailTask's regenerate gates) so the server converges
+ // the marker via resolveFailedRegenerateQuickActions instead of leaving
+ // the client to its own timeout (MUL-5149).
+ taskLog.Warn("chat quick-actions regenerate supplement failed", "error", err)
+ return TaskResult{
+ Status: "blocked",
+ FailureReason: "quick_actions_supplement_failed",
+ Usage: usageEntries,
+ }, nil
+ }
+ return TaskResult{Status: "completed", Comment: "", Usage: usageEntries}, nil
+}
+
+// runChatSuggestPass runs one extra provider turn on the just-finished chat
+// session and returns its raw text output (the JSON array, hopefully — the
+// server parses leniently and treats garbage as "no suggestions"). ok is false
+// only when the pass itself FAILED (didn't start, didn't complete, or timed
+// out), distinct from a pass that completed and simply produced no suggestions
+// (ok=true, possibly empty raw). The automatic pass is best-effort and ignores
+// ok; the explicit-refresh caller uses it to surface failure feedback (MUL-5149).
+//
+// The pass deliberately reuses the main turn's backend and exec options so it
+// lands on the same provider, model, and workdir; only the resume pointer,
+// timeouts, and prompt differ. Its transcript messages are discarded — the
+// suggestion turn must not appear in the task's reported message log.
+//
+// Known debt: providers whose resume appends in place (rather than forking a
+// new session file) keep the suggestion exchange in the session history the
+// next user turn resumes. The prompt's leading line instructs the model to
+// never surface it.
+func (d *Daemon) runChatSuggestPass(ctx context.Context, backend agent.Backend, opts agent.ExecOptions, sessionID string, taskLog *slog.Logger) (raw string, usage map[string]agent.TokenUsage, ok bool) {
+ suggestCtx, cancel := context.WithTimeout(ctx, chatSuggestTimeout)
+ defer cancel()
+
+ opts.ResumeSessionID = sessionID
+ opts.ResumeExpected = true
+ opts.Timeout = chatSuggestTimeout
+ opts.IdleWatchdogTimeout = chatSuggestTimeout
+
+ start := time.Now()
+ session, err := backend.Execute(suggestCtx, chatSuggestPrompt, opts)
+ if err != nil {
+ taskLog.Warn("chat suggest pass failed to start", "error", err)
+ return "", nil, false
+ }
+
+ // Drain and discard the message stream: backends block on an undrained
+ // channel, and none of these messages belong in the task transcript.
+ msgDone := make(chan struct{})
+ go func() {
+ defer close(msgDone)
+ for range session.Messages {
+ }
+ }()
+
+ select {
+ case result := <-session.Result:
+ <-msgDone
+ if result.Status != "completed" {
+ taskLog.Warn("chat suggest pass did not complete",
+ "status", result.Status,
+ "error", result.Error,
+ )
+ return "", result.Usage, false
+ }
+ taskLog.Debug("chat suggest pass finished",
+ "duration", time.Since(start).Round(time.Second).String(),
+ "output_bytes", len(result.Output),
+ )
+ return strings.TrimSpace(result.Output), result.Usage, true
+ case <-suggestCtx.Done():
+ taskLog.Warn("chat suggest pass timed out or was cancelled", "timeout", chatSuggestTimeout.String())
+ return "", nil, false
+ }
+}
diff --git a/server/internal/daemon/chat_suggest_test.go b/server/internal/daemon/chat_suggest_test.go
new file mode 100644
index 0000000000..1161aa9997
--- /dev/null
+++ b/server/internal/daemon/chat_suggest_test.go
@@ -0,0 +1,61 @@
+package daemon
+
+import (
+ "context"
+ "log/slog"
+ "testing"
+
+ "github.com/multica-ai/multica/server/pkg/agent"
+)
+
+func TestRunChatSuggestPassReturnsTrimmedOutputAndResumesSession(t *testing.T) {
+ t.Parallel()
+ backend := &fakeBackend{
+ results: []agent.Result{{
+ Status: "completed",
+ Output: "\n[{\"label\":\"Next\",\"prompt\":\"Do the next thing\"}]\n",
+ Usage: map[string]agent.TokenUsage{"m1": {InputTokens: 10, OutputTokens: 5}},
+ }},
+ }
+ d := &Daemon{logger: slog.Default()}
+
+ raw, usage, ok := d.runChatSuggestPass(context.Background(), backend, agent.ExecOptions{Model: "m1"}, "sess-1", slog.Default())
+ if !ok {
+ t.Fatal("a completed pass must report ok=true")
+ }
+ if raw != `[{"label":"Next","prompt":"Do the next thing"}]` {
+ t.Fatalf("raw = %q", raw)
+ }
+ if usage["m1"].OutputTokens != 5 {
+ t.Fatalf("usage must be forwarded, got %+v", usage)
+ }
+ if len(backend.calls) != 1 {
+ t.Fatalf("expected one backend call, got %d", len(backend.calls))
+ }
+ opts := backend.calls[0]
+ if opts.ResumeSessionID != "sess-1" || !opts.ResumeExpected {
+ t.Fatalf("suggest pass must resume the finished session, got %+v", opts)
+ }
+ if opts.Timeout != chatSuggestTimeout || opts.IdleWatchdogTimeout != chatSuggestTimeout {
+ t.Fatalf("suggest pass must narrow its timeouts, got %+v", opts)
+ }
+}
+
+func TestRunChatSuggestPassSoftFailsOnErrorAndNonCompletion(t *testing.T) {
+ t.Parallel()
+ d := &Daemon{logger: slog.Default()}
+
+ failedStart := &fakeBackend{errors: []error{context.DeadlineExceeded}, results: []agent.Result{{}}}
+ if raw, _, ok := d.runChatSuggestPass(context.Background(), failedStart, agent.ExecOptions{}, "sess-1", slog.Default()); raw != "" || ok {
+ t.Fatalf("start failure must report ok=false and no suggestions, got raw=%q ok=%v", raw, ok)
+ }
+
+ notCompleted := &fakeBackend{results: []agent.Result{{Status: "timeout", Error: "slow", Usage: map[string]agent.TokenUsage{"m": {InputTokens: 1}}}}}
+ raw, usage, ok := d.runChatSuggestPass(context.Background(), notCompleted, agent.ExecOptions{}, "sess-1", slog.Default())
+ if raw != "" || ok {
+ t.Fatalf("non-completed result must report ok=false and no suggestions, got raw=%q ok=%v", raw, ok)
+ }
+ if usage["m"].InputTokens != 1 {
+ t.Fatalf("tokens burned by a failed pass must still be reported, got %+v", usage)
+ }
+}
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 4ac3fb1d64..0cbf7b7557 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -370,7 +370,7 @@ func (c *Client) ReportTaskMessages(ctx context.Context, taskID string, messages
}, nil)
}
-func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, sessionID, workDir string, sessionRolloutMissing bool, retiredSessionID string) error {
+func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, sessionID, workDir string, quickActionsPending bool, sessionRolloutMissing bool, retiredSessionID string) error {
body := map[string]any{"output": output}
if branchName != "" {
body["branch_name"] = branchName
@@ -381,6 +381,9 @@ func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, s
if workDir != "" {
body["work_dir"] = workDir
}
+ if quickActionsPending {
+ body["quick_actions_pending"] = true
+ }
if sessionRolloutMissing {
body["session_rollout_missing"] = true
}
@@ -390,6 +393,15 @@ func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, s
return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/complete", taskID), body, nil, defaultTerminalRetrySchedule)
}
+// SupplementTaskQuickActions delivers the background suggestion pass's raw
+// output for an already-completed chat task. Empty raw is meaningful — it
+// resolves the client-side pending placeholder with "no suggestions".
+func (c *Client) SupplementTaskQuickActions(ctx context.Context, taskID, raw string) error {
+ return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/quick-actions", taskID), map[string]any{
+ "raw": raw,
+ }, nil, defaultTerminalRetrySchedule)
+}
+
func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []TaskUsageEntry) error {
if len(usage) == 0 {
return nil
diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.go
index 360ae181af..dd7fc27472 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -420,7 +420,7 @@ func TestTerminalReportsCarryRetiredSessionID(t *testing.T) {
name: "complete",
endpoint: "/api/daemon/tasks/task-1/complete",
call: func(c *Client) error {
- return c.CompleteTask(context.Background(), "task-1", "done", "", "", "/tmp/wd", false, "POISONED-S")
+ return c.CompleteTask(context.Background(), "task-1", "done", "", "", "/tmp/wd", false, false, "POISONED-S")
},
},
{
@@ -463,7 +463,7 @@ func TestTerminalReportsOmitEmptyRetiredSessionID(t *testing.T) {
}))
defer srv.Close()
- if err := NewClient(srv.URL).CompleteTask(context.Background(), "task-1", "done", "", "sess-1", "/tmp/wd", false, ""); err != nil {
+ if err := NewClient(srv.URL).CompleteTask(context.Background(), "task-1", "done", "", "sess-1", "/tmp/wd", false, false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
if _, present := body["retired_session_id"]; present {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index f3762491e6..f00d698534 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -156,6 +156,10 @@ type terminalTaskReport struct {
sessionID string
workDir string
failureReason string
+ // quickActionsPending is true when a direct-chat turn will be followed by a
+ // background quick-actions suggestion pass (MUL-5149); the server raises the
+ // client's pill placeholder on chat:done.
+ quickActionsPending bool
// sessionRolloutMissing is true when the daemon withheld this task's Codex
// session because its rollout was not in the store (MUL-5305). The server
// clears the resume pointer and flags the continuity gap for the next claim.
@@ -259,6 +263,10 @@ type Daemon struct {
mu sync.Mutex
workspaces map[string]*workspaceState
runtimeIndex map[string]Runtime // runtimeID -> Runtime for provider lookups
+ // chatSuggestCancels maps chat session id -> *chatSuggestHandle for the
+ // in-flight background suggestion pass, so a new turn on the same session
+ // can abort it (stale suggestions + no concurrent resume on one session).
+ chatSuggestCancels sync.Map
// profileLaunchSpecs maps a custom runtime profile_id -> the absolute
// executable path plus fixed launch args resolved for that profile
// (MUL-3284). Populated in registerRuntimesForWorkspace when a profile's
@@ -4120,10 +4128,21 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
branchName: result.BranchName,
sessionID: result.SessionID,
workDir: result.WorkDir,
+ quickActionsPending: result.QuickActionsPending,
sessionRolloutMissing: result.SessionRolloutMissing,
retiredSessionID: result.RetiredSessionID,
})
if err == nil {
+ // Completion landed: the assistant row exists, so the deferred
+ // suggestion pass can now run and supplement it. Deliberately
+ // detached from taskWG and the daemon root ctx: best-effort and
+ // bounded (~20s pass + 30s report), it must not hold up slot
+ // release or graceful shutdown — a shutdown mid-pass just means
+ // this turn's supplement never arrives and the client skeleton
+ // times out.
+ if result.QuickActionsSuggest != nil {
+ go result.QuickActionsSuggest()
+ }
return
}
// CompleteTask retries transient errors internally. A transient
@@ -4209,7 +4228,7 @@ func (d *Daemon) reportTerminalTask(parentCtx context.Context, report terminalTa
switch report.kind {
case terminalTaskReportComplete:
- return d.client.CompleteTask(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir, report.sessionRolloutMissing, report.retiredSessionID)
+ return d.client.CompleteTask(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir, report.quickActionsPending, report.sessionRolloutMissing, report.retiredSessionID)
case terminalTaskReportFail:
return d.client.FailTask(ctx, report.taskID, report.errorMessage, report.sessionID, report.workDir, report.failureReason, report.sessionRolloutMissing, report.retiredSessionID)
default:
@@ -4726,6 +4745,12 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
return TaskResult{}, fmt.Errorf("refusing to spawn agent: task has no workspace_id (task_id=%s)", task.ID)
}
+ // A new turn on a chat session supersedes any background suggestion pass
+ // still running for the previous turn (see chat_suggest.go).
+ if task.ChatSessionID != "" {
+ d.cancelPendingChatSuggest(task.ChatSessionID)
+ }
+
prepareTimeout := d.effectiveTaskPrepareTimeout()
prepareCtx, cancelPrepare := context.WithTimeoutCause(ctx, prepareTimeout, errTaskPrepareTimeout)
prepareComplete := false
@@ -5389,6 +5414,15 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
execOpts.SystemPrompt = runtimeBrief
}
+ // Quick-actions refresh (MUL-5149): this task carries no user turn — it only
+ // re-runs the suggestion pass for an existing assistant reply and supplements
+ // that reply's row. Resume pointer, backend, and workdir are already prepared
+ // above, so diverge here, before the main provider turn, and never write a
+ // reply.
+ if task.RegenerateQuickActionsFor != "" {
+ return d.runChatQuickActionsRegenerate(ctx, task, backend, execOpts, provider, taskLog)
+ }
+
taskLog.Debug("invoking backend",
"provider", provider,
"model", model,
@@ -5486,6 +5520,23 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
"agent_error", result.Error,
)
+ // Follow-up suggestion pass for direct (non-channel) chat turns: one extra
+ // resumed provider turn whose only job is emitting the quick-actions JSON.
+ // Deferred: the completed return below carries the job, and
+ // reportTaskResult starts it only after the completion callback succeeds —
+ // the user's turn ends immediately, suggestions arrive as a supplement.
+ // Skipped for channel-backed sessions (no pill surface), empty replies
+ // (the no_response contract owns those), and poisoned outputs (blocked
+ // path handles those).
+ suggestEligible := result.Status == "completed" && task.ChatSessionID != "" &&
+ task.ChatChannelType == "" && !task.QuickActionsDisabled &&
+ result.SessionID != "" && strings.TrimSpace(result.Output) != ""
+ if suggestEligible {
+ if _, poisoned := classifyPoisonedOutput(result.Output); poisoned {
+ suggestEligible = false
+ }
+ }
+
// Convert agent usage map to task usage entries.
var usageEntries []TaskUsageEntry
for model, u := range result.Usage {
@@ -5563,14 +5614,19 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
FailureReason: reason,
}, nil
}
- return TaskResult{
- Status: "completed",
- Comment: result.Output,
- SessionID: result.SessionID,
- WorkDir: env.WorkDir,
- EnvRoot: env.RootDir,
- Usage: usageEntries,
- }, nil
+ taskResult = TaskResult{
+ Status: "completed",
+ Comment: result.Output,
+ SessionID: result.SessionID,
+ WorkDir: env.WorkDir,
+ EnvRoot: env.RootDir,
+ Usage: usageEntries,
+ QuickActionsPending: suggestEligible,
+ }
+ if suggestEligible {
+ taskResult.QuickActionsSuggest = d.chatSuggestJob(task, backend, execOpts, result.SessionID, result.Usage, provider, taskLog)
+ }
+ return taskResult, nil
case "timeout":
// Surface session_id/work_dir so the chat resume pointer is kept
// in sync even when the agent times out after building a session.
diff --git a/server/internal/daemon/execenv/runtime_config_delivery_test.go b/server/internal/daemon/execenv/runtime_config_delivery_test.go
index b6450326ef..9b810ecc2d 100644
--- a/server/internal/daemon/execenv/runtime_config_delivery_test.go
+++ b/server/internal/daemon/execenv/runtime_config_delivery_test.go
@@ -150,6 +150,24 @@ func TestChannelDisplayName(t *testing.T) {
}
}
+// Quick actions moved to the daemon's dedicated post-completion suggestion
+// pass; the brief must no longer teach the in-band footer syntax to anyone —
+// a taught agent would emit footers the transcript then has to strip.
+func TestQuickActionsInstructionsAbsentFromAllChatBriefs(t *testing.T) {
+ t.Parallel()
+ contexts := []TaskContextForEnv{
+ {ChatSessionID: "c-1", AgentName: "Eve", AgentID: "eve-1"},
+ {ChatSessionID: "c-1", ChatChannelType: ChannelTypeSlack, AgentName: "Eve", AgentID: "eve-1"},
+ {ChatSessionID: "c-1", ChatChannelType: ChannelTypeFeishu, AgentName: "Eve", AgentID: "eve-1"},
+ }
+ for _, ctx := range contexts {
+ brief := buildMetaSkillContent("claude", ctx)
+ if strings.Contains(brief, "```quick-actions") || strings.Contains(brief, "### Quick Actions") {
+ t.Fatalf("brief (channel=%q) must not teach the in-band quick-actions syntax", ctx.ChatChannelType)
+ }
+ }
+}
+
// outputSection extracts the brief's `## Output` section for readable failures.
func outputSection(brief string) string {
idx := strings.Index(brief, "\n## Output\n")
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 5dfd4f8b5d..e0be14772f 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -380,7 +380,11 @@ func writeWorkflowHeader(b *strings.Builder) {
b.WriteString("### Workflow\n\n")
}
-// writeWorkflowChat emits the chat-mode workflow.
+// writeWorkflowChat emits the chat-mode workflow. Follow-up quick actions are
+// deliberately NOT taught here: the daemon generates them in a dedicated
+// post-completion suggestion pass (chat_suggest.go), because an optional
+// formatting instruction in this brief proved unreliable across providers and
+// long conversations.
func writeWorkflowChat(b *strings.Builder) {
b.WriteString("**You are in chat mode.** A user is messaging you directly in a chat window.\n\n")
b.WriteString("- Respond conversationally and helpfully to the user's message\n")
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index b45060122e..38a91be089 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -90,6 +90,8 @@ type Task struct {
NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; empty on cold start
ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Drives the channel-awareness block in the prompt
+ QuickActionsDisabled bool `json:"quick_actions_disabled,omitempty"` // sender opted this turn out of follow-up suggestions — skip the suggestion pass at the source
+ RegenerateQuickActionsFor string `json:"regenerate_quick_actions_for,omitempty"` // set → run ONLY the suggestion pass (no reply) and supplement the named turn's assistant row (MUL-5149 quick-actions refresh)
ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; selects which read command the prompt tells the agent to start with
ChatMessage string `json:"chat_message,omitempty"` // user message content for chat tasks
ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments linked to the chat message; agent uses these to `multica attachment download <id>`
@@ -268,6 +270,15 @@ type TaskResult struct {
// abandoned as unresumable (GH #6066). Forwarded on every terminal path,
// including the completed one: a fresh-session retry that SUCCEEDS is
// precisely when the abandoned id would otherwise stay selectable.
- RetiredSessionID string `json:"-"`
- Usage []TaskUsageEntry `json:"usage,omitempty"` // per-model token usage
+ RetiredSessionID string `json:"-"`
+ // QuickActionsPending declares on the complete callback that a background
+ // quick-actions suggestion pass will follow for this direct-chat turn
+ // (MUL-5149); the server raises the client's pill placeholder on chat:done.
+ QuickActionsPending bool `json:"-"`
+ // QuickActionsSuggest is the deferred suggestion pass; reportTaskResult
+ // invokes it on its own goroutine only AFTER the completion callback
+ // succeeds, so the user's turn ends immediately and suggestions arrive as a
+ // later chat:quick_actions supplement (MUL-5149).
+ QuickActionsSuggest func() `json:"-"`
+ Usage []TaskUsageEntry `json:"usage,omitempty"` // per-model token usage
}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 800a9e5d71..e5573dca07 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -322,39 +322,41 @@ type AgentTaskResponse struct {
// when WorkDir is empty, or when stripping leaves nothing. See
// relativeWorkDir() for the full rules. Older clients can still read
// WorkDir directly; newer UIs should prefer RelativeWorkDir.
- RelativeWorkDir string `json:"relative_work_dir,omitempty"`
- TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task
- CoalescedCommentIDs []string `json:"coalesced_comment_ids,omitempty"` // MUL-4195: earlier comments folded into this run when it had not yet started, so a single run still covers every deliberate comment; trigger_comment_id is the newest. Surfaced so the UI can show which comments a run covered. omitempty so old clients ignore it
- CoalescedComments []CoalescedCommentData `json:"coalesced_comments,omitempty"` // MUL-4195: full detail (thread_id/author/created_at/content) of the folded comments, so the daemon prompt can address each without assuming they share the triggering thread. omitempty so old clients ignore it
- DeliveredCommentIDs []string `json:"delivered_comment_ids"` // always present: [] is an authoritative empty receipt, while field absence identifies responses from legacy servers
- TriggerThreadID string `json:"trigger_thread_id,omitempty"` // root comment ID for the triggering thread
- TriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment
- TriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes
- TriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind of the triggering comment
- TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author
- NewCommentCount int `json:"new_comment_count,omitempty"` // trigger-thread comments since last run; excludes injected trigger + own comments; omitempty so old daemons ignore it
- NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it
- ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
- ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Makes the agent channel-aware (read history from the channel, not Multica)
- ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`
- ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks
- ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry
- ChatIntro bool `json:"chat_intro,omitempty"` // true for the agent's proactive self-introduction chat (is_agent_intro session, no user message); the daemon builds an intro prompt instead of a reply prompt
- AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasks
- AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this task
- AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context
- AutopilotDescription string `json:"autopilot_description,omitempty"` // autopilot description used as task prompt
- AutopilotSource string `json:"autopilot_source,omitempty"` // manual, schedule, webhook, or api
- AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs
- QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
- QuickCreatePriority string `json:"quick_create_priority,omitempty"` // explicit priority selected in quick-create
- QuickCreateDueDate string `json:"quick_create_due_date,omitempty"` // explicit calendar due date selected in quick-create
- QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachment ids uploaded in the quick-create prompt and bound on issue create
- HandoffNote string `json:"handoff_note,omitempty"` // assignment handoff instruction; rendered into the run's opening prompt + issue_context.md (omitempty so old daemons ignore it)
- SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader
- SquadName string `json:"squad_name,omitempty"` // display name for the picker squad
- ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under
- ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, resolved on claim for prompt context
+ RelativeWorkDir string `json:"relative_work_dir,omitempty"`
+ TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task
+ CoalescedCommentIDs []string `json:"coalesced_comment_ids,omitempty"` // MUL-4195: earlier comments folded into this run when it had not yet started, so a single run still covers every deliberate comment; trigger_comment_id is the newest. Surfaced so the UI can show which comments a run covered. omitempty so old clients ignore it
+ CoalescedComments []CoalescedCommentData `json:"coalesced_comments,omitempty"` // MUL-4195: full detail (thread_id/author/created_at/content) of the folded comments, so the daemon prompt can address each without assuming they share the triggering thread. omitempty so old clients ignore it
+ DeliveredCommentIDs []string `json:"delivered_comment_ids"` // always present: [] is an authoritative empty receipt, while field absence identifies responses from legacy servers
+ TriggerThreadID string `json:"trigger_thread_id,omitempty"` // root comment ID for the triggering thread
+ TriggerCommentContent string `json:"trigger_comment_content,omitempty"` // content of the triggering comment
+ TriggerSummary *string `json:"trigger_summary,omitempty"` // canonical short description snapshot — comment text / autopilot title — taken at task creation; survives source edits/deletes
+ TriggerAuthorType string `json:"trigger_author_type,omitempty"` // "agent" or "member" — author kind of the triggering comment
+ TriggerAuthorName string `json:"trigger_author_name,omitempty"` // display name of the triggering comment author
+ NewCommentCount int `json:"new_comment_count,omitempty"` // trigger-thread comments since last run; excludes injected trigger + own comments; omitempty so old daemons ignore it
+ NewCommentsSince string `json:"new_comments_since,omitempty"` // RFC3339 anchor (last run's started_at) the count is measured from; omitempty so old daemons ignore it
+ ChatSessionID string `json:"chat_session_id,omitempty"` // non-empty for chat tasks
+ ChatChannelType string `json:"chat_channel_type,omitempty"` // "slack" when the chat session is backed by an IM channel; empty for a web-only chat. Makes the agent channel-aware (read history from the channel, not Multica)
+ ChatInThread bool `json:"chat_in_thread,omitempty"` // true when the latest @mention was a thread reply; tells the agent to start with `multica chat thread` vs `multica chat history`
+ ChatMessage string `json:"chat_message,omitempty"` // user message for chat tasks
+ ChatMessageAttachments []ChatAttachmentMeta `json:"chat_message_attachments,omitempty"` // attachments on the user message — agent calls `multica attachment download <id>` per entry
+ ChatIntro bool `json:"chat_intro,omitempty"` // true for the agent's proactive self-introduction chat (is_agent_intro session, no user message); the daemon builds an intro prompt instead of a reply prompt
+ QuickActionsDisabled bool `json:"quick_actions_disabled,omitempty"` // sender opted out of follow-up suggestions for this turn — the daemon skips the suggestion pass entirely
+ RegenerateQuickActionsFor string `json:"regenerate_quick_actions_for,omitempty"` // set → this task only re-runs the suggestion pass for the named turn (no reply); the daemon supplements that task's assistant row (MUL-5149)
+ AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot-spawned tasks
+ AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this task
+ AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context
+ AutopilotDescription string `json:"autopilot_description,omitempty"` // autopilot description used as task prompt
+ AutopilotSource string `json:"autopilot_source,omitempty"` // manual, schedule, webhook, or api
+ AutopilotTriggerPayload json.RawMessage `json:"autopilot_trigger_payload,omitempty"` // optional trigger payload for webhook/api runs
+ QuickCreatePrompt string `json:"quick_create_prompt,omitempty"` // user's natural-language input for quick-create tasks
+ QuickCreatePriority string `json:"quick_create_priority,omitempty"` // explicit priority selected in quick-create
+ QuickCreateDueDate string `json:"quick_create_due_date,omitempty"` // explicit calendar due date selected in quick-create
+ QuickCreateAttachmentIDs []string `json:"quick_create_attachment_ids,omitempty"` // attachment ids uploaded in the quick-create prompt and bound on issue create
+ HandoffNote string `json:"handoff_note,omitempty"` // assignment handoff instruction; rendered into the run's opening prompt + issue_context.md (omitempty so old daemons ignore it)
+ SquadID string `json:"squad_id,omitempty"` // for quick-create tasks where the picker was a squad; Agent is still the resolved leader
+ SquadName string `json:"squad_name,omitempty"` // display name for the picker squad
+ ParentIssueID string `json:"parent_issue_id,omitempty"` // for quick-create tasks opened from "Add sub issue" — UUID of the parent issue the new issue should be filed under
+ ParentIssueIdentifier string `json:"parent_issue_identifier,omitempty"` // human-readable identifier (e.g. MUL-123) of the quick-create parent issue, resolved on claim for prompt context
// RequestingUserName + RequestingUserProfileDescription mirror the user
// the agent is acting on behalf of (see daemon/types.go). v1 sources them
// from the runtime owner so they're populated for daemon runtimes and
diff --git a/server/internal/handler/agent_builder_test.go b/server/internal/handler/agent_builder_test.go
index d8d4079848..b4a15d3fb6 100644
--- a/server/internal/handler/agent_builder_test.go
+++ b/server/internal/handler/agent_builder_test.go
@@ -391,7 +391,7 @@ func TestSendDirectChatMessageUsesCurrentlyBoundRuntime(t *testing.T) {
})
sent, err := testHandler.TaskService.SendDirectChatMessage(
- ctx, session, staleAgent, parseUUID(testUserID), "hello after the switch", nil, "member", parseUUID(testUserID),
+ ctx, session, staleAgent, parseUUID(testUserID), "hello after the switch", nil, "member", parseUUID(testUserID), false,
)
if err != nil {
t.Fatalf("SendDirectChatMessage: %v", err)
@@ -511,7 +511,7 @@ func TestSendDirectChatMessageWaitsForUncommittedRebind(t *testing.T) {
go func() {
sent, err := testHandler.TaskService.SendDirectChatMessage(
context.Background(), session, staleAgent, parseUUID(testUserID),
- "sent while the rebind was still open", nil, "member", parseUUID(testUserID),
+ "sent while the rebind was still open", nil, "member", parseUUID(testUserID), false,
)
if err != nil {
results <- sendResult{err: err}
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index a1e98e3fd1..df028c48fa 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -667,6 +667,10 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
type SendChatMessageRequest struct {
Content string `json:"content"`
AttachmentIDs []string `json:"attachment_ids"`
+ // QuickActionsEnabled lets the sender opt this turn out of follow-up
+ // suggestion generation (Settings → Chat toggle). Pointer so an absent
+ // field (older clients) means enabled — only an explicit false disables.
+ QuickActionsEnabled *bool `json:"quick_actions_enabled"`
}
type SendChatMessageResponse struct {
@@ -788,7 +792,8 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
// creator-only), so they are the task initiator — surfaced to the agent
// under `## Task Initiator`. actorType/actorID were resolved above for the
// invoke gate.
- sent, err := h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID))
+ quickActionsDisabled := req.QuickActionsEnabled != nil && !*req.QuickActionsEnabled
+ sent, err := h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID), quickActionsDisabled)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to send chat message: "+err.Error())
return
@@ -889,6 +894,109 @@ func parseChatMessagesPageParams(r *http.Request) (int, pgtype.Timestamptz, pgty
return limit, pgtype.Timestamptz{Time: beforeTime, Valid: true}, beforeID, nil
}
+// RegenerateChatQuickActionsResponse acknowledges an accepted refresh request.
+// message_id is the assistant turn the refreshed pills will attach to — the
+// client anchors its pending placeholder on it and resolves it when the
+// chat:quick_actions supplement arrives.
+// RegenerateChatQuickActionsRequest names the assistant turn the client is
+// refreshing. The server confirms it is still the session's latest turn before
+// enqueuing (409 otherwise), so the client's pending marker stays aligned with
+// the turn chat:quick_actions will resolve — no ack reconciliation needed
+// (MUL-5149).
+type RegenerateChatQuickActionsRequest struct {
+ MessageID string `json:"message_id"`
+}
+
+type RegenerateChatQuickActionsResponse struct {
+ MessageID string `json:"message_id"`
+ TaskID string `json:"task_id"`
+}
+
+// RegenerateChatQuickActions re-runs the daemon suggestion pass for a session's
+// latest assistant turn on explicit user request (the "refresh" button on the
+// quick-actions row, MUL-5149). It enqueues a background regenerate task; the
+// refreshed pills arrive over the same chat:quick_actions realtime path as the
+// automatic pass. Same gate as sending a message — it enqueues an agent run.
+func (h *Handler) RegenerateChatQuickActions(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ sessionID := chi.URLParam(r, "sessionId")
+
+ session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)
+ if !ok {
+ return
+ }
+ if session.Status != "active" {
+ writeError(w, http.StatusBadRequest, "chat session is archived")
+ return
+ }
+ agent, err := h.Queries.GetAgent(r.Context(), session.AgentID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load chat agent")
+ return
+ }
+ if agent.ArchivedAt.Valid {
+ writeError(w, http.StatusConflict, "chat agent is archived")
+ return
+ }
+ if !agent.RuntimeID.Valid {
+ writeError(w, http.StatusConflict, "chat agent has no runtime")
+ return
+ }
+ // Enqueuing a suggestion pass runs the agent and spends quota, so it must
+ // clear the same INVOKE gate as a normal send (MUL-4525), not just the
+ // softer view gate in gateChatSessionForUser.
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ if !h.canInvokeAgent(r.Context(), agent, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {
+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)
+ return
+ }
+
+ var req RegenerateChatQuickActionsRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ expectedMessageID, ok := parseUUIDOrBadRequest(w, req.MessageID, "message_id")
+ if !ok {
+ return
+ }
+
+ messageID, task, err := h.TaskService.RegenerateChatQuickActions(r.Context(), session, parseUUID(userID), expectedMessageID)
+ if err != nil {
+ switch {
+ case errors.Is(err, service.ErrChatQuickActionsStale):
+ // The turn the client was refreshing is no longer the latest — its
+ // view is stale (a newer reply arrived). 409 → the client rolls back
+ // its optimistic marker and re-offers refresh on the new turn.
+ writeError(w, http.StatusConflict, "a newer reply arrived — refresh it instead")
+ case errors.Is(err, service.ErrChatQuickActionsBusy):
+ // A turn or another refresh is already running for this session; the
+ // result would be stale or a duplicate. 409 → the client rolls back
+ // and can refresh once the session settles.
+ writeError(w, http.StatusConflict, "still working — try refreshing in a moment")
+ case errors.Is(err, service.ErrChatQuickActionsNoTurn):
+ writeError(w, http.StatusConflict, "no assistant reply to refresh yet")
+ case errors.Is(err, service.ErrChatQuickActionsNotResumable):
+ writeError(w, http.StatusConflict, "this conversation can't be refreshed right now")
+ case errors.Is(err, service.ErrChatTaskAgentArchived):
+ writeError(w, http.StatusConflict, "chat agent is archived")
+ case errors.Is(err, service.ErrChatTaskAgentNoRuntime):
+ writeError(w, http.StatusConflict, "chat agent has no runtime")
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to regenerate quick actions")
+ }
+ return
+ }
+ writeJSON(w, http.StatusAccepted, RegenerateChatQuickActionsResponse{
+ MessageID: uuidToString(messageID),
+ TaskID: uuidToString(task.ID),
+ })
+}
+
func (h *Handler) ListChatMessages(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
@@ -1533,6 +1641,9 @@ type ChatMessageResponse struct {
// direct-chat turn that produced no text reply (MUL-4351). Additive:
// clients that don't understand it fall back to the non-empty content.
MessageKind string `json:"message_kind"`
+ // QuickActions are sanitized follow-ups generated with this assistant turn.
+ // Always an empty array for legacy rows and user messages.
+ QuickActions []protocol.ChatQuickAction `json:"quick_actions"`
// Attachments linked to this message via chat_message_id. The chat
// bubble renders file cards from these, and the daemon claim path
// (daemon.go) pulls structured metadata from the same source so the
@@ -1567,10 +1678,30 @@ func chatMessageToResponse(m db.ChatMessage, attachments []AttachmentResponse) C
FailureReason: textToPtr(m.FailureReason),
ElapsedMs: int8ToPtr(m.ElapsedMs),
MessageKind: normalizeMessageKind(m.MessageKind),
+ QuickActions: decodeChatQuickActions(m.QuickActions),
Attachments: attachments,
}
}
+func decodeChatQuickActions(raw []byte) []protocol.ChatQuickAction {
+ actions := make([]protocol.ChatQuickAction, 0)
+ if len(raw) == 0 {
+ return actions
+ }
+ if err := json.Unmarshal(raw, &actions); err != nil {
+ return []protocol.ChatQuickAction{}
+ }
+ if actions == nil {
+ return []protocol.ChatQuickAction{}
+ }
+ if len(actions) > chatQuickActionResponseLimit {
+ actions = actions[:chatQuickActionResponseLimit]
+ }
+ return actions
+}
+
+const chatQuickActionResponseLimit = 3
+
// normalizeMessageKind maps a stored chat_message.message_kind to the value the
// API exposes. Unknown / empty kinds degrade to 'message' so a future kind
// never surprises an older client into a broken render (MUL-4351).
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
index 10ebacbb96..5b1c475e3b 100644
--- a/server/internal/handler/chat_input_ownership_test.go
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -3,8 +3,10 @@ package handler
import (
"context"
"encoding/json"
+ "errors"
"testing"
+ "github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -39,7 +41,7 @@ func sendDirectChat(t *testing.T, ctx context.Context, agentID, sessionID, conte
if err != nil {
t.Fatalf("load agent: %v", err)
}
- res, err := testHandler.TaskService.SendDirectChatMessage(ctx, sess, ag, parseUUID(testUserID), content, nil, "member", parseUUID(testUserID))
+ res, err := testHandler.TaskService.SendDirectChatMessage(ctx, sess, ag, parseUUID(testUserID), content, nil, "member", parseUUID(testUserID), false)
if err != nil {
t.Fatalf("SendDirectChatMessage: %v", err)
}
@@ -474,3 +476,342 @@ func TestCompleteTask_SealedChannelRetryEmptyOutputWritesNoRow(t *testing.T) {
t.Fatalf("sealed channel retry empty completion must write NO assistant row, got %d", len(rows))
}
}
+
+func TestCompleteTask_ChatQuickActions(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "quick-actions chat")
+ taskID := sendDirectChat(t, ctx, agentID, sessionID, "what next?")
+ markTaskRunning(t, ctx, taskID)
+
+ output := "Here is the plan.\n\n```quick-actions\n" +
+ `[{"label":"Draft it","prompt":"Draft the complete plan","primary":true},` +
+ `{"label":"Make a checklist","prompt":"Turn this into a checklist"}]` +
+ "\n```"
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, output), "", "", false, ""); err != nil {
+ t.Fatalf("complete task: %v", err)
+ }
+
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("expected one assistant message, got %d", len(rows))
+ }
+ if rows[0].Content != "Here is the plan." || rows[0].MessageKind != protocol.ChatMessageKindMessage {
+ t.Fatalf("persisted reply = kind %q content %q", rows[0].MessageKind, rows[0].Content)
+ }
+ var actions []protocol.ChatQuickAction
+ if err := json.Unmarshal(rows[0].QuickActions, &actions); err != nil {
+ t.Fatalf("decode quick actions: %v", err)
+ }
+ if len(actions) != 2 || actions[0].Prompt != "Draft the complete plan" || !actions[0].Primary {
+ t.Fatalf("persisted quick actions = %+v", actions)
+ }
+
+ // An actions-only turn (quick-actions footer with no visible text) must NOT
+ // become an empty-content message: older Desktop / mobile clients ignore
+ // quick_actions and would render an empty bubble. It falls through to the
+ // visible no_response fallback instead, and the chips are dropped (MUL-4351).
+ actionsOnlyTask := sendDirectChat(t, ctx, agentID, sessionID, "give me options only")
+ markTaskRunning(t, ctx, actionsOnlyTask)
+ actionsOnly := "```quick-actions\n[{\"label\":\"Continue\",\"prompt\":\"Continue the plan\"}]\n```"
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(actionsOnlyTask), completeResult(t, actionsOnly), "", "", false, ""); err != nil {
+ t.Fatalf("complete actions-only task: %v", err)
+ }
+ rows = assistantRows(t, ctx, sessionID)
+ if len(rows) != 2 || rows[1].MessageKind != protocol.ChatMessageKindNoResponse {
+ t.Fatalf("actions-only outcome = %+v", rows)
+ }
+ if rows[1].Content == "" {
+ t.Fatal("actions-only no_response row must carry a non-empty fallback body for old clients")
+ }
+ var droppedActions []protocol.ChatQuickAction
+ if err := json.Unmarshal(rows[1].QuickActions, &droppedActions); err != nil {
+ t.Fatalf("decode quick actions: %v", err)
+ }
+ if len(droppedActions) != 0 {
+ t.Fatalf("actions-only no_response row must not carry quick actions, got %+v", droppedActions)
+ }
+}
+
+func TestCompleteTask_ChatQuickActionsSupplement(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "suggest-pass chat")
+ taskID := sendDirectChat(t, ctx, agentID, sessionID, "what next?")
+ markTaskRunning(t, ctx, taskID)
+
+ output := "Main reply.\n\n```quick-actions\n" +
+ `[{"label":"From footer","prompt":"in-band fallback"}]` + "\n```"
+ req := TaskCompleteRequest{Output: output, QuickActionsPending: true}
+ result, err := json.Marshal(req)
+ if err != nil {
+ t.Fatalf("marshal complete request: %v", err)
+ }
+ task, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), result, "", "", false, "")
+ if err != nil {
+ t.Fatalf("complete task: %v", err)
+ }
+
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("expected one assistant message, got %d", len(rows))
+ }
+ if rows[0].Content != "Main reply." {
+ t.Fatalf("footer must still be stripped from content, got %q", rows[0].Content)
+ }
+
+ raw := "```json\n" + `[{"label":"From pass","prompt":"suggested prompt","primary":true}]` + "\n```"
+ if err := testHandler.TaskService.SupplementChatQuickActions(ctx, *task, raw, false); err != nil {
+ t.Fatalf("supplement quick actions: %v", err)
+ }
+ rows = assistantRows(t, ctx, sessionID)
+ var actions []protocol.ChatQuickAction
+ if err := json.Unmarshal(rows[0].QuickActions, &actions); err != nil {
+ t.Fatalf("decode quick actions: %v", err)
+ }
+ if len(actions) != 1 || actions[0].Label != "From pass" || !actions[0].Primary {
+ t.Fatalf("supplement must overwrite the in-band fallback, got %+v", actions)
+ }
+
+ // An empty supplement must not clobber existing actions (it only resolves
+ // the pending placeholder client-side).
+ if err := testHandler.TaskService.SupplementChatQuickActions(ctx, *task, "", false); err != nil {
+ t.Fatalf("empty supplement: %v", err)
+ }
+ rows = assistantRows(t, ctx, sessionID)
+ actions = nil
+ if err := json.Unmarshal(rows[0].QuickActions, &actions); err != nil {
+ t.Fatalf("decode quick actions after empty supplement: %v", err)
+ }
+ if len(actions) != 1 || actions[0].Label != "From pass" {
+ t.Fatalf("empty supplement must keep existing actions, got %+v", actions)
+ }
+}
+
+func TestDirectChat_QuickActionsOptOutStampsTask(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "opt-out chat")
+ sess, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("load chat session: %v", err)
+ }
+ ag, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatalf("load agent: %v", err)
+ }
+
+ optedOut, err := testHandler.TaskService.SendDirectChatMessage(ctx, sess, ag, parseUUID(testUserID), "no suggestions", nil, "member", parseUUID(testUserID), true)
+ if err != nil {
+ t.Fatalf("send opted-out message: %v", err)
+ }
+ if !optedOut.Task.QuickActionsDisabled {
+ t.Fatal("opt-out send must stamp quick_actions_disabled on the task")
+ }
+
+ // Default (older clients / toggle on) stays enabled.
+ normal, err := testHandler.TaskService.SendDirectChatMessage(ctx, sess, ag, parseUUID(testUserID), "with suggestions", nil, "member", parseUUID(testUserID), false)
+ if err != nil {
+ t.Fatalf("send normal message: %v", err)
+ }
+ if normal.Task.QuickActionsDisabled {
+ t.Fatal("default send must leave quick_actions_disabled false")
+ }
+}
+
+// TestRegenerateChatQuickActions_StaleTargetRejected pins the ack-alignment
+// contract (MUL-5149 review): a refresh names the turn it is refreshing, and
+// the server enqueues it only while that turn is STILL the session's latest.
+// Once a newer reply lands, refreshing the older turn is refused, so the
+// client's pending marker never points at a turn the resulting
+// chat:quick_actions event could not match.
+func TestRegenerateChatQuickActions_StaleTargetRejected(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "regen stale chat")
+
+ // Turn 1: a resumable assistant reply (session_id + runtime bound) is latest.
+ t1 := sendDirectChat(t, ctx, agentID, sessionID, "first question")
+ markTaskRunning(t, ctx, t1)
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "first reply"), "sess-1", "/tmp/wd", false, ""); err != nil {
+ t.Fatalf("complete turn 1: %v", err)
+ }
+ session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("reload session: %v", err)
+ }
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("expected one assistant turn, got %d", len(rows))
+ }
+ m1 := rows[0].ID
+
+ // Refreshing the current latest turn is accepted and targets exactly it.
+ target, regenTask, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, parseUUID(testUserID), m1)
+ if err != nil {
+ t.Fatalf("regenerate latest turn: %v", err)
+ }
+ if target != m1 {
+ t.Fatalf("regenerate target = %v, want the latest turn %v", target, m1)
+ }
+ // That refresh enqueues a regen pass that occupies the session until the
+ // daemon finishes it. Settle it so the session is idle again — this test
+ // isolates the STALE check; the busy-rejection path has its own tests.
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_task_queue SET status='completed', completed_at=now() WHERE id=$1`,
+ uuidToString(regenTask.ID)); err != nil {
+ t.Fatalf("settle regen task: %v", err)
+ }
+
+ // Turn 2 lands, so m1 is no longer the latest.
+ t2 := sendDirectChat(t, ctx, agentID, sessionID, "second question")
+ markTaskRunning(t, ctx, t2)
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t2), completeResult(t, "second reply"), "sess-2", "/tmp/wd", false, ""); err != nil {
+ t.Fatalf("complete turn 2: %v", err)
+ }
+ session, err = testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("reload session after turn 2: %v", err)
+ }
+ rows = assistantRows(t, ctx, sessionID)
+ if len(rows) != 2 {
+ t.Fatalf("expected two assistant turns, got %d", len(rows))
+ }
+ m2 := rows[1].ID
+
+ // Refreshing the now-stale m1 is refused; refreshing the new latest m2 works.
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, parseUUID(testUserID), m1); !errors.Is(err, service.ErrChatQuickActionsStale) {
+ t.Fatalf("stale-target regenerate error = %v, want ErrChatQuickActionsStale", err)
+ }
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, parseUUID(testUserID), m2); err != nil {
+ t.Fatalf("regenerate new latest turn: %v", err)
+ }
+}
+
+// TestRegenerateChatQuickActions_ActiveTurnRejected pins finding §1 of the
+// MUL-5149 review: a newer reply that is queued/running but whose assistant row
+// has not landed yet leaves the OLD turn as the latest-persisted one, so the
+// stale check still passes on it. Regenerating then would resume the session
+// after the newer turn advanced its provider state, attaching suggestions built
+// from the newer context to the older turn. The in-flight task must refuse it.
+func TestRegenerateChatQuickActions_ActiveTurnRejected(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "regen busy chat")
+
+ // Turn 1 completes with a resumable session → m1 is the latest assistant turn.
+ t1 := sendDirectChat(t, ctx, agentID, sessionID, "first")
+ markTaskRunning(t, ctx, t1)
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "first reply"), "sess-1", "/tmp/wd", false, ""); err != nil {
+ t.Fatalf("complete turn 1: %v", err)
+ }
+ session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("reload session: %v", err)
+ }
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("expected one assistant turn, got %d", len(rows))
+ }
+ m1 := rows[0].ID
+
+ // Turn 2 is in flight (running, no assistant row yet) so m1 is STILL the
+ // latest-persisted turn — the stale check passes — but the session is busy.
+ t2 := sendDirectChat(t, ctx, agentID, sessionID, "second")
+ markTaskRunning(t, ctx, t2)
+
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, parseUUID(testUserID), m1); !errors.Is(err, service.ErrChatQuickActionsBusy) {
+ t.Fatalf("busy-session regenerate error = %v, want ErrChatQuickActionsBusy", err)
+ }
+}
+
+// TestRegenerateChatQuickActions_ConcurrentRefreshRejected pins finding §2 of
+// the MUL-5149 review: a second refresh of the same turn while the first pass is
+// still in flight is refused rather than enqueuing a duplicate, quota-spending
+// pass. A per-client disabled button cannot stop a second client, so the guard
+// lives under the session lock next to the enqueue.
+func TestRegenerateChatQuickActions_ConcurrentRefreshRejected(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "regen dedup chat")
+
+ t1 := sendDirectChat(t, ctx, agentID, sessionID, "q")
+ markTaskRunning(t, ctx, t1)
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "a"), "sess-1", "/tmp/wd", false, ""); err != nil {
+ t.Fatalf("complete turn 1: %v", err)
+ }
+ session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("reload session: %v", err)
+ }
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("expected one assistant turn, got %d", len(rows))
+ }
+ m1 := rows[0].ID
+
+ // First refresh is accepted and enqueues a regen pass that now occupies the session.
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, parseUUID(testUserID), m1); err != nil {
+ t.Fatalf("first refresh: %v", err)
+ }
+ // Second refresh of the same turn while the first pass is still queued is refused.
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, parseUUID(testUserID), m1); !errors.Is(err, service.ErrChatQuickActionsBusy) {
+ t.Fatalf("concurrent refresh error = %v, want ErrChatQuickActionsBusy", err)
+ }
+}
+
+// TestRegenerateChatQuickActions_DeferredActiveTurnRejected pins the re-review
+// §1 gap: a chat auto-retry armed with a backoff fire_at is inserted 'deferred'
+// (CreateRetryTask; provider_network's final attempt waits ~5s that way). During
+// that window the failed turn has written no assistant row, so the old turn is
+// still latest-persisted and its pills stay clickable — yet the session is about
+// to advance when the retry fires. HasActiveChatTaskForSession must count
+// 'deferred', else the refresh resumes a session the retry moves past and pins
+// the new turn's suggestions onto the old one.
+func TestRegenerateChatQuickActions_DeferredActiveTurnRejected(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "regen deferred chat")
+
+ t1 := sendDirectChat(t, ctx, agentID, sessionID, "first")
+ markTaskRunning(t, ctx, t1)
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "first reply"), "sess-1", "/tmp/wd", false, ""); err != nil {
+ t.Fatalf("complete turn 1: %v", err)
+ }
+ session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("reload session: %v", err)
+ }
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("expected one assistant turn, got %d", len(rows))
+ }
+ m1 := rows[0].ID
+
+ // Turn 2 failed and is waiting out its retry backoff: a deferred task with a
+ // future fire_at and no assistant row yet, so m1 is still latest-persisted.
+ t2 := sendDirectChat(t, ctx, agentID, sessionID, "second")
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_task_queue SET status='deferred', fire_at=now() + interval '5 seconds' WHERE id=$1`,
+ t2); err != nil {
+ t.Fatalf("defer turn 2: %v", err)
+ }
+
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, parseUUID(testUserID), m1); !errors.Is(err, service.ErrChatQuickActionsBusy) {
+ t.Fatalf("deferred-active regenerate error = %v, want ErrChatQuickActionsBusy", err)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 44d0460a54..cd0f07ca0b 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2053,6 +2053,13 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
// Chat task: populate workspace/session info from the chat_session table.
if task.ChatSessionID.Valid {
+ resp.QuickActionsDisabled = task.QuickActionsDisabled
+ // A quick-actions regeneration task carries the id of the turn to
+ // re-supplement; the daemon runs only the suggestion pass for it and
+ // skips the main reply (MUL-5149).
+ if task.RegenerateQuickActionsFor.Valid {
+ resp.RegenerateQuickActionsFor = uuidToString(task.RegenerateQuickActionsFor)
+ }
if cs, err := h.Queries.GetChatSession(r.Context(), task.ChatSessionID); err == nil {
resp.WorkspaceID = uuidToString(cs.WorkspaceID)
resp.ChatSessionID = uuidToString(cs.ID)
@@ -2916,6 +2923,10 @@ type TaskCompleteRequest struct {
Output string `json:"output"`
SessionID string `json:"session_id"` // Claude session ID for future resumption
WorkDir string `json:"work_dir"` // working directory used during execution
+ // QuickActionsPending declares a chat:quick_actions supplement will follow;
+ // the json tag must match protocol.TaskCompletedPayload because this request
+ // is re-marshalled into that payload for the completion transaction.
+ QuickActionsPending bool `json:"quick_actions_pending"`
// SessionRolloutMissing: the daemon withheld this task's Codex session
// because its rollout was missing (MUL-5305). Clear the resume pointer and
// flag the continuity gap for the next claim.
@@ -2927,6 +2938,35 @@ type TaskCompleteRequest struct {
RetiredSessionID string `json:"retired_session_id,omitempty"`
}
+// TaskQuickActionsRequest carries the raw (unparsed) output of the daemon's
+// post-completion suggestion pass; the service parses it leniently.
+type TaskQuickActionsRequest struct {
+ Raw string `json:"raw"`
+}
+
+// SupplementTaskQuickActions attaches follow-up suggestions to an already
+// completed chat turn. Arrives after CompleteTask by design — the daemon
+// reports completion first so the user's turn is not blocked on suggestion
+// generation, then follows up here.
+func (h *Handler) SupplementTaskQuickActions(w http.ResponseWriter, r *http.Request) {
+ taskID := chi.URLParam(r, "taskId")
+ task, _, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, taskID)
+ if !ok {
+ return
+ }
+ var req TaskQuickActionsRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if err := h.TaskService.SupplementChatQuickActions(r.Context(), task, req.Raw, false); err != nil {
+ slog.Warn("supplement task quick actions failed", "task_id", taskID, "error", err)
+ writeError(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
+}
+
func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
taskID := chi.URLParam(r, "taskId")
diff --git a/server/internal/service/chat_quick_actions.go b/server/internal/service/chat_quick_actions.go
new file mode 100644
index 0000000000..f31e4c57dd
--- /dev/null
+++ b/server/internal/service/chat_quick_actions.go
@@ -0,0 +1,267 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+ "github.com/multica-ai/multica/server/pkg/redact"
+)
+
+const (
+ chatQuickActionsFence = "```quick-actions\n"
+ chatQuickActionMaxCount = 3
+ chatQuickActionLabelMax = 80
+ chatQuickActionPromptMax = 500
+)
+
+// parseChatQuickActionsOutput parses the daemon suggestion pass's raw output
+// into sanitized actions. The pass is instructed to emit a bare JSON array,
+// but this parser is deliberately lenient — models wrap output in code fences
+// or lead with a sentence often enough that strict parsing would silently
+// drop good suggestions. Anything unparseable degrades to "no suggestions";
+// this output never reaches the transcript, so there is nothing to leak.
+func parseChatQuickActionsOutput(raw string) []protocol.ChatQuickAction {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return nil
+ }
+ // Attempt order narrows from strict to desperate: the bare array the pass
+ // was asked for, then the inside of a code fence, then the outermost
+ // bracket span. The bracket scan runs last because leading prose may
+ // itself contain brackets ("here's [my] take: [...]"), which would
+ // misalign the slice if it were tried first.
+ for _, candidate := range []string{raw, insideCodeFence(raw)} {
+ if actions, ok := unmarshalChatQuickActions(candidate); ok {
+ return actions
+ }
+ }
+ start := strings.Index(raw, "[")
+ end := strings.LastIndex(raw, "]")
+ if start < 0 || end <= start {
+ return nil
+ }
+ actions, _ := unmarshalChatQuickActions(raw[start : end+1])
+ return actions
+}
+
+// insideCodeFence returns the content of the first fenced code block in raw
+// (language tag tolerated), or "" when no complete fence exists.
+func insideCodeFence(raw string) string {
+ open := strings.Index(raw, "```")
+ if open < 0 {
+ return ""
+ }
+ rest := raw[open+3:]
+ if nl := strings.Index(rest, "\n"); nl >= 0 {
+ rest = rest[nl+1:] // drop the opening fence's language line
+ } else {
+ return ""
+ }
+ closing := strings.Index(rest, "```")
+ if closing < 0 {
+ return ""
+ }
+ return strings.TrimSpace(rest[:closing])
+}
+
+func unmarshalChatQuickActions(raw string) ([]protocol.ChatQuickAction, bool) {
+ if raw == "" {
+ return nil, false
+ }
+ var candidates []protocol.ChatQuickAction
+ if err := json.Unmarshal([]byte(raw), &candidates); err != nil {
+ return nil, false
+ }
+ return sanitizeChatQuickActions(candidates), true
+}
+
+// splitChatQuickActions separates one reserved trailing quick-actions fence
+// from the visible reply. A recognized footer is always stripped, including
+// when its JSON is malformed, so private control syntax never leaks into Chat.
+// A mid-response fence is ordinary user-visible markdown and is left intact.
+//
+// The in-band footer is no longer the primary suggestion source — the daemon
+// suggestion pass is (parseChatQuickActionsOutput). This split stays for two
+// reasons: older daemons still inject the retired brief instruction, and
+// provider sessions created before the upgrade carry the syntax in their own
+// history, so agents keep emitting footers for a while either way.
+func splitChatQuickActions(output string) (string, []protocol.ChatQuickAction) {
+ normalized := strings.ReplaceAll(output, "\r\n", "\n")
+ trimmed := strings.TrimRight(normalized, " \t\n")
+ if !strings.HasSuffix(trimmed, "\n```") {
+ return output, nil
+ }
+
+ withoutClose := strings.TrimSuffix(trimmed, "\n```")
+ marker := "\n" + chatQuickActionsFence
+ start := strings.LastIndex(withoutClose, marker)
+ visible := ""
+ raw := ""
+ switch {
+ case start >= 0:
+ visible = withoutClose[:start]
+ raw = withoutClose[start+len(marker):]
+ case strings.HasPrefix(withoutClose, chatQuickActionsFence):
+ raw = strings.TrimPrefix(withoutClose, chatQuickActionsFence)
+ default:
+ return output, nil
+ }
+ // A quick-actions fence that closes before the end of the reply is ordinary
+ // visible markdown, even when a later, unrelated code fence happens to end
+ // the whole message. Without this guard the final closing fence above can be
+ // paired with a mid-response opener and silently truncate everything after
+ // that example.
+ if strings.Contains(raw, "\n```") {
+ return output, nil
+ }
+
+ visible = strings.TrimRight(visible, " \t\n")
+ var candidates []protocol.ChatQuickAction
+ if err := json.Unmarshal([]byte(raw), &candidates); err != nil {
+ return visible, nil
+ }
+ return visible, sanitizeChatQuickActions(candidates)
+}
+
+// sanitizeChatQuickActions enforces the server-side contract on agent-supplied
+// candidates regardless of which channel they arrived through: at most three
+// actions, normalized non-empty labels, case-insensitive label dedup, prompts
+// defaulting to the label, rune-safe truncation, and exactly one primary.
+func sanitizeChatQuickActions(candidates []protocol.ChatQuickAction) []protocol.ChatQuickAction {
+ actions := make([]protocol.ChatQuickAction, 0, min(len(candidates), chatQuickActionMaxCount))
+ seen := make(map[string]struct{}, chatQuickActionMaxCount)
+ primarySeen := false
+ for _, candidate := range candidates {
+ if len(actions) == chatQuickActionMaxCount {
+ break
+ }
+ label := strings.Join(strings.Fields(candidate.Label), " ")
+ if label == "" {
+ continue
+ }
+ label = truncateChatQuickAction(label, chatQuickActionLabelMax)
+ key := strings.ToLower(label)
+ if _, duplicate := seen[key]; duplicate {
+ continue
+ }
+ seen[key] = struct{}{}
+
+ prompt := strings.TrimSpace(candidate.Prompt)
+ if prompt == "" {
+ prompt = label
+ }
+ prompt = truncateChatQuickAction(prompt, chatQuickActionPromptMax)
+ primary := candidate.Primary && !primarySeen
+ primarySeen = primarySeen || primary
+ actions = append(actions, protocol.ChatQuickAction{
+ Label: label,
+ Prompt: prompt,
+ Primary: primary,
+ })
+ }
+ if len(actions) > 0 && !primarySeen {
+ actions[0].Primary = true
+ }
+ return actions
+}
+
+func truncateChatQuickAction(value string, maxRunes int) string {
+ runes := []rune(value)
+ if len(runes) <= maxRunes {
+ return value
+ }
+ return string(runes[:maxRunes-1]) + "…"
+}
+
+// chatQuickActionsPending decides whether the chat:done broadcast should tell
+// clients to expect a chat:quick_actions supplement: the daemon declared one
+// on the complete callback, an ordinary assistant message was written, and no
+// actions are attached yet (an in-band fallback already delivered would make
+// a placeholder pointless).
+func chatQuickActionsPending(result []byte, msg *db.ChatMessage) bool {
+ var payload protocol.TaskCompletedPayload
+ _ = json.Unmarshal(result, &payload)
+ if !payload.QuickActionsPending || msg == nil {
+ return false
+ }
+ if msg.MessageKind != protocol.ChatMessageKindMessage {
+ return false
+ }
+ var existing []protocol.ChatQuickAction
+ _ = json.Unmarshal(msg.QuickActions, &existing)
+ return len(existing) == 0
+}
+
+// SupplementChatQuickActions attaches the daemon suggestion pass's output to
+// the completed turn's assistant message and broadcasts chat:quick_actions.
+// Best-effort semantics: an unparseable or empty result still broadcasts the
+// row's current (usually empty) actions so pending placeholders resolve. A
+// turn that never wrote an assistant row (no_response, channel empty-drop)
+// returns silently — no client is waiting in that case, because the pending
+// flag is only ever raised for a written ordinary message.
+//
+// failed marks the broadcast as a failure resolution (an explicit refresh whose
+// regeneration failed): the pills stay unchanged but the client shows a
+// "couldn't refresh" notice instead of treating them as freshly generated.
+func (s *TaskService) SupplementChatQuickActions(ctx context.Context, task db.AgentTaskQueue, raw string, failed bool) error {
+ if !task.ChatSessionID.Valid {
+ return nil
+ }
+ actions := parseChatQuickActionsOutput(raw)
+ for i := range actions {
+ actions[i].Label = redact.Text(actions[i].Label)
+ actions[i].Prompt = redact.Text(actions[i].Prompt)
+ }
+
+ var msg db.ChatMessage
+ var err error
+ if len(actions) > 0 {
+ encoded, marshalErr := json.Marshal(actions)
+ if marshalErr != nil {
+ return fmt.Errorf("marshal chat quick actions: %w", marshalErr)
+ }
+ msg, err = s.Queries.SetChatMessageQuickActionsByTask(ctx, db.SetChatMessageQuickActionsByTaskParams{
+ TaskID: task.ID,
+ QuickActions: encoded,
+ })
+ } else {
+ msg, err = s.Queries.GetChatMessageByTaskAssistant(ctx, task.ID)
+ }
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ return fmt.Errorf("attach chat quick actions: %w", err)
+ }
+
+ workspaceID := s.ResolveTaskWorkspaceID(ctx, task)
+ if workspaceID == "" {
+ return nil
+ }
+ payload := protocol.ChatQuickActionsPayload{
+ ChatSessionID: util.UUIDToString(task.ChatSessionID),
+ TaskID: util.UUIDToString(task.ID),
+ MessageID: util.UUIDToString(msg.ID),
+ QuickActions: []protocol.ChatQuickAction{},
+ Failed: failed,
+ }
+ _ = json.Unmarshal(msg.QuickActions, &payload.QuickActions)
+ s.Bus.Publish(events.Event{
+ Type: protocol.EventChatQuickActions,
+ WorkspaceID: workspaceID,
+ ActorType: "system",
+ ActorID: "",
+ ChatSessionID: util.UUIDToString(task.ChatSessionID),
+ Payload: payload,
+ })
+ return nil
+}
diff --git a/server/internal/service/chat_quick_actions_test.go b/server/internal/service/chat_quick_actions_test.go
new file mode 100644
index 0000000000..69d444e9e7
--- /dev/null
+++ b/server/internal/service/chat_quick_actions_test.go
@@ -0,0 +1,151 @@
+package service
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestSplitChatQuickActions(t *testing.T) {
+ t.Parallel()
+ input := "Answer first.\r\n\r\n```quick-actions\r\n" +
+ `[{"label":" Draft a brief ","prompt":"Write the full brief","primary":true},` +
+ `{"label":"Plan next steps","prompt":"","primary":true},` +
+ `{"label":"Draft a brief","prompt":"duplicate"},` +
+ `{"label":"Define success","prompt":"Define the success metric"}]` +
+ "\r\n```\r\n"
+
+ visible, actions := splitChatQuickActions(input)
+ if visible != "Answer first." {
+ t.Fatalf("visible reply = %q", visible)
+ }
+ if len(actions) != 3 {
+ t.Fatalf("actions len = %d, want 3: %+v", len(actions), actions)
+ }
+ if actions[0].Label != "Draft a brief" || actions[0].Prompt != "Write the full brief" || !actions[0].Primary {
+ t.Fatalf("first action was not normalized: %+v", actions[0])
+ }
+ if actions[1].Prompt != "Plan next steps" || actions[1].Primary {
+ t.Fatalf("second action must default its prompt and lose duplicate primary: %+v", actions[1])
+ }
+ if actions[2].Label != "Define success" {
+ t.Fatalf("third action = %+v", actions[2])
+ }
+}
+
+func TestSplitChatQuickActionsPromotesFirstAndSupportsActionsOnly(t *testing.T) {
+ t.Parallel()
+ visible, actions := splitChatQuickActions("```quick-actions\n[{\"label\":\"Continue\",\"prompt\":\"Continue the work\"}]\n```")
+ if visible != "" {
+ t.Fatalf("actions-only visible body = %q, want empty", visible)
+ }
+ if len(actions) != 1 || !actions[0].Primary {
+ t.Fatalf("first action should become primary: %+v", actions)
+ }
+}
+
+func TestSplitChatQuickActionsStripsMalformedTrailingProtocol(t *testing.T) {
+ t.Parallel()
+ visible, actions := splitChatQuickActions("Useful answer.\n```quick-actions\nnot json\n```")
+ if visible != "Useful answer." || len(actions) != 0 {
+ t.Fatalf("malformed footer should be stripped safely: visible=%q actions=%+v", visible, actions)
+ }
+}
+
+func TestSplitChatQuickActionsLeavesMidResponseFenceVisible(t *testing.T) {
+ t.Parallel()
+ input := "Example:\n```quick-actions\n[]\n```\nMore explanation."
+ visible, actions := splitChatQuickActions(input)
+ if visible != input || actions != nil {
+ t.Fatalf("non-trailing fence changed: visible=%q actions=%+v", visible, actions)
+ }
+}
+
+func TestSplitChatQuickActionsLeavesMidResponseFenceWhenLaterFenceEndsReply(t *testing.T) {
+ t.Parallel()
+ input := "Here is the quick-actions format:\n" +
+ "```quick-actions\n" +
+ `[{"label":"Go","prompt":"Go now"}]` +
+ "\n```\n" +
+ "And here is a bash example:\n" +
+ "```bash\nls -la\n```"
+ visible, actions := splitChatQuickActions(input)
+ if visible != input || actions != nil {
+ t.Fatalf("mid-response quick-actions example changed: visible=%q actions=%+v", visible, actions)
+ }
+}
+
+func TestSplitChatQuickActionsTruncatesByRune(t *testing.T) {
+ t.Parallel()
+ label := strings.Repeat("深", chatQuickActionLabelMax+5)
+ input := "Done.\n```quick-actions\n[{\"label\":\"" + label + "\",\"prompt\":\"go\"}]\n```"
+ _, actions := splitChatQuickActions(input)
+ if got := len([]rune(actions[0].Label)); got != chatQuickActionLabelMax {
+ t.Fatalf("label rune length = %d, want %d", got, chatQuickActionLabelMax)
+ }
+}
+
+func TestParseChatQuickActionsOutputBareArray(t *testing.T) {
+ t.Parallel()
+ actions := parseChatQuickActionsOutput(
+ `[{"label":"Draft it","prompt":"Draft the plan","primary":true},{"label":"List risks","prompt":"List the risks"}]`)
+ if len(actions) != 2 || actions[0].Label != "Draft it" || !actions[0].Primary || actions[1].Primary {
+ t.Fatalf("actions = %+v", actions)
+ }
+}
+
+func TestParseChatQuickActionsOutputToleratesFencesAndProse(t *testing.T) {
+ t.Parallel()
+ wrapped := "Sure, here are the suggestions:\n```json\n" +
+ `[{"label":"Continue","prompt":"Continue the work"}]` +
+ "\n```\nLet me know if you need more."
+ actions := parseChatQuickActionsOutput(wrapped)
+ if len(actions) != 1 || actions[0].Label != "Continue" || !actions[0].Primary {
+ t.Fatalf("fence-wrapped output must still parse and promote primary: %+v", actions)
+ }
+}
+
+func TestParseChatQuickActionsOutputDegradesToNone(t *testing.T) {
+ t.Parallel()
+ for name, raw := range map[string]string{
+ "empty": "",
+ "empty array": "[]",
+ "no array": "I have no suggestions this time.",
+ "broken json": `[{"label":"x","prompt":`,
+ "non-array": `{"label":"x","prompt":"y"}`,
+ "blank entries": `[{"label":" ","prompt":"y"}]`,
+ } {
+ if actions := parseChatQuickActionsOutput(raw); len(actions) != 0 {
+ t.Fatalf("%s: expected no actions, got %+v", name, actions)
+ }
+ }
+}
+
+func TestParseChatQuickActionsOutputAppliesSanitizeContract(t *testing.T) {
+ t.Parallel()
+ long := strings.Repeat("剑", 700)
+ actions := parseChatQuickActionsOutput(
+ `[{"label":"A","prompt":"` + long + `"},{"label":"a","prompt":"dup"},{"label":"B"},{"label":"C","prompt":"c"},{"label":"D","prompt":"d"}]`)
+ if len(actions) != 3 {
+ t.Fatalf("cap at three after dedup, got %+v", actions)
+ }
+ if got := len([]rune(actions[0].Prompt)); got != 500 {
+ t.Fatalf("prompt must truncate to 500 runes, got %d", got)
+ }
+ if actions[1].Prompt != "B" {
+ t.Fatalf("empty prompt must default to label, got %+v", actions[1])
+ }
+ if !actions[0].Primary {
+ t.Fatal("first action must be promoted primary when none marked")
+ }
+}
+
+func TestParseChatQuickActionsOutputHandlesBracketsInProse(t *testing.T) {
+ t.Parallel()
+ wrapped := "Here's [my] take on it:\n```json\n" +
+ `[{"label":"Ship it","prompt":"Ship the fix"}]` +
+ "\n```"
+ actions := parseChatQuickActionsOutput(wrapped)
+ if len(actions) != 1 || actions[0].Label != "Ship it" {
+ t.Fatalf("stray prose brackets must not break fenced parsing: %+v", actions)
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 0f42cb5815..735cfd25b1 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1427,6 +1427,29 @@ var ErrChatTaskAgentArchived = errors.New("chat task: agent archived")
// path returns a task row, not this error.
var ErrChatTaskAgentNoRuntime = errors.New("chat task: agent has no runtime")
+// ErrChatQuickActionsNoTurn signals that a quick-actions regeneration was asked
+// for a session with no eligible assistant turn to resume from (empty session,
+// or the latest turn is a no_response / failure with nothing to suggest from).
+var ErrChatQuickActionsNoTurn = errors.New("chat quick actions: no assistant turn to regenerate")
+
+// ErrChatQuickActionsNotResumable signals that the session has no provider
+// resume pointer bound to the agent's current runtime, so a regeneration pass
+// would run context-less. Productizable as "can't refresh right now".
+var ErrChatQuickActionsNotResumable = errors.New("chat quick actions: session not resumable")
+
+// ErrChatQuickActionsStale signals the turn the client asked to refresh is no
+// longer the session's latest assistant turn (a newer reply landed since the
+// refresh button was rendered). The regeneration is refused so the client's
+// optimistic pending marker never points at a turn the resulting
+// chat:quick_actions event will not match (MUL-5149).
+var ErrChatQuickActionsStale = errors.New("chat quick actions: refresh target is stale")
+
+// ErrChatQuickActionsBusy signals the session already has work in flight — a
+// running turn about to change the latest reply, or another regenerate pass —
+// so a new refresh is refused to avoid a stale-target supplement or a duplicate
+// quota-spending pass (MUL-5149).
+var ErrChatQuickActionsBusy = errors.New("chat quick actions: session busy")
+
// EnqueueChatTask creates a task-owned input batch for a chat session. Channel
// media makes the task deferred until binding completes or its durable fallback
// deadline expires; other chat tasks are queued immediately. Unlike issue
@@ -1574,6 +1597,155 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
return task, nil
}
+// RegenerateChatQuickActions enqueues a background suggestion pass for the
+// session's latest assistant turn, letting the user refresh the quick-action
+// pills without sending a new message (MUL-5149). The task carries no user
+// message and owns no assistant turn (chat_input_task_id stays NULL): the daemon
+// resumes the same provider session the target turn ran on, runs only the
+// suggest prompt, and supplements the target turn's assistant row — so the
+// refreshed pills arrive over the identical chat:quick_actions path as the
+// automatic pass. It reports the target assistant message id so the client can
+// anchor its pending placeholder there.
+//
+// This is an explicit user action, so it ignores the per-device quick-actions
+// toggle (which only gates automatic generation at send time).
+func (s *TaskService) RegenerateChatQuickActions(ctx context.Context, chatSession db.ChatSession, initiatorUserID pgtype.UUID, expectedMessageID pgtype.UUID) (targetMessageID pgtype.UUID, task db.AgentTaskQueue, err error) {
+ // Preflight on the caller's snapshot for a fast reject, and resolve
+ // attribution (may do network I/O) BEFORE opening the transaction. The
+ // authoritative runtime/resume decision is re-read under the lock below.
+ agent, err := s.Queries.GetAgent(ctx, chatSession.AgentID)
+ if err != nil {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, fmt.Errorf("load agent: %w", err)
+ }
+ if agent.ArchivedAt.Valid {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, ErrChatTaskAgentArchived
+ }
+ if !agent.RuntimeID.Valid {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, ErrChatTaskAgentNoRuntime
+ }
+ attr := attribution.DirectHumanRun(initiatorUserID, attribution.EvidenceChat, chatSession.ID)
+ attr, err = s.applyAttributionFallback(ctx, attr, agent)
+ if err != nil {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, err
+ }
+ attrSource, _, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
+
+ var targetID pgtype.UUID
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ // Serialise against a concurrent runtime rebind of the same session
+ // (MUL-5163): lock first, then re-read BOTH the session and the agent
+ // under the lock. Unlike SendDirectChatMessage, regeneration depends on
+ // runtime-mutable session fields (session_id + runtime_id) to resume the
+ // right provider conversation — the caller's snapshot can already be
+ // stale, so validate and dispatch off the freshly-read rows. Locking
+ // chat_session first matches the send/delete lock order (no deadlock).
+ if _, err := qtx.LockChatSessionForRuntimeBind(ctx, chatSession.ID); err != nil {
+ return fmt.Errorf("lock chat session: %w", err)
+ }
+ session, err := qtx.GetChatSession(ctx, chatSession.ID)
+ if err != nil {
+ return fmt.Errorf("reload chat session: %w", err)
+ }
+ carrier, err := qtx.GetAgent(ctx, chatSession.AgentID)
+ if err != nil {
+ return fmt.Errorf("reload chat agent: %w", err)
+ }
+ if carrier.ArchivedAt.Valid {
+ return ErrChatTaskAgentArchived
+ }
+ if !carrier.RuntimeID.Valid {
+ return ErrChatTaskAgentNoRuntime
+ }
+ // Regeneration resumes the provider session the last turn produced.
+ // Without a resume pointer bound to the agent's CURRENT runtime there is
+ // nothing to resume, so refuse rather than spawn a fresh, context-less
+ // pass — or dispatch to a runtime the session just switched away from.
+ if !session.SessionID.Valid || session.SessionID.String == "" ||
+ !session.RuntimeID.Valid || session.RuntimeID != carrier.RuntimeID {
+ return ErrChatQuickActionsNotResumable
+ }
+ // The target is the latest assistant turn. Only an ordinary message turn
+ // can seed suggestions — a no_response / failure turn has nothing to
+ // build on. Resolved in-tx so target and dispatch commit together.
+ target, terr := qtx.GetLatestAssistantChatMessageForSession(ctx, chatSession.ID)
+ if terr != nil {
+ if errors.Is(terr, pgx.ErrNoRows) {
+ return ErrChatQuickActionsNoTurn
+ }
+ return fmt.Errorf("load latest assistant turn: %w", terr)
+ }
+ if target.MessageKind != protocol.ChatMessageKindMessage || !target.TaskID.Valid {
+ return ErrChatQuickActionsNoTurn
+ }
+ // Confirm the client is refreshing the turn that is STILL the latest.
+ // Under a multi-client race a newer reply can land between the button
+ // rendering and this request; regenerating then would resume the newer
+ // state yet the client's pending marker (and the chat:quick_actions it
+ // waits on) would point at the stale turn and never reconcile. Refuse so
+ // the client rolls back and re-offers refresh on the new turn (MUL-5149).
+ if target.ID != expectedMessageID {
+ return ErrChatQuickActionsStale
+ }
+ // Refuse while the session already has work in flight (MUL-5149 review
+ // §1/§2). Two races this closes, both under the same session lock as the
+ // enqueue so neither can slip a sibling insert past it:
+ // 1. A normal turn is queued/running but its assistant row hasn't
+ // landed, so the latest-persisted check above still passes on the
+ // OLD turn. That turn will change the reply and advance the session
+ // pointer before this regen claims, leaving the suggestions built
+ // from the newer context but attached to the older turn.
+ // 2. A second concurrent refresh of the same turn would just enqueue a
+ // duplicate pass and double-spend quota — the button being disabled
+ // on one client can't stop another.
+ busy, berr := qtx.HasActiveChatTaskForSession(ctx, chatSession.ID)
+ if berr != nil {
+ return fmt.Errorf("check active chat task: %w", berr)
+ }
+ if busy {
+ return ErrChatQuickActionsBusy
+ }
+ created, cerr := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{
+ AgentID: chatSession.AgentID,
+ RuntimeID: carrier.RuntimeID,
+ Priority: 2, // medium priority, same as an ordinary chat turn
+ ChatSessionID: chatSession.ID,
+ InitiatorUserID: initiatorUserID,
+ OriginatorUserID: initiatorUserID,
+ AccountableUserID: attr.AccountableUserID,
+ // Must resume the target turn's session — a fresh session has no context.
+ ForceFreshSession: pgtype.Bool{Bool: false, Valid: true},
+ OriginatorSource: attrSource,
+ TriggerEvidenceKind: attrEvidenceKind,
+ TriggerEvidenceRefID: attrEvidenceRef,
+ RegenerateQuickActionsFor: target.TaskID,
+ })
+ if cerr != nil {
+ return fmt.Errorf("create quick-actions regenerate task: %w", cerr)
+ }
+ task = created
+ targetID = target.ID
+ return nil
+ }); err != nil {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, err
+ }
+
+ slog.Info("chat quick-actions regenerate enqueued",
+ "task_id", util.UUIDToString(task.ID),
+ "chat_session_id", util.UUIDToString(chatSession.ID),
+ "target_task_id", util.UUIDToString(task.RegenerateQuickActionsFor),
+ )
+ // Deliberately NO task:queued broadcast (contrast EnqueueChatTask): that
+ // event seeds the frontend's chat pending-task cache, which raises the
+ // "Thinking…" StatusPill under the reply (MUL-5149 refresh follow-up). A
+ // regeneration is a background pass that owns no visible turn — its only
+ // affordance is the spinning refresh icon on the pills. The daemon still
+ // wakes via NotifyTaskEnqueued below, and task:dispatch/running are
+ // update-only (guarded on an existing seed), so without the queued seed they
+ // stay no-ops and no pill ever appears.
+ s.NotifyTaskEnqueued(ctx, task)
+ return targetID, task, nil
+}
+
// PromoteChannelChatTasksIfMediaReady queues channel tasks as soon as every
// unexpired media marker in the session has been cleared. If the process dies
// first, the normal deferred-task promoter queues them at their persisted
@@ -1616,7 +1788,7 @@ type DirectChatSendResult struct {
// (archived / no-runtime), passing the loaded agent in; this method trusts those
// permission checks. It does NOT trust the agent's runtime_id: that field is
// re-read inside the transaction (see below).
-func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.ChatSession, agent db.Agent, initiatorUserID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, uploaderType string, uploaderID pgtype.UUID) (*DirectChatSendResult, error) {
+func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.ChatSession, agent db.Agent, initiatorUserID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, uploaderType string, uploaderID pgtype.UUID, quickActionsDisabled bool) (*DirectChatSendResult, error) {
// Build the per-task Composio overlay before the transaction — it can do
// network I/O and must not run with a DB transaction open.
overlay := s.buildRuntimeMCPOverlay(ctx, initiatorUserID, agent)
@@ -1668,6 +1840,7 @@ func (s *TaskService) SendDirectChatMessage(ctx context.Context, session db.Chat
OriginatorSource: attrSource,
TriggerEvidenceKind: attrEvidenceKind,
TriggerEvidenceRefID: attrEvidenceRef,
+ QuickActionsDisabled: pgtype.Bool{Bool: quickActionsDisabled, Valid: true},
})
if err != nil {
return fmt.Errorf("create direct chat task: %w", err)
@@ -2922,11 +3095,19 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
// cursor (chat_session.last_read_at) vs the assistant messages after it — a
// no_response row has role='assistant' and a fresh created_at, so it counts
// as unread just like a text reply, no per-reply stamping needed.
- if task.ChatSessionID.Valid {
+ if task.ChatSessionID.Valid && !task.RegenerateQuickActionsFor.Valid {
// The assistant outcome row (message / no_response) and any attachment
// binding were written inside the completion transaction above by
// writeChatCompletionOutcome. Broadcast chat:done AFTER commit.
- s.broadcastChatDone(ctx, task, chatAssistantMsg)
+ //
+ // A quick-actions regeneration is excluded: it owns no visible turn, and
+ // chat:done unconditionally clears the session's pending-task cache
+ // (use-realtime-sync.ts). If the user sent a real message DURING the
+ // refresh, that turn's "Thinking…" pill would be wrongly cleared. The
+ // refresh's own pending marker is resolved by the daemon's
+ // chat:quick_actions supplement (or resolveFailedRegenerateQuickActions on
+ // failure) instead (MUL-5149).
+ s.broadcastChatDone(ctx, task, chatAssistantMsg, chatQuickActionsPending(result, chatAssistantMsg))
}
// Reconcile agent status
@@ -2972,8 +3153,32 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
// Same unescape as the issue-comment path: literal `\n` from agent stdout
// becomes a real newline so the chat panel renders paragraph breaks.
body := util.UnescapeBackslashEscapes(payload.Output)
+ // Strip any in-band quick-actions footer from EVERY chat completion — the
+ // reserved syntax must never reach a stored transcript. This includes the
+ // agent-initiated intro turn (chat_input_task_id NULL), which previously
+ // fell outside the strip gate and leaked the raw footer into its content;
+ // channel outputs never carry the syntax, so the split is a no-op there.
+ //
+ // New daemons deliver suggestions out-of-band AFTER this callback (the
+ // chat:quick_actions supplement, see SupplementChatQuickActions); the
+ // stripped in-band footer stays as the source for older daemons and
+ // pre-upgrade provider sessions that still emit it.
+ body, quickActions := splitChatQuickActions(body)
+ for i := range quickActions {
+ quickActions[i].Label = redact.Text(quickActions[i].Label)
+ quickActions[i].Prompt = redact.Text(quickActions[i].Prompt)
+ }
isEmpty := strings.TrimSpace(body) == ""
+ // Quick actions only accompany a visible reply. With no visible text they
+ // would produce an assistant row with empty content that older Desktop /
+ // mobile clients — which ignore the quick_actions field — render as an empty
+ // bubble, breaking the no_response fallback contract (MUL-4351). Drop them so
+ // an actions-only turn falls through to the visible no_response outcome below.
+ if isEmpty {
+ quickActions = nil
+ }
+
// MUL-4899 completion-boundary observation. Measures whether the delivery
// contract in the runtime brief is actually landing on the chat surface.
// Strictly non-blocking: the reply is written either way.
@@ -3022,6 +3227,13 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
TaskID: task.ID,
ElapsedMs: computeChatElapsedMs(task),
}
+ if len(quickActions) > 0 {
+ encoded, err := json.Marshal(quickActions)
+ if err != nil {
+ return nil, fmt.Errorf("marshal chat quick actions: %w", err)
+ }
+ params.QuickActions = encoded
+ }
switch {
case !isEmpty:
params.Content = redact.Text(body)
@@ -3335,7 +3547,13 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
// pending (the new attempt will write its own outcome) — same guard as
// the issue path above.
if task.ChatSessionID.Valid && retried == nil {
- if _, err := s.Queries.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ if task.RegenerateQuickActionsFor.Valid {
+ // A failed quick-actions regeneration owns no visible turn: write no
+ // failure bubble (MUL-5149). Its refresh spinner is only resolved by a
+ // chat:quick_actions event, which the daemon's supplement never sent on
+ // this pre-supplement failure — so resolve it here off the target turn.
+ s.resolveFailedRegenerateQuickActions(ctx, task)
+ } else if _, err := s.Queries.CreateChatMessage(ctx, db.CreateChatMessageParams{
ChatSessionID: task.ChatSessionID,
Role: "assistant",
Content: redact.Text(errMsg),
@@ -3368,6 +3586,33 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
return &task, nil
}
+// resolveFailedRegenerateQuickActions resolves a refresh whose regeneration
+// task failed before it could deliver suggestions (MUL-5149). It loads the
+// target turn the refresh was aimed at and broadcasts a FAILED
+// chat:quick_actions carrying that turn's current (unchanged) pills — which
+// resolves the pending marker on every client AND flags the failure so the UI
+// shows a "couldn't refresh" notice instead of stopping the spinner on
+// unchanged content as if it had succeeded. Best-effort: a lookup miss just
+// leaves the client's own timeout fallback to clear the marker.
+func (s *TaskService) resolveFailedRegenerateQuickActions(ctx context.Context, task db.AgentTaskQueue) {
+ if !task.RegenerateQuickActionsFor.Valid {
+ return
+ }
+ target, err := s.Queries.GetAgentTask(ctx, task.RegenerateQuickActionsFor)
+ if err != nil {
+ slog.Warn("regenerate failure: target task lookup failed",
+ "task_id", util.UUIDToString(task.ID), "error", err)
+ return
+ }
+ // Empty raw parses to no actions, so SupplementChatQuickActions re-broadcasts
+ // the target's existing pills (GetChatMessageByTaskAssistant) and resolves the
+ // marker without overwriting anything; failed=true marks it a failure.
+ if err := s.SupplementChatQuickActions(ctx, target, "", true); err != nil {
+ slog.Warn("regenerate failure: resolve pending marker failed",
+ "task_id", util.UUIDToString(task.ID), "error", err)
+ }
+}
+
// retryableReasons enumerates failure reasons that the auto-retry path is
// allowed to act on. Agent-side errors (compile failures, model rejections,
// etc.) are intentionally excluded — those are real problems that the user
@@ -3490,6 +3735,13 @@ func retryEligible(failureReason string, t db.AgentTaskQueue) bool {
return retryableReasons[failureReason] &&
t.Attempt < retryAttemptCeiling(failureReason, t.MaxAttempts) &&
!t.AutopilotRunID.Valid &&
+ // A quick-actions regeneration is an explicit, quota-spending refresh that
+ // is never retried (MUL-5149). CreateRetryTask does not carry the
+ // regenerate_quick_actions_for discriminator, so a retry child would run
+ // as an ordinary chat turn — a visible reply + Thinking pill the user
+ // never asked for. Gating here also covers MaybeRetryFailedTask, which
+ // funnels through retryEligible.
+ !t.RegenerateQuickActionsFor.Valid &&
(t.IssueID.Valid || t.ChatSessionID.Valid)
}
@@ -3857,6 +4109,14 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTas
}
}
+ // A failed quick-actions regeneration owns no visible turn and is never
+ // retried (retryEligible gates it). This sweeper — not FailTask — is how
+ // an orphaned / recovered regenerate task reaches a terminal state, so
+ // converge its client-side refresh spinner here too (MUL-5149).
+ if t.RegenerateQuickActionsFor.Valid {
+ s.resolveFailedRegenerateQuickActions(ctx, t)
+ }
+
failureReason := "agent_error"
if t.FailureReason.Valid && t.FailureReason.String != "" {
failureReason = t.FailureReason.String
@@ -4320,19 +4580,23 @@ func (s *TaskService) ResolveTaskWorkspaceID(ctx context.Context, task db.AgentT
return ""
}
-func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQueue, msg *db.ChatMessage) {
+func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQueue, msg *db.ChatMessage, quickActionsPending bool) {
workspaceID := s.ResolveTaskWorkspaceID(ctx, task)
if workspaceID == "" {
return
}
payload := protocol.ChatDonePayload{
- ChatSessionID: util.UUIDToString(task.ChatSessionID),
- TaskID: util.UUIDToString(task.ID),
+ ChatSessionID: util.UUIDToString(task.ChatSessionID),
+ TaskID: util.UUIDToString(task.ID),
+ QuickActionsPending: quickActionsPending,
}
if msg != nil {
payload.MessageID = util.UUIDToString(msg.ID)
payload.Content = msg.Content
payload.MessageKind = msg.MessageKind
+ if len(msg.QuickActions) > 0 {
+ _ = json.Unmarshal(msg.QuickActions, &payload.QuickActions)
+ }
if msg.CreatedAt.Valid {
payload.CreatedAt = msg.CreatedAt.Time.UTC().Format(time.RFC3339Nano)
}
diff --git a/server/migrations/235_chat_message_quick_actions.down.sql b/server/migrations/235_chat_message_quick_actions.down.sql
new file mode 100644
index 0000000000..724dfa0d50
--- /dev/null
+++ b/server/migrations/235_chat_message_quick_actions.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE chat_message
+DROP COLUMN IF EXISTS quick_actions;
diff --git a/server/migrations/235_chat_message_quick_actions.up.sql b/server/migrations/235_chat_message_quick_actions.up.sql
new file mode 100644
index 0000000000..b518c52b00
--- /dev/null
+++ b/server/migrations/235_chat_message_quick_actions.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE chat_message
+ADD COLUMN IF NOT EXISTS quick_actions JSONB NOT NULL DEFAULT '[]'::jsonb;
diff --git a/server/migrations/236_agent_task_quick_actions_disabled.down.sql b/server/migrations/236_agent_task_quick_actions_disabled.down.sql
new file mode 100644
index 0000000000..b1ca2e755d
--- /dev/null
+++ b/server/migrations/236_agent_task_quick_actions_disabled.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_task_queue
+DROP COLUMN IF EXISTS quick_actions_disabled;
diff --git a/server/migrations/236_agent_task_quick_actions_disabled.up.sql b/server/migrations/236_agent_task_quick_actions_disabled.up.sql
new file mode 100644
index 0000000000..4d9f956278
--- /dev/null
+++ b/server/migrations/236_agent_task_quick_actions_disabled.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_task_queue
+ADD COLUMN IF NOT EXISTS quick_actions_disabled BOOLEAN NOT NULL DEFAULT false;
diff --git a/server/migrations/240_agent_task_regenerate_quick_actions.down.sql b/server/migrations/240_agent_task_regenerate_quick_actions.down.sql
new file mode 100644
index 0000000000..122c05948d
--- /dev/null
+++ b/server/migrations/240_agent_task_regenerate_quick_actions.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_task_queue
+DROP COLUMN IF EXISTS regenerate_quick_actions_for;
diff --git a/server/migrations/240_agent_task_regenerate_quick_actions.up.sql b/server/migrations/240_agent_task_regenerate_quick_actions.up.sql
new file mode 100644
index 0000000000..76d0d932d7
--- /dev/null
+++ b/server/migrations/240_agent_task_regenerate_quick_actions.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_task_queue
+ADD COLUMN IF NOT EXISTS regenerate_quick_actions_for UUID;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 66b067570b..d53fa62678 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -196,7 +196,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -252,6 +252,8 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -260,7 +262,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -327,6 +329,8 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -342,7 +346,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Cancels active tasks belonging to a chat session. Called from
@@ -409,6 +413,8 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -424,7 +430,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -491,6 +497,8 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -506,7 +514,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -577,6 +585,8 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -593,7 +603,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -659,6 +669,8 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -679,9 +691,9 @@ WITH cancelled AS (
AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
AND primary_task.issue_id = $1
AND primary_task.agent_id = $2
- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id
+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for
)
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM cancelled
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM cancelled
`
type CancelDeferredEscalationsForIssueAgentParams struct {
@@ -690,55 +702,57 @@ type CancelDeferredEscalationsForIssueAgentParams struct {
}
type CancelDeferredEscalationsForIssueAgentRow struct {
- ID pgtype.UUID `json:"id"`
- AgentID pgtype.UUID `json:"agent_id"`
- IssueID pgtype.UUID `json:"issue_id"`
- Status string `json:"status"`
- Priority int32 `json:"priority"`
- DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
- StartedAt pgtype.Timestamptz `json:"started_at"`
- CompletedAt pgtype.Timestamptz `json:"completed_at"`
- Result []byte `json:"result"`
- Error pgtype.Text `json:"error"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- Context []byte `json:"context"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- SessionID pgtype.Text `json:"session_id"`
- WorkDir pgtype.Text `json:"work_dir"`
- TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
- Attempt int32 `json:"attempt"`
- MaxAttempts int32 `json:"max_attempts"`
- ParentTaskID pgtype.UUID `json:"parent_task_id"`
- FailureReason pgtype.Text `json:"failure_reason"`
- TriggerSummary pgtype.Text `json:"trigger_summary"`
- ForceFreshSession bool `json:"force_fresh_session"`
- IsLeaderTask bool `json:"is_leader_task"`
- WaitReason pgtype.Text `json:"wait_reason"`
- InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
- HandoffNote pgtype.Text `json:"handoff_note"`
- PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`
- SquadID pgtype.UUID `json:"squad_id"`
- RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
- EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`
- FireAt pgtype.Timestamptz `json:"fire_at"`
- OriginatorUserID pgtype.UUID `json:"originator_user_id"`
- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
- CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
- DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
- ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
- ChatFinalizeDeferredAt pgtype.Timestamptz `json:"chat_finalize_deferred_at"`
- OriginatorSource pgtype.Text `json:"originator_source"`
- DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`
- RetryOfTaskID pgtype.UUID `json:"retry_of_task_id"`
- RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`
- RuleVersionID pgtype.UUID `json:"rule_version_id"`
- TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
- TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
- AccountableUserID pgtype.UUID `json:"accountable_user_id"`
- SessionRolloutMissing bool `json:"session_rollout_missing"`
- RetiredSessionID pgtype.Text `json:"retired_session_id"`
+ ID pgtype.UUID `json:"id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Status string `json:"status"`
+ Priority int32 `json:"priority"`
+ DispatchedAt pgtype.Timestamptz `json:"dispatched_at"`
+ StartedAt pgtype.Timestamptz `json:"started_at"`
+ CompletedAt pgtype.Timestamptz `json:"completed_at"`
+ Result []byte `json:"result"`
+ Error pgtype.Text `json:"error"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ Context []byte `json:"context"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ Attempt int32 `json:"attempt"`
+ MaxAttempts int32 `json:"max_attempts"`
+ ParentTaskID pgtype.UUID `json:"parent_task_id"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ TriggerSummary pgtype.Text `json:"trigger_summary"`
+ ForceFreshSession bool `json:"force_fresh_session"`
+ IsLeaderTask bool `json:"is_leader_task"`
+ WaitReason pgtype.Text `json:"wait_reason"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ HandoffNote pgtype.Text `json:"handoff_note"`
+ PrepareLeaseExpiresAt pgtype.Timestamptz `json:"prepare_lease_expires_at"`
+ SquadID pgtype.UUID `json:"squad_id"`
+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
+ EscalationForTaskID pgtype.UUID `json:"escalation_for_task_id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
+ DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
+ ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
+ ChatFinalizeDeferredAt pgtype.Timestamptz `json:"chat_finalize_deferred_at"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`
+ RetryOfTaskID pgtype.UUID `json:"retry_of_task_id"`
+ RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`
+ RuleVersionID pgtype.UUID `json:"rule_version_id"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
+ SessionRolloutMissing bool `json:"session_rollout_missing"`
+ RetiredSessionID pgtype.Text `json:"retired_session_id"`
+ QuickActionsDisabled bool `json:"quick_actions_disabled"`
+ RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`
}
func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
@@ -800,6 +814,8 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -816,7 +832,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE escalation_for_task_id = $1
AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -878,6 +894,8 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -918,7 +936,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type ClaimAgentTaskParams struct {
@@ -988,6 +1006,8 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -996,7 +1016,7 @@ const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = NULL
WHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Atomically claims the deferred marker so the daemon ack and the sweeper
@@ -1054,6 +1074,8 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -1246,7 +1268,7 @@ SET status = 'completed', completed_at = now(), result = $2,
retired_session_id = COALESCE($6, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type CompleteAgentTaskParams struct {
@@ -1329,6 +1351,8 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -1545,7 +1569,7 @@ VALUES (
$21,
$22
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type CreateAgentTaskParams struct {
@@ -1656,6 +1680,8 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -1682,7 +1708,7 @@ VALUES (
$15,
$16
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type CreateDeferredAgentTaskParams struct {
@@ -1781,6 +1807,8 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -1801,7 +1829,7 @@ VALUES (
$10,
$11
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type CreateQuickCreateTaskParams struct {
@@ -1889,6 +1917,8 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -1924,7 +1954,7 @@ SELECT
p.chat_input_task_id, $2
FROM agent_task_queue p
WHERE p.id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type CreateRetryTaskParams struct {
@@ -2046,6 +2076,8 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -2082,7 +2114,7 @@ FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for
`
type ExpireStaleQueuedTasksParams struct {
@@ -2172,6 +2204,8 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -2190,7 +2224,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -2256,6 +2290,8 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -2272,7 +2308,7 @@ SET status = 'failed',
retired_session_id = COALESCE($7, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type FailAgentTaskParams struct {
@@ -2361,6 +2397,8 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -2385,7 +2423,7 @@ WHERE (
AND r.last_seen_at >= now() - make_interval(secs => $3::double precision)
)
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type FailStaleTasksParams struct {
@@ -2490,6 +2528,8 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -2675,7 +2715,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM agent_task_queue
WHERE id = $1
`
@@ -2732,12 +2772,14 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -2807,6 +2849,8 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -3416,7 +3460,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -3485,6 +3529,8 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -3497,7 +3543,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -3561,6 +3607,8 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -3748,7 +3796,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U
}
const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM agent_task_queue
WHERE chat_finalize_deferred_at IS NOT NULL
AND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)
ORDER BY chat_finalize_deferred_at
@@ -3822,6 +3870,8 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -3834,7 +3884,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -3898,6 +3948,8 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -3910,7 +3962,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -3982,6 +4034,8 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -3994,7 +4048,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM agent_task_queue
WHERE runtime_id = ANY($1::uuid[]) AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -4068,6 +4122,8 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -4080,7 +4136,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -4144,6 +4200,8 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -4156,16 +4214,16 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id FROM agent a
+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for FROM agent a
JOIN LATERAL (
- SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id
+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for
FROM agent_task_queue atq
WHERE atq.agent_id = a.id
AND atq.status IN ('completed', 'failed')
@@ -4259,6 +4317,8 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -4452,7 +4512,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
WHERE id = $1 AND status = 'dispatched'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -4523,6 +4583,8 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -4531,7 +4593,7 @@ const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = now()
WHERE id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Arms the deferred chat-finalize marker for a cancelled chat task whose
@@ -4589,6 +4651,8 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -4731,7 +4795,7 @@ SET status = 'queued'
WHERE runtime_id = $1
AND status = 'deferred'
AND fire_at <= now()
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -4793,6 +4857,8 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtime
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -4810,7 +4876,7 @@ SET status = 'queued'
WHERE runtime_id = ANY($1::uuid[])
AND status = 'deferred'
AND fire_at <= now()
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all
@@ -4874,6 +4940,8 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, runtim
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -4974,7 +5042,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -5041,6 +5109,8 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -5060,7 +5130,7 @@ WHERE id IN (
LIMIT $4::int
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type ReclaimStaleDispatchedTasksForRuntimesParams struct {
@@ -5141,6 +5211,8 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -5161,7 +5233,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -5229,6 +5301,8 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -5367,7 +5441,7 @@ WHERE id = $1
AND status = 'dispatched'
AND started_at IS NULL
AND dispatched_at = $3
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -5434,6 +5508,8 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -5534,7 +5610,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -5596,6 +5672,8 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index fcf59fd1c6..1cf3147050 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -288,7 +288,7 @@ VALUES (
$10,
$11
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type CreateAutopilotTaskParams struct {
@@ -385,6 +385,8 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -746,7 +748,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD
}
const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for FROM agent_task_queue
WHERE autopilot_run_id = $1
ORDER BY created_at
LIMIT 1
@@ -807,6 +809,8 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index db12a6d767..8d26573fbb 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -142,22 +142,23 @@ func (q *Queries) CreateChatDraftRestore(ctx context.Context, arg CreateChatDraf
const createChatMessage = `-- name: CreateChatMessage :one
INSERT INTO chat_message (
chat_session_id, role, content, task_id, failure_reason, elapsed_ms,
- message_kind, channel_media_pending_until, channel_ingested
+ message_kind, quick_actions, channel_media_pending_until, channel_ingested
)
VALUES (
$1, $2, $3, $4, $5, $6,
COALESCE($7::text, 'message'),
+ COALESCE($8::jsonb, '[]'::jsonb),
-- The media deadline is DB-clock time: every consumer compares it against
-- SQL now() (GetChannelMediaPendingUntil, the deferred promote, the
-- trailing-message guard), so the writer must use the same clock. The
-- caller passes a relative budget in seconds; an application-clock
-- timestamp here would let a skewed app node shrink or stretch the
-- fallback window.
- CASE WHEN $8::float8 IS NULL THEN NULL
- ELSE now() + make_interval(secs => $8::float8) END,
- COALESCE($9::boolean, FALSE)
+ CASE WHEN $9::float8 IS NULL THEN NULL
+ ELSE now() + make_interval(secs => $9::float8) END,
+ COALESCE($10::boolean, FALSE)
)
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions
`
type CreateChatMessageParams struct {
@@ -168,11 +169,12 @@ type CreateChatMessageParams struct {
FailureReason pgtype.Text `json:"failure_reason"`
ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
MessageKind pgtype.Text `json:"message_kind"`
+ QuickActions []byte `json:"quick_actions"`
ChannelMediaPendingSecs pgtype.Float8 `json:"channel_media_pending_secs"`
ChannelIngested pgtype.Bool `json:"channel_ingested"`
}
-// message_kind defaults to 'message' via COALESCE so every existing caller
+// message_kind and quick_actions default via COALESCE so every existing caller
// (which omits it) keeps writing ordinary messages; the empty-reply path passes
// 'no_response' to mark a visible turn with no text output (MUL-4351).
func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessageParams) (ChatMessage, error) {
@@ -184,6 +186,7 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
arg.FailureReason,
arg.ElapsedMs,
arg.MessageKind,
+ arg.QuickActions,
arg.ChannelMediaPendingSecs,
arg.ChannelIngested,
)
@@ -200,6 +203,7 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
&i.MessageKind,
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
+ &i.QuickActions,
)
return i, err
}
@@ -255,7 +259,7 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
- fire_at
+ quick_actions_disabled, regenerate_quick_actions_for, fire_at
)
VALUES (
$1, $2, NULL,
@@ -269,26 +273,30 @@ VALUES (
$12,
$13,
$14,
+ COALESCE($15::boolean, FALSE),
+ $16,
$6::timestamptz
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type CreateChatTaskParams struct {
- AgentID pgtype.UUID `json:"agent_id"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- Priority int32 `json:"priority"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
- FireAt pgtype.Timestamptz `json:"fire_at"`
- OriginatorUserID pgtype.UUID `json:"originator_user_id"`
- AccountableUserID pgtype.UUID `json:"accountable_user_id"`
- ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
- RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
- OriginatorSource pgtype.Text `json:"originator_source"`
- TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
- TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Priority int32 `json:"priority"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ QuickActionsDisabled pgtype.Bool `json:"quick_actions_disabled"`
+ RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`
}
// The chat sender (initiator) is a direct_human originator and accountable;
@@ -310,6 +318,8 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
arg.OriginatorSource,
arg.TriggerEvidenceKind,
arg.TriggerEvidenceRefID,
+ arg.QuickActionsDisabled,
+ arg.RegenerateQuickActionsFor,
)
var i AgentTaskQueue
err := row.Scan(
@@ -362,6 +372,8 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -379,7 +391,7 @@ FROM (
WHERE task.id = $1
AND pending.max_until IS NOT NULL
AND (task.fire_at IS NULL OR task.fire_at < pending.max_until)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for
`
// Closes the enqueue-vs-append race: under READ COMMITTED a media message can
@@ -441,6 +453,8 @@ func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
@@ -538,7 +552,7 @@ func (q *Queries) DeleteChatSession(ctx context.Context, arg DeleteChatSessionPa
const deleteUserChatMessageByTask = `-- name: DeleteUserChatMessageByTask :one
DELETE FROM chat_message
WHERE task_id = $1 AND role = 'user'
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions
`
func (q *Queries) DeleteUserChatMessageByTask(ctx context.Context, taskID pgtype.UUID) (ChatMessage, error) {
@@ -556,6 +570,7 @@ func (q *Queries) DeleteUserChatMessageByTask(ctx context.Context, taskID pgtype
&i.MessageKind,
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
+ &i.QuickActions,
)
return i, err
}
@@ -580,7 +595,7 @@ func (q *Queries) GetChannelMediaPendingUntil(ctx context.Context, chatSessionID
}
const getChatMessage = `-- name: GetChatMessage :one
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
WHERE id = $1
`
@@ -599,6 +614,36 @@ func (q *Queries) GetChatMessage(ctx context.Context, id pgtype.UUID) (ChatMessa
&i.MessageKind,
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
+ &i.QuickActions,
+ )
+ return i, err
+}
+
+const getChatMessageByTaskAssistant = `-- name: GetChatMessageByTaskAssistant :one
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
+WHERE task_id = $1 AND role = 'assistant'
+ORDER BY created_at DESC
+LIMIT 1
+`
+
+// The completed turn's assistant outcome row, for the quick-actions
+// supplement path (daemon suggestion pass finishing after chat:done).
+func (q *Queries) GetChatMessageByTaskAssistant(ctx context.Context, taskID pgtype.UUID) (ChatMessage, error) {
+ row := q.db.QueryRow(ctx, getChatMessageByTaskAssistant, taskID)
+ var i ChatMessage
+ err := row.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.Role,
+ &i.Content,
+ &i.TaskID,
+ &i.CreatedAt,
+ &i.FailureReason,
+ &i.ElapsedMs,
+ &i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
+ &i.QuickActions,
)
return i, err
}
@@ -732,8 +777,39 @@ func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgty
return i, err
}
+const getLatestAssistantChatMessageForSession = `-- name: GetLatestAssistantChatMessageForSession :one
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
+WHERE chat_session_id = $1 AND role = 'assistant' AND task_id IS NOT NULL
+ORDER BY created_at DESC
+LIMIT 1
+`
+
+// The session's most recent assistant turn, used as the regeneration target
+// when the user clicks "refresh" on the quick-actions row (MUL-5149). Only rows
+// with a task_id qualify — the daemon suggest supplement keys off task_id and
+// a resume needs a real completed turn to resume from.
+func (q *Queries) GetLatestAssistantChatMessageForSession(ctx context.Context, chatSessionID pgtype.UUID) (ChatMessage, error) {
+ row := q.db.QueryRow(ctx, getLatestAssistantChatMessageForSession, chatSessionID)
+ var i ChatMessage
+ err := row.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.Role,
+ &i.Content,
+ &i.TaskID,
+ &i.CreatedAt,
+ &i.FailureReason,
+ &i.ElapsedMs,
+ &i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
+ &i.QuickActions,
+ )
+ return i, err
+}
+
const getMostRecentUserChatMessage = `-- name: GetMostRecentUserChatMessage :one
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
WHERE chat_session_id = $1 AND role = 'user'
ORDER BY created_at DESC
LIMIT 1
@@ -759,6 +835,7 @@ func (q *Queries) GetMostRecentUserChatMessage(ctx context.Context, chatSessionI
&i.MessageKind,
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
+ &i.QuickActions,
)
return i, err
}
@@ -766,6 +843,10 @@ func (q *Queries) GetMostRecentUserChatMessage(ctx context.Context, chatSessionI
const getPendingChatTask = `-- name: GetPendingChatTask :one
SELECT id, status, created_at FROM agent_task_queue
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ -- Background quick-actions regeneration passes are invisible to the chat UI:
+ -- they own no assistant turn and must not raise the StatusPill or disable the
+ -- composer (MUL-5149 refresh follow-up).
+ AND regenerate_quick_actions_for IS NULL
ORDER BY created_at DESC
LIMIT 1
`
@@ -788,6 +869,36 @@ func (q *Queries) GetPendingChatTask(ctx context.Context, chatSessionID pgtype.U
return i, err
}
+const hasActiveChatTaskForSession = `-- name: HasActiveChatTaskForSession :one
+SELECT EXISTS (
+ SELECT 1 FROM agent_task_queue
+ WHERE chat_session_id = $1
+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+) AS has_active
+`
+
+// True while ANY task — a normal user turn OR a background quick-actions
+// regenerate — is in flight for the session (contrast GetPendingChatTask, which
+// hides regenerate passes from the UI). A quick-actions refresh is refused when
+// this is true: a running turn is about to change the latest reply, so the
+// target we'd resume is already stale even before its assistant row lands; and a
+// second concurrent regenerate would double-spend quota on the same turn. Read
+// inside the same session lock as the enqueue so it cannot race a sibling insert
+// (MUL-5149 review §1/§2).
+//
+// 'deferred' is included: an auto-retry armed with a backoff fire_at is inserted
+// deferred (CreateRetryTask), and provider_network's final chat attempt waits
+// ~5s that way. During that window the failed turn has written no assistant row,
+// so the latest-persisted check still points at the OLD turn — omitting deferred
+// would let a refresh resume a session the retry is about to advance and attach
+// the new turn's suggestions to the old one (MUL-5149 re-review §1).
+func (q *Queries) HasActiveChatTaskForSession(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {
+ row := q.db.QueryRow(ctx, hasActiveChatTaskForSession, chatSessionID)
+ var has_active bool
+ err := row.Scan(&has_active)
+ return has_active, err
+}
+
const hasPendingChatTasksByCreator = `-- name: HasPendingChatTasksByCreator :one
SELECT EXISTS (
SELECT 1
@@ -795,6 +906,9 @@ SELECT EXISTS (
JOIN chat_session cs ON cs.id = atq.chat_session_id
WHERE atq.chat_session_id IS NOT NULL
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ -- Background quick-actions regeneration passes own no visible turn and must
+ -- never light the FAB "running" indicator (MUL-5149 refresh follow-up).
+ AND atq.regenerate_quick_actions_for IS NULL
AND cs.workspace_id = $1
AND cs.creator_id = $2
AND cs.agent_id = ANY($3::uuid[])
@@ -1006,7 +1120,7 @@ func (q *Queries) ListChatDraftRestoresBySession(ctx context.Context, chatSessio
}
const listChatInputMessages = `-- name: ListChatInputMessages :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
WHERE task_id = $1 AND role = 'user'
ORDER BY created_at ASC, id ASC
`
@@ -1039,6 +1153,7 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)
&i.MessageKind,
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
+ &i.QuickActions,
); err != nil {
return nil, err
}
@@ -1051,7 +1166,7 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)
}
const listChatMessages = `-- name: ListChatMessages :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
WHERE chat_session_id = $1
ORDER BY created_at ASC, id ASC
`
@@ -1077,6 +1192,7 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI
&i.MessageKind,
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
+ &i.QuickActions,
); err != nil {
return nil, err
}
@@ -1089,7 +1205,7 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI
}
const listChatMessagesPage = `-- name: ListChatMessagesPage :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions FROM chat_message
WHERE chat_session_id = $1
AND (
$3::timestamptz IS NULL
@@ -1132,6 +1248,7 @@ func (q *Queries) ListChatMessagesPage(ctx context.Context, arg ListChatMessages
&i.MessageKind,
&i.ChannelMediaPendingUntil,
&i.ChannelIngested,
+ &i.QuickActions,
); err != nil {
return nil, err
}
@@ -1248,6 +1365,9 @@ FROM agent_task_queue atq
JOIN chat_session cs ON cs.id = atq.chat_session_id
WHERE atq.chat_session_id IS NOT NULL
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ -- Exclude background quick-actions regeneration passes: they own no assistant
+ -- turn and must not surface as "running" chat work (MUL-5149 refresh follow-up).
+ AND atq.regenerate_quick_actions_for IS NULL
AND cs.workspace_id = $1
AND cs.creator_id = $2
ORDER BY atq.created_at DESC
@@ -1503,7 +1623,7 @@ WHERE task.chat_session_id = $1
AND message.role = 'user'
AND message.channel_media_pending_until > now()
)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for
`
// Media completion may race with the 3s run batcher. Promote every original
@@ -1568,6 +1688,8 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -1579,6 +1701,43 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS
return items, nil
}
+const setChatMessageQuickActionsByTask = `-- name: SetChatMessageQuickActionsByTask :one
+UPDATE chat_message
+SET quick_actions = $2
+WHERE id = (
+ SELECT inner_msg.id FROM chat_message AS inner_msg
+ WHERE inner_msg.task_id = $1 AND inner_msg.role = 'assistant'
+ ORDER BY inner_msg.created_at DESC
+ LIMIT 1
+)
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions
+`
+
+type SetChatMessageQuickActionsByTaskParams struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ QuickActions []byte `json:"quick_actions"`
+}
+
+func (q *Queries) SetChatMessageQuickActionsByTask(ctx context.Context, arg SetChatMessageQuickActionsByTaskParams) (ChatMessage, error) {
+ row := q.db.QueryRow(ctx, setChatMessageQuickActionsByTask, arg.TaskID, arg.QuickActions)
+ var i ChatMessage
+ err := row.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.Role,
+ &i.Content,
+ &i.TaskID,
+ &i.CreatedAt,
+ &i.FailureReason,
+ &i.ElapsedMs,
+ &i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
+ &i.QuickActions,
+ )
+ return i, err
+}
+
const setChatSessionArchived = `-- name: SetChatSessionArchived :one
UPDATE chat_session
SET status = CASE WHEN $2::bool THEN 'archived' ELSE 'active' END,
@@ -1665,7 +1824,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :one
UPDATE agent_task_queue
SET chat_input_task_id = id
WHERE id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Stamps a freshly-created direct-chat task as the owner of its own input batch
@@ -1728,6 +1887,8 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 21b0a965b7..a8a061b2eb 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -149,9 +149,11 @@ type AgentTaskQueue struct {
// The row id referenced by trigger_evidence_kind (a comment id, autopilot_run id, rule_version id, source task id, ...). No FK; resolvable per-kind in the app layer (MUL-4302 §2).
TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
// The one human accountable for this run, for audit / visibility / cost only — NEVER consulted for authorization (that is originator_user_id). Invariant: when originator_user_id IS NOT NULL, this equals it; the two diverge only when originator_user_id IS NULL (autopilot rule_owner / degraded owner_fallback name an accountable human while authorization carries none). No FK, no cascade (MUL-4302 §1/§7). NULL means no accountable human was resolved: a pre-migration row, OR a NEW row whose audit source is not-yet-resolved / unattributed (e.g. run_only autopilot until rule_owner lands) — NOT pre-migration only.
- AccountableUserID pgtype.UUID `json:"accountable_user_id"`
- SessionRolloutMissing bool `json:"session_rollout_missing"`
- RetiredSessionID pgtype.Text `json:"retired_session_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
+ SessionRolloutMissing bool `json:"session_rollout_missing"`
+ RetiredSessionID pgtype.Text `json:"retired_session_id"`
+ QuickActionsDisabled bool `json:"quick_actions_disabled"`
+ RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`
}
type AgentToLabel struct {
@@ -381,6 +383,7 @@ type ChatMessage struct {
MessageKind string `json:"message_kind"`
ChannelMediaPendingUntil pgtype.Timestamptz `json:"channel_media_pending_until"`
ChannelIngested bool `json:"channel_ingested"`
+ QuickActions []byte `json:"quick_actions"`
}
type ChatPinnedAgent struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index e2e302f262..59652ee2f1 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -97,6 +97,8 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
@@ -228,7 +230,7 @@ WHERE status IN ('dispatched', 'running', 'waiting_local_directory')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -293,6 +295,8 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.AccountableUserID,
&i.SessionRolloutMissing,
&i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 92064e500f..2205450929 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -208,16 +208,17 @@ UPDATE chat_session SET updated_at = now()
WHERE id = $1;
-- name: CreateChatMessage :one
--- message_kind defaults to 'message' via COALESCE so every existing caller
+-- message_kind and quick_actions default via COALESCE so every existing caller
-- (which omits it) keeps writing ordinary messages; the empty-reply path passes
-- 'no_response' to mark a visible turn with no text output (MUL-4351).
INSERT INTO chat_message (
chat_session_id, role, content, task_id, failure_reason, elapsed_ms,
- message_kind, channel_media_pending_until, channel_ingested
+ message_kind, quick_actions, channel_media_pending_until, channel_ingested
)
VALUES (
$1, $2, $3, sqlc.narg(task_id), sqlc.narg(failure_reason), sqlc.narg(elapsed_ms),
COALESCE(sqlc.narg(message_kind)::text, 'message'),
+ COALESCE(sqlc.narg(quick_actions)::jsonb, '[]'::jsonb),
-- The media deadline is DB-clock time: every consumer compares it against
-- SQL now() (GetChannelMediaPendingUntil, the deferred promote, the
-- trailing-message guard), so the writer must use the same clock. The
@@ -350,7 +351,7 @@ INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
- fire_at
+ quick_actions_disabled, regenerate_quick_actions_for, fire_at
)
VALUES (
$1, $2, NULL,
@@ -364,6 +365,8 @@ VALUES (
sqlc.narg(originator_source),
sqlc.narg(trigger_evidence_kind),
sqlc.narg(trigger_evidence_ref_id),
+ COALESCE(sqlc.narg('quick_actions_disabled')::boolean, FALSE),
+ sqlc.narg(regenerate_quick_actions_for),
sqlc.narg('fire_at')::timestamptz
)
RETURNING *;
@@ -453,6 +456,28 @@ WHERE session_id NOT IN (SELECT session_id FROM retired_sessions)
ORDER BY completed_at DESC
LIMIT 1;
+-- name: HasActiveChatTaskForSession :one
+-- True while ANY task — a normal user turn OR a background quick-actions
+-- regenerate — is in flight for the session (contrast GetPendingChatTask, which
+-- hides regenerate passes from the UI). A quick-actions refresh is refused when
+-- this is true: a running turn is about to change the latest reply, so the
+-- target we'd resume is already stale even before its assistant row lands; and a
+-- second concurrent regenerate would double-spend quota on the same turn. Read
+-- inside the same session lock as the enqueue so it cannot race a sibling insert
+-- (MUL-5149 review §1/§2).
+--
+-- 'deferred' is included: an auto-retry armed with a backoff fire_at is inserted
+-- deferred (CreateRetryTask), and provider_network's final chat attempt waits
+-- ~5s that way. During that window the failed turn has written no assistant row,
+-- so the latest-persisted check still points at the OLD turn — omitting deferred
+-- would let a refresh resume a session the retry is about to advance and attach
+-- the new turn's suggestions to the old one (MUL-5149 re-review §1).
+SELECT EXISTS (
+ SELECT 1 FROM agent_task_queue
+ WHERE chat_session_id = $1
+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+) AS has_active;
+
-- name: GetPendingChatTask :one
-- Returns the most recent in-flight task for a chat session, if any.
-- Used by the frontend to recover pending state after refresh / reopen.
@@ -461,6 +486,10 @@ LIMIT 1;
-- without "resetting to 0s".
SELECT id, status, created_at FROM agent_task_queue
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ -- Background quick-actions regeneration passes are invisible to the chat UI:
+ -- they own no assistant turn and must not raise the StatusPill or disable the
+ -- composer (MUL-5149 refresh follow-up).
+ AND regenerate_quick_actions_for IS NULL
ORDER BY created_at DESC
LIMIT 1;
@@ -481,6 +510,9 @@ FROM agent_task_queue atq
JOIN chat_session cs ON cs.id = atq.chat_session_id
WHERE atq.chat_session_id IS NOT NULL
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ -- Exclude background quick-actions regeneration passes: they own no assistant
+ -- turn and must not surface as "running" chat work (MUL-5149 refresh follow-up).
+ AND atq.regenerate_quick_actions_for IS NULL
AND cs.workspace_id = $1
AND cs.creator_id = $2
ORDER BY atq.created_at DESC;
@@ -501,6 +533,9 @@ SELECT EXISTS (
JOIN chat_session cs ON cs.id = atq.chat_session_id
WHERE atq.chat_session_id IS NOT NULL
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ -- Background quick-actions regeneration passes own no visible turn and must
+ -- never light the FAB "running" indicator (MUL-5149 refresh follow-up).
+ AND atq.regenerate_quick_actions_for IS NULL
AND cs.workspace_id = sqlc.arg(workspace_id)
AND cs.creator_id = sqlc.arg(creator_id)
AND cs.agent_id = ANY(sqlc.arg(agent_ids)::uuid[])
@@ -637,3 +672,32 @@ WHERE chat_session_id IN (
JOIN agent a ON a.id = cs.agent_id
WHERE a.runtime_id = $1 AND a.kind = 'system'
);
+
+-- name: GetChatMessageByTaskAssistant :one
+-- The completed turn's assistant outcome row, for the quick-actions
+-- supplement path (daemon suggestion pass finishing after chat:done).
+SELECT * FROM chat_message
+WHERE task_id = $1 AND role = 'assistant'
+ORDER BY created_at DESC
+LIMIT 1;
+
+-- name: GetLatestAssistantChatMessageForSession :one
+-- The session's most recent assistant turn, used as the regeneration target
+-- when the user clicks "refresh" on the quick-actions row (MUL-5149). Only rows
+-- with a task_id qualify — the daemon suggest supplement keys off task_id and
+-- a resume needs a real completed turn to resume from.
+SELECT * FROM chat_message
+WHERE chat_session_id = $1 AND role = 'assistant' AND task_id IS NOT NULL
+ORDER BY created_at DESC
+LIMIT 1;
+
+-- name: SetChatMessageQuickActionsByTask :one
+UPDATE chat_message
+SET quick_actions = $2
+WHERE id = (
+ SELECT inner_msg.id FROM chat_message AS inner_msg
+ WHERE inner_msg.task_id = $1 AND inner_msg.role = 'assistant'
+ ORDER BY inner_msg.created_at DESC
+ LIMIT 1
+)
+RETURNING *;
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 2d1ca386c9..e5fc06dbb7 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -73,6 +73,11 @@ const (
// Chat events
EventChatMessage = "chat:message"
EventChatDone = "chat:done"
+ // EventChatQuickActions supplements a finished turn with follow-up
+ // suggestions generated by the daemon's post-completion pass. Sent after
+ // chat:done; clients that don't know it simply never resolve the
+ // (equally unknown) pending state.
+ EventChatQuickActions = "chat:quick_actions"
// EventChatCancelFinalized carries the deferred outcome of a cancelled
// chat task once the daemon has flushed its transcript (or the sweeper
// grace period expired): either a late "Stopped." assistant message or a
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 91a8d37fc4..820bd2086e 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -21,6 +21,14 @@ const (
AppCapabilityChatDraftRestoreV1 = "chat-draft-restore-v1"
)
+// ChatQuickAction is a server-validated follow-up attached to one assistant
+// reply. Label is the concise chip text; Prompt is the full next user turn.
+type ChatQuickAction struct {
+ Label string `json:"label"`
+ Prompt string `json:"prompt"`
+ Primary bool `json:"primary,omitempty"`
+}
+
// RPCRequestPayload is the generic daemon→server request envelope carried in a
// protocol.Message of type EventDaemonRPCRequest. RequestID correlates the
// response; Method selects the server-side handler (e.g. "tasks.claim"); Body
@@ -116,6 +124,30 @@ type TaskCompletedPayload struct {
TaskID string `json:"task_id"`
PRURL string `json:"pr_url,omitempty"`
Output string `json:"output,omitempty"`
+ // QuickActionsPending declares that this daemon will follow up with a
+ // quick-actions supplement for this chat turn (the suggestion pass runs
+ // in the background after this callback). Per-turn capability signal:
+ // absent on non-chat tasks, skipped turns, and older daemons — so a
+ // false/missing flag means clients must not wait for suggestions.
+ QuickActionsPending bool `json:"quick_actions_pending,omitempty"`
+}
+
+// ChatQuickActionsPayload supplements one completed chat turn with the
+// sanitized follow-up actions from the daemon's suggestion pass. An empty
+// QuickActions list is a meaningful terminal state — it resolves the
+// pending skeleton with "no suggestions this turn".
+type ChatQuickActionsPayload struct {
+ ChatSessionID string `json:"chat_session_id"`
+ TaskID string `json:"task_id"`
+ MessageID string `json:"message_id"`
+ QuickActions []ChatQuickAction `json:"quick_actions"`
+ // Failed marks a supplement that resolves the client's refresh spinner
+ // because the regeneration FAILED (the provider pass or its delivery), not
+ // because it produced new suggestions. QuickActions then carries the turn's
+ // unchanged pills; the client shows a "couldn't refresh" notice instead of
+ // treating unchanged content as a silent success (MUL-5149). Omitted (false)
+ // on the normal success path and for the automatic best-effort pass.
+ Failed bool `json:"failed,omitempty"`
}
// TaskMessagePayload represents a single agent execution message (tool call, text, etc.)
@@ -180,13 +212,18 @@ const (
// the omitempty tags only elide fields for the legacy paths that broadcast
// without a row.
type ChatDonePayload struct {
- ChatSessionID string `json:"chat_session_id"`
- TaskID string `json:"task_id"`
- MessageID string `json:"message_id,omitempty"`
- Content string `json:"content,omitempty"`
- ElapsedMs int64 `json:"elapsed_ms,omitempty"`
- CreatedAt string `json:"created_at,omitempty"`
- MessageKind string `json:"message_kind,omitempty"`
+ ChatSessionID string `json:"chat_session_id"`
+ TaskID string `json:"task_id"`
+ MessageID string `json:"message_id,omitempty"`
+ Content string `json:"content,omitempty"`
+ ElapsedMs int64 `json:"elapsed_ms,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
+ MessageKind string `json:"message_kind,omitempty"`
+ QuickActions []ChatQuickAction `json:"quick_actions,omitempty"`
+ // QuickActionsPending tells clients a chat:quick_actions supplement will
+ // follow for this turn (render a placeholder). Never true when
+ // QuickActions is already populated.
+ QuickActionsPending bool `json:"quick_actions_pending,omitempty"`
}
// Outcome values carried by ChatCancelFinalizedPayload.