Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(issues): batch status applies directly; coalesce staged parent notifications (MUL-4155) (#5151)
Naiyuan Qing302662aee331
diff --git a/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx b/packages/views/issues/components/batch-action-toolbar.confirm.test.tsxnew file mode 100644index 0000000000..4025c200bc--- /dev/null+++ b/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx@@ -0,0 +1,143 @@+import { describe, it, expect, beforeEach, vi } from "vitest";+import { render, screen, fireEvent } from "@testing-library/react";+import type { Issue, UpdateIssueRequest } from "@multica/core/types";+import { BatchActionToolbar } from "./batch-action-toolbar";++// MUL-4155: batch status changes must apply directly (no run-confirm modal),+// while agent/squad assignment still confirms and delete still confirms. These+// tests drive the pickers' onUpdate callbacks and assert which path is taken.++const selection = vi.hoisted(() => ({+ selectedIds: new Set<string>(),+ clear: vi.fn(),+ toggle: vi.fn(),+ select: vi.fn(),+ deselect: vi.fn(),+}));+vi.mock("@multica/core/issues/stores/selection-store", () => ({+ useIssueSelectionStore: (selector: (s: typeof selection) => unknown) => selector(selection),+}));++const batchUpdate = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+const batchDelete = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));+vi.mock("@multica/core/issues/mutations", () => ({+ useBatchUpdateIssues: () => ({ mutateAsync: batchUpdate, isPending: false }),+ useBatchDeleteIssues: () => ({ mutateAsync: batchDelete, isPending: false }),+}));++const openModal = vi.hoisted(() => vi.fn());+vi.mock("@multica/core/modals", () => ({+ useModalStore: (selector: (s: { open: typeof openModal }) => unknown) => selector({ open: openModal }),+}));++vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "label" }) }));+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++// Interactive picker stubs: each renders buttons that fire the real onUpdate the+// toolbar passes in, so we exercise handleBatchStatus / handleBatchAssignee.+const ACTIVE_STATUSES = ["todo", "in_progress", "in_review", "blocked"] as const;+const TERMINAL_STATUSES = ["done", "cancelled"] as const;+vi.mock("./pickers", () => ({+ StatusPicker: ({ onUpdate }: { onUpdate: (u: Partial<UpdateIssueRequest>) => void }) => (+ <div>+ {[...ACTIVE_STATUSES, ...TERMINAL_STATUSES, "backlog"].map((s) => (+ <button+ key={s}+ data-testid={`status-${s}`}+ onClick={() => onUpdate({ status: s as UpdateIssueRequest["status"] })}+ />+ ))}+ </div>+ ),+ PriorityPicker: () => <div data-testid="priority-picker" />,+ AssigneePicker: ({ onUpdate }: { onUpdate: (u: Partial<UpdateIssueRequest>) => void }) => (+ <div>+ <button+ data-testid="assign-agent"+ onClick={() => onUpdate({ assignee_type: "agent", assignee_id: "agent-1" })}+ />+ <button+ data-testid="assign-member"+ onClick={() => onUpdate({ assignee_type: "member", assignee_id: "user-1" })}+ />+ </div>+ ),+}));++function makeIssue(overrides: Partial<Issue> = {}): Issue {+ return {+ id: "a",+ workspace_id: "ws-1",+ number: 1,+ identifier: "MUL-1",+ title: "Issue",+ description: null,+ status: "todo",+ priority: "none",+ assignee_type: null,+ assignee_id: null,+ creator_type: "member",+ creator_id: "user-1",+ parent_issue_id: null,+ project_id: null,+ position: 1,+ stage: null,+ start_date: null,+ due_date: null,+ metadata: {},+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...overrides,+ };+}++beforeEach(() => {+ selection.selectedIds = new Set(["a"]);+ batchUpdate.mockClear();+ batchDelete.mockClear();+ openModal.mockClear();+});++describe("BatchActionToolbar status routing (MUL-4155)", () => {+ it("applies every status target directly, never opening the run-confirm modal", () => {+ for (const status of [...ACTIVE_STATUSES, ...TERMINAL_STATUSES, "backlog"]) {+ batchUpdate.mockClear();+ openModal.mockClear();+ // A backlog issue in the selection is the case that historically could+ // start a run — it still must not pop the confirm modal now.+ const { unmount } = render(<BatchActionToolbar issues={[makeIssue({ status: "backlog" })]} />);+ fireEvent.click(screen.getByTestId(`status-${status}`));+ expect(openModal).not.toHaveBeenCalled();+ expect(batchUpdate).toHaveBeenCalledWith({ ids: ["a"], updates: { status } });+ unmount();+ }+ });++ it("still routes agent assignment through the run-confirm modal", () => {+ render(<BatchActionToolbar issues={[makeIssue({ status: "todo" })]} />);+ fireEvent.click(screen.getByTestId("assign-agent"));+ expect(openModal).toHaveBeenCalledWith(+ "issue-run-confirm",+ expect.objectContaining({ issueIds: ["a"], mode: "assign", assigneeType: "agent", assigneeId: "agent-1" }),+ );+ expect(batchUpdate).not.toHaveBeenCalled();+ });++ it("applies member assignment directly (never starts a run)", () => {+ render(<BatchActionToolbar issues={[makeIssue({ status: "todo" })]} />);+ fireEvent.click(screen.getByTestId("assign-member"));+ expect(openModal).not.toHaveBeenCalled();+ expect(batchUpdate).toHaveBeenCalledWith({+ ids: ["a"],+ updates: { assignee_type: "member", assignee_id: "user-1" },+ });+ });++ it("opens the dedicated delete confirmation, not the run-confirm modal", () => {+ render(<BatchActionToolbar issues={[makeIssue({ status: "todo" })]} />);+ fireEvent.click(screen.getByText("label", { selector: "button.text-destructive" }));+ expect(screen.getByRole("alertdialog")).toBeInTheDocument();+ expect(openModal).not.toHaveBeenCalled();+ expect(batchDelete).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsxindex 75d33d8107..b59cea80f0 100644--- a/packages/views/issues/components/batch-action-toolbar.tsx+++ b/packages/views/issues/components/batch-action-toolbar.tsx@@ -89,21 +89,18 @@ export function BatchActionToolbar({}};- // Status and agent/squad assignment can fan out runs across the selection, so- // route them through the pre-trigger confirm modal (aggregate "将启动 N 个" +- // collective handoff note for assign + 暂不开始). The modal applies the batch- // itself. Priority, member assign, and unassign never start a run — direct.+ // Batch status changes apply directly — no run-confirm modal (MUL-4155).+ // done/cancelled can never start a run, and a backlog → active promotion now+ // starts its run the same way a single-issue status change or the CLI does,+ // without an extra confirmation step (product decision on MUL-4155). The+ // status change was previously routed through the pre-trigger modal, which for+ // the common done/cancelled case only rendered a misleading "现在开始处理? →+ // 不会开始处理" box. Agent/squad assignment still confirms via+ // handleBatchAssignee — that is the only batch action that should preview a+ // run fan-out.const handleBatchStatus = (updates: Partial<UpdateIssueRequest>) => {if (!updates.status) return;- // Backlog is the parking lot — a move into backlog never starts a run- // (server/internal/service/issue_trigger.go), so the confirm modal would- // only render an empty "won't start" box with a single Apply button. Apply- // directly, matching the single-issue status path.- if (updates.status === "backlog") {- void handleBatchUpdate(updates);- return;- }- openModal("issue-run-confirm", { issueIds: ids, mode: "status", status: updates.status });+ void handleBatchUpdate(updates);};const handleBatchAssignee = (updates: Partial<UpdateIssueRequest>) => {diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.jsonindex 7090d816f1..c47487af6b 100644--- a/packages/views/locales/en/modals.json+++ b/packages/views/locales/en/modals.json@@ -52,14 +52,12 @@},"run_confirm": {"title_assign": "Assign and start?",- "title_status": "Start working now?","checking": "Checking…","will_start_named": "Once assigned, {{name}} will start working on this issue right away.","will_start_named_squad": "Once assigned, {{name}}'s leader will review it and start assigning the work.","will_start": "This will start work on {{count}} issues right away.","will_start_squad": "This hands {{count}} issues to the squad's leader to review and assign.","nothing_assign": "Assigned — won't start working while in Backlog.",- "nothing_status": "Won't start working.","note_label": "Handoff note (optional)","note_placeholder": "Tell them what matters — scope, focus, or what to avoid…","note_unsupported": "Their runtime is too old to receive this handoff note; it may not be read.",diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.jsonindex 18660e2548..dc8e4133a5 100644--- a/packages/views/locales/ja/modals.json+++ b/packages/views/locales/ja/modals.json@@ -52,14 +52,12 @@},"run_confirm": {"title_assign": "割り当てて開始しますか?",- "title_status": "今すぐ作業を開始しますか?","checking": "確認中…","will_start_named": "割り当てると、{{name}} がすぐにこのイシューの作業を開始します。","will_start_named_squad": "割り当てると、{{name}} のリーダーが内容を評価し、タスクの割り振りを開始します。","will_start": "{{count}} 件のイシューの作業をすぐに開始します。","will_start_squad": "{{count}} 件のイシューをスクワッドのリーダーに渡し、評価して割り振ります。","nothing_assign": "割り当て済み — バックログ中は作業を開始しません。",- "nothing_status": "作業を開始しません。","note_label": "引き継ぎメモ(任意)","note_placeholder": "範囲・重点・触れてほしくない点などを一言で…","note_unsupported": "相手の実行環境が古いため、この引き継ぎメモは読み取れない可能性があります。",diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.jsonindex cd615317e7..649d4abf4e 100644--- a/packages/views/locales/ko/modals.json+++ b/packages/views/locales/ko/modals.json@@ -52,14 +52,12 @@},"run_confirm": {"title_assign": "할당하고 시작할까요?",- "title_status": "지금 작업을 시작할까요?","checking": "확인 중…","will_start_named": "할당하면 {{name}}이(가) 이 이슈 작업을 바로 시작합니다.","will_start_named_squad": "할당하면 {{name}}의 리더가 내용을 평가한 뒤 작업 배분을 시작합니다.","will_start": "{{count}}개 이슈의 작업을 바로 시작합니다.","will_start_squad": "{{count}}개 이슈를 스쿼드 리더에게 넘겨 평가하고 배분합니다.","nothing_assign": "할당됨 — 백로그에서는 작업을 시작하지 않습니다.",- "nothing_status": "작업을 시작하지 않습니다.","note_label": "인계 메모 (선택)","note_placeholder": "범위·핵심·건드리지 말 것 등을 한마디로…","note_unsupported": "상대 런타임이 오래되어 이 인계 메모를 읽지 못할 수 있습니다.",diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.jsonindex 3e47eddc0a..bef20e6d12 100644--- a/packages/views/locales/zh-Hans/modals.json+++ b/packages/views/locales/zh-Hans/modals.json@@ -52,14 +52,12 @@},"run_confirm": {"title_assign": "指派并开始处理?",- "title_status": "现在开始处理?","checking": "检查中…","will_start_named": "指派后,{{name}} 会立即开始工作。","will_start_named_squad": "指派后,{{name}} 的队长会评估并开始安排任务。","will_start": "将立即开始处理 {{count}} 个 issue。","will_start_squad": "将把 {{count}} 个 issue 交给队长评估并安排。","nothing_assign": "已指派 —— 在 backlog 中不会开始处理。",- "nothing_status": "不会开始处理。","note_label": "交接说明(可选)","note_placeholder": "交代一句 —— 范围、重点、或别碰什么……","note_unsupported": "对方的运行环境版本较旧,这条交接说明可能读不到。",diff --git a/packages/views/modals/run-confirm.test.tsx b/packages/views/modals/run-confirm.test.tsxindex 6313d127ba..50a07dd4f5 100644--- a/packages/views/modals/run-confirm.test.tsx+++ b/packages/views/modals/run-confirm.test.tsx@@ -70,13 +70,11 @@ vi.mock("../i18n", () => ({const labels = {run_confirm: {title_assign: "Assign and start?",- title_status: "Start working now?",will_start_named: "start Walt",will_start_named_squad: "start squad Walt",will_start: "start many",will_start_squad: "start squad many",nothing_assign: "no run (backlog)",- nothing_status: "no runs",checking: "Checking…",note_label: "Handoff note",note_placeholder: "scope...",@@ -209,21 +207,24 @@ describe("RunConfirmModal", () => {expect(screen.getByText("runtime too old")).toBeInTheDocument();});- it("batch (N ids) applies via batchUpdate", async () => {+ it("batch assign (N ids) applies via batchUpdate with the assignee change", async () => {previewState.triggers = [- { issue_id: "i1", agent_id: "a1", source: "status", handoff_supported: true },- { issue_id: "i2", agent_id: "a2", source: "status", handoff_supported: true },+ { issue_id: "i1", agent_id: "a1", source: "assign", handoff_supported: true },+ { issue_id: "i2", agent_id: "a2", source: "assign", handoff_supported: true },];previewState.totalCount = 2;render(<RunConfirmModalonClose={vi.fn()}- data={{ issueIds: ["i1", "i2"], mode: "status", status: "todo" }}+ data={{ issueIds: ["i1", "i2"], mode: "assign", assigneeType: "agent", assigneeId: "agent-1" }}/>,);fireEvent.click(screen.getByText("Start"));await waitFor(() => expect(mockBatch).toHaveBeenCalledTimes(1));- expect(mockBatch).toHaveBeenCalledWith({ ids: ["i1", "i2"], updates: { status: "todo" } });+ expect(mockBatch).toHaveBeenCalledWith({+ ids: ["i1", "i2"],+ updates: { assignee_type: "agent", assignee_id: "agent-1" },+ });expect(mockUpdate).not.toHaveBeenCalled();});});diff --git a/packages/views/modals/run-confirm.tsx b/packages/views/modals/run-confirm.tsxindex 9680ea8756..8d6c1f2ba6 100644--- a/packages/views/modals/run-confirm.tsx+++ b/packages/views/modals/run-confirm.tsx@@ -14,7 +14,7 @@ import {import { Button } from "@multica/ui/components/ui/button";import { Textarea } from "@multica/ui/components/ui/textarea";import { Spinner } from "@multica/ui/components/ui/spinner";-import type { IssueAssigneeType, IssueStatus, UpdateIssueRequest } from "@multica/core/types";+import type { IssueAssigneeType, UpdateIssueRequest } from "@multica/core/types";import { useUpdateIssue, useBatchUpdateIssues } from "@multica/core/issues/mutations";import { useActorName } from "@multica/core/workspace/hooks";import { useWorkspaceId } from "@multica/core/hooks";@@ -45,20 +45,22 @@ function boldName(text: string): ReactNode {interface RunConfirmData {issueIds?: string[];- mode?: "assign" | "status";+ // Assign is the only mode: agent/squad assignment is the sole issue write that+ // needs the pre-trigger confirmation. Batch status changes apply directly now+ // (MUL-4155), so there is no "status" mode.+ mode?: "assign";assigneeType?: IssueAssigneeType;assigneeId?: string;assigneeName?: string;- status?: IssueStatus;}/**- * Pre-trigger confirmation for issue writes that may start agent runs+ * Pre-trigger confirmation for issue assignment that may start agent runs* (MUL-3375 §4). Shows what the unified backend predicate says will start (via* the preview endpoint — never a frontend guess), lets the user attach a- * handoff note (assign only) and choose "暂不开始", then applies the change.- * Dismissing the dialog (X / Esc / click-outside) cancels without any write.- * Shared by single assign (1 id) and batch assign / batch status (N ids).+ * handoff note and choose "暂不开始", then applies the change. Dismissing the+ * dialog (X / Esc / click-outside) cancels without any write. Shared by single+ * assign (1 id) and batch assign (N ids).*/export function RunConfirmModal({onClose,@@ -71,7 +73,6 @@ export function RunConfirmModal({const { getActorName } = useActorName();const d = (data ?? {}) as RunConfirmData;const issueIds = d.issueIds ?? [];- const mode = d.mode ?? "assign";const [note, setNote] = useState("");// Which footer action is in flight, so only the clicked button shows a@@ -87,34 +88,33 @@ export function RunConfirmModal({issueIds,assigneeType: d.assigneeType ?? null,assigneeId: d.assigneeId ?? null,- status: d.status,enabled: issueIds.length > 0,});const loading = preview.isLoading;const willStart = preview.totalCount > 0;- const canNote = mode === "assign" && willStart;+ const canNote = willStart;// Local-first handoff-support verdict. For a concrete agent assignee the// target runtime is exactly that agent's, and its CLI version is already warm// in the prefetched agent + runtime caches (useWorkspacePresencePrefetch) —// so we can decide whether the note box is usable synchronously, the same way// the quick-create version gate does, instead of waiting on the preview- // round-trip just to learn something the client already holds. Squad / status- // / unresolved-agent stay `null` and fall through to the server's verdict,+ // round-trip just to learn something the client already holds. Squad /+ // unresolved-agent stay `null` and fall through to the server's verdict,// because their resolved trigger set (hence runtime versions) is only known// after the backend predicate lands.const wsId = useWorkspaceId();const { data: agents = [] } = useQuery({ ...agentListOptions(wsId), enabled: !!wsId });const { data: runtimes = [] } = useQuery({ ...runtimeListOptions(wsId), enabled: !!wsId });const localHandoff = useMemo<boolean | null>(() => {- if (mode !== "assign" || d.assigneeType !== "agent" || !d.assigneeId) return null;+ if (d.assigneeType !== "agent" || !d.assigneeId) return null;const agent = agents.find((a) => a.id === d.assigneeId);if (!agent?.runtime_id) return null;const runtime = runtimes.find((r) => r.id === agent.runtime_id);if (!runtime) return null;return handoffSupported(readRuntimeCliVersion(runtime.metadata));- }, [mode, d.assigneeType, d.assigneeId, agents, runtimes]);+ }, [d.assigneeType, d.assigneeId, agents, runtimes]);// Soft gate: an old runtime can't render the note. Disable the box but let// the assignment proceed (MUL-3375 §6.3). The local verdict resolves it@@ -124,10 +124,10 @@ export function RunConfirmModal({localHandoff !== null ? localHandoff === false : canNote && !preview.handoffSupported;const applyTo = (extra: Partial<UpdateIssueRequest>) => {- const base: UpdateIssueRequest =- mode === "assign"- ? { assignee_type: d.assigneeType ?? null, assignee_id: d.assigneeId ?? null }- : { status: d.status };+ const base: UpdateIssueRequest = {+ assignee_type: d.assigneeType ?? null,+ assignee_id: d.assigneeId ?? null,+ };return { ...base, ...extra };};@@ -154,16 +154,12 @@ export function RunConfirmModal({};// A squad doesn't "work" — its leader evaluates the issue and delegates. The- // copy reflects that (see issues.json squad_leader_*). Only knowable in assign- // mode, where assigneeType is carried; status-mode triggers expose only the- // resolved leader agent, so they stay on the generic copy.- const isSquad = mode === "assign" && d.assigneeType === "squad";+ // copy reflects that (see issues.json squad_leader_*).+ const isSquad = d.assigneeType === "squad";const headline: ReactNode = (() => {if (!willStart) {- return mode === "assign"- ? t(($) => $.run_confirm.nothing_assign)- : t(($) => $.run_confirm.nothing_status);+ return t(($) => $.run_confirm.nothing_assign);}// Single trigger → name the assignee (bolded), resolved from the preview's// runnable agent (squad leader for squads). Batch → count.@@ -184,9 +180,7 @@ export function RunConfirmModal({<Dialog open onOpenChange={(v) => { if (!v && !submitting) onClose(); }}><DialogContent><DialogHeader>- <DialogTitle>- {mode === "assign" ? t(($) => $.run_confirm.title_assign) : t(($) => $.run_confirm.title_status)}- </DialogTitle>+ <DialogTitle>{t(($) => $.run_confirm.title_assign)}</DialogTitle><DialogDescription>{loading ? (<span className="flex items-center gap-1.5 text-muted-foreground">@@ -199,12 +193,12 @@ export function RunConfirmModal({</DialogDescription></DialogHeader>- {/* Assign mode keeps the note box mounted while the preview is in flight- (disabled), so the dialog opens at its resolved height instead of- growing when the predicate lands. Parked (no run) is the only case- without a note, and it can't be a Backlog assign (those skip this- modal), so it is rare. */}- {mode === "assign" && (loading || canNote) ? (+ {/* The note box stays mounted while the preview is in flight (disabled),+ so the dialog opens at its resolved height instead of growing when+ the predicate lands. Parked (no run) is the only case without a note,+ and it can't be a Backlog assign (those skip this modal), so it is+ rare. */}+ {loading || canNote ? (<div className="grid gap-1.5"><label className="text-sm font-medium" htmlFor="handoff-note">{t(($) => $.run_confirm.note_label)}@@ -214,9 +208,9 @@ export function RunConfirmModal({value={note}maxLength={MAX_HANDOFF_NOTE}// Only block on the preview round-trip when we have no local- // verdict (squad / status). With a local verdict the box is- // usable the instant it opens — supported → editable, old runtime- // → disabled — never a "checking…" wait.+ // verdict (squad). With a local verdict the box is usable the+ // instant it opens — supported → editable, old runtime → disabled+ // — never a "checking…" wait.disabled={submitting || noteDisabled || (localHandoff === null && loading)}placeholder={t(($) => $.run_confirm.note_placeholder)}onChange={(e) => setNote(e.target.value)}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 7256f23155..ad983b6723 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -2969,6 +2969,10 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {return}updated := 0+ // Children that transitioned into a terminal status this batch, collected so+ // the parent/stage notification is evaluated once against the final state+ // after the loop (MUL-4155) rather than per-child mid-batch.+ var childDoneCompleted []db.Issuefor _, issueID := range req.IssueIDs {issueUUID, err := util.ParseUUID(issueID)if err != nil {@@ -3168,14 +3172,27 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {}// Platform-driven parent notification, mirrored from UpdateIssue- // (MUL-2538). Best-effort; failure does not abort the batch.- if statusChanged {- h.notifyParentOfChildDone(r.Context(), prevIssue, issue)+ // (MUL-2538) but DEFERRED to after the loop. Evaluating the stage+ // barrier here, per-child, would read a mid-batch sibling snapshot and+ // fire a stale "advance Stage N+1" wake when one batch closes several+ // stages at once (MUL-4155). Collect the terminal transitions and let+ // notifyParentsOfBatchChildDone below evaluate each parent once against+ // the batch's final committed state. Same transition guard as+ // notifyParentOfChildDone: a non-terminal -> terminal move on a child.+ if statusChanged && issue.ParentIssueID.Valid &&+ !isTerminalChildStatus(prevIssue.Status) && isTerminalChildStatus(issue.Status) {+ childDoneCompleted = append(childDoneCompleted, issue)}updated++}+ // Aggregate parent/stage notification over the whole batch's final state so+ // each affected parent gets at most one accurate comment + wake, independent+ // of issue_ids order (MUL-4155). Best-effort; failure does not abort the+ // batch. Single-issue UpdateIssue is unchanged and still notifies inline.+ h.notifyParentsOfBatchChildDone(r.Context(), childDoneCompleted)+slog.Info("batch update issues", append(logger.RequestAttrs(r), "count", updated)...)writeJSON(w, http.StatusOK, map[string]any{"updated": updated})}diff --git a/server/internal/handler/issue_batch_test.go b/server/internal/handler/issue_batch_test.goindex 0f63e9917f..8725ab58f0 100644--- a/server/internal/handler/issue_batch_test.go+++ b/server/internal/handler/issue_batch_test.go@@ -1,10 +1,13 @@package handlerimport (+ "context""encoding/json""net/http""net/http/httptest"+ "strings""testing"+ "time")// TestBatchUpdateNoMutationReturnsZero — regression for #1660.@@ -182,3 +185,223 @@ func deleteTestIssue(t *testing.T, id string) {req = withURLParam(req, "id", id)testHandler.DeleteIssue(w, req)}++// --- MUL-4155: batch cross-stage child-done aggregation ---+//+// A single batch that finishes sub-issues spanning multiple stages must+// evaluate the parent stage barrier ONCE against the batch's final committed+// state, not per-child mid-batch. The mid-batch behaviour fired one comment per+// intermediate stage, pinned the parent assignee's wake to a stale "advance the+// next stage" instruction, and produced order-dependent output. These tests+// lock in the aggregated behaviour: at most one accurate comment + one wake per+// parent, identical regardless of issue_ids order.++// stagedBatchFixture is a parent (agent-assigned, in_progress) with two ordered+// stages of two in_progress children each, so a single batch that finishes all+// four exercises the cross-stage barrier aggregation.+type stagedBatchFixture struct {+ parent IssueResponse+ agentID string+ stage1 []IssueResponse+ stage2 []IssueResponse+}++func newStagedBatchFixture(t *testing.T) stagedBatchFixture {+ t.Helper()+ if testHandler == nil {+ t.Skip("database not available")+ }++ pw := httptest.NewRecorder()+ preq := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "batch-stage parent " + time.Now().Format(time.RFC3339Nano),+ "status": "in_progress",+ })+ testHandler.CreateIssue(pw, preq)+ if pw.Code != http.StatusCreated {+ t.Fatalf("create parent: expected 201, got %d: %s", pw.Code, pw.Body.String())+ }+ var parent IssueResponse+ json.NewDecoder(pw.Body).Decode(&parent)++ // Assign the parent to the ready test agent via direct SQL so the child-done+ // wake actually enqueues a task we can pin to the final comment — without the+ // assignment trigger queuing an unrelated task at setup.+ var agentID string+ if err := testPool.QueryRow(context.Background(),+ `SELECT id FROM agent WHERE workspace_id = $1 AND name = $2`,+ testWorkspaceID, "Handler Test Agent",+ ).Scan(&agentID); err != nil {+ t.Fatalf("locate test agent: %v", err)+ }+ setIssueAssigneeDirect(t, parent.ID, "agent", agentID)++ mkChild := func(stage int32) IssueResponse {+ cw := httptest.NewRecorder()+ creq := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "batch-stage child " + time.Now().Format(time.RFC3339Nano),+ "status": "in_progress",+ "parent_issue_id": parent.ID,+ })+ testHandler.CreateIssue(cw, creq)+ if cw.Code != http.StatusCreated {+ t.Fatalf("create child: expected 201, got %d: %s", cw.Code, cw.Body.String())+ }+ var child IssueResponse+ json.NewDecoder(cw.Body).Decode(&child)+ // Set the stage directly — the barrier logic only reads issue.stage.+ if _, err := testPool.Exec(context.Background(),+ `UPDATE issue SET stage = $2 WHERE id = $1`, child.ID, stage); err != nil {+ t.Fatalf("set child stage: %v", err)+ }+ return child+ }++ fx := stagedBatchFixture{parent: parent, agentID: agentID}+ fx.stage1 = []IssueResponse{mkChild(1), mkChild(1)}+ fx.stage2 = []IssueResponse{mkChild(2), mkChild(2)}++ t.Cleanup(func() {+ ctx := context.Background()+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, parent.ID)+ for _, c := range append(append([]IssueResponse{}, fx.stage1...), fx.stage2...) {+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, c.ID)+ }+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, parent.ID)+ })++ return fx+}++// batchSetStatus drives BatchUpdateIssues over the given ids, in order.+func batchSetStatus(t *testing.T, ids []string, status string) {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues/batch-update", map[string]any{+ "issue_ids": ids,+ "updates": map[string]any{"status": status},+ })+ testHandler.BatchUpdateIssues(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("BatchUpdateIssues status=%q: expected 200, got %d: %s", status, w.Code, w.Body.String())+ }+}++// systemCommentIDOn returns the id of the single (latest) system comment on issueID.+func systemCommentIDOn(t *testing.T, issueID string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(context.Background(),+ `SELECT id::text FROM comment+ WHERE issue_id = $1 AND author_type = 'system'+ ORDER BY created_at DESC LIMIT 1`,+ issueID,+ ).Scan(&id); err != nil {+ t.Fatalf("read system comment id: %v", err)+ }+ return id+}++// triggerCommentIDForAgentTask returns the trigger_comment_id of the single+// pending task on issueID for agentID.+func triggerCommentIDForAgentTask(t *testing.T, issueID, agentID string) string {+ t.Helper()+ var id string+ if err := testPool.QueryRow(context.Background(),+ `SELECT trigger_comment_id::text FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2+ AND status IN ('queued','dispatched','running')+ ORDER BY created_at DESC LIMIT 1`,+ issueID, agentID,+ ).Scan(&id); err != nil {+ t.Fatalf("read task trigger_comment_id: %v", err)+ }+ return id+}++// TestBatchChildDoneCrossStage_OneComment is the MUL-4155 core. A single batch+// that finishes children across two stages must produce exactly ONE accurate+// system comment on the parent — announcing the highest stage closed by the+// final state, never a stale "Stage 2 is next" — and the parent assignee's+// single wake must be pinned to that final comment, regardless of id order.+func TestBatchChildDoneCrossStage_OneComment(t *testing.T) {+ assertFinal := func(t *testing.T, parentID, agentID string) {+ t.Helper()+ if got := countSystemCommentsOn(t, parentID); got != 1 {+ t.Fatalf("expected exactly 1 system comment on parent, got %d", got)+ }+ content, _, _, _ := systemCommentOn(t, parentID)+ if !strings.Contains(content, "Stage 2 of this issue is complete") {+ t.Errorf("expected the comment to announce the top closed stage (Stage 2), got: %s", content)+ }+ if !strings.Contains(content, "Stage 1: 2/2 done; Stage 2: 2/2 done") {+ t.Errorf("expected the final-state stage summary, got: %s", content)+ }+ // The bug: a mid-batch snapshot told the parent to advance a stage this+ // same batch had already finished.+ if strings.Contains(content, "is next") || strings.Contains(content, "(next)") {+ t.Errorf("comment must not carry a stale next-stage instruction, got: %s", content)+ }+ // Exactly one wake, pinned to the final comment.+ if got := countPendingTasksForAgent(t, parentID, agentID); got != 1 {+ t.Fatalf("expected exactly 1 pending parent task, got %d", got)+ }+ if trig, want := triggerCommentIDForAgentTask(t, parentID, agentID), systemCommentIDOn(t, parentID); trig != want {+ t.Errorf("parent wake pinned to %s, want the final comment %s", trig, want)+ }+ }++ t.Run("forward order [stage1, stage2]", func(t *testing.T) {+ fx := newStagedBatchFixture(t)+ batchSetStatus(t, []string{fx.stage1[0].ID, fx.stage1[1].ID, fx.stage2[0].ID, fx.stage2[1].ID}, "done")+ assertFinal(t, fx.parent.ID, fx.agentID)+ })++ t.Run("reverse order [stage2, stage1]", func(t *testing.T) {+ fx := newStagedBatchFixture(t)+ batchSetStatus(t, []string{fx.stage2[0].ID, fx.stage2[1].ID, fx.stage1[0].ID, fx.stage1[1].ID}, "done")+ assertFinal(t, fx.parent.ID, fx.agentID)+ })+}++// TestBatchChildDoneCrossStage_Cancelled — cancelling every stage in one batch+// is terminal too and must behave identically: one accurate final comment, no+// stale advance instruction.+func TestBatchChildDoneCrossStage_Cancelled(t *testing.T) {+ fx := newStagedBatchFixture(t)+ batchSetStatus(t, []string{fx.stage1[0].ID, fx.stage1[1].ID, fx.stage2[0].ID, fx.stage2[1].ID}, "cancelled")++ if got := countSystemCommentsOn(t, fx.parent.ID); got != 1 {+ t.Fatalf("expected exactly 1 system comment on parent, got %d", got)+ }+ content, _, _, _ := systemCommentOn(t, fx.parent.ID)+ if !strings.Contains(content, "Stage 2 of this issue is complete") {+ t.Errorf("expected Stage 2 completion announcement, got: %s", content)+ }+ if strings.Contains(content, "is next") || strings.Contains(content, "(next)") {+ t.Errorf("comment must not carry a stale next-stage instruction, got: %s", content)+ }+}++// TestBatchChildDoneClosesLowerStageOnly — when a batch finishes only the lower+// stage (a later stage still has open children), the parent must be told Stage 1+// is complete AND accurately pointed at Stage 2 as next. Guards against+// over-suppressing the legitimate advance instruction.+func TestBatchChildDoneClosesLowerStageOnly(t *testing.T) {+ fx := newStagedBatchFixture(t)+ batchSetStatus(t, []string{fx.stage1[0].ID, fx.stage1[1].ID}, "done")++ if got := countSystemCommentsOn(t, fx.parent.ID); got != 1 {+ t.Fatalf("expected exactly 1 system comment on parent, got %d", got)+ }+ content, _, _, _ := systemCommentOn(t, fx.parent.ID)+ if !strings.Contains(content, "Stage 1 of this issue is complete") {+ t.Errorf("expected Stage 1 completion announcement, got: %s", content)+ }+ if !strings.Contains(content, "Stage 2: 0/2 done (next)") {+ t.Errorf("expected accurate next-stage progress, got: %s", content)+ }+ if !strings.Contains(content, "Stage 2 is next") {+ t.Errorf("expected the advance-to-next-stage instruction, got: %s", content)+ }+}diff --git a/server/internal/handler/issue_child_done.go b/server/internal/handler/issue_child_done.goindex d41fd5bd57..b9f0be80c9 100644--- a/server/internal/handler/issue_child_done.go+++ b/server/internal/handler/issue_child_done.go@@ -125,11 +125,142 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.Isreturn}staged := siblingsAreStaged(children)+ // When the set is staged and the barrier closed, the completed child is+ // guaranteed to carry a stage (stageBarrierClosed returns false for an+ // unstaged completed child in a staged set), so issue.Stage.Int32 is safe.+ var closedStage int32+ if staged {+ closedStage = issue.Stage.Int32+ }+ h.postChildDoneComment(ctx, parent, issue, children, staged, closedStage, false)+}++// notifyParentsOfBatchChildDone emits child-done parent notifications for a+// whole batch AFTER every status write has committed. `completed` is the set of+// children that transitioned non-terminal -> terminal during the batch.+//+// Evaluating the stage barrier per-child inside the batch loop used the+// mid-batch sibling snapshot, so a batch that closed several stages at once+// fired one comment per intermediate stage: the first (stale) comment pinned the+// parent assignee's wake to an already-superseded "advance Stage N+1"+// instruction while the accurate final wake was swallowed by the pending-task+// dedup, and the outcome depended on issue_ids order (MUL-4155). Aggregating+// here makes the result order-independent — each affected parent gets at most+// one comment built from the final state, plus one wake pinned to that comment.+//+// Best-effort, mirroring notifyParentOfChildDone: a failure on one parent is+// logged and skipped; it never rolls back the committed batch.+func (h *Handler) notifyParentsOfBatchChildDone(ctx context.Context, completed []db.Issue) {+ if len(completed) == 0 {+ return+ }++ // Group the completed children by parent, preserving first-seen order so the+ // emitted comments (and any test assertions) are deterministic.+ type parentGroup struct {+ parentID pgtype.UUID+ children []db.Issue+ }+ var groups []*parentGroup+ index := map[string]*parentGroup{}+ for _, c := range completed {+ if !c.ParentIssueID.Valid {+ continue+ }+ key := uuidToString(c.ParentIssueID)+ g, ok := index[key]+ if !ok {+ g = &parentGroup{parentID: c.ParentIssueID}+ index[key] = g+ groups = append(groups, g)+ }+ g.children = append(g.children, c)+ }++ for _, g := range groups {+ parent, err := h.Queries.GetIssue(ctx, g.parentID)+ if err != nil {+ slog.Warn("batch child done: failed to load parent",+ "error", err, "parent_id", uuidToString(g.parentID))+ continue+ }+ // Same parent guards as the single path (see notifyParentOfChildDone).+ if parent.Status == "done" || parent.Status == "cancelled" {+ continue+ }+ if parent.Status == "backlog" {+ continue+ }+ if parent.AssigneeType.Valid && parent.AssigneeType.String == "member" {+ continue+ }- prefix := h.getIssuePrefix(ctx, issue.WorkspaceID)- identifier := prefix + "-" + strconv.Itoa(int(issue.Number))- childID := uuidToString(issue.ID)- title := sanitizeChildTitleForSystemComment(issue.Title)+ children, err := h.Queries.ListChildIssues(ctx, parent.ID)+ if err != nil {+ slog.Warn("batch child done: failed to list siblings for stage barrier",+ "error", err, "parent_id", uuidToString(parent.ID))+ continue+ }++ batch := len(g.children) > 1+ if !siblingsAreStaged(children) {+ // Unstaged: one implicit stage. Fire once iff every child is terminal+ // in the final state. stageBarrierClosed ignores `completed` on the+ // unstaged path, so any completed child stands in for the barrier check.+ if !stageBarrierClosed(children, g.children[0]) {+ continue+ }+ h.postChildDoneComment(ctx, parent, g.children[0], children, false, 0, batch)+ continue+ }++ // Staged: announce the HIGHEST stage among this batch's completed children+ // whose barrier is closed in the final state. This is what makes the+ // result order-independent — whether the caller sent [stage1, stage2] or+ // [stage2, stage1], the final committed state is identical, so the same+ // top stage wins and stageProgressSummary's "Stage N is next" reflects+ // reality rather than a mid-batch snapshot. A lower closed stage would+ // re-introduce the stale "advance the next stage" instruction the bug was+ // about.+ var rep db.Issue+ var bestStage int32+ found := false+ for _, c := range g.children {+ if !c.Stage.Valid {+ continue // an unstaged child in a staged set closes no stage+ }+ if !stageBarrierClosed(children, c) {+ continue+ }+ if !found || c.Stage.Int32 > bestStage {+ found = true+ bestStage = c.Stage.Int32+ rep = c+ }+ }+ if !found {+ continue+ }+ h.postChildDoneComment(ctx, parent, rep, children, true, bestStage, batch)+ }+}++// postChildDoneComment builds and posts the parent's child-done system comment+// for a closed stage barrier, then dispatches the parent-assignee trigger. It+// assumes every guard in notifyParentOfChildDone / notifyParentsOfBatchChildDone+// has already passed and that `completed` is a terminal child whose barrier is+// closed within `children` (the final sibling set).+//+// `completed` is the representative finished child named in the comment.+// `staged`/`closedStage` describe the closed barrier (closedStage is unused for+// an unstaged set). `batch` selects batch-aware wording: a single update keeps+// its historical byte-identical copy, while a batch that finished several+// children at once must not claim "the last sub-issue just finished".+func (h *Handler) postChildDoneComment(ctx context.Context, parent, completed db.Issue, children []db.Issue, staged bool, closedStage int32, batch bool) {+ prefix := h.getIssuePrefix(ctx, completed.WorkspaceID)+ identifier := prefix + "-" + strconv.Itoa(int(completed.Number))+ childID := uuidToString(completed.ID)+ title := sanitizeChildTitleForSystemComment(completed.Title)parentID := uuidToString(parent.ID)// Build the parent-assignee mention prefix. Empty when the parent has no@@ -138,22 +269,32 @@ func (h *Handler) notifyParentOfChildDone(ctx context.Context, prev, issue db.IsmentionPrefix := h.buildParentAssigneeMention(ctx, parent)var content string- // When the set is staged and the barrier closed, the completed child is- // guaranteed to carry a stage (stageBarrierClosed returns false for an- // unstaged completed child in a staged set), so issue.Stage.Int32 is safe.if staged {- closedStage := issue.Stage.Int32summary, nextStage := stageProgressSummary(children, closedStage)advance := stageAdvanceInstruction(nextStage, parentID)- content = fmt.Sprintf(- "%sStage %d of this issue is complete — its last sub-issue [%s](mention://issue/%s) — \"%s\" — just finished. Stage progress — %s.%s",- mentionPrefix, closedStage, identifier, childID, title, summary, advance,- )+ if batch {+ content = fmt.Sprintf(+ "%sStage %d of this issue is complete — its sub-issues just finished together in a batch update, most recently [%s](mention://issue/%s) — \"%s\". Stage progress — %s.%s",+ mentionPrefix, closedStage, identifier, childID, title, summary, advance,+ )+ } else {+ content = fmt.Sprintf(+ "%sStage %d of this issue is complete — its last sub-issue [%s](mention://issue/%s) — \"%s\" — just finished. Stage progress — %s.%s",+ mentionPrefix, closedStage, identifier, childID, title, summary, advance,+ )+ }} else {- content = fmt.Sprintf(- "%sAll sub-issues are complete — the last one, [%s](mention://issue/%s) — \"%s\", just finished. Continue the parent: synthesize the children's results and move it forward, or close it out if nothing remains.",- mentionPrefix, identifier, childID, title,- )+ if batch {+ content = fmt.Sprintf(+ "%sAll sub-issues are complete — they just finished together in a batch update, most recently [%s](mention://issue/%s) — \"%s\". Continue the parent: synthesize the children's results and move it forward, or close it out if nothing remains.",+ mentionPrefix, identifier, childID, title,+ )+ } else {+ content = fmt.Sprintf(+ "%sAll sub-issues are complete — the last one, [%s](mention://issue/%s) — \"%s\", just finished. Continue the parent: synthesize the children's results and move it forward, or close it out if nothing remains.",+ mentionPrefix, identifier, childID, title,+ )+ }}// author_type='system', author_id=zero UUID. The zero UUID is a valid 16