Skip to content

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

Go

feat(issues): bulk edit labels, project, dates, parent and custom properties (MUL-8882) (#10629)

Jiayuan Zhang894ec73f5c00
diff --git a/packages/core/api/batch-update-issues.test.ts b/packages/core/api/batch-update-issues.test.ts
new file mode 100644
index 0000000000..a545a0aa1b
--- /dev/null
+++ b/packages/core/api/batch-update-issues.test.ts
@@ -0,0 +1,84 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ApiClient, BatchOpsUnsupportedError } from "./client";
+
+afterEach(() => vi.unstubAllGlobals());
+
+function respond(body: unknown) {
+ const fetch = vi.fn().mockResolvedValue(Response.json(body));
+ vi.stubGlobal("fetch", fetch);
+ return fetch;
+}
+
+const client = () => new ApiClient("https://api.example.test");
+
+describe("batchUpdateIssues", () => {
+ it("sends label and property operations and parses per-issue results", async () => {
+ const fetch = respond({
+ updated: 1,
+ results: [
+ { issue_id: "a", identifier: "MUL-1", outcome: "updated" },
+ { issue_id: "b", identifier: "MUL-2", outcome: "skipped", code: "not_found", message: "issue not found" },
+ ],
+ });
+ await expect(
+ client().batchUpdateIssues(["a", "b"], {}, { labels: { add: ["l1"] }, properties: { unset: ["p1"] } }),
+ ).resolves.toEqual({
+ updated: 1,
+ results: [
+ { issue_id: "a", identifier: "MUL-1", outcome: "updated" },
+ { issue_id: "b", identifier: "MUL-2", outcome: "skipped", code: "not_found", message: "issue not found" },
+ ],
+ });
+ const [url, init] = fetch.mock.calls[0]!;
+ expect(new URL(url).pathname).toBe("/api/issues/batch-update");
+ expect(JSON.parse(init.body)).toEqual({
+ issue_ids: ["a", "b"],
+ updates: {},
+ labels: { add: ["l1"] },
+ properties: { unset: ["p1"] },
+ });
+ });
+
+ it("keeps an older server's bare count for field updates", async () => {
+ respond({ updated: 2 });
+ await expect(client().batchUpdateIssues(["a", "b"], { priority: "high" })).resolves.toEqual({ updated: 2 });
+ });
+
+ it("refuses an older server's bare count for label or property operations", async () => {
+ respond({ updated: 2 });
+ await expect(client().batchUpdateIssues(["a"], {}, { labels: { clear: true } })).rejects.toBeInstanceOf(
+ BatchOpsUnsupportedError,
+ );
+ });
+
+ it("reads an outcome it does not know as skipped, never as success", async () => {
+ respond({ updated: 1, results: [{ issue_id: "a", outcome: "queued", message: "later" }] });
+ const response = await client().batchUpdateIssues(["a"], {}, { labels: { add: ["l1"] } });
+ expect(response.results).toEqual([{ issue_id: "a", outcome: "skipped", message: "later" }]);
+ });
+
+ it("tolerates malformed optional fields on a result", async () => {
+ respond({ updated: 1, dry_run: "yes", results: [{ issue_id: "a", outcome: "updated", identifier: 7, code: null }] });
+ await expect(client().batchUpdateIssues(["a"], {})).resolves.toEqual({
+ updated: 1,
+ results: [{ issue_id: "a", outcome: "updated" }],
+ });
+ });
+
+ it.each([
+ null,
+ {},
+ { updated: "2" },
+ { updated: -1 },
+ { updated: 1, results: "none" },
+ { updated: 1, results: [{ outcome: "updated" }] },
+ { updated: 1, results: [{ issue_id: "a" }] },
+ ])("reports a malformed response as unconfirmed, not as success: %j", async (body) => {
+ respond(body);
+ await expect(client().batchUpdateIssues(["a"], {}, { labels: { add: ["l1"] } })).resolves.toEqual({
+ updated: 0,
+ unconfirmed: true,
+ });
+ });
+});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 916d381196..d94ba50173 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -13,6 +13,9 @@ import type {
CreateIssueRequest,
MoveIssueRequest,
UpdateIssueRequest,
+ BatchIssueLabelOps,
+ BatchIssuePropertyOps,
+ BatchUpdateIssuesResponse,
IssueDuplicates,
GroupedIssuesResponse,
ListIssuesResponse,
@@ -408,6 +411,8 @@ import {
CreateBillingPortalSessionResponseSchema,
WorkspaceSubscriptionSummarySchema,
IssueLimitUsageSchema,
+ BatchUpdateIssuesResponseSchema,
+ UNCONFIRMED_BATCH_UPDATE,
WorkspaceSubscriptionPricesSchema,
CreateWorkspaceSubscriptionCheckoutResponseSchema,
WorkspaceSubscriptionSeatReconcileResultSchema,
@@ -691,6 +696,14 @@ function assertIssueCreatePropertiesSnapshot(
// or a server that did not send one — the caller then falls back to
// err.message, which is what every endpoint that has not adopted this yet
// produces.
+/** The server predates batch label / property operations and ignored them. */
+export class BatchOpsUnsupportedError extends Error {
+ constructor() {
+ super("batch label and property changes are not supported by this server");
+ this.name = "BatchOpsUnsupportedError";
+ }
+}
+
export function errorCode(err: unknown): string | undefined {
if (err instanceof ApiError && err.body && typeof err.body === "object") {
const code = (err.body as { code?: unknown }).code;
@@ -1800,11 +1813,25 @@ export class ApiClient {
await this.fetch(`/api/issues/${id}`, { method: "DELETE" });
}
- async batchUpdateIssues(issueIds: string[], updates: UpdateIssueRequest): Promise<{ updated: number }> {
- return this.fetch("/api/issues/batch-update", {
+ async batchUpdateIssues(
+ issueIds: string[],
+ updates: UpdateIssueRequest,
+ ops: { labels?: BatchIssueLabelOps; properties?: BatchIssuePropertyOps } = {},
+ ): Promise<BatchUpdateIssuesResponse> {
+ const raw = await this.fetch<unknown>("/api/issues/batch-update", {
method: "POST",
- body: JSON.stringify({ issue_ids: issueIds, updates }),
+ body: JSON.stringify({ issue_ids: issueIds, updates, ...ops }),
});
+ const response = parseWithFallback(raw, BatchUpdateIssuesResponseSchema, UNCONFIRMED_BATCH_UPDATE, {
+ endpoint: "POST /api/issues/batch-update",
+ });
+ if (response.unconfirmed) return response;
+ // Older servers ignore label and property operations and answer with a
+ // bare count, which would read as success.
+ if ((ops.labels || ops.properties) && !response.results) {
+ throw new BatchOpsUnsupportedError();
+ }
+ return response;
}
async batchDeleteIssues(issueIds: string[]): Promise<{ deleted: number }> {
diff --git a/packages/core/api/index.ts b/packages/core/api/index.ts
index 68a2a5f1a2..d91fa9de42 100644
--- a/packages/core/api/index.ts
+++ b/packages/core/api/index.ts
@@ -1,6 +1,7 @@
export {
ApiClient,
ApiError,
+ BatchOpsUnsupportedError,
clientErrorMessage,
dispatchReasonCode,
errorCode,
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index a5f7137daf..dca67687ca 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1,6 +1,9 @@
import { z } from "zod";
import { normalizeIssueStatusCategory } from "../issues/config/status";
import type {
+ BatchIssueOutcome,
+ BatchIssueResult,
+ BatchUpdateIssuesResponse,
AppCatalogResponse,
AppsOverview,
TeamAppImpact,
@@ -3540,6 +3543,55 @@ export const WorkspaceSubscriptionSummarySchema = z
}),
);
+const BATCH_ISSUE_OUTCOMES: readonly string[] = [
+ "updated",
+ "unchanged",
+ "skipped",
+ "would_update",
+ "deleted",
+ "would_delete",
+] satisfies BatchIssueOutcome[];
+
+// An outcome this client does not know is not a confirmed write: it reads as
+// skipped, never as success.
+const BatchIssueResultSchema = z
+ .object({
+ issue_id: z.string().min(1),
+ identifier: z.string().optional().catch(undefined),
+ outcome: z.string(),
+ code: z.string().optional().catch(undefined),
+ message: z.string().optional().catch(undefined),
+ })
+ .loose()
+ .transform(
+ (value): BatchIssueResult => ({
+ issue_id: value.issue_id,
+ identifier: value.identifier,
+ outcome: BATCH_ISSUE_OUTCOMES.includes(value.outcome) ? (value.outcome as BatchIssueOutcome) : "skipped",
+ code: value.code,
+ message: value.message,
+ }),
+ );
+
+/** `results` is absent on servers that predate per-issue batch results. */
+export const BatchUpdateIssuesResponseSchema = z
+ .object({
+ updated: z.number().int().nonnegative(),
+ results: z.array(BatchIssueResultSchema).optional(),
+ dry_run: z.boolean().optional().catch(undefined),
+ })
+ .loose()
+ .transform(
+ (value): BatchUpdateIssuesResponse => ({
+ updated: value.updated,
+ ...(value.results ? { results: value.results } : {}),
+ ...(value.dry_run !== undefined ? { dry_run: value.dry_run } : {}),
+ }),
+ );
+
+/** A batch response that failed validation: whatever was written is unknown. */
+export const UNCONFIRMED_BATCH_UPDATE: BatchUpdateIssuesResponse = { updated: 0, unconfirmed: true };
+
export const IssueLimitUsageSchema = z
.object({
used: z.number().int().nonnegative(),
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index f43a3d6fa8..e893639566 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -51,6 +51,8 @@ import type {
ListIssuesResponse,
MoveIssueRequest,
UpdateIssueRequest,
+ BatchIssueLabelOps,
+ BatchIssuePropertyOps,
} from "../types";
import type { TimelineEntry, IssueSubscriber, Reaction } from "../types";
import { sortTimelineEntriesAsc } from "./timeline-sort";
@@ -556,10 +558,17 @@ export function useBatchUpdateIssues() {
mutationFn: ({
ids,
updates,
+ labels,
+ properties,
}: {
ids: string[];
updates: UpdateIssueRequest;
- }) => api.batchUpdateIssues(ids, updates),
+ labels?: BatchIssueLabelOps;
+ properties?: BatchIssuePropertyOps;
+ }) =>
+ labels || properties
+ ? api.batchUpdateIssues(ids, updates, { labels, properties })
+ : api.batchUpdateIssues(ids, updates),
onMutate: async ({ ids, updates }) => {
// Control and description-merge fields are not safe optimistic cache
// patches. The server resolves description against description_base, so
@@ -696,6 +705,14 @@ export function useBatchUpdateIssues() {
// refreshed below, plus the specific keys the coordinator flagged as
// drifted — the surgical replacement for the old blanket "invalidate
// myAll on project move" safety net (MUL-3669 / #4548).
+ // Label and property writes are not patched optimistically; the
+ // realtime events usually land first, and this catches a dropped socket.
+ if (_vars.labels || _vars.properties) {
+ qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.flatAll(wsId) });
+ for (const id of _vars.ids) qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, id) });
+ }
invalidateIssueDerivatives(qc, wsId, {
statusOrProjectChanged:
_vars.updates.status !== undefined ||
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 2f6783ef7c..cac27d5a5d 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -96,6 +96,46 @@ export interface UpdateIssueRequest {
duplicate_of_issue_id?: string;
}
+/** Label changes for a batch update; add and remove leave other labels alone, clear removes every label not being added. */
+export interface BatchIssueLabelOps {
+ add?: string[];
+ remove?: string[];
+ clear?: boolean;
+}
+
+/** Custom property changes for a batch update, keyed by property id. */
+export interface BatchIssuePropertyOps {
+ set?: IssuePropertyValues;
+ unset?: string[];
+}
+
+export type BatchIssueOutcome =
+ | "updated"
+ | "unchanged"
+ | "skipped"
+ | "would_update"
+ | "deleted"
+ | "would_delete";
+
+/** One issue's outcome in a batch write; skipped results carry a reason code. */
+export interface BatchIssueResult {
+ issue_id: string;
+ identifier?: string;
+ outcome: BatchIssueOutcome;
+ code?: string;
+ message?: string;
+}
+
+export interface BatchUpdateIssuesResponse {
+ /** Issues that now hold the requested values (updated or already unchanged). */
+ updated: number;
+ /** Absent on servers that predate per-issue results. */
+ results?: BatchIssueResult[];
+ dry_run?: boolean;
+ /** The response could not be read, so which issues changed is unknown. */
+ unconfirmed?: boolean;
+}
+
/** Both sides of an issue's duplicate relation (MUL-7349). */
export interface IssueDuplicates {
/** The original this issue duplicates, when it is marked as a duplicate. */
diff --git a/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx b/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
index 5c13d2fb5a..bdc9ac6897 100644
--- a/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
@@ -45,7 +45,18 @@ vi.mock("@multica/core/modals", () => ({
useModalStore: (selector: (s: { open: typeof openModal }) => unknown) => selector({ open: openModal }),
}));
-vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "label" }) }));
+// Render each message as its key path ("batch.delete_count"), so the menu
+// items the tests click are distinguishable.
+vi.mock("../../i18n", () => ({
+ useT: () => ({
+ t: (select: (keys: unknown) => unknown) => {
+ const path: string[] = [];
+ const keys: unknown = new Proxy({}, { get: (_target, key) => (path.push(String(key)), keys) });
+ select(keys);
+ return path.join(".");
+ },
+ }),
+}));
const toast = vi.hoisted(() => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn() }));
vi.mock("sonner", () => ({ toast }));
@@ -78,8 +89,25 @@ vi.mock("./pickers", () => ({
/>
</div>
),
+ AssigneePickerPanel: () => null,
+ DueDatePicker: () => null,
+ StartDatePicker: () => null,
+}));
+vi.mock("./pickers/batch-label-picker", () => ({ BatchLabelPicker: () => null }));
+vi.mock("../../projects/components/project-picker", () => ({ ProjectPicker: () => null }));
+vi.mock("@multica/core/paths", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/paths")>()),
+ useWorkspacePaths: () => ({ issueDetail: (id: string) => `/acme/issues/${id}` }),
+}));
+vi.mock("../../navigation", () => ({
+ useNavigation: () => ({ getShareableUrl: (path: string) => `https://app.example${path}` }),
}));
+async function openDeleteItem() {
+ fireEvent.click(screen.getByRole("button", { name: "batch.more" }));
+ return screen.findByRole("menuitem", { name: "batch.delete_count" });
+}
+
function makeIssue(overrides: Partial<Issue> = {}): Issue {
return {
id: "a",
@@ -163,20 +191,21 @@ describe("BatchActionToolbar status routing (MUL-4155)", () => {
});
});
- it("disables deleting a selection containing an unauthorized issue", () => {
+ it("disables deleting a selection containing an unauthorized issue", async () => {
deletionPolicy.allowed = false;
render(<BatchActionToolbar issues={[makeIssue()]} />);
- const button = screen.getByText("label", { selector: "button.text-destructive" });
- expect(button).toBeDisabled();
- fireEvent.click(button);
+ const item = await openDeleteItem();
+ expect(item).toHaveAttribute("aria-disabled", "true");
+ fireEvent.click(item);
expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
expect(batchDelete).not.toHaveBeenCalled();
});
- it("opens the dedicated delete confirmation, not the run-confirm modal", () => {
+ it("keeps delete out of the bar and opens the dedicated confirmation from the More menu", async () => {
render(<BatchActionToolbar issues={[makeIssue({ status: "todo" })]} />);
- fireEvent.click(screen.getByText("label", { selector: "button.text-destructive" }));
- expect(screen.getByRole("alertdialog")).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /delete/ })).not.toBeInTheDocument();
+ fireEvent.click(await openDeleteItem());
+ expect(await screen.findByRole("alertdialog")).toBeInTheDocument();
expect(openModal).not.toHaveBeenCalled();
expect(batchDelete).not.toHaveBeenCalled();
});
diff --git a/packages/views/issues/components/batch-action-toolbar.menu.test.tsx b/packages/views/issues/components/batch-action-toolbar.menu.test.tsx
index 71671fca11..5216985486 100644
--- a/packages/views/issues/components/batch-action-toolbar.menu.test.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.menu.test.tsx
@@ -43,6 +43,8 @@ vi.mock("./pickers", () => ({
PriorityPicker: () => null,
AssigneePicker: () => null,
AssigneePickerPanel: () => null,
+ DueDatePicker: () => null,
+ StartDatePicker: () => null,
}));
vi.mock("../../search/register-context", () => ({ useRegisterCommandBarContext: () => {} }));
vi.mock("../actions/use-issue-actions", () => ({
@@ -73,6 +75,9 @@ describe("BatchActionToolbar — batch context menu", () => {
const menu = await screen.findByRole("menu");
expect(menu).toHaveTextContent("2 selected");
expect(screen.getByRole("menuitem", { name: "Delete 2 issues" })).toBeInTheDocument();
+ for (const field of ["Labels", "Project", "Due date"]) {
+ expect(screen.getByRole("menuitem", { name: field })).toBeInTheDocument();
+ }
fireEvent.click(screen.getByRole("menuitem", { name: "Clear selection" }));
expect(selection.clear).toHaveBeenCalledTimes(1);
diff --git a/packages/views/issues/components/batch-action-toolbar.properties.test.tsx b/packages/views/issues/components/batch-action-toolbar.properties.test.tsx
new file mode 100644
index 0000000000..1d485152bb
--- /dev/null
+++ b/packages/views/issues/components/batch-action-toolbar.properties.test.tsx
@@ -0,0 +1,124 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, screen } from "@testing-library/react";
+import type { Issue, IssueProperty } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { BatchActionToolbar } from "./batch-action-toolbar";
+
+const selection = vi.hoisted(() => ({ selectedIds: new Set(["a", "b"]), clear: vi.fn() }));
+const batchUpdate = vi.hoisted(() => vi.fn());
+const PROPERTIES = vi.hoisted(() => [
+ { id: "notes", name: "Notes", type: "multi_text", config: {}, archived: false },
+] as IssueProperty[]);
+
+vi.mock("@multica/core/issues/stores/selection-store", () => ({
+ useIssueSelectionStore: (selector: (s: typeof selection) => unknown) => selector(selection),
+}));
+vi.mock("@multica/core/issues/use-issue-deletion", () => ({
+ useIssueDeletion: () => ({ canDelete: () => true }),
+}));
+vi.mock("@multica/core/issues/mutations", () => ({
+ useBatchUpdateIssues: () => ({ mutateAsync: batchUpdate, isPending: false }),
+ useBatchDeleteIssues: () => ({ mutateAsync: vi.fn(), isPending: false }),
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/issue-workflows", () => ({
+ useIssueWorkflows: () => ({ workflows: [] }),
+ sharedWorkflowStatusKeys: () => null,
+}));
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQuery: () => ({ data: PROPERTIES }),
+}));
+vi.mock("@multica/core/paths", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/paths")>()),
+ useWorkspacePaths: () => ({ issueDetail: (id: string) => `/acme/issues/${id}` }),
+}));
+vi.mock("../../navigation", () => ({
+ useNavigation: () => ({ getShareableUrl: (path: string) => `https://app.example${path}` }),
+}));
+vi.mock("./pickers", () => ({
+ StatusPicker: () => null,
+ PriorityPicker: () => null,
+ AssigneePicker: () => null,
+ AssigneePickerPanel: () => null,
+ DueDatePicker: () => null,
+ StartDatePicker: () => null,
+}));
+vi.mock("./pickers/batch-label-picker", () => ({
+ BatchLabelPicker: () => null,
+ BatchLabelPanel: () => null,
+}));
+vi.mock("../../projects/components/project-picker", () => ({ ProjectPicker: () => null }));
+vi.mock("../../search/register-context", () => ({ useRegisterCommandBarContext: () => {} }));
+const toast = vi.hoisted(() => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn(), dismiss: vi.fn() }));
+vi.mock("sonner", () => ({ toast }));
+
+function issue(id: string): Issue {
+ return { id, identifier: id, title: id, status: "todo", priority: "none", project_id: null, properties: {} } as Issue;
+}
+
+beforeEach(() => {
+ batchUpdate.mockReset();
+});
+
+async function openNotesEditor() {
+ renderWithI18n(<BatchActionToolbar issues={[issue("a"), issue("b")]} />);
+ fireEvent.click(screen.getByRole("button", { name: "More actions" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Custom properties" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Notes" }));
+ return screen.findByRole("textbox", { name: "Notes" });
+}
+
+async function submit(input: HTMLElement, value: string) {
+ fireEvent.change(input, { target: { value } });
+ fireEvent.submit(input.closest("form")!);
+ await act(async () => {});
+}
+
+const sentNotes = () => batchUpdate.mock.calls.map(([request]) => request.properties.set.notes);
+
+describe("BatchActionToolbar multi-value property editor", () => {
+ it("keeps the draft locked while the save is in flight, so a second entry cannot replace the first", async () => {
+ batchUpdate.mockReturnValue(new Promise(() => {}));
+ const input = await openNotesEditor();
+
+ await submit(input, "alpha");
+ expect(batchUpdate).toHaveBeenCalledWith({ ids: ["a", "b"], updates: {}, properties: { set: { notes: ["alpha"] } } });
+ expect(input).toHaveValue("alpha");
+ expect(input).toHaveAttribute("readonly");
+
+ await submit(input, "beta");
+ expect(sentNotes()).toEqual([["alpha"]]);
+ });
+
+ it("keeps the draft and shows the failure when the write does not apply", async () => {
+ batchUpdate.mockResolvedValue({
+ updated: 1,
+ results: [
+ { issue_id: "a", outcome: "updated" },
+ { issue_id: "b", outcome: "skipped", code: "properties_too_large" },
+ ],
+ });
+ const input = await openNotesEditor();
+
+ await submit(input, "alpha");
+ expect(input).toHaveValue("alpha");
+ expect(input).not.toHaveAttribute("readonly");
+ expect(screen.getByText("Failed to update issues")).toBeInTheDocument();
+ });
+
+ it("clears the draft once every issue took the value", async () => {
+ batchUpdate.mockResolvedValue({
+ updated: 2,
+ results: [
+ { issue_id: "a", outcome: "updated" },
+ { issue_id: "b", outcome: "updated" },
+ ],
+ });
+ const input = await openNotesEditor();
+
+ await submit(input, "alpha");
+ expect(input).toHaveValue("");
+ expect(input).not.toHaveAttribute("readonly");
+ });
+});
diff --git a/packages/views/issues/components/batch-action-toolbar.test.tsx b/packages/views/issues/components/batch-action-toolbar.test.tsx
index 4c232f1a9f..7fcb583104 100644
--- a/packages/views/issues/components/batch-action-toolbar.test.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.test.tsx
@@ -95,6 +95,20 @@ vi.mock("./pickers", () => ({
data-mixed={String(Boolean(mixed))}
/>
),
+ DueDatePicker: ({ dueDate }: { dueDate: string | null }) => (
+ <div data-testid="due-date-picker" data-due={dueDate ?? "__none__"} />
+ ),
+ StartDatePicker: () => null,
+}));
+vi.mock("./pickers/batch-label-picker", () => ({
+ BatchLabelPicker: ({ issues }: { issues: Issue[] }) => (
+ <div data-testid="label-picker" data-issues={issues.map((issue) => issue.id).join(",")} />
+ ),
+}));
+vi.mock("../../projects/components/project-picker", () => ({
+ ProjectPicker: ({ projectId }: { projectId: string | null | undefined }) => (
+ <div data-testid="project-picker" data-project={projectId === undefined ? "__mixed__" : projectId ?? "__none__"} />
+ ),
}));
function makeIssue(overrides: Partial<Issue> = {}): Issue {
@@ -177,6 +191,25 @@ describe("BatchActionToolbar picker wiring", () => {
expect(assignee).toHaveAttribute("data-assignee-id", "__null__");
});
+ it("hands the label, project and due date pickers the selection's shared values", () => {
+ const issues = [
+ makeIssue({ id: "a", project_id: "p-dev", due_date: "2026-02-01" }),
+ makeIssue({ id: "b", project_id: "p-dev", due_date: "2026-02-01" }),
+ makeIssue({ id: "c", project_id: null, due_date: "2026-03-01" }),
+ ];
+ selection.selectedIds = new Set(["a", "b"]);
+ const view = render(<BatchActionToolbar issues={issues} />);
+
+ expect(screen.getByTestId("label-picker")).toHaveAttribute("data-issues", "a,b");
+ expect(screen.getByTestId("project-picker")).toHaveAttribute("data-project", "p-dev");
+ expect(screen.getByTestId("due-date-picker")).toHaveAttribute("data-due", "2026-02-01");
+
+ selection.selectedIds = new Set(["a", "b", "c"]);
+ view.rerender(<BatchActionToolbar issues={[...issues]} />);
+ expect(screen.getByTestId("project-picker")).toHaveAttribute("data-project", "__mixed__");
+ expect(screen.getByTestId("due-date-picker")).toHaveAttribute("data-due", "__none__");
+ });
+
it("offers only the statuses every selected project's workflow allows", () => {
const issues = [
makeIssue({ id: "a", project_id: "p-dev" }),
diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsx
index 52e9f4d4f8..32b6daefaa 100644
--- a/packages/views/issues/components/batch-action-toolbar.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
-import { Check, CircleDot, Link2, Trash2, UserMinus, X } from "@multica/ui/icons";
+import { Ellipsis } from "@multica/ui/icons";
import { toast } from "sonner";
import { Button } from "@multica/ui/components/ui/button";
import {
@@ -14,34 +14,36 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@multica/ui/components/ui/alert-dialog";
+import { ContextMenu, ContextMenuContent } from "@multica/ui/components/ui/context-menu";
import {
- ContextMenu,
- ContextMenuContent,
- ContextMenuItem,
- ContextMenuSeparator,
- ContextMenuSub,
- ContextMenuSubContent,
- ContextMenuSubTrigger,
-} from "@multica/ui/components/ui/context-menu";
-import { copyText } from "@multica/ui/lib/clipboard";
-import { PRIORITY_CONFIG, PRIORITY_DISPLAY_ORDER } from "@multica/core/issues/config";
-import { useWorkspacePaths } from "@multica/core/paths";
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
import { useQuery } from "@tanstack/react-query";
import { useIssueDeletion } from "@multica/core/issues/use-issue-deletion";
-import type { Issue, UpdateIssueRequest } from "@multica/core/types";
+import {
+ isListPropertyType,
+ type BatchIssueLabelOps,
+ type BatchIssuePropertyOps,
+ type Issue,
+ type UpdateIssueRequest,
+} from "@multica/core/types";
import { useWorkspaceId } from "@multica/core/hooks";
import { commonIssueFields } from "@multica/core/issues/batch";
import { sharedWorkflowStatusKeys, useIssueWorkflows } from "@multica/core/issue-workflows";
import { projectListOptions } from "@multica/core/projects/queries";
import { useBatchUpdateIssues, useBatchDeleteIssues } from "@multica/core/issues/mutations";
import { useModalStore } from "@multica/core/modals";
-import { StatusPicker, PriorityPicker, AssigneePicker, AssigneePickerPanel } from "./pickers";
-import { StatusIcon } from "./status-icon";
-import { PriorityIcon } from "./priority-icon";
-import { useIssueStatusOptions } from "../utils/status-options";
-import { SubmenuPanel } from "../actions/issue-actions-menu-items";
+import { StatusPicker, PriorityPicker, AssigneePicker, DueDatePicker, StartDatePicker } from "./pickers";
+import { BatchLabelPicker } from "./pickers/batch-label-picker";
+import { CustomPropertyValueInput } from "./pickers/custom-property-picker";
+import { BatchMenuItems, sharedPropertyValue, type BatchEditor } from "./batch-menu-items";
+import { useBatchResultToast } from "./batch-result-toast";
+import { contextPrimitives, dropdownPrimitives } from "../../common/menu-primitives";
import { useRegisterIssueBatchMenu } from "../actions/issue-actions-context-menu";
-import { useNavigation } from "../../navigation";
+import { IssuePickerModal } from "../../modals/issue-picker-modal";
+import { ProjectPicker } from "../../projects/components/project-picker";
import { useT } from "../../i18n";
import { CollectionBatchBar } from "../../layout/collection-list";
import { useIssueSurfaceActionsOptional } from "../surface/actions-context";
@@ -127,6 +129,12 @@ export function BatchActionToolbar({
const [statusOpen, setStatusOpen] = useState(false);
const [priorityOpen, setPriorityOpen] = useState(false);
const [assigneeOpen, setAssigneeOpen] = useState(false);
+ const [labelsOpen, setLabelsOpen] = useState(false);
+ const [projectOpen, setProjectOpen] = useState(false);
+ const [dueOpen, setDueOpen] = useState(false);
+ const [moreOpen, setMoreOpen] = useState(false);
+ const [parentOpen, setParentOpen] = useState(false);
+ const [editor, setEditor] = useState<BatchEditor | null>(null);
const [deleteOpen, setDeleteOpen] = useState(false);
const [menuPoint, setMenuPoint] = useState<{ x: number; y: number } | null>(null);
const [menuOpen, setMenuOpen] = useState(false);
@@ -149,39 +157,63 @@ export function BatchActionToolbar({
const batchUpdate = useBatchUpdateIssues();
const batchDelete = useBatchDeleteIssues();
const openModal = useModalStore((s) => s.open);
+ const { report, reportError } = useBatchResultToast();
const loading =
surfaceActions?.isPending ?? (batchUpdate.isPending || batchDelete.isPending);
const ids = selectedIssues.map((issue) => issue.id);
+ // The same rule as commonIssueFields, for the nullable fields the bar adds:
+ // undefined when the selection disagrees, so no row is checked.
+ const sharedProject = shared(selectedIssues, (issue) => issue.project_id ?? null);
+ const sharedDueDate = shared(selectedIssues, (issue) => issue.due_date ?? null);
+ const sharedStartDate = shared(selectedIssues, (issue) => issue.start_date ?? null);
+
useEffect(() => {
if (count > 0) return;
setStatusOpen(false);
setPriorityOpen(false);
setAssigneeOpen(false);
+ setLabelsOpen(false);
+ setProjectOpen(false);
+ setDueOpen(false);
+ setMoreOpen(false);
+ setParentOpen(false);
+ setEditor(null);
setDeleteOpen(false);
setMenuOpen(false);
}, [count]);
- const handleBatchUpdate = async (updates: Partial<UpdateIssueRequest>) => {
+ const selectOnly = (issueIds: string[]) => {
+ clear();
+ selection.select(issueIds);
+ };
+
+ const handleBatchUpdate = async (
+ updates: Partial<UpdateIssueRequest>,
+ ops: { labels?: BatchIssueLabelOps; properties?: BatchIssuePropertyOps } = {},
+ { quiet = false }: { quiet?: boolean } = {},
+ ): Promise<boolean> => {
try {
- const { updated } = surfaceActions
- ? await surfaceActions.batchUpdate(ids, updates)
- : await batchUpdate.mutateAsync({ ids, updates });
- if (updated < count) {
- toast.warning(t(($) => $.batch.update_partial, { updated, count }));
- } else {
- if (clearSelectionOnApply) clear();
- toast.success(t(($) => $.batch.update_success, { count }));
- }
+ const response = surfaceActions
+ ? await surfaceActions.batchUpdate(ids, updates, ops)
+ : await batchUpdate.mutateAsync({ ids, updates, ...ops });
+ const applied = report(response, count, {
+ onSelectSkipped: selectOnly,
+ successMessage: quiet ? null : undefined,
+ });
+ if (applied && clearSelectionOnApply && !quiet) clear();
+ return applied;
} catch (err) {
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.batch.update_failed),
- );
+ reportError(err);
+ return false;
}
};
+ // Label toggles stay quiet on success: the picker stays open for the next
+ // toggle and the rows themselves show the result.
+ const handleLabels = (labels: BatchIssueLabelOps) => handleBatchUpdate({}, { labels }, { quiet: !labels.clear });
+ const handleProperties = (properties: BatchIssuePropertyOps) => handleBatchUpdate({}, { properties });
+
// 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,
@@ -240,6 +272,54 @@ export function BatchActionToolbar({
}
};
+ // An editor picked from a menu opens once that menu has closed, so the
+ // menu's focus return does not dismiss it.
+ const openEditor = (next: BatchEditor) => {
+ setMoreOpen(false);
+ setMenuOpen(false);
+ setTimeout(() => setEditor(next), 0);
+ };
+ const openSetParent = () => {
+ setMoreOpen(false);
+ setMenuOpen(false);
+ setParentOpen(true);
+ };
+
+ const menuProps = {
+ issues: selectedIssues,
+ common,
+ projectId: sharedProjectId,
+ allowedStatuses,
+ disabled: loading,
+ canDelete: canDeleteSelection,
+ onStatus: (status: string) => handleBatchStatus({ status }),
+ onAssignee: handleBatchAssignee,
+ onUpdate: (updates: Partial<UpdateIssueRequest>) => void handleBatchUpdate(updates),
+ onLabels: handleLabels,
+ onProperties: (properties: BatchIssuePropertyOps) => void handleProperties(properties),
+ onEditor: openEditor,
+ onSetParent: openSetParent,
+ onDelete: () => {
+ setMoreOpen(false);
+ setMenuOpen(false);
+ setDeleteOpen(true);
+ },
+ };
+
+ const barButton = <Button variant="ghost" size="sm" disabled={loading} />;
+ // Editors opened from a menu anchor on the "More" button.
+ const editorAnchor = (
+ <button
+ type="button"
+ tabIndex={-1}
+ aria-hidden
+ className="pointer-events-none absolute inset-0 overflow-hidden opacity-0"
+ />
+ );
+ const closeEditor = (open: boolean) => {
+ if (!open) setEditor(null);
+ };
+
return (
<>
<CollectionBatchBar
@@ -258,7 +338,7 @@ export function BatchActionToolbar({
onUpdate={handleBatchStatus}
open={statusOpen}
onOpenChange={setStatusOpen}
- triggerRender={<Button variant="ghost" size="sm" disabled={loading} />}
+ triggerRender={barButton}
trigger={t(($) => $.batch.status)}
align="center"
/>
@@ -269,7 +349,7 @@ export function BatchActionToolbar({
onUpdate={handleBatchUpdate}
open={priorityOpen}
onOpenChange={setPriorityOpen}
- triggerRender={<Button variant="ghost" size="sm" disabled={loading} />}
+ triggerRender={barButton}
trigger={t(($) => $.batch.priority)}
align="center"
/>
@@ -282,41 +362,134 @@ export function BatchActionToolbar({
onUpdate={handleBatchAssignee}
open={assigneeOpen}
onOpenChange={setAssigneeOpen}
- triggerRender={<Button variant="ghost" size="sm" disabled={loading} />}
+ triggerRender={barButton}
trigger={t(($) => $.batch.assignee)}
align="center"
/>
- {/* Delete */}
- <Button
- variant="ghost"
- size="sm"
- disabled={loading || !canDeleteSelection}
- title={!canDeleteSelection ? t(($) => $.batch.delete_restricted) : undefined}
- onClick={() => setDeleteOpen(true)}
- className="text-destructive hover:text-destructive"
- >
- <Trash2 className="size-3.5 mr-1" />
- {t(($) => $.batch.delete)}
- </Button>
+ {/* Labels */}
+ <BatchLabelPicker
+ issues={selectedIssues}
+ onApply={handleLabels}
+ open={labelsOpen}
+ onOpenChange={setLabelsOpen}
+ triggerRender={barButton}
+ trigger={t(($) => $.batch.labels)}
+ />
+
+ {/* Project */}
+ <ProjectPicker
+ projectId={sharedProject}
+ onUpdate={handleBatchUpdate}
+ open={projectOpen}
+ onOpenChange={setProjectOpen}
+ triggerRender={barButton}
+ trigger={t(($) => $.batch.project)}
+ align="center"
+ />
+
+ {/* Due date */}
+ <DueDatePicker
+ dueDate={sharedDueDate ?? null}
+ onUpdate={handleBatchUpdate}
+ open={dueOpen}
+ onOpenChange={setDueOpen}
+ triggerRender={barButton}
+ trigger={t(($) => $.batch.due_date)}
+ align="center"
+ />
+
+ {/* More: the remaining fields, copy links and delete */}
+ <span className="relative inline-flex">
+ <DropdownMenu open={moreOpen} onOpenChange={setMoreOpen}>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={loading}
+ aria-label={t(($) => $.batch.more)}
+ title={t(($) => $.batch.more)}
+ />
+ }
+ >
+ <Ellipsis className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="top" align="end" className="w-auto min-w-52">
+ <BatchMenuItems
+ primitives={dropdownPrimitives}
+ variant="more"
+ {...menuProps}
+ onClose={() => setMoreOpen(false)}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {editor?.kind === "start_date" && (
+ <StartDatePicker
+ startDate={sharedStartDate ?? null}
+ onUpdate={handleBatchUpdate}
+ open
+ onOpenChange={closeEditor}
+ triggerRender={editorAnchor}
+ align="end"
+ />
+ )}
+ {editor?.kind === "due_date" && (
+ <DueDatePicker
+ dueDate={sharedDueDate ?? null}
+ onUpdate={handleBatchUpdate}
+ open
+ onOpenChange={closeEditor}
+ triggerRender={editorAnchor}
+ align="end"
+ />
+ )}
+ {editor?.kind === "property" && (
+ <CustomPropertyValueInput
+ key={editor.property.id}
+ property={editor.property}
+ value={sharedPropertyValue(selectedIssues, editor.property.id)}
+ onChange={(value) => {
+ const save = handleProperties(
+ value === undefined
+ ? { unset: [editor.property.id] }
+ : { set: { [editor.property.id]: value } },
+ );
+ // List editors hold their draft and lock input until the write
+ // settles, and show a rejection beside the draft.
+ if (!isListPropertyType(editor.property.type)) return;
+ return save.then((applied) => {
+ if (!applied) throw new Error(t(($) => $.batch.update_failed));
+ });
+ }}
+ open
+ onOpenChange={closeEditor}
+ triggerRender={editorAnchor}
+ />
+ )}
+ </span>
</CollectionBatchBar>
{menuPoint && count > 1 && (
- <BatchContextMenu
- point={menuPoint}
- open={menuOpen}
- onOpenChange={setMenuOpen}
- issues={selectedIssues}
- projectId={sharedProjectId}
- allowedStatuses={allowedStatuses}
- common={common}
- disabled={loading}
- canDelete={canDeleteSelection}
- onStatus={(status) => handleBatchStatus({ status })}
- onPriority={(priority) => void handleBatchUpdate({ priority })}
- onAssignee={handleBatchAssignee}
- onClear={clear}
- onDelete={() => setDeleteOpen(true)}
+ <BatchContextMenu point={menuPoint} open={menuOpen} onOpenChange={setMenuOpen}>
+ <BatchMenuItems
+ primitives={contextPrimitives}
+ variant="context"
+ {...menuProps}
+ onClearSelection={clear}
+ onClose={() => setMenuOpen(false)}
+ />
+ </BatchContextMenu>
+ )}
+
+ {parentOpen && (
+ <IssuePickerModal
+ open
+ onOpenChange={setParentOpen}
+ title={t(($) => $.batch.set_parent_title, { count })}
+ description={t(($) => $.batch.set_parent_description, { count })}
+ excludeIds={ids}
+ onSelect={(parent) => void handleBatchUpdate({ parent_issue_id: parent.id })}
/>
)}
@@ -346,145 +519,36 @@ export function BatchActionToolbar({
);
}
-/** The batch bar's actions at the cursor, for a right-click on a selected row. */
+/** The value every issue shares, or undefined when they differ. */
+function shared<T>(issues: readonly Issue[], pick: (issue: Issue) => T): T | undefined {
+ const first = issues[0];
+ if (!first) return undefined;
+ const value = pick(first);
+ return issues.every((issue) => pick(issue) === value) ? value : undefined;
+}
+
+/** The batch menu at the cursor, for a right-click on a selected row. */
function BatchContextMenu({
point,
open,
onOpenChange,
- issues,
- projectId,
- allowedStatuses,
- common,
- disabled,
- canDelete,
- onStatus,
- onPriority,
- onAssignee,
- onClear,
- onDelete,
+ children,
}: {
point: { x: number; y: number };
open: boolean;
onOpenChange: (open: boolean) => void;
- issues: Issue[];
- projectId: string | null;
- allowedStatuses: ReadonlySet<string> | null;
- common: ReturnType<typeof commonIssueFields>;
- disabled: boolean;
- canDelete: boolean;
- onStatus: (status: string) => void;
- onPriority: (priority: Issue["priority"]) => void;
- onAssignee: (updates: Partial<UpdateIssueRequest>) => void;
- onClear: () => void;
- onDelete: () => void;
+ children: React.ReactNode;
}) {
- const { t } = useT("issues");
- const { t: tLayout } = useT("layout");
- const wsId = useWorkspaceId();
- const paths = useWorkspacePaths();
- const { getShareableUrl } = useNavigation();
- const { options } = useIssueStatusOptions(wsId, projectId ?? undefined, common.status);
- const statusOptions = allowedStatuses ? options.filter((o) => allowedStatuses.has(o.key)) : options;
- const count = issues.length;
const anchor = useMemo(
() => ({
getBoundingClientRect: () => DOMRect.fromRect({ x: point.x, y: point.y, width: 0, height: 0 }),
}),
[point.x, point.y],
);
- const copyLinks = () => {
- const links = issues.map((issue) => getShareableUrl(paths.issueDetail(issue.identifier || issue.id)));
- void copyText(links.join("\n")).then((ok) => {
- if (ok) toast.success(t(($) => $.batch.links_copied, { count }));
- });
- };
-
return (
<ContextMenu open={open} onOpenChange={onOpenChange}>
<ContextMenuContent anchor={anchor} className="w-auto min-w-52">
- <div className="px-2 pt-1 pb-1.5 text-caption text-muted-foreground">
- {t(($) => $.batch.selected, { count })}
- </div>
- <ContextMenuSeparator />
- <ContextMenuSub>
- <ContextMenuSubTrigger disabled={disabled}>
- {common.status ? (
- <StatusIcon status={common.status} className="h-3.5 w-3.5" />
- ) : (
- <CircleDot className="h-3.5 w-3.5" />
- )}
- {t(($) => $.batch.status)}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent>
- {statusOptions.map((option) => (
- <ContextMenuItem key={option.key} onClick={() => onStatus(option.key)}>
- <StatusIcon
- status={option.key}
- category={option.category}
- color={option.color}
- icon={option.icon}
- className="h-3.5 w-3.5"
- />
- {option.label}
- {common.status === option.key && <Check className="ml-auto size-3.5 text-muted-foreground" />}
- </ContextMenuItem>
- ))}
- </ContextMenuSubContent>
- </ContextMenuSub>
- <ContextMenuSub>
- <ContextMenuSubTrigger disabled={disabled}>
- <PriorityIcon priority={common.priority ?? "none"} />
- {t(($) => $.batch.priority)}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent>
- {PRIORITY_DISPLAY_ORDER.map((p) => (
- <ContextMenuItem key={p} onClick={() => onPriority(p)}>
- <span
- className={`inline-flex items-center gap-1 rounded-xs px-1.5 py-0.5 text-caption font-medium ${PRIORITY_CONFIG[p].badgeBg} ${PRIORITY_CONFIG[p].badgeText}`}
- >
- <PriorityIcon priority={p} className="h-3 w-3" inheritColor />
- {t(($) => $.priority[p])}
- </span>
- {common.priority === p && <Check className="ml-auto size-3.5 text-muted-foreground" />}
- </ContextMenuItem>
- ))}
- </ContextMenuSubContent>
- </ContextMenuSub>
- <ContextMenuSub>
- <ContextMenuSubTrigger disabled={disabled}>
- <UserMinus className="h-3.5 w-3.5" />
- {t(($) => $.batch.assignee)}
- </ContextMenuSubTrigger>
- <ContextMenuSubContent className="w-64 p-0">
- <SubmenuPanel>
- <AssigneePickerPanel
- assigneeType={common.assignee?.type ?? null}
- assigneeId={common.assignee?.id ?? null}
- onUpdate={onAssignee}
- onPicked={() => onOpenChange(false)}
- />
- </SubmenuPanel>
- </ContextMenuSubContent>
- </ContextMenuSub>
- <ContextMenuSeparator />
- <ContextMenuItem onClick={copyLinks}>
- <Link2 className="h-3.5 w-3.5" />
- {t(($) => $.batch.copy_links)}
- </ContextMenuItem>
- <ContextMenuItem onClick={onClear}>
- <X className="h-3.5 w-3.5" />
- {tLayout(($) => $.collection.clear_selection)}
- </ContextMenuItem>
- <ContextMenuSeparator />
- <ContextMenuItem
- variant="destructive"
- disabled={disabled || !canDelete}
- title={!canDelete ? t(($) => $.batch.delete_restricted) : undefined}
- onClick={onDelete}
- >
- <Trash2 className="h-3.5 w-3.5" />
- {t(($) => $.batch.delete_count, { count })}
- </ContextMenuItem>
+ {children}
</ContextMenuContent>
</ContextMenu>
);
diff --git a/packages/views/issues/components/batch-menu-items.test.tsx b/packages/views/issues/components/batch-menu-items.test.tsx
new file mode 100644
index 0000000000..be08f85bc0
--- /dev/null
+++ b/packages/views/issues/components/batch-menu-items.test.tsx
@@ -0,0 +1,84 @@
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, screen } from "@testing-library/react";
+import { DropdownMenu, DropdownMenuContent } from "@multica/ui/components/ui/dropdown-menu";
+import { commonIssueFields } from "@multica/core/issues/batch";
+import type { Issue, IssueProperty } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { dropdownPrimitives } from "../../common/menu-primitives";
+import { BatchMenuItems } from "./batch-menu-items";
+
+const PROPERTIES = vi.hoisted(
+ () => [{ id: "notes", name: "Notes", type: "text", config: {}, archived: false }] as IssueProperty[],
+);
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQuery: () => ({ data: PROPERTIES }),
+}));
+vi.mock("@multica/core/paths", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/paths")>()),
+ useWorkspacePaths: () => ({ issueDetail: (id: string) => `/acme/issues/${id}` }),
+}));
+vi.mock("../../navigation", () => ({
+ useNavigation: () => ({ getShareableUrl: (path: string) => `https://app.example${path}` }),
+}));
+
+function issue(id: string, notes?: string): Issue {
+ return { id, identifier: id, properties: notes === undefined ? {} : { notes } } as Issue;
+}
+
+function renderMenu(issues: Issue[]) {
+ const onProperties = vi.fn();
+ const onEditor = vi.fn();
+ renderWithI18n(
+ <DropdownMenu open>
+ <DropdownMenuContent>
+ <BatchMenuItems
+ primitives={dropdownPrimitives}
+ variant="more"
+ issues={issues}
+ common={commonIssueFields(issues)}
+ projectId={null}
+ allowedStatuses={null}
+ disabled={false}
+ canDelete
+ onStatus={vi.fn()}
+ onAssignee={vi.fn()}
+ onUpdate={vi.fn()}
+ onLabels={vi.fn().mockResolvedValue(true)}
+ onProperties={onProperties}
+ onEditor={onEditor}
+ onSetParent={vi.fn()}
+ onDelete={vi.fn()}
+ onClose={vi.fn()}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>,
+ );
+ fireEvent.click(screen.getByRole("menuitem", { name: "Custom properties" }));
+ return { onProperties, onEditor };
+}
+
+describe("BatchMenuItems custom properties", () => {
+ it("clears a text property whose values differ across the selection", async () => {
+ const { onProperties } = renderMenu([issue("a", "alpha"), issue("b", "beta"), issue("c")]);
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Notes" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Clear (2 set)" }));
+ expect(onProperties).toHaveBeenCalledWith({ unset: ["notes"] });
+ });
+
+ it("still offers the editor next to the clear action", async () => {
+ const { onEditor } = renderMenu([issue("a", "alpha"), issue("b", "beta")]);
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Notes" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Set value…" }));
+ expect(onEditor).toHaveBeenCalledWith({ kind: "property", property: PROPERTIES[0] });
+ });
+
+ it("opens the editor directly when no selected issue has a value", async () => {
+ const { onEditor } = renderMenu([issue("a"), issue("b")]);
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Notes" }));
+ expect(onEditor).toHaveBeenCalledWith({ kind: "property", property: PROPERTIES[0] });
+ expect(screen.queryByRole("menuitem", { name: /Clear/ })).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/issues/components/batch-menu-items.tsx b/packages/views/issues/components/batch-menu-items.tsx
new file mode 100644
index 0000000000..4977a9873b
--- /dev/null
+++ b/packages/views/issues/components/batch-menu-items.tsx
@@ -0,0 +1,494 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import {
+ ArrowUp,
+ Calendar,
+ CalendarClock,
+ Check,
+ CircleDot,
+ FolderKanban,
+ Link2,
+ Milestone,
+ SlidersHorizontal,
+ Tag,
+ Trash2,
+ Unlink,
+ UserMinus,
+ X,
+} from "@multica/ui/icons";
+import { copyText } from "@multica/ui/lib/clipboard";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { PRIORITY_CONFIG, PRIORITY_DISPLAY_ORDER } from "@multica/core/issues/config";
+import { addDaysDateOnly, todayDateOnly } from "@multica/core/issues/date";
+import type { CommonIssueFields } from "@multica/core/issues/batch";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { propertyListOptions } from "@multica/core/properties";
+import { paletteColor } from "@multica/core/appearance";
+import type {
+ BatchIssuePropertyOps,
+ Issue,
+ IssueProperty,
+ IssuePropertyValue,
+ UpdateIssueRequest,
+} from "@multica/core/types";
+import type { MenuPrimitives } from "../../common/menu-primitives";
+import { PropertyIcon } from "../../common/property-icon";
+import { ProjectIcon } from "../../projects/components/project-icon";
+import { useNavigation } from "../../navigation";
+import { SubmenuPanel } from "../actions/issue-actions-menu-items";
+import { useIssueStatusOptions } from "../utils/status-options";
+import { AssigneePickerPanel } from "./pickers";
+import { BatchLabelPanel, type BatchLabelApply } from "./pickers/batch-label-picker";
+import { stageOptions } from "./pickers/stage-picker";
+import { StatusIcon } from "./status-icon";
+import { PriorityIcon } from "./priority-icon";
+import { useT } from "../../i18n";
+
+/** Editors too rich for a menu row; the toolbar opens them above its "More" button. */
+export type BatchEditor =
+ | { kind: "start_date" }
+ | { kind: "due_date" }
+ | { kind: "property"; property: IssueProperty };
+
+/** Property types whose values fit in a submenu of plain rows. */
+const INLINE_PROPERTY_TYPES = new Set(["select", "checkbox"]);
+
+function dateUpdate(field: "start_date" | "due_date", value: string | null): Partial<UpdateIssueRequest> {
+ return field === "start_date" ? { start_date: value } : { due_date: value };
+}
+
+/** The value every issue shares for a property, or undefined when they differ or none has one. */
+export function sharedPropertyValue(issues: readonly Issue[], propertyId: string): IssuePropertyValue | undefined {
+ const first = issues[0]?.properties?.[propertyId];
+ if (first === undefined) return undefined;
+ const key = JSON.stringify(first);
+ return issues.every((issue) => JSON.stringify(issue.properties?.[propertyId]) === key) ? first : undefined;
+}
+
+interface BatchMenuItemsProps {
+ primitives: MenuPrimitives;
+ /** `more` is the toolbar's overflow menu; `context` is the right-click menu, which repeats the toolbar's own fields. */
+ variant: "more" | "context";
+ issues: Issue[];
+ common: CommonIssueFields;
+ projectId: string | null;
+ allowedStatuses: ReadonlySet<string> | null;
+ disabled: boolean;
+ canDelete: boolean;
+ onStatus: (status: string) => void;
+ onAssignee: (updates: Partial<UpdateIssueRequest>) => void;
+ onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
+ onLabels: BatchLabelApply;
+ onProperties: (ops: BatchIssuePropertyOps) => void;
+ onEditor: (editor: BatchEditor) => void;
+ onSetParent: () => void;
+ onClearSelection?: () => void;
+ onDelete: () => void;
+ onClose: () => void;
+}
+
+export function BatchMenuItems({
+ primitives: P,
+ variant,
+ issues,
+ common,
+ projectId,
+ allowedStatuses,
+ disabled,
+ canDelete,
+ onStatus,
+ onAssignee,
+ onUpdate,
+ onLabels,
+ onProperties,
+ onEditor,
+ onSetParent,
+ onClearSelection,
+ onDelete,
+ onClose,
+}: BatchMenuItemsProps) {
+ const { t } = useT("issues");
+ const { t: tLayout } = useT("layout");
+ const wsId = useWorkspaceId();
+ const paths = useWorkspacePaths();
+ const { getShareableUrl } = useNavigation();
+ const { data: properties = [] } = useQuery(propertyListOptions(wsId));
+ const count = issues.length;
+ const anyParent = issues.some((issue) => !!issue.parent_issue_id);
+ const allChildren = count > 0 && issues.every((issue) => !!issue.parent_issue_id);
+ const sharedStage = issues.every((issue) => issue.stage === issues[0]?.stage) ? (issues[0]?.stage ?? null) : null;
+ const maxStage = issues.reduce((max, issue) => Math.max(max, issue.stage ?? 0), 0);
+
+ const copyLinks = () => {
+ const links = issues.map((issue) => getShareableUrl(paths.issueDetail(issue.identifier || issue.id)));
+ void copyText(links.join("\n")).then((ok) => {
+ if (ok) toast.success(t(($) => $.batch.links_copied, { count }));
+ });
+ };
+
+ const dateItems = (field: "start_date" | "due_date") => {
+ const hasValue = issues.some((issue) => !!issue[field]);
+ const labels =
+ field === "start_date"
+ ? {
+ today: t(($) => $.actions.start_today),
+ tomorrow: t(($) => $.actions.start_tomorrow),
+ nextWeek: t(($) => $.actions.start_next_week),
+ clear: t(($) => $.actions.start_clear),
+ }
+ : {
+ today: t(($) => $.actions.due_today),
+ tomorrow: t(($) => $.actions.due_tomorrow),
+ nextWeek: t(($) => $.actions.due_next_week),
+ clear: t(($) => $.actions.due_clear),
+ };
+ return (
+ <>
+ <P.Item onClick={() => onUpdate(dateUpdate(field, todayDateOnly()))}>{labels.today}</P.Item>
+ <P.Item onClick={() => onUpdate(dateUpdate(field, addDaysDateOnly(1)))}>{labels.tomorrow}</P.Item>
+ <P.Item onClick={() => onUpdate(dateUpdate(field, addDaysDateOnly(7)))}>{labels.nextWeek}</P.Item>
+ <P.Item onClick={() => onEditor({ kind: field })}>{t(($) => $.batch.pick_date)}</P.Item>
+ {hasValue && (
+ <>
+ <P.Separator />
+ <P.Item onClick={() => onUpdate(dateUpdate(field, null))}>{labels.clear}</P.Item>
+ </>
+ )}
+ </>
+ );
+ };
+
+ const activeProperties = properties.filter((property) => !property.archived);
+
+ return (
+ <>
+ {variant === "context" && (
+ <>
+ <div className="px-2 pt-1 pb-1.5 text-caption text-muted-foreground">
+ {t(($) => $.batch.selected, { count })}
+ </div>
+ <P.Separator />
+ <StatusSub P={P} projectId={projectId} allowedStatuses={allowedStatuses} common={common} disabled={disabled} onStatus={onStatus} />
+ <P.Sub>
+ <P.SubTrigger disabled={disabled}>
+ <PriorityIcon priority={common.priority ?? "none"} />
+ {t(($) => $.batch.priority)}
+ </P.SubTrigger>
+ <P.SubContent>
+ {PRIORITY_DISPLAY_ORDER.map((p) => (
+ <P.Item key={p} onClick={() => onUpdate({ priority: p })}>
+ <span
+ className={`inline-flex items-center gap-1 rounded-xs px-1.5 py-0.5 text-caption font-medium ${PRIORITY_CONFIG[p].badgeBg} ${PRIORITY_CONFIG[p].badgeText}`}
+ >
+ <PriorityIcon priority={p} className="h-3 w-3" inheritColor />
+ {t(($) => $.priority[p])}
+ </span>
+ {common.priority === p && <Check className="ml-auto size-3.5 text-muted-foreground" />}
+ </P.Item>
+ ))}
+ </P.SubContent>
+ </P.Sub>
+ <P.Sub>
+ <P.SubTrigger disabled={disabled}>
+ <UserMinus className="h-3.5 w-3.5" />
+ {t(($) => $.batch.assignee)}
+ </P.SubTrigger>
+ <P.SubContent className="w-64 p-0">
+ <SubmenuPanel>
+ <AssigneePickerPanel
+ assigneeType={common.assignee?.type ?? null}
+ assigneeId={common.assignee?.id ?? null}
+ onUpdate={onAssignee}
+ onPicked={onClose}
+ />
+ </SubmenuPanel>
+ </P.SubContent>
+ </P.Sub>
+ <P.Sub>
+ <P.SubTrigger disabled={disabled}>
+ <Tag className="h-3.5 w-3.5" />
+ {t(($) => $.batch.labels)}
+ </P.SubTrigger>
+ <P.SubContent className="w-72 p-0">
+ <SubmenuPanel>
+ <BatchLabelPanel issues={issues} onApply={onLabels} onClose={onClose} />
+ </SubmenuPanel>
+ </P.SubContent>
+ </P.Sub>
+ <ProjectSub P={P} issues={issues} disabled={disabled} onUpdate={onUpdate} />
+ <P.Sub>
+ <P.SubTrigger disabled={disabled}>
+ <Calendar className="h-3.5 w-3.5" />
+ {t(($) => $.batch.due_date)}
+ </P.SubTrigger>
+ <P.SubContent>{dateItems("due_date")}</P.SubContent>
+ </P.Sub>
+ <P.Separator />
+ </>
+ )}
+
+ <P.Sub>
+ <P.SubTrigger disabled={disabled}>
+ <CalendarClock className="h-3.5 w-3.5" />
+ {t(($) => $.actions.start_date)}
+ </P.SubTrigger>
+ <P.SubContent>{dateItems("start_date")}</P.SubContent>
+ </P.Sub>
+ <P.Item disabled={disabled} onClick={onSetParent}>
+ <ArrowUp className="h-3.5 w-3.5" />
+ {t(($) => $.actions.set_parent_issue)}
+ </P.Item>
+ {anyParent && (
+ <P.Item disabled={disabled} onClick={() => onUpdate({ parent_issue_id: null })}>
+ <Unlink className="h-3.5 w-3.5" />
+ {t(($) => $.actions.remove_parent_issue)}
+ </P.Item>
+ )}
+ {allChildren && (
+ <P.Sub>
+ <P.SubTrigger disabled={disabled}>
+ <Milestone className="h-3.5 w-3.5" />
+ {t(($) => $.batch.stage)}
+ </P.SubTrigger>
+ <P.SubContent>
+ <P.Item onClick={() => onUpdate({ stage: null })}>
+ {t(($) => $.stage.none)}
+ {issues.every((issue) => issue.stage == null) && <Check className="ml-auto size-3.5 text-muted-foreground" />}
+ </P.Item>
+ {stageOptions(sharedStage, maxStage).map((n) => (
+ <P.Item key={n} onClick={() => onUpdate({ stage: n })}>
+ {t(($) => $.stage.value, { n })}
+ {sharedStage === n && <Check className="ml-auto size-3.5 text-muted-foreground" />}
+ </P.Item>
+ ))}
+ </P.SubContent>
+ </P.Sub>
+ )}
+ {activeProperties.length > 0 && (
+ <P.Sub>
+ <P.SubTrigger disabled={disabled}>
+ <SlidersHorizontal className="h-3.5 w-3.5" />
+ {t(($) => $.batch.custom_properties)}
+ </P.SubTrigger>
+ <P.SubContent className="max-h-80 overflow-y-auto">
+ {activeProperties.map((property) => (
+ <PropertyEntry
+ key={property.id}
+ P={P}
+ issues={issues}
+ property={property}
+ onProperties={onProperties}
+ onEditor={onEditor}
+ />
+ ))}
+ </P.SubContent>
+ </P.Sub>
+ )}
+
+ <P.Separator />
+ <P.Item onClick={copyLinks}>
+ <Link2 className="h-3.5 w-3.5" />
+ {t(($) => $.batch.copy_links)}
+ </P.Item>
+ {onClearSelection && (
+ <P.Item onClick={onClearSelection}>
+ <X className="h-3.5 w-3.5" />
+ {tLayout(($) => $.collection.clear_selection)}
+ </P.Item>
+ )}
+ <P.Separator />
+ <P.Item
+ variant="destructive"
+ disabled={disabled || !canDelete}
+ title={!canDelete ? t(($) => $.batch.delete_restricted) : undefined}
+ onClick={onDelete}
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ {t(($) => $.batch.delete_count, { count })}
+ </P.Item>
+ </>
+ );
+}
+
+function StatusSub({
+ P,
+ projectId,
+ allowedStatuses,
+ common,
+ disabled,
+ onStatus,
+}: {
+ P: MenuPrimitives;
+ projectId: string | null;
+ allowedStatuses: ReadonlySet<string> | null;
+ common: CommonIssueFields;
+ disabled: boolean;
+ onStatus: (status: string) => void;
+}) {
+ const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const { options } = useIssueStatusOptions(wsId, projectId ?? undefined, common.status);
+ const statusOptions = allowedStatuses ? options.filter((o) => allowedStatuses.has(o.key)) : options;
+ return (
+ <P.Sub>
+ <P.SubTrigger disabled={disabled}>
+ {common.status ? (
+ <StatusIcon status={common.status} className="h-3.5 w-3.5" />
+ ) : (
+ <CircleDot className="h-3.5 w-3.5" />
+ )}
+ {t(($) => $.batch.status)}
+ </P.SubTrigger>
+ <P.SubContent>
+ {statusOptions.map((option) => (
+ <P.Item key={option.key} onClick={() => onStatus(option.key)}>
+ <StatusIcon
+ status={option.key}
+ category={option.category}
+ color={option.color}
+ icon={option.icon}
+ className="h-3.5 w-3.5"
+ />
+ {option.label}
+ {common.status === option.key && <Check className="ml-auto size-3.5 text-muted-foreground" />}
+ </P.Item>
+ ))}
+ </P.SubContent>
+ </P.Sub>
+ );
+}
+
+function ProjectSub({
+ P,
+ issues,
+ disabled,
+ onUpdate,
+}: {
+ P: MenuPrimitives;
+ issues: Issue[];
+ disabled: boolean;
+ onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
+}) {
+ const { t } = useT("issues");
+ const { t: tProjects } = useT("projects");
+ const wsId = useWorkspaceId();
+ const { data: projects = [] } = useQuery(projectListOptions(wsId));
+ const first = issues[0]?.project_id ?? null;
+ const current = issues.every((issue) => (issue.project_id ?? null) === first) ? first : undefined;
+ const live = projects.filter((project) => project.status !== "cancelled" || project.id === current);
+ return (
+ <P.Sub>
+ <P.SubTrigger disabled={disabled}>
+ <FolderKanban className="h-3.5 w-3.5" />
+ {t(($) => $.batch.project)}
+ </P.SubTrigger>
+ <P.SubContent className="max-h-80 overflow-y-auto">
+ <P.Item onClick={() => onUpdate({ project_id: null })}>
+ <FolderKanban className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="text-muted-foreground">{tProjects(($) => $.picker.no_project)}</span>
+ {current === null && <Check className="ml-auto size-3.5 text-muted-foreground" />}
+ </P.Item>
+ {live.map((project) => (
+ <P.Item key={project.id} onClick={() => onUpdate({ project_id: project.id })}>
+ <ProjectIcon project={project} size="sm" />
+ <span className="max-w-56 truncate">{project.title}</span>
+ {current === project.id && <Check className="ml-auto size-3.5 text-muted-foreground" />}
+ </P.Item>
+ ))}
+ </P.SubContent>
+ </P.Sub>
+ );
+}
+
+/**
+ * One custom property in the batch menu. Select and checkbox values are rows
+ * in a submenu; every other type opens the property's own editor.
+ */
+function PropertyEntry({
+ P,
+ issues,
+ property,
+ onProperties,
+ onEditor,
+}: {
+ P: MenuPrimitives;
+ issues: Issue[];
+ property: IssueProperty;
+ onProperties: (ops: BatchIssuePropertyOps) => void;
+ onEditor: (editor: BatchEditor) => void;
+}) {
+ const { t } = useT("issues");
+ const label = (
+ <>
+ <PropertyIcon property={property} className="size-3.5" />
+ <span className="max-w-48 truncate">{property.name}</span>
+ </>
+ );
+ // Clearing is its own action: a selection with differing values has no
+ // shared value for the editor to clear from.
+ const setCount = issues.filter((issue) => issue.properties?.[property.id] !== undefined).length;
+ const clearItem = setCount > 0 && (
+ <>
+ <P.Separator />
+ <P.Item onClick={() => onProperties({ unset: [property.id] })}>
+ <X className="h-3.5 w-3.5" />
+ {t(($) => $.batch.property_clear, { count: setCount })}
+ </P.Item>
+ </>
+ );
+ if (!INLINE_PROPERTY_TYPES.has(property.type)) {
+ const edit = () => onEditor({ kind: "property", property });
+ if (!clearItem) return <P.Item onClick={edit}>{label}</P.Item>;
+ return (
+ <P.Sub>
+ <P.SubTrigger>{label}</P.SubTrigger>
+ <P.SubContent className="min-w-48">
+ <P.Item onClick={edit}>{t(($) => $.batch.property_edit)}</P.Item>
+ {clearItem}
+ </P.SubContent>
+ </P.Sub>
+ );
+ }
+ const countOf = (value: IssuePropertyValue) =>
+ issues.filter((issue) => issue.properties?.[property.id] === value).length;
+ const set = (value: IssuePropertyValue) => onProperties({ set: { [property.id]: value } });
+ const valueRow = (key: string, value: IssuePropertyValue, content: React.ReactNode) => {
+ const n = countOf(value);
+ return (
+ <P.Item key={key} onClick={() => set(value)}>
+ {content}
+ {n > 0 && (
+ <span className="ml-auto pl-3 text-caption tabular-nums text-muted-foreground">
+ {n}/{issues.length}
+ </span>
+ )}
+ </P.Item>
+ );
+ };
+ return (
+ <P.Sub>
+ <P.SubTrigger>{label}</P.SubTrigger>
+ <P.SubContent className="max-h-80 min-w-48 overflow-y-auto">
+ {property.type === "select"
+ ? (property.config.options ?? []).map((option) =>
+ valueRow(
+ option.id,
+ option.id,
+ <>
+ <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: paletteColor(option.color) }} />
+ <span className="max-w-48 truncate">{option.name}</span>
+ </>,
+ ),
+ )
+ : [
+ valueRow("true", true, t(($) => $.pickers.custom_property.true_label)),
+ valueRow("false", false, t(($) => $.pickers.custom_property.false_label)),
+ ]}
+ {clearItem}
+ </P.SubContent>
+ </P.Sub>
+ );
+}
diff --git a/packages/views/issues/components/batch-result-toast.test.tsx b/packages/views/issues/components/batch-result-toast.test.tsx
new file mode 100644
index 0000000000..45f8d63fc7
--- /dev/null
+++ b/packages/views/issues/components/batch-result-toast.test.tsx
@@ -0,0 +1,116 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import type { ReactElement } from "react";
+import type { BatchUpdateIssuesResponse } from "@multica/core/types";
+import { BatchOpsUnsupportedError } from "@multica/core/api";
+import { renderWithI18n } from "../../test/i18n";
+import { useBatchResultToast, type BatchResultToastOptions } from "./batch-result-toast";
+
+const toast = vi.hoisted(() => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn(), dismiss: vi.fn() }));
+vi.mock("sonner", () => ({ toast }));
+
+type Reporter = ReturnType<typeof useBatchResultToast>;
+
+function withReporter(): Reporter {
+ let reporter: Reporter | undefined;
+ function Probe() {
+ reporter = useBatchResultToast();
+ return null;
+ }
+ renderWithI18n(<Probe />);
+ return reporter!;
+}
+
+function report(response: BatchUpdateIssuesResponse, count: number, options?: BatchResultToastOptions) {
+ return withReporter().report(response, count, options);
+}
+
+const updated = (id: string) => ({ issue_id: id, identifier: id.toUpperCase(), outcome: "updated" as const });
+const skipped = (id: string, code: string) => ({
+ issue_id: id,
+ identifier: id.toUpperCase(),
+ outcome: "skipped" as const,
+ code,
+ message: "server message",
+});
+
+beforeEach(() => {
+ toast.success.mockClear();
+ toast.warning.mockClear();
+ toast.error.mockClear();
+});
+
+describe("useBatchResultToast", () => {
+ it("reports success when every issue took the change", () => {
+ expect(report({ updated: 2, results: [updated("a"), updated("b")] }, 2)).toBe(true);
+ expect(toast.success).toHaveBeenCalledWith("Updated 2 issues");
+ expect(toast.warning).not.toHaveBeenCalled();
+ });
+
+ it("stays silent on success when asked to", () => {
+ expect(report({ updated: 1, results: [updated("a")] }, 1, { successMessage: null })).toBe(true);
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it("names each skipped issue with its reason and offers to select only those", () => {
+ const onSelectSkipped = vi.fn();
+ const applied = report(
+ {
+ updated: 1,
+ results: [updated("a"), skipped("b", "workflow_rejected"), skipped("c", "something_new")],
+ },
+ 3,
+ { onSelectSkipped },
+ );
+
+ expect(applied).toBe(false);
+ expect(toast.success).not.toHaveBeenCalled();
+ const [title, options] = toast.warning.mock.calls[0]! as [string, { id: string; description: ReactElement }];
+ expect(title).toBe("Updated 1, skipped 2 issues");
+ // Toast content renders outside the app's providers.
+ render(options.description);
+ expect(screen.getByText("B")).toBeInTheDocument();
+ expect(screen.getByText("Its project's workflow doesn't allow this change")).toBeInTheDocument();
+ // An unknown code falls back to the server's message.
+ expect(screen.getByText("server message")).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Select only these 2" }));
+ expect(onSelectSkipped).toHaveBeenCalledWith(["b", "c"]);
+ expect(toast.dismiss).toHaveBeenCalledWith(options.id);
+ });
+
+ it("names the single skipped issue in the select action", () => {
+ report({ updated: 1, results: [updated("a"), skipped("b", "not_found")] }, 2, { onSelectSkipped: vi.fn() });
+ render((toast.warning.mock.calls[0]![1] as { description: ReactElement }).description);
+ expect(screen.getByRole("button", { name: "Select only this issue" })).toBeInTheDocument();
+ });
+
+ it("summarises skips beyond the first three", () => {
+ report(
+ { updated: 0, results: ["a", "b", "c", "d", "e"].map((id) => skipped(id, "not_found")) },
+ 5,
+ );
+ const options = toast.warning.mock.calls[0]![1] as { description: ReactElement };
+ render(options.description);
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+ expect(screen.queryByText("D")).not.toBeInTheDocument();
+ expect(screen.getByText("and 2 more")).toBeInTheDocument();
+ });
+
+ it("falls back to the count when the server sends no per-issue results", () => {
+ expect(report({ updated: 2 }, 2)).toBe(true);
+ expect(report({ updated: 1 }, 2)).toBe(false);
+ expect(toast.warning).toHaveBeenCalledTimes(1);
+ });
+
+ it("warns that the result is unknown when the response could not be read", () => {
+ expect(report({ updated: 0, unconfirmed: true }, 2)).toBe(false);
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(toast.warning).toHaveBeenCalledWith(expect.stringMatching(/Couldn't confirm/));
+ });
+
+ it("explains an outdated server instead of showing a generic failure", () => {
+ withReporter().reportError(new BatchOpsUnsupportedError());
+ expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/server/i));
+ });
+});
diff --git a/packages/views/issues/components/batch-result-toast.tsx b/packages/views/issues/components/batch-result-toast.tsx
new file mode 100644
index 0000000000..e8580f034d
--- /dev/null
+++ b/packages/views/issues/components/batch-result-toast.tsx
@@ -0,0 +1,150 @@
+"use client";
+
+import { useCallback } from "react";
+import { toast } from "sonner";
+import type { BatchUpdateIssuesResponse } from "@multica/core/types";
+import { BatchOpsUnsupportedError } from "@multica/core/api";
+import { useT } from "../../i18n";
+
+const SKIP_REASONS = [
+ "invalid_id",
+ "not_found",
+ "invalid_value",
+ "parent_self",
+ "parent_not_found",
+ "parent_cycle",
+ "workflow_rejected",
+ "assignee_not_allowed",
+ "properties_too_large",
+ "write_failed",
+] as const;
+type SkipReason = (typeof SKIP_REASONS)[number];
+
+const isSkipReason = (code: string | undefined): code is SkipReason =>
+ SKIP_REASONS.includes(code as SkipReason);
+
+/** How many skipped issues the toast names before summarising the rest. */
+const LISTED_SKIPS = 3;
+
+let skippedToastSeq = 0;
+
+// Rendered under <Toaster />, outside the app's providers: no hooks here, every
+// string arrives translated.
+function SkippedList({
+ rows,
+ more,
+ action,
+}: {
+ rows: { id: string; identifier: string; reason: string }[];
+ more: string | null;
+ action: { label: string; onClick: () => void } | null;
+}) {
+ return (
+ <div className="mt-1 flex flex-col gap-1">
+ {rows.map((row) => (
+ <div key={row.id} className="flex min-w-0 gap-2 text-caption">
+ <span className="shrink-0 font-mono text-muted-foreground">{row.identifier}</span>
+ <span className="min-w-0 break-words">{row.reason}</span>
+ </div>
+ ))}
+ {more && <div className="text-caption text-muted-foreground">{more}</div>}
+ {action && (
+ <button
+ type="button"
+ className="mt-1 self-start text-caption font-medium text-primary hover:underline cursor-pointer"
+ onClick={action.onClick}
+ >
+ {action.label}
+ </button>
+ )}
+ </div>
+ );
+}
+
+export interface BatchResultToastOptions {
+ /** Offer "Select only these" so the skipped issues can be fixed and retried. */
+ onSelectSkipped?: (issueIds: string[]) => void;
+ /** Override the success toast; `null` stays silent on full success. */
+ successMessage?: string | null;
+}
+
+/**
+ * Reports a batch write: a success toast when every issue took the change,
+ * otherwise a warning naming the skipped issues and why. Returns whether the
+ * whole selection applied, so callers keep the selection for a retry when not.
+ */
+export function useBatchResultToast() {
+ const { t } = useT("issues");
+
+ const report = useCallback(
+ (response: BatchUpdateIssuesResponse, count: number, options: BatchResultToastOptions = {}): boolean => {
+ if (response.unconfirmed) {
+ toast.warning(t(($) => $.batch.result_unknown));
+ return false;
+ }
+ const results = response.results;
+ if (!results) {
+ // Older servers report only a count.
+ if (response.updated >= count) {
+ if (options.successMessage !== null) {
+ toast.success(options.successMessage ?? t(($) => $.batch.update_success, { count }));
+ }
+ return true;
+ }
+ toast.warning(t(($) => $.batch.update_partial, { updated: response.updated, count }));
+ return false;
+ }
+ const skipped = results.filter((result) => result.outcome === "skipped");
+ if (skipped.length === 0) {
+ if (options.successMessage !== null) {
+ toast.success(options.successMessage ?? t(($) => $.batch.update_success, { count }));
+ }
+ return true;
+ }
+ const { onSelectSkipped } = options;
+ const toastId = `batch-skipped-${++skippedToastSeq}`;
+ const rows = skipped.slice(0, LISTED_SKIPS).map((result) => ({
+ id: result.issue_id,
+ identifier: result.identifier ?? result.issue_id.slice(0, 8),
+ reason: isSkipReason(result.code)
+ ? t(($) => $.batch.skip_reason[result.code as SkipReason])
+ : result.message || t(($) => $.batch.skip_reason.write_failed),
+ }));
+ const more =
+ skipped.length > LISTED_SKIPS
+ ? t(($) => $.batch.skipped_more, { count: skipped.length - LISTED_SKIPS })
+ : null;
+ const action = onSelectSkipped
+ ? {
+ label: t(($) => $.batch.select_skipped, { count: skipped.length }),
+ onClick: () => {
+ onSelectSkipped(skipped.map((result) => result.issue_id));
+ toast.dismiss(toastId);
+ },
+ }
+ : null;
+ toast.warning(t(($) => $.batch.skipped_title, { updated: response.updated, count: skipped.length }), {
+ id: toastId,
+ description: <SkippedList rows={rows} more={more} action={action} />,
+ duration: 10_000,
+ });
+ return false;
+ },
+ [t],
+ );
+
+ const reportError = useCallback(
+ (err: unknown) => {
+ toast.error(
+ err instanceof BatchOpsUnsupportedError
+ ? t(($) => $.batch.server_outdated)
+ : err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.batch.update_failed),
+ );
+ },
+ [t],
+ );
+
+ return { report, reportError };
+}
diff --git a/packages/views/issues/components/pickers/batch-label-picker.test.tsx b/packages/views/issues/components/pickers/batch-label-picker.test.tsx
new file mode 100644
index 0000000000..e39aaeb423
--- /dev/null
+++ b/packages/views/issues/components/pickers/batch-label-picker.test.tsx
@@ -0,0 +1,93 @@
+import { describe, expect, it, vi } from "vitest";
+import { act, fireEvent, screen, waitFor } from "@testing-library/react";
+import type { Issue, Label } from "@multica/core/types";
+import { renderWithI18n } from "../../../test/i18n";
+import { BatchLabelPicker } from "./batch-label-picker";
+
+const LABELS = vi.hoisted(() =>
+ ["bug", "frontend", "docs"].map((name) => ({ id: `l-${name}`, name, color: "blue" })),
+);
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@tanstack/react-query", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),
+ useQuery: () => ({ data: LABELS }),
+}));
+
+function issue(id: string, labelNames: string[]): Issue {
+ return { id, labels: LABELS.filter((label) => labelNames.includes(label.name)) as Label[] } as Issue;
+}
+
+function renderPicker(issues: Issue[], onApply = vi.fn().mockResolvedValue(true)) {
+ const onOpenChange = vi.fn();
+ const picker = () => (
+ <BatchLabelPicker issues={issues} onApply={onApply} open onOpenChange={onOpenChange} trigger="Labels" />
+ );
+ const view = renderWithI18n(picker());
+ const row = (name: string) => screen.getByText(name).closest("button")!;
+ const box = (name: string) => row(name).querySelector("[data-state]")!;
+ return { onApply, onOpenChange, row, box, rerender: () => view.rerender(picker()), unmount: view.unmount };
+}
+
+describe("BatchLabelPicker", () => {
+ const issues = [issue("a", ["bug", "frontend"]), issue("b", ["bug"]), issue("c", [])];
+
+ it("shows whether all, some or none of the selection has each label", () => {
+ const { row, box } = renderPicker(issues);
+ expect(box("bug")).toHaveAttribute("data-state", "some");
+ expect(row("bug")).toHaveTextContent("2/3");
+ expect(box("frontend")).toHaveAttribute("data-state", "some");
+ expect(box("docs")).toHaveAttribute("data-state", "none");
+ expect(row("docs")).not.toHaveTextContent("/3");
+ });
+
+ it("adds a partial label to every issue, and removes one every issue has", async () => {
+ const { onApply, row, box } = renderPicker(issues);
+ fireEvent.click(row("bug"));
+ expect(onApply).toHaveBeenLastCalledWith({ add: ["l-bug"] });
+ // Held as applied until realtime brings the updated issues.
+ expect(box("bug")).toHaveAttribute("data-state", "all");
+ // Confirmed: the next click on the now-complete label removes it.
+ await act(async () => {});
+
+ fireEvent.click(row("bug"));
+ expect(onApply).toHaveBeenLastCalledWith({ remove: ["l-bug"] });
+ expect(box("bug")).toHaveAttribute("data-state", "none");
+ });
+
+ it("restores the real counts when a write does not fully apply, so a retry adds again", async () => {
+ for (const outcome of [() => Promise.resolve(false), () => Promise.reject(new Error("network"))]) {
+ const onApply = vi.fn(outcome);
+ const { row, box, rerender, unmount } = renderPicker(issues, onApply);
+ fireEvent.click(row("bug"));
+ await waitFor(() => expect(box("bug")).toHaveAttribute("data-state", "some"));
+ // An unchanged refetch keeps the same issues reference.
+ rerender();
+ expect(row("bug")).toHaveTextContent("2/3");
+ fireEvent.click(row("bug"));
+ expect(onApply).toHaveBeenLastCalledWith({ add: ["l-bug"] });
+ unmount();
+ }
+ });
+
+ it("ignores another click on a label while its write is in flight", () => {
+ const onApply = vi.fn(() => new Promise<boolean>(() => {}));
+ const { row } = renderPicker(issues, onApply);
+ fireEvent.click(row("bug"));
+ fireEvent.click(row("bug"));
+ expect(onApply).toHaveBeenCalledTimes(1);
+ expect(onApply).toHaveBeenCalledWith({ add: ["l-bug"] });
+ });
+
+ it("clears every label from the selection from the footer", () => {
+ const { onApply, onOpenChange } = renderPicker(issues);
+ fireEvent.click(screen.getByRole("button", { name: /Remove all labels/ }));
+ expect(onApply).toHaveBeenCalledWith({ clear: true });
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it("offers no clear action when no selected issue has a label", () => {
+ renderPicker([issue("a", []), issue("b", [])]);
+ expect(screen.queryByRole("button", { name: /Remove all labels/ })).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/issues/components/pickers/batch-label-picker.tsx b/packages/views/issues/components/pickers/batch-label-picker.tsx
new file mode 100644
index 0000000000..cf2fa3aa93
--- /dev/null
+++ b/packages/views/issues/components/pickers/batch-label-picker.tsx
@@ -0,0 +1,222 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Check, Minus, X } from "@multica/ui/icons";
+import { cn } from "@multica/ui/lib/utils";
+import type { BatchIssueLabelOps, Issue, Label } from "@multica/core/types";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { labelListOptions } from "@multica/core/labels";
+import { paletteColor } from "@multica/core/appearance";
+import { matchesPinyin } from "../../../editor/extensions/pinyin-match";
+import { PickerEmpty, PickerItem, PickerPanel, PropertyPicker } from "./property-picker";
+import { useT } from "../../../i18n";
+
+type LabelState = "all" | "some" | "none";
+type Pick = { state: "all" | "none"; pending: boolean };
+
+/** Resolves true only when the write applied to every selected issue. */
+export type BatchLabelApply = (ops: BatchIssueLabelOps) => Promise<boolean>;
+
+const EMPTY_LABELS: Label[] = [];
+const NO_PICKS: ReadonlyMap<string, Pick> = new Map();
+
+/**
+ * Label rows for a selection, each with a tri-state box: checked when every
+ * issue has the label, a dash when only some do. Picking a row adds the label
+ * to every issue, or removes it from all when every issue already has it.
+ */
+function useBatchLabelRows(issues: readonly Issue[], query: string, onApply: BatchLabelApply) {
+ const wsId = useWorkspaceId();
+ const { data: labels = EMPTY_LABELS } = useQuery(labelListOptions(wsId, "issue"));
+ const counts = useMemo(() => {
+ const map = new Map<string, number>();
+ for (const issue of issues) {
+ for (const label of issue.labels ?? []) map.set(label.id, (map.get(label.id) ?? 0) + 1);
+ }
+ return map;
+ }, [issues]);
+ // The write lands through realtime a moment later; hold the picked state
+ // until the issues themselves change so the box does not flicker back. A
+ // write that did not fully apply drops its hold, so the real counts show and
+ // a retry repeats the same operation instead of inverting it.
+ const [held, setHeld] = useState<{ issues: readonly Issue[]; picks: ReadonlyMap<string, Pick> }>({
+ issues,
+ picks: new Map(),
+ });
+ const picks = held.issues === issues ? held.picks : NO_PICKS;
+
+ const total = issues.length;
+ const stateOf = (labelId: string): LabelState => {
+ const pick = picks.get(labelId);
+ if (pick) return pick.state;
+ const n = counts.get(labelId) ?? 0;
+ return n === 0 ? "none" : n === total ? "all" : "some";
+ };
+ const countOf = (labelId: string) => {
+ const pick = picks.get(labelId);
+ if (pick) return pick.state === "all" ? total : 0;
+ return counts.get(labelId) ?? 0;
+ };
+ const toggle = (labelId: string) => {
+ if (picks.get(labelId)?.pending) return;
+ const removing = stateOf(labelId) === "all";
+ const pick: Pick = { state: removing ? "none" : "all", pending: true };
+ setHeld({ issues, picks: new Map(picks).set(labelId, pick) });
+ const settle = (applied: boolean) =>
+ setHeld((prev) => {
+ if (prev.picks.get(labelId) !== pick) return prev;
+ const next = new Map(prev.picks);
+ if (applied) next.set(labelId, { ...pick, pending: false });
+ else next.delete(labelId);
+ return { issues: prev.issues, picks: next };
+ });
+ onApply(removing ? { remove: [labelId] } : { add: [labelId] }).then(
+ (applied) => settle(applied === true),
+ () => settle(false),
+ );
+ };
+
+ const q = query.trim().toLowerCase();
+ const visible = q
+ ? labels.filter((label) => label.name.toLowerCase().includes(q) || matchesPinyin(label.name, q))
+ : labels;
+ const anyLabeled = issues.some((issue) => (issue.labels?.length ?? 0) > 0);
+ return { visible, stateOf, countOf, toggle, total, anyLabeled };
+}
+
+function LabelRows({ rows }: { rows: ReturnType<typeof useBatchLabelRows> }) {
+ if (rows.visible.length === 0) return <PickerEmpty />;
+ return (
+ <>
+ {rows.visible.map((label) => {
+ const state = rows.stateOf(label.id);
+ const count = rows.countOf(label.id);
+ return (
+ <PickerItem key={label.id} selected={false} onClick={() => rows.toggle(label.id)}>
+ <span
+ role="presentation"
+ data-state={state}
+ className={cn(
+ "flex size-3.5 shrink-0 items-center justify-center rounded-xs border",
+ state === "none" ? "border-input" : "border-primary bg-primary text-primary-foreground",
+ )}
+ >
+ {state === "all" ? <Check className="size-3" /> : state === "some" ? <Minus className="size-3" /> : null}
+ </span>
+ <span
+ className="inline-block size-2.5 shrink-0 rounded-full"
+ style={{ backgroundColor: paletteColor(label.color) }}
+ aria-hidden
+ />
+ <span className="min-w-0 flex-1 truncate">{label.name}</span>
+ {count > 0 && (
+ <span className="shrink-0 text-caption tabular-nums text-muted-foreground">
+ {count}/{rows.total}
+ </span>
+ )}
+ </PickerItem>
+ );
+ })}
+ </>
+ );
+}
+
+function ClearLabelsButton({ count, onClick }: { count: number; onClick: () => void }) {
+ const { t } = useT("issues");
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-body text-muted-foreground transition-colors hover:bg-accent"
+ >
+ <X className="h-3.5 w-3.5" />
+ <span>{t(($) => $.batch.clear_labels, { count })}</span>
+ </button>
+ );
+}
+
+export function BatchLabelPicker({
+ issues,
+ onApply,
+ open,
+ onOpenChange,
+ trigger,
+ triggerRender,
+ align = "center",
+}: {
+ issues: readonly Issue[];
+ onApply: BatchLabelApply;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ trigger: React.ReactNode;
+ triggerRender?: React.ReactElement;
+ align?: "start" | "center" | "end";
+}) {
+ const { t } = useT("issues");
+ const [query, setQuery] = useState("");
+ const rows = useBatchLabelRows(issues, query, onApply);
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={onOpenChange}
+ width="w-72"
+ align={align}
+ side="top"
+ searchable
+ searchPlaceholder={t(($) => $.batch.labels_search)}
+ onSearchChange={setQuery}
+ trigger={trigger}
+ triggerRender={triggerRender}
+ footer={
+ rows.anyLabeled ? (
+ <ClearLabelsButton
+ count={rows.total}
+ onClick={() => {
+ void onApply({ clear: true });
+ onOpenChange(false);
+ }}
+ />
+ ) : undefined
+ }
+ >
+ <LabelRows rows={rows} />
+ </PropertyPicker>
+ );
+}
+
+/** The same rows inside a menu's submenu. */
+export function BatchLabelPanel({
+ issues,
+ onApply,
+ onClose,
+}: {
+ issues: readonly Issue[];
+ onApply: BatchLabelApply;
+ onClose: () => void;
+}) {
+ const { t } = useT("issues");
+ const [query, setQuery] = useState("");
+ const rows = useBatchLabelRows(issues, query, onApply);
+ return (
+ <PickerPanel
+ searchable
+ autoFocusSearch
+ searchPlaceholder={t(($) => $.batch.labels_search)}
+ onSearchChange={setQuery}
+ footer={
+ rows.anyLabeled ? (
+ <ClearLabelsButton
+ count={rows.total}
+ onClick={() => {
+ void onApply({ clear: true });
+ onClose();
+ }}
+ />
+ ) : undefined
+ }
+ >
+ <LabelRows rows={rows} />
+ </PickerPanel>
+ );
+}
diff --git a/packages/views/issues/surface/actions-context.tsx b/packages/views/issues/surface/actions-context.tsx
index 0458c96aa8..616cb99373 100644
--- a/packages/views/issues/surface/actions-context.tsx
+++ b/packages/views/issues/surface/actions-context.tsx
@@ -1,7 +1,13 @@
"use client";
import { createContext, useContext, type ReactNode } from "react";
-import type { Issue, UpdateIssueRequest } from "@multica/core/types";
+import type {
+ BatchIssueLabelOps,
+ BatchIssuePropertyOps,
+ BatchUpdateIssuesResponse,
+ Issue,
+ UpdateIssueRequest,
+} from "@multica/core/types";
import type { IssueCreateDefaults } from "./types";
export type IssueSurfaceMutationOptions = {
@@ -24,11 +30,12 @@ export interface IssueSurfaceActions {
updates: Partial<UpdateIssueRequest>,
options?: IssueSurfaceMutationOptions,
) => void;
- /** Resolves with how many issues the server wrote; it skips the ones its per-issue guards refuse. */
+ /** Resolves with the server's per-issue results; it skips the ones its per-issue guards refuse. */
batchUpdate: (
issueIds: string[],
updates: Partial<UpdateIssueRequest>,
- ) => Promise<{ updated: number }>;
+ ops?: { labels?: BatchIssueLabelOps; properties?: BatchIssuePropertyOps },
+ ) => Promise<BatchUpdateIssuesResponse>;
batchDelete: (issueIds: string[]) => Promise<void>;
}
diff --git a/packages/views/issues/surface/use-issue-surface-actions.ts b/packages/views/issues/surface/use-issue-surface-actions.ts
index ee69539856..399b98716b 100644
--- a/packages/views/issues/surface/use-issue-surface-actions.ts
+++ b/packages/views/issues/surface/use-issue-surface-actions.ts
@@ -132,7 +132,8 @@ export function useIssueSurfaceActions({
errorMessage: t(($) => $.detail.toast_move_issue_failed),
...options,
}),
- batchUpdate: (issueIds, updates) => batchUpdateMutation.mutateAsync({ ids: issueIds, updates }),
+ batchUpdate: (issueIds, updates, ops) =>
+ batchUpdateMutation.mutateAsync({ ids: issueIds, updates, ...ops }),
batchDelete: async (issueIds) => {
await batchDeleteMutation.mutateAsync(issueIds);
},
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 042233ea52..f07944bff8 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -1009,7 +1009,42 @@
"links_copied_one": "Copied {{count}} link",
"links_copied_other": "Copied {{count}} links",
"delete_count_one": "Delete {{count}} issue",
- "delete_count_other": "Delete {{count}} issues"
+ "delete_count_other": "Delete {{count}} issues",
+ "labels": "Labels",
+ "project": "Project",
+ "due_date": "Due date",
+ "more": "More actions",
+ "stage": "Stage",
+ "custom_properties": "Custom properties",
+ "pick_date": "Pick a date…",
+ "property_edit": "Set value…",
+ "result_unknown": "Couldn't confirm which issues changed. Check the list before retrying.",
+ "property_clear": "Clear ({{count}} set)",
+ "labels_search": "Add or remove labels…",
+ "clear_labels_one": "Remove all labels from {{count}} issue",
+ "clear_labels_other": "Remove all labels from {{count}} issues",
+ "set_parent_title_one": "Set parent for {{count}} issue",
+ "set_parent_title_other": "Set parent for {{count}} issues",
+ "set_parent_description_one": "Search for an issue to make it the parent of the selected issue.",
+ "set_parent_description_other": "Search for an issue to make it the parent of the {{count}} selected issues.",
+ "skipped_title_one": "Updated {{updated}}, skipped {{count}} issue",
+ "skipped_title_other": "Updated {{updated}}, skipped {{count}} issues",
+ "skipped_more": "and {{count}} more",
+ "select_skipped_one": "Select only this issue",
+ "select_skipped_other": "Select only these {{count}}",
+ "server_outdated": "This server can't change labels or custom properties in bulk yet. Update the server and try again.",
+ "skip_reason": {
+ "invalid_id": "Not a valid issue",
+ "not_found": "Not found, or you can't see it",
+ "invalid_value": "The value isn't valid for this issue",
+ "parent_self": "An issue can't be its own parent",
+ "parent_not_found": "Parent issue not found",
+ "parent_cycle": "The parent is one of its sub-issues",
+ "workflow_rejected": "Its project's workflow doesn't allow this change",
+ "assignee_not_allowed": "Can't be assigned to this assignee",
+ "properties_too_large": "Its custom properties would exceed the size limit",
+ "write_failed": "Couldn't save this issue"
+ }
},
"card": {
"update_failed": "Failed to update issue",
diff --git a/packages/views/locales/en/search.json b/packages/views/locales/en/search.json
index 7f37331a67..fda9ebe553 100644
--- a/packages/views/locales/en/search.json
+++ b/packages/views/locales/en/search.json
@@ -125,7 +125,6 @@
"unsubscribed": "Unsubscribed",
"label_added": "Added label {{name}}",
"label_removed": "Removed label {{name}}",
- "label_failed": "Couldn't add label {{name}} to every issue",
"update_failed": "Update failed",
"assigned": "Assigned {{identifier}} to {{name}}"
},
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index d841dcc1c1..2c18019b9d 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -923,7 +923,42 @@
"links_copied_one": "{{count}} enlace copiado",
"links_copied_other": "{{count}} enlaces copiados",
"delete_count_one": "Eliminar {{count}} tarea",
- "delete_count_other": "Eliminar {{count}} tareas"
+ "delete_count_other": "Eliminar {{count}} tareas",
+ "labels": "Etiquetas",
+ "project": "Proyecto",
+ "due_date": "Fecha de entrega",
+ "more": "Más acciones",
+ "stage": "Etapa",
+ "custom_properties": "Propiedades personalizadas",
+ "pick_date": "Elegir fecha…",
+ "property_edit": "Establecer valor…",
+ "result_unknown": "No se pudo confirmar qué tareas cambiaron. Revisa la lista antes de reintentar.",
+ "property_clear": "Borrar ({{count}} con valor)",
+ "labels_search": "Añadir o quitar etiquetas…",
+ "clear_labels_one": "Quitar todas las etiquetas de {{count}} tarea",
+ "clear_labels_other": "Quitar todas las etiquetas de {{count}} tareas",
+ "set_parent_title_one": "Establecer tarea principal para {{count}} tarea",
+ "set_parent_title_other": "Establecer tarea principal para {{count}} tareas",
+ "set_parent_description_one": "Busca una tarea para hacerla principal de la tarea seleccionada.",
+ "set_parent_description_other": "Busca una tarea para hacerla principal de las {{count}} tareas seleccionadas.",
+ "skipped_title_one": "Actualizadas {{updated}}, {{count}} tarea sin actualizar",
+ "skipped_title_other": "Actualizadas {{updated}}, {{count}} tareas sin actualizar",
+ "skipped_more": "y {{count}} más",
+ "select_skipped_one": "Seleccionar solo esta tarea",
+ "select_skipped_other": "Seleccionar solo estas {{count}}",
+ "server_outdated": "Este servidor aún no permite cambiar etiquetas ni propiedades personalizadas en bloque. Actualiza el servidor e inténtalo de nuevo.",
+ "skip_reason": {
+ "invalid_id": "No es una tarea válida",
+ "not_found": "No existe o no tienes acceso",
+ "invalid_value": "El valor no es válido para esta tarea",
+ "parent_self": "Una tarea no puede ser su propia tarea principal",
+ "parent_not_found": "No se encontró la tarea principal",
+ "parent_cycle": "La tarea principal es una de sus subtareas",
+ "workflow_rejected": "El flujo de trabajo de su proyecto no permite este cambio",
+ "assignee_not_allowed": "No se puede asignar a este responsable",
+ "properties_too_large": "Sus propiedades personalizadas superarían el límite de tamaño",
+ "write_failed": "No se pudo guardar esta tarea"
+ }
},
"card": {
"update_failed": "No se ha podido actualizar la tarea",
diff --git a/packages/views/locales/es/search.json b/packages/views/locales/es/search.json
index 99245ccc20..21a31369f2 100644
--- a/packages/views/locales/es/search.json
+++ b/packages/views/locales/es/search.json
@@ -43,7 +43,6 @@
"unsubscribed": "Suscripción cancelada",
"label_added": "Etiqueta {{name}} añadida",
"label_removed": "Etiqueta {{name}} quitada",
- "label_failed": "No se ha podido añadir la etiqueta {{name}} a todas las tareas",
"update_failed": "La actualización falló",
"assigned": "{{identifier}} asignada a {{name}}"
},
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 687838998f..279e482d79 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -1009,7 +1009,42 @@
"links_copied_one": "{{count}} lien copié",
"links_copied_other": "{{count}} liens copiés",
"delete_count_one": "Supprimer {{count}} tâche",
- "delete_count_other": "Supprimer {{count}} tâches"
+ "delete_count_other": "Supprimer {{count}} tâches",
+ "labels": "Étiquettes",
+ "project": "Projet",
+ "due_date": "Date d'échéance",
+ "more": "Plus d'actions",
+ "stage": "Étape",
+ "custom_properties": "Propriétés personnalisées",
+ "pick_date": "Choisir une date…",
+ "property_edit": "Définir la valeur…",
+ "result_unknown": "Impossible de confirmer les tâches modifiées. Vérifiez la liste avant de réessayer.",
+ "property_clear": "Effacer ({{count}} renseignées)",
+ "labels_search": "Ajouter ou retirer des étiquettes…",
+ "clear_labels_one": "Retirer toutes les étiquettes de {{count}} tâche",
+ "clear_labels_other": "Retirer toutes les étiquettes de {{count}} tâches",
+ "set_parent_title_one": "Définir la tâche parente de {{count}} tâche",
+ "set_parent_title_other": "Définir la tâche parente de {{count}} tâches",
+ "set_parent_description_one": "Recherchez une tâche à définir comme parente de la tâche sélectionnée.",
+ "set_parent_description_other": "Recherchez une tâche à définir comme parente des {{count}} tâches sélectionnées.",
+ "skipped_title_one": "{{updated}} mises à jour, {{count}} tâche ignorée",
+ "skipped_title_other": "{{updated}} mises à jour, {{count}} tâches ignorées",
+ "skipped_more": "et {{count}} de plus",
+ "select_skipped_one": "Sélectionner seulement cette tâche",
+ "select_skipped_other": "Sélectionner seulement ces {{count}}",
+ "server_outdated": "Ce serveur ne permet pas encore de modifier les étiquettes ou les propriétés personnalisées en masse. Mettez le serveur à jour, puis réessayez.",
+ "skip_reason": {
+ "invalid_id": "Tâche non valide",
+ "not_found": "Introuvable, ou vous n'y avez pas accès",
+ "invalid_value": "La valeur n'est pas valide pour cette tâche",
+ "parent_self": "Une tâche ne peut pas être sa propre parente",
+ "parent_not_found": "Tâche parente introuvable",
+ "parent_cycle": "La tâche parente est l'une de ses sous-tâches",
+ "workflow_rejected": "Le workflow de son projet n'autorise pas cette modification",
+ "assignee_not_allowed": "Impossible de l'attribuer à ce responsable",
+ "properties_too_large": "Ses propriétés personnalisées dépasseraient la taille maximale",
+ "write_failed": "Impossible d'enregistrer cette tâche"
+ }
},
"card": {
"update_failed": "Échec de la mise à jour de la tâche",
diff --git a/packages/views/locales/fr/search.json b/packages/views/locales/fr/search.json
index 43cd5ce54b..3e045fcb2e 100644
--- a/packages/views/locales/fr/search.json
+++ b/packages/views/locales/fr/search.json
@@ -125,7 +125,6 @@
"unsubscribed": "Désabonné",
"label_added": "Libellé {{name}} ajouté",
"label_removed": "Libellé {{name}} retiré",
- "label_failed": "Impossible d'ajouter le libellé {{name}} à toutes les tâches",
"update_failed": "Échec de la mise à jour",
"assigned": "{{identifier}} assignée à {{name}}"
},
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 7efe436ee7..f526dd72f1 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -960,7 +960,37 @@
"cancel": "キャンセル",
"copy_links": "リンクをコピー",
"links_copied_other": "{{count}} 件のリンクをコピーしました",
- "delete_count_other": "タスク {{count}} 件を削除"
+ "delete_count_other": "タスク {{count}} 件を削除",
+ "labels": "ラベル",
+ "project": "プロジェクト",
+ "due_date": "期限",
+ "more": "その他の操作",
+ "stage": "ステージ",
+ "custom_properties": "カスタムプロパティ",
+ "pick_date": "日付を選択…",
+ "property_edit": "値を設定…",
+ "result_unknown": "どの課題が変更されたか確認できませんでした。再試行する前に一覧を確認してください。",
+ "property_clear": "クリア({{count}} 件設定済み)",
+ "labels_search": "ラベルを追加または削除…",
+ "clear_labels_other": "タスク {{count}} 件のラベルをすべて削除",
+ "set_parent_title_other": "タスク {{count}} 件の親タスクを設定",
+ "set_parent_description_other": "選択したタスク {{count}} 件の親にするタスクを検索します。",
+ "skipped_title_other": "{{updated}} 件を更新、{{count}} 件は更新されませんでした",
+ "skipped_more": "ほか {{count}} 件",
+ "select_skipped_other": "この {{count}} 件だけを選択",
+ "server_outdated": "このサーバーはラベルやカスタムプロパティの一括変更にまだ対応していません。サーバーを更新してから再試行してください。",
+ "skip_reason": {
+ "invalid_id": "有効なタスクではありません",
+ "not_found": "見つからないか、閲覧権限がありません",
+ "invalid_value": "この値はこのタスクに使えません",
+ "parent_self": "タスクを自分自身の親にはできません",
+ "parent_not_found": "親タスクが見つかりません",
+ "parent_cycle": "親タスクがこのタスクのサブタスクです",
+ "workflow_rejected": "プロジェクトのワークフローがこの変更を許可していません",
+ "assignee_not_allowed": "この担当者には割り当てられません",
+ "properties_too_large": "カスタムプロパティがサイズ上限を超えます",
+ "write_failed": "保存できませんでした"
+ }
},
"card": {
"update_failed": "タスクを更新できませんでした",
diff --git a/packages/views/locales/ja/search.json b/packages/views/locales/ja/search.json
index 7ceb3b3490..722dcd0fa2 100644
--- a/packages/views/locales/ja/search.json
+++ b/packages/views/locales/ja/search.json
@@ -122,7 +122,6 @@
"unsubscribed": "購読を解除しました",
"label_added": "ラベル {{name}} を追加しました",
"label_removed": "ラベル {{name}} を削除しました",
- "label_failed": "一部のタスクにラベル {{name}} を追加できませんでした",
"update_failed": "更新に失敗しました",
"assigned": "{{identifier}} を {{name}} に割り当てました"
},
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index d0cc615014..403bb692c0 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -960,7 +960,37 @@
"cancel": "취소",
"copy_links": "링크 복사",
"links_copied_other": "링크 {{count}}개를 복사했습니다",
- "delete_count_other": "태스크 {{count}}개 삭제"
+ "delete_count_other": "태스크 {{count}}개 삭제",
+ "labels": "라벨",
+ "project": "프로젝트",
+ "due_date": "마감일",
+ "more": "더 보기",
+ "stage": "단계",
+ "custom_properties": "사용자 지정 속성",
+ "pick_date": "날짜 선택…",
+ "property_edit": "값 설정…",
+ "result_unknown": "어떤 이슈가 변경되었는지 확인할 수 없습니다. 다시 시도하기 전에 목록을 확인하세요.",
+ "property_clear": "지우기 ({{count}}개 설정됨)",
+ "labels_search": "라벨 추가 또는 제거…",
+ "clear_labels_other": "태스크 {{count}}개의 라벨 모두 제거",
+ "set_parent_title_other": "태스크 {{count}}개의 상위 태스크 설정",
+ "set_parent_description_other": "선택한 태스크 {{count}}개의 상위로 지정할 태스크를 검색하세요.",
+ "skipped_title_other": "{{updated}}개 업데이트, {{count}}개는 업데이트되지 않음",
+ "skipped_more": "외 {{count}}개",
+ "select_skipped_other": "이 {{count}}개만 선택",
+ "server_outdated": "이 서버는 아직 라벨과 사용자 지정 속성의 일괄 변경을 지원하지 않습니다. 서버를 업데이트한 후 다시 시도하세요.",
+ "skip_reason": {
+ "invalid_id": "유효한 태스크가 아닙니다",
+ "not_found": "찾을 수 없거나 볼 권한이 없습니다",
+ "invalid_value": "이 태스크에 사용할 수 없는 값입니다",
+ "parent_self": "태스크를 자기 자신의 상위로 지정할 수 없습니다",
+ "parent_not_found": "상위 태스크를 찾을 수 없습니다",
+ "parent_cycle": "상위 태스크가 이 태스크의 하위 태스크입니다",
+ "workflow_rejected": "프로젝트 워크플로가 이 변경을 허용하지 않습니다",
+ "assignee_not_allowed": "이 담당자에게 배정할 수 없습니다",
+ "properties_too_large": "사용자 지정 속성이 크기 제한을 넘습니다",
+ "write_failed": "저장하지 못했습니다"
+ }
},
"card": {
"update_failed": "태스크를 업데이트하지 못했습니다",
diff --git a/packages/views/locales/ko/search.json b/packages/views/locales/ko/search.json
index cdce8db951..c571c2a71a 100644
--- a/packages/views/locales/ko/search.json
+++ b/packages/views/locales/ko/search.json
@@ -122,7 +122,6 @@
"unsubscribed": "구독을 취소했습니다",
"label_added": "라벨 {{name}}을 추가했습니다",
"label_removed": "라벨 {{name}}을 제거했습니다",
- "label_failed": "일부 태스크에 라벨 {{name}}을 추가하지 못했습니다",
"update_failed": "업데이트에 실패했습니다",
"assigned": "{{identifier}}를 {{name}}에게 지정했습니다"
},
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index 24704dd3fc..2c7763b700 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -1106,7 +1106,52 @@
"delete_count_one": "Удалить {{count}} задачу",
"delete_count_few": "Удалить {{count}} задачи",
"delete_count_many": "Удалить {{count}} задач",
- "delete_count_other": "Удалить {{count}} задачи"
+ "delete_count_other": "Удалить {{count}} задачи",
+ "labels": "Метки",
+ "project": "Проект",
+ "due_date": "Срок выполнения",
+ "more": "Другие действия",
+ "stage": "Этап",
+ "custom_properties": "Пользовательские свойства",
+ "pick_date": "Выбрать дату…",
+ "property_edit": "Задать значение…",
+ "result_unknown": "Не удалось подтвердить, какие задачи изменились. Проверьте список перед повтором.",
+ "property_clear": "Очистить (задано: {{count}})",
+ "labels_search": "Добавить или убрать метки…",
+ "clear_labels_one": "Убрать все метки у {{count}} задачи",
+ "clear_labels_few": "Убрать все метки у {{count}} задач",
+ "clear_labels_many": "Убрать все метки у {{count}} задач",
+ "clear_labels_other": "Убрать все метки у {{count}} задачи",
+ "set_parent_title_one": "Родительская задача для {{count}} задачи",
+ "set_parent_title_few": "Родительская задача для {{count}} задач",
+ "set_parent_title_many": "Родительская задача для {{count}} задач",
+ "set_parent_title_other": "Родительская задача для {{count}} задачи",
+ "set_parent_description_one": "Найдите задачу, которая станет родительской для {{count}} выбранной задачи.",
+ "set_parent_description_few": "Найдите задачу, которая станет родительской для {{count}} выбранных задач.",
+ "set_parent_description_many": "Найдите задачу, которая станет родительской для {{count}} выбранных задач.",
+ "set_parent_description_other": "Найдите задачу, которая станет родительской для {{count}} выбранной задачи.",
+ "skipped_title_one": "Обновлено: {{updated}}, пропущена {{count}} задача",
+ "skipped_title_few": "Обновлено: {{updated}}, пропущены {{count}} задачи",
+ "skipped_title_many": "Обновлено: {{updated}}, пропущено {{count}} задач",
+ "skipped_title_other": "Обновлено: {{updated}}, пропущено {{count}} задачи",
+ "skipped_more": "и ещё {{count}}",
+ "select_skipped_one": "Выбрать только эту задачу",
+ "select_skipped_few": "Выбрать только эти ({{count}})",
+ "select_skipped_many": "Выбрать только эти ({{count}})",
+ "select_skipped_other": "Выбрать только эти ({{count}})",
+ "server_outdated": "Этот сервер пока не умеет массово менять метки и пользовательские свойства. Обновите сервер и попробуйте снова.",
+ "skip_reason": {
+ "invalid_id": "Недопустимая задача",
+ "not_found": "Не найдена или нет доступа",
+ "invalid_value": "Значение не подходит для этой задачи",
+ "parent_self": "Задача не может быть родительской для самой себя",
+ "parent_not_found": "Родительская задача не найдена",
+ "parent_cycle": "Родительская задача — одна из её подзадач",
+ "workflow_rejected": "Процесс её проекта не допускает этого изменения",
+ "assignee_not_allowed": "Нельзя назначить этому исполнителю",
+ "properties_too_large": "Пользовательские свойства превысят допустимый размер",
+ "write_failed": "Не удалось сохранить задачу"
+ }
},
"card": {
"update_failed": "Не удалось обновить задачу",
diff --git a/packages/views/locales/ru/search.json b/packages/views/locales/ru/search.json
index 117614d91d..29f3be0e90 100644
--- a/packages/views/locales/ru/search.json
+++ b/packages/views/locales/ru/search.json
@@ -131,7 +131,6 @@
"unsubscribed": "Подписка отменена",
"label_added": "Добавлена метка «{{name}}»",
"label_removed": "Удалена метка «{{name}}»",
- "label_failed": "Не удалось добавить метку «{{name}}» ко всем задачам",
"update_failed": "Не удалось обновить",
"assigned": "Задача {{identifier}} назначена: {{name}}"
},
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 7ffd773261..f572dc66b5 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -960,7 +960,37 @@
"cancel": "取消",
"copy_links": "复制链接",
"links_copied_other": "已复制 {{count}} 个链接",
- "delete_count_other": "删除 {{count}} 个任务"
+ "delete_count_other": "删除 {{count}} 个任务",
+ "labels": "标签",
+ "project": "项目",
+ "due_date": "截止日期",
+ "more": "更多操作",
+ "stage": "阶段",
+ "custom_properties": "自定义属性",
+ "pick_date": "选择日期…",
+ "property_edit": "设置值…",
+ "result_unknown": "无法确认哪些任务已修改,重试前请先检查列表。",
+ "property_clear": "清空({{count}} 个已设置)",
+ "labels_search": "添加或移除标签…",
+ "clear_labels_other": "清除这 {{count}} 个任务的全部标签",
+ "set_parent_title_other": "为 {{count}} 个任务设置父任务",
+ "set_parent_description_other": "搜索一个任务,设为所选 {{count}} 个任务的父任务",
+ "skipped_title_other": "已更新 {{updated}} 个任务,{{count}} 个未更新",
+ "skipped_more": "还有 {{count}} 个",
+ "select_skipped_other": "只选中这 {{count}} 个",
+ "server_outdated": "当前服务器版本还不支持批量修改标签和自定义属性,请升级后重试。",
+ "skip_reason": {
+ "invalid_id": "不是有效的任务",
+ "not_found": "任务不存在或你无权查看",
+ "invalid_value": "这个值不适用于该任务",
+ "parent_self": "不能把任务设为它自己的父任务",
+ "parent_not_found": "找不到父任务",
+ "parent_cycle": "父任务是它的子任务,会形成循环",
+ "workflow_rejected": "所在项目的工作流不允许这项修改",
+ "assignee_not_allowed": "不能分配给这个负责人",
+ "properties_too_large": "自定义属性会超出大小上限",
+ "write_failed": "保存失败"
+ }
},
"card": {
"update_failed": "更新任务失败",
diff --git a/packages/views/locales/zh-Hans/search.json b/packages/views/locales/zh-Hans/search.json
index d8312dc59f..3e2eed3875 100644
--- a/packages/views/locales/zh-Hans/search.json
+++ b/packages/views/locales/zh-Hans/search.json
@@ -122,7 +122,6 @@
"unsubscribed": "已取消订阅",
"label_added": "已添加标签 {{name}}",
"label_removed": "已移除标签 {{name}}",
- "label_failed": "未能给所有任务添加标签 {{name}}",
"update_failed": "更新失败",
"assigned": "已把 {{identifier}} 指派给 {{name}}"
},
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index 321462abaf..17743b93aa 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -960,7 +960,37 @@
"cancel": "取消",
"copy_links": "複製連結",
"links_copied_other": "已複製 {{count}} 個連結",
- "delete_count_other": "刪除 {{count}} 個任務"
+ "delete_count_other": "刪除 {{count}} 個任務",
+ "labels": "標籤",
+ "project": "專案",
+ "due_date": "截止日期",
+ "more": "更多操作",
+ "stage": "階段",
+ "custom_properties": "自訂屬性",
+ "pick_date": "選擇日期…",
+ "property_edit": "設定值…",
+ "result_unknown": "無法確認哪些任務已修改,重試前請先檢查列表。",
+ "property_clear": "清空({{count}} 個已設定)",
+ "labels_search": "新增或移除標籤…",
+ "clear_labels_other": "清除這 {{count}} 個任務的全部標籤",
+ "set_parent_title_other": "為 {{count}} 個任務設定父任務",
+ "set_parent_description_other": "搜尋一個任務,設為所選 {{count}} 個任務的父任務",
+ "skipped_title_other": "已更新 {{updated}} 個任務,{{count}} 個未更新",
+ "skipped_more": "還有 {{count}} 個",
+ "select_skipped_other": "只選取這 {{count}} 個",
+ "server_outdated": "目前的伺服器版本尚不支援批次修改標籤和自訂屬性,請升級後重試。",
+ "skip_reason": {
+ "invalid_id": "不是有效的任務",
+ "not_found": "任務不存在或你無權檢視",
+ "invalid_value": "這個值不適用於該任務",
+ "parent_self": "不能把任務設為它自己的父任務",
+ "parent_not_found": "找不到父任務",
+ "parent_cycle": "父任務是它的子任務,會形成循環",
+ "workflow_rejected": "所在專案的工作流程不允許這項修改",
+ "assignee_not_allowed": "不能指派給這個負責人",
+ "properties_too_large": "自訂屬性會超出大小上限",
+ "write_failed": "儲存失敗"
+ }
},
"card": {
"update_failed": "更新任務失敗",
diff --git a/packages/views/locales/zh-Hant/search.json b/packages/views/locales/zh-Hant/search.json
index 503b8ddb03..795f216b28 100644
--- a/packages/views/locales/zh-Hant/search.json
+++ b/packages/views/locales/zh-Hant/search.json
@@ -122,7 +122,6 @@
"unsubscribed": "已取消訂閱",
"label_added": "已新增標籤 {{name}}",
"label_removed": "已移除標籤 {{name}}",
- "label_failed": "未能給所有任務新增標籤 {{name}}",
"update_failed": "更新失敗",
"assigned": "已把 {{identifier}} 指派給 {{name}}"
},
diff --git a/packages/views/modals/run-confirm.tsx b/packages/views/modals/run-confirm.tsx
index f96bf954e0..3a3d372e1d 100644
--- a/packages/views/modals/run-confirm.tsx
+++ b/packages/views/modals/run-confirm.tsx
@@ -14,6 +14,7 @@ import { Button } from "@multica/ui/components/ui/button";
import { Spinner } from "@multica/ui/components/ui/spinner";
import type { IssueAssigneeType, IssueStatus, UpdateIssueRequest } from "@multica/core/types";
import { useUpdateIssue, useBatchUpdateIssues } from "@multica/core/issues/mutations";
+import { useBatchResultToast } from "../issues/components/batch-result-toast";
import { errorCode } from "@multica/core/api";
import { useActorName } from "@multica/core/workspace/hooks";
import { useWorkspaceId } from "@multica/core/hooks";
@@ -111,6 +112,7 @@ export function RunConfirmModal({
const updateIssue = useUpdateIssue();
const batchUpdate = useBatchUpdateIssues();
+ const { report: reportBatch } = useBatchResultToast();
const wsId = useWorkspaceId();
// Built-ins resolve through i18n, custom statuses through the catalog, so the
@@ -153,14 +155,11 @@ export function RunConfirmModal({
...payload,
});
} else {
- const { updated } = await batchUpdate.mutateAsync({ ids: issueIds, updates: payload });
+ const response = await batchUpdate.mutateAsync({ ids: issueIds, updates: payload });
// A partial batch still closes (the applied writes are real), but it
- // warns with the real count and skips onApplied so the caller keeps
+ // names the skipped issues and skips onApplied so the caller keeps
// its selection for a retry.
- if (updated < issueIds.length) {
- toast.warning(
- tIssues(($) => $.batch.update_partial, { updated, count: issueIds.length }),
- );
+ if (!reportBatch(response, issueIds.length, { successMessage: null })) {
onClose();
return;
}
diff --git a/packages/views/projects/components/project-picker.tsx b/packages/views/projects/components/project-picker.tsx
index 5bd3f9907e..120ffa4c17 100644
--- a/packages/views/projects/components/project-picker.tsx
+++ b/packages/views/projects/components/project-picker.tsx
@@ -21,6 +21,7 @@ import { useT } from "../../i18n";
export function ProjectPicker({
projectId,
onUpdate,
+ trigger: customTrigger,
triggerRender,
tooltip,
align = "start",
@@ -29,8 +30,11 @@ export function ProjectPicker({
onOpenChange,
disabled = false,
}: {
- projectId: string | null;
+ /** `undefined` for a selection whose issues sit in different projects: no row is checked. */
+ projectId: string | null | undefined;
onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
+ /** Trigger content in place of the current project. */
+ trigger?: React.ReactNode;
triggerRender?: React.ReactElement;
/** Hover tooltip naming the property; hidden while the picker is open. */
tooltip?: React.ReactNode;
@@ -88,7 +92,7 @@ export function ProjectPicker({
triggerRender={resolvedTriggerRender}
tooltip={tooltip}
trigger={
- current ? (
+ customTrigger ?? (current ? (
<>
<ProjectIcon project={current} size="sm" />
<span className="truncate">{current.title}</span>
@@ -98,7 +102,7 @@ export function ProjectPicker({
<FolderKanban className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="truncate">{t(($) => $.picker.no_project)}</span>
</>
- )
+ ))
}
>
{/* "No project" — always the first row, search active or not, and the
@@ -106,7 +110,7 @@ export function ProjectPicker({
the unassigned row in the assignee picker. */}
<PickerItem
emptyValue
- selected={!projectId}
+ selected={projectId === null}
onClick={() => {
onUpdate({ project_id: null });
setOpen(false);
diff --git a/packages/views/search/issue-target.ts b/packages/views/search/issue-target.ts
index 1fcfac3aac..8e0655b350 100644
--- a/packages/views/search/issue-target.ts
+++ b/packages/views/search/issue-target.ts
@@ -2,13 +2,14 @@
import { useCallback, useMemo } from "react";
import { toast } from "sonner";
-import type { Issue, UpdateIssueRequest } from "@multica/core/types";
+import type { BatchIssueLabelOps, Issue, UpdateIssueRequest } from "@multica/core/types";
import { errorCode } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useBatchUpdateIssues, useUpdateIssue } from "@multica/core/issues/mutations";
import { useModalStore } from "@multica/core/modals";
import { runConfirmIntent } from "../issues/actions/run-confirm-gate";
+import { useBatchResultToast } from "../issues/components/batch-result-toast";
import { useT } from "../i18n";
import type { IssueTarget } from "./types";
@@ -37,25 +38,19 @@ export function useIssueTargetWriter(target: IssueTarget) {
const openModal = useModalStore((s) => s.open);
const issues = useMemo(() => targetIssues(target), [target]);
+ const { report, reportError } = useBatchResultToast();
const applyBatch = useCallback(
- async (updates: Partial<UpdateIssueRequest>) => {
+ async (updates: Partial<UpdateIssueRequest>, labels?: BatchIssueLabelOps, successMessage?: string) => {
if (target.kind !== "batch") return;
const ids = issues.map((issue) => issue.id);
- const count = ids.length;
try {
- const { updated } = await batchUpdate.mutateAsync({ ids, updates });
- if (updated < count) {
- toast.warning(t(($) => $.batch.update_partial, { updated, count }));
- } else {
- toast.success(t(($) => $.batch.update_success, { count }));
- }
+ const response = await batchUpdate.mutateAsync({ ids, updates, labels });
+ report(response, ids.length, { successMessage });
} catch (err) {
- toast.error(
- err instanceof Error && err.message ? err.message : t(($) => $.batch.update_failed),
- );
+ reportError(err);
}
},
- [batchUpdate, issues, t, target.kind],
+ [batchUpdate, issues, report, reportError, target.kind],
);
const applySingle = useCallback(
@@ -115,5 +110,11 @@ export function useIssueTargetWriter(target: IssueTarget) {
[apply, issues, openModal, target.kind],
);
- return { issues, apply, assign };
+ /** Label add / remove across a selection, as one batch write. */
+ const applyLabels = useCallback(
+ (labels: BatchIssueLabelOps, successMessage: string) => void applyBatch({}, labels, successMessage),
+ [applyBatch],
+ );
+
+ return { issues, apply, assign, applyLabels };
}
diff --git a/packages/views/search/pages/issue-pages.tsx b/packages/views/search/pages/issue-pages.tsx
index c3d796bc77..b070b9c88a 100644
--- a/packages/views/search/pages/issue-pages.tsx
+++ b/packages/views/search/pages/issue-pages.tsx
@@ -320,35 +320,44 @@ export function IssueLabelsPage({ target, query }: { target: IssueTarget; query:
});
const attach = useAttachLabelToIssue();
const detach = useDetachLabel(single?.id ?? "");
+ const writer = useIssueTargetWriter(target);
const labelIdsOf = (issue: Issue) =>
new Set((single && issue.id === single.id && singleLabels ? singleLabels : issue.labels ?? []).map((l) => l.id));
const visible = filterByLabel(labels, query, (label) => label.name);
+ const countOf = (label: Label) => issues.filter((issue) => labelIdsOf(issue).has(label.id)).length;
+ // A row on every target is a checked toggle: selecting it removes the label.
const toggle = (label: Label) => {
palette.close();
- const lacking = issues.filter((issue) => !labelIdsOf(issue).has(label.id));
- if (lacking.length === 0 && single) {
- // Every target already has it: on a single issue the row reads as a
- // checked toggle, so selecting it removes the label.
- detach.mutateAsync(label.id).then(
- () => toast.success(t(($) => $.toast.label_removed, { name: label.name })),
- (err: unknown) => toast.error(err instanceof Error ? err.message : String(err)),
+ const onAll = countOf(label) === issues.length;
+ if (!single) {
+ writer.applyLabels(
+ onAll ? { remove: [label.id] } : { add: [label.id] },
+ onAll
+ ? t(($) => $.toast.label_removed, { name: label.name })
+ : t(($) => $.toast.label_added, { name: label.name }),
);
return;
}
- void Promise.allSettled(
- lacking.map((issue) => attach.mutateAsync({ issueId: issue.id, labelId: label.id })),
- ).then((results) => {
- const failed = results.filter((r) => r.status === "rejected").length;
- if (failed > 0) toast.error(t(($) => $.toast.label_failed, { name: label.name }));
- else toast.success(t(($) => $.toast.label_added, { name: label.name }));
- });
+ const write = onAll
+ ? detach.mutateAsync(label.id)
+ : attach.mutateAsync({ issueId: single.id, labelId: label.id });
+ write.then(
+ () =>
+ toast.success(
+ onAll
+ ? t(($) => $.toast.label_removed, { name: label.name })
+ : t(($) => $.toast.label_added, { name: label.name }),
+ ),
+ (err: unknown) => toast.error(err instanceof Error ? err.message : String(err)),
+ );
};
return (
<PaletteGroup heading={t(($) => $.pages.labels)}>
{visible.map((label) => {
- const onAll = issues.every((issue) => labelIdsOf(issue).has(label.id));
+ const n = countOf(label);
+ const onAll = n === issues.length;
return (
<CommandPrimitive.Item
data-mc="palette-item"
@@ -365,7 +374,11 @@ export function IssueLabelsPage({ target, query }: { target: IssueTarget; query:
<span className="min-w-0 flex-1 truncate">
<HighlightText text={label.name} query={query} />
</span>
- {onAll && <RowCheck label={t(($) => $.pages.current)} />}
+ {onAll ? (
+ <RowCheck label={t(($) => $.pages.current)} />
+ ) : (
+ n > 0 && <RowHint>{`${n}/${issues.length}`}</RowHint>
+ )}
</CommandPrimitive.Item>
);
})}
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 0073a7cc13..dfe948f557 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -714,6 +714,7 @@ func init() {
// issue delete
issueDeleteCmd.Flags().BoolP("yes", "y", false, "Skip the confirmation prompt")
+ issueDeleteCmd.Flags().Bool("dry-run", false, "List what would be deleted without deleting")
issueDeleteCmd.Flags().String("output", "table", "Output format: table or json")
// issue reorder
diff --git a/server/cmd/multica/cmd_issue_batch.go b/server/cmd/multica/cmd_issue_batch.go
new file mode 100644
index 0000000000..2f2d0f553d
--- /dev/null
+++ b/server/cmd/multica/cmd_issue_batch.go
@@ -0,0 +1,400 @@
+package main
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// multica issue batch update — one change applied to many issues through
+// POST /api/issues/batch-update. Each issue is written on its own, so the
+// server answers with a result per issue: updated, unchanged, or skipped with
+// a reason. Deletion in batch is `multica issue delete <id>...`.
+
+const issueBatchChunkSize = 100
+
+var issueBatchCmd = &cobra.Command{
+ Use: "batch",
+ Short: "Change many issues at once",
+}
+
+var issueBatchUpdateCmd = &cobra.Command{
+ Use: "update <id>...",
+ Short: "Apply the same change to several issues",
+ Long: "Apply the same change to several issues.\n\n" +
+ "Ids may be issue keys (e.g. MUL-123) or full UUIDs, as arguments or one per line\n" +
+ "with --ids-stdin. Every issue is written on its own: the command prints one row per\n" +
+ "issue saying whether it was updated, already matched (unchanged) or skipped and why.\n" +
+ "It exits non-zero when any issue was skipped, after printing the rows.\n\n" +
+ "Labels: --add-label and --remove-label leave other labels alone; --clear-labels\n" +
+ "removes every label first, so --clear-labels --add-label X replaces the set.\n" +
+ "Custom properties: --property Name=Value sets a value (same forms as\n" +
+ "`issue create --property`); --unset-property Name clears it.\n\n" +
+ "--dry-run runs every check and prints the same rows without writing anything.",
+ RunE: runIssueBatchUpdate,
+}
+
+func init() {
+ issueBatchCmd.AddCommand(issueBatchUpdateCmd)
+ issueCmd.AddCommand(issueBatchCmd)
+ addIssueBatchUpdateFlags(issueBatchUpdateCmd)
+}
+
+func addIssueBatchUpdateFlags(cmd *cobra.Command) {
+ f := cmd.Flags()
+ f.Bool("ids-stdin", false, "Read issue ids from stdin, one per line (in addition to arguments)")
+ f.String("status", "", "New status")
+ f.String("priority", "", "New priority")
+ f.String("assignee", "", "New assignee name (member, agent, or squad; fuzzy match)")
+ f.String("assignee-id", "", "New assignee UUID — member, agent, or squad (mutually exclusive with --assignee)")
+ f.Bool("unassign", false, "Remove the assignee")
+ f.String("project", "", "Project ID (use --project \"\" to clear)")
+ f.String("start-date", "", "Start date (YYYY-MM-DD; pass empty string to clear)")
+ f.String("due-date", "", "Due date (YYYY-MM-DD; pass empty string to clear)")
+ f.String("parent", "", "Parent issue ID (use --parent \"\" to clear)")
+ f.Int("stage", 0, "Stage ordinal (>=1) for sub-issues; see `issue create --stage`")
+ f.StringArray("add-label", nil, "Label name or UUID to add (repeatable)")
+ f.StringArray("remove-label", nil, "Label name or UUID to remove (repeatable)")
+ f.Bool("clear-labels", false, "Remove every label before --add-label is applied")
+ f.StringArray("property", nil, `Set a custom property as "Name=Value" (repeatable; same value forms as issue create --property)`)
+ f.StringArray("unset-property", nil, "Custom property name or UUID to clear (repeatable)")
+ f.Bool("no-start", false, "Apply the change without starting agent runs")
+ f.Bool("dry-run", false, "Report what would change without writing")
+ f.String("output", "table", "Output format: table or json")
+}
+
+type issueBatchResult struct {
+ IssueID string `json:"issue_id"`
+ Identifier string `json:"identifier,omitempty"`
+ Outcome string `json:"outcome"`
+ Code string `json:"code,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+type issueBatchResponse struct {
+ Updated int `json:"updated"`
+ Deleted int `json:"deleted"`
+ DryRun bool `json:"dry_run,omitempty"`
+ Results []issueBatchResult `json:"results"`
+}
+
+// requireIssueBatchOps fails closed on servers that predate per-issue results:
+// they ignore labels, properties and dry_run, so a dry run there would write.
+func requireIssueBatchOps(ctx context.Context, client *cli.APIClient) error {
+ var config struct {
+ Supported bool `json:"issue_batch_ops_supported"`
+ }
+ if err := client.GetJSON(ctx, "/api/config", &config); err != nil {
+ return fmt.Errorf("check batch support: %w", err)
+ }
+ if !config.Supported {
+ return errors.New("this server version does not support batch results or dry runs; update the server, or change issues one at a time with `multica issue update`")
+ }
+ return nil
+}
+
+func collectIssueBatchArgs(cmd *cobra.Command, args []string, stdin io.Reader) ([]string, error) {
+ refs := append([]string(nil), args...)
+ if fromStdin, _ := cmd.Flags().GetBool("ids-stdin"); fromStdin {
+ scanner := bufio.NewScanner(stdin)
+ for scanner.Scan() {
+ if line := strings.TrimSpace(scanner.Text()); line != "" {
+ refs = append(refs, line)
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ return nil, fmt.Errorf("read ids from stdin: %w", err)
+ }
+ }
+ if len(refs) == 0 {
+ return nil, errors.New("no issues given; pass ids as arguments or with --ids-stdin")
+ }
+ return refs, nil
+}
+
+func buildIssueBatchUpdateBody(ctx context.Context, client *cli.APIClient, cmd *cobra.Command) (map[string]any, error) {
+ flags := cmd.Flags()
+ updates := map[string]any{}
+ if flags.Changed("status") {
+ v, _ := flags.GetString("status")
+ if err := validateIssueStatus(v); err != nil {
+ return nil, err
+ }
+ updates["status"] = v
+ }
+ if flags.Changed("priority") {
+ v, _ := flags.GetString("priority")
+ if err := validateIssuePriority(v); err != nil {
+ return nil, err
+ }
+ updates["priority"] = v
+ }
+ unassign, _ := flags.GetBool("unassign")
+ if unassign && (flags.Changed("assignee") || flags.Changed("assignee-id")) {
+ return nil, errors.New("--unassign cannot be combined with --assignee or --assignee-id")
+ }
+ if unassign {
+ updates["assignee_type"] = nil
+ updates["assignee_id"] = nil
+ } else if flags.Changed("assignee") || flags.Changed("assignee-id") {
+ aType, aID, ok, err := pickAssigneeFromFlags(ctx, client, cmd, "assignee", "assignee-id", issueAssigneeKinds)
+ if err != nil {
+ return nil, fmt.Errorf("resolve assignee: %w", err)
+ }
+ if ok {
+ updates["assignee_type"] = aType
+ updates["assignee_id"] = aID
+ }
+ }
+ if flags.Changed("project") {
+ v, _ := flags.GetString("project")
+ if v == "" {
+ updates["project_id"] = nil
+ } else {
+ project, err := resolveProjectID(ctx, client, v)
+ if err != nil {
+ return nil, fmt.Errorf("resolve project: %w", err)
+ }
+ updates["project_id"] = project.ID
+ }
+ }
+ for _, name := range []string{"start-date", "due-date"} {
+ if flags.Changed(name) {
+ v, _ := flags.GetString(name)
+ updates[strings.ReplaceAll(name, "-", "_")] = v
+ }
+ }
+ if flags.Changed("parent") {
+ v, _ := flags.GetString("parent")
+ if v == "" {
+ updates["parent_issue_id"] = nil
+ } else {
+ parent, err := resolveIssueRef(ctx, client, v)
+ if err != nil {
+ return nil, fmt.Errorf("resolve parent issue: %w", err)
+ }
+ updates["parent_issue_id"] = parent.ID
+ }
+ }
+ if flags.Changed("stage") {
+ stage, _ := flags.GetInt("stage")
+ if stage < 1 {
+ return nil, errors.New("--stage must be >= 1")
+ }
+ updates["stage"] = stage
+ }
+
+ body := map[string]any{}
+ if len(updates) > 0 {
+ if noStart, _ := flags.GetBool("no-start"); noStart {
+ updates["suppress_run"] = true
+ }
+ body["updates"] = updates
+ }
+
+ addRefs, _ := flags.GetStringArray("add-label")
+ removeRefs, _ := flags.GetStringArray("remove-label")
+ clearLabels, _ := flags.GetBool("clear-labels")
+ if len(addRefs) > 0 || len(removeRefs) > 0 || clearLabels {
+ candidates, err := fetchLabelCandidates(ctx, client, "issue")
+ if err != nil {
+ return nil, fmt.Errorf("list labels: %w", err)
+ }
+ add, err := resolveIssueBatchLabels(ctx, client, candidates, addRefs)
+ if err != nil {
+ return nil, err
+ }
+ remove, err := resolveIssueBatchLabels(ctx, client, candidates, removeRefs)
+ if err != nil {
+ return nil, err
+ }
+ if clearLabels && len(remove) > 0 {
+ return nil, errors.New("--clear-labels already removes every label; drop --remove-label")
+ }
+ body["labels"] = map[string]any{"add": add, "remove": remove, "clear": clearLabels}
+ }
+
+ setPairs, _ := flags.GetStringArray("property")
+ unsetRefs, _ := flags.GetStringArray("unset-property")
+ if len(setPairs) > 0 || len(unsetRefs) > 0 {
+ properties := map[string]any{}
+ if len(setPairs) > 0 {
+ set, err := buildIssuePropertyValues(ctx, client, setPairs, "in a batch update", "cannot unset a property; use --unset-property")
+ if err != nil {
+ return nil, err
+ }
+ properties["set"] = set
+ }
+ if len(unsetRefs) > 0 {
+ catalog, err := fetchProperties(ctx, client)
+ if err != nil {
+ return nil, err
+ }
+ unset := make([]string, 0, len(unsetRefs))
+ for _, ref := range unsetRefs {
+ property, err := resolvePropertyRef(catalog, ref)
+ if err != nil {
+ return nil, err
+ }
+ unset = append(unset, property.ID)
+ }
+ properties["unset"] = unset
+ }
+ body["properties"] = properties
+ }
+
+ if len(body) == 0 {
+ return nil, errors.New("nothing to change; use flags like --status, --assignee, --add-label or --property")
+ }
+ if dryRun, _ := flags.GetBool("dry-run"); dryRun {
+ body["dry_run"] = true
+ }
+ return body, nil
+}
+
+// resolveIssueBatchLabels accepts a label's name (case-insensitive) as well
+// as its UUID or UUID prefix.
+func resolveIssueBatchLabels(ctx context.Context, client *cli.APIClient, candidates []idCandidate, refs []string) ([]string, error) {
+ ids := make([]string, 0, len(refs))
+ for _, ref := range refs {
+ var byName []idCandidate
+ for _, c := range candidates {
+ if strings.EqualFold(c.Display, strings.TrimSpace(ref)) {
+ byName = append(byName, c)
+ }
+ }
+ switch {
+ case len(byName) == 1:
+ ids = append(ids, byName[0].ID)
+ case len(byName) > 1:
+ return nil, fmt.Errorf("label name %q is ambiguous; pass its UUID", ref)
+ default:
+ label, err := resolveLabelID(ctx, client, ref, "issue")
+ if err != nil {
+ return nil, fmt.Errorf("resolve label %q: %w", ref, err)
+ }
+ ids = append(ids, label.ID)
+ }
+ }
+ return ids, nil
+}
+
+func runIssueBatchUpdate(cmd *cobra.Command, args []string) error {
+ refs, err := collectIssueBatchArgs(cmd, args, os.Stdin)
+ if err != nil {
+ return err
+ }
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+
+ prepCtx, cancelPrep := cli.APIContext(context.Background())
+ defer cancelPrep()
+ if err := requireIssueBatchOps(prepCtx, client); err != nil {
+ return err
+ }
+ body, err := buildIssueBatchUpdateBody(prepCtx, client, cmd)
+ if err != nil {
+ return err
+ }
+ ids := make([]string, 0, len(refs))
+ seen := make(map[string]struct{}, len(refs))
+ for _, ref := range refs {
+ resolved, err := resolveIssueRef(prepCtx, client, ref)
+ if err != nil {
+ return fmt.Errorf("resolve issue %q: %w", ref, err)
+ }
+ if _, dup := seen[resolved.ID]; dup {
+ continue
+ }
+ seen[resolved.ID] = struct{}{}
+ ids = append(ids, resolved.ID)
+ }
+
+ var combined issueBatchResponse
+ for start := 0; start < len(ids); start += issueBatchChunkSize {
+ end := min(start+issueBatchChunkSize, len(ids))
+ body["issue_ids"] = ids[start:end]
+ var resp issueBatchResponse
+ ctx, cancel := cli.APIContext(context.Background())
+ err := client.PostJSON(ctx, "/api/issues/batch-update", body, &resp)
+ cancel()
+ if err != nil {
+ if start > 0 {
+ printIssueBatchResults(cmd, combined)
+ return fmt.Errorf("batch update stopped after %d of %d issues: %w", start, len(ids), err)
+ }
+ return fmt.Errorf("batch update: %w", err)
+ }
+ if resp.Results == nil {
+ return errors.New("the server did not return per-issue results; update the server before using `issue batch update`")
+ }
+ combined.Updated += resp.Updated
+ combined.DryRun = resp.DryRun
+ combined.Results = append(combined.Results, resp.Results...)
+ }
+ return finishIssueBatch(cmd, combined)
+}
+
+// finishIssueBatch prints the rows and turns any skipped issue into a
+// non-zero exit, so scripts cannot mistake a partial batch for success.
+func finishIssueBatch(cmd *cobra.Command, resp issueBatchResponse) error {
+ if err := printIssueBatchResults(cmd, resp); err != nil {
+ return err
+ }
+ skipped := 0
+ for _, r := range resp.Results {
+ if r.Outcome == "skipped" {
+ skipped++
+ }
+ }
+ if skipped > 0 {
+ return fmt.Errorf("%d of %d issues were skipped; see the reasons above", skipped, len(resp.Results))
+ }
+ return nil
+}
+
+func printIssueBatchResults(cmd *cobra.Command, resp issueBatchResponse) error {
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, resp)
+ }
+ rows := make([][]string, 0, len(resp.Results))
+ counts := map[string]int{}
+ for _, r := range resp.Results {
+ key := r.Identifier
+ if key == "" {
+ key = r.IssueID
+ }
+ reason := r.Message
+ if r.Code != "" && reason == "" {
+ reason = r.Code
+ }
+ rows = append(rows, []string{key, strings.ReplaceAll(r.Outcome, "_", " "), reason})
+ counts[r.Outcome]++
+ }
+ cli.PrintTable(os.Stdout, []string{"ISSUE", "OUTCOME", "REASON"}, rows)
+ var parts []string
+ for _, outcome := range []string{"updated", "would_update", "unchanged", "deleted", "would_delete", "skipped"} {
+ if counts[outcome] > 0 {
+ parts = append(parts, fmt.Sprintf("%d %s", counts[outcome], strings.ReplaceAll(outcome, "_", " ")))
+ }
+ }
+ if len(parts) > 0 {
+ prefix := ""
+ if resp.DryRun {
+ prefix = "Dry run, nothing written: "
+ }
+ fmt.Fprintln(os.Stderr, prefix+strings.Join(parts, ", ")+".")
+ }
+ return nil
+}
diff --git a/server/cmd/multica/cmd_issue_batch_test.go b/server/cmd/multica/cmd_issue_batch_test.go
new file mode 100644
index 0000000000..0bc892d7ef
--- /dev/null
+++ b/server/cmd/multica/cmd_issue_batch_test.go
@@ -0,0 +1,191 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/spf13/cobra"
+)
+
+func newIssueBatchUpdateTestCmd() *cobra.Command {
+ cmd := &cobra.Command{Use: "update"}
+ addIssueBatchUpdateFlags(cmd)
+ return cmd
+}
+
+type issueBatchTestServer struct {
+ supported bool
+ posts []map[string]any
+ response map[string]any
+}
+
+func (s *issueBatchTestServer) start(t *testing.T, labels, properties []map[string]any) {
+ t.Helper()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/config":
+ cfg := map[string]any{}
+ if s.supported {
+ cfg["issue_batch_ops_supported"] = true
+ }
+ json.NewEncoder(w).Encode(cfg)
+ case "/api/labels":
+ json.NewEncoder(w).Encode(map[string]any{"labels": labels})
+ case "/api/properties":
+ json.NewEncoder(w).Encode(map[string]any{"properties": properties})
+ case "/api/issues/batch-update", "/api/issues/batch-delete":
+ var body map[string]any
+ json.NewDecoder(r.Body).Decode(&body)
+ s.posts = append(s.posts, body)
+ json.NewEncoder(w).Encode(s.response)
+ default:
+ if id, ok := strings.CutPrefix(r.URL.Path, "/api/issues/"); ok && r.Method == http.MethodGet {
+ json.NewEncoder(w).Encode(map[string]any{"id": id, "identifier": "MUL-9"})
+ return
+ }
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(srv.Close)
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+}
+
+func TestIssueBatchUpdateFailsClosedOnOldServer(t *testing.T) {
+ s := &issueBatchTestServer{}
+ s.start(t, nil, nil)
+ cmd := newIssueBatchUpdateTestCmd()
+ _ = cmd.Flags().Set("status", "done")
+ _ = cmd.Flags().Set("dry-run", "true")
+ err := runIssueBatchUpdate(cmd, []string{uuid.NewString()})
+ if err == nil || !strings.Contains(err.Error(), "does not support batch results") {
+ t.Fatalf("error = %v, want capability failure", err)
+ }
+ if len(s.posts) != 0 {
+ t.Fatalf("old server received %d batch POST(s); a dry run there would write", len(s.posts))
+ }
+}
+
+func TestIssueBatchUpdateSendsLabelAndPropertyOpsAndFailsOnSkips(t *testing.T) {
+ bugID, frontendID, staleID := uuid.NewString(), uuid.NewString(), uuid.NewString()
+ propertyID := uuid.NewString()
+ a, b := uuid.NewString(), uuid.NewString()
+ s := &issueBatchTestServer{supported: true, response: map[string]any{
+ "updated": 1,
+ "results": []map[string]any{
+ {"issue_id": a, "identifier": "MUL-1", "outcome": "updated"},
+ {"issue_id": b, "identifier": "MUL-2", "outcome": "skipped", "code": "parent_cycle", "message": "MUL-2 is an ancestor"},
+ },
+ }}
+ s.start(t,
+ []map[string]any{{"id": bugID, "name": "Bug"}, {"id": frontendID, "name": "Frontend"}, {"id": staleID, "name": "Stale"}},
+ []map[string]any{{"id": propertyID, "name": "Notes", "type": "text", "config": map[string]any{}, "archived": false}},
+ )
+
+ cmd := newIssueBatchUpdateTestCmd()
+ _ = cmd.Flags().Set("priority", "high")
+ _ = cmd.Flags().Set("add-label", "bug")
+ _ = cmd.Flags().Set("add-label", frontendID)
+ _ = cmd.Flags().Set("remove-label", "Stale")
+ _ = cmd.Flags().Set("property", "Notes=needs repro")
+ _ = cmd.Flags().Set("output", "json")
+ err := runIssueBatchUpdate(cmd, []string{a, b, a})
+ if err == nil || !strings.Contains(err.Error(), "1 of 2 issues were skipped") {
+ t.Fatalf("error = %v, want a skipped-issues failure", err)
+ }
+ if len(s.posts) != 1 {
+ t.Fatalf("batch POST count = %d, want 1", len(s.posts))
+ }
+ body := s.posts[0]
+ if got := body["issue_ids"]; !reflect.DeepEqual(got, []any{a, b}) {
+ t.Errorf("issue_ids = %#v, want de-duplicated in order", got)
+ }
+ if got := body["updates"]; !reflect.DeepEqual(got, map[string]any{"priority": "high"}) {
+ t.Errorf("updates = %#v", got)
+ }
+ wantLabels := map[string]any{"add": []any{bugID, frontendID}, "remove": []any{staleID}, "clear": false}
+ if got := body["labels"]; !reflect.DeepEqual(got, wantLabels) {
+ t.Errorf("labels = %#v, want %#v", got, wantLabels)
+ }
+ wantProps := map[string]any{"set": map[string]any{propertyID: "needs repro"}}
+ if got := body["properties"]; !reflect.DeepEqual(got, wantProps) {
+ t.Errorf("properties = %#v, want %#v", got, wantProps)
+ }
+ if _, ok := body["dry_run"]; ok {
+ t.Errorf("dry_run sent without --dry-run")
+ }
+}
+
+func TestIssueBatchUpdateRejectsMissingResults(t *testing.T) {
+ s := &issueBatchTestServer{supported: true, response: map[string]any{"updated": 1}}
+ s.start(t, nil, nil)
+ cmd := newIssueBatchUpdateTestCmd()
+ _ = cmd.Flags().Set("status", "done")
+ err := runIssueBatchUpdate(cmd, []string{uuid.NewString()})
+ if err == nil || !strings.Contains(err.Error(), "did not return per-issue results") {
+ t.Fatalf("error = %v", err)
+ }
+}
+
+func TestIssueBatchUpdateRequiresAChange(t *testing.T) {
+ s := &issueBatchTestServer{supported: true}
+ s.start(t, nil, nil)
+ cmd := newIssueBatchUpdateTestCmd()
+ err := runIssueBatchUpdate(cmd, []string{uuid.NewString()})
+ if err == nil || !strings.Contains(err.Error(), "nothing to change") {
+ t.Fatalf("error = %v", err)
+ }
+ if len(s.posts) != 0 {
+ t.Fatalf("sent %d POST(s) for an empty change", len(s.posts))
+ }
+}
+
+func TestIssueBatchUpdateClearAndReplaceLabels(t *testing.T) {
+ bugID := uuid.NewString()
+ id := uuid.NewString()
+ s := &issueBatchTestServer{supported: true, response: map[string]any{
+ "updated": 0, "dry_run": true,
+ "results": []map[string]any{{"issue_id": id, "outcome": "would_update"}},
+ }}
+ s.start(t, []map[string]any{{"id": bugID, "name": "Bug"}}, nil)
+ cmd := newIssueBatchUpdateTestCmd()
+ _ = cmd.Flags().Set("clear-labels", "true")
+ _ = cmd.Flags().Set("add-label", "Bug")
+ _ = cmd.Flags().Set("dry-run", "true")
+ if err := runIssueBatchUpdate(cmd, []string{id}); err != nil {
+ t.Fatalf("runIssueBatchUpdate: %v", err)
+ }
+ body := s.posts[0]
+ if body["dry_run"] != true {
+ t.Errorf("dry_run = %#v", body["dry_run"])
+ }
+ if got := body["labels"]; !reflect.DeepEqual(got, map[string]any{"add": []any{bugID}, "remove": []any{}, "clear": true}) {
+ t.Errorf("labels = %#v", got)
+ }
+}
+
+func TestIssueDeleteDryRunSendsDryRunWithoutPrompt(t *testing.T) {
+ id := uuid.NewString()
+ s := &issueBatchTestServer{supported: true, response: map[string]any{
+ "deleted": 0, "dry_run": true,
+ "results": []map[string]any{{"issue_id": id, "identifier": "MUL-9", "outcome": "would_delete"}},
+ }}
+ s.start(t, nil, nil)
+ if err := issueDeleteCmd.Flags().Set("dry-run", "true"); err != nil {
+ t.Fatalf("set --dry-run: %v", err)
+ }
+ t.Cleanup(func() { _ = issueDeleteCmd.Flags().Set("dry-run", "false") })
+
+ if err := runIssueDelete(issueDeleteCmd, []string{id}); err != nil {
+ t.Fatalf("runIssueDelete: %v", err)
+ }
+ if len(s.posts) != 1 || s.posts[0]["dry_run"] != true {
+ t.Fatalf("posts = %#v, want one batch-delete with dry_run", s.posts)
+ }
+}
diff --git a/server/cmd/multica/cmd_issue_delete.go b/server/cmd/multica/cmd_issue_delete.go
index c0f4c0c093..6a4c5ce3ca 100644
--- a/server/cmd/multica/cmd_issue_delete.go
+++ b/server/cmd/multica/cmd_issue_delete.go
@@ -3,6 +3,7 @@ package main
import (
"bufio"
"context"
+ "errors"
"fmt"
"net/url"
"os"
@@ -39,7 +40,9 @@ var issueDeleteCmd = &cobra.Command{
"aborts the whole command instead of leaving a partial batch. Ids may be issue\n" +
"keys (e.g. MUL-123) or full UUIDs.\n\n" +
"Without --yes the command asks for confirmation. A non-interactive run that\n" +
- "cannot answer the prompt fails without deleting; pass --yes to skip it.",
+ "cannot answer the prompt fails without deleting; pass --yes to skip it.\n\n" +
+ "--dry-run checks the selection, including permission to delete it, and lists\n" +
+ "what would be deleted without deleting anything or asking for confirmation.",
Args: minimumArgs(1),
RunE: runIssueDelete,
}
@@ -57,6 +60,10 @@ func runIssueDelete(cmd *cobra.Command, args []string) error {
return err
}
+ if dryRun, _ := cmd.Flags().GetBool("dry-run"); dryRun {
+ return runIssueDeleteDryRun(cmd, client, refs)
+ }
+
yes, _ := cmd.Flags().GetBool("yes")
if !yes {
fmt.Fprint(os.Stderr, issueDeleteConfirmation(refs))
@@ -126,6 +133,26 @@ func runIssueDelete(cmd *cobra.Command, args []string) error {
return nil
}
+func runIssueDeleteDryRun(cmd *cobra.Command, client *cli.APIClient, refs []resolvedID) error {
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+ if err := requireIssueBatchOps(ctx, client); err != nil {
+ return err
+ }
+ ids := make([]string, len(refs))
+ for i, ref := range refs {
+ ids[i] = ref.ID
+ }
+ var resp issueBatchResponse
+ if err := client.PostJSON(ctx, "/api/issues/batch-delete", map[string]any{"issue_ids": ids, "dry_run": true}, &resp); err != nil {
+ return issueDeleteError("check deletion", err)
+ }
+ if !resp.DryRun {
+ return errors.New("the server did not confirm a dry run; nothing is known about what it did — run `multica issue list` before retrying")
+ }
+ return finishIssueBatch(cmd, resp)
+}
+
// issueDeleteError keeps the step that failed and the server's own refusal
// text — the 403 copy naming who may delete, or the 404 copy — instead of
// FormatError's generic kind message.
diff --git a/server/cmd/multica/cmd_property.go b/server/cmd/multica/cmd_property.go
index 993bbf72d8..5d978813a8 100644
--- a/server/cmd/multica/cmd_property.go
+++ b/server/cmd/multica/cmd_property.go
@@ -631,6 +631,12 @@ func encodeIssuePropertyValue(ctx context.Context, client *cli.APIClient, direct
// API's ID-keyed typed bag. A definition may appear only once, including when
// one flag uses its name and another its UUID.
func buildIssueCreateProperties(ctx context.Context, client *cli.APIClient, pairs []string) (map[string]json.RawMessage, error) {
+ return buildIssuePropertyValues(ctx, client, pairs, "when creating an issue", "cannot unset a property during create")
+}
+
+// buildIssuePropertyValues is the shared Name=Value resolver; when and
+// sentinelHint finish the two error messages that depend on the command.
+func buildIssuePropertyValues(ctx context.Context, client *cli.APIClient, pairs []string, when, sentinelHint string) (map[string]json.RawMessage, error) {
properties, err := fetchProperties(ctx, client)
if err != nil {
return nil, err
@@ -644,13 +650,13 @@ func buildIssueCreateProperties(ctx context.Context, client *cli.APIClient, pair
return nil, fmt.Errorf(`--property %q must be in "Name=Value" form`, pair)
}
if strings.HasSuffix(name, "<") || strings.HasSuffix(name, ">") || strings.HasSuffix(name, "!") {
- return nil, fmt.Errorf(`--property %q: filter comparison operators are not valid when creating an issue; use a property UUID if its name ends with that character`, pair)
+ return nil, fmt.Errorf(`--property %q: filter comparison operators are not valid %s; use a property UUID if its name ends with that character`, pair, when)
}
if strings.TrimSpace(rawValue) == "" {
return nil, fmt.Errorf("--property %s: value cannot be empty", name)
}
if strings.TrimSpace(rawValue) == propertyNoValueSentinel {
- return nil, fmt.Errorf("--property %s: %s is a list-filter value and cannot unset a property during create", name, propertyNoValueSentinel)
+ return nil, fmt.Errorf("--property %s: %s is a list-filter value and %s", name, propertyNoValueSentinel, sentinelHint)
}
property, err := resolvePropertyRef(properties, name)
if err != nil {
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index d150e9d7cb..53b4a9274e 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -750,7 +750,7 @@ const platformSkillName = "multica-platform"
// description, repeated in the brief's recall hint for agents that never read
// the skill listing. TestPlatformSkillDomainsMatchDescription keeps it equal to
// the description, so a new reference cannot ship without reaching the brief.
-const platformSkillDomains = "issue and PR contracts, sub-issues, saved views, charts and files in comments, mentions, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes"
+const platformSkillDomains = "issue and PR contracts, sub-issues, batch changes, saved views, charts and files in comments, mentions, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes"
// subIssueContractsSkill returns how the brief should refer to the skill
// carrying the sub-issue contracts, and whether any such skill is installed.
diff --git a/server/internal/handler/config.go b/server/internal/handler/config.go
index 16ae3c49e6..8f06ee535b 100644
--- a/server/internal/handler/config.go
+++ b/server/internal/handler/config.go
@@ -107,6 +107,12 @@ type AppConfig struct {
// replies unless it is declared.
CommentDeleteKeepRepliesSupported bool `json:"comment_delete_keep_replies_supported"`
+ // IssueBatchOpsSupported tells clients that batch update accepts labels,
+ // properties and dry_run, and that batch update and delete return
+ // per-issue results. Older handlers ignore those fields — a dry run there
+ // would write — so clients must fail closed when this is absent.
+ IssueBatchOpsSupported bool `json:"issue_batch_ops_supported"`
+
// ServerVersion is the running API build version, so self-hosted
// operators can confirm what's deployed and include it in bug reports.
// Only emitted on self-hosted deployments — omitted on the managed cloud,
@@ -127,6 +133,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
AgentConversationStartersSupported: true,
IssueCreatePropertiesSupported: true,
CommentDeleteKeepRepliesSupported: true,
+ IssueBatchOpsSupported: true,
AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",
GoogleClientID: os.Getenv("GOOGLE_CLIENT_ID"),
WorkspaceCreationDisabled: os.Getenv("DISABLE_WORKSPACE_CREATION") == "true",
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index 7fadd1e9a7..2fa3d4fdcb 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -645,6 +645,18 @@ func TestGetConfigDeclaresIssueCreatePropertiesSupport(t *testing.T) {
}
}
+func TestGetConfigDeclaresIssueBatchOpsSupport(t *testing.T) {
+ w := httptest.NewRecorder()
+ testHandler.GetConfig(w, httptest.NewRequest(http.MethodGet, "/api/config", nil))
+ var raw map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {
+ t.Fatalf("decode config: %v", err)
+ }
+ if raw["issue_batch_ops_supported"] != true {
+ t.Fatalf("issue_batch_ops_supported = %v; clients gate dry runs on it", raw["issue_batch_ops_supported"])
+ }
+}
+
// Web/Desktop, mobile and the CLI promise that a delete keeps the replies only
// when the server declares it (#8296). Older servers omit the field and delete
// the replies too, so this build must advertise the contract explicitly.
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 8e42933e70..981078ac2d 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -4798,8 +4798,13 @@ func (h *Handler) publishClearedDuplicates(ctx context.Context, cleared []cleare
// Batch operations
type BatchUpdateIssuesRequest struct {
- IssueIDs []string `json:"issue_ids"`
- Updates UpdateIssueRequest `json:"updates"`
+ IssueIDs []string `json:"issue_ids"`
+ Updates UpdateIssueRequest `json:"updates"`
+ Labels *BatchLabelOps `json:"labels"`
+ Properties *BatchPropertyOps `json:"properties"`
+ // DryRun runs every check and reports the per-issue outcome without
+ // writing anything.
+ DryRun bool `json:"dry_run"`
}
func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
@@ -4846,21 +4851,27 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
// at the top level, "update" misspelled as singular). Telling the truth
// here — `{"updated": 0}` — keeps the wire shape stable while making the
// count match reality. See multica-ai/multica#1660.
- hasMutation := req.Updates.Title != nil ||
+ hasFieldUpdate := req.Updates.Title != nil ||
req.Updates.Description != nil ||
req.Updates.Status != nil ||
req.Updates.Priority != nil ||
req.Updates.Position != nil
- if !hasMutation {
+ if !hasFieldUpdate {
for _, k := range []string{"assignee_type", "assignee_id", "start_date", "due_date", "parent_issue_id", "project_id", "stage"} {
if _, ok := rawUpdates[k]; ok {
- hasMutation = true
+ hasFieldUpdate = true
break
}
}
}
- if !hasMutation {
- writeJSON(w, http.StatusOK, map[string]any{"updated": 0})
+ hasLabelOps := req.Labels != nil && (len(req.Labels.Add) > 0 || len(req.Labels.Remove) > 0 || req.Labels.Clear)
+ hasPropertyOps := req.Properties != nil && (len(req.Properties.Set) > 0 || len(req.Properties.Unset) > 0)
+ if !hasFieldUpdate && !hasLabelOps && !hasPropertyOps {
+ writeJSON(w, http.StatusOK, map[string]any{"updated": 0, "results": []batchIssueResult{}})
+ return
+ }
+ if req.Updates.Description != nil && (hasLabelOps || hasPropertyOps) {
+ writeError(w, http.StatusBadRequest, "a batch update cannot change description together with labels or properties; send them as two requests")
return
}
if req.Updates.Priority != nil {
@@ -4920,8 +4931,24 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
}
batchProjectID = projectUUID
}
+ labelPlan, ok := h.resolveBatchLabelPlan(w, r, wsUUID, req.Labels)
+ if !ok {
+ return
+ }
+ propertyPlan, ok := h.resolveBatchPropertyPlan(w, r, wsUUID, req.Properties)
+ if !ok {
+ return
+ }
updated := 0
+ // Every issue gets one entry, so a caller can tell which issues a short
+ // `updated` count left out and why. (MUL-8882)
+ results := make([]batchIssueResult, 0, len(req.IssueIDs))
+ prefix := h.getIssuePrefix(r.Context(), wsUUID)
+ identifierOf := func(issue db.Issue) string { return prefix + "-" + strconv.Itoa(int(issue.Number)) }
+ skip := func(issueID, identifier, code, message string) {
+ results = append(results, batchIssueResult{IssueID: issueID, Identifier: identifier, Outcome: batchOutcomeSkipped, Code: code, Message: message})
+ }
// One Resolver for the whole batch — a per-issue filler would query the
// catalog once per custom-status row. (MUL-6243)
fillBatch := h.newStatusCategoryFiller(r.Context(), wsUUID, projectaccess.Hidden{})
@@ -4933,18 +4960,27 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ seen := make(map[pgtype.UUID]bool, len(req.IssueIDs))
for _, issueID := range req.IssueIDs {
issueUUID, err := util.ParseUUID(issueID)
if err != nil {
+ skip(issueID, "", "invalid_id", "not a valid issue id")
continue
}
+ if seen[issueUUID] {
+ continue
+ }
+ seen[issueUUID] = true
prevIssue, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{
ID: issueUUID,
WorkspaceID: wsUUID,
})
if err != nil || !hidden.CanSeeProject(prevIssue.ProjectID) {
+ skip(issueID, "", "not_found", "issue not found in this workspace")
continue
}
+ identifier := identifierOf(prevIssue)
+ issueID = uuidToString(prevIssue.ID)
params := db.UpdateIssueParams{
SourceTaskID: h.wakeupSourceTaskID(r),
@@ -4984,6 +5020,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if req.Updates.AssigneeID != nil {
assigneeUUID, err := util.ParseUUID(*req.Updates.AssigneeID)
if err != nil {
+ skip(issueID, identifier, "invalid_value", "assignee_id must be a UUID")
continue
}
params.AssigneeID = assigneeUUID
@@ -4995,6 +5032,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if req.Updates.StartDate != nil && *req.Updates.StartDate != "" {
d, err := util.ParseCalendarDate(*req.Updates.StartDate)
if err != nil {
+ skip(issueID, identifier, "invalid_value", "start_date must be a calendar date (YYYY-MM-DD)")
continue
}
params.StartDate = d
@@ -5006,6 +5044,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if req.Updates.DueDate != nil && *req.Updates.DueDate != "" {
d, err := util.ParseCalendarDate(*req.Updates.DueDate)
if err != nil {
+ skip(issueID, identifier, "invalid_value", "due_date must be a calendar date (YYYY-MM-DD)")
continue
}
params.DueDate = d
@@ -5018,10 +5057,12 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if req.Updates.ParentIssueID != nil {
newParentID, err := util.ParseUUID(*req.Updates.ParentIssueID)
if err != nil {
+ skip(issueID, identifier, "invalid_value", "parent_issue_id must be a UUID")
continue
}
// Cannot set self as parent.
if newParentID == prevIssue.ID {
+ skip(issueID, identifier, "parent_self", "an issue cannot be its own parent")
continue
}
// Validate parent exists in the same workspace.
@@ -5030,6 +5071,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
WorkspaceID: prevIssue.WorkspaceID,
})
if err != nil || !hidden.CanSeeProject(newParent.ProjectID) {
+ skip(issueID, identifier, "parent_not_found", "parent issue not found in this workspace")
continue
}
// Cycle detection: walk up from the new parent to ensure we don't reach this issue.
@@ -5047,6 +5089,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
cursor = ancestor.ParentIssueID
}
if cycleDetected {
+ skip(issueID, identifier, "parent_cycle", fmt.Sprintf("%s is a descendant of this issue, so making it the parent would create a cycle", identifierOf(newParent)))
continue
}
params.ParentIssueID = newParentID
@@ -5061,6 +5104,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if _, ok := rawUpdates["stage"]; ok {
if req.Updates.Stage != nil {
if *req.Updates.Stage < 1 {
+ skip(issueID, identifier, "invalid_value", "stage must be 1 or greater")
continue
}
params.Stage = pgtype.Int4{Int32: *req.Updates.Stage, Valid: true}
@@ -5069,39 +5113,55 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
}
}
- // Validate the resulting assignee pair when this batch update touches
- // either assignee field. Skip the issue silently on failure.
- //
- // Scoped PER ISSUE (prevIssue is this iteration's row), so one bound
- // issue in the batch can never lend its authority to the others: an
- // unbound entry simply fails the check and is skipped. This IS a real
- // agent-reachable authorization point — a task token authenticates as its
- // bound workspace member, so requireUserID above is satisfied and
- // resolveActor still classifies the caller as an agent (MUL-6691).
- _, batchTouchedType := rawUpdates["assignee_type"]
- _, batchTouchedID := rawUpdates["assignee_id"]
- // Project workflow (MUL-7420), per issue: an issue whose workflow does
- // not list the batch status is skipped like the other per-item guards;
- // entering a handoff step reassigns this issue to the step's handler.
- callerType, _ := h.resolveActor(r, userID, workspaceID)
- callerRun := h.agentRunOnIssue(r, callerType, prevIssue)
- handoff, err := h.applyIssueWorkflow(r.Context(), prevIssue, &params, req.Updates.Status != nil, batchTouchedType || batchTouchedID, false, callerRun)
- if err != nil {
- continue
- }
+ var callerRun *db.AgentTaskQueue
+ var handoff *workflowHandoff
issueStatusGuard := batchStatusKey
- if params.Status.Valid {
- issueStatusGuard = params.Status.String
- }
- if batchTouchedType || batchTouchedID || handoff != nil {
- if status, _ := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID); status != 0 {
+ if hasFieldUpdate {
+ // Validate the resulting assignee pair when this batch update touches
+ // either assignee field. Skip the issue on failure.
+ //
+ // Scoped PER ISSUE (prevIssue is this iteration's row), so one bound
+ // issue in the batch can never lend its authority to the others: an
+ // unbound entry simply fails the check and is skipped. This IS a real
+ // agent-reachable authorization point — a task token authenticates as its
+ // bound workspace member, so requireUserID above is satisfied and
+ // resolveActor still classifies the caller as an agent (MUL-6691).
+ _, batchTouchedType := rawUpdates["assignee_type"]
+ _, batchTouchedID := rawUpdates["assignee_id"]
+ // Project workflow (MUL-7420), per issue: an issue whose workflow does
+ // not list the batch status is skipped like the other per-item guards;
+ // entering a handoff step reassigns this issue to the step's handler.
+ callerType, _ := h.resolveActor(r, userID, workspaceID)
+ callerRun = h.agentRunOnIssue(r, callerType, prevIssue)
+ handoff, err = h.applyIssueWorkflow(r.Context(), prevIssue, &params, req.Updates.Status != nil, batchTouchedType || batchTouchedID, false, callerRun)
+ if err != nil {
+ skip(issueID, identifier, "workflow_rejected", err.Error())
continue
}
+ if params.Status.Valid {
+ issueStatusGuard = params.Status.String
+ }
+ if batchTouchedType || batchTouchedID || handoff != nil {
+ if status, msg := h.validateAssigneePair(r.Context(), r, workspaceID, params.AssigneeType, params.AssigneeID); status != 0 {
+ skip(issueID, identifier, "assignee_not_allowed", msg)
+ continue
+ }
+ }
+ }
+
+ if req.DryRun {
+ results = append(results, batchIssueResult{IssueID: issueID, Identifier: identifier, Outcome: batchOutcomeWouldUpdate})
+ continue
}
- writeCtx := withWakeupHandedTo(r.Context(), h.handedToAgent(r.Context(), prevIssue, params, handoff != nil))
+ writeCtx := r.Context()
+ if hasFieldUpdate {
+ writeCtx = withWakeupHandedTo(writeCtx, h.handedToAgent(r.Context(), prevIssue, params, handoff != nil))
+ }
var issue db.Issue
- if req.Updates.Description != nil {
+ labelsChanged, propertiesChanged := false, false
+ switch {
+ case req.Updates.Description != nil:
// One batch-level base cannot describe multiple issue documents.
// Preserve every marked channel-media block conservatively, matching
// legacy single-update clients that omit description_base.
@@ -5112,8 +5172,18 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if err == nil {
prevIssue = lockedPrev
}
- } else {
+ case labelPlan == nil && propertyPlan == nil:
issue, err = h.updateIssueWithStatusGuard(writeCtx, wsUUID, issueStatusGuard, params)
+ default:
+ var fieldParams *db.UpdateIssueParams
+ if hasFieldUpdate {
+ fieldParams = &params
+ } else {
+ issueStatusGuard = ""
+ }
+ var written batchIssueWrite
+ written, err = h.writeBatchIssue(writeCtx, wsUUID, prevIssue, fieldParams, issueStatusGuard, labelPlan, propertyPlan)
+ issue, labelsChanged, propertiesChanged = written.issue, written.labelsChanged, written.propertiesChanged
}
if err != nil {
// The archive race is a property of the batch's shared target
@@ -5122,73 +5192,101 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
if writeIssueStatusRaceError(w, err) {
return
}
+ var skipErr *batchSkipError
+ if errors.As(err, &skipErr) {
+ skip(issueID, identifier, skipErr.code, skipErr.message)
+ continue
+ }
slog.Warn("batch update issue failed", "issue_id", issueID, "error", err)
+ skip(issueID, identifier, "write_failed", "failed to write this issue")
continue
}
- prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)
- resp := issueToResponse(issue, prefix)
actorType, actorID := h.resolveActor(r, userID, workspaceID)
- h.advanceRunStep(r.Context(), callerRun, prevIssue, issue)
-
- fillBatch(&resp)
- assigneeChanged := (req.Updates.AssigneeType != nil || req.Updates.AssigneeID != nil || handoff != nil) &&
- (prevIssue.AssigneeType.String != issue.AssigneeType.String || uuidToString(prevIssue.AssigneeID) != uuidToString(issue.AssigneeID))
- statusChanged := (req.Updates.Status != nil || params.Status.Valid) && prevIssue.Status != issue.Status
- priorityChanged := req.Updates.Priority != nil && prevIssue.Priority != issue.Priority
- projectChanged := req.Updates.ProjectID != nil && uuidToString(prevIssue.ProjectID) != uuidToString(issue.ProjectID)
-
- batchHandoffNote := req.Updates.HandoffNote
- trigger, willRun := h.IssueService.WillEnqueueRun(r.Context(),
- service.IssueTriggerInput{
- Issue: issue,
- PrevStatus: prevIssue.Status,
- AssigneeChanged: assigneeChanged || handoff != nil,
- StatusChanged: statusChanged,
- EnteredHandoffStep: handoff != nil,
- },
- h.issueTriggerWriteProbe(r, actorType, actorID, issue),
- )
- willRun = willRun && !req.Updates.SuppressRun
- batchPayload := map[string]any{
- "issue": resp,
- "assignee_changed": assigneeChanged,
- "status_changed": statusChanged,
- "priority_changed": priorityChanged,
- "project_changed": projectChanged,
- "title_changed": req.Updates.Title != nil && prevIssue.Title != issue.Title,
- "prev_title": prevIssue.Title,
- "parent_changed": prevIssue.ParentIssueID != issue.ParentIssueID,
- "prev_parent_issue_id": uuidToPtr(prevIssue.ParentIssueID),
- "prev_status": prevIssue.Status,
- "duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),
- "prev_duplicate_of_issue_id": liveDuplicateMark(prevIssue.Status, prevIssue.DuplicateOfIssueID),
- }
- if handoff != nil {
- batchPayload["workflow_handoff"] = workflowHandoffPayload(issue, handoff, h.workflowHandoffBrief(r.Context(), issue, handoff), willRun)
- }
- h.publish(protocol.EventIssueUpdated, workspaceID, actorType, actorID, batchPayload)
-
- // Reassignment does not cancel existing tasks (#4963 / MUL-4113) —
- // mirrors UpdateIssue. See that handler for the rationale.
- //
- // Same single predicate as UpdateIssue — batch must not grow its own
- // copy of the enqueue rule (the historical source of four-entry-point
- // drift, MUL-3375). suppress_run applies batch-wide.
- if handoff != nil && req.Updates.StopPreviousAssigneeRuns {
- h.stopPreviousAssigneeRuns(r.Context(), prevIssue, issue, actorType, actorID)
- }
- if willRun {
- h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, batchHandoffNote)
- }
+ if hasFieldUpdate {
+ resp := issueToResponse(issue, prefix)
+ h.advanceRunStep(r.Context(), callerRun, prevIssue, issue)
+
+ fillBatch(&resp)
+ assigneeChanged := (req.Updates.AssigneeType != nil || req.Updates.AssigneeID != nil || handoff != nil) &&
+ (prevIssue.AssigneeType.String != issue.AssigneeType.String || uuidToString(prevIssue.AssigneeID) != uuidToString(issue.AssigneeID))
+ statusChanged := (req.Updates.Status != nil || params.Status.Valid) && prevIssue.Status != issue.Status
+ priorityChanged := req.Updates.Priority != nil && prevIssue.Priority != issue.Priority
+ projectChanged := req.Updates.ProjectID != nil && uuidToString(prevIssue.ProjectID) != uuidToString(issue.ProjectID)
+
+ batchHandoffNote := req.Updates.HandoffNote
+ trigger, willRun := h.IssueService.WillEnqueueRun(r.Context(),
+ service.IssueTriggerInput{
+ Issue: issue,
+ PrevStatus: prevIssue.Status,
+ AssigneeChanged: assigneeChanged || handoff != nil,
+ StatusChanged: statusChanged,
+ EnteredHandoffStep: handoff != nil,
+ },
+ h.issueTriggerWriteProbe(r, actorType, actorID, issue),
+ )
+ willRun = willRun && !req.Updates.SuppressRun
+ batchPayload := map[string]any{
+ "issue": resp,
+ "assignee_changed": assigneeChanged,
+ "status_changed": statusChanged,
+ "priority_changed": priorityChanged,
+ "project_changed": projectChanged,
+ "title_changed": req.Updates.Title != nil && prevIssue.Title != issue.Title,
+ "prev_title": prevIssue.Title,
+ "parent_changed": prevIssue.ParentIssueID != issue.ParentIssueID,
+ "prev_parent_issue_id": uuidToPtr(prevIssue.ParentIssueID),
+ "prev_status": prevIssue.Status,
+ "duplicate_of_issue_id": liveDuplicateMark(issue.Status, issue.DuplicateOfIssueID),
+ "prev_duplicate_of_issue_id": liveDuplicateMark(prevIssue.Status, prevIssue.DuplicateOfIssueID),
+ }
+ if handoff != nil {
+ batchPayload["workflow_handoff"] = workflowHandoffPayload(issue, handoff, h.workflowHandoffBrief(r.Context(), issue, handoff), willRun)
+ }
+ h.publish(protocol.EventIssueUpdated, workspaceID, actorType, actorID, batchPayload)
+
+ // Reassignment does not cancel existing tasks (#4963 / MUL-4113) —
+ // mirrors UpdateIssue. See that handler for the rationale.
+ //
+ // Same single predicate as UpdateIssue — batch must not grow its own
+ // copy of the enqueue rule (the historical source of four-entry-point
+ // drift, MUL-3375). suppress_run applies batch-wide.
+ if handoff != nil && req.Updates.StopPreviousAssigneeRuns {
+ h.stopPreviousAssigneeRuns(r.Context(), prevIssue, issue, actorType, actorID)
+ }
+ if willRun {
+ h.dispatchIssueRun(r.Context(), issue, trigger, actorType, actorID, batchHandoffNote)
+ }
- // No status change — not even → cancelled — cancels active tasks here,
- // mirroring UpdateIssue (MUL-4465). See that handler for the rationale.
+ // No status change — not even → cancelled — cancels active tasks here,
+ // mirroring UpdateIssue (MUL-4465). See that handler for the rationale.
- if statusChanged || prevIssue.ParentIssueID != issue.ParentIssueID || prevIssue.Stage != issue.Stage {
- changedParents = append(changedParents, issue.ParentIssueID, prevIssue.ParentIssueID)
+ if statusChanged || prevIssue.ParentIssueID != issue.ParentIssueID || prevIssue.Stage != issue.Stage {
+ changedParents = append(changedParents, issue.ParentIssueID, prevIssue.ParentIssueID)
+ }
+ }
+ if labelsChanged {
+ if labels, ok := h.listLabelsForIssueSafe(r, issue.ID, issue.WorkspaceID); ok {
+ h.publish(protocol.EventIssueLabelsChanged, workspaceID, actorType, actorID, map[string]any{
+ "issue_id": issueID,
+ "labels": labelsToResponse(labels),
+ "issue_revision": issue.Revision,
+ })
+ }
+ }
+ if propertiesChanged {
+ h.publish(protocol.EventIssuePropertiesChanged, workspaceID, actorType, actorID, map[string]any{
+ "issue_id": issueID,
+ "properties": parseIssueProperties(issue.Properties),
+ "issue_revision": issue.Revision,
+ })
}
+ outcome := batchOutcomeUpdated
+ if issue.Revision == prevIssue.Revision {
+ outcome = batchOutcomeUnchanged
+ }
+ results = append(results, batchIssueResult{IssueID: issueID, Identifier: identifier, Outcome: outcome})
updated++
}
@@ -5198,12 +5296,17 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
// by the sweep.
h.processChildEvents(r.Context(), changedParents...)
- slog.Info("batch update issues", append(logger.RequestAttrs(r), "count", updated)...)
- writeJSON(w, http.StatusOK, map[string]any{"updated": updated})
+ slog.Info("batch update issues", append(logger.RequestAttrs(r), "count", updated, "dry_run", req.DryRun)...)
+ response := map[string]any{"updated": updated, "results": results}
+ if req.DryRun {
+ response["dry_run"] = true
+ }
+ writeJSON(w, http.StatusOK, response)
}
type BatchDeleteIssuesRequest struct {
IssueIDs []string `json:"issue_ids"`
+ DryRun bool `json:"dry_run"`
}
func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {
@@ -5234,30 +5337,47 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ prefix := h.getIssuePrefix(r.Context(), wsUUID)
+ results := make([]batchIssueResult, 0, len(req.IssueIDs))
seenIssueIDs := make(map[pgtype.UUID]struct{}, len(req.IssueIDs))
for _, issueID := range req.IssueIDs {
issueUUID, err := util.ParseUUID(issueID)
if err != nil {
+ results = append(results, batchIssueResult{IssueID: issueID, Outcome: batchOutcomeSkipped, Code: "invalid_id", Message: "not a valid issue id"})
continue
}
if _, duplicate := seenIssueIDs[issueUUID]; duplicate {
continue
}
+ seenIssueIDs[issueUUID] = struct{}{}
issue, err := h.Queries.GetIssueInWorkspace(r.Context(), db.GetIssueInWorkspaceParams{
ID: issueUUID,
WorkspaceID: wsUUID,
})
if err != nil || !hidden.CanSeeProject(issue.ProjectID) {
+ results = append(results, batchIssueResult{IssueID: issueID, Outcome: batchOutcomeSkipped, Code: "not_found", Message: "issue not found"})
continue
}
- seenIssueIDs[issueUUID] = struct{}{}
issues = append(issues, issue)
excludedIDs = append(excludedIDs, issue.ID)
+ outcome := batchOutcomeDeleted
+ if req.DryRun {
+ outcome = batchOutcomeWouldDelete
+ }
+ results = append(results, batchIssueResult{
+ IssueID: uuidToString(issue.ID),
+ Identifier: prefix + "-" + strconv.Itoa(int(issue.Number)),
+ Outcome: outcome,
+ })
}
if !h.requireIssueDeletion(w, r, wsUUID, issues) {
return
}
+ if req.DryRun {
+ writeJSON(w, http.StatusOK, map[string]any{"deleted": 0, "results": results, "dry_run": true})
+ return
+ }
for _, issue := range issues {
h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)
_ = h.AutopilotService.FailAutopilotRunsByIssue(r.Context(), issue.ID)
@@ -5278,5 +5398,5 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {
deleted := len(issues)
slog.Info("batch delete issues", append(logger.RequestAttrs(r), "count", deleted)...)
- writeJSON(w, http.StatusOK, map[string]any{"deleted": deleted})
+ writeJSON(w, http.StatusOK, map[string]any{"deleted": deleted, "results": results})
}
diff --git a/server/internal/handler/issue_batch.go b/server/internal/handler/issue_batch.go
new file mode 100644
index 0000000000..74f6a4ec40
--- /dev/null
+++ b/server/internal/handler/issue_batch.go
@@ -0,0 +1,392 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "sort"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/logger"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Label and property changes carried by a batch update (MUL-8882). They are
+// operations, not replacement values: add and remove leave every other label
+// on the issue alone, and clear + add is how a caller replaces the set.
+type BatchLabelOps struct {
+ Add []string `json:"add"`
+ Remove []string `json:"remove"`
+ Clear bool `json:"clear"`
+}
+
+type BatchPropertyOps struct {
+ Set map[string]json.RawMessage `json:"set"`
+ Unset []string `json:"unset"`
+}
+
+// maxBatchFieldOps bounds the label and property operations one request may
+// carry; each one is a write per selected issue.
+const maxBatchFieldOps = 50
+
+// Per-issue outcomes of a batch update. `updated` in the response counts
+// both written outcomes, so a client that predates `results` keeps reading a
+// value-already-set issue as a success.
+const (
+ batchOutcomeUpdated = "updated"
+ batchOutcomeUnchanged = "unchanged"
+ batchOutcomeSkipped = "skipped"
+ batchOutcomeWouldUpdate = "would_update"
+ batchOutcomeDeleted = "deleted"
+ batchOutcomeWouldDelete = "would_delete"
+)
+
+type batchIssueResult struct {
+ IssueID string `json:"issue_id"`
+ Identifier string `json:"identifier,omitempty"`
+ Outcome string `json:"outcome"`
+ Code string `json:"code,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+// batchSkipError ends one issue's write with a reason the caller can act on,
+// rolling back everything written for that issue.
+type batchSkipError struct {
+ code string
+ message string
+}
+
+func (e *batchSkipError) Error() string { return e.message }
+
+type batchLabelPlan struct {
+ add []pgtype.UUID
+ remove []pgtype.UUID
+ clear bool
+}
+
+type batchPropertySet struct {
+ id pgtype.UUID
+ raw json.RawMessage
+}
+
+type batchPropertyPlan struct {
+ set []batchPropertySet
+ unset []pgtype.UUID
+ // Advisory lock keys of the properties written, sorted so two batches
+ // over overlapping properties take them in the same order.
+ lockKeys []string
+}
+
+// resolveBatchLabelPlan validates the label operations once for the whole
+// batch. A label that does not exist invalidates the request rather than
+// skipping every issue one by one.
+func (h *Handler) resolveBatchLabelPlan(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, ops *BatchLabelOps) (*batchLabelPlan, bool) {
+ if ops == nil || (len(ops.Add) == 0 && len(ops.Remove) == 0 && !ops.Clear) {
+ return nil, true
+ }
+ if len(ops.Add)+len(ops.Remove) > maxBatchFieldOps {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("at most %d label operations per batch update", maxBatchFieldOps))
+ return nil, false
+ }
+ plan := &batchLabelPlan{clear: ops.Clear}
+ seen := make(map[pgtype.UUID]bool, len(ops.Add)+len(ops.Remove))
+ resolve := func(raw string, adding bool) (pgtype.UUID, bool, bool) {
+ id, err := util.ParseUUID(raw)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("label id %q must be a UUID", raw))
+ return id, false, false
+ }
+ if wasAdd, dup := seen[id]; dup {
+ if wasAdd != adding {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("label %s cannot be both added and removed", raw))
+ return id, false, false
+ }
+ return id, false, true
+ }
+ label, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{ID: id, WorkspaceID: workspaceID})
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("label %s not found in this workspace", raw))
+ return id, false, false
+ }
+ slog.Warn("batch update issues: load label", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to validate labels")
+ return id, false, false
+ }
+ if label.ResourceType != "issue" {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("label %s is not an issue label", raw))
+ return id, false, false
+ }
+ seen[id] = adding
+ return id, true, true
+ }
+ for _, raw := range ops.Add {
+ id, fresh, ok := resolve(raw, true)
+ if !ok {
+ return nil, false
+ }
+ if fresh {
+ plan.add = append(plan.add, id)
+ }
+ }
+ for _, raw := range ops.Remove {
+ id, fresh, ok := resolve(raw, false)
+ if !ok {
+ return nil, false
+ }
+ if fresh {
+ plan.remove = append(plan.remove, id)
+ }
+ }
+ return plan, true
+}
+
+// resolveBatchPropertyPlan validates property definitions and values once for
+// the whole batch, with the same rules as SetIssueProperty. The write re-checks
+// each definition under its lock, since it can change between here and there.
+func (h *Handler) resolveBatchPropertyPlan(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, ops *BatchPropertyOps) (*batchPropertyPlan, bool) {
+ if ops == nil || (len(ops.Set) == 0 && len(ops.Unset) == 0) {
+ return nil, true
+ }
+ if len(ops.Set)+len(ops.Unset) > maxBatchFieldOps {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("at most %d property operations per batch update", maxBatchFieldOps))
+ return nil, false
+ }
+ load := func(raw string) (db.IssueProperty, bool) {
+ id, err := util.ParseUUID(raw)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("property id %q must be a UUID", raw))
+ return db.IssueProperty{}, false
+ }
+ def, err := h.Queries.GetIssueProperty(r.Context(), db.GetIssuePropertyParams{ID: id, WorkspaceID: workspaceID})
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("property %s not found in this workspace", raw))
+ return def, false
+ }
+ slog.Warn("batch update issues: load property", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to validate properties")
+ return def, false
+ }
+ return def, true
+ }
+
+ plan := &batchPropertyPlan{}
+ setIDs := make(map[pgtype.UUID]bool, len(ops.Set))
+ rawIDs := make([]string, 0, len(ops.Set))
+ for raw := range ops.Set {
+ rawIDs = append(rawIDs, raw)
+ }
+ sort.Strings(rawIDs)
+ for _, raw := range rawIDs {
+ def, ok := load(raw)
+ if !ok {
+ return nil, false
+ }
+ if setIDs[def.ID] {
+ continue
+ }
+ if def.ArchivedAt.Valid {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("property %q is archived and cannot receive new values", def.Name))
+ return nil, false
+ }
+ value, err := validatePropertyValue(def, ops.Set[raw])
+ if err != nil {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("property %q: %s", def.Name, err.Error()))
+ return nil, false
+ }
+ if propertyTypeIsActor(def.Type) {
+ refs, err := actorRefsInValue(def.Type, value)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return nil, false
+ }
+ if status, msg := h.resolveActorRefs(r, uuidToString(workspaceID), refs); status != 0 {
+ writeError(w, status, msg)
+ return nil, false
+ }
+ }
+ setIDs[def.ID] = true
+ plan.set = append(plan.set, batchPropertySet{id: def.ID, raw: ops.Set[raw]})
+ plan.lockKeys = append(plan.lockKeys, "prop:"+uuidToString(def.ID))
+ }
+ unsetIDs := make(map[pgtype.UUID]bool, len(ops.Unset))
+ for _, raw := range ops.Unset {
+ // Unsetting stays allowed on an archived definition: cleanup must never
+ // be blocked, as in DeleteIssueProperty.
+ def, ok := load(raw)
+ if !ok {
+ return nil, false
+ }
+ if setIDs[def.ID] {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("property %q cannot be both set and unset", def.Name))
+ return nil, false
+ }
+ if unsetIDs[def.ID] {
+ continue
+ }
+ unsetIDs[def.ID] = true
+ plan.unset = append(plan.unset, def.ID)
+ }
+ sort.Strings(plan.lockKeys)
+ return plan, true
+}
+
+type batchIssueWrite struct {
+ issue db.Issue
+ labelsChanged bool
+ propertiesChanged bool
+}
+
+// writeBatchIssue applies one issue's field update, label operations and
+// property operations in a single transaction, so an issue is either written
+// in full or skipped in full. params is nil when the batch changes no field.
+func (h *Handler) writeBatchIssue(ctx context.Context, workspaceID pgtype.UUID, prev db.Issue, params *db.UpdateIssueParams, statusKey string, labels *batchLabelPlan, properties *batchPropertyPlan) (batchIssueWrite, error) {
+ out := batchIssueWrite{issue: prev}
+ tx, err := h.beginWakeupWrite(ctx)
+ if err != nil {
+ return out, err
+ }
+ defer tx.Rollback(ctx)
+ q := h.Queries.WithTx(tx)
+
+ // Property locks first, then the status catalog lock, then row locks —
+ // the order SetIssueProperty and the status guard each take theirs in.
+ if properties != nil {
+ for _, key := range properties.lockKeys {
+ if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", key); err != nil {
+ return out, err
+ }
+ }
+ }
+ if err := assertIssueStatusStillActive(ctx, q, workspaceID, statusKey); err != nil {
+ return out, err
+ }
+
+ var cancelled []db.AgentTaskQueue
+ if params != nil {
+ out.issue, cancelled, err = updateIssueStoppingWakeups(ctx, q, *params)
+ if err != nil {
+ return out, err
+ }
+ }
+ if labels != nil {
+ if out.labelsChanged, err = applyBatchLabelPlan(ctx, q, prev, labels); err != nil {
+ return out, err
+ }
+ }
+ if properties != nil {
+ if out.propertiesChanged, err = applyBatchPropertyPlan(ctx, q, prev, properties); err != nil {
+ return out, err
+ }
+ }
+ if out.labelsChanged || out.propertiesChanged {
+ if out.issue, err = q.GetIssue(ctx, prev.ID); err != nil {
+ return out, err
+ }
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return out, err
+ }
+ h.broadcastCancelledWakeups(ctx, workspaceID, cancelled)
+ return out, nil
+}
+
+func applyBatchLabelPlan(ctx context.Context, q *db.Queries, issue db.Issue, plan *batchLabelPlan) (bool, error) {
+ remove := plan.remove
+ if plan.clear {
+ current, err := q.ListLabelsByIssue(ctx, db.ListLabelsByIssueParams{IssueID: issue.ID, WorkspaceID: issue.WorkspaceID})
+ if err != nil {
+ return false, err
+ }
+ keep := make(map[pgtype.UUID]bool, len(plan.add))
+ for _, id := range plan.add {
+ keep[id] = true
+ }
+ remove = nil
+ for _, label := range current {
+ if !keep[label.ID] {
+ remove = append(remove, label.ID)
+ }
+ }
+ }
+ changed := false
+ for _, id := range remove {
+ row, err := q.DetachLabelFromIssue(ctx, db.DetachLabelFromIssueParams{IssueID: issue.ID, LabelID: id, WorkspaceID: issue.WorkspaceID})
+ if err != nil {
+ return false, err
+ }
+ changed = changed || row.Changed
+ }
+ for _, id := range plan.add {
+ row, err := q.AttachLabelToIssue(ctx, db.AttachLabelToIssueParams{IssueID: issue.ID, LabelID: id, WorkspaceID: issue.WorkspaceID})
+ if err != nil {
+ return false, err
+ }
+ changed = changed || row.Changed
+ }
+ return changed, nil
+}
+
+func applyBatchPropertyPlan(ctx context.Context, q *db.Queries, issue db.Issue, plan *batchPropertyPlan) (bool, error) {
+ // Value writes bump the revision only when the stored value changes.
+ current, err := q.GetIssue(ctx, issue.ID)
+ if err != nil {
+ return false, err
+ }
+ revision := current.Revision
+ changed := false
+ note := func(updated db.Issue) {
+ if updated.Revision != revision {
+ changed = true
+ }
+ revision = updated.Revision
+ }
+
+ for _, s := range plan.set {
+ def, err := q.GetIssueProperty(ctx, db.GetIssuePropertyParams{ID: s.id, WorkspaceID: issue.WorkspaceID})
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return false, &batchSkipError{code: "invalid_value", message: "the property was deleted while this request was in flight"}
+ }
+ return false, err
+ }
+ if def.ArchivedAt.Valid {
+ return false, &batchSkipError{code: "invalid_value", message: fmt.Sprintf("property %q was archived while this request was in flight", def.Name)}
+ }
+ value, err := validatePropertyValue(def, s.raw)
+ if err != nil {
+ return false, &batchSkipError{code: "invalid_value", message: fmt.Sprintf("property %q: %s", def.Name, err.Error())}
+ }
+ updated, err := q.SetIssuePropertyValue(ctx, db.SetIssuePropertyValueParams{
+ ID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ Key: uuidToString(def.ID),
+ Value: value,
+ })
+ if err != nil {
+ if isCheckViolation(err) {
+ return false, &batchSkipError{code: "properties_too_large", message: "issue properties would exceed the 16KB size limit"}
+ }
+ return false, err
+ }
+ note(updated)
+ }
+ for _, id := range plan.unset {
+ updated, err := q.DeleteIssuePropertyValue(ctx, db.DeleteIssuePropertyValueParams{
+ ID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ Key: uuidToString(id),
+ })
+ if err != nil {
+ return false, err
+ }
+ note(updated)
+ }
+ return changed, nil
+}
diff --git a/server/internal/handler/issue_batch_ops_test.go b/server/internal/handler/issue_batch_ops_test.go
new file mode 100644
index 0000000000..7d4217124d
--- /dev/null
+++ b/server/internal/handler/issue_batch_ops_test.go
@@ -0,0 +1,353 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+type batchUpdateTestResponse struct {
+ Updated int `json:"updated"`
+ DryRun bool `json:"dry_run"`
+ Results []batchIssueResult `json:"results"`
+}
+
+func batchUpdate(t *testing.T, body map[string]any) (int, batchUpdateTestResponse, string) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ testHandler.BatchUpdateIssues(w, newRequest("POST", "/api/issues/batch-update", body))
+ var resp batchUpdateTestResponse
+ raw := w.Body.String()
+ if w.Code == http.StatusOK {
+ if err := json.Unmarshal([]byte(raw), &resp); err != nil {
+ t.Fatalf("decode batch response: %v (%s)", err, raw)
+ }
+ }
+ return w.Code, resp, raw
+}
+
+func resultFor(t *testing.T, resp batchUpdateTestResponse, issueID string) batchIssueResult {
+ t.Helper()
+ for _, r := range resp.Results {
+ if r.IssueID == issueID {
+ return r
+ }
+ }
+ t.Fatalf("no result for issue %s in %+v", issueID, resp.Results)
+ return batchIssueResult{}
+}
+
+func issueLabelSet(t *testing.T, issueID string) map[string]bool {
+ t.Helper()
+ rows, err := testPool.Query(context.Background(), `SELECT label_id::text FROM issue_to_label WHERE issue_id = $1`, issueID)
+ if err != nil {
+ t.Fatalf("list issue labels: %v", err)
+ }
+ defer rows.Close()
+ set := map[string]bool{}
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ t.Fatalf("scan label: %v", err)
+ }
+ set[id] = true
+ }
+ return set
+}
+
+func issuePropertyValue(t *testing.T, issueID, propertyID string) (string, bool) {
+ t.Helper()
+ var value *string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT properties ->> $2 FROM issue WHERE id = $1`, issueID, propertyID,
+ ).Scan(&value); err != nil {
+ t.Fatalf("read property: %v", err)
+ }
+ if value == nil {
+ return "", false
+ }
+ return *value, true
+}
+
+func setIssueParent(t *testing.T, issueID, parentID string) {
+ t.Helper()
+ code, resp, raw := batchUpdate(t, map[string]any{
+ "issue_ids": []string{issueID},
+ "updates": map[string]any{"parent_issue_id": parentID},
+ })
+ if code != http.StatusOK || resp.Updated != 1 {
+ t.Fatalf("set parent: %d %s", code, raw)
+ }
+}
+
+// A batch that cannot apply to every issue reports, per issue, which ones it
+// skipped and why, instead of only a short count. (MUL-8882)
+func TestBatchUpdateReportsSkippedIssues(t *testing.T) {
+ root := createTestIssue(t, "BU-skip root", "todo", "low")
+ child := createTestIssue(t, "BU-skip child", "todo", "low")
+ other := createTestIssue(t, "BU-skip other", "todo", "low")
+ for _, id := range []string{child, other, root} {
+ id := id
+ t.Cleanup(func() { deleteTestIssue(t, id) })
+ }
+ setIssueParent(t, child, root)
+
+ missing := uuid.NewString()
+ code, resp, raw := batchUpdate(t, map[string]any{
+ "issue_ids": []string{root, child, other, "not-a-uuid", missing, other},
+ "updates": map[string]any{"parent_issue_id": child},
+ })
+ if code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", code, raw)
+ }
+ if resp.Updated != 1 {
+ t.Fatalf("expected updated=1, got %d: %s", resp.Updated, raw)
+ }
+ // The repeated id is reported once.
+ if len(resp.Results) != 5 {
+ t.Fatalf("expected 5 results, got %d: %s", len(resp.Results), raw)
+ }
+ want := map[string]string{root: "parent_cycle", child: "parent_self", "not-a-uuid": "invalid_id", missing: "not_found"}
+ for id, code := range want {
+ got := resultFor(t, resp, id)
+ if got.Outcome != batchOutcomeSkipped || got.Code != code || got.Message == "" {
+ t.Errorf("issue %s: want skipped/%s with a message, got %+v", id, code, got)
+ }
+ }
+ if got := resultFor(t, resp, other); got.Outcome != batchOutcomeUpdated || got.Identifier == "" {
+ t.Errorf("other: want updated with identifier, got %+v", got)
+ }
+}
+
+func TestBatchUpdateLabelOperations(t *testing.T) {
+ a := createTestIssue(t, "BU-labels A", "todo", "low")
+ b := createTestIssue(t, "BU-labels B", "todo", "low")
+ t.Cleanup(func() { deleteTestIssue(t, a) })
+ t.Cleanup(func() { deleteTestIssue(t, b) })
+ suffix := uuid.NewString()[:8]
+ keep := createTestIssueLabel(t, "bu-keep-"+suffix)
+ drop := createTestIssueLabel(t, "bu-drop-"+suffix)
+ add := createTestIssueLabel(t, "bu-add-"+suffix)
+
+ code, _, raw := batchUpdate(t, map[string]any{
+ "issue_ids": []string{a},
+ "labels": map[string]any{"add": []string{keep, drop}},
+ })
+ if code != http.StatusOK {
+ t.Fatalf("seed labels: %d %s", code, raw)
+ }
+
+ // Add and remove leave every other label alone.
+ code, resp, raw := batchUpdate(t, map[string]any{
+ "issue_ids": []string{a, b},
+ "labels": map[string]any{"add": []string{add}, "remove": []string{drop}},
+ })
+ if code != http.StatusOK || resp.Updated != 2 {
+ t.Fatalf("add/remove: %d %s", code, raw)
+ }
+ if got := issueLabelSet(t, a); !got[keep] || !got[add] || got[drop] || len(got) != 2 {
+ t.Errorf("issue A labels after add/remove: %v", got)
+ }
+ if got := issueLabelSet(t, b); !got[add] || len(got) != 1 {
+ t.Errorf("issue B labels after add/remove: %v", got)
+ }
+
+ // Repeating the same operation changes nothing and says so.
+ _, resp, raw = batchUpdate(t, map[string]any{
+ "issue_ids": []string{a},
+ "labels": map[string]any{"add": []string{add}},
+ })
+ if got := resultFor(t, resp, a); got.Outcome != batchOutcomeUnchanged || resp.Updated != 1 {
+ t.Errorf("repeat add: want unchanged and counted, got %+v (%s)", got, raw)
+ }
+
+ // clear + add replaces the set.
+ code, _, raw = batchUpdate(t, map[string]any{
+ "issue_ids": []string{a, b},
+ "labels": map[string]any{"clear": true, "add": []string{drop}},
+ })
+ if code != http.StatusOK {
+ t.Fatalf("clear+add: %d %s", code, raw)
+ }
+ for _, id := range []string{a, b} {
+ if got := issueLabelSet(t, id); !got[drop] || len(got) != 1 {
+ t.Errorf("issue %s labels after clear+add: %v", id, got)
+ }
+ }
+}
+
+func TestBatchUpdatePropertyOperations(t *testing.T) {
+ a := createTestIssue(t, "BU-props A", "todo", "low")
+ b := createTestIssue(t, "BU-props B", "todo", "low")
+ t.Cleanup(func() { deleteTestIssue(t, a) })
+ t.Cleanup(func() { deleteTestIssue(t, b) })
+ prop := createTestProperty(t, map[string]any{"name": "BU Notes " + uuid.NewString()[:8], "type": "text"})
+
+ code, resp, raw := batchUpdate(t, map[string]any{
+ "issue_ids": []string{a, b},
+ "properties": map[string]any{"set": map[string]any{prop.ID: "needs repro"}},
+ })
+ if code != http.StatusOK || resp.Updated != 2 {
+ t.Fatalf("set: %d %s", code, raw)
+ }
+ for _, id := range []string{a, b} {
+ if got, ok := issuePropertyValue(t, id, prop.ID); !ok || got != "needs repro" {
+ t.Errorf("issue %s: property = %q, %v", id, got, ok)
+ }
+ }
+
+ code, _, raw = batchUpdate(t, map[string]any{
+ "issue_ids": []string{a},
+ "properties": map[string]any{"unset": []string{prop.ID}},
+ })
+ if code != http.StatusOK {
+ t.Fatalf("unset: %d %s", code, raw)
+ }
+ if _, ok := issuePropertyValue(t, a, prop.ID); ok {
+ t.Errorf("issue A: property still set after unset")
+ }
+ if _, ok := issuePropertyValue(t, b, prop.ID); !ok {
+ t.Errorf("issue B: property cleared although it was not selected")
+ }
+}
+
+// Fields, labels and properties of one issue land together in one write.
+func TestBatchUpdateFieldsLabelsAndPropertiesTogether(t *testing.T) {
+ a := createTestIssue(t, "BU-combined A", "todo", "low")
+ t.Cleanup(func() { deleteTestIssue(t, a) })
+ label := createTestIssueLabel(t, "bu-combined-"+uuid.NewString()[:8])
+ prop := createTestProperty(t, map[string]any{"name": "BU Combined " + uuid.NewString()[:8], "type": "text"})
+
+ code, resp, raw := batchUpdate(t, map[string]any{
+ "issue_ids": []string{a},
+ "updates": map[string]any{"priority": "high"},
+ "labels": map[string]any{"add": []string{label}},
+ "properties": map[string]any{"set": map[string]any{prop.ID: "x"}},
+ })
+ if code != http.StatusOK || resultFor(t, resp, a).Outcome != batchOutcomeUpdated {
+ t.Fatalf("combined: %d %s", code, raw)
+ }
+ var priority string
+ testPool.QueryRow(context.Background(), `SELECT priority FROM issue WHERE id = $1`, a).Scan(&priority)
+ if priority != "high" {
+ t.Errorf("priority = %q", priority)
+ }
+ if !issueLabelSet(t, a)[label] {
+ t.Errorf("label not attached")
+ }
+ if v, ok := issuePropertyValue(t, a, prop.ID); !ok || v != "x" {
+ t.Errorf("property = %q, %v", v, ok)
+ }
+}
+
+func TestBatchUpdateDryRunWritesNothing(t *testing.T) {
+ a := createTestIssue(t, "BU-dry A", "todo", "low")
+ t.Cleanup(func() { deleteTestIssue(t, a) })
+ label := createTestIssueLabel(t, "bu-dry-"+uuid.NewString()[:8])
+
+ code, resp, raw := batchUpdate(t, map[string]any{
+ "issue_ids": []string{a},
+ "updates": map[string]any{"status": "in_progress", "parent_issue_id": a},
+ "dry_run": true,
+ })
+ if code != http.StatusOK || !resp.DryRun || resp.Updated != 0 {
+ t.Fatalf("dry run: %d %s", code, raw)
+ }
+ if got := resultFor(t, resp, a); got.Code != "parent_self" {
+ t.Errorf("dry run should still report the skip, got %+v", got)
+ }
+
+ _, resp, raw = batchUpdate(t, map[string]any{
+ "issue_ids": []string{a},
+ "updates": map[string]any{"status": "in_progress"},
+ "labels": map[string]any{"add": []string{label}},
+ "dry_run": true,
+ })
+ if got := resultFor(t, resp, a); got.Outcome != batchOutcomeWouldUpdate {
+ t.Errorf("dry run outcome: %+v (%s)", got, raw)
+ }
+ var status string
+ testPool.QueryRow(context.Background(), `SELECT status FROM issue WHERE id = $1`, a).Scan(&status)
+ if status != "todo" || len(issueLabelSet(t, a)) != 0 {
+ t.Errorf("dry run wrote: status=%q labels=%v", status, issueLabelSet(t, a))
+ }
+}
+
+func TestBatchDeleteReportsResultsAndDryRun(t *testing.T) {
+ a := createTestIssue(t, "BD-results A", "todo", "low")
+ t.Cleanup(func() { deleteTestIssue(t, a) })
+ missing := uuid.NewString()
+
+ run := func(dryRun bool) (int, batchUpdateTestResponse, string) {
+ w := httptest.NewRecorder()
+ testHandler.BatchDeleteIssues(w, newRequest("POST", "/api/issues/batch-delete", map[string]any{
+ "issue_ids": []string{a, missing}, "dry_run": dryRun,
+ }))
+ var resp batchUpdateTestResponse
+ json.Unmarshal(w.Body.Bytes(), &resp)
+ return w.Code, resp, w.Body.String()
+ }
+
+ code, resp, raw := run(true)
+ if code != http.StatusOK || !resp.DryRun {
+ t.Fatalf("dry run: %d %s", code, raw)
+ }
+ if got := resultFor(t, resp, a); got.Outcome != batchOutcomeWouldDelete {
+ t.Errorf("dry run outcome: %+v", got)
+ }
+ if got := resultFor(t, resp, missing); got.Code != "not_found" {
+ t.Errorf("missing issue: %+v", got)
+ }
+ var n int
+ testPool.QueryRow(context.Background(), `SELECT COUNT(*) FROM issue WHERE id = $1`, a).Scan(&n)
+ if n != 1 {
+ t.Fatalf("dry run deleted the issue")
+ }
+
+ code, resp, raw = run(false)
+ if code != http.StatusOK {
+ t.Fatalf("delete: %d %s", code, raw)
+ }
+ if got := resultFor(t, resp, a); got.Outcome != batchOutcomeDeleted {
+ t.Errorf("delete outcome: %+v", got)
+ }
+ testPool.QueryRow(context.Background(), `SELECT COUNT(*) FROM issue WHERE id = $1`, a).Scan(&n)
+ if n != 0 {
+ t.Errorf("issue still exists after delete")
+ }
+}
+
+// Problems shared by every issue reject the whole request up front.
+func TestBatchUpdateRejectsInvalidLabelAndPropertyOps(t *testing.T) {
+ a := createTestIssue(t, "BU-invalid A", "todo", "low")
+ t.Cleanup(func() { deleteTestIssue(t, a) })
+ label := createTestIssueLabel(t, "bu-invalid-"+uuid.NewString()[:8])
+ prop := createTestProperty(t, map[string]any{"name": "BU Number " + uuid.NewString()[:8], "type": "number"})
+
+ cases := []struct {
+ name string
+ body map[string]any
+ }{
+ {"unknown label", map[string]any{"labels": map[string]any{"add": []string{uuid.NewString()}}}},
+ {"label added and removed", map[string]any{"labels": map[string]any{"add": []string{label}, "remove": []string{label}}}},
+ {"unknown property", map[string]any{"properties": map[string]any{"set": map[string]any{uuid.NewString(): "x"}}}},
+ {"invalid property value", map[string]any{"properties": map[string]any{"set": map[string]any{prop.ID: "not a number"}}}},
+ {"property set and unset", map[string]any{"properties": map[string]any{"set": map[string]any{prop.ID: 3}, "unset": []string{prop.ID}}}},
+ {"description with labels", map[string]any{"updates": map[string]any{"description": "x"}, "labels": map[string]any{"add": []string{label}}}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ tc.body["issue_ids"] = []string{a}
+ if code, _, raw := batchUpdate(t, tc.body); code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d: %s", code, raw)
+ }
+ if got := issueLabelSet(t, a); len(got) != 0 {
+ t.Errorf("rejected request wrote labels: %v", got)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/source_context_integration_test.go b/server/internal/handler/source_context_integration_test.go
index f08bf08a1e..14567cd489 100644
--- a/server/internal/handler/source_context_integration_test.go
+++ b/server/internal/handler/source_context_integration_test.go
@@ -749,8 +749,10 @@ func TestBatchDeleteParentAndChildPublishesOnlySurvivingDetach(t *testing.T) {
if recorder.Code != http.StatusOK {
t.Fatalf("batch delete = %d: %s", recorder.Code, recorder.Body.String())
}
- var response map[string]int
- if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response["deleted"] != 2 {
+ var response struct {
+ Deleted int `json:"deleted"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Deleted != 2 {
t.Fatalf("batch delete response = %#v, err=%v", response, err)
}
grandchild, err := testHandler.Queries.GetIssue(ctx, util.MustParseUUID(grandchildID))
diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.md
index 54ba5d5c55..912afe4288 100644
--- a/server/internal/service/builtin_skills/multica-platform/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md
@@ -1,6 +1,6 @@
---
name: multica-platform
-description: "Use for Multica platform actions the runtime brief does not fully cover: issue and PR contracts, sub-issues, saved views, charts and files in comments, mentions, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes. Not for the product code you are working on."
+description: "Use for Multica actions the runtime brief does not fully cover: issue and PR contracts, sub-issues, batch changes, saved views, charts and files in comments, mentions, agents, squads, autopilots, projects, runtimes, local environments, skill import, themes. Not for product code you are working on."
user-invocable: false
allowed-tools: Bash(multica *), Bash(git *), Bash(gh *)
---
@@ -20,6 +20,7 @@ Read the invariants below, then open the reference(s) your task actually needs
| Open | When the task is about |
|---|---|
| `references/issues.md` | Issues: PR linking, reading a linked PR's state, saved views (reading, creating, changing), custom properties, status side effects, who else is running, wakeups (events, conditions, timers, check-ins), charts vs attached files in a comment |
+| `references/batch-changes.md` | Changing many issues at once (`issue batch update`, `issue delete <id>... --dry-run`): label and property operations, per-issue results, dry runs |
| `references/sub-issues.md` | Sub-issues: whether to split an issue at all, `todo` vs `backlog` children, serial chains, stages and the parent wakeups they drive |
| `references/mentions.md` | Writing a `mention://` link: which types enqueue a run, which are inert, why one silently did nothing; steering another agent's running turn (`comment add --steer`) |
| `references/agents.md` | Creating, copying or debugging an agent definition: fields, secrets, MCP config, skill binding |
diff --git a/server/internal/service/builtin_skills/multica-platform/references/batch-changes.md b/server/internal/service/builtin_skills/multica-platform/references/batch-changes.md
new file mode 100644
index 0000000000..b4c4ad50a9
--- /dev/null
+++ b/server/internal/service/builtin_skills/multica-platform/references/batch-changes.md
@@ -0,0 +1,29 @@
+# Batch changes
+
+One change applied to many issues, with a result for each issue.
+
+`multica issue batch update` applies one change to many issues. It takes the
+same field flags as `issue update` (status, priority, assignee, project,
+dates, parent, stage) plus label and property operations, and ids as
+arguments or one per line with `--ids-stdin`:
+
+```bash
+multica issue batch update MUL-12 MUL-13 MUL-14 --status in_review --add-label QA
+multica issue batch update MUL-12 MUL-13 --clear-labels --add-label Backend # replace labels
+multica issue batch update MUL-12 MUL-13 --property "Severity=High" --unset-property Reviewer
+multica issue list --status todo --output json --fields identifier | jq -r '.issues[].identifier' \
+ | multica issue batch update --ids-stdin --priority high --dry-run
+```
+
+- Each issue is written on its own and gets a row: updated, unchanged
+ (already matched), or skipped with a reason (for example `parent_cycle`,
+ `workflow_rejected`, `assignee_not_allowed`). The command exits non-zero when
+ any issue was skipped, after printing every row; fix those issues and rerun
+ only them.
+- `--add-label` / `--remove-label` leave other labels alone; `--clear-labels`
+ removes every label first. Multi-value properties are set or unset as a whole.
+- `--dry-run` runs every check and prints the same rows without writing.
+ `multica issue delete <id>... --dry-run` does the same for deletion.
+- A batch status or assignee change has the same side effects as a single
+ one, issue by issue; add `--no-start` to change ownership without starting
+ agent runs.
diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.go
index 71b0e60aff..e34539765a 100644
--- a/server/internal/service/builtin_skills_test.go
+++ b/server/internal/service/builtin_skills_test.go
@@ -352,17 +352,18 @@ func TestPlatformSkillDescriptionNamesEveryDomain(t *testing.T) {
// These are task nouns, not section headings: a task arrives as "set up an
// autopilot", never as "Core model".
triggerWords := map[string]string{
- "references/issues.md": "issue",
- "references/sub-issues.md": "sub-issue",
- "references/mentions.md": "mention",
- "references/agents.md": "agent",
- "references/squads.md": "squad",
- "references/autopilots.md": "autopilot",
- "references/projects.md": "project",
- "references/runtimes.md": "runtime",
- "references/environments.md": "local environment",
- "references/skill-import.md": "skill import",
- "references/themes.md": "theme",
+ "references/issues.md": "issue",
+ "references/sub-issues.md": "sub-issue",
+ "references/batch-changes.md": "batch",
+ "references/mentions.md": "mention",
+ "references/agents.md": "agent",
+ "references/squads.md": "squad",
+ "references/autopilots.md": "autopilot",
+ "references/projects.md": "project",
+ "references/runtimes.md": "runtime",
+ "references/environments.md": "local environment",
+ "references/skill-import.md": "skill import",
+ "references/themes.md": "theme",
}
skill, ok := findSkill(t, PlatformSkillName)