Skip to content

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

Go

refactor(chat): generate quick actions server-side via the LLM layer (MUL-5573) (#6214)

Jiayuan Zhangf13969b99641
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 1e8677b825..da4ad9502e 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -2317,21 +2317,14 @@ export class ApiClient {
sessionId: string,
content: string,
attachmentIds?: string[],
- options?: { quickActionsEnabled?: boolean },
): Promise<SendChatMessageResponse> {
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/chat/queries.ts b/packages/core/chat/queries.ts
index 19177af58e..553f559e4f 100644
--- a/packages/core/chat/queries.ts
+++ b/packages/core/chat/queries.ts
@@ -13,8 +13,14 @@ import type {
* `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.
+ *
+ * Sized from the server's own budget: suggestions are generated by a bounded
+ * (8s) LLM call, leaving room for the write and the realtime broadcast. Keep
+ * this above `chatQuickActionsTimeout` in the backend — a window shorter than
+ * the work it waits on makes every slow-but-successful pass look like a
+ * failure, then silently swap the pills in afterwards.
*/
-export const QUICK_ACTIONS_PENDING_TIMEOUT_MS = 30_000;
+export const QUICK_ACTIONS_PENDING_TIMEOUT_MS = 12_000;
// NOTE on workspace scoping:
// `wsId` is used only as part of queryKey for cache isolation per workspace.
diff --git a/packages/core/chat/store.test.ts b/packages/core/chat/store.test.ts
index f3d1ea19a8..cacb1c9b81 100644
--- a/packages/core/chat/store.test.ts
+++ b/packages/core/chat/store.test.ts
@@ -308,33 +308,6 @@ 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 dee2ded469..2bfba088b7 100644
--- a/packages/core/chat/store.ts
+++ b/packages/core/chat/store.ts
@@ -74,13 +74,6 @@ 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);
@@ -311,8 +304,6 @@ 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
@@ -334,7 +325,6 @@ 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;
@@ -389,7 +379,6 @@ 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(
@@ -402,7 +391,6 @@ 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)),
@@ -432,11 +420,6 @@ 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/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index bad1d73233..a362341f2f 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -495,9 +495,7 @@ export function ChatWindow() {
// the draft for retry (ChatInput never cleared it).
let result;
try {
- result = await api.sendChatMessage(sessionId, finalContent, attachmentIds, {
- quickActionsEnabled: useChatStore.getState().quickActionsEnabled,
- });
+ result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);
} catch (err) {
apiLogger.error("sendChatMessage.error", { sessionId, err });
toast.error(t(($) => $.input.send_failed_toast));
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 3890f37c70..87530ad580 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -539,9 +539,7 @@ export function useChatController(opts?: { isActive?: boolean }) {
// the draft for retry (ChatInput never cleared it).
let result;
try {
- result = await api.sendChatMessage(sessionId, finalContent, attachmentIds, {
- quickActionsEnabled: useChatStore.getState().quickActionsEnabled,
- });
+ result = await api.sendChatMessage(sessionId, finalContent, attachmentIds);
} 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/locales/en/settings.json b/packages/views/locales/en/settings.json
index cff65b5b00..345d440efe 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -145,10 +145,7 @@
"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.",
- "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."
+ "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."
},
"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/settings.json b/packages/views/locales/ja/settings.json
index e0cdb67d78..77f614b22e 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -145,10 +145,7 @@
"chat": {
"floating_title": "フローティングウィンドウ",
"floating_label": "フローティングチャット",
- "floating_hint": "すべてのページの隅にフローティングチャットボタンを表示します。デフォルトはオフ——オンにするとどこからでもチャットを呼び出せます。オフのときは専用タブでのみ利用できます。",
- "quick_actions_title": "おすすめアクション",
- "quick_actions_label": "おすすめアクションを生成",
- "quick_actions_hint": "エージェントの返信ごとに、次の操作の候補を最大3件生成します。オフにすると、このデバイスから送信したメッセージでは生成されなくなります。既存の候補は引き続き表示されます。"
+ "floating_hint": "すべてのページの隅にフローティングチャットボタンを表示します。デフォルトはオフ——オンにするとどこからでもチャットを呼び出せます。オフのときは専用タブでのみ利用できます。"
},
"issue": {
"description": "各作成ダイアログのツールバーに常時表示するフィールドを選択します。非表示のフィールドは ⋯ メニューから引き続き使用でき、値がある間は自動的に表示されます。",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index dbdc875554..299745b22e 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -145,10 +145,7 @@
"chat": {
"floating_title": "플로팅 창",
"floating_label": "플로팅 채팅 창",
- "floating_hint": "모든 페이지 모서리에 플로팅 채팅 버튼을 표시합니다. 기본값은 꺼짐 — 켜면 어디서나 채팅을 불러올 수 있고, 꺼면 채팅은 이 탭에서만 사용할 수 있습니다.",
- "quick_actions_title": "추천 작업",
- "quick_actions_label": "추천 작업 생성",
- "quick_actions_hint": "에이전트가 답변할 때마다 후속 작업 추천을 최대 3개 생성합니다. 끄면 이 기기에서 보낸 메시지는 더 이상 생성을 트리거하지 않으며, 기존 추천은 계속 표시됩니다."
+ "floating_hint": "모든 페이지 모서리에 플로팅 채팅 버튼을 표시합니다. 기본값은 꺼짐 — 켜면 어디서나 채팅을 불러올 수 있고, 꺼면 채팅은 이 탭에서만 사용할 수 있습니다."
},
"issue": {
"description": "각 생성 방식의 툴바에 항상 표시할 필드를 선택합니다. 숨긴 필드는 ⋯ 메뉴에서 계속 사용할 수 있으며, 값이 있는 동안에는 자동으로 표시됩니다.",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 08a098963d..3985f807cb 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -145,10 +145,7 @@
"chat": {
"floating_title": "悬浮窗",
"floating_label": "悬浮聊天窗",
- "floating_hint": "在每个页面右下角显示悬浮聊天按钮。默认关闭——打开后可随处召唤聊天;关闭时,聊天只在此标签页中可用。",
- "quick_actions_title": "推荐操作",
- "quick_actions_label": "生成推荐操作",
- "quick_actions_hint": "智能体每次回复后自动生成最多三个后续操作建议。关闭后,本设备发送的消息不再触发生成;已有的建议仍会显示。"
+ "floating_hint": "在每个页面右下角显示悬浮聊天按钮。默认关闭——打开后可随处召唤聊天;关闭时,聊天只在此标签页中可用。"
},
"issue": {
"description": "选择各创建方式的工具栏中常驻显示的字段。隐藏的字段仍可从 ⋯ 菜单使用,有值时会自动显示。",
diff --git a/packages/views/settings/components/chat-tab.tsx b/packages/views/settings/components/chat-tab.tsx
index 24afb5d472..6ece764fae 100644
--- a/packages/views/settings/components/chat-tab.tsx
+++ b/packages/views/settings/components/chat-tab.tsx
@@ -22,8 +22,6 @@ 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)}>
@@ -46,25 +44,6 @@ 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 e809e9356f..ba6d348590 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -869,7 +869,6 @@ 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)
diff --git a/server/internal/daemon/chat_suggest.go b/server/internal/daemon/chat_suggest.go
deleted file mode 100644
index a5fe66190f..0000000000
--- a/server/internal/daemon/chat_suggest.go
+++ /dev/null
@@ -1,236 +0,0 @@
-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
deleted file mode 100644
index 1161aa9997..0000000000
--- a/server/internal/daemon/chat_suggest_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-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 0cbf7b7557..4ac3fb1d64 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, quickActionsPending bool, sessionRolloutMissing bool, retiredSessionID string) error {
+func (c *Client) CompleteTask(ctx context.Context, taskID, output, branchName, sessionID, workDir string, sessionRolloutMissing bool, retiredSessionID string) error {
body := map[string]any{"output": output}
if branchName != "" {
body["branch_name"] = branchName
@@ -381,9 +381,6 @@ 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
}
@@ -393,15 +390,6 @@ 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 dd7fc27472..360ae181af 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, false, "POISONED-S")
+ return c.CompleteTask(context.Background(), "task-1", "done", "", "", "/tmp/wd", 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, false, ""); err != nil {
+ if err := NewClient(srv.URL).CompleteTask(context.Background(), "task-1", "done", "", "sess-1", "/tmp/wd", 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 91dd548ae0..989decf770 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -156,10 +156,6 @@ 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.
@@ -263,10 +259,6 @@ 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
@@ -4128,21 +4120,10 @@ 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
@@ -4228,7 +4209,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.quickActionsPending, report.sessionRolloutMissing, report.retiredSessionID)
+ return d.client.CompleteTask(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir, 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:
@@ -4745,12 +4726,6 @@ 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
@@ -5406,13 +5381,19 @@ 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.
+ // A quick-actions refresh task from a server that predates server-side
+ // generation (MUL-5573). This daemon no longer has a suggestion pass to run
+ // it with, and it must NOT fall through to the ordinary chat path below:
+ // the task carries no user message, so the agent would answer a prompt
+ // nobody wrote and that server would persist the result as a real assistant
+ // reply. Complete it empty instead — the same shape the retired pass
+ // produced on this task, which that server writes no row for. The user's
+ // refresh spinner resolves via the client's own timeout.
if task.RegenerateQuickActionsFor != "" {
- return d.runChatQuickActionsRegenerate(ctx, task, backend, execOpts, provider, taskLog)
+ taskLog.Warn("refusing quick-actions refresh task from an older server; complete the daemon upgrade by updating the server",
+ "target_task", shortID(task.RegenerateQuickActionsFor),
+ )
+ return TaskResult{Status: "completed", Comment: "", WorkDir: env.WorkDir, EnvRoot: env.RootDir}, nil
}
taskLog.Debug("invoking backend",
@@ -5512,23 +5493,6 @@ 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 {
@@ -5607,16 +5571,12 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}, 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)
+ Status: "completed",
+ Comment: result.Output,
+ SessionID: result.SessionID,
+ WorkDir: env.WorkDir,
+ EnvRoot: env.RootDir,
+ Usage: usageEntries,
}
return taskResult, nil
case "timeout":
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index 38a91be089..cea701b7fb 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -90,12 +90,11 @@ 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>`
ChatIntro bool `json:"chat_intro,omitempty"` // true for the agent's proactive self-introduction chat (no user message); selects the self-introduction prompt in buildChatPrompt
+ RegenerateQuickActionsFor string `json:"regenerate_quick_actions_for,omitempty"` // set only by servers predating server-side quick-actions generation (MUL-5573). Read as a REFUSAL marker, never executed: see the guard in runTask
AutopilotRunID string `json:"autopilot_run_id,omitempty"` // non-empty for autopilot run_only tasks
AutopilotID string `json:"autopilot_id,omitempty"` // autopilot that spawned this run
AutopilotTitle string `json:"autopilot_title,omitempty"` // autopilot title used as task context
@@ -270,15 +269,6 @@ 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:"-"`
- // 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
+ RetiredSessionID string `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 e5573dca07..800a9e5d71 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -322,41 +322,39 @@ 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
- 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
+ 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
// 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 b4a15d3fb6..d8d4079848 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), false,
+ ctx, session, staleAgent, parseUUID(testUserID), "hello after the switch", nil, "member", parseUUID(testUserID),
)
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), false,
+ "sent while the rebind was still open", nil, "member", parseUUID(testUserID),
)
if err != nil {
results <- sendResult{err: err}
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index df028c48fa..2357b977b3 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -667,10 +667,6 @@ 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 {
@@ -792,8 +788,7 @@ 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.
- quickActionsDisabled := req.QuickActionsEnabled != nil && !*req.QuickActionsEnabled
- sent, err := h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID), quickActionsDisabled)
+ sent, err := h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID))
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to send chat message: "+err.Error())
return
@@ -909,14 +904,13 @@ type RegenerateChatQuickActionsRequest struct {
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.
+// RegenerateChatQuickActions re-runs the suggestion pass for a session's latest
+// assistant turn on explicit user request (the "refresh" button on the
+// quick-actions row, MUL-5149). Generation is server-side, so this spawns no
+// agent run; the refreshed pills arrive over the same chat:quick_actions
+// realtime path as the automatic pass.
func (h *Handler) RegenerateChatQuickActions(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
if !ok {
@@ -942,13 +936,11 @@ func (h *Handler) RegenerateChatQuickActions(w http.ResponseWriter, r *http.Requ
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.
+ // The refresh no longer runs the agent, but it is still a user-triggered
+ // spend against that agent's conversation, so it keeps clearing the same
+ // INVOKE gate as a send (MUL-4525) rather than the softer view gate in
+ // gateChatSessionForUser. Deliberately NOT relaxed as a side effect of
+ // moving generation server-side.
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)
@@ -965,7 +957,7 @@ func (h *Handler) RegenerateChatQuickActions(w http.ResponseWriter, r *http.Requ
return
}
- messageID, task, err := h.TaskService.RegenerateChatQuickActions(r.Context(), session, parseUUID(userID), expectedMessageID)
+ messageID, targetTask, err := h.TaskService.RegenerateChatQuickActions(r.Context(), session, expectedMessageID)
if err != nil {
switch {
case errors.Is(err, service.ErrChatQuickActionsStale):
@@ -974,26 +966,24 @@ func (h *Handler) RegenerateChatQuickActions(w http.ResponseWriter, r *http.Requ
// 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
+ // A turn is already running for this session; it is about to replace
+ // the reply these pills would hang on. 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")
+ case errors.Is(err, service.ErrChatQuickActionsUnavailable):
+ writeError(w, http.StatusServiceUnavailable, "suggestions are not available on this deployment")
default:
writeError(w, http.StatusInternalServerError, "failed to regenerate quick actions")
}
return
}
+ // Detached like the automatic pass: answer 202 now, deliver the refreshed
+ // pills over chat:quick_actions.
+ h.TaskService.GenerateChatQuickActionsAsync(targetTask, service.ChatQuickActionsRefresh)
writeJSON(w, http.StatusAccepted, RegenerateChatQuickActionsResponse{
MessageID: uuidToString(messageID),
- TaskID: uuidToString(task.ID),
})
}
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
index 5b1c475e3b..2f4b4bec1d 100644
--- a/server/internal/handler/chat_input_ownership_test.go
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "strings"
"testing"
"github.com/multica-ai/multica/server/internal/service"
@@ -41,7 +42,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), false)
+ res, err := testHandler.TaskService.SendDirectChatMessage(ctx, sess, ag, parseUUID(testUserID), content, nil, "member", parseUUID(testUserID))
if err != nil {
t.Fatalf("SendDirectChatMessage: %v", err)
}
@@ -501,18 +502,22 @@ func TestCompleteTask_ChatQuickActions(t *testing.T) {
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)
}
+ // The footer's actions are DISCARDED, not persisted: suggestions come from
+ // the server-side pass now. Honouring an in-band footer would pin a
+ // pre-upgrade provider session to the retired, lower-quality suggestions and
+ // suppress the pass that replaces them.
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)
+ if len(actions) != 0 {
+ t.Fatalf("in-band footer actions must not be persisted, got %+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).
+ // visible no_response fallback instead (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```"
@@ -546,7 +551,7 @@ func TestCompleteTask_ChatQuickActionsSupplement(t *testing.T) {
output := "Main reply.\n\n```quick-actions\n" +
`[{"label":"From footer","prompt":"in-band fallback"}]` + "\n```"
- req := TaskCompleteRequest{Output: output, QuickActionsPending: true}
+ req := TaskCompleteRequest{Output: output}
result, err := json.Marshal(req)
if err != nil {
t.Fatalf("marshal complete request: %v", err)
@@ -574,7 +579,7 @@ func TestCompleteTask_ChatQuickActionsSupplement(t *testing.T) {
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)
+ t.Fatalf("supplement must attach the pass's actions, got %+v", actions)
}
// An empty supplement must not clobber existing actions (it only resolves
@@ -592,39 +597,94 @@ func TestCompleteTask_ChatQuickActionsSupplement(t *testing.T) {
}
}
-func TestDirectChat_QuickActionsOptOutStampsTask(t *testing.T) {
+// stubChatQuickActionsLLM is an enabled ChatQuickActionsLLM that never dials an
+// upstream, so the refresh gates below can be exercised on a deployment-shaped
+// TaskService (RegenerateChatQuickActions refuses outright when the LLM layer
+// is unconfigured).
+type stubChatQuickActionsLLM struct {
+ // lastPrompt records the rendered conversation the pass was given, so a
+ // test can assert WHICH turn the suggestions were built from.
+ lastPrompt *string
+}
+
+func (stubChatQuickActionsLLM) Enabled() bool { return true }
+
+func (s stubChatQuickActionsLLM) GenerateJSON(_ context.Context, _, _, userPrompt string, _ float64, _ int64) (string, error) {
+ if s.lastPrompt != nil {
+ *s.lastPrompt = userPrompt
+ }
+ return `{"actions":[{"label":"Next","prompt":"do the next thing","primary":true}]}`, nil
+}
+
+// TestChatQuickActions_ContextAnchorsOnTargetTurn pins the anchoring contract:
+// generation runs on a detached goroutine, so by the time it executes the
+// session may already carry a newer turn. The context it builds must end at the
+// assistant turn the pills are written to — not at whatever is newest when the
+// read happens.
+//
+// Without the anchor, a user who types a follow-up in the second after the
+// reply lands leaves the window ending on a user row with no reply to build on,
+// and that turn silently never gets pills.
+func TestChatQuickActions_ContextAnchorsOnTargetTurn(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))
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "quick-actions anchor")
+
+ taskID := sendDirectChat(t, ctx, agentID, sessionID, "first question")
+ markTaskRunning(t, ctx, taskID)
+ task, err := testHandler.TaskService.CompleteTask(
+ ctx, parseUUID(taskID), completeResult(t, "ANCHOR REPLY"), "", "", false, "")
if err != nil {
- t.Fatalf("load chat session: %v", err)
+ t.Fatalf("complete turn 1: %v", err)
}
- ag, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
- if err != nil {
- t.Fatalf("load agent: %v", err)
+
+ // The race: a newer user message lands before the pass reads the session.
+ sendDirectChat(t, ctx, agentID, sessionID, "NEWER USER MESSAGE")
+
+ var prompt string
+ prev := testHandler.TaskService.QuickActions
+ testHandler.TaskService.QuickActions = stubChatQuickActionsLLM{lastPrompt: &prompt}
+ defer func() { testHandler.TaskService.QuickActions = prev }()
+
+ if err := testHandler.TaskService.GenerateChatQuickActionsForTask(
+ ctx, *task, service.ChatQuickActionsAutomatic); err != nil {
+ t.Fatalf("generate quick actions: %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 !strings.Contains(prompt, "ANCHOR REPLY") {
+ t.Fatalf("context must end at the target reply, got:\n%s", prompt)
}
- if !optedOut.Task.QuickActionsDisabled {
- t.Fatal("opt-out send must stamp quick_actions_disabled on the task")
+ if strings.Contains(prompt, "NEWER USER MESSAGE") {
+ t.Fatalf("context must exclude turns newer than the target, got:\n%s", prompt)
}
- // 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)
+ // And the pills land on the target turn, not the newer one.
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("expected one assistant row, got %d", len(rows))
+ }
+ var actions []protocol.ChatQuickAction
+ if err := json.Unmarshal(rows[0].QuickActions, &actions); err != nil {
+ t.Fatalf("decode quick actions: %v", err)
}
- if normal.Task.QuickActionsDisabled {
- t.Fatal("default send must leave quick_actions_disabled false")
+ if len(actions) != 1 || actions[0].Label != "Next" {
+ t.Fatalf("target turn quick actions = %+v", actions)
}
}
+// installStubQuickActions enables suggestion generation and returns the undo.
+// Scoped tightly around the synchronous RegenerateChatQuickActions calls rather
+// than installed for a whole test: CompleteTask starts a background pass when
+// the feature is on, and a goroutine writing quick_actions mid-test would race
+// these assertions.
+func installStubQuickActions() func() {
+ prev := testHandler.TaskService.QuickActions
+ testHandler.TaskService.QuickActions = stubChatQuickActionsLLM{}
+ return func() { testHandler.TaskService.QuickActions = prev }
+}
+
// 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.
@@ -655,21 +715,15 @@ func TestRegenerateChatQuickActions_StaleTargetRejected(t *testing.T) {
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)
+ restore := installStubQuickActions()
+ target, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, m1)
+ restore()
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")
@@ -688,10 +742,12 @@ func TestRegenerateChatQuickActions_StaleTargetRejected(t *testing.T) {
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) {
+ restore = installStubQuickActions()
+ defer restore()
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, 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 {
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, m2); err != nil {
t.Fatalf("regenerate new latest turn: %v", err)
}
}
@@ -730,48 +786,13 @@ func TestRegenerateChatQuickActions_ActiveTurnRejected(t *testing.T) {
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) {
+ restore := installStubQuickActions()
+ defer restore()
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, 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
@@ -811,7 +832,9 @@ func TestRegenerateChatQuickActions_DeferredActiveTurnRejected(t *testing.T) {
t.Fatalf("defer turn 2: %v", err)
}
- if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, parseUUID(testUserID), m1); !errors.Is(err, service.ErrChatQuickActionsBusy) {
+ restore := installStubQuickActions()
+ defer restore()
+ if _, _, err := testHandler.TaskService.RegenerateChatQuickActions(ctx, session, 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 cd0f07ca0b..44d0460a54 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2053,13 +2053,6 @@ 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)
@@ -2923,10 +2916,6 @@ 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.
@@ -2938,35 +2927,6 @@ 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/handler/handler.go b/server/internal/handler/handler.go
index 0d87ea7e35..ca5a27e141 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -313,8 +313,18 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
daemonWorkspaceRefresh = daemonHub
}
+ llmClient := llm.New(llm.Config{
+ APIKey: cfg.LLMAPIKey,
+ BaseURL: cfg.LLMBaseURL,
+ DefaultModel: cfg.LLMDefaultModel,
+ })
+
taskSvc := service.NewTaskService(queries, txStarter, hub, bus, daemonHub)
taskSvc.Analytics = analyticsClient
+ // Chat follow-up suggestions run through the same internal LLM layer that
+ // backs auto-titling. A deployment with no MULTICA_LLM_* configuration gets
+ // a disabled client, which turns the feature off rather than failing.
+ taskSvc.QuickActions = llmClient
h := &Handler{
Queries: queries,
DB: executor,
@@ -345,11 +355,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
BaseURL: cfg.CloudRuntimeFleetURL,
Timeout: cfg.CloudRuntimeFleetTimeout,
}),
- LLM: llm.New(llm.Config{
- APIKey: cfg.LLMAPIKey,
- BaseURL: cfg.LLMBaseURL,
- DefaultModel: cfg.LLMDefaultModel,
- }),
+ LLM: llmClient,
cfg: cfg,
}
h.WebhookDeliveryWorker = NewWebhookDeliveryWorker(h)
diff --git a/server/internal/service/chat_quick_actions.go b/server/internal/service/chat_quick_actions.go
index f31e4c57dd..c780464831 100644
--- a/server/internal/service/chat_quick_actions.go
+++ b/server/internal/service/chat_quick_actions.go
@@ -23,21 +23,22 @@ const (
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.
+// parseChatQuickActionsOutput parses the suggestion pass's raw output into
+// sanitized actions. The pass is instructed to emit {"actions":[...]}, but this
+// parser is deliberately lenient — models wrap output in code fences, drop the
+// wrapper, 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
+ // Attempt order narrows from strict to desperate: the object the pass was
+ // asked for (or a bare array), 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 {
@@ -77,6 +78,16 @@ func unmarshalChatQuickActions(raw string) ([]protocol.ChatQuickAction, bool) {
if raw == "" {
return nil, false
}
+ // The pass asks for {"actions":[...]} because response_format=json_object
+ // requires a top-level object. A bare array is still accepted: the bracket
+ // fallback below extracts one out of prose, and a model that drops the
+ // wrapper should not cost the user their suggestions.
+ var wrapper struct {
+ Actions []protocol.ChatQuickAction `json:"actions"`
+ }
+ if err := json.Unmarshal([]byte(raw), &wrapper); err == nil && wrapper.Actions != nil {
+ return sanitizeChatQuickActions(wrapper.Actions), true
+ }
var candidates []protocol.ChatQuickAction
if err := json.Unmarshal([]byte(raw), &candidates); err != nil {
return nil, false
@@ -89,11 +100,11 @@ func unmarshalChatQuickActions(raw string) ([]protocol.ChatQuickAction, bool) {
// 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.
+// Suggestions are generated server-side now, so this is no longer a source of
+// actions — but the split stays as a defensive stripper. Provider sessions
+// created before the retirement carry the footer syntax in their own history,
+// so agents keep emitting it for a while; without this the raw fence would land
+// in a stored transcript.
func splitChatQuickActions(output string) (string, []protocol.ChatQuickAction) {
normalized := strings.ReplaceAll(output, "\r\n", "\n")
trimmed := strings.TrimRight(normalized, " \t\n")
@@ -182,27 +193,42 @@ func truncateChatQuickAction(value string, maxRunes int) string {
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 {
+// chatQuickActionsEligible decides whether a completed turn gets a suggestion
+// pass — and therefore whether the chat:done broadcast should tell clients to
+// expect a chat:quick_actions supplement.
+//
+// The decision is the server's own: suggestions are generated here now, so
+// nothing the daemon reports can grant or withhold them.
+func (s *TaskService) chatQuickActionsEligible(ctx context.Context, task db.AgentTaskQueue, msg *db.ChatMessage) bool {
+ if s.QuickActions == nil || !s.QuickActions.Enabled() {
+ return false
+ }
+ if !task.ChatSessionID.Valid {
+ return false
+ }
+ // Only an ordinary reply can seed suggestions: a no_response outcome has
+ // nothing to build on, and an attachment-only reply has no text to anchor in.
+ if msg == nil || msg.MessageKind != protocol.ChatMessageKindMessage {
return false
}
- if msg.MessageKind != protocol.ChatMessageKindMessage {
+ if strings.TrimSpace(msg.Content) == "" {
return false
}
- var existing []protocol.ChatQuickAction
- _ = json.Unmarshal(msg.QuickActions, &existing)
- return len(existing) == 0
+ // Channel-backed sessions (Slack / Lark) have no pill surface. Same
+ // discriminator writeChatCompletionOutcome uses: the immutable
+ // channel_ingested stamp on the turn's owned input batch. A NULL owner is
+ // an agent-initiated intro turn, which does render in Chat.
+ if task.ChatInputTaskID.Valid {
+ channelIngested, err := s.Queries.TaskHasChannelIngestedMessages(ctx, task.ChatInputTaskID)
+ if err != nil || channelIngested {
+ return false
+ }
+ }
+ return true
}
-// SupplementChatQuickActions attaches the daemon suggestion pass's output to
-// the completed turn's assistant message and broadcasts chat:quick_actions.
+// SupplementChatQuickActions attaches a suggestion pass's raw 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)
diff --git a/server/internal/service/chat_quick_actions_generate.go b/server/internal/service/chat_quick_actions_generate.go
new file mode 100644
index 0000000000..d3d3618d7a
--- /dev/null
+++ b/server/internal/service/chat_quick_actions_generate.go
@@ -0,0 +1,436 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "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"
+)
+
+// Budgets for one suggestion pass. The whole call is a nicety attached to a
+// reply the user already has, so it is bounded tightly: a slow pass is worse
+// than no pass, because the client holds a skeleton placeholder until it
+// resolves (QUICK_ACTIONS_PENDING_TIMEOUT_MS on the frontend is sized from
+// chatQuickActionsTimeout plus room for the write and the broadcast).
+const (
+ chatQuickActionsTimeout = 8 * time.Second
+ chatQuickActionsTemperature = 0.3
+ // Output cap. Three actions at the sanitizer's ceilings (80-rune label,
+ // 500-rune prompt) fit comfortably; the headroom exists so a verbose model
+ // is truncated by sanitizeChatQuickActions rather than by the upstream
+ // mid-JSON, which would fail the parse outright.
+ chatQuickActionsMaxTokens = 800
+)
+
+// Context window for the pass. Suggestions are about where the conversation
+// goes next, so only the tail matters — older turns cost tokens and latency
+// without changing the answer.
+const (
+ chatQuickActionsContextMessages = 6
+ // The latest assistant reply gets the largest share: it is what the
+ // suggestions must be anchored in.
+ chatQuickActionsLatestBudget = 3000
+ chatQuickActionsOlderBudget = 800
+ // Head/tail split applied to an over-long latest reply. The tail carries
+ // the conclusion and the proposed next steps — exactly the material
+ // suggestions are built from — so keeping only the head would strip the
+ // most useful part.
+ chatQuickActionsHeadBudget = 2000
+ chatQuickActionsTailBudget = 1000
+ // Cap on how many previously-suggested labels are replayed to the model.
+ chatQuickActionsPreviousMax = 6
+)
+
+// chatQuickActionsMaxConcurrent bounds how many suggestion passes may be in
+// flight process-wide. Generation is spawned from request handling with no
+// queue behind it, so without a ceiling a burst of chat traffic (or a client
+// looping the refresh endpoint) scales goroutines, upstream connections, and
+// model spend without limit. Passes over the ceiling are dropped, not queued:
+// a suggestion that arrives after the client's pending window has expired is
+// worth nothing, so shedding beats backlogging.
+const chatQuickActionsMaxConcurrent = 16
+
+// ChatQuickActionsOrigin says which caller asked for a pass. It decides how a
+// failure is reported: an explicit refresh is a user action that must surface
+// its own failure, while the automatic pass is best-effort background work the
+// user never asked for and must fail silently (protocol.ChatQuickActionsPayload
+// documents Failed as false for the automatic pass, and the client turns every
+// failed=true into a "couldn't refresh" toast).
+type ChatQuickActionsOrigin int
+
+const (
+ ChatQuickActionsAutomatic ChatQuickActionsOrigin = iota
+ ChatQuickActionsRefresh
+)
+
+// ChatQuickActionsLLM is the seam TaskService uses to generate follow-up
+// suggestions, satisfied by *llm.Client. It is an interface (not the concrete
+// client) so tests can drive the whole path — prompt rendering, parsing,
+// persistence, broadcast — without an HTTP upstream, mirroring how
+// ComposioOverlayBuilder and TaskWakeupNotifier are injected.
+//
+// A nil ChatQuickActionsLLM, or one whose Enabled() is false, disables the
+// feature entirely: no pending marker is raised and no pills are generated.
+// That is the expected state for a self-hosted deployment with no
+// MULTICA_LLM_API_KEY / MULTICA_LLM_BASE_URL, and matches how chat auto-titling
+// already degrades.
+type ChatQuickActionsLLM interface {
+ Enabled() bool
+ GenerateJSON(ctx context.Context, model, systemPrompt, userPrompt string, temperature float64, maxTokens int64) (string, error)
+}
+
+// chatQuickActionsSystemPrompt is the entire instruction set for the pass. It
+// is a system prompt (stable across calls, so upstream prompt caching applies);
+// the per-call conversation goes in the user message.
+//
+// The rules are deliberately prescriptive about WHO the suggestions are for.
+// The retired daemon pass ran as a resumed turn inside the agent's own session,
+// so it inherited the Multica runtime brief's identity and drifted toward
+// agent-operations actions; this pass has no such context and must be told the
+// frame explicitly.
+//
+// The word "JSON" must stay in this text: response_format=json_object is
+// rejected upstream without it.
+const chatQuickActionsSystemPrompt = `You generate follow-up suggestions for a chat between a user and an AI agent.
+Your output is rendered as three clickable buttons under the agent's latest
+reply. Clicking one sends that suggestion's "prompt" to the same agent as the
+user's next message.
+
+You write FOR THE USER, not for the agent. Every suggestion must be something
+the user would plausibly want to ask or do next — never a task the agent should
+perform on its own, never a status report, never a question addressed to the user.
+
+Quality bar:
+- Return exactly 3 suggestions.
+- Every suggestion must be anchored in something concrete the latest agent reply
+ actually mentioned — a file, a name, an option it listed, a caveat it raised,
+ a next step it proposed. Never invent a topic the conversation did not touch.
+- Never suggest something the agent already did in this turn.
+- Never repeat or paraphrase anything under ALREADY SUGGESTED.
+- Make the three distinct from each other: different intents, not three
+ rewordings of the same request.
+
+Field rules:
+- "label": the button text. A short verb phrase — at most 6 words in English, at
+ most 12 characters in Chinese. No trailing punctuation, no quotes, no emoji.
+ It is a button, not a sentence.
+- "prompt": the full message sent on the user's behalf. First person, the user's
+ own voice, and SELF-CONTAINED — the agent never sees the label, so the prompt
+ must carry every detail itself. One or two sentences.
+- "primary": true on exactly one suggestion, the single most likely next step.
+ false on all others.
+
+Write both fields in the same language the USER has been writing in, regardless
+of what language the agent replied in.
+
+Output JSON only, exactly this shape:
+{"actions":[{"label":"...","prompt":"...","primary":true}]}
+No prose, no markdown, no code fences.`
+
+// GenerateChatQuickActionsForTask runs one suggestion pass for a completed chat
+// turn and attaches the result to that turn's assistant row, broadcasting
+// chat:quick_actions. It is the synchronous core shared by the automatic
+// post-completion pass and the explicit refresh, and is safe to call directly
+// from tests.
+//
+// origin decides failure reporting: a refresh surfaces failed=true so the user
+// who pressed the button learns it did not work, while the automatic pass
+// resolves the placeholder quietly. Reporting an automatic failure would pop a
+// "couldn't refresh" toast for an action the user never took.
+func (s *TaskService) GenerateChatQuickActionsForTask(ctx context.Context, task db.AgentTaskQueue, origin ChatQuickActionsOrigin) error {
+ if s.QuickActions == nil || !s.QuickActions.Enabled() {
+ return nil
+ }
+ if !task.ChatSessionID.Valid {
+ return nil
+ }
+
+ // Resolve the target turn FIRST and anchor everything to it. The context
+ // window, the write, and the broadcast must all describe the same assistant
+ // message: this runs on a detached goroutine, so by the time it executes the
+ // session may already have moved on by a full turn.
+ target, err := s.Queries.GetChatMessageByTaskAssistant(ctx, task.ID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ // No assistant row to attach to (no_response, channel empty-drop).
+ // No client is waiting either — the pending flag is only raised for
+ // a written ordinary message.
+ return nil
+ }
+ return fmt.Errorf("load chat quick actions target: %w", err)
+ }
+ if target.MessageKind != protocol.ChatMessageKindMessage || strings.TrimSpace(target.Content) == "" {
+ // Nothing to build suggestions on. Resolve the placeholder rather than
+ // leaving the client's skeleton to time out.
+ return s.SupplementChatQuickActions(ctx, task, "", false)
+ }
+
+ prompt, err := s.buildChatQuickActionsPrompt(ctx, target)
+ if err != nil {
+ return err
+ }
+
+ raw, err := s.QuickActions.GenerateJSON(ctx,
+ "", // deployment default: MULTICA_LLM_DEFAULT_MODEL, else llm.FallbackModel
+ chatQuickActionsSystemPrompt,
+ prompt,
+ chatQuickActionsTemperature,
+ chatQuickActionsMaxTokens,
+ )
+ if err != nil {
+ // Resolve the placeholder either way; only an explicit refresh reports
+ // the failure to the user (see origin).
+ if suppErr := s.SupplementChatQuickActions(ctx, task, "", origin == ChatQuickActionsRefresh); suppErr != nil {
+ slog.Warn("chat quick actions failure broadcast failed",
+ "task_id", util.UUIDToString(task.ID),
+ "error", suppErr,
+ )
+ }
+ return fmt.Errorf("generate chat quick actions: %w", err)
+ }
+ return s.SupplementChatQuickActions(ctx, task, raw, false)
+}
+
+// GenerateChatQuickActionsAsync runs GenerateChatQuickActionsForTask on a
+// detached goroutine and returns immediately. Used on the completion path,
+// where the user's reply is already delivered and must never wait on this, and
+// on the refresh path, which answers 202 before the pass runs.
+//
+// Two admission gates before anything is spawned:
+//
+// - One pass per chat session. Concurrent passes on one session would race to
+// write the same row and burn duplicate spend for a single visible outcome
+// — two refreshes of one turn, or a refresh overlapping the automatic pass.
+// - A process-wide ceiling (chatQuickActionsMaxConcurrent).
+//
+// A rejected pass still resolves the client's placeholder, so a skeleton never
+// hangs waiting for work that was never started.
+//
+// The goroutine owns its own context: the caller's is typically an HTTP request
+// context that is cancelled the moment the completion callback returns.
+func (s *TaskService) GenerateChatQuickActionsAsync(task db.AgentTaskQueue, origin ChatQuickActionsOrigin) {
+ if s.QuickActions == nil || !s.QuickActions.Enabled() {
+ return
+ }
+ sessionKey := util.UUIDToString(task.ChatSessionID)
+ if sessionKey == "" {
+ return
+ }
+ if _, inFlight := s.quickActionsInFlight.LoadOrStore(sessionKey, struct{}{}); inFlight {
+ slog.Info("chat quick actions pass skipped: one already running for this session",
+ "chat_session_id", sessionKey, "task_id", util.UUIDToString(task.ID))
+ s.resolveChatQuickActionsPlaceholder(task)
+ return
+ }
+ if s.quickActionsRunning.Add(1) > chatQuickActionsMaxConcurrent {
+ s.quickActionsRunning.Add(-1)
+ s.quickActionsInFlight.Delete(sessionKey)
+ slog.Warn("chat quick actions pass shed: process-wide concurrency ceiling reached",
+ "ceiling", chatQuickActionsMaxConcurrent, "task_id", util.UUIDToString(task.ID))
+ s.resolveChatQuickActionsPlaceholder(task)
+ return
+ }
+
+ go func() {
+ defer func() {
+ s.quickActionsRunning.Add(-1)
+ s.quickActionsInFlight.Delete(sessionKey)
+ }()
+ // Panic containment: this goroutine is detached from the HTTP request,
+ // so chi's Recoverer middleware is not in the call stack and a panic
+ // here would take down the whole server process. Suggestions are a
+ // nicety — swallow, log, and leave the turn's pills as they are.
+ defer func() {
+ if rec := recover(); rec != nil {
+ slog.Error("chat quick actions generation panicked",
+ "task_id", util.UUIDToString(task.ID),
+ "panic", rec,
+ )
+ }
+ }()
+
+ ctx, cancel := context.WithTimeout(context.Background(), chatQuickActionsTimeout)
+ defer cancel()
+
+ if err := s.GenerateChatQuickActionsForTask(ctx, task, origin); err != nil {
+ slog.Warn("chat quick actions generation failed",
+ "task_id", util.UUIDToString(task.ID),
+ "chat_session_id", sessionKey,
+ "error", err,
+ )
+ }
+ }()
+}
+
+// chatQuickActionsInFlight reports whether a pass is already running for this
+// session. The refresh endpoint checks it so a duplicate request is refused
+// with a 409 the client can act on, instead of being accepted and silently
+// dropped by the admission gate in GenerateChatQuickActionsAsync.
+func (s *TaskService) chatQuickActionsInFlight(sessionID pgtype.UUID) bool {
+ _, running := s.quickActionsInFlight.Load(util.UUIDToString(sessionID))
+ return running
+}
+
+// resolveChatQuickActionsPlaceholder ends a client's pending skeleton without
+// generating anything, rebroadcasting the turn's current pills. Used when a
+// pass is refused admission — the placeholder was already raised by chat:done,
+// and leaving it to expire would show a spinner for work that never started.
+func (s *TaskService) resolveChatQuickActionsPlaceholder(task db.AgentTaskQueue) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if err := s.SupplementChatQuickActions(ctx, task, "", false); err != nil {
+ slog.Warn("chat quick actions placeholder resolve failed",
+ "task_id", util.UUIDToString(task.ID), "error", err)
+ }
+}
+
+// buildChatQuickActionsPrompt renders the pass's user message from the window
+// of conversation ENDING AT target, which is the assistant turn the suggestions
+// will be attached to.
+//
+// Anchoring on the target (rather than re-reading the session's newest
+// messages) is what keeps an async pass correct: a turn that lands between the
+// completion callback and this read would otherwise supply the context while
+// the result is still written to the older turn, and a newly-sent user message
+// would leave the window ending on a user row with no reply to build on.
+func (s *TaskService) buildChatQuickActionsPrompt(ctx context.Context, target db.ChatMessage) (string, error) {
+ // Strictly older than target, newest-first; reversed below. Over-fetch so
+ // dropped rows (no_response, failures) don't shrink the window below the
+ // intended turn count.
+ rows, err := s.Queries.ListChatMessagesPage(ctx, db.ListChatMessagesPageParams{
+ ChatSessionID: target.ChatSessionID,
+ Limit: chatQuickActionsContextMessages * 2,
+ BeforeCreatedAt: target.CreatedAt,
+ BeforeID: target.ID,
+ })
+ if err != nil {
+ return "", fmt.Errorf("load chat messages for quick actions: %w", err)
+ }
+
+ msgs := make([]db.ChatMessage, 0, len(rows)+1)
+ for i := len(rows) - 1; i >= 0; i-- {
+ msg := rows[i]
+ // Only ordinary turns carry usable text. A no_response row holds an
+ // English placeholder body and a failure row holds an error, neither of
+ // which describes what the conversation is about.
+ if msg.MessageKind != protocol.ChatMessageKindMessage {
+ continue
+ }
+ if strings.TrimSpace(msg.Content) == "" {
+ continue
+ }
+ msgs = append(msgs, msg)
+ }
+ if len(msgs) > chatQuickActionsContextMessages-1 {
+ msgs = msgs[len(msgs)-(chatQuickActionsContextMessages-1):]
+ }
+ msgs = append(msgs, target)
+ return renderChatQuickActionsContext(msgs, collectPreviousChatQuickActions(msgs)), nil
+}
+
+// collectPreviousChatQuickActions gathers the labels already offered in this
+// window so the prompt can forbid repeating them. The newest assistant row is
+// included: on an explicit refresh it holds the pills the user is asking to
+// replace, and offering the same three back is the one outcome a refresh must
+// never produce.
+func collectPreviousChatQuickActions(msgs []db.ChatMessage) []string {
+ labels := make([]string, 0, chatQuickActionsPreviousMax)
+ seen := make(map[string]struct{}, chatQuickActionsPreviousMax)
+ // Newest first, so the most recent suggestions survive the cap.
+ for i := len(msgs) - 1; i >= 0; i-- {
+ if len(msgs[i].QuickActions) == 0 {
+ continue
+ }
+ var actions []protocol.ChatQuickAction
+ if err := json.Unmarshal(msgs[i].QuickActions, &actions); err != nil {
+ continue
+ }
+ for _, action := range actions {
+ label := strings.TrimSpace(action.Label)
+ if label == "" {
+ continue
+ }
+ key := strings.ToLower(label)
+ if _, dup := seen[key]; dup {
+ continue
+ }
+ seen[key] = struct{}{}
+ labels = append(labels, label)
+ if len(labels) == chatQuickActionsPreviousMax {
+ return labels
+ }
+ }
+ }
+ return labels
+}
+
+// renderChatQuickActionsContext formats the conversation window and the
+// already-suggested labels into the pass's user message. Pure, so the
+// truncation rules are unit-testable without a database.
+//
+// msgs is oldest-first and its last entry must be the assistant reply the
+// suggestions are for.
+func renderChatQuickActionsContext(msgs []db.ChatMessage, previous []string) string {
+ var b strings.Builder
+ b.WriteString("CONVERSATION (oldest first):\n")
+ for i, msg := range msgs {
+ speaker := "agent"
+ if msg.Role == "user" {
+ speaker = "user"
+ }
+ content := strings.TrimSpace(msg.Content)
+ if i == len(msgs)-1 {
+ content = truncateChatQuickActionsLatest(content)
+ } else {
+ content = truncateChatQuickActionsRunes(content, chatQuickActionsOlderBudget)
+ }
+ fmt.Fprintf(&b, "[%s]: %s\n", speaker, content)
+ }
+
+ b.WriteString("\nALREADY SUGGESTED (do not repeat or paraphrase):\n")
+ if len(previous) == 0 {
+ b.WriteString("(none)\n")
+ } else {
+ for _, label := range previous {
+ fmt.Fprintf(&b, "- %s\n", label)
+ }
+ }
+
+ b.WriteString("\nProduce the follow-up suggestions for the latest agent reply.")
+ return b.String()
+}
+
+// truncateChatQuickActionsLatest shortens the anchor reply while keeping both
+// ends. The head establishes what the reply is about and the tail holds its
+// conclusion and proposed next steps; a plain head-only cut on a long reply
+// discards exactly the material the suggestions should be built from.
+func truncateChatQuickActionsLatest(content string) string {
+ runes := []rune(content)
+ if len(runes) <= chatQuickActionsLatestBudget {
+ return content
+ }
+ head := string(runes[:chatQuickActionsHeadBudget])
+ tail := string(runes[len(runes)-chatQuickActionsTailBudget:])
+ return head + "\n…[truncated]…\n" + tail
+}
+
+// truncateChatQuickActionsRunes cuts an older message to a rune budget. Head
+// only: for context turns, what the message opened with is enough to follow the
+// thread.
+func truncateChatQuickActionsRunes(content string, maxRunes int) string {
+ runes := []rune(content)
+ if len(runes) <= maxRunes {
+ return content
+ }
+ return string(runes[:maxRunes]) + "…"
+}
diff --git a/server/internal/service/chat_quick_actions_generate_test.go b/server/internal/service/chat_quick_actions_generate_test.go
new file mode 100644
index 0000000000..7a196e4cca
--- /dev/null
+++ b/server/internal/service/chat_quick_actions_generate_test.go
@@ -0,0 +1,189 @@
+package service
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func chatMsg(role, content string, actions ...protocol.ChatQuickAction) db.ChatMessage {
+ msg := db.ChatMessage{
+ Role: role,
+ Content: content,
+ MessageKind: protocol.ChatMessageKindMessage,
+ }
+ if len(actions) > 0 {
+ encoded, err := json.Marshal(actions)
+ if err != nil {
+ panic(err)
+ }
+ msg.QuickActions = encoded
+ }
+ return msg
+}
+
+func TestRenderChatQuickActionsContextLabelsSpeakersAndClosesWithTheTask(t *testing.T) {
+ out := renderChatQuickActionsContext([]db.ChatMessage{
+ chatMsg("user", "why is this slow"),
+ chatMsg("assistant", "because it spawns a CLI per turn"),
+ }, nil)
+
+ if !strings.Contains(out, "[user]: why is this slow") {
+ t.Fatalf("user turn missing or mislabeled:\n%s", out)
+ }
+ // The role label must be "agent", not the DB's "assistant": the prompt
+ // talks about the agent's reply throughout.
+ if !strings.Contains(out, "[agent]: because it spawns a CLI per turn") {
+ t.Fatalf("assistant turn must render as [agent]:\n%s", out)
+ }
+ if !strings.Contains(out, "ALREADY SUGGESTED (do not repeat or paraphrase):\n(none)") {
+ t.Fatalf("empty previous-suggestion section must read (none):\n%s", out)
+ }
+ if !strings.HasSuffix(out, "Produce the follow-up suggestions for the latest agent reply.") {
+ t.Fatalf("prompt must end with the instruction:\n%s", out)
+ }
+}
+
+func TestRenderChatQuickActionsContextListsPreviousLabels(t *testing.T) {
+ out := renderChatQuickActionsContext(
+ []db.ChatMessage{chatMsg("assistant", "done")},
+ []string{"看下 diff", "老 daemon 的影响"},
+ )
+ if !strings.Contains(out, "- 看下 diff\n- 老 daemon 的影响") {
+ t.Fatalf("previous labels must be listed verbatim:\n%s", out)
+ }
+ if strings.Contains(out, "(none)") {
+ t.Fatalf("(none) must not appear when labels exist:\n%s", out)
+ }
+}
+
+// The anchor reply keeps BOTH ends when it is too long: the tail carries the
+// conclusion and proposed next steps, which is exactly the material the
+// suggestions are built from, so a head-only cut would strip the most useful
+// part of the input.
+func TestRenderChatQuickActionsContextKeepsHeadAndTailOfLongLatestReply(t *testing.T) {
+ head := strings.Repeat("H", 500)
+ middle := strings.Repeat("M", chatQuickActionsLatestBudget)
+ tail := strings.Repeat("T", 500)
+ out := renderChatQuickActionsContext([]db.ChatMessage{
+ chatMsg("assistant", head+middle+tail),
+ }, nil)
+
+ if !strings.Contains(out, head) {
+ t.Fatal("truncated latest reply must keep its head")
+ }
+ if !strings.Contains(out, tail) {
+ t.Fatal("truncated latest reply must keep its tail")
+ }
+ if !strings.Contains(out, "…[truncated]…") {
+ t.Fatal("truncation must be marked so the model does not read across the cut")
+ }
+ if strings.Contains(out, middle) {
+ t.Fatal("the middle of an over-long reply must be dropped")
+ }
+}
+
+func TestRenderChatQuickActionsContextLeavesShortLatestReplyIntact(t *testing.T) {
+ reply := strings.Repeat("x", chatQuickActionsLatestBudget)
+ out := renderChatQuickActionsContext([]db.ChatMessage{chatMsg("assistant", reply)}, nil)
+ if strings.Contains(out, "…[truncated]…") {
+ t.Fatal("a reply exactly at the budget must not be truncated")
+ }
+}
+
+func TestRenderChatQuickActionsContextTruncatesOlderMessagesToTheSmallerBudget(t *testing.T) {
+ long := strings.Repeat("y", chatQuickActionsOlderBudget+200)
+ out := renderChatQuickActionsContext([]db.ChatMessage{
+ chatMsg("user", long),
+ chatMsg("assistant", "short reply"),
+ }, nil)
+
+ if strings.Contains(out, long) {
+ t.Fatal("an older message over budget must be cut")
+ }
+ if !strings.Contains(out, strings.Repeat("y", chatQuickActionsOlderBudget)+"…") {
+ t.Fatalf("older messages are head-truncated with an ellipsis:\n%s", out)
+ }
+}
+
+func TestCollectPreviousChatQuickActionsPrefersNewestAndDedupes(t *testing.T) {
+ msgs := []db.ChatMessage{
+ chatMsg("assistant", "older", protocol.ChatQuickAction{Label: "Old one"}),
+ chatMsg("user", "next"),
+ chatMsg("assistant", "newer",
+ protocol.ChatQuickAction{Label: "New one"},
+ // Case-insensitive duplicate of the older label: one entry only.
+ protocol.ChatQuickAction{Label: "OLD ONE"},
+ ),
+ }
+
+ got := collectPreviousChatQuickActions(msgs)
+ want := []string{"New one", "OLD ONE"}
+ if len(got) != len(want) {
+ t.Fatalf("labels = %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("labels = %v, want %v (newest first, deduped)", got, want)
+ }
+ }
+}
+
+func TestCollectPreviousChatQuickActionsCapsTheList(t *testing.T) {
+ var msgs []db.ChatMessage
+ for i := 0; i < chatQuickActionsPreviousMax+3; i++ {
+ msgs = append(msgs, chatMsg("assistant", "reply", protocol.ChatQuickAction{
+ Label: string(rune('a'+i)) + " label",
+ }))
+ }
+ if got := collectPreviousChatQuickActions(msgs); len(got) != chatQuickActionsPreviousMax {
+ t.Fatalf("collected %d labels, want the cap of %d", len(got), chatQuickActionsPreviousMax)
+ }
+}
+
+func TestCollectPreviousChatQuickActionsSkipsUnparseableAndBlank(t *testing.T) {
+ msgs := []db.ChatMessage{
+ {Role: "assistant", QuickActions: []byte("not json")},
+ chatMsg("assistant", "reply", protocol.ChatQuickAction{Label: " "}),
+ chatMsg("assistant", "reply", protocol.ChatQuickAction{Label: "Real"}),
+ }
+ got := collectPreviousChatQuickActions(msgs)
+ if len(got) != 1 || got[0] != "Real" {
+ t.Fatalf("labels = %v, want just [Real]", got)
+ }
+}
+
+// The pass is asked for {"actions":[...]} because response_format=json_object
+// rejects a top-level array.
+func TestParseChatQuickActionsOutputAcceptsObjectShape(t *testing.T) {
+ actions := parseChatQuickActionsOutput(`{"actions":[{"label":"Ship it","prompt":"open the PR","primary":true}]}`)
+ if len(actions) != 1 || actions[0].Label != "Ship it" || !actions[0].Primary {
+ t.Fatalf("actions = %+v", actions)
+ }
+}
+
+func TestParseChatQuickActionsOutputAcceptsEmptyObjectShape(t *testing.T) {
+ if actions := parseChatQuickActionsOutput(`{"actions":[]}`); len(actions) != 0 {
+ t.Fatalf("actions = %+v, want none", actions)
+ }
+}
+
+// The bare array stays supported: it is what the bracket fallback extracts out
+// of prose, and a model that drops the wrapper should not cost the user pills.
+func TestParseChatQuickActionsOutputStillAcceptsBareArray(t *testing.T) {
+ actions := parseChatQuickActionsOutput(`[{"label":"Bare","prompt":"still parsed"}]`)
+ if len(actions) != 1 || actions[0].Label != "Bare" {
+ t.Fatalf("actions = %+v", actions)
+ }
+}
+
+func TestParseChatQuickActionsOutputAcceptsFencedObject(t *testing.T) {
+ raw := "Here you go:\n```json\n" + `{"actions":[{"label":"Fenced","prompt":"p"}]}` + "\n```"
+ actions := parseChatQuickActionsOutput(raw)
+ if len(actions) != 1 || actions[0].Label != "Fenced" {
+ t.Fatalf("actions = %+v", actions)
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 735cfd25b1..93341dd9b8 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -9,6 +9,7 @@ import (
"strconv"
"strings"
"sync"
+ "sync/atomic"
"time"
"unicode/utf8"
@@ -56,6 +57,19 @@ type TaskService struct {
// exactly as before. Wired in router.go after composiointeg.NewService
// succeeds; the concrete type is *composio.Service.
Composio ComposioOverlayBuilder
+ // QuickActions generates chat follow-up suggestions through the
+ // server-internal LLM layer. Optional: nil (or a disabled client) turns the
+ // whole feature off — no pending marker, no pills — which is the expected
+ // state for a self-hosted deployment with no MULTICA_LLM_* configuration.
+ // Wired in router.go from the same *llm.Client that backs chat auto-titling.
+ QuickActions ChatQuickActionsLLM
+ // quickActionsInFlight (chat session id -> struct{}{}) and
+ // quickActionsRunning admit suggestion passes: one per session, and a
+ // process-wide ceiling. Both zero values are usable, so a TaskService built
+ // without NewTaskService still gates correctly rather than deadlocking or
+ // shedding everything.
+ quickActionsInFlight sync.Map
+ quickActionsRunning atomic.Int64
analyticsContextMu sync.Mutex
analyticsContextCache map[string]analytics.TaskContext
@@ -1432,10 +1446,12 @@ var ErrChatTaskAgentNoRuntime = errors.New("chat task: agent has no runtime")
// 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")
+// ErrChatQuickActionsUnavailable signals that the deployment has no LLM layer
+// configured (no MULTICA_LLM_API_KEY / MULTICA_LLM_BASE_URL), so suggestions
+// cannot be generated at all. Automatic generation degrades silently in that
+// case; an explicit refresh gets this error so the client can say why nothing
+// happened.
+var ErrChatQuickActionsUnavailable = errors.New("chat quick actions: llm layer not configured")
// ErrChatQuickActionsStale signals the turn the client asked to refresh is no
// longer the session's latest assistant turn (a newer reply landed since the
@@ -1597,153 +1613,77 @@ 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.
+// RegenerateChatQuickActions runs a fresh suggestion pass for the session's
+// latest assistant turn, letting the user refresh the quick-action pills
+// without sending a new message (MUL-5149). Generation happens server-side
+// through the same LLM path as the automatic pass, so this enqueues no agent
+// task and resumes no provider session — it just validates the target. It
+// returns the target assistant message id (so the client can anchor its pending
+// placeholder there) and the turn's task row, which the caller hands to
+// GenerateChatQuickActionsAsync.
//
// 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)
+func (s *TaskService) RegenerateChatQuickActions(ctx context.Context, chatSession db.ChatSession, expectedMessageID pgtype.UUID) (targetMessageID pgtype.UUID, targetTask db.AgentTaskQueue, err error) {
+ if s.QuickActions == nil || !s.QuickActions.Enabled() {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, ErrChatQuickActionsUnavailable
+ }
+
+ // 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, and the generator keys its write off the turn's task id.
+ target, err := s.Queries.GetLatestAssistantChatMessageForSession(ctx, chatSession.ID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, ErrChatQuickActionsNoTurn
+ }
+ return pgtype.UUID{}, db.AgentTaskQueue{}, fmt.Errorf("load latest assistant turn: %w", err)
+ }
+ if target.MessageKind != protocol.ChatMessageKindMessage || !target.TaskID.Valid {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, 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 build suggestions from the
+ // newer context yet attach them to the stale turn, and the client's pending
+ // marker would wait on a chat:quick_actions that never matches. Refuse so
+ // the client rolls back and re-offers refresh on the new turn (MUL-5149).
+ if target.ID != expectedMessageID {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, ErrChatQuickActionsStale
+ }
+ // Refuse while a turn is already running on this session: it is about to
+ // replace the latest reply, so suggestions built now would be attached to a
+ // turn the user is seconds away from scrolling past.
+ busy, err := s.Queries.HasActiveChatTaskForSession(ctx, chatSession.ID)
if err != nil {
- return pgtype.UUID{}, db.AgentTaskQueue{}, fmt.Errorf("load agent: %w", err)
+ return pgtype.UUID{}, db.AgentTaskQueue{}, fmt.Errorf("check active chat task: %w", err)
}
- if agent.ArchivedAt.Valid {
- return pgtype.UUID{}, db.AgentTaskQueue{}, ErrChatTaskAgentArchived
+ if busy {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, ErrChatQuickActionsBusy
}
- if !agent.RuntimeID.Valid {
- return pgtype.UUID{}, db.AgentTaskQueue{}, ErrChatTaskAgentNoRuntime
+ // A refresh no longer creates a task row, so the check above cannot see a
+ // generation already running for this session — a second refresh (or one
+ // racing the automatic pass) would otherwise be accepted, spend a second
+ // upstream call, and race the first to write the same row. Refuse it here
+ // so the client rolls its optimistic marker back instead.
+ if s.chatQuickActionsInFlight(chatSession.ID) {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, ErrChatQuickActionsBusy
}
- 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
+ task, err := s.Queries.GetAgentTask(ctx, target.TaskID)
+ if err != nil {
+ return pgtype.UUID{}, db.AgentTaskQueue{}, fmt.Errorf("load target turn task: %w", err)
}
- slog.Info("chat quick-actions regenerate enqueued",
- "task_id", util.UUIDToString(task.ID),
+ slog.Info("chat quick-actions regenerate accepted",
"chat_session_id", util.UUIDToString(chatSession.ID),
- "target_task_id", util.UUIDToString(task.RegenerateQuickActionsFor),
+ "target_task_id", util.UUIDToString(target.TaskID),
+ "target_message_id", util.UUIDToString(target.ID),
)
- // 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
+ // Validation only: the caller starts the pass. Keeping dispatch out of here
+ // means the refresh gates can be tested without a background goroutine
+ // writing to the same rows mid-assertion.
+ return target.ID, task, nil
}
// PromoteChannelChatTasksIfMediaReady queues channel tasks as soon as every
@@ -1788,7 +1728,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, quickActionsDisabled bool) (*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) (*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)
@@ -1840,7 +1780,6 @@ 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)
@@ -3095,19 +3034,22 @@ 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 && !task.RegenerateQuickActionsFor.Valid {
+ if task.ChatSessionID.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.
//
- // 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))
+ // The quick-actions decision is made here, before the broadcast, so the
+ // pending flag and the pass that resolves it can never disagree: a
+ // client only shows the skeleton placeholder when generation is
+ // actually about to run.
+ suggest := s.chatQuickActionsEligible(ctx, task, chatAssistantMsg)
+ s.broadcastChatDone(ctx, task, chatAssistantMsg, suggest)
+ if suggest {
+ // Detached: the reply is already delivered and the user's next turn
+ // must never wait on suggestions.
+ s.GenerateChatQuickActionsAsync(task, ChatQuickActionsAutomatic)
+ }
}
// Reconcile agent status
@@ -3159,26 +3101,13 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
// 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)
- }
+ // The parsed footer is DISCARDED: suggestions come from the server-side pass
+ // now (SupplementChatQuickActions). Honouring a footer here would pin a
+ // pre-upgrade session to the retired, lower-quality in-band suggestions and
+ // suppress the pass that would have replaced them.
+ body, _ = splitChatQuickActions(body)
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.
@@ -3227,13 +3156,6 @@ 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)
@@ -3547,13 +3469,7 @@ 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 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{
+ if _, err := s.Queries.CreateChatMessage(ctx, db.CreateChatMessageParams{
ChatSessionID: task.ChatSessionID,
Role: "assistant",
Content: redact.Text(errMsg),
@@ -3586,33 +3502,6 @@ 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
@@ -3735,13 +3624,6 @@ 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)
}
@@ -4109,14 +3991,6 @@ 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
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 8d26573fbb..89d83e33c6 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -259,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,
- quick_actions_disabled, regenerate_quick_actions_for, fire_at
+ fire_at
)
VALUES (
$1, $2, NULL,
@@ -273,30 +273,26 @@ 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, 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"`
- QuickActionsDisabled pgtype.Bool `json:"quick_actions_disabled"`
- RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`
+ 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"`
}
// The chat sender (initiator) is a direct_human originator and accountable;
@@ -318,8 +314,6 @@ 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(
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 2205450929..9700680f23 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -351,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,
- quick_actions_disabled, regenerate_quick_actions_for, fire_at
+ fire_at
)
VALUES (
$1, $2, NULL,
@@ -365,8 +365,6 @@ 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 *;
diff --git a/server/pkg/llm/client.go b/server/pkg/llm/client.go
index 29939a7700..28d09f816c 100644
--- a/server/pkg/llm/client.go
+++ b/server/pkg/llm/client.go
@@ -191,6 +191,53 @@ func (c *Client) GenerateText(ctx context.Context, model, systemPrompt, userProm
return completion.Choices[0].Message.Content, nil
}
+// GenerateJSON is GenerateText's structured sibling, for internal callers whose
+// reply has to be machine-readable (quick-action suggestions, ...). It requests
+// response_format=json_object and returns the assistant's raw text unparsed.
+//
+// JSON-object mode only guarantees the reply is syntactically valid JSON, never
+// that its shape matches what the prompt asked for, so the caller still owns
+// parsing and validation. One upstream constraint the caller must honor: the
+// word "JSON" has to appear somewhere in the prompt, or OpenAI-compatible
+// endpoints reject the request outright.
+//
+// temperature and maxTokens apply only when positive; zero leaves the upstream
+// default in place. Model empty -> the configured default.
+func (c *Client) GenerateJSON(ctx context.Context, model, systemPrompt, userPrompt string, temperature float64, maxTokens int64) (string, error) {
+ if !c.Enabled() {
+ return "", ErrNotConfigured
+ }
+
+ messages := make([]openai.ChatCompletionMessageParamUnion, 0, 2)
+ if strings.TrimSpace(systemPrompt) != "" {
+ messages = append(messages, openai.SystemMessage(systemPrompt))
+ }
+ messages = append(messages, openai.UserMessage(userPrompt))
+
+ params := openai.ChatCompletionNewParams{
+ Messages: messages,
+ Model: shared.ChatModel(strings.TrimSpace(model)),
+ ResponseFormat: openai.ChatCompletionNewParamsResponseFormatUnion{
+ OfJSONObject: &shared.ResponseFormatJSONObjectParam{},
+ },
+ }
+ if temperature > 0 {
+ params.Temperature = openai.Float(temperature)
+ }
+ if maxTokens > 0 {
+ params.MaxTokens = openai.Int(maxTokens)
+ }
+
+ completion, err := c.Chat(ctx, params)
+ if err != nil {
+ return "", err
+ }
+ if len(completion.Choices) == 0 {
+ return "", errors.New("llm: upstream returned no choices")
+ }
+ return completion.Choices[0].Message.Content, nil
+}
+
// withDefaultTimeout returns ctx unchanged (with a no-op cancel) when it already
// has a deadline, otherwise a child context bounded by defaultRequestTimeout.
func withDefaultTimeout(ctx context.Context) (context.Context, context.CancelFunc) {
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 820bd2086e..7e0f1888ca 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -124,12 +124,6 @@ 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