Skip to content

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

Go

fix(realtime): announce comments folded into a queued run (#9702)

Jiayuan Zhang16f0d307dd06
diff --git a/apps/mobile/data/realtime/use-issue-realtime.ts b/apps/mobile/data/realtime/use-issue-realtime.ts
index 0e9ea333c7..5475e47c85 100644
--- a/apps/mobile/data/realtime/use-issue-realtime.ts
+++ b/apps/mobile/data/realtime/use-issue-realtime.ts
@@ -10,10 +10,10 @@
* - activity:created → timeline
* - reaction:added / reaction:removed → comment reactions on timeline
* - issue_reaction:added / issue_reaction:removed → issue-level reactions on detail
- * - task:queued / task:dispatch / task:progress / task:completed /
- * task:failed / task:cancelled → invalidate timeline + detail (task
- * state can flip an issue's status server-side without firing
- * issue:updated, so we refetch the authoritative detail too)
+ * - task:queued / task:coalesced / task:dispatch / task:progress /
+ * task:completed / task:failed / task:cancelled → invalidate timeline +
+ * detail (task state can flip an issue's status server-side without
+ * firing issue:updated, so we refetch the authoritative detail too)
* - reconnect → invalidate detail + timeline (we might've missed events
* while disconnected; server has no replay buffer for this client)
*
@@ -230,6 +230,7 @@ export function useIssueRealtime(
// ----- Agent task progress -----
ws.on("task:queued", onTaskEvent),
+ ws.on("task:coalesced", onTaskEvent),
ws.on("task:dispatch", onTaskEvent),
ws.on("task:progress", onTaskEvent),
ws.on("task:completed", onTaskEvent),
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 334b9122f6..c7e2803119 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -395,6 +395,30 @@ describe("useRealtimeSync — queued chat promotion", () => {
});
});
+describe("useRealtimeSync — comment folded into a queued run", () => {
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
+
+ it("refreshes the issue's runs so the queued block moves under the folded comment", async () => {
+ vi.useFakeTimers();
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ const ws = createMockWs();
+ renderHook(() => useRealtimeSync(ws, createStores()), { wrapper: createWrapper(qc) });
+ const onAny = vi.mocked(ws.onAny).mock.calls[0]![0];
+ qc.setQueryData(issueKeys.tasks("issue-1"), []);
+
+ onAny({
+ type: "task:coalesced",
+ payload: { task_id: "task-1", agent_id: "agent-1", issue_id: "issue-1", status: "queued" },
+ } as never);
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect(qc.getQueryState(issueKeys.tasks("issue-1"))?.isInvalidated).toBe(true);
+ });
+});
+
describe("useRealtimeSync — Table server membership invalidation", () => {
let qc: QueryClient;
let stores: RealtimeSyncStores;
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 2617b68c9b..3a5e671a64 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -24,6 +24,7 @@ export type WSEventType =
| "agent:archived"
| "agent:restored"
| "task:queued"
+ | "task:coalesced"
| "task:dispatch"
| "task:running"
| "task:waiting_local_directory"
@@ -328,6 +329,17 @@ export interface TaskQueuedPayload {
status: string;
}
+// task:coalesced fires when a comment folds into a run that has not started.
+// The status is unchanged, but the run's trigger and covered comments changed,
+// which moves its block under the newest comment it answers.
+export interface TaskCoalescedPayload {
+ task_id: string;
+ agent_id: string;
+ issue_id: string;
+ chat_session_id?: string;
+ status: string;
+}
+
export interface TaskDispatchPayload {
task_id: string;
agent_id: string;
@@ -598,6 +610,7 @@ export interface WSEventPayloadMap {
"agent:archived": AgentArchivedPayload;
"agent:restored": AgentRestoredPayload;
"task:queued": TaskQueuedPayload;
+ "task:coalesced": TaskCoalescedPayload;
"task:dispatch": TaskDispatchPayload;
"task:running": TaskRunningPayload;
"task:waiting_local_directory": TaskWaitingLocalDirectoryPayload;
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 1f3f7c8f48..0739d6345a 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -2450,6 +2450,9 @@ func (h *Handler) mergeCommentIntoPendingTask(ctx context.Context, issue db.Issu
// The fold re-attributes the queued run to this comment's author; record that
// human's action now, since the run row keeps no history of who acted.
h.TaskService.RecordHumanDelegation(ctx, attr)
+ // The run's status is unchanged, so no lifecycle event tells clients that it
+ // now answers this comment.
+ h.TaskService.BroadcastTaskCoalesced(ctx, row)
return commentMergeSucceeded
}
diff --git a/server/internal/handler/comment_thread_queue_test.go b/server/internal/handler/comment_thread_queue_test.go
index be6d54c39d..7fdb337b9e 100644
--- a/server/internal/handler/comment_thread_queue_test.go
+++ b/server/internal/handler/comment_thread_queue_test.go
@@ -7,8 +7,10 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
func TestCommentThreadQueuesMergeAndExecuteIndependently(t *testing.T) {
@@ -112,6 +114,63 @@ func TestCommentThreadQueuesMergeAndExecuteIndependently(t *testing.T) {
}
}
+// Clients place a queued run under the newest comment it answers. Folding a
+// reply into that run leaves its status alone, so only task:coalesced moves the
+// run's block under the reply on open issue pages.
+func TestCommentFoldedIntoQueuedRunBroadcastsCoalesced(t *testing.T) {
+ ctx := context.Background()
+ runtimeID := dbfx.Runtime(t, "coalesced broadcast runtime")
+ agentID := dbfx.Agent(t, "coalesced broadcast agent", runtimeID)
+ issueID := dbfx.Issue(t, "coalesced broadcast issue", testutil.Cols{"assignee_type": "agent", "assignee_id": agentID})
+ root := dbfx.Comment(t, issueID, "release flow is incomplete")
+ reply := dbfx.Comment(t, issueID, "so is the issue pipeline", testutil.Cols{"parent_id": root})
+ t.Cleanup(func() { dbfx.Exec(t, "DELETE FROM agent_task_queue WHERE issue_id = $1", issueID) })
+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ agent, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ coalesced := make(chan events.Event, 4)
+ testHandler.Bus.Subscribe(protocol.EventTaskCoalesced, func(e events.Event) {
+ if payload, ok := e.Payload.(map[string]any); ok && payload["issue_id"] == issueID {
+ coalesced <- e
+ }
+ })
+ enqueue := func(commentID string, pending bool, want DispatchStatus) {
+ t.Helper()
+ result := testHandler.enqueueCommentAgentTriggers(ctx, issue, parseUUID(commentID),
+ []commentAgentTrigger{{Agent: agent, Source: commentTriggerSourceIssueAssignee, AlreadyPending: pending}})
+ if result[agentID].status != want {
+ t.Fatalf("enqueue %s: got %+v, want %s", commentID, result[agentID], want)
+ }
+ }
+
+ enqueue(root, false, DispatchQueued)
+ if len(coalesced) != 0 {
+ t.Fatal("a new run must not be announced as coalesced")
+ }
+ enqueue(reply, true, DispatchCoalesced)
+
+ tasks, err := testHandler.Queries.ListTasksByIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(tasks) != 1 || uuidToString(tasks[0].TriggerCommentID) != reply {
+ t.Fatalf("reply did not fold into the queued run: %+v", tasks)
+ }
+ if len(coalesced) != 1 {
+ t.Fatalf("got %d task:coalesced events, want 1", len(coalesced))
+ }
+ event := <-coalesced
+ payload := event.Payload.(map[string]any)
+ if event.WorkspaceID != uuidToString(issue.WorkspaceID) || payload["task_id"] != uuidToString(tasks[0].ID) || payload["status"] != "queued" {
+ t.Fatalf("wrong task:coalesced event: workspace=%s payload=%+v", event.WorkspaceID, payload)
+ }
+}
+
func TestDeferredCommentThreadsPromoteIndependently(t *testing.T) {
ctx := context.Background()
runtimeID := dbfx.Runtime(t, "thread promotion runtime")
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 4e88c9ff45..86718feab0 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2811,6 +2811,13 @@ func (s *TaskService) BroadcastTaskQueued(ctx context.Context, task db.AgentTask
s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
}
+// BroadcastTaskCoalesced tells clients a pending run took in another comment.
+// The run keeps its status, but its trigger and covered comments changed, and
+// clients place the run under the newest comment it answers.
+func (s *TaskService) BroadcastTaskCoalesced(ctx context.Context, task db.AgentTaskQueue) {
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCoalesced, task)
+}
+
// CaptureCancelledTasks records analytics for an already-committed bulk
// cancellation. It deliberately does NOT settle delegated-failure recoveries:
// by the time it runs the cancel has committed, so a failure here could not be
@@ -6855,6 +6862,7 @@ func (s *TaskService) dispatchDelegatedFailureRecovery(ctx context.Context, targ
"failed_task_id", util.UUIDToString(target.failed.ID),
"coordinator_task_id", util.UUIDToString(merged.ID),
)
+ s.BroadcastTaskCoalesced(ctx, merged)
return delegatedFailureRecoveryReplayed, nil
} else if !errors.Is(err, pgx.ErrNoRows) {
return delegatedFailureRecoveryCovered, fmt.Errorf("merge recovery into pending task: %w", err)
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 72c5d4b56d..007dd97cd6 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -7111,7 +7111,7 @@ WHERE id = (
ORDER BY t.created_at DESC
LIMIT 1
)
-RETURNING id, coalesced_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, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot, workflow_step
`
type MergeCommentIntoPendingTaskParams struct {
@@ -7131,11 +7131,6 @@ type MergeCommentIntoPendingTaskParams struct {
HeadSha pgtype.Text `json:"head_sha"`
}
-type MergeCommentIntoPendingTaskRow struct {
- ID pgtype.UUID `json:"id"`
- CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`
-}
-
// MUL-4195: fold a newly-arrived comment into an existing task for (issue,
// agent) that has NOT yet been claimed, instead of letting the
// HasPendingTaskForIssueAndAgent dedup silently DROP it. The task's prior
@@ -7178,7 +7173,7 @@ type MergeCommentIntoPendingTaskRow struct {
// dispatched/running). The caller must NOT blindly enqueue a fresh task in that
// case — a dispatched sibling would trip the unique index — it defers to
// completion reconciliation unless no active task exists at all.
-func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeCommentIntoPendingTaskParams) (MergeCommentIntoPendingTaskRow, error) {
+func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeCommentIntoPendingTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, mergeCommentIntoPendingTask,
arg.NewTriggerCommentID,
arg.NewTriggerSummary,
@@ -7195,8 +7190,69 @@ func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeComm
arg.AgentID,
arg.HeadSha,
)
- var i MergeCommentIntoPendingTaskRow
- err := row.Scan(&i.ID, &i.CoalescedCommentIds)
+ 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,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.BranchName,
+ &i.DurableWorkDir,
+ &i.ChannelContextRevision,
+ &i.CommentThreadID,
+ &i.CancelledByType,
+ &i.CancelledByID,
+ &i.CancelledByName,
+ &i.IssueSnapshot,
+ &i.WorkflowStep,
+ )
return i, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 16b9d20802..415da1d7b5 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -1825,7 +1825,7 @@ WHERE id = (
ORDER BY t.created_at DESC
LIMIT 1
)
-RETURNING id, coalesced_comment_ids;
+RETURNING *;
-- name: RegisterPlannedCommentForActiveTask :one
-- #5914: durably register a comment that lost an enqueue race as a PLANNED
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 03ee83f0cb..bf04f63836 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -32,6 +32,7 @@ const (
// snapshot, so the granularity here is "what does the user want to see
// change" — not "every internal status flip".
EventTaskQueued = "task:queued" // ∅ → queued (enqueue / retry create)
+ EventTaskCoalesced = "task:coalesced" // status unchanged (a comment folded into a run not yet claimed, which now answers it)
EventTaskDispatch = "task:dispatch" // queued → dispatched (daemon claim)
EventTaskRunning = "task:running" // dispatched → running (daemon started)
EventTaskWaitingLocalDirectory = "task:waiting_local_directory" // dispatched → waiting_local_directory (daemon parked on a busy local_directory path)