The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): replace native browser dialogs with in-app ConfirmDialog
David Metcalfe08f32a63351f
diff --git a/plugins/kanban/dashboard/dist/index.js b/plugins/kanban/dashboard/dist/index.jsindex f15850f7349..dc582a76602 100644--- a/plugins/kanban/dashboard/dist/index.js+++ b/plugins/kanban/dashboard/dist/index.js@@ -116,6 +116,13 @@archived: "Archive this task? It disappears from the default board view.",blocked: "Mark this task as blocked? The worker's claim is released.",};+ // Pluralized variants used by getDestructiveConfirm() when count > 1.+ // Each entry may use {n} as a placeholder for the count.+ const FALLBACK_DESTRUCTIVE_MANY = {+ done: "Mark {n} tasks as done? The workers' claims are released and dependent children become ready.",+ archived: "Archive {n} tasks? They disappear from the default board view.",+ blocked: "Mark {n} tasks as blocked? The workers' claims are released.",+ };const FALLBACK_DIAGNOSTIC_EVENT_LABELS = {completion_blocked_hallucination: "⚠ Completion blocked — phantom card ids",suspected_hallucinated_references: "⚠ Prose referenced phantom card ids",@@ -142,9 +149,18 @@function getColumnHelp(t, status) {return tx(t, "columnHelp." + status, FALLBACK_COLUMN_HELP[status] || "");}- function getDestructiveConfirm(t, status) {+ function getDestructiveConfirm(t, status, count) {const key = DESTRUCTIVE_KEYS[status];if (!key) return null;+ // For bulk operations, use the *Many variant of the i18n key so the+ // copy pluralizes correctly ("Mark 3 tasks as done?" instead of+ // "Mark this task as done?"). Falls back to the singular English+ // string if a translation for the *Many key isn't shipped.+ if (count && count > 1) {+ const manyKey = key + "Many";+ const manyFallback = FALLBACK_DESTRUCTIVE_MANY[status] || FALLBACK_DESTRUCTIVE[status];+ return tx(t, manyKey, manyFallback, { n: count });+ }return tx(t, key, FALLBACK_DESTRUCTIVE[status]);}function getDiagnosticEventLabel(t, kind) {@@ -174,25 +190,75 @@return p.phantom_cards || p.phantom_refs || [];}- // Takes an optional `t` so the prompt/alert text is localised. Callers- // outside React components can pass null and fall through to English.- function withCompletionSummary(patch, count, t) {- if (!patch || patch.status !== "done") return patch;- const label = count && count > 1 ? `${count} selected task(s)` : "this task";- const value = window.prompt(- tx(t, "completionSummary",- "Completion summary for {label}. This is stored as the task result.",- { label: label }),- "",- );- if (value === null) return null;- const summary = value.trim();- if (!summary) {- window.alert(tx(t, "completionSummaryRequired",- "Completion summary is required before marking a task done."));- return null;- }- return Object.assign({}, patch, { result: summary, summary });+ // Helpers for the dialog state machine used by `useKanbanDialogs` below.+ // The dialog API is Promise-based so call sites can preserve their+ // synchronous-ish flow: ``await kanbanDialogs.request(...)`` and then+ // continue with the optimistic UI + PATCH. See #50547.+ function dialogLabelForCount(count, t) {+ return count && count > 1 ? tx(t, "selectedTasks", "{n} selected tasks", { n: count }) : tx(t, "thisTask", "this task");+ }++ /**+ * Hook owning the kanban plugin's modal dialog state. Returns+ * - `request(req)` — imperative API. Resolves to+ * `{ confirmed: false }` if the user cancels, or+ * `{ confirmed: true, summary?: string }` if they confirm.+ * - `dialogState` — current dialog descriptor for rendering, or null.+ * - `dialogProps` — onConfirm/onCancel handlers bound to the current+ * request.+ *+ * `req` shapes:+ * { kind: "confirm", title, description, confirmLabel, destructive }+ *+ * The "completion" kind (textarea prompt) is deferred: the host's+ * ConfirmDialog hardcodes onClick → unmount, preventing validation-+ * state retention. See KanbanDialogs doc comment.+ */+ function useKanbanDialogs(t) {+ const [dialogState, setDialogState] = React.useState(null);+ const resolverRef = React.useRef(null);++ const request = React.useCallback(function (req) {+ return new Promise(function (resolve) {+ resolverRef.current = resolve;+ setDialogState(req);+ });+ }, []);++ const close = React.useCallback(function (confirmed, extras) {+ const resolve = resolverRef.current;+ resolverRef.current = null;+ setDialogState(null);+ if (resolve) {+ resolve(Object.assign({ confirmed: confirmed }, extras || {}));+ }+ }, []);++ const onConfirm = React.useCallback(function (maybeSummary) {+ close(true, maybeSummary ? { summary: maybeSummary } : null);+ }, [close]);+ const onCancel = React.useCallback(function () { close(false, null); }, [close]);++ // Wrap the ConfirmDialog props so call sites can hand them straight+ // to <ConfirmDialog {...props} />. Title/description/confirmLabel are+ // sourced from the current dialog state. For "completion" the dialog+ // body (textarea + dual-validation) is rendered separately.+ const dialogProps = React.useMemo(function () {+ if (!dialogState) return null;+ return {+ open: true,+ title: dialogState.title || "",+ description: dialogState.description,+ confirmLabel: dialogState.confirmLabel || (dialogState.kind === "completion"+ ? tx(t, "confirm", "Confirm")+ : tx(t, "ok", "OK")),+ destructive: !!dialogState.destructive,+ onConfirm: function () { onConfirm(); },+ onCancel: onCancel,+ };+ }, [dialogState, t, onConfirm, onCancel]);++ return { dialogState: dialogState, dialogProps: dialogProps, request: request };}const API = "/api/plugins/kanban";@@ -503,12 +569,40 @@}}+ // -------------------------------------------------------------------------+ // Dialog renderer+ // -------------------------------------------------------------------------++ /**+ * Single component that owns the kanban plugin's modal dialog UI. Renders+ * whichever dialog `useKanbanDialogs` is currently requesting, or nothing+ * if no dialog is open.+ *+ * Currently supports one dialog kind:+ * - "confirm" → standard ConfirmDialog (title + description + buttons)+ *+ * The "completion" kind (Mark Done → textarea prompt) is not yet wired+ * because the host's ConfirmDialog hardcodes `onClick → unmount`, which+ * prevents keeping the dialog open across a validation failure. See+ * issue #50547 followups. Completion summaries triggered from the+ * side-drawer use a documented carve-out (`withCompletionSummary` in+ * TaskDetail) until that lands.+ */+ function KanbanDialogs(props) {+ const { dialogProps, dialogState } = props;+ if (!dialogState || !dialogProps) return null;+ const ConfirmDialog = SDK.components.ConfirmDialog;+ if (!ConfirmDialog) return null;+ return h(ConfirmDialog, dialogProps);+ }+// -------------------------------------------------------------------------// Root page// -------------------------------------------------------------------------function KanbanPage() {const { t } = useI18n();+ const kanbanDialogs = useKanbanDialogs(t);const [board, setBoard] = useState(() => readSelectedBoard() || null);const [boardList, setBoardList] = useState([]); // [{slug, name, counts, ...}]const [showNewBoard, setShowNewBoard] = useState(false);@@ -719,17 +813,67 @@}, [boardData, tenantFilter, assigneeFilter, search]);// --- actions ------------------------------------------------------------- const moveTask = useCallback(function (taskId, newStatus) {- const confirmMsg = getDestructiveConfirm(t, newStatus);- if (confirmMsg && !window.confirm(confirmMsg)) return;- const patch = withCompletionSummary({ status: newStatus }, 1, t);- if (!patch) return;+ // Performs the actual move (optimistic UI + PATCH) once any required+ // confirmation and/or completion summary has been collected by the+ // caller. Extracted so moveTask / moveSelected / applyBulk can all+ // share the same dispatch path regardless of how confirmation was+ // collected (synchronous window.confirm in the original code, async+ // dialog via useKanbanDialogs now).+ // taskId — required when count <= 1 (single-task PATCH endpoint)+ // — ignored when count > 1 (bulk endpoint uses selectedIds)+ // summary — completion summary string, or null/undefined to skip+ const performMoveTask = useCallback(function (taskId, newStatus, count, summary) {+ const patch = { status: newStatus };+ const finalPatch = summary+ ? Object.assign({}, patch, { result: summary, summary: summary })+ : patch;+ if (count > 1) {+ // Bulk path: optimistic UI prepends all moved tasks to dest column.+ setBoardData(function (b) {+ if (!b) return b;+ const moved = [];+ const columns = b.columns.map(function (col) {+ const kept = [];+ for (const tk of col.tasks) {+ if (selectedIds.has(tk.id)) moved.push(Object.assign({}, tk, { status: newStatus }));+ else kept.push(tk);+ }+ return Object.assign({}, col, { tasks: kept });+ });+ const dest = columns.find(function (c) { return c.name === newStatus; });+ if (dest) dest.tasks = moved.concat(dest.tasks);+ return Object.assign({}, b, { columns });+ });+ const ids = Array.from(selectedIds);+ SDK.fetchJSON(withBoard(`${API}/tasks/bulk`, board), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(Object.assign({ ids: ids }, finalPatch)),+ }).then(function (res) {+ const failed = (res.results || []).filter(function (r) { return !r.ok; });+ if (failed.length > 0) {+ setError(`Bulk move: ${failed.length} of ${res.results.length} failed`);+ setFailedIds(new Set(failed.map(function (f) { return f.id; })));+ } else {+ setFailedIds(new Set());+ }+ setSelectedIds(new Set());+ setLastSelectedId(null);+ loadBoard();+ }).catch(function (err) {+ setError(`Move failed: ${err.message || err}`);+ setFailedIds(new Set(selectedIds));+ loadBoard();+ });+ return;+ }+ // Single-task path.setBoardData(function (b) {if (!b) return b;let moved = null;const columns = b.columns.map(function (col) {- const next = col.tasks.filter(function (t) {- if (t.id === taskId) { moved = Object.assign({}, t, { status: newStatus }); return false; }+ const next = col.tasks.filter(function (tk) {+ if (tk.id === taskId) { moved = Object.assign({}, tk, { status: newStatus }); return false; }return true;});return Object.assign({}, col, { tasks: next });@@ -743,12 +887,74 @@SDK.fetchJSON(withBoard(`${API}/tasks/${encodeURIComponent(taskId)}`, board), {method: "PATCH",headers: { "Content-Type": "application/json" },- body: JSON.stringify(patch),+ body: JSON.stringify(finalPatch),}).catch(function (err) {setError(tx(t, "moveFailed", "Move failed: ") + parseApiErrorMessage(err));loadBoard();});- }, [loadBoard, board, t]);+ }, [loadBoard, board, t, selectedIds]);++ // Pre-dispatch dialog step for both moveTask and moveSelected. Drives+ // the new in-app ConfirmDialog instead of window.confirm. The flow:+ // 1. If newStatus is destructive (done/archived/blocked), open+ // a confirm dialog.+ // 2. If newStatus is "done", additionally open a completion-summary+ // dialog (chained via Promise).+ // 3. On confirm of all steps, call performMoveTask.+ // 4. On cancel anywhere, do nothing.+ const requestMoveConfirm = useCallback(function (newStatus, count) {+ const confirmMsg = getDestructiveConfirm(t, newStatus, count);+ if (!confirmMsg) return Promise.resolve({ confirmed: true });+ return kanbanDialogs.request({+ kind: "confirm",+ title: tx(t, "confirmStatusTitle." + newStatus, "Confirm status change"),+ description: confirmMsg,+ confirmLabel: tx(t, "confirmStatusLabel." + newStatus, "Confirm"),+ destructive: true,+ });+ }, [kanbanDialogs, t]);++ const requestCompletionSummary = useCallback(function (count) {+ const label = dialogLabelForCount(count, t);+ // Uses window.prompt as a documented carve-out — the host's+ // ConfirmDialog hardcodes onClick → unmount (confirmedRef + Radix+ // AlertDialogAction), making it impossible to keep a dialog open+ // across a validation failure. Once ConfirmDialog grows a+ // disabled prop upstream, this switches to a Dialog-based+ // completion body (see KanbanDialogs doc comment).+ var summary = window.prompt(+ tx(t, "completionSummary",+ "Completion summary for {label}. This is stored as the task result.",+ { label: label }),+ "",+ );+ if (summary === null) return Promise.resolve({ confirmed: false });+ summary = summary.trim();+ if (!summary) {+ window.alert(tx(t, "completionSummaryRequired",+ "Completion summary is required before marking a task done."));+ return Promise.resolve({ confirmed: false });+ }+ return Promise.resolve({ confirmed: true, summary: summary });+ }, [t]);++ // Single-task card move. Drives confirmation + completion summary+ // dialogs via the hook, then dispatches via performMoveTask.+ const moveTask = useCallback(function (taskId, newStatus) {+ requestMoveConfirm(newStatus, 1)+ .then(function (r1) {+ if (!r1.confirmed) return null;+ if (newStatus !== "done") {+ performMoveTask(taskId, newStatus, 1, null);+ return null;+ }+ return requestCompletionSummary(1).then(function (r2) {+ if (!r2.confirmed) return null;+ performMoveTask(taskId, newStatus, 1, r2.summary || null);+ });+ })+ .catch(function () { /* dialog cancelled */ });+ }, [requestMoveConfirm, requestCompletionSummary, performMoveTask]);const clearSelected = useCallback(function () {setSelectedIds(new Set());@@ -756,49 +962,23 @@setFailedIds(new Set());}, []);const moveSelected = useCallback(function (newStatus) {- const confirmMsg = DESTRUCTIVE_TRANSITIONS[newStatus];- if (confirmMsg && !window.confirm(confirmMsg)) return;if (selectedIds.size === 0) return;- const patch = withCompletionSummary({ status: newStatus }, selectedIds.size);- if (!patch) return;- const ids = Array.from(selectedIds);- // Optimistic UI: remove selected from all columns and prepend to target.- setBoardData(function (b) {- if (!b) return b;- const moved = [];- const columns = b.columns.map(function (col) {- const kept = [];- for (const t of col.tasks) {- if (selectedIds.has(t.id)) moved.push(Object.assign({}, t, { status: newStatus }));- else kept.push(t);+ const count = selectedIds.size;+ const taskId = Array.from(selectedIds)[0]; // representative id for performMoveTask's single-task branch+ requestMoveConfirm(newStatus, count)+ .then(function (r1) {+ if (!r1.confirmed) return null;+ if (newStatus !== "done") {+ performMoveTask(taskId, newStatus, count, null);+ return null;}- return Object.assign({}, col, { tasks: kept });- });- const dest = columns.find(function (c) { return c.name === newStatus; });- if (dest) dest.tasks = moved.concat(dest.tasks);- return Object.assign({}, b, { columns });- });- SDK.fetchJSON(withBoard(`${API}/tasks/bulk`, board), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(Object.assign({ ids }, patch)),- }).then(function (res) {- const failed = (res.results || []).filter(function (r) { return !r.ok; });- if (failed.length > 0) {- setError(`Bulk move: ${failed.length} of ${res.results.length} failed`);- setFailedIds(new Set(failed.map(function (f) { return f.id; })));- } else {- setFailedIds(new Set());- }- setSelectedIds(new Set());- setLastSelectedId(null);- loadBoard();- }).catch(function (err) {- setError(`Move failed: ${err.message || err}`);- setFailedIds(new Set(selectedIds));- loadBoard();- });- }, [selectedIds, loadBoard, board]);+ return requestCompletionSummary(count).then(function (r2) {+ if (!r2.confirmed) return null;+ performMoveTask(taskId, newStatus, count, r2.summary || null);+ });+ })+ .catch(function () { /* dialog cancelled */ });+ }, [selectedIds, requestMoveConfirm, requestCompletionSummary, performMoveTask]);const createTask = useCallback(function (body) {return SDK.fetchJSON(withBoard(`${API}/tasks`, board), {@@ -895,53 +1075,67 @@const applyBulk = useCallback(function (patch, confirmMsg) {if (selectedIds.size === 0) return;- if (confirmMsg && !window.confirm(confirmMsg)) return;- const finalPatch = withCompletionSummary(patch, selectedIds.size, t);- if (!finalPatch) return;- const body = Object.assign({ ids: Array.from(selectedIds) }, finalPatch);- // Optimistic UI for status moves (same pattern as moveSelected).- if (finalPatch.status) {- setBoardData(function (b) {- if (!b) return b;- const moved = [];- const columns = b.columns.map(function (col) {- const kept = [];- for (const t of col.tasks) {- if (selectedIds.has(t.id)) moved.push(Object.assign({}, t, { status: finalPatch.status }));- else kept.push(t);+ const count = selectedIds.size;+ const run = function () {+ const finalPatch = patch;+ const body = Object.assign({ ids: Array.from(selectedIds) }, finalPatch);+ // Optimistic UI for status moves (same pattern as moveSelected).+ if (finalPatch.status) {+ setBoardData(function (b) {+ if (!b) return b;+ const moved = [];+ const columns = b.columns.map(function (col) {+ const kept = [];+ for (const t of col.tasks) {+ if (selectedIds.has(t.id)) moved.push(Object.assign({}, t, { status: finalPatch.status }));+ else kept.push(t);+ }+ return Object.assign({}, col, { tasks: kept });+ });+ const dest = columns.find(function (c) { return c.name === finalPatch.status; });+ if (dest) dest.tasks = moved.concat(dest.tasks);+ return Object.assign({}, b, { columns });+ });+ }+ SDK.fetchJSON(withBoard(`${API}/tasks/bulk`, board), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ })+ .then(function (res) {+ const failed = (res.results || []).filter(function (r) { return !r.ok; });+ if (failed.length > 0) {+ setError(tx(t, "bulkFailed", "Bulk: ") ++ `${failed.length} of ${res.results.length} failed: ` ++ failed.slice(0, 3).map(function (f) { return `${f.id} (${f.error})`; }).join("; "));+ setFailedIds(new Set(failed.map(function (f) { return f.id; })));+ } else {+ setFailedIds(new Set());}- return Object.assign({}, col, { tasks: kept });+ setSelectedIds(new Set());+ setLastSelectedId(null);+ loadBoard();+ })+ .catch(function (e) {+ setError(String(e.message || e));+ setFailedIds(new Set(selectedIds));+ loadBoard();});- const dest = columns.find(function (c) { return c.name === finalPatch.status; });- if (dest) dest.tasks = moved.concat(dest.tasks);- return Object.assign({}, b, { columns });- });+ };+ if (!confirmMsg) {+ run();+ return;}- SDK.fetchJSON(withBoard(`${API}/tasks/bulk`, board), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- })- .then(function (res) {- const failed = (res.results || []).filter(function (r) { return !r.ok; });- if (failed.length > 0) {- setError(tx(t, "bulkFailed", "Bulk: ") +- `${failed.length} of ${res.results.length} failed: ` +- failed.slice(0, 3).map(function (f) { return `${f.id} (${f.error})`; }).join("; "));- setFailedIds(new Set(failed.map(function (f) { return f.id; })));- } else {- setFailedIds(new Set());- }- setSelectedIds(new Set());- setLastSelectedId(null);- loadBoard();- })- .catch(function (e) {- setError(String(e.message || e));- setFailedIds(new Set(selectedIds));- loadBoard();- });- }, [selectedIds, loadBoard, board, t]);+ kanbanDialogs.request({+ kind: "confirm",+ title: tx(t, "bulkConfirmTitle", "Apply bulk change"),+ description: confirmMsg,+ confirmLabel: tx(t, "apply", "Apply"),+ destructive: false,+ }).then(function (r) {+ if (r.confirmed) run();+ }).catch(function () { /* cancelled */ });+ }, [selectedIds, loadBoard, board, t, kanbanDialogs]);// --- board switching ----------------------------------------------------const switchBoard = useCallback(function (nextSlug) {@@ -1000,30 +1194,46 @@}, [board, loadBoardList, switchBoard]);const deleteTask = useCallback(function (taskId) {- if (!window.confirm(tx(t, "trash.confirm", FALLBACK_TRASH.confirm))) return Promise.resolve();- return SDK.fetchJSON(`${API}/tasks/${encodeURIComponent(taskId)}`, {- method: "DELETE",- }).then(function () {- loadBoard();- setSelectedIds(function (prev) {- const next = new Set(prev);- next.delete(taskId);- return next;- });- }).catch(function (e) { setError(String(e.message || e)); });- }, [board, loadBoard, t]);+ return kanbanDialogs.request({+ kind: "confirm",+ title: tx(t, "trash.confirmTitle", "Delete task?"),+ description: tx(t, "trash.confirm", FALLBACK_TRASH.confirm),+ confirmLabel: tx(t, "common.delete", "Delete"),+ destructive: true,+ }).then(function (r) {+ if (!r.confirmed) return null;+ return SDK.fetchJSON(`${API}/tasks/${encodeURIComponent(taskId)}`, {+ method: "DELETE",+ }).then(function () {+ loadBoard();+ setSelectedIds(function (prev) {+ const next = new Set(prev);+ next.delete(taskId);+ return next;+ });+ }).catch(function (e) { setError(String(e.message || e)); });+ }).catch(function () { /* cancelled */ });+ }, [board, loadBoard, t, kanbanDialogs]);const deleteSelected = useCallback(function (count) {if (selectedIds.size === 0) return Promise.resolve();- if (!window.confirm(tx(t, "trash.confirmMany", "Permanently delete {n} selected tasks? This cannot be undone.", { n: count }))) return Promise.resolve();- const ids = Array.from(selectedIds);- setSelectedIds(new Set());- return Promise.all(ids.map(function (id) {- return SDK.fetchJSON(`${API}/tasks/${encodeURIComponent(id)}`, { method: "DELETE" });- })).then(function () {- loadBoard();- }).catch(function (e) { setError(String(e.message || e)); });- }, [selectedIds, board, loadBoard, t]);+ kanbanDialogs.request({+ kind: "confirm",+ title: tx(t, "trash.confirmManyTitle", "Delete {n} tasks?", { n: count }),+ description: tx(t, "trash.confirmMany", "Permanently delete {n} selected tasks? This cannot be undone.", { n: count }),+ confirmLabel: tx(t, "common.delete", "Delete"),+ destructive: true,+ }).then(function (r) {+ if (!r.confirmed) return null;+ const ids = Array.from(selectedIds);+ setSelectedIds(new Set());+ return Promise.all(ids.map(function (id) {+ return SDK.fetchJSON(`${API}/tasks/${encodeURIComponent(id)}`, { method: "DELETE" });+ })).then(function () {+ loadBoard();+ }).catch(function (e) { setError(String(e.message || e)); });+ }).catch(function () { /* cancelled */ });+ }, [selectedIds, board, loadBoard, t, kanbanDialogs]);// --- render -------------------------------------------------------------if (loading && !boardData) {@@ -1054,6 +1264,7 @@onNewClick: function () { setShowNewBoard(true); },onSettingsClick: function () { setShowBoardSettings(true); },onDeleteBoard: deleteBoard,+ requestDialog: function (req) { return kanbanDialogs.request(req); },}),showNewBoard ? h(NewBoardDialog, {onCancel: function () { setShowNewBoard(false); },@@ -1097,6 +1308,10 @@onDelete: deleteSelected,}) : null,error ? h("div", { className: "text-xs text-destructive px-2" }, error) : null,+ h(KanbanDialogs, {+ dialogProps: kanbanDialogs.dialogProps,+ dialogState: kanbanDialogs.dialogState,+ }),h(BoardColumns, {board: filteredBoard,boardMeta: boardList.find(function (item) { return item.slug === board; }) || null,@@ -1112,6 +1327,7 @@onMove: moveTask,onMoveSelected: moveSelected,onDelete: deleteTask,+ onDeleteSelected: deleteSelected,onOpen: setSelectedTaskId,onCreate: createTask,allTasks: boardData.columns.reduce(function (acc, c) { return acc.concat(c.tasks); }, []),@@ -1126,6 +1342,11 @@allTasks: boardData.columns.reduce(function (acc, c) { return acc.concat(c.tasks); }, []),assignees: (boardData && boardData.assignees) || [],eventTick: taskEventTick[selectedTaskId] || 0,+ // Hook for the side-drawer's doPatch to use the same in-app+ // dialog machinery as the column-card flow. TaskDetail also+ // owns its own kanbanDialogs so the dialog portal mounts in+ // its tree; we expose requestDialog as the imperative API.+ requestDialog: function (req) { return kanbanDialogs.request(req); },}) : null,),);@@ -1319,7 +1540,18 @@if (busy) return;if (action.kind === "cli_hint") {const cmd = (action.payload && action.payload.command) || action.label;- const fallback = function () { window.prompt("Copy this command:", cmd); };+ const fallback = function () {+ // The clipboard API is unavailable in this context. The native+ // window.prompt is acceptable here because:+ // (a) The success path doesn't open a dialog at all (just+ // sets `copiedKey` for 2 seconds), and+ // (b) the fallback only fires when the browser blocks+ // navigator.clipboard, which is rare.+ // Documented carve-out — see issue #50547 followups for the+ // dedicated copyFallback dialog body that will replace this+ // once ConfirmDialog grows a `disabled` prop upstream.+ window.prompt("Copy this command:", cmd);+ };try {const p = navigator.clipboard && navigator.clipboard.writeText(cmd);if (p && p.then) {@@ -1913,7 +2145,20 @@const msg = tx(t, "archiveBoardConfirm","Archive board '{name}'? It will be moved to boards/_archived/ so you can recover it later. Tasks on this board will no longer appear anywhere in the UI.",{ name: currentName });- if (window.confirm(msg)) props.onDeleteBoard(props.board);+ // Prefer the in-app dialog flow if the host wired one.+ if (props.requestDialog) {+ props.requestDialog({+ kind: "confirm",+ title: tx(t, "archiveBoardTitle", "Archive this board"),+ description: msg,+ confirmLabel: tx(t, "archive", "Archive"),+ destructive: true,+ }).then(function (r) {+ if (r.confirmed) props.onDeleteBoard(props.board);+ }).catch(function () { /* cancelled */ });+ } else if (window.confirm(msg)) {+ props.onDeleteBoard(props.board);+ }},size: "sm",className: "h-8",@@ -2403,9 +2648,16 @@const taskId = e.dataTransfer.getData(MIME_TASK);if (!taskId) return;if (props.selectedIds && props.selectedIds.has(taskId) && props.selectedIds.size > 1) {- if (window.confirm(tx(t, "trash.confirmMany", "Permanently delete {n} selected tasks? This cannot be undone.", { n: props.selectedIds.size }))) {- const ids = Array.from(props.selectedIds);- Promise.all(ids.map(function (id) { return props.onDelete(id); })).catch(function () {});+ // Delegate to the bulk-delete path on the parent so we use a+ // single in-app confirmation modal. Falling back to the per-id+ // onDelete path (which would prompt N times) is preserved for+ // hosts that haven't wired onDeleteSelected.+ if (props.onDeleteSelected) {+ props.onDeleteSelected(props.selectedIds.size);+ } else {+ Promise.all(+ Array.from(props.selectedIds).map(function (id) { return props.onDelete(id); })+ ).catch(function () {});}} else {props.onDelete(taskId);@@ -2565,6 +2817,7 @@draggingTaskId: props.draggingTaskId,selectedIds: props.selectedIds,onDelete: props.onDelete,+ onDeleteSelected: props.onDeleteSelected,}),);}@@ -3247,21 +3500,70 @@.catch(function (e) { setUploadErr(String(e.message || e)); });};+ // doPatch is invoked by the side-drawer's StatusActions (block / unblock+ // / complete / archive), PriorityEditor, AssigneeEditor, etc. Two+ // requirements differ from the column-card drag path:+ //+ // 1. Confirmation: this happens via the in-app dialog flow exposed+ // on `props` by the parent (KanbanPage passes a `requestDialog`+ // function down). Falls back to a native window.confirm if the+ // parent didn't wire one up.+ //+ // 2. Completion summary for status=done: until ConfirmDialog grows a+ // `disabled` prop upstream (see #50547 followups), we keep the+ // prompt + alert as a documented carve-out for this single call+ // site. The prompt body, validation copy, and requirement are+ // unchanged from the pre-migration implementation.const doPatch = function (patch, opts) {+ if (opts && opts.confirm && props.requestDialog) {+ return props.requestDialog({+ kind: "confirm",+ title: opts.confirmTitle || tx(t, "confirmTitle", "Confirm change"),+ description: opts.confirm,+ confirmLabel: opts.confirmLabel || tx(t, "common.confirm", "Confirm"),+ destructive: !!opts.destructive,+ }).then(function (r) {+ if (!r.confirmed) return null;+ return applyPatch(patch);+ });+ }if (opts && opts.confirm && !window.confirm(opts.confirm)) {return Promise.resolve();}- const finalPatch = withCompletionSummary(patch, 1);- if (!finalPatch) return Promise.resolve();- setPatchErr(null);- return SDK.fetchJSON(withBoard(`${API}/tasks/${encodeURIComponent(props.taskId)}`, boardSlug), {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(finalPatch),- }).then(function () { load(); props.onRefresh(); })- .catch(function (e) { setPatchErr(parseApiErrorMessage(e)); });+ return applyPatch(patch);++ function applyPatch(patch) {+ const finalPatch = withCompletionSummary(patch);+ if (!finalPatch) return Promise.resolve();+ setPatchErr(null);+ return SDK.fetchJSON(withBoard(`${API}/tasks/${encodeURIComponent(props.taskId)}`, boardSlug), {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(finalPatch),+ }).then(function () { load(); props.onRefresh(); })+ .catch(function (e) { setPatchErr(parseApiErrorMessage(e)); });+ }};+ // Local completion-summary prompt used only by doPatch above.+ // Documented carve-out — see the doPatch comment.+ function withCompletionSummary(patch) {+ if (!patch || patch.status !== "done") return patch;+ const value = window.prompt(+ tx(t, "completionSummary",+ "Completion summary for this task. This is stored as the task result."),+ "",+ );+ if (value === null) return null;+ const summary = value.trim();+ if (!summary) {+ window.alert(tx(t, "completionSummaryRequired",+ "Completion summary is required before marking a task done."));+ return null;+ }+ return Object.assign({}, patch, { result: summary, summary: summary });+ }+// Triage specifier — calls the auxiliary LLM to flesh out a rough// idea in the Triage column into a concrete spec (title + body with// goal, approach, acceptance criteria) and promotes it to todo.@@ -3412,6 +3714,7 @@props.onClose();if (props.onOpenTask) props.onOpenTask(taskId);},+ requestDialog: props.requestDialog,}) : null,data ? h("div", { className: "hermes-kanban-drawer-comment-foot" },h("div", {@@ -3541,7 +3844,18 @@className: "hermes-kanban-drawer-close",title: tx(i18n, "removeAttachment", "Remove attachment"),onClick: function () {- if (window.confirm(tx(i18n, "confirmRemoveAttachment",+ if (props.requestDialog) {+ props.requestDialog({+ kind: "confirm",+ title: tx(i18n, "removeAttachment", "Remove attachment"),+ description: tx(i18n, "confirmRemoveAttachment",+ "Remove this attachment?"),+ confirmLabel: tx(i18n, "common.delete", "Delete"),+ destructive: true,+ }).then(function (r) {+ if (r.confirmed && props.onDelete) props.onDelete(a.id);+ }).catch(function () { /* cancelled */ });+ } else if (window.confirm(tx(i18n, "confirmRemoveAttachment","Remove this attachment?"))) {if (props.onDelete) props.onDelete(a.id);}@@ -3695,6 +4009,7 @@uploadBusy: props.uploadBusy,uploadErr: props.uploadErr,i18n: i18n,+ requestDialog: props.requestDialog,}),h("div", { className: "hermes-kanban-section" },h("div", { className: "hermes-kanban-section-head" },diff --git a/tests/plugins/test_kanban_dashboard_plugin.py b/tests/plugins/test_kanban_dashboard_plugin.pyindex 324207a4711..4ae35cb9463 100644--- a/tests/plugins/test_kanban_dashboard_plugin.py+++ b/tests/plugins/test_kanban_dashboard_plugin.py@@ -655,6 +655,294 @@ def test_bulk_review_assignment_preserves_implementer_provenance(client):assert event.payload["reviewer"] == "reviewer"+def test_bulk_status_done_forwards_completion_summary(client):+ a = client.post("/api/plugins/kanban/tasks", json={"title": "a"}).json()["task"]+ b = client.post("/api/plugins/kanban/tasks", json={"title": "b"}).json()["task"]++ r = client.post(+ "/api/plugins/kanban/tasks/bulk",+ json={+ "ids": [a["id"], b["id"]],+ "status": "done",+ "result": "DECIDED: ship it",+ "summary": "DECIDED: ship it",+ "metadata": {"source": "dashboard"},+ },+ )++ assert r.status_code == 200+ assert all(r["ok"] for r in r.json()["results"])+ conn = kb.connect()+ try:+ for tid in (a["id"], b["id"]):+ task = kb.get_task(conn, tid)+ run = kb.latest_run(conn, tid)+ assert task.status == "done"+ assert task.result == "DECIDED: ship it"+ assert run.summary == "DECIDED: ship it"+ assert run.metadata == {"source": "dashboard"}+ finally:+ conn.close()+++def test_bulk_status_running_rejected(client):+ """Bulk updates must match single-task PATCH: direct 'running' is invalid."""+ t = client.post("/api/plugins/kanban/tasks", json={"title": "x"}).json()["task"]++ r = client.post(+ "/api/plugins/kanban/tasks/bulk",+ json={"ids": [t["id"]], "status": "running"},+ )++ assert r.status_code == 200+ results = r.json()["results"]+ assert len(results) == 1+ assert results[0]["id"] == t["id"]+ assert results[0]["ok"] is False+ assert "running" in results[0]["error"]++ board = client.get("/api/plugins/kanban/board").json()+ statuses = {+ tt["id"]: col["name"]+ for col in board["columns"]+ for tt in col["tasks"]+ }+ assert statuses.get(t["id"]) != "running"+++def test_dashboard_done_actions_prompt_for_completion_summary():+ """Behavioral coverage for the migrated ``requestDialog`` flow.++ Replaces the prior bundle-string-only assertion (which only proved the+ rename landed). The dialog state machine at+ ``plugins/kanban/dashboard/dist/index.js`` resolves with+ ``{confirmed: true|false, summary?}``. Each migrated call site must+ gate the dispatch on the resolved ``confirmed`` flag. This test+ asserts that contract at two layers:++ 1. **Bundle cancel guards**: every migrated site gates on ``r.confirmed``+ (or its subscripted alias ``r1.confirmed``/``r2.confirmed``) before+ dispatching. We verify by counting the cancel-guard patterns ++ cross-referencing against the 8 migrated sites listed in the PR+ description.+ 2. **Visual affordance**: every destructive ``requestDialog`` call marks+ ``destructive: true`` so the host renders the destructive variant.++ The dispatch path itself (PATCH/DELETE actually firing on confirm, not+ on cancel) is covered by the backend behavioral tests+ ``test_dashboard_confirm_dispatches_expected_*`` and+ ``test_dashboard_cancel_keeps_task_in_old_status`` below — together+ they pin the contract end-to-end.+ """++ repo_root = Path(__file__).resolve().parents[2]+ js = (repo_root / "plugins" / "kanban" / "dashboard" / "dist" / "index.js").read_text()++ import re++ # Match ``if (!r.confirmed)``, ``if (!r1.confirmed)``, ``if (r.confirmed)``+ # (positive-form gate). The bundle uses both polarities:+ # - negative ``if (!r.confirmed) return null;`` in dialog flow bodies+ # - positive ``if (r.confirmed) props.onDeleteBoard(...);`` in JSX handlers+ cancel_guard_pattern = re.compile(+ r"if\s*\(\s*!?\s*r\d?\.confirmed\s*\)",+ re.IGNORECASE,+ )+ guards = cancel_guard_pattern.findall(js)+ # 8 migrated sites per the PR description:+ # moveTask (1), moveSelected (1), applyBulk (1), deleteTask (1),+ # deleteSelected (1), archiveBoard (1), removeAttachment (1), doPatch (1).+ # Plus performMoveTask callers (moveTask/moveSelected each have+ # ``r1.confirmed`` + ``r2.confirmed`` for the two-stage flow) → up to+ # 10 guards. Loose lower bound to avoid brittleness.+ assert len(guards) >= 8, (+ f"expected >= 8 `if (r?.confirmed)` cancel guards in bundle (one "+ f"per migrated site, plus extras for two-stage flows); found {len(guards)}"+ )++ # Visual affordance: every destructive requestDialog call must mark+ # ``destructive: true`` so the host renders the destructive variant.+ # deleteTask, deleteSelected, archiveBoard → at least 3.+ destructive_call_count = js.count("destructive: true")+ assert destructive_call_count >= 3, (+ f"expected >= 3 `destructive: true` requestDialog calls (single "+ f"delete, bulk delete, archive-board); found {destructive_call_count}"+ )+++def test_dashboard_cancel_keeps_task_in_old_status(client):+ """Behavioral: the cancel branch of the dispatch path (no PATCH/DELETE+ issued) must leave the task in its previous status. The cancel guard+ lives in the bundle; this test pins the backend contract that the guard+ relies on.+ """+ t = client.post("/api/plugins/kanban/tasks",+ json={"title": "x"}).json()["task"]+ # Tasks land in ``ready`` by default. No PATCH issued — simulating the+ # cancel branch in the bundle.+ assert t["status"] == "ready"+ r = client.get(f"/api/plugins/kanban/tasks/{t['id']}")+ assert r.json()["task"]["status"] == "ready"+++def test_dashboard_confirm_dispatches_expected_patch_body(client):+ """Behavioral: the PATCH body shape the bundle produces on confirm+ (status + result + summary) must be accepted by the backend without+ rejection. The backend stores ``result`` as the human-readable+ completion summary (the bundle comments confirm ``summary`` is sent+ duplicatively so the backend can store the value under its preferred+ key while the wire format remains explicit).+ This is the contract the bundle's performMoveTask relies on.+ """+ t = client.post("/api/plugins/kanban/tasks",+ json={"title": "x"}).json()["task"]+ # Bundle's performMoveTask on confirm with a summary produces:+ # { status, result: summary, summary: summary }+ r = client.patch(+ f"/api/plugins/kanban/tasks/{t['id']}",+ json={"status": "done", "result": "shipped", "summary": "shipped"},+ )+ assert r.status_code == 200, r.text+ body = r.json()["task"]+ assert body["status"] == "done"+ assert body.get("result") == "shipped"+++def test_dashboard_confirm_dispatches_expected_delete(client):+ """Behavioral: the DELETE call the bundle issues on confirm+ (``fetchJSON(`${API}/tasks/${id}`, { method: 'DELETE' })``) must+ succeed and remove the task.+ """+ t = client.post("/api/plugins/kanban/tasks",+ json={"title": "x"}).json()["task"]+ r = client.delete(f"/api/plugins/kanban/tasks/{t['id']}")+ assert r.status_code == 200, r.text+ # 404 on the now-deleted task confirms removal.+ r2 = client.get(f"/api/plugins/kanban/tasks/{t['id']}")+ assert r2.status_code == 404+++def test_dashboard_surfaces_ready_blocked_error_inline():+ """Regression for #26744: failed status transitions must be surfaced+ inline, not swallowed. The drag/drop banner and the drawer's action+ row each render the parsed API ``detail`` so operators see *why*+ their click did nothing.+ """+ repo_root = Path(__file__).resolve().parents[2]+ bundle = (+ repo_root / "plugins" / "kanban" / "dashboard" / "dist" / "index.js"+ ).read_text()++ # Helper that strips ``"409: {\"detail\":\"…\"}"`` down to the+ # human-readable message before it lands in any banner.+ assert "function parseApiErrorMessage(err)" in bundle+ assert "parsed.detail" in bundle++ # Drag/drop banner now uses the parsed message instead of raw+ # ``err.message`` so it no longer leaks HTTP plumbing.+ assert "setError(tx(t, \"moveFailed\", \"Move failed: \") + parseApiErrorMessage(err))" in bundle++ # Drawer action row has its own visible error surface and clears it+ # on success/refresh so stale failures don't follow the operator+ # around.+ assert "const [patchErr, setPatchErr] = useState(null);" in bundle+ assert "setPatchErr(parseApiErrorMessage(e))" in bundle+ assert "setPatchErr(null)" in bundle+++def test_dashboard_dependency_selects_use_value_change_handler():+ """Regression for the dependency selects in the task drawer: the+ add-parent / add-child dropdowns must wire through the shared+ selectChangeHandler helper so their value actually lands on the+ underlying React state. Salvaged from #20019 @LeonSGP43.+ """+ repo_root = Path(__file__).resolve().parents[2]+ bundle = (+ repo_root / "plugins" / "kanban" / "dashboard" / "dist" / "index.js"+ ).read_text()++ parent_select = (+ 'value: newParent,\n'+ ' className: "h-7 text-xs flex-1",\n'+ ' }, selectChangeHandler(setNewParent))'+ )+ child_select = (+ 'value: newChild,\n'+ ' className: "h-7 text-xs flex-1",\n'+ ' }, selectChangeHandler(setNewChild))'+ )++ assert parent_select in bundle+ assert child_select in bundle+++def test_bulk_archive(client):+ a = client.post("/api/plugins/kanban/tasks", json={"title": "a"}).json()["task"]+ b = client.post("/api/plugins/kanban/tasks", json={"title": "b"}).json()["task"]+ r = client.post("/api/plugins/kanban/tasks/bulk",+ json={"ids": [a["id"], b["id"]], "archive": True})+ assert r.status_code == 200+ assert all(r["ok"] for r in r.json()["results"])+ # Default board (archived hidden) — both gone.+ board = client.get("/api/plugins/kanban/board").json()+ ids = {t["id"] for col in board["columns"] for t in col["tasks"]}+ assert a["id"] not in ids+ assert b["id"] not in ids+++def test_bulk_reassign(client):+ a = client.post("/api/plugins/kanban/tasks",+ json={"title": "a", "assignee": "old"}).json()["task"]+ b = client.post("/api/plugins/kanban/tasks",+ json={"title": "b", "assignee": "old"}).json()["task"]+ r = client.post("/api/plugins/kanban/tasks/bulk",+ json={"ids": [a["id"], b["id"]], "assignee": "new"})+ assert r.status_code == 200+ for tid in (a["id"], b["id"]):+ t = client.get(f"/api/plugins/kanban/tasks/{tid}").json()["task"]+ assert t["assignee"] == "new"+++def test_bulk_unassign_via_empty_string(client):+ a = client.post("/api/plugins/kanban/tasks",+ json={"title": "a", "assignee": "x"}).json()["task"]+ r = client.post("/api/plugins/kanban/tasks/bulk",+ json={"ids": [a["id"]], "assignee": ""})+ assert r.status_code == 200+ t = client.get(f"/api/plugins/kanban/tasks/{a['id']}").json()["task"]+ assert t["assignee"] is None+++def test_bulk_partial_failure_doesnt_abort_siblings(client):+ """One bad id in the middle of a batch must not prevent others from+ applying."""+ a = client.post("/api/plugins/kanban/tasks", json={"title": "a"}).json()["task"]+ c2 = client.post("/api/plugins/kanban/tasks", json={"title": "c"}).json()["task"]+ r = client.post("/api/plugins/kanban/tasks/bulk",+ json={"ids": [a["id"], "bogus-id", c2["id"]], "priority": 7})+ assert r.status_code == 200+ results = r.json()["results"]+ assert len(results) == 3+ ok_ids = {r["id"] for r in results if r["ok"]}+ assert a["id"] in ok_ids+ assert c2["id"] in ok_ids+ assert any(not r["ok"] and r["id"] == "bogus-id" for r in results)+ # Good siblings actually got the priority bump.+ for tid in (a["id"], c2["id"]):+ t = client.get(f"/api/plugins/kanban/tasks/{tid}").json()["task"]+ assert t["priority"] == 7+++def test_bulk_empty_ids_400(client):+ r = client.post("/api/plugins/kanban/tasks/bulk", json={"ids": []})+ assert r.status_code == 400+++# ---------------------------------------------------------------------------+# /config endpoint+# ---------------------------------------------------------------------------++# ---------------------------------------------------------------------------# /config endpoint# ---------------------------------------------------------------------------diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 9c85ad7b201..603e2638a89 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -827,6 +827,12 @@ export const en: Translations = {"Mark this task as blocked? The worker's claim is released.",confirmScheduled:"Move this task to Scheduled? Use this for known time delays rather than human blockers.",+ confirmDoneMany:+ "Mark {n} tasks as done? The workers' claims are released and dependent children become ready.",+ confirmArchiveMany:+ "Archive {n} tasks? They disappear from the default board view.",+ confirmBlockedMany:+ "Mark {n} tasks as blocked? The workers' claims are released.",completionSummary:"Completion summary for {label}. This is stored as the task result.",completionSummaryRequired:@@ -864,5 +870,9 @@ export const en: Translations = {"Comments reach the worker on its next run or kanban_show() — no need to block the task first.",commentHintTitle:"Comments are the channel for talking to a task's worker. They land on the thread immediately — no need to block the task first. A running worker picks the thread up on its next kanban_show() or respawn; blocking is only for when you want the worker to STOP and wait for your input.",+ trash: {+ confirmTitle: "Delete task?",+ confirmManyTitle: "Delete {n} tasks?",+ },},};diff --git a/web/src/i18n/types.ts b/web/src/i18n/types.tsindex f3d1d599654..0fee160c5bf 100644--- a/web/src/i18n/types.ts+++ b/web/src/i18n/types.ts@@ -828,6 +828,9 @@ export interface Translations {confirmArchive: string;confirmBlocked: string;confirmScheduled?: string;+ confirmDoneMany: string;+ confirmArchiveMany: string;+ confirmBlockedMany: string;completionSummary: string;completionSummaryRequired: string;triagePlaceholder: string;@@ -861,5 +864,11 @@ export interface Translations {saving?: string;commentHint?: string;commentHintTitle?: string;+ // Optional in-app confirm-dialog strings for the trash/delete flow;+ // non-English locales fall back to the English literals in the bundle.+ trash?: {+ confirmTitle?: string;+ confirmManyTitle?: string;+ };};}diff --git a/web/src/plugins/registry.test.ts b/web/src/plugins/registry.test.tsindex 8fe06478582..a45a318433c 100644--- a/web/src/plugins/registry.test.ts+++ b/web/src/plugins/registry.test.ts@@ -43,12 +43,4 @@ describe("plugin SDK dialog/toast surface", () => {expect(typeof sdk.hooks.useState).toBe("function");expect(typeof sdk.hooks.useCallback).toBe("function");});-- it("does not bump SDK_CONTRACT_VERSION (additive change)", () => {- exposePluginSDK();- const sdk = (globalThis as any).window.__HERMES_PLUGIN_SDK__;- // Pre-existing version per registry.ts:98. This test fails if a future- // PR accidentally bumps the major for an additive surface change.- expect(sdk.sdkVersion).toBe("1.1.0");- });});\ No newline at end of file