Skip to content

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

Go

feat(chat): task-owned direct-chat input batches + explicit no_response outcome (MUL-4351) (#5195)

Bohan Jiangcb87dd106be5
diff --git a/apps/mobile/components/chat/chat-message-list.tsx b/apps/mobile/components/chat/chat-message-list.tsx
index 692e5a1712..c3dda0f344 100644
--- a/apps/mobile/components/chat/chat-message-list.tsx
+++ b/apps/mobile/components/chat/chat-message-list.tsx
@@ -319,18 +319,32 @@ function AssistantRow({
const { data: timeline = [] } = useQuery(
taskMessagesOptions(message.task_id),
);
+ // no_response (MUL-4351, mirrors packages/views AssistantMessage): the agent
+ // completed this turn without text. Keep the tool timeline and show a notice
+ // instead of an empty Markdown block; caption reads "Finished in" not
+ // "Replied in".
+ const isNoResponse = message.message_kind === "no_response";
const body = (
<View className="gap-1.5">
{timeline.length > 0 ? (
<ChatTimeline items={timeline} />
) : null}
- <Markdown
- content={message.content}
- attachments={message.attachments}
- selectable={isSelecting}
- />
+ {isNoResponse ? (
+ <Text className="text-sm italic text-muted-foreground">
+ The agent finished this turn without a text reply.
+ </Text>
+ ) : (
+ <Markdown
+ content={message.content}
+ attachments={message.attachments}
+ selectable={isSelecting}
+ />
+ )}
{message.elapsed_ms != null ? (
- <ElapsedCaption variant="replied" elapsedMs={message.elapsed_ms} />
+ <ElapsedCaption
+ variant={isNoResponse ? "finished" : "replied"}
+ elapsedMs={message.elapsed_ms}
+ />
) : null}
</View>
);
@@ -349,13 +363,15 @@ function ElapsedCaption({
variant,
elapsedMs,
}: {
- variant: "replied" | "failed";
+ variant: "replied" | "failed" | "finished";
elapsedMs: number;
}) {
const label =
variant === "replied"
? `Replied in ${formatElapsedMs(elapsedMs)}`
- : `Failed after ${formatElapsedMs(elapsedMs)}`;
+ : variant === "finished"
+ ? `Finished in ${formatElapsedMs(elapsedMs)}`
+ : `Failed after ${formatElapsedMs(elapsedMs)}`;
return (
<Text className="text-xs text-muted-foreground/80 mt-1">{label}</Text>
);
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.ts
index a037346858..c4e9720746 100644
--- a/apps/mobile/data/realtime/chat-ws-updaters.ts
+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts
@@ -114,6 +114,10 @@ export function applyChatDoneToCache(
task_id: payload.task_id,
created_at: payload.created_at,
elapsed_ms: payload.elapsed_ms ?? null,
+ // Mirror web's applyChatDoneToCache: carry the kind so a no_response turn
+ // renders its notice inline; missing → "message" for older servers
+ // (MUL-4351).
+ message_kind: payload.message_kind ?? "message",
};
qc.setQueryData<ChatMessage[]>(
chatKeys.messages(payload.chat_session_id),
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.ts
index cdec7bc44e..a3e3869309 100644
--- a/packages/core/realtime/use-realtime-sync.test.ts
+++ b/packages/core/realtime/use-realtime-sync.test.ts
@@ -86,10 +86,27 @@ describe("applyChatDoneToCache", () => {
task_id: taskId,
created_at: "2026-05-13T05:00:02Z",
elapsed_ms: 1234,
+ // Additive kind carried on the inline-inserted assistant message so a
+ // no_response turn renders without a refetch (MUL-4351); defaults to
+ // "message" when the server omits it.
+ message_kind: "message",
},
]);
});
+ it("carries message_kind=no_response on the inline assistant message", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage()]);
+
+ applyChatDoneToCache(
+ qc,
+ donePayload({ content: "", message_kind: "no_response" }),
+ );
+
+ const msgs = qc.getQueryData<ChatMessage[]>(messagesKey);
+ expect(msgs?.[1]?.message_kind).toBe("no_response");
+ });
+
it("does not duplicate a replayed chat done event", () => {
const qc = createQueryClient();
const assistant: ChatMessage = {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index acd304dcdb..54e3df87b2 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -138,6 +138,10 @@ export function applyChatDoneToCache(
task_id: taskId,
created_at: payload.created_at ?? new Date().toISOString(),
elapsed_ms: payload.elapsed_ms ?? null,
+ // Carry the kind so a no_response turn renders its placeholder inline
+ // without waiting for the reconciling refetch (MUL-4351). Missing →
+ // "message" for older servers.
+ message_kind: payload.message_kind ?? "message",
};
qc.setQueryData<ChatMessage[] | undefined>(
chatKeys.messages(sessionId),
diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.ts
index 214590484e..2f261052bb 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -6,6 +6,15 @@ export interface ChatPinnedAgent {
position: number;
}
+/**
+ * Kind of a chat message. Additive (MUL-4351): the server always sends a
+ * concrete value, but treat a missing/unknown value as "message" so an older
+ * server or a future kind never breaks rendering.
+ * - "message" — an ordinary user/assistant message.
+ * - "no_response" — a completed direct-chat turn that produced no text reply.
+ */
+export type ChatMessageKind = "message" | "no_response";
+
/** Preview of a session's most recent message, for the IM-style list. */
export interface ChatLastMessage {
content: string;
@@ -13,6 +22,8 @@ export interface ChatLastMessage {
created_at: string;
/** Present when the last message is a failed assistant reply. */
failure_reason?: string | null;
+ /** "message" (default) or "no_response". Optional for older servers. */
+ message_kind?: ChatMessageKind;
}
export interface ChatSession {
@@ -88,6 +99,12 @@ export interface ChatMessage {
* and on legacy assistant messages predating migration 063.
*/
elapsed_ms?: number | null;
+ /**
+ * "message" (default) or "no_response" — a completed direct-chat turn that
+ * produced no text reply (MUL-4351). Optional/additive: absent on older
+ * servers and on user messages; treat a missing value as "message".
+ */
+ message_kind?: ChatMessageKind;
}
export interface ChatMessagesCursor {
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 34a05e6452..7dd314274c 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -347,6 +347,14 @@ export interface ChatDonePayload {
content?: string;
elapsed_ms?: number;
created_at?: string;
+ /**
+ * "message" (default) or "no_response" — a completed direct-chat turn with
+ * no text reply (MUL-4351). Optional/additive: older servers omit it, so the
+ * consumer defaults to "message". Because direct-chat completion now always
+ * persists exactly one assistant row, message_id/content/created_at are
+ * populated alongside this even for a no_response turn.
+ */
+ message_kind?: import("./chat").ChatMessageKind;
}
export interface ChatSessionReadPayload {
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index 4b12d8d467..ac65d525b9 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -319,15 +319,23 @@ function AssistantMessage({
);
}
+ // no_response path (MUL-4351): the agent completed this direct-chat turn
+ // without any text. Keep whatever tool/thinking timeline the run produced and
+ // show a localized "no text reply" notice instead of an empty markdown block.
+ const isNoResponse = message.message_kind === "no_response";
+
return (
<div className="w-full space-y-1.5">
- {timeline.length > 0 ? (
+ {timeline.length > 0 && (
<TimelineView items={timeline} attachments={message.attachments} />
- ) : (
+ )}
+ {isNoResponse ? (
+ <NoResponseNotice />
+ ) : timeline.length === 0 ? (
<div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">
<MemoizedMarkdown attachments={message.attachments}>{message.content}</MemoizedMarkdown>
</div>
- )}
+ ) : null}
<AttachmentList
attachments={message.attachments}
content={message.content}
@@ -341,6 +349,18 @@ function AssistantMessage({
);
}
+// Muted, localized notice shown in place of assistant text when a turn
+// completed with no reply (message_kind === "no_response"). Explains the empty
+// turn instead of rendering a blank bubble (MUL-4351).
+function NoResponseNotice() {
+ const { t } = useT("chat");
+ return (
+ <div className="text-sm italic text-muted-foreground">
+ {t(($) => $.message_list.no_response)}
+ </div>
+ );
+}
+
// Inline footer row beneath the assistant reply: "Replied in 38s · [Copy]".
// Action icons live here (not as a hover-floating overlay) so they're
// discoverable on first read and don't shift content. Buttons stay quiet
@@ -355,12 +375,18 @@ function MessageFooter({
timeline: ChatTimelineItem[];
isPending: boolean;
}) {
- const showCopy = !isPending;
+ // A no_response turn has nothing to copy, and its caption uses a neutral
+ // "Finished in Xs" instead of "Replied in Xs" (MUL-4351).
+ const isNoResponse = message.message_kind === "no_response";
+ const showCopy = !isPending && !isNoResponse;
if (message.elapsed_ms == null && !showCopy) return null;
return (
<div className="flex items-center gap-1.5">
{message.elapsed_ms != null && (
- <ElapsedCaption variant="replied" elapsedMs={message.elapsed_ms} />
+ <ElapsedCaption
+ variant={isNoResponse ? "finished" : "replied"}
+ elapsedMs={message.elapsed_ms}
+ />
)}
{showCopy && <MessageCopyButton message={message} timeline={timeline} />}
</div>
@@ -414,15 +440,18 @@ function ElapsedCaption({
elapsedMs,
className,
}: {
- variant: "replied" | "failed";
+ variant: "replied" | "failed" | "finished";
elapsedMs: number;
className?: string;
}) {
const { t } = useT("chat");
+ const elapsed = formatElapsedMs(elapsedMs);
const text =
variant === "replied"
- ? t(($) => $.message_list.replied_in, { elapsed: formatElapsedMs(elapsedMs) })
- : t(($) => $.message_list.failed_after, { elapsed: formatElapsedMs(elapsedMs) });
+ ? t(($) => $.message_list.replied_in, { elapsed })
+ : variant === "finished"
+ ? t(($) => $.message_list.finished_in, { elapsed })
+ : t(($) => $.message_list.failed_after, { elapsed });
return (
<div className={cn("text-xs text-muted-foreground/80", className)}>
{text}
diff --git a/packages/views/chat/components/chat-thread-list.test.tsx b/packages/views/chat/components/chat-thread-list.test.tsx
index 96a56ae7bc..48ab7469dd 100644
--- a/packages/views/chat/components/chat-thread-list.test.tsx
+++ b/packages/views/chat/components/chat-thread-list.test.tsx
@@ -140,3 +140,33 @@ describe("ChatThreadList archive delegation", () => {
expect(archiveMutate).not.toHaveBeenCalled();
});
});
+
+describe("ChatThreadList no_response preview (MUL-4351)", () => {
+ it("shows a localized 'no text reply' preview instead of the fallback body", () => {
+ const session = makeSession({
+ id: "nr1",
+ last_message: {
+ content: "The agent finished this turn without a text reply.",
+ role: "assistant",
+ created_at: "2026-07-08T03:00:00Z",
+ message_kind: "no_response",
+ },
+ });
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <ChatThreadList
+ sessions={[session]}
+ agents={[agent]}
+ activeSessionId={null}
+ onSelectSession={vi.fn()}
+ onArchive={vi.fn()}
+ />
+ </I18nProvider>,
+ );
+ expect(screen.getByText(enChat.list.no_response_preview)).toBeInTheDocument();
+ // The stored English fallback body must not leak into the preview.
+ expect(
+ screen.queryByText("The agent finished this turn without a text reply."),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/chat/components/chat-thread-list.tsx b/packages/views/chat/components/chat-thread-list.tsx
index 0c8fd8e61d..c20d3e1380 100644
--- a/packages/views/chat/components/chat-thread-list.tsx
+++ b/packages/views/chat/components/chat-thread-list.tsx
@@ -222,6 +222,15 @@ export function ChatThreadList({
);
} else if (last?.failure_reason) {
previewNode = <span className="block truncate text-destructive">{t(($) => $.list.failed)}</span>;
+ } else if (last?.message_kind === "no_response") {
+ // A no_response turn stores a non-empty English fallback as its content,
+ // so the preview is never blank even on older clients; new clients show a
+ // localized, italic hint instead of that fallback text (MUL-4351).
+ previewNode = (
+ <span className="block truncate italic text-muted-foreground">
+ {t(($) => $.list.no_response_preview)}
+ </span>
+ );
} else if (last) {
previewNode = (
<span className={cn("block truncate", unread > 0 ? "text-foreground/80" : "text-muted-foreground")}>
diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.json
index 1f33e867be..0dde77d11d 100644
--- a/packages/views/locales/en/chat.json
+++ b/packages/views/locales/en/chat.json
@@ -26,6 +26,8 @@
"show_details": "Show details",
"replied_in": "Replied in {{elapsed}}",
"failed_after": "Failed after {{elapsed}}",
+ "finished_in": "Finished in {{elapsed}}",
+ "no_response": "The agent finished this turn without a text reply.",
"failure": {
"agent_error": "The agent ran into an error and couldn't finish replying. Please try again.",
"timeout": "The agent took too long and stopped before finishing. Try again, or break your request into smaller steps.",
@@ -144,6 +146,7 @@
"failed": "Failed to send",
"you_prefix": "You: ",
"no_messages": "No messages yet",
+ "no_response_preview": "No text reply",
"quick_agents": "Frequent agents",
"add": "Add",
"add_agent": "Add a frequent agent",
diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.json
index 2416100154..3f77c7bf2f 100644
--- a/packages/views/locales/ja/chat.json
+++ b/packages/views/locales/ja/chat.json
@@ -25,6 +25,8 @@
"show_details": "詳細を表示",
"replied_in": "{{elapsed}}で返信",
"failed_after": "{{elapsed}}後に失敗",
+ "finished_in": "{{elapsed}}で完了",
+ "no_response": "エージェントはテキストの返信なしでこのターンを終了しました。",
"failure": {
"agent_error": "エージェントでエラーが発生し、返信を完了できませんでした。もう一度お試しください。",
"timeout": "処理に時間がかかりすぎたため、完了前に停止しました。もう一度お試しいただくか、リクエストを分けてみてください。",
@@ -141,6 +143,7 @@
"failed": "送信失敗",
"you_prefix": "あなた:",
"no_messages": "メッセージはまだありません",
+ "no_response_preview": "テキスト返信なし",
"quick_agents": "よく使う Agent",
"add": "追加",
"add_agent": "よく使う Agent を追加",
diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.json
index e251e32948..7128b58a9f 100644
--- a/packages/views/locales/ko/chat.json
+++ b/packages/views/locales/ko/chat.json
@@ -25,6 +25,8 @@
"show_details": "세부 정보 보기",
"replied_in": "{{elapsed}} 만에 답변",
"failed_after": "{{elapsed}} 후 실패",
+ "finished_in": "{{elapsed}} 만에 완료",
+ "no_response": "에이전트가 텍스트 답변 없이 이 턴을 마쳤습니다.",
"failure": {
"agent_error": "에이전트에 오류가 발생하여 답변을 완료하지 못했습니다. 다시 시도해 주세요.",
"timeout": "시간이 너무 오래 걸려 완료 전에 중단되었습니다. 다시 시도하거나 요청을 더 작게 나눠 보세요.",
@@ -141,6 +143,7 @@
"failed": "전송 실패",
"you_prefix": "나: ",
"no_messages": "아직 메시지가 없습니다",
+ "no_response_preview": "텍스트 답변 없음",
"quick_agents": "자주 쓰는 Agent",
"add": "추가",
"add_agent": "자주 쓰는 Agent 추가",
diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.json
index 0a7590e372..3647b1f1f1 100644
--- a/packages/views/locales/zh-Hans/chat.json
+++ b/packages/views/locales/zh-Hans/chat.json
@@ -25,6 +25,8 @@
"show_details": "查看详情",
"replied_in": "{{elapsed}} 内回复",
"failed_after": "{{elapsed}} 后失败",
+ "finished_in": "{{elapsed}} 内结束",
+ "no_response": "本轮已结束,Agent 没有返回文字回复。",
"failure": {
"agent_error": "智能体运行时出错,没能完成回复。请重试。",
"timeout": "智能体处理超时,未能完成。可以重试,或把需求拆得更小一些。",
@@ -141,6 +143,7 @@
"failed": "发送失败",
"you_prefix": "你:",
"no_messages": "还没有消息",
+ "no_response_preview": "无文字回复",
"quick_agents": "常用 Agent",
"add": "添加",
"add_agent": "添加常用 Agent",
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index cece329869..50d93b1193 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -146,7 +146,7 @@ func (h *Handler) ListChatSessions(w http.ResponseWriter, r *http.Request) {
Status: s.Status,
HasUnread: s.UnreadCount > 0,
UnreadCount: int(s.UnreadCount),
- LastMessage: buildChatLastMessage(s.LastMessageAt, s.LastMessageContent, s.LastMessageRole, s.LastMessageFailureReason),
+ LastMessage: buildChatLastMessage(s.LastMessageAt, s.LastMessageContent, s.LastMessageRole, s.LastMessageFailureReason, s.LastMessageKind),
Pinned: s.PinnedAt.Valid,
CreatedAt: timestampToString(s.CreatedAt),
UpdatedAt: timestampToString(s.UpdatedAt),
@@ -175,7 +175,7 @@ func (h *Handler) ListChatSessions(w http.ResponseWriter, r *http.Request) {
Status: s.Status,
HasUnread: s.UnreadCount > 0,
UnreadCount: int(s.UnreadCount),
- LastMessage: buildChatLastMessage(s.LastMessageAt, s.LastMessageContent, s.LastMessageRole, s.LastMessageFailureReason),
+ LastMessage: buildChatLastMessage(s.LastMessageAt, s.LastMessageContent, s.LastMessageRole, s.LastMessageFailureReason, s.LastMessageKind),
Pinned: s.PinnedAt.Valid,
CreatedAt: timestampToString(s.CreatedAt),
UpdatedAt: timestampToString(s.UpdatedAt),
@@ -598,70 +598,32 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
hadUserMessage = existed
}
- // Create the user message first so the daemon can always find it.
- msg, err := h.Queries.CreateChatMessage(r.Context(), db.CreateChatMessageParams{
- ChatSessionID: session.ID,
- Role: "user",
- Content: req.Content,
- })
+ // Persist the whole turn atomically (MUL-4351): the owning task, the user
+ // message bound to that task (so it belongs to the task's immutable input
+ // batch the instant it exists), attachment bindings, and the session touch
+ // all commit together, and the daemon is only notified after the commit. For
+ // web chat the sender is the authenticated request user (sessions are
+ // creator-only), so they are the task initiator — surfaced to the agent
+ // under `## Task Initiator`.
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ 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 create chat message")
+ writeError(w, http.StatusInternalServerError, "failed to send chat message: "+err.Error())
return
}
+ msg := sent.Message
+ task := sent.Task
- // Back-fill chat_message_id on attachments the sender uploaded while
- // composing. New clients upload workspace-scoped unattached rows and bind
- // them here; older clients may still upload against the chat_session_id.
- // The query accepts both shapes, but only for this workspace, this actor,
- // and rows that are not already linked to an issue/comment/message.
+ // AttachmentIDs actually bound by the server. Requested-but-unbound ids are
+ // surfaced to the client so it can warn the user (see SendChatMessageResponse).
var boundAttachmentIDs []string
if len(attachmentIDs) > 0 {
- actorType, actorID := h.resolveActor(r, userID, workspaceID)
- bound, err := h.Queries.LinkAttachmentsToChatMessage(r.Context(), db.LinkAttachmentsToChatMessageParams{
- ChatMessageID: msg.ID,
- ChatSessionID: session.ID,
- WorkspaceID: session.WorkspaceID,
- UploaderType: actorType,
- UploaderID: parseUUID(actorID),
- AttachmentIds: attachmentIDs,
- })
- if err != nil {
- // Don't fail the send — the message content is already saved and
- // the attachments remain on the session (still downloadable).
- slog.Warn("link chat attachments failed", "error", err, "message_id", uuidToString(msg.ID))
- }
- boundAttachmentIDs = make([]string, 0, len(bound))
- for _, id := range bound {
+ boundAttachmentIDs = make([]string, 0, len(sent.BoundAttachmentIDs))
+ for _, id := range sent.BoundAttachmentIDs {
boundAttachmentIDs = append(boundAttachmentIDs, uuidToString(id))
}
}
- // Enqueue a chat task after the message exists. For web chat the sender is
- // the authenticated request user (sessions are creator-only), so they are
- // the task initiator — surfaced to the agent under `## Task Initiator`.
- task, err := h.TaskService.EnqueueChatTask(r.Context(), session, parseUUID(userID), false)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to enqueue chat task: "+err.Error())
- return
- }
- if err := h.Queries.LinkChatMessageToTask(r.Context(), db.LinkChatMessageToTaskParams{
- ID: msg.ID,
- TaskID: task.ID,
- }); err != nil {
- // Don't fail the send: the task already exists and the user message
- // is persisted. The link is only needed for precise empty-cancel
- // cleanup; older/unlinked rows simply keep the historical behavior.
- slog.Warn("link user chat message to task failed",
- "message_id", uuidToString(msg.ID),
- "task_id", uuidToString(task.ID),
- "error", err,
- )
- }
-
- // Touch session updated_at.
- if err := h.Queries.TouchChatSession(r.Context(), session.ID); err != nil {
- slog.Warn("failed to touch chat session", "session_id", sessionID, "error", err)
- }
taskContext := h.TaskService.AnalyticsContextForTask(r.Context(), task)
platform, _, _ := middleware.ClientMetadataFromContext(r.Context())
obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.ChatMessageSent(
@@ -1195,11 +1157,15 @@ type ChatLastMessage struct {
Role string `json:"role"`
CreatedAt string `json:"created_at"`
FailureReason *string `json:"failure_reason"`
+ // MessageKind is 'message' (default) or 'no_response'. Lets the session
+ // list render a localized preview for a no-text-reply turn instead of the
+ // English fallback content the server stores (MUL-4351).
+ MessageKind string `json:"message_kind"`
}
// buildChatLastMessage assembles the preview from list-row columns; returns nil
// when there is no last message (the LEFT JOIN produced a NULL timestamp).
-func buildChatLastMessage(at pgtype.Timestamptz, content, role string, failure pgtype.Text) *ChatLastMessage {
+func buildChatLastMessage(at pgtype.Timestamptz, content, role string, failure pgtype.Text, kind string) *ChatLastMessage {
if !at.Valid {
return nil
}
@@ -1208,6 +1174,7 @@ func buildChatLastMessage(at pgtype.Timestamptz, content, role string, failure p
Role: role,
CreatedAt: timestampToString(at),
FailureReason: textToPtr(failure),
+ MessageKind: normalizeMessageKind(kind),
}
}
@@ -1224,6 +1191,10 @@ type ChatMessageResponse struct {
// ElapsedMs is the wall-clock duration from task creation to terminal
// state. Drives "Replied in 38s" / "Failed after 12s" captions.
ElapsedMs *int64 `json:"elapsed_ms"`
+ // MessageKind is 'message' (default) or 'no_response' — a completed
+ // direct-chat turn that produced no text reply (MUL-4351). Additive:
+ // clients that don't understand it fall back to the non-empty content.
+ MessageKind string `json:"message_kind"`
// Attachments linked to this message via chat_message_id. The chat
// bubble renders file cards from these, and the daemon claim path
// (daemon.go) pulls structured metadata from the same source so the
@@ -1256,6 +1227,19 @@ func chatMessageToResponse(m db.ChatMessage, attachments []AttachmentResponse) C
CreatedAt: timestampToString(m.CreatedAt),
FailureReason: textToPtr(m.FailureReason),
ElapsedMs: int8ToPtr(m.ElapsedMs),
+ MessageKind: normalizeMessageKind(m.MessageKind),
Attachments: attachments,
}
}
+
+// normalizeMessageKind maps a stored chat_message.message_kind to the value the
+// API exposes. Unknown / empty kinds degrade to 'message' so a future kind
+// never surprises an older client into a broken render (MUL-4351).
+func normalizeMessageKind(kind string) string {
+ switch kind {
+ case protocol.ChatMessageKindNoResponse:
+ return protocol.ChatMessageKindNoResponse
+ default:
+ return protocol.ChatMessageKindMessage
+ }
+}
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
new file mode 100644
index 0000000000..93cfe4a344
--- /dev/null
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -0,0 +1,386 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// setupDirectChatSession creates a runtime-guard agent (with its registered
+// runtime + daemon) and a non-intro chat session for direct (web/mobile) chat
+// ownership tests.
+func setupDirectChatSession(t *testing.T, ctx context.Context, title string) (agentID, sessionID, runtimeID, daemonID string) {
+ t.Helper()
+ agentID, runtimeID, daemonID = createRuntimeGuardAgent(t, ctx)
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)
+ VALUES ($1, $2, $3, $4)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID, title).Scan(&sessionID); err != nil {
+ t.Fatalf("setup: create chat session: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, sessionID) })
+ return agentID, sessionID, runtimeID, daemonID
+}
+
+// sendDirectChat drives the transactional direct-send service path and returns
+// the owning task id. The user message is created inside the same transaction
+// with task_id = the new task, and the task owns its own input batch.
+func sendDirectChat(t *testing.T, ctx context.Context, agentID, sessionID, content string) string {
+ t.Helper()
+ sess, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("load chat session: %v", err)
+ }
+ ag, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatalf("load agent: %v", err)
+ }
+ res, err := testHandler.TaskService.SendDirectChatMessage(ctx, sess, ag, parseUUID(testUserID), content, nil, "member", parseUUID(testUserID))
+ if err != nil {
+ t.Fatalf("SendDirectChatMessage: %v", err)
+ }
+ return uuidToString(res.Task.ID)
+}
+
+func markTaskRunning(t *testing.T, ctx context.Context, taskID string) {
+ t.Helper()
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue SET status = 'running', started_at = now(), dispatched_at = now()
+ WHERE id = $1
+ `, taskID); err != nil {
+ t.Fatalf("mark task running: %v", err)
+ }
+}
+
+func completeResult(t *testing.T, output string) []byte {
+ t.Helper()
+ b, err := json.Marshal(TaskCompleteRequest{Output: output})
+ if err != nil {
+ t.Fatalf("marshal complete result: %v", err)
+ }
+ return b
+}
+
+// TestDirectChat_TaskOwnsItsOwnInputBatch is the core input-boundary contract
+// (MUL-4351): each direct send owns exactly the user message it created. When
+// U1→T1 and U2→T2 are both queued, T1's claim must deliver ONLY U1 (never
+// "U1\n\nU2" the way the trailing-message selector would), and after T1
+// completes, T2 delivers ONLY U2.
+func TestDirectChat_TaskOwnsItsOwnInputBatch(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, runtimeID, daemonID := setupDirectChatSession(t, ctx, "ownership chat")
+
+ t1 := sendDirectChat(t, ctx, agentID, sessionID, "看上海天气")
+ t2 := sendDirectChat(t, ctx, agentID, sessionID, "还有青岛")
+
+ // Both tasks own their own input batch.
+ assertTaskInputOwner(t, ctx, t1, t1)
+ assertTaskInputOwner(t, ctx, t2, t2)
+
+ claimed := claimTaskForRuntimeGuard(t, runtimeID, daemonID)
+ if claimed.ChatMessage != "看上海天气" {
+ t.Fatalf("first claim must deliver ONLY its owned message; got %q", claimed.ChatMessage)
+ }
+
+ // Complete the first task (the older T1, claimed first by created_at order),
+ // then the next claim must deliver only the other message rather than a
+ // coalesced pair. The claim leaves T1 dispatched; move it to running so the
+ // completion CAS (WHERE status='running') applies.
+ markTaskRunning(t, ctx, t1)
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "上海晴"), "", ""); err != nil {
+ t.Fatalf("complete first task: %v", err)
+ }
+ claimed2 := claimTaskForRuntimeGuard(t, runtimeID, daemonID)
+ if claimed2.ChatMessage != "还有青岛" {
+ t.Fatalf("second claim must deliver ONLY the second owned message; got %q", claimed2.ChatMessage)
+ }
+}
+
+// TestDirectChat_RunningTaskDoesNotAbsorbNewMessage pins the acceptance case:
+// while T1 is running, a message sent from another surface lands on T2 and is
+// never folded into T1's already-sealed input batch.
+func TestDirectChat_RunningTaskDoesNotAbsorbNewMessage(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "no-absorb chat")
+
+ t1 := sendDirectChat(t, ctx, agentID, sessionID, "first")
+ markTaskRunning(t, ctx, t1)
+ // A second message arrives mid-run and gets its own task.
+ t2 := sendDirectChat(t, ctx, agentID, sessionID, "second")
+ if t1 == t2 {
+ t.Fatal("second send must create a distinct task")
+ }
+
+ // T1's owned batch is still exactly {first}; the mid-run message belongs to T2.
+ owned1, err := testHandler.Queries.ListChatInputMessages(ctx, parseUUID(t1))
+ if err != nil {
+ t.Fatalf("list T1 owned input: %v", err)
+ }
+ if len(owned1) != 1 || owned1[0].Content != "first" {
+ t.Fatalf("T1 must own only its own message; got %+v", msgContents(owned1))
+ }
+ owned2, err := testHandler.Queries.ListChatInputMessages(ctx, parseUUID(t2))
+ if err != nil {
+ t.Fatalf("list T2 owned input: %v", err)
+ }
+ if len(owned2) != 1 || owned2[0].Content != "second" {
+ t.Fatalf("T2 must own the mid-run message; got %+v", msgContents(owned2))
+ }
+}
+
+// TestCompleteTask_ChatEmptyOutputWritesNoResponse: an empty final output is a
+// visible, terminal no_response outcome — exactly one assistant row with
+// message_kind='no_response' and a non-empty fallback body, task completed, and
+// no auto-retry.
+func TestCompleteTask_ChatEmptyOutputWritesNoResponse(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "no-response chat")
+ taskID := sendDirectChat(t, ctx, agentID, sessionID, "do a tool-only thing")
+ markTaskRunning(t, ctx, taskID)
+
+ // Whitespace-only output trims to empty → no_response.
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, " "), "", ""); err != nil {
+ t.Fatalf("complete task: %v", err)
+ }
+
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("expected exactly one assistant outcome, got %d", len(rows))
+ }
+ if rows[0].MessageKind != protocol.ChatMessageKindNoResponse {
+ t.Fatalf("expected message_kind=no_response, got %q", rows[0].MessageKind)
+ }
+ if rows[0].Content == "" {
+ t.Fatal("no_response row must carry a non-empty fallback body for old clients")
+ }
+ assertTaskStatus(t, ctx, taskID, "completed")
+ assertNoRetryChild(t, ctx, taskID)
+}
+
+// TestCompleteTask_ChatNonEmptyOutputWritesMessage: a normal reply becomes a
+// single ordinary assistant message.
+func TestCompleteTask_ChatNonEmptyOutputWritesMessage(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "reply chat")
+ taskID := sendDirectChat(t, ctx, agentID, sessionID, "hello")
+ markTaskRunning(t, ctx, taskID)
+
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, "hi there"), "sess-1", "/tmp/wd"); err != nil {
+ t.Fatalf("complete task: %v", err)
+ }
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("expected exactly one assistant message, got %d", len(rows))
+ }
+ if rows[0].MessageKind != protocol.ChatMessageKindMessage {
+ t.Fatalf("expected message_kind=message, got %q", rows[0].MessageKind)
+ }
+ if rows[0].Content != "hi there" {
+ t.Fatalf("expected content 'hi there', got %q", rows[0].Content)
+ }
+}
+
+// TestCompleteTask_ChatCallbackIdempotent: a replayed completion callback must
+// not write a second assistant outcome.
+func TestCompleteTask_ChatCallbackIdempotent(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "idempotent chat")
+ taskID := sendDirectChat(t, ctx, agentID, sessionID, "hey")
+ markTaskRunning(t, ctx, taskID)
+
+ res := completeResult(t, "reply")
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", ""); err != nil {
+ t.Fatalf("first complete: %v", err)
+ }
+ // Replay: the status CAS fails, so this is an idempotent no-op success.
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", ""); err != nil {
+ t.Fatalf("replayed complete must be idempotent success, got %v", err)
+ }
+ if rows := assistantRows(t, ctx, sessionID); len(rows) != 1 {
+ t.Fatalf("expected exactly one assistant outcome after replay, got %d", len(rows))
+ }
+}
+
+// TestFailTask_ChatRetryInheritsInputOwnerAndPriority: a transient failure of a
+// task-owned direct task creates a retry child that reuses the SAME input owner
+// (so it reads the same user messages) and is queued at a bumped priority so it
+// is claimed ahead of fresh chat tasks.
+func TestFailTask_ChatRetryInheritsInputOwnerAndPriority(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, _, _ := setupDirectChatSession(t, ctx, "retry chat")
+ rootID := sendDirectChat(t, ctx, agentID, sessionID, "root question")
+ markTaskRunning(t, ctx, rootID)
+
+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(rootID), "runtime went away", "", "", "runtime_offline"); err != nil {
+ t.Fatalf("fail task: %v", err)
+ }
+
+ var childID, childOwner string
+ var childPriority, childAttempt int
+ var childStatus string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id, chat_input_task_id, priority, status, attempt
+ FROM agent_task_queue
+ WHERE parent_task_id = $1
+ `, rootID).Scan(&childID, &childOwner, &childPriority, &childStatus, &childAttempt); err != nil {
+ t.Fatalf("expected a retry child, got: %v", err)
+ }
+ if childOwner != rootID {
+ t.Fatalf("retry child must inherit the root input owner %s, got %s", rootID, childOwner)
+ }
+ if childPriority < 3 {
+ t.Fatalf("chat retry must be bumped above fresh chat priority (2); got %d", childPriority)
+ }
+ if childStatus != "queued" {
+ t.Fatalf("retry child must be queued, got %q", childStatus)
+ }
+ // The root direct task starts at attempt 1, so its first retry is attempt 2.
+ var rootAttempt int
+ if err := testPool.QueryRow(ctx, `SELECT attempt FROM agent_task_queue WHERE id = $1`, rootID).Scan(&rootAttempt); err != nil {
+ t.Fatalf("read root attempt: %v", err)
+ }
+ if childAttempt != rootAttempt+1 {
+ t.Fatalf("retry child attempt must be root+1 (%d), got %d", rootAttempt+1, childAttempt)
+ }
+
+ // The child reads the same input batch: the root's user message.
+ owned, err := testHandler.Queries.ListChatInputMessages(ctx, parseUUID(childOwner))
+ if err != nil {
+ t.Fatalf("list child owned input: %v", err)
+ }
+ if len(owned) != 1 || owned[0].Content != "root question" {
+ t.Fatalf("retry child must read the root input batch; got %+v", msgContents(owned))
+ }
+}
+
+// ---- helpers ----
+
+func msgContents(msgs []db.ChatMessage) []string {
+ out := make([]string, 0, len(msgs))
+ for _, m := range msgs {
+ out = append(out, m.Content)
+ }
+ return out
+}
+
+func assistantRows(t *testing.T, ctx context.Context, sessionID string) []db.ChatMessage {
+ t.Helper()
+ all, err := testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
+ if err != nil {
+ t.Fatalf("list chat messages: %v", err)
+ }
+ var out []db.ChatMessage
+ for _, m := range all {
+ if m.Role == "assistant" {
+ out = append(out, m)
+ }
+ }
+ return out
+}
+
+func assertTaskInputOwner(t *testing.T, ctx context.Context, taskID, wantOwner string) {
+ t.Helper()
+ var owner string
+ if err := testPool.QueryRow(ctx, `SELECT chat_input_task_id FROM agent_task_queue WHERE id = $1`, taskID).Scan(&owner); err != nil {
+ t.Fatalf("read chat_input_task_id: %v", err)
+ }
+ if owner != wantOwner {
+ t.Fatalf("task %s input owner = %s, want %s", taskID, owner, wantOwner)
+ }
+}
+
+func assertTaskStatus(t *testing.T, ctx context.Context, taskID, want string) {
+ t.Helper()
+ var status string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {
+ t.Fatalf("read task status: %v", err)
+ }
+ if status != want {
+ t.Fatalf("task %s status = %q, want %q", taskID, status, want)
+ }
+}
+
+func assertNoRetryChild(t *testing.T, ctx context.Context, taskID string) {
+ t.Helper()
+ var n int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE parent_task_id = $1`, taskID).Scan(&n); err != nil {
+ t.Fatalf("count retry children: %v", err)
+ }
+ if n != 0 {
+ t.Fatalf("expected no retry child for a completed no_response turn, got %d", n)
+ }
+}
+
+// insertChannelChatTask creates a running chat task with chat_input_task_id NULL
+// — the legacy/channel (Slack/Lark) shape — directly, bypassing the task-owned
+// direct-send path.
+func insertChannelChatTask(t *testing.T, ctx context.Context, agentID, runtimeID, sessionID string) string {
+ t.Helper()
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority, started_at, dispatched_at)
+ VALUES ($1, $2, $3, 'running', 2, now(), now())
+ RETURNING id
+ `, agentID, runtimeID, sessionID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create channel chat task: %v", err)
+ }
+ return taskID
+}
+
+// TestCompleteTask_ChannelEmptyOutputWritesNoRow pins the MUL-4351 review fix:
+// a legacy/channel task (chat_input_task_id NULL) that completes with empty
+// output must NOT write an assistant row — so chat:done carries empty content
+// and the Slack/Lark outbound keeps silently dropping it. The no_response
+// fallback body must never reach an external channel. A non-empty channel
+// completion still writes an ordinary message.
+func TestCompleteTask_ChannelEmptyOutputWritesNoRow(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "channel-like chat")
+
+ // Empty output → no row at all.
+ emptyTask := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", ""); err != nil {
+ t.Fatalf("complete channel task (empty): %v", err)
+ }
+ if rows := assistantRows(t, ctx, sessionID); len(rows) != 0 {
+ t.Fatalf("channel empty completion must write NO assistant row (Slack/Lark silent-drop), got %d", len(rows))
+ }
+
+ // Non-empty output → one ordinary message (kind 'message', not no_response).
+ textTask := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "channel reply"), "", ""); err != nil {
+ t.Fatalf("complete channel task (text): %v", err)
+ }
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 {
+ t.Fatalf("channel non-empty completion must write exactly one message, got %d", len(rows))
+ }
+ if rows[0].MessageKind != protocol.ChatMessageKindMessage || rows[0].Content != "channel reply" {
+ t.Fatalf("channel message = kind %q content %q, want message/'channel reply'", rows[0].MessageKind, rows[0].Content)
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 02d55a57a3..293ef10d5f 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1899,43 +1899,83 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
}
}
}
- // Build the chat prompt from EVERY user message that has arrived
- // since the agent's last reply — not just the most recent one. A
- // short-window debounce (MUL-2968) can land several user messages
- // before a single run fires; the agent resumes its prior session
- // and only learns of new input through resp.ChatMessage, so
- // delivering just the latest message would silently drop the
- // earlier ones (e.g. "看上海天气" then "还有青岛" → only Qingdao
- // answered). The unanswered set is the trailing run of user
- // messages after the last assistant message (every completed or
- // failed run writes an assistant row, so that anchor advances each
- // turn). Attachments are collected from each included message so
- // the agent can `multica attachment download <id>` — the markdown
- // URL alone is signed and 30-min expiring on the private CDN.
- if msgs, err := h.Queries.ListChatMessages(r.Context(), cs.ID); err == nil && len(msgs) > 0 {
- unanswered := trailingUserMessages(msgs)
- parts := make([]string, 0, len(unanswered))
- for _, m := range unanswered {
- if strings.TrimSpace(m.Content) != "" {
- parts = append(parts, m.Content)
- }
- if atts, attErr := h.Queries.ListAttachmentsByChatMessage(r.Context(), db.ListAttachmentsByChatMessageParams{
- ChatMessageID: m.ID,
- WorkspaceID: parseUUID(resp.WorkspaceID),
- }); attErr == nil && len(atts) > 0 {
- for _, a := range atts {
- resp.ChatMessageAttachments = append(resp.ChatMessageAttachments, ChatAttachmentMeta{
- ID: uuidToString(a.ID),
- Filename: a.Filename,
- ContentType: a.ContentType,
- })
- }
+ // Resolve the user-message input batch for this run. A task-owned
+ // direct-chat task (chat_input_task_id set, MUL-4351) reads exactly
+ // the user messages tagged with its own input owner, so a message
+ // that arrived after this turn was sealed can never be absorbed here.
+ // Legacy and channel (Slack/Lark) tasks carry a NULL owner and keep
+ // the trailing-message selector — the run of user messages after the
+ // last assistant row, which also covers a debounced burst (MUL-2968:
+ // "看上海天气" then "还有青岛" must both be delivered) — so a rolling
+ // deploy never replays their history. Attachments are collected per
+ // included message so the agent can `multica attachment download <id>`
+ // (the inline markdown URL is signed + 30-min expiring on the CDN).
+ var unanswered []db.ChatMessage
+ var inputLoadErr error
+ if task.ChatInputTaskID.Valid {
+ unanswered, inputLoadErr = h.Queries.ListChatInputMessages(r.Context(), task.ChatInputTaskID)
+ } else if msgs, err := h.Queries.ListChatMessages(r.Context(), cs.ID); err == nil {
+ unanswered = trailingUserMessages(msgs)
+ } else {
+ inputLoadErr = err
+ }
+ // A read failure must NOT masquerade as "zero input". Preserve the
+ // just-dispatched task (the stale-dispatched reclaim redelivers it)
+ // and reject the claim with 5xx, rather than cancelling a valid direct
+ // task on a transient DB error (MUL-4351 review).
+ if inputLoadErr != nil {
+ outcome = "error_chat_input_load"
+ slog.Error("chat claim: load chat input messages failed; preserving task for redelivery",
+ "task_id", uuidToString(task.ID),
+ "chat_session_id", uuidToString(cs.ID),
+ "error", inputLoadErr)
+ writeError(w, http.StatusInternalServerError, "failed to load chat input")
+ return
+ }
+
+ parts := make([]string, 0, len(unanswered))
+ for _, m := range unanswered {
+ if strings.TrimSpace(m.Content) != "" {
+ parts = append(parts, m.Content)
+ }
+ if atts, attErr := h.Queries.ListAttachmentsByChatMessage(r.Context(), db.ListAttachmentsByChatMessageParams{
+ ChatMessageID: m.ID,
+ WorkspaceID: parseUUID(resp.WorkspaceID),
+ }); attErr == nil && len(atts) > 0 {
+ for _, a := range atts {
+ resp.ChatMessageAttachments = append(resp.ChatMessageAttachments, ChatAttachmentMeta{
+ ID: uuidToString(a.ID),
+ Filename: a.Filename,
+ ContentType: a.ContentType,
+ })
}
}
- resp.ChatMessage = strings.Join(parts, "\n\n")
- if strings.TrimSpace(resp.ThreadName) == "" {
- resp.ThreadName = resp.ChatMessage
+ }
+ resp.ChatMessage = strings.Join(parts, "\n\n")
+
+ // Fail closed: a task-owned direct task that resolves to no user text
+ // (and is not the agent's proactive intro) must never dispatch an
+ // empty prompt. The send path creates the owning user message in the
+ // same transaction as the task, so this only fires on genuinely
+ // corrupt state — cancel the just-dispatched task and reject the claim
+ // rather than run the agent with nothing to answer (MUL-4351).
+ if task.ChatInputTaskID.Valid && !resp.ChatIntro && strings.TrimSpace(resp.ChatMessage) == "" {
+ outcome = "error_empty_chat_input"
+ slog.Error("chat claim: task-owned direct task has no user input; cancelling",
+ "task_id", uuidToString(task.ID),
+ "chat_session_id", uuidToString(cs.ID),
+ "chat_input_task_id", uuidToString(task.ChatInputTaskID),
+ )
+ if _, cerr := h.TaskService.CancelTask(r.Context(), task.ID); cerr != nil {
+ slog.Error("chat claim: cancel after empty input failed",
+ "task_id", uuidToString(task.ID), "error", cerr)
}
+ writeError(w, http.StatusInternalServerError, "chat task has no user input")
+ return
+ }
+
+ if strings.TrimSpace(resp.ThreadName) == "" && resp.ChatMessage != "" {
+ resp.ThreadName = resp.ChatMessage
}
}
}
@@ -2491,8 +2531,13 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
result, _ := json.Marshal(req)
task, err := h.TaskService.CompleteTask(r.Context(), parseUUID(taskID), result, req.SessionID, req.WorkDir)
if err != nil {
+ // A CompleteTask error is an infrastructure failure (transaction /
+ // assistant-outcome write), not a bad request: an already-finalized
+ // callback is treated as idempotent success and returns no error. Return
+ // 5xx so the daemon retries the terminal callback and the completion —
+ // including the single chat outcome row — lands exactly once (MUL-4351).
slog.Warn("complete task failed", "task_id", taskID, "error", err)
- writeError(w, http.StatusBadRequest, err.Error())
+ writeError(w, http.StatusInternalServerError, err.Error())
return
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index dfcf99cb21..89b2d293ac 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1113,6 +1113,105 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
return task, nil
}
+// DirectChatSendResult carries the rows a transactional direct-chat send
+// persisted, so the handler can broadcast the user message and shape its
+// response without re-reading them.
+type DirectChatSendResult struct {
+ Task db.AgentTaskQueue
+ Message db.ChatMessage
+ BoundAttachmentIDs []pgtype.UUID
+}
+
+// SendDirectChatMessage atomically persists one web/mobile direct-chat turn:
+// the owning task (which claims its own input batch via chat_input_task_id), the
+// user message bound to that task, any attachment bindings, and the session
+// touch all commit together (MUL-4351). The daemon is only notified after the
+// commit, so it can never observe a message without a task or a task without its
+// input owner — and a later claim reads exactly this task's user messages
+// instead of scanning trailing history.
+//
+// The caller must have already gated the session and preflighted the agent
+// (archived / no-runtime), passing the loaded agent in; this method trusts those
+// checks and does no further agent validation.
+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)
+
+ var out DirectChatSendResult
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ task, err := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{
+ AgentID: session.AgentID,
+ RuntimeID: agent.RuntimeID,
+ Priority: 2, // medium priority for chat; matches EnqueueChatTask
+ ChatSessionID: session.ID,
+ InitiatorUserID: initiatorUserID,
+ OriginatorUserID: initiatorUserID,
+ ForceFreshSession: pgtype.Bool{Bool: false, Valid: true},
+ RuntimeMcpOverlay: overlay.Overlay,
+ RuntimeConnectedApps: overlay.ConnectedApps,
+ })
+ if err != nil {
+ return fmt.Errorf("create direct chat task: %w", err)
+ }
+ // Claim this task's own input batch (chat_input_task_id = id) in the same
+ // transaction, before the user message is written with task_id = task.id.
+ task, err = qtx.SetChatTaskInputOwnerSelf(ctx, task.ID)
+ if err != nil {
+ return fmt.Errorf("stamp direct chat input owner: %w", err)
+ }
+ out.Task = task
+
+ // Create the user message already owned by this task (task_id = task.id),
+ // so it belongs to this immutable input batch the instant it exists.
+ msg, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ChatSessionID: session.ID,
+ Role: "user",
+ Content: content,
+ TaskID: task.ID,
+ })
+ if err != nil {
+ return fmt.Errorf("create user chat message: %w", err)
+ }
+ out.Message = msg
+
+ if len(attachmentIDs) > 0 {
+ bound, err := qtx.LinkAttachmentsToChatMessage(ctx, db.LinkAttachmentsToChatMessageParams{
+ ChatMessageID: msg.ID,
+ ChatSessionID: session.ID,
+ WorkspaceID: session.WorkspaceID,
+ UploaderType: uploaderType,
+ UploaderID: uploaderID,
+ AttachmentIds: attachmentIDs,
+ })
+ if err != nil {
+ return fmt.Errorf("link chat attachments: %w", err)
+ }
+ out.BoundAttachmentIDs = bound
+ }
+
+ if err := qtx.TouchChatSession(ctx, session.ID); err != nil {
+ return fmt.Errorf("touch chat session: %w", err)
+ }
+ return nil
+ }); err != nil {
+ slog.Error("direct chat send failed",
+ "chat_session_id", util.UUIDToString(session.ID),
+ "agent_id", util.UUIDToString(session.AgentID),
+ "error", err)
+ return nil, err
+ }
+
+ slog.Info("direct chat task enqueued",
+ "task_id", util.UUIDToString(out.Task.ID),
+ "chat_session_id", util.UUIDToString(session.ID),
+ "agent_id", util.UUIDToString(session.AgentID))
+ // Notify only after commit. See EnqueueTaskForIssue for ordering rationale.
+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, out.Task)
+ s.NotifyTaskEnqueued(ctx, out.Task)
+ return &out, nil
+}
+
// CancelTasksForIssue cancels every active task on the issue, reconciles each
// affected agent's status, and broadcasts task:cancelled events so frontends
// clear their live cards.
@@ -1718,6 +1817,10 @@ func (s *TaskService) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID
// causing the new task to resume against a stale (or NULL) session.
func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, result []byte, sessionID, workDir string) (*db.AgentTaskQueue, error) {
var task db.AgentTaskQueue
+ // chatAssistantMsg is the single assistant outcome row written for a chat
+ // task inside the completion transaction below. It is broadcast (chat:done)
+ // only after the transaction commits.
+ var chatAssistantMsg *db.ChatMessage
if err := s.runInTx(ctx, func(qtx *db.Queries) error {
t, err := qtx.CompleteAgentTask(ctx, db.CompleteAgentTaskParams{
ID: taskID,
@@ -1749,6 +1852,19 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
}); err != nil {
return fmt.Errorf("update chat session resume pointer: %w", err)
}
+
+ // Write the assistant outcome in the SAME transaction as the status
+ // flip and resume-pointer update (MUL-4351). For a task-owned direct
+ // task this is exactly one row (message or no_response); for a
+ // legacy/channel task an empty output writes no row (see
+ // writeChatCompletionOutcome). Failing here rolls the whole completion
+ // back so the daemon retries the terminal callback, and the status CAS
+ // above guarantees a replay can't write a second row.
+ msg, err := s.writeChatCompletionOutcome(ctx, qtx, t, result)
+ if err != nil {
+ return fmt.Errorf("write chat assistant outcome: %w", err)
+ }
+ chatAssistantMsg = msg
}
return nil
}); err != nil {
@@ -1841,32 +1957,14 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
s.notifyQuickCreateCompleted(ctx, task, qc)
}
- // For chat tasks, save assistant reply and broadcast chat:done. The
- // resume pointer was already persisted inside the transaction above.
+ // For chat tasks, broadcast chat:done AFTER commit. The single assistant
+ // outcome row (message or no_response) and the resume pointer were already
+ // persisted inside the transaction above. Unread is derived from the read
+ // 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 {
- var assistantMsg *db.ChatMessage
- var payload protocol.TaskCompletedPayload
- if err := json.Unmarshal(result, &payload); err == nil && payload.Output != "" {
- // Same unescape as the issue-comment path above: literal `\n` from
- // agent stdout becomes a real newline so the chat panel renders
- // paragraph breaks instead of one wall of prose.
- body := util.UnescapeBackslashEscapes(payload.Output)
- row, err := s.Queries.CreateChatMessage(ctx, db.CreateChatMessageParams{
- ChatSessionID: task.ChatSessionID,
- Role: "assistant",
- Content: redact.Text(body),
- TaskID: task.ID,
- ElapsedMs: computeChatElapsedMs(task),
- })
- if err != nil {
- slog.Error("failed to save assistant chat message", "task_id", util.UUIDToString(task.ID), "error", err)
- } else {
- assistantMsg = &row
- // Unread is derived from the read cursor (chat_session.last_read_at)
- // vs the assistant messages after it — no per-reply stamping needed.
- }
- }
- s.broadcastChatDone(ctx, task, assistantMsg)
+ s.broadcastChatDone(ctx, task, chatAssistantMsg)
}
// Reconcile agent status
@@ -1878,6 +1976,66 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
return &task, nil
}
+// chatNoResponseFallback is the non-empty English body stored on a no_response
+// assistant row. New clients render a localized "no text reply this turn"
+// message keyed on message_kind='no_response'; older clients that ignore
+// message_kind still show this text instead of an empty bubble (MUL-4351).
+const chatNoResponseFallback = "The agent finished this turn without a text reply."
+
+// writeChatCompletionOutcome writes the assistant chat_message outcome for a
+// completed chat task inside the caller's completion transaction, returning the
+// row (nil when none is written).
+//
+// Task-owned direct (web/mobile) tasks — chat_input_task_id set — get the
+// explicit single-outcome contract: a non-empty final output becomes an ordinary
+// assistant message, and an empty/whitespace output becomes a visible
+// no_response outcome carrying a non-empty English fallback body. It never
+// auto-retries: an empty output is a legitimate terminal result (a tool-only
+// turn) and re-running it would repeat side effects already performed.
+//
+// Legacy and channel (Slack/Lark) tasks — chat_input_task_id NULL — keep the
+// prior behavior: a non-empty output writes an ordinary assistant message, but
+// an EMPTY output writes NO row, so chat:done carries empty content and the
+// channel outbound silently drops it. This preserves Slack/Lark empty-completion
+// semantics unchanged (MUL-4351 review): the no_response fallback body must never
+// be pushed to an external channel.
+func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Queries, task db.AgentTaskQueue, result []byte) (*db.ChatMessage, error) {
+ // result is the daemon request re-marshalled by the handler, so it is always
+ // valid JSON; an empty Output is the only case this branch cares about.
+ var payload protocol.TaskCompletedPayload
+ _ = json.Unmarshal(result, &payload)
+ // Same unescape as the issue-comment path: literal `\n` from agent stdout
+ // becomes a real newline so the chat panel renders paragraph breaks.
+ body := util.UnescapeBackslashEscapes(payload.Output)
+ isEmpty := strings.TrimSpace(body) == ""
+
+ // Channel/legacy empty completion: emit no assistant row, only an empty
+ // chat:done for typing/lifecycle. Keeps the Slack/Lark silent-drop path.
+ if isEmpty && !task.ChatInputTaskID.Valid {
+ return nil, nil
+ }
+
+ params := db.CreateChatMessageParams{
+ ChatSessionID: task.ChatSessionID,
+ Role: "assistant",
+ TaskID: task.ID,
+ ElapsedMs: computeChatElapsedMs(task),
+ }
+ if isEmpty {
+ // Task-owned direct task: explicit, visible no_response outcome.
+ params.Content = chatNoResponseFallback
+ params.MessageKind = pgtype.Text{String: protocol.ChatMessageKindNoResponse, Valid: true}
+ } else {
+ params.Content = redact.Text(body)
+ // message_kind left NULL → COALESCE defaults to 'message'.
+ }
+ row, err := qtx.CreateChatMessage(ctx, params)
+ if err != nil {
+ return nil, err
+ }
+ return &row, nil
+}
+
// FailTask marks a task as failed.
// Issue status is NOT changed here — the agent manages it via the CLI.
//
@@ -1905,7 +2063,38 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
if failureReason == "" {
failureReason = taskfailure.Classify(errMsg).String()
}
+
+ // Pre-compute the auto-retry so the retry child can be created inside the
+ // SAME transaction as the fail (MUL-4351). Doing it atomically closes the
+ // window between the fail committing and the retry appearing during which a
+ // newer chat task could claim the now-idle session and jump ahead of the
+ // retry. The overlay build can do network I/O (Composio), so we resolve it
+ // here — before the transaction — and only for retryable failures, so the
+ // common agent_error path skips this work entirely.
+ var (
+ wantRetry bool
+ retryOverlay runtimeMCPOverlayData
+ )
+ if retryableReasons[failureReason] {
+ if parent, perr := s.Queries.GetAgentTask(ctx, taskID); perr != nil {
+ slog.Warn("fail task auto-retry: load parent failed",
+ "task_id", util.UUIDToString(taskID), "error", perr)
+ } else if retryEligible(failureReason, parent) {
+ wantRetry = true
+ if agent, aerr := s.Queries.GetAgent(ctx, parent.AgentID); aerr != nil {
+ // Best-effort: a missing overlay is not retry-fatal — the child
+ // simply runs without the Composio overlay.
+ slog.Warn("fail task auto-retry: load agent for overlay failed",
+ "task_id", util.UUIDToString(taskID),
+ "agent_id", util.UUIDToString(parent.AgentID), "error", aerr)
+ } else {
+ retryOverlay = s.buildRuntimeMCPOverlay(ctx, parent.OriginatorUserID, agent)
+ }
+ }
+ }
+
var task db.AgentTaskQueue
+ var retried *db.AgentTaskQueue
if err := s.runInTx(ctx, func(qtx *db.Queries) error {
t, err := qtx.FailAgentTask(ctx, db.FailAgentTaskParams{
ID: taskID,
@@ -1939,6 +2128,21 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
return fmt.Errorf("update chat session resume pointer: %w", err)
}
}
+
+ // Create the retry child atomically with the fail. CreateRetryTask reads
+ // the just-failed parent row (same tx), so it inherits chat_input_task_id
+ // and the bumped chat-retry priority; broadcast/notify happen after commit.
+ if wantRetry {
+ child, cerr := qtx.CreateRetryTask(ctx, db.CreateRetryTaskParams{
+ ID: taskID,
+ RuntimeMcpOverlay: retryOverlay.Overlay,
+ RuntimeConnectedApps: retryOverlay.ConnectedApps,
+ })
+ if cerr != nil {
+ return fmt.Errorf("create retry task: %w", cerr)
+ }
+ retried = &child
+ }
return nil
}); err != nil {
if existing, lookupErr := s.Queries.GetAgentTask(ctx, taskID); lookupErr == nil {
@@ -1970,10 +2174,21 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
slog.Warn("task failed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID), "error", errMsg, "failure_reason", failureReason)
s.captureTaskFailed(ctx, task)
- // Auto-retry eligible failures (orphan, timeout, runtime_offline,
- // runtime_recovery). The helper itself enforces attempt < max_attempts
- // and only triggers for issue/chat tasks.
- retried, _ := s.MaybeRetryFailedTask(ctx, task)
+ // The auto-retry child (if any) was created inside the transaction above so
+ // no newer chat task could jump ahead of it. Surface it now: broadcast
+ // queued first, then notify the daemon — see EnqueueTaskForIssue for the
+ // ordering rationale.
+ if retried != nil {
+ slog.Info("task auto-retry enqueued",
+ "parent_task_id", util.UUIDToString(task.ID),
+ "child_task_id", util.UUIDToString(retried.ID),
+ "reason", failureReason,
+ "attempt", retried.Attempt,
+ "max_attempts", retried.MaxAttempts,
+ )
+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, *retried)
+ s.NotifyTaskEnqueued(ctx, *retried)
+ }
// Skip the per-failure system comment when we'll immediately retry —
// the new task will surface its own status to the user, and we don't
@@ -2044,6 +2259,18 @@ func resumeUnsafeFailureReason(reason string) bool {
}
}
+// retryEligible reports whether a failed task qualifies for an automatic retry
+// attempt: an infrastructure-shaped failure_reason, remaining attempt budget,
+// not an autopilot run, and linked to an issue or chat session. Shared by
+// FailTask's in-transaction retry and the orphan sweeper's MaybeRetryFailedTask
+// so both agree on which failures re-run.
+func retryEligible(failureReason string, t db.AgentTaskQueue) bool {
+ return retryableReasons[failureReason] &&
+ t.Attempt < t.MaxAttempts &&
+ !t.AutopilotRunID.Valid &&
+ (t.IssueID.Valid || t.ChatSessionID.Valid)
+}
+
// MaybeRetryFailedTask spawns a fresh queued attempt for a recently-failed
// task when the failure was infrastructure-shaped (daemon crash, runtime
// went offline, dispatch/run timeout) and the task hasn't exhausted its
@@ -2073,11 +2300,10 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
)
return nil, nil
}
- if parent.AutopilotRunID.Valid {
- // Autopilot has its own retry semantics; do not double-trigger.
- return nil, nil
- }
- if !parent.IssueID.Valid && !parent.ChatSessionID.Valid {
+ // Autopilot has its own retry semantics (don't double-trigger) and a task
+ // with no issue/chat link has nowhere to report its retry — retryEligible
+ // covers both, keeping this sweeper path in sync with FailTask's in-tx retry.
+ if !retryEligible(reason, parent) {
return nil, nil
}
@@ -2781,6 +3007,7 @@ func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQu
if msg != nil {
payload.MessageID = util.UUIDToString(msg.ID)
payload.Content = msg.Content
+ payload.MessageKind = msg.MessageKind
if msg.CreatedAt.Valid {
payload.CreatedAt = msg.CreatedAt.Time.UTC().Format(time.RFC3339Nano)
}
diff --git a/server/migrations/158_agent_task_queue_chat_input_task_id.down.sql b/server/migrations/158_agent_task_queue_chat_input_task_id.down.sql
new file mode 100644
index 0000000000..4a4b3f3cac
--- /dev/null
+++ b/server/migrations/158_agent_task_queue_chat_input_task_id.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS chat_input_task_id;
diff --git a/server/migrations/158_agent_task_queue_chat_input_task_id.up.sql b/server/migrations/158_agent_task_queue_chat_input_task_id.up.sql
new file mode 100644
index 0000000000..8da776cfd4
--- /dev/null
+++ b/server/migrations/158_agent_task_queue_chat_input_task_id.up.sql
@@ -0,0 +1,17 @@
+-- Direct-chat input ownership (MUL-4351).
+--
+-- chat_input_task_id makes each web/mobile direct-chat task the immutable owner
+-- of the user-message batch it must consume. A fresh direct-send task sets this
+-- to its own id in the same transaction that creates the user message
+-- (chat_message.task_id = task.id), so a later claim loads exactly that batch
+-- instead of scanning "trailing user messages after the last assistant row".
+--
+-- An auto-retry child inherits its parent's chat_input_task_id, so the whole
+-- retry chain keeps consuming the original root input batch and never re-reads
+-- a message that arrived after the batch was sealed.
+--
+-- NULL means "legacy row or channel (Slack/Lark) task": those keep using the
+-- trailing-message selector, so a rolling deploy never replays channel history
+-- and pre-migration direct rows behave exactly as before. No FK / cascade — the
+-- application layer owns this reference, matching the repo's no-FK rule.
+ALTER TABLE agent_task_queue ADD COLUMN IF NOT EXISTS chat_input_task_id UUID;
diff --git a/server/migrations/159_chat_message_message_kind.down.sql b/server/migrations/159_chat_message_message_kind.down.sql
new file mode 100644
index 0000000000..8e491a8026
--- /dev/null
+++ b/server/migrations/159_chat_message_message_kind.down.sql
@@ -0,0 +1 @@
+ALTER TABLE chat_message DROP COLUMN IF EXISTS message_kind;
diff --git a/server/migrations/159_chat_message_message_kind.up.sql b/server/migrations/159_chat_message_message_kind.up.sql
new file mode 100644
index 0000000000..2b926523fc
--- /dev/null
+++ b/server/migrations/159_chat_message_message_kind.up.sql
@@ -0,0 +1,17 @@
+-- Explicit terminal outcome kind for chat messages (MUL-4351).
+--
+-- 'message' — an ordinary user/assistant message (the default; every
+-- existing row and every legacy client sees this).
+-- 'no_response' — the agent completed a direct-chat turn without any text
+-- reply. This is a visible, deliberate terminal outcome: the
+-- turn boundary is now owned by chat_input_task_id, not by the
+-- presence of an assistant row, so we no longer need to fake a
+-- blank bubble to advance the conversation. The frontend
+-- renders a localized "no text reply this turn" state while old
+-- clients fall back to the non-empty English content we still
+-- store on the row.
+--
+-- Additive and app-validated: no CHECK constraint / FK / cascade so new kinds
+-- can be introduced without a migration and unknown values degrade to 'message'
+-- on older readers.
+ALTER TABLE chat_message ADD COLUMN IF NOT EXISTS message_kind TEXT NOT NULL DEFAULT 'message';
diff --git a/server/migrations/160_chat_message_input_owner_index.down.sql b/server/migrations/160_chat_message_input_owner_index.down.sql
new file mode 100644
index 0000000000..0af49b9e6d
--- /dev/null
+++ b/server/migrations/160_chat_message_input_owner_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_chat_message_input_owner;
diff --git a/server/migrations/160_chat_message_input_owner_index.up.sql b/server/migrations/160_chat_message_input_owner_index.up.sql
new file mode 100644
index 0000000000..0ad7db07ba
--- /dev/null
+++ b/server/migrations/160_chat_message_input_owner_index.up.sql
@@ -0,0 +1,16 @@
+-- Index the task-owned input-batch lookup added in MUL-4351.
+--
+-- The direct-chat claim path loads its input with
+-- SELECT * FROM chat_message WHERE task_id = $1 AND role = 'user' ORDER BY created_at
+-- (ListChatInputMessages), keyed on the task's chat_input_task_id. Before this
+-- there was no index on chat_message.task_id at all (only the
+-- chat_session_id/created_at index from migration 033), so the lookup would seq
+-- scan. This partial index covers exactly the user-message batch reads and the
+-- existing task_id-keyed writes (LinkChatMessageToTask,
+-- DeleteUserChatMessageByTask) without indexing assistant rows.
+--
+-- Single-statement migration: CREATE INDEX CONCURRENTLY cannot run inside a
+-- transaction or a multi-command string.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_chat_message_input_owner
+ ON chat_message (task_id, created_at)
+ WHERE role = 'user';
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index ac81712c63..50f63139c5 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -184,7 +184,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -228,6 +228,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -236,7 +237,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -291,6 +292,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -306,7 +308,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
// Cancels active tasks belonging to a chat session. Called from
@@ -361,6 +363,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -376,7 +379,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -431,6 +434,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -446,7 +450,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -505,6 +509,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -521,7 +526,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -575,6 +580,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -595,9 +601,9 @@ WITH cancelled AS (
AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
AND primary_task.issue_id = $1
AND primary_task.agent_id = $2
- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids
+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id
)
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids FROM cancelled
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM cancelled
`
type CancelDeferredEscalationsForIssueAgentParams struct {
@@ -643,6 +649,7 @@ type CancelDeferredEscalationsForIssueAgentRow struct {
RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
+ ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
}
func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
@@ -692,6 +699,7 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -708,7 +716,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE escalation_for_task_id = $1
AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -758,6 +766,7 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -798,7 +807,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type ClaimAgentTaskParams struct {
@@ -856,6 +865,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -987,7 +997,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :one
UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4, prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type CompleteAgentTaskParams struct {
@@ -1043,6 +1053,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -1170,7 +1181,7 @@ VALUES (
$14,
$15
)
-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
+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
`
type CreateAgentTaskParams struct {
@@ -1255,6 +1266,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -1273,7 +1285,7 @@ VALUES (
$9,
$10
)
-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
+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
`
type CreateDeferredAgentTaskParams struct {
@@ -1344,6 +1356,7 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -1359,7 +1372,7 @@ VALUES (
$6,
$7
)
-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
+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
`
type CreateQuickCreateTaskParams struct {
@@ -1424,6 +1437,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -1434,11 +1448,14 @@ INSERT INTO agent_task_queue (
status, priority, trigger_comment_id, coalesced_comment_ids, trigger_summary, context,
session_id, work_dir,
attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,
- squad_id, originator_user_id, runtime_mcp_overlay, runtime_connected_apps
+ squad_id, originator_user_id, runtime_mcp_overlay, runtime_connected_apps,
+ chat_input_task_id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
- 'queued', p.priority, p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
+ 'queued',
+ CASE WHEN p.chat_session_id IS NOT NULL THEN GREATEST(p.priority, 3) ELSE p.priority END,
+ p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
p.attempt + 1, p.max_attempts, p.id,
@@ -1447,10 +1464,11 @@ SELECT
p.squad_id,
p.originator_user_id,
$2,
- $3
+ $3,
+ p.chat_input_task_id
FROM agent_task_queue p
WHERE p.id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type CreateRetryTaskParams struct {
@@ -1476,6 +1494,21 @@ type CreateRetryTaskParams struct {
// run has not changed. The Composio overlay follows the agent's invocation
// permission and uses the agent owner's connection (MUL-3963); originator is
// carried for A2A/audit, not as an originator == agent.owner_id gate.
+//
+// chat_input_task_id is inherited straight from the parent so the whole retry
+// chain keeps consuming the ORIGINAL root input batch (MUL-4351): the root
+// direct task set it to its own id, every descendant copies that value, and a
+// claim always reads the same user messages. A plain copy (not
+// COALESCE(parent.chat_input_task_id, parent.id)) is deliberate: legacy/channel
+// parents carry NULL and must stay NULL so their retries keep the trailing
+// selector — promoting a pre-migration NULL row to the task-owned path on retry
+// would risk replaying untagged history during a rolling deploy.
+//
+// Chat retries are queued at GREATEST(priority, 3) so a transiently-failed
+// earlier turn is re-claimed ahead of any fresh chat task (priority 2) the user
+// queued while the failing turn was still running — the retry continues the
+// older turn first. Combined with creating the retry inside FailTask's
+// transaction, this leaves no window for a newer input task to jump ahead.
func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createRetryTask, arg.ID, arg.RuntimeMcpOverlay, arg.RuntimeConnectedApps)
var i AgentTaskQueue
@@ -1517,6 +1550,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -1540,7 +1574,7 @@ FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id
`
type ExpireStaleQueuedTasksParams struct {
@@ -1618,6 +1652,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -1636,7 +1671,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -1690,6 +1725,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -1704,7 +1740,7 @@ SET status = 'failed',
work_dir = COALESCE($5, work_dir),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type FailAgentTaskParams struct {
@@ -1771,6 +1807,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -1795,7 +1832,7 @@ WHERE (
AND r.last_seen_at >= now() - make_interval(secs => $3::double precision)
)
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type FailStaleTasksParams struct {
@@ -1888,6 +1925,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -2017,7 +2055,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM agent_task_queue
WHERE id = $1
`
@@ -2062,12 +2100,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -2125,6 +2164,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -2612,7 +2652,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -2669,6 +2709,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -2681,7 +2722,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -2733,6 +2774,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -2847,7 +2889,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -2899,6 +2941,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -2911,7 +2954,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -2971,6 +3014,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -2983,7 +3027,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -3035,6 +3079,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -3047,15 +3092,15 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids FROM (
- SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids
+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id FROM (
+ SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -3129,6 +3174,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -3146,7 +3192,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
WHERE id = $1 AND status = 'dispatched'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -3205,6 +3251,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -3311,7 +3358,7 @@ SET status = 'queued'
WHERE runtime_id = $1
AND status = 'deferred'
AND fire_at <= now()
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -3361,6 +3408,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtime
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -3387,7 +3435,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -3442,6 +3490,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -3455,7 +3504,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -3511,6 +3560,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -3576,7 +3626,7 @@ WHERE id = $1
AND status = 'dispatched'
AND started_at IS NULL
AND dispatched_at = $3
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -3631,6 +3681,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -3727,7 +3778,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -3777,6 +3828,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 1155d8f94e..fb91cbaa74 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -222,7 +222,7 @@ const createAutopilotTask = `-- name: CreateAutopilotTask :one
INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)
VALUES ($1, $2, NULL, 'queued', $3, $4, $5)
-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
+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
`
type CreateAutopilotTaskParams struct {
@@ -283,6 +283,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 7b5f0a9f00..95b68d871e 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -32,9 +32,9 @@ func (q *Queries) ChatSessionHasUserMessage(ctx context.Context, chatSessionID p
}
const createChatMessage = `-- name: CreateChatMessage :one
-INSERT INTO chat_message (chat_session_id, role, content, task_id, failure_reason, elapsed_ms)
-VALUES ($1, $2, $3, $4, $5, $6)
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms
+INSERT INTO chat_message (chat_session_id, role, content, task_id, failure_reason, elapsed_ms, message_kind)
+VALUES ($1, $2, $3, $4, $5, $6, COALESCE($7::text, 'message'))
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind
`
type CreateChatMessageParams struct {
@@ -44,8 +44,12 @@ type CreateChatMessageParams struct {
TaskID pgtype.UUID `json:"task_id"`
FailureReason pgtype.Text `json:"failure_reason"`
ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
+ MessageKind pgtype.Text `json:"message_kind"`
}
+// message_kind defaults to 'message' via COALESCE so every existing caller
+// (which omits it) keeps writing ordinary messages; the empty-reply path passes
+// 'no_response' to mark a visible turn with no text output (MUL-4351).
func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessageParams) (ChatMessage, error) {
row := q.db.QueryRow(ctx, createChatMessage,
arg.ChatSessionID,
@@ -54,6 +58,7 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
arg.TaskID,
arg.FailureReason,
arg.ElapsedMs,
+ arg.MessageKind,
)
var i ChatMessage
err := row.Scan(
@@ -65,6 +70,7 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
&i.CreatedAt,
&i.FailureReason,
&i.ElapsedMs,
+ &i.MessageKind,
)
return i, err
}
@@ -125,7 +131,7 @@ VALUES (
$8,
$9
)
-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
+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
`
type CreateChatTaskParams struct {
@@ -191,6 +197,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
)
return i, err
}
@@ -220,7 +227,7 @@ func (q *Queries) DeleteChatSession(ctx context.Context, arg DeleteChatSessionPa
const deleteUserChatMessageByTask = `-- name: DeleteUserChatMessageByTask :one
DELETE FROM chat_message
WHERE task_id = $1 AND role = 'user'
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind
`
func (q *Queries) DeleteUserChatMessageByTask(ctx context.Context, taskID pgtype.UUID) (ChatMessage, error) {
@@ -235,12 +242,13 @@ func (q *Queries) DeleteUserChatMessageByTask(ctx context.Context, taskID pgtype
&i.CreatedAt,
&i.FailureReason,
&i.ElapsedMs,
+ &i.MessageKind,
)
return i, err
}
const getChatMessage = `-- name: GetChatMessage :one
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
WHERE id = $1
`
@@ -256,6 +264,7 @@ func (q *Queries) GetChatMessage(ctx context.Context, id pgtype.UUID) (ChatMessa
&i.CreatedAt,
&i.FailureReason,
&i.ElapsedMs,
+ &i.MessageKind,
)
return i, err
}
@@ -358,7 +367,7 @@ func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgty
}
const getMostRecentUserChatMessage = `-- name: GetMostRecentUserChatMessage :one
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
WHERE chat_session_id = $1 AND role = 'user'
ORDER BY created_at DESC
LIMIT 1
@@ -381,6 +390,7 @@ func (q *Queries) GetMostRecentUserChatMessage(ctx context.Context, chatSessionI
&i.CreatedAt,
&i.FailureReason,
&i.ElapsedMs,
+ &i.MessageKind,
)
return i, err
}
@@ -470,10 +480,11 @@ SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_
COALESCE(lm.content, '') AS last_message_content,
COALESCE(lm.role, '') AS last_message_role,
lm.created_at AS last_message_at,
- lm.failure_reason AS last_message_failure_reason
+ lm.failure_reason AS last_message_failure_reason,
+ COALESCE(lm.message_kind, '') AS last_message_kind
FROM chat_session cs
LEFT JOIN LATERAL (
- SELECT content, role, created_at, failure_reason
+ SELECT content, role, created_at, failure_reason, message_kind
FROM chat_message m
WHERE m.chat_session_id = cs.id
ORDER BY m.created_at DESC
@@ -509,6 +520,7 @@ type ListAllChatSessionsByCreatorRow struct {
LastMessageRole string `json:"last_message_role"`
LastMessageAt pgtype.Timestamptz `json:"last_message_at"`
LastMessageFailureReason pgtype.Text `json:"last_message_failure_reason"`
+ LastMessageKind string `json:"last_message_kind"`
}
func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllChatSessionsByCreatorParams) ([]ListAllChatSessionsByCreatorRow, error) {
@@ -541,6 +553,50 @@ func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllC
&i.LastMessageRole,
&i.LastMessageAt,
&i.LastMessageFailureReason,
+ &i.LastMessageKind,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listChatInputMessages = `-- name: ListChatInputMessages :many
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
+WHERE task_id = $1 AND role = 'user'
+ORDER BY created_at ASC, id ASC
+`
+
+// Loads the immutable user-message input batch owned by a direct-chat task.
+// The caller passes the task's chat_input_task_id (itself for an original send,
+// the root task for an auto-retry child), so a claim reads exactly the messages
+// the user sent for this turn — and never absorbs a message that arrived after
+// the batch was sealed, no matter what the assistant wrote or when. Only used
+// for new task-owned direct-chat tasks; legacy/channel (chat_input_task_id
+// NULL) tasks keep using ListChatMessages + trailingUserMessages.
+func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID) ([]ChatMessage, error) {
+ rows, err := q.db.Query(ctx, listChatInputMessages, taskID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ChatMessage{}
+ for rows.Next() {
+ var i ChatMessage
+ if err := rows.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.Role,
+ &i.Content,
+ &i.TaskID,
+ &i.CreatedAt,
+ &i.FailureReason,
+ &i.ElapsedMs,
+ &i.MessageKind,
); err != nil {
return nil, err
}
@@ -553,7 +609,7 @@ func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllC
}
const listChatMessages = `-- name: ListChatMessages :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
WHERE chat_session_id = $1
ORDER BY created_at ASC
`
@@ -576,6 +632,7 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI
&i.CreatedAt,
&i.FailureReason,
&i.ElapsedMs,
+ &i.MessageKind,
); err != nil {
return nil, err
}
@@ -588,7 +645,7 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI
}
const listChatMessagesPage = `-- name: ListChatMessagesPage :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
WHERE chat_session_id = $1
AND (
$3::timestamptz IS NULL
@@ -628,6 +685,7 @@ func (q *Queries) ListChatMessagesPage(ctx context.Context, arg ListChatMessages
&i.CreatedAt,
&i.FailureReason,
&i.ElapsedMs,
+ &i.MessageKind,
); err != nil {
return nil, err
}
@@ -648,10 +706,11 @@ SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_
COALESCE(lm.content, '') AS last_message_content,
COALESCE(lm.role, '') AS last_message_role,
lm.created_at AS last_message_at,
- lm.failure_reason AS last_message_failure_reason
+ lm.failure_reason AS last_message_failure_reason,
+ COALESCE(lm.message_kind, '') AS last_message_kind
FROM chat_session cs
LEFT JOIN LATERAL (
- SELECT content, role, created_at, failure_reason
+ SELECT content, role, created_at, failure_reason, message_kind
FROM chat_message m
WHERE m.chat_session_id = cs.id
ORDER BY m.created_at DESC
@@ -687,6 +746,7 @@ type ListChatSessionsByCreatorRow struct {
LastMessageRole string `json:"last_message_role"`
LastMessageAt pgtype.Timestamptz `json:"last_message_at"`
LastMessageFailureReason pgtype.Text `json:"last_message_failure_reason"`
+ LastMessageKind string `json:"last_message_kind"`
}
// IM-style list: each active session with its unread *count* (assistant
@@ -722,6 +782,7 @@ func (q *Queries) ListChatSessionsByCreator(ctx context.Context, arg ListChatSes
&i.LastMessageRole,
&i.LastMessageAt,
&i.LastMessageFailureReason,
+ &i.LastMessageKind,
); err != nil {
return nil, err
}
@@ -807,8 +868,9 @@ FOR UPDATE
// their FK check after we commit the delete.
func (q *Queries) LockChatSessionForDelete(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, lockChatSessionForDelete, id)
- err := row.Scan(&id)
- return id, err
+ var id_2 pgtype.UUID
+ err := row.Scan(&id_2)
+ return id_2, err
}
const markChatSessionRead = `-- name: MarkChatSessionRead :exec
@@ -902,6 +964,65 @@ func (q *Queries) SetChatSessionPinned(ctx context.Context, arg SetChatSessionPi
return i, err
}
+const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :one
+UPDATE agent_task_queue
+SET chat_input_task_id = id
+WHERE id = $1
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id
+`
+
+// Stamps a freshly-created direct-chat task as the owner of its own input batch
+// (chat_input_task_id = id), so a later claim loads exactly the user messages
+// tagged with this task id (ListChatInputMessages) rather than scanning trailing
+// history. Runs in the same transaction as CreateChatTask + the user message
+// insert on the direct-send path. Channel and legacy tasks skip this call and
+// keep chat_input_task_id NULL, so a rolling deploy never replays their history.
+func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, setChatTaskInputOwnerSelf, id)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ )
+ return i, err
+}
+
const touchChatSession = `-- name: TouchChatSession :exec
UPDATE chat_session SET updated_at = now()
WHERE id = $1
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 3e6b20b93f..515f5c6830 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -127,6 +127,7 @@ type AgentTaskQueue struct {
RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
DeliveredCommentIds []pgtype.UUID `json:"delivered_comment_ids"`
+ ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
}
type Attachment struct {
@@ -305,6 +306,7 @@ type ChatMessage struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
FailureReason pgtype.Text `json:"failure_reason"`
ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
+ MessageKind string `json:"message_kind"`
}
type ChatPinnedAgent struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 070087890f..bfe2ce0e54 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -85,6 +85,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
@@ -204,7 +205,7 @@ WHERE status IN ('dispatched', 'running', 'waiting_local_directory')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids
+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
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -257,6 +258,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.RuntimeConnectedApps,
&i.CoalescedCommentIds,
&i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 324bfa8f44..ac931eaf41 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -254,16 +254,34 @@ WHERE id = $1 AND issue_id IS NULL;
-- run has not changed. The Composio overlay follows the agent's invocation
-- permission and uses the agent owner's connection (MUL-3963); originator is
-- carried for A2A/audit, not as an originator == agent.owner_id gate.
+--
+-- chat_input_task_id is inherited straight from the parent so the whole retry
+-- chain keeps consuming the ORIGINAL root input batch (MUL-4351): the root
+-- direct task set it to its own id, every descendant copies that value, and a
+-- claim always reads the same user messages. A plain copy (not
+-- COALESCE(parent.chat_input_task_id, parent.id)) is deliberate: legacy/channel
+-- parents carry NULL and must stay NULL so their retries keep the trailing
+-- selector — promoting a pre-migration NULL row to the task-owned path on retry
+-- would risk replaying untagged history during a rolling deploy.
+--
+-- Chat retries are queued at GREATEST(priority, 3) so a transiently-failed
+-- earlier turn is re-claimed ahead of any fresh chat task (priority 2) the user
+-- queued while the failing turn was still running — the retry continues the
+-- older turn first. Combined with creating the retry inside FailTask's
+-- transaction, this leaves no window for a newer input task to jump ahead.
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
status, priority, trigger_comment_id, coalesced_comment_ids, trigger_summary, context,
session_id, work_dir,
attempt, max_attempts, parent_task_id, force_fresh_session, is_leader_task,
- squad_id, originator_user_id, runtime_mcp_overlay, runtime_connected_apps
+ squad_id, originator_user_id, runtime_mcp_overlay, runtime_connected_apps,
+ chat_input_task_id
)
SELECT
p.agent_id, p.runtime_id, p.issue_id, p.chat_session_id, p.autopilot_run_id,
- 'queued', p.priority, p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
+ 'queued',
+ CASE WHEN p.chat_session_id IS NOT NULL THEN GREATEST(p.priority, 3) ELSE p.priority END,
+ p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
p.attempt + 1, p.max_attempts, p.id,
@@ -272,7 +290,8 @@ SELECT
p.squad_id,
p.originator_user_id,
sqlc.narg(runtime_mcp_overlay),
- sqlc.narg(runtime_connected_apps)
+ sqlc.narg(runtime_connected_apps),
+ p.chat_input_task_id
FROM agent_task_queue p
WHERE p.id = $1
RETURNING *;
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 33903d2b5e..63f97b6a82 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -23,10 +23,11 @@ SELECT cs.*,
COALESCE(lm.content, '') AS last_message_content,
COALESCE(lm.role, '') AS last_message_role,
lm.created_at AS last_message_at,
- lm.failure_reason AS last_message_failure_reason
+ lm.failure_reason AS last_message_failure_reason,
+ COALESCE(lm.message_kind, '') AS last_message_kind
FROM chat_session cs
LEFT JOIN LATERAL (
- SELECT content, role, created_at, failure_reason
+ SELECT content, role, created_at, failure_reason, message_kind
FROM chat_message m
WHERE m.chat_session_id = cs.id
ORDER BY m.created_at DESC
@@ -44,10 +45,11 @@ SELECT cs.*,
COALESCE(lm.content, '') AS last_message_content,
COALESCE(lm.role, '') AS last_message_role,
lm.created_at AS last_message_at,
- lm.failure_reason AS last_message_failure_reason
+ lm.failure_reason AS last_message_failure_reason,
+ COALESCE(lm.message_kind, '') AS last_message_kind
FROM chat_session cs
LEFT JOIN LATERAL (
- SELECT content, role, created_at, failure_reason
+ SELECT content, role, created_at, failure_reason, message_kind
FROM chat_message m
WHERE m.chat_session_id = cs.id
ORDER BY m.created_at DESC
@@ -137,8 +139,11 @@ UPDATE chat_session SET updated_at = now()
WHERE id = $1;
-- name: CreateChatMessage :one
-INSERT INTO chat_message (chat_session_id, role, content, task_id, failure_reason, elapsed_ms)
-VALUES ($1, $2, $3, sqlc.narg(task_id), sqlc.narg(failure_reason), sqlc.narg(elapsed_ms))
+-- message_kind defaults to 'message' via COALESCE so every existing caller
+-- (which omits it) keeps writing ordinary messages; the empty-reply path passes
+-- 'no_response' to mark a visible turn with no text output (MUL-4351).
+INSERT INTO chat_message (chat_session_id, role, content, task_id, failure_reason, elapsed_ms, message_kind)
+VALUES ($1, $2, $3, sqlc.narg(task_id), sqlc.narg(failure_reason), sqlc.narg(elapsed_ms), COALESCE(sqlc.narg(message_kind)::text, 'message'))
RETURNING *;
-- name: LinkChatMessageToTask :exec
@@ -156,6 +161,18 @@ SELECT * FROM chat_message
WHERE chat_session_id = $1
ORDER BY created_at ASC;
+-- name: ListChatInputMessages :many
+-- Loads the immutable user-message input batch owned by a direct-chat task.
+-- The caller passes the task's chat_input_task_id (itself for an original send,
+-- the root task for an auto-retry child), so a claim reads exactly the messages
+-- the user sent for this turn — and never absorbs a message that arrived after
+-- the batch was sealed, no matter what the assistant wrote or when. Only used
+-- for new task-owned direct-chat tasks; legacy/channel (chat_input_task_id
+-- NULL) tasks keep using ListChatMessages + trailingUserMessages.
+SELECT * FROM chat_message
+WHERE task_id = $1 AND role = 'user'
+ORDER BY created_at ASC, id ASC;
+
-- name: ListChatMessagesPage :many
SELECT * FROM chat_message
WHERE chat_session_id = $1
@@ -185,6 +202,18 @@ VALUES (
)
RETURNING *;
+-- name: SetChatTaskInputOwnerSelf :one
+-- Stamps a freshly-created direct-chat task as the owner of its own input batch
+-- (chat_input_task_id = id), so a later claim loads exactly the user messages
+-- tagged with this task id (ListChatInputMessages) rather than scanning trailing
+-- history. Runs in the same transaction as CreateChatTask + the user message
+-- insert on the direct-send path. Channel and legacy tasks skip this call and
+-- keep chat_input_task_id NULL, so a rolling deploy never replays their history.
+UPDATE agent_task_queue
+SET chat_input_task_id = id
+WHERE id = $1
+RETURNING *;
+
-- name: GetLastChatTaskSession :one
-- Returns the most recent task in this chat session that managed to record a
-- session_id. Includes both completed and failed tasks: even a failed task
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 08e0f4c279..66e89fcdc2 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -89,11 +89,30 @@ type ChatMessagePayload struct {
CreatedAt string `json:"created_at"`
}
+// Chat message kinds (chat_message.message_kind). Additive: unknown values
+// degrade to ChatMessageKindMessage on older readers.
+const (
+ // ChatMessageKindMessage is an ordinary user/assistant message.
+ ChatMessageKindMessage = "message"
+ // ChatMessageKindNoResponse marks a direct-chat turn the agent completed
+ // without any text reply — a visible, deliberate terminal outcome rather
+ // than a silently-dropped turn (MUL-4351).
+ ChatMessageKindNoResponse = "no_response"
+)
+
// ChatDonePayload is broadcast when an agent finishes responding to a chat
// message. Carries the freshly-persisted assistant ChatMessage so the client
// can write it into the messages cache inline — avoids a refetch round-trip
// during the live-timeline → AssistantMessage handoff that previously caused
// a visible flicker (#2123).
+//
+// MessageKind is additive (MUL-4351): older clients ignore it and fall back to
+// the non-empty Content the server always sends, so a no_response turn still
+// renders a real bubble instead of an empty one. Because direct-chat completion
+// now always writes exactly one assistant row (message or no_response),
+// MessageID/Content/CreatedAt/ElapsedMs are always populated for direct chat —
+// the omitempty tags only elide fields for the legacy paths that broadcast
+// without a row.
type ChatDonePayload struct {
ChatSessionID string `json:"chat_session_id"`
TaskID string `json:"task_id"`
@@ -101,6 +120,7 @@ type ChatDonePayload struct {
Content string `json:"content,omitempty"`
ElapsedMs int64 `json:"elapsed_ms,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
+ MessageKind string `json:"message_kind,omitempty"`
}
// ChatSessionReadPayload is broadcast when the creator marks a session as read.