Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(chat): deliver every debounced user message to the agent (MUL-2968) (#3744)
Bohan Jiang9beb45b55bcb
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 30a4ce183a..a2d35a4eff 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1364,32 +1364,40 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {}}}- // Load the latest user message for the chat prompt, plus any- // attachments linked to that exact message. Without the structured- // attachment list the agent only sees the markdown URL in- // `ChatMessage` — fine for vision models inline but unusable when- // the agent wants to `multica attachment download <id>` (URL is- // signed and 30-min expiring on private CDN).+ // 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 {- for i := len(msgs) - 1; i >= 0; i-- {- if msgs[i].Role == "user" {- resp.ChatMessage = msgs[i].Content- if atts, attErr := h.Queries.ListAttachmentsByChatMessage(r.Context(), db.ListAttachmentsByChatMessageParams{- ChatMessageID: msgs[i].ID,- WorkspaceID: parseUUID(resp.WorkspaceID),- }); attErr == nil && len(atts) > 0 {- resp.ChatMessageAttachments = make([]ChatAttachmentMeta, len(atts))- for j, a := range atts {- resp.ChatMessageAttachments[j] = ChatAttachmentMeta{- ID: uuidToString(a.ID),- Filename: a.Filename,- ContentType: a.ContentType,- }- }+ 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,+ })}- break}}+ resp.ChatMessage = strings.Join(parts, "\n\n")}}}@@ -1638,6 +1646,25 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, map[string]any{"task": resp})}+// trailingUserMessages returns the run of user messages after the last+// assistant message in a chronologically-ordered chat history — the set the+// agent has NOT yet replied to. The agent resumes its prior session and only+// learns of new input through the claim response's chat_message, so a single+// run that covers a debounced burst (MUL-2968) must deliver every one of+// these, not just the latest. Every completed or failed run writes an+// assistant row, so the anchor advances one turn at a time; the result is the+// whole slice on the first turn and exactly the new message(s) thereafter.+func trailingUserMessages(msgs []db.ChatMessage) []db.ChatMessage {+ start := 0+ for i := len(msgs) - 1; i >= 0; i-- {+ if msgs[i].Role != "user" {+ start = i + 1+ break+ }+ }+ return msgs[start:]+}+// ListPendingTasksByRuntime returns queued/dispatched tasks for a runtime.func (h *Handler) ListPendingTasksByRuntime(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")diff --git a/server/internal/handler/daemon_chat_prompt_test.go b/server/internal/handler/daemon_chat_prompt_test.gonew file mode 100644index 0000000000..2f4280f05b--- /dev/null+++ b/server/internal/handler/daemon_chat_prompt_test.go@@ -0,0 +1,88 @@+package handler++import (+ "testing"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func msg(role, content string) db.ChatMessage {+ return db.ChatMessage{Role: role, Content: content}+}++func contents(msgs []db.ChatMessage) []string {+ out := make([]string, len(msgs))+ for i, m := range msgs {+ out[i] = m.Content+ }+ return out+}++func eq(a, b []string) bool {+ if len(a) != len(b) {+ return false+ }+ for i := range a {+ if a[i] != b[i] {+ return false+ }+ }+ return true+}++// TestTrailingUserMessages pins the message-selection logic behind the daemon+// chat prompt: the agent must receive every user message since its last reply+// (the MUL-2968 debounce can land several before one run fires), not just the+// most recent one.+func TestTrailingUserMessages(t *testing.T) {+ cases := []struct {+ name string+ in []db.ChatMessage+ want []string+ }{+ {+ name: "debounced burst with no prior reply delivers all",+ in: []db.ChatMessage{msg("user", "看上海天气"), msg("user", "还有青岛")},+ want: []string{"看上海天气", "还有青岛"},+ },+ {+ name: "only messages after the last assistant reply",+ in: []db.ChatMessage{+ msg("user", "old q"), msg("assistant", "old a"),+ msg("user", "看上海天气"), msg("user", "还有青岛"),+ },+ want: []string{"看上海天气", "还有青岛"},+ },+ {+ name: "single new message after a reply",+ in: []db.ChatMessage{+ msg("user", "看上海天气"), msg("user", "还有青岛"),+ msg("assistant", "weather…"), msg("user", "深圳呢"),+ },+ want: []string{"深圳呢"},+ },+ {+ name: "no trailing user message (last is assistant)",+ in: []db.ChatMessage{msg("user", "hi"), msg("assistant", "done")},+ want: []string{},+ },+ {+ name: "empty history",+ in: []db.ChatMessage{},+ want: []string{},+ },+ {+ name: "single user message",+ in: []db.ChatMessage{msg("user", "hi")},+ want: []string{"hi"},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := contents(trailingUserMessages(tc.in))+ if !eq(got, tc.want) {+ t.Fatalf("trailingUserMessages = %v, want %v", got, tc.want)+ }+ })+ }+}diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 10a1a79cf5..0fd3636492 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -2386,6 +2386,7 @@ func TestCompleteTask_AssignmentTriggered_DoesNotSuppressTrivialDoneOutput(t *tetype claimRuntimeGuardTask struct {PriorSessionID string `json:"prior_session_id"`PriorWorkDir string `json:"prior_work_dir"`+ ChatMessage string `json:"chat_message"`}func claimTaskForRuntimeGuard(t *testing.T, runtimeID, daemonID string) *claimRuntimeGuardTask {@@ -2862,6 +2863,83 @@ func TestClaimTask_ChatPriorSessionRuntimeGuard(t *testing.T) {}}+// TestClaimTask_ChatDeliversAllUnansweredUserMessages pins the fix for the+// regression the MUL-2968 debounce exposed: when several user messages are+// debounced into a single run, the agent must receive ALL of them, not just+// the most recent. Before the fix the daemon prompt was the single latest+// user message, so "看上海天气" then "还有青岛" answered only Qingdao.+func TestClaimTask_ChatDeliversAllUnansweredUserMessages(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)++ var sessionID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)+ VALUES ($1, $2, $3, 'debounce delivery chat')+ RETURNING id+ `, testWorkspaceID, agentID, testUserID).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) })++ // Two user messages debounced into one run (explicit created_at so the+ // ASC ordering is deterministic).+ if _, err := testPool.Exec(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, created_at) VALUES+ ($1, 'user', '看上海天气', now()),+ ($1, 'user', '还有青岛', now() + interval '1 second')+ `, sessionID); err != nil {+ t.Fatalf("setup: insert user messages: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)+ VALUES ($1, $2, $3, 'queued', 2)+ `, agentID, runtimeID, sessionID); err != nil {+ t.Fatalf("setup: create chat task: %v", err)+ }++ task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if task.ChatMessage != "看上海天气\n\n还有青岛" {+ t.Fatalf("chat prompt must include every unanswered user message in order; got %q", task.ChatMessage)+ }++ // Complete the run and record the agent's assistant reply, then send a+ // fresh user message — only the new one should be delivered next.+ if _, err := testPool.Exec(ctx, `+ UPDATE agent_task_queue SET status = 'completed', completed_at = now()+ WHERE chat_session_id = $1 AND status IN ('dispatched', 'running')+ `, sessionID); err != nil {+ t.Fatalf("setup: complete first chat task: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, created_at)+ VALUES ($1, 'assistant', '上海与青岛天气如下…', now() + interval '2 second')+ `, sessionID); err != nil {+ t.Fatalf("setup: insert assistant reply: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO chat_message (chat_session_id, role, content, created_at)+ VALUES ($1, 'user', '深圳呢', now() + interval '3 second')+ `, sessionID); err != nil {+ t.Fatalf("setup: insert follow-up user message: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority)+ VALUES ($1, $2, $3, 'queued', 2)+ `, agentID, runtimeID, sessionID); err != nil {+ t.Fatalf("setup: create follow-up chat task: %v", err)+ }++ task = claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if task.ChatMessage != "深圳呢" {+ t.Fatalf("after a reply, only the new user message must be delivered; got %q", task.ChatMessage)+ }+}+func TestClaimTask_ChatForceFreshSessionSkipsPriorSession(t *testing.T) {if testHandler == nil {t.Skip("database not available")