Skip to content

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

Go

MUL-8316: feat: restrict issue deletion to creators and workspace admins (#9789)

SUBARUAWA486e9e4f6315177
diff --git a/apps/docs/content/docs/issues.fr.mdx b/apps/docs/content/docs/issues.fr.mdx
index d4e6759667..d681f23b87 100644
--- a/apps/docs/content/docs/issues.fr.mdx
+++ b/apps/docs/content/docs/issues.fr.mdx
@@ -189,7 +189,13 @@ La relation n'a qu'un niveau : une tâche déjà marquée comme doublon ne peut
## Supprimer une tâche
-Tout membre de l'espace de travail peut supprimer une tâche.
+Qui peut supprimer une tâche :
+
+- Les propriétaires et administrateurs peuvent supprimer toute tâche.
+- Les membres peuvent supprimer les tâches créées par eux ou par les agents dont ils sont actuellement propriétaires.
+- Un agent peut uniquement supprimer les tâches qu'il a créées, sans hériter des droits de suppression de son propriétaire.
+
+La règle dépend du créateur, pas du responsable actuel. Pour un agent partagé, son propriétaire actuel gère ses tâches, quelle que soit la personne qui l'a invoqué. Si l'agent créateur n'existe plus, un propriétaire ou administrateur peut supprimer la tâche. Si une sélection contient une tâche que vous ne pouvez pas supprimer, toute la suppression groupée est refusée et rien n'est supprimé.
<Callout type="warning">
La suppression est irréversible : la tâche, avec ses commentaires, ses pièces jointes et ses enregistrements liés, est définitivement supprimée, et les exécutions non terminées sont annulées. Si le travail n'est simplement plus poursuivi, passez plutôt le statut à `cancelled` — la discussion et les résultats restent disponibles.
diff --git a/apps/docs/content/docs/issues.ja.mdx b/apps/docs/content/docs/issues.ja.mdx
index da4e11df8c..a03615110b 100644
--- a/apps/docs/content/docs/issues.ja.mdx
+++ b/apps/docs/content/docs/issues.ja.mdx
@@ -189,7 +189,13 @@ import { DeliverablesDemo } from "@/components/demos/deliverables-demo";
## タスクの削除
-ワークスペースのメンバーは誰でもタスクを削除できます。
+タスクを削除できるのは次のとおりです。
+
+- ワークスペースの owner と admin はすべてのタスクを削除できます。
+- メンバーは、自分または現在所有するエージェントが作成したタスクを削除できます。
+- エージェントは自分が作成したタスクのみ削除でき、所有者の削除権限を引き継ぎません。
+
+現在の担当者ではなく、作成者で判定します。共有エージェントのタスクは、呼び出した人に関係なく現在の所有者が管理します。作成したエージェントが存在しない場合は、ワークスペースの owner または admin が削除できます。一括削除に削除できないタスクが含まれる場合は、全体が拒否され、何も削除されません。
<Callout type="warning">
削除は元に戻せません。タスクとそのコメント、添付ファイル、関連レコードは完全に削除され、終了していない実行はキャンセルされます。作業を続けないだけであれば、ステータスを `cancelled` に変更してください。議論と結果は引き続き参照できます。
diff --git a/apps/docs/content/docs/issues.ko.mdx b/apps/docs/content/docs/issues.ko.mdx
index 2b5dc67df1..a963d41e1e 100644
--- a/apps/docs/content/docs/issues.ko.mdx
+++ b/apps/docs/content/docs/issues.ko.mdx
@@ -189,7 +189,13 @@ import { DeliverablesDemo } from "@/components/demos/deliverables-demo";
## 태스크 삭제
-모든 워크스페이스 멤버가 태스크를 삭제할 수 있습니다.
+태스크를 삭제할 수 있는 사람:
+
+- 워크스페이스 owner와 admin은 모든 태스크를 삭제할 수 있습니다.
+- 멤버는 본인 또는 현재 본인 소유 에이전트가 만든 태스크를 삭제할 수 있습니다.
+- 에이전트는 자신이 만든 태스크만 삭제할 수 있으며, 소유자의 삭제 권한을 상속하지 않습니다.
+
+현재 담당자가 아닌 생성자를 기준으로 판단합니다. 공유 에이전트가 만든 태스크는 호출한 사람과 관계없이 현재 소유자가 관리합니다. 생성한 에이전트가 더 이상 없으면 워크스페이스 owner 또는 admin이 삭제할 수 있습니다. 일괄 삭제에 삭제할 수 없는 태스크가 하나라도 있으면 전체가 거부되며 아무것도 삭제되지 않습니다.
<Callout type="warning">
삭제는 복구할 수 없습니다. 태스크와 댓글, 첨부 파일, 관련 기록이 영구적으로 제거되고 끝나지 않은 실행도 취소됩니다. 더 이상 진행하지 않으려면 상태를 `cancelled`로 바꾸세요. 논의와 결과는 계속 확인할 수 있습니다.
diff --git a/apps/docs/content/docs/issues.mdx b/apps/docs/content/docs/issues.mdx
index 55381b9d37..e3dbba47b2 100644
--- a/apps/docs/content/docs/issues.mdx
+++ b/apps/docs/content/docs/issues.mdx
@@ -189,7 +189,13 @@ The relation is one level deep: an issue that is itself a duplicate cannot be an
## Delete an issue
-Any workspace member can delete an issue.
+Who can delete an issue:
+
+- Workspace owners and admins can delete any issue.
+- Members can delete issues they created or that agents they currently own created.
+- Agents can delete only issues they created; they do not inherit their owner's deletion rights.
+
+This uses the creator, not the current assignee. For a shared agent, its current owner manages its issues regardless of who invoked it. If the creating agent no longer exists, a workspace owner or admin can delete the issue. When a batch includes an issue you cannot delete, the whole batch is refused and nothing is deleted.
<Callout type="warning">
Deletion cannot be undone: the issue with its comments, attachments, and linked records is permanently removed, and unfinished runs are cancelled. When the work is simply no longer pursued, set the status to `cancelled` instead — the discussion and results stay available.
diff --git a/apps/docs/content/docs/issues.zh.mdx b/apps/docs/content/docs/issues.zh.mdx
index ed8aa3026b..50cd530fe0 100644
--- a/apps/docs/content/docs/issues.zh.mdx
+++ b/apps/docs/content/docs/issues.zh.mdx
@@ -189,7 +189,13 @@ import { DeliverablesDemo } from "@/components/demos/deliverables-demo";
## 删除任务
-任何工作区成员都可以删除任务。
+谁可以删除任务:
+
+- 工作区 owner 和 admin 可以删除任意任务。
+- 成员可以删除本人或本人当前拥有的智能体创建的任务。
+- 智能体只能删除自身创建的任务,不继承其 owner 的删除权限。
+
+权限按创建者判断,与当前负责人无关。共享智能体创建的任务由其当前 owner 管理,与调用者无关。创建任务的智能体已不存在时,由工作区 owner 或 admin 删除。批量删除中只要有一条无权删除,整批都会被拒绝,不会删除任何任务。
<Callout type="warning">
删除不可恢复:任务及其评论、附件和关联记录会被永久移除,尚未结束的运行会被取消。不再继续时把状态改为 `cancelled`,讨论和结果仍可查阅。
diff --git a/apps/mobile/app/(app)/[workspace]/issue/[id].tsx b/apps/mobile/app/(app)/[workspace]/issue/[id].tsx
index 91f2b8e4dc..01217a7bb1 100644
--- a/apps/mobile/app/(app)/[workspace]/issue/[id].tsx
+++ b/apps/mobile/app/(app)/[workspace]/issue/[id].tsx
@@ -33,6 +33,7 @@ import {
issueKeys,
issueTimelineOptions,
} from "@/data/queries/issues";
+import { ApiError } from "@/data/api";
import { useDeleteIssue } from "@/data/mutations/issues";
import { pinListOptions } from "@/data/queries/pins";
import { useCreatePin, useDeletePin } from "@/data/mutations/pins";
@@ -163,6 +164,12 @@ export default function IssueDetail() {
confirmDelete(issue, t, () =>
deleteIssue.mutate(issue.id, {
onSuccess: () => router.back(),
+ onError: (error) => Alert.alert(
+ t("delete.failed_title"),
+ error instanceof ApiError && error.status === 403
+ ? t("delete.permission_denied")
+ : t("delete.failed"),
+ ),
}),
);
}
diff --git a/apps/mobile/data/mutations/issues.test.ts b/apps/mobile/data/mutations/issues.test.ts
index 385e229431..8cbaa3e6bc 100644
--- a/apps/mobile/data/mutations/issues.test.ts
+++ b/apps/mobile/data/mutations/issues.test.ts
@@ -8,7 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { api } from "@/data/api";
import { appConfigOptions } from "@/data/queries/billing";
import { issueKeys } from "@/data/queries/issue-keys";
-import { useCancelTask, useDeleteComment } from "./issues";
+import { useCancelTask, useDeleteComment, useDeleteIssue } from "./issues";
const state = vi.hoisted(() => ({
qc: undefined as unknown as QueryClient,
@@ -43,6 +43,7 @@ vi.mock("@/data/api", () => ({
api: {
deleteComment: vi.fn(async () => undefined),
cancelTaskById: vi.fn(async () => undefined),
+ deleteIssue: vi.fn(async () => undefined),
},
}));
@@ -240,3 +241,59 @@ describe("useCancelTask", () => {
}
});
});
+
+describe("useDeleteIssue", () => {
+ const listKey = issueKeys.list(wsId);
+ const assignedKey = issueKeys.myList(wsId, "assigned", { assignee_id: "user-1" });
+ const createdKey = issueKeys.myList(wsId, "created", { creator_id: "user-1" });
+ const detailKey = issueKeys.detail(wsId, issueId);
+ const issue = { id: issueId, title: "Keep until deleted" } as Issue;
+ const other = { id: "issue-2" } as Issue;
+
+ beforeEach(() => {
+ state.qc = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
+ vi.mocked(api.deleteIssue).mockReset();
+ for (const key of [listKey, assignedKey, createdKey]) {
+ state.qc.setQueryData<Issue[]>(key, [issue, other]);
+ }
+ state.qc.setQueryData(detailKey, issue);
+ state.qc.setQueryData(timelineKey, [comment("comment-1")]);
+ state.qc.setQueryData(issueKeys.activeTasks(wsId, issueId), [{ id: "run-1" }]);
+ state.qc.setQueryData(issueKeys.tasks(wsId, issueId), [{ id: "run-1" }]);
+ state.qc.setQueryData(issueKeys.list("other-workspace"), [issue]);
+ });
+
+ it("keeps lists and details while pending, then clears them only after success", async () => {
+ let resolveDelete!: () => void;
+ vi.mocked(api.deleteIssue).mockReturnValueOnce(new Promise<void>((resolve) => { resolveDelete = resolve; }));
+ const pending = useDeleteIssue().mutateAsync(issueId);
+ await vi.waitFor(() => expect(api.deleteIssue).toHaveBeenCalledWith(issueId));
+ for (const key of [listKey, assignedKey, createdKey]) {
+ expect(state.qc.getQueryData(key)).toEqual([issue, other]);
+ }
+ expect(state.qc.getQueryData(detailKey)).toEqual(issue);
+ resolveDelete();
+ await pending;
+ for (const key of [listKey, assignedKey, createdKey]) {
+ expect(state.qc.getQueryData(key)).toEqual([other]);
+ }
+ for (const key of [detailKey, timelineKey, issueKeys.activeTasks(wsId, issueId), issueKeys.tasks(wsId, issueId)]) {
+ expect(state.qc.getQueryState(key)).toBeUndefined();
+ }
+ expect(state.qc.getQueryData(issueKeys.list("other-workspace"))).toEqual([issue]);
+ });
+
+ it.each([403, 500])("keeps all issue caches intact when deletion fails with %s", async (status) => {
+ const error = Object.assign(new Error("Delete rejected"), { status });
+ vi.mocked(api.deleteIssue).mockRejectedValueOnce(error);
+ await expect(useDeleteIssue().mutateAsync(issueId)).rejects.toBe(error);
+ for (const key of [listKey, assignedKey, createdKey]) {
+ expect(state.qc.getQueryData(key)).toEqual([issue, other]);
+ expect(state.qc.getQueryState(key)?.isInvalidated).toBe(false);
+ }
+ expect(state.qc.getQueryData(detailKey)).toEqual(issue);
+ expect(state.qc.getQueryData(timelineKey)).toEqual([comment("comment-1")]);
+ expect(state.qc.getQueryData(issueKeys.activeTasks(wsId, issueId))).toEqual([{ id: "run-1" }]);
+ expect(state.qc.getQueryData(issueKeys.tasks(wsId, issueId))).toEqual([{ id: "run-1" }]);
+ });
+});
diff --git a/apps/mobile/data/mutations/issues.ts b/apps/mobile/data/mutations/issues.ts
index 5e12aaaaff..deeb241f34 100644
--- a/apps/mobile/data/mutations/issues.ts
+++ b/apps/mobile/data/mutations/issues.ts
@@ -695,20 +695,8 @@ export function useCreateIssue() {
}
/**
- * Delete an issue. Mirrors `useDeleteProject` (mutations/projects.ts:103-128)
- * but the cache surface is wider:
- * - issueKeys.list(wsId) — workspace-wide flat list
- * - issueKeys.myList(wsId, ...) — three scopes × N filter combos
- *
- * Both are flat `Issue[]` caches. We use `setQueriesData` with the
- * `myAll(wsId)` prefix to filter the issue out of every `myList` key in one
- * pass, snapshot the previous data for rollback, and remove the detail /
- * timeline / tasks caches on settle so a stale return-trip can't surface
- * 404-y data.
- *
- * The WS `issue:deleted` event is already handled in `use-issue-realtime.ts`
- * (callers like the detail screen pass `() => router.back()`), so the other
- * tab/client case is covered.
+ * Keep the issue visible until the server confirms deletion. A rejected delete
+ * leaves list, detail, timeline and run caches intact for retry.
*/
export function useDeleteIssue() {
const qc = useQueryClient();
@@ -716,44 +704,25 @@ export function useDeleteIssue() {
return useMutation({
mutationFn: (id: string) => api.deleteIssue(id),
- onMutate: async (id) => {
+ onSuccess: async (_data, id) => {
const listKey = issueKeys.list(wsId);
const myAllKey = issueKeys.myAll(wsId);
await Promise.all([
qc.cancelQueries({ queryKey: listKey }),
qc.cancelQueries({ queryKey: myAllKey }),
]);
-
- // Snapshot every matching cache (flat list + each my-issues scope×filter)
- // so we can roll back per-key on error.
- const prevList = qc.getQueryData<Issue[]>(listKey);
- const prevMy = qc.getQueriesData<Issue[]>({ queryKey: myAllKey });
-
qc.setQueryData<Issue[]>(listKey, (old) =>
- old ? old.filter((i) => i.id !== id) : old,
+ old ? old.filter((issue) => issue.id !== id) : old,
);
qc.setQueriesData<Issue[]>({ queryKey: myAllKey }, (old) =>
- old ? old.filter((i) => i.id !== id) : old,
+ old ? old.filter((issue) => issue.id !== id) : old,
);
-
- return { prevList, prevMy, listKey, myAllKey };
- },
- onError: (_err, _id, ctx) => {
- if (!ctx) return;
- if (ctx.prevList !== undefined) {
- qc.setQueryData(ctx.listKey, ctx.prevList);
- }
- for (const [key, value] of ctx.prevMy) {
- qc.setQueryData(key, value);
- }
- },
- onSettled: (_data, _err, id) => {
- qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
- qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
qc.removeQueries({ queryKey: issueKeys.detail(wsId, id) });
qc.removeQueries({ queryKey: issueKeys.timeline(wsId, id) });
qc.removeQueries({ queryKey: issueKeys.activeTasks(wsId, id) });
qc.removeQueries({ queryKey: issueKeys.tasks(wsId, id) });
+ qc.invalidateQueries({ queryKey: listKey });
+ qc.invalidateQueries({ queryKey: myAllKey });
},
});
}
diff --git a/apps/mobile/locales/en/issues.json b/apps/mobile/locales/en/issues.json
index cda2b6e4e6..f56c85827e 100644
--- a/apps/mobile/locales/en/issues.json
+++ b/apps/mobile/locales/en/issues.json
@@ -134,6 +134,9 @@
"issue_actions": "Issue actions"
},
"delete": {
+ "failed_title": "Could not delete issue",
+ "permission_denied": "You don't have permission to delete this issue.",
+ "failed": "The issue could not be deleted. Please try again.",
"title": "Delete issue?",
"message": "{{identifier}} and its comments, reactions, and attachments will be permanently deleted. This cannot be undone."
},
diff --git a/apps/mobile/locales/zh-Hans/issues.json b/apps/mobile/locales/zh-Hans/issues.json
index 3be529a3d6..e6dcd8cc5b 100644
--- a/apps/mobile/locales/zh-Hans/issues.json
+++ b/apps/mobile/locales/zh-Hans/issues.json
@@ -132,6 +132,9 @@
"issue_actions": "任务操作"
},
"delete": {
+ "failed_title": "无法删除任务",
+ "permission_denied": "你没有删除此任务的权限。",
+ "failed": "任务未能删除,请重试。",
"title": "删除任务?",
"message": "{{identifier}} 及其评论、表情和附件将被永久删除,且无法撤销。"
},
diff --git a/apps/mobile/locales/zh-Hant/issues.json b/apps/mobile/locales/zh-Hant/issues.json
index 07154eb4ec..09fe3cfe37 100644
--- a/apps/mobile/locales/zh-Hant/issues.json
+++ b/apps/mobile/locales/zh-Hant/issues.json
@@ -132,6 +132,9 @@
"issue_actions": "任務操作"
},
"delete": {
+ "failed_title": "無法刪除任務",
+ "permission_denied": "你沒有刪除此任務的權限。",
+ "failed": "任務未能刪除,請重試。",
"title": "刪除任務?",
"message": "{{identifier}} 及其評論、表情和附件將被永久刪除,且無法撤銷。"
},
diff --git a/packages/core/issues/deletion-permissions.test.ts b/packages/core/issues/deletion-permissions.test.ts
new file mode 100644
index 0000000000..869f6b4874
--- /dev/null
+++ b/packages/core/issues/deletion-permissions.test.ts
@@ -0,0 +1,25 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { canDeleteIssue } from "./deletion-permissions";
+import type { MemberRole } from "../types";
+
+const agents = [{ id: "owned", owner_id: "me" }, { id: "other", owner_id: "someone" }];
+describe("issue deletion permissions", () => {
+ it.each([
+ ["member", "member", "me", true],
+ ["member", "member", "someone", false],
+ ["member", "agent", "owned", true],
+ ["member", "agent", "other", false],
+ ["member", "agent", "deleted", false],
+ ["owner", "member", "someone", true],
+ ["admin", "agent", "other", true],
+ ["admin", "agent", "deleted", true],
+ [null, "member", "me", false],
+ ["member", "unknown", "me", false],
+ ] as const)("role=%s creator=%s:%s allows=%s", (role, type, id, expected) => {
+ expect(canDeleteIssue({ creator_type: type as "member" | "agent", creator_id: id }, "me", role as MemberRole | null, agents)).toBe(expected);
+ });
+ it("does not grant former owners access after an agent changes owner", () => {
+ expect(canDeleteIssue({ creator_type: "agent", creator_id: "owned" }, "me", "member", [{ id: "owned", owner_id: "someone" }])).toBe(false);
+ });
+});
diff --git a/packages/core/issues/deletion-permissions.ts b/packages/core/issues/deletion-permissions.ts
new file mode 100644
index 0000000000..48e28df705
--- /dev/null
+++ b/packages/core/issues/deletion-permissions.ts
@@ -0,0 +1,20 @@
+import type { Agent, Issue, MemberRole } from "../types";
+
+// Mirrors the server rule. The server stays authoritative; this only decides
+// whether delete affordances are offered.
+export function canDeleteIssue(
+ issue: Pick<Issue, "creator_type" | "creator_id">,
+ userId: string | null,
+ role: MemberRole | null,
+ agents: readonly Pick<Agent, "id" | "owner_id">[],
+): boolean {
+ if (!userId || !role) return false;
+ if (role === "owner" || role === "admin") return true;
+ if (issue.creator_type === "member") return issue.creator_id === userId;
+ return (
+ issue.creator_type === "agent" &&
+ agents.some(
+ (agent) => agent.id === issue.creator_id && agent.owner_id === userId,
+ )
+ );
+}
diff --git a/packages/core/issues/use-issue-deletion.test.tsx b/packages/core/issues/use-issue-deletion.test.tsx
new file mode 100644
index 0000000000..5e093a890e
--- /dev/null
+++ b/packages/core/issues/use-issue-deletion.test.tsx
@@ -0,0 +1,54 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, renderHook } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import type { Issue } from "../types";
+import { workspaceKeys } from "../workspace/queries";
+import { useIssueDeletion } from "./use-issue-deletion";
+
+vi.mock("../auth", () => ({
+ useAuthStore: (select: (state: { user: { id: string } }) => unknown) =>
+ select({ user: { id: "me" } }),
+}));
+vi.mock("../api", () => ({
+ api: {
+ listMembers: vi.fn(),
+ listAgents: vi.fn(),
+ },
+}));
+afterEach(cleanup);
+
+function setup(role: string | null, agents: unknown[] = []) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ if (role) client.setQueryData(workspaceKeys.members("ws"), [{ user_id: "me", role }]);
+ client.setQueryData(workspaceKeys.agents("ws"), agents);
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ return renderHook(() => useIssueDeletion("ws"), { wrapper });
+}
+const issue = (type: "member" | "agent", id: string) => ({ creator_type: type, creator_id: id } as Issue);
+
+describe("useIssueDeletion", () => {
+ it("lets members delete only their own and their agents' issues", () => {
+ const { result } = setup("member", [
+ { id: "agent", owner_id: "me", archived_at: "2026-01-01" },
+ ]);
+ expect(result.current.canDelete(issue("member", "me"))).toBe(true);
+ expect(result.current.canDelete(issue("agent", "agent"))).toBe(true);
+ expect(result.current.canDelete(issue("member", "someone"))).toBe(false);
+ expect(result.current.canDelete(issue("agent", "missing"))).toBe(false);
+ });
+ it("allows admins to manage any issue, including orphaned agent issues", () => {
+ const { result } = setup("admin");
+ expect(result.current.canDelete(issue("member", "someone"))).toBe(true);
+ expect(result.current.canDelete(issue("agent", "missing"))).toBe(true);
+ });
+ it("offers no deletion until membership is known", () => {
+ const { result } = setup(null);
+ expect(result.current.canDelete(issue("member", "me"))).toBe(false);
+ });
+});
diff --git a/packages/core/issues/use-issue-deletion.ts b/packages/core/issues/use-issue-deletion.ts
new file mode 100644
index 0000000000..41d01a3bef
--- /dev/null
+++ b/packages/core/issues/use-issue-deletion.ts
@@ -0,0 +1,18 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { useCurrentMember } from "../permissions/use-current-member";
+import { agentListOptions } from "../workspace/queries";
+import type { Issue } from "../types";
+import { canDeleteIssue } from "./deletion-permissions";
+
+export function useIssueDeletion(wsId: string) {
+ const { userId, role } = useCurrentMember(wsId);
+ const { data: agents = [] } = useQuery({
+ ...agentListOptions(wsId),
+ enabled: role === "member",
+ });
+ return {
+ canDelete: (issue: Issue) => canDeleteIssue(issue, userId, role, agents),
+ };
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index b06572e337..3e3332000e 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -39,6 +39,7 @@
"./issue-workflows/hooks": "./issue-workflows/hooks.ts",
"./issue-workflows/mutations": "./issue-workflows/mutations.ts",
"./issues": "./issues/index.ts",
+ "./issues/use-issue-deletion": "./issues/use-issue-deletion.ts",
"./issues/batch": "./issues/batch.ts",
"./issues/canonical-id": "./issues/canonical-id.ts",
"./issues/queries": "./issues/queries.ts",
diff --git a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
index 6f1dd7cbd2..08f1a8f770 100644
--- a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
+++ b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx
@@ -13,6 +13,11 @@ const TEST_RESOURCES = { en: { common: enCommon, issues: enIssues } };
// Mocks — same pattern as the issue-detail test suite.
// ---------------------------------------------------------------------------
+const deletionPolicy = vi.hoisted(() => ({ allowed: true }));
+vi.mock("@multica/core/issues/use-issue-deletion", () => ({
+ useIssueDeletion: () => ({ canDelete: () => deletionPolicy.allowed }),
+}));
+
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
}));
@@ -193,6 +198,7 @@ function wrap(ui: React.ReactNode) {
}
beforeEach(() => {
+ deletionPolicy.allowed = true;
mockOpenModal.mockReset();
openInNewTabMock.mockReset();
getShareableUrlMock.mockClear();
@@ -330,6 +336,16 @@ describe("IssueActionsDropdown", () => {
expect(screen.queryByText("Remove parent issue")).not.toBeInTheDocument();
});
+ it("disables Delete issue when the user cannot delete the issue", async () => {
+ deletionPolicy.allowed = false;
+ render(wrap(<IssueActionsDropdown issue={mockIssue} trigger={<button data-testid="trigger">Menu</button>} />));
+ fireEvent.click(screen.getByTestId("trigger"));
+ const item = await screen.findByText("Delete issue");
+ expect(item.closest('[role="menuitem"]')).toHaveAttribute("aria-disabled", "true");
+ fireEvent.click(item);
+ expect(mockOpenModal).not.toHaveBeenCalled();
+ });
+
it("clicking Delete issue opens the delete-confirm modal", async () => {
render(
wrap(
diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsx
index cdf8f078cb..be3e746195 100644
--- a/packages/views/issues/actions/issue-actions-menu-items.tsx
+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx
@@ -25,6 +25,7 @@ import {
Unlink,
UserMinus,
} from "@multica/ui/icons";
+import { useIssueDeletion } from "@multica/core/issues/use-issue-deletion";
import type { AgentTask, Issue } from "@multica/core/types";
import { resolveWorkdirCopyTarget } from "@multica/core/issues";
import { todayDateOnly, addDaysDateOnly } from "@multica/core/issues/date";
@@ -133,6 +134,7 @@ export function IssueActionsMenuItems({
}: IssueActionsMenuItemsProps) {
const { t } = useT("issues");
const wsId = useWorkspaceId();
+ const { canDelete } = useIssueDeletion(wsId);
const sidebar = variant === "sidebar";
const statusLabel = useStatusLabel(wsId);
// Only the statuses the issue's workflow allows; entering a step that hands
@@ -505,6 +507,8 @@ export function IssueActionsMenuItems({
<P.Separator />
<P.Item
+ disabled={!canDelete(issue)}
+ title={!canDelete(issue) ? t(($) => $.batch.delete_restricted) : undefined}
variant="destructive"
onClick={() => openDeleteConfirm({ onDeletedFallbackPath })}
>
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 97cc77452c..5c13d2fb5a 100644
--- a/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
@@ -14,6 +14,11 @@ const selection = vi.hoisted(() => ({
select: vi.fn(),
deselect: vi.fn(),
}));
+const deletionPolicy = vi.hoisted(() => ({ allowed: true }));
+vi.mock("@multica/core/issues/use-issue-deletion", () => ({
+ useIssueDeletion: () => ({ canDelete: () => deletionPolicy.allowed }),
+}));
+
vi.mock("@multica/core/issues/stores/selection-store", () => ({
useIssueSelectionStore: (selector: (s: typeof selection) => unknown) => selector(selection),
}));
@@ -104,6 +109,7 @@ function makeIssue(overrides: Partial<Issue> = {}): Issue {
}
beforeEach(() => {
+ deletionPolicy.allowed = true;
selection.selectedIds = new Set(["a"]);
batchUpdate.mockClear();
batchDelete.mockClear();
@@ -157,6 +163,16 @@ describe("BatchActionToolbar status routing (MUL-4155)", () => {
});
});
+ it("disables deleting a selection containing an unauthorized issue", () => {
+ deletionPolicy.allowed = false;
+ render(<BatchActionToolbar issues={[makeIssue()]} />);
+ const button = screen.getByText("label", { selector: "button.text-destructive" });
+ expect(button).toBeDisabled();
+ fireEvent.click(button);
+ expect(screen.queryByRole("alertdialog")).not.toBeInTheDocument();
+ expect(batchDelete).not.toHaveBeenCalled();
+ });
+
it("opens the dedicated delete confirmation, not the run-confirm modal", () => {
render(<BatchActionToolbar issues={[makeIssue({ status: "todo" })]} />);
fireEvent.click(screen.getByText("label", { selector: "button.text-destructive" }));
diff --git a/packages/views/issues/components/batch-action-toolbar.test.tsx b/packages/views/issues/components/batch-action-toolbar.test.tsx
index dd95a9e06d..4c232f1a9f 100644
--- a/packages/views/issues/components/batch-action-toolbar.test.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.test.tsx
@@ -11,6 +11,11 @@ const selection = vi.hoisted(() => ({
clear: () => {},
}));
+const deletionPolicy = vi.hoisted(() => ({ allowed: true }));
+vi.mock("@multica/core/issues/use-issue-deletion", () => ({
+ useIssueDeletion: () => ({ canDelete: () => deletionPolicy.allowed }),
+}));
+
vi.mock("@multica/core/issues/stores/selection-store", () => ({
useIssueSelectionStore: (selector: (s: typeof selection) => unknown) =>
selector(selection),
@@ -121,6 +126,7 @@ function makeIssue(overrides: Partial<Issue> = {}): Issue {
}
beforeEach(() => {
+ deletionPolicy.allowed = true;
selection.selectedIds = new Set();
});
diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsx
index e4e80e99b2..f855771929 100644
--- a/packages/views/issues/components/batch-action-toolbar.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.tsx
@@ -15,6 +15,7 @@ import {
AlertDialogTitle,
} from "@multica/ui/components/ui/alert-dialog";
import { useQuery } from "@tanstack/react-query";
+import { useIssueDeletion } from "@multica/core/issues/use-issue-deletion";
import type { Issue, UpdateIssueRequest } from "@multica/core/types";
import { useWorkspaceId } from "@multica/core/hooks";
import { commonIssueFields } from "@multica/core/issues/batch";
@@ -96,6 +97,8 @@ export function BatchActionToolbar({
return first && selectedIssues.every((i) => i.project_id === first) ? first : null;
}, [selectedIssues]);
const wsId = useWorkspaceId();
+ const { canDelete } = useIssueDeletion(wsId);
+ const canDeleteSelection = selectedIssues.every(canDelete);
const { workflows } = useIssueWorkflows(wsId);
const { data: projects } = useQuery({ ...projectListOptions(wsId), enabled: count > 0 && !sharedProjectId });
const allowedStatuses = useMemo(
@@ -181,6 +184,7 @@ export function BatchActionToolbar({
};
const handleBatchDelete = async () => {
+ if (!canDeleteSelection) return;
try {
if (surfaceActions) {
await surfaceActions.batchDelete(ids);
@@ -251,7 +255,8 @@ export function BatchActionToolbar({
<Button
variant="ghost"
size="sm"
- disabled={loading}
+ disabled={loading || !canDeleteSelection}
+ title={!canDeleteSelection ? t(($) => $.batch.delete_restricted) : undefined}
onClick={() => setDeleteOpen(true)}
className="text-destructive hover:text-destructive"
>
@@ -268,14 +273,12 @@ export function BatchActionToolbar({
</AlertDialogTitle>
<AlertDialogDescription>
{t(($) => $.batch.delete_dialog_desc, { count })}
- <span className="mt-2 block text-caption text-muted-foreground">
- {t(($) => $.batch.delete_dialog_warning)}
- </span>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{t(($) => $.batch.cancel)}</AlertDialogCancel>
<AlertDialogAction
+ disabled={loading || !canDeleteSelection}
onClick={handleBatchDelete}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 2b5693ec34..a632303597 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -938,6 +938,7 @@
"confirm": "Stop run"
},
"batch": {
+ "delete_restricted": "You can delete issues you created or that your agents created. Workspace owners and admins can delete any issue.",
"selected": "{{count}} selected",
"status": "Status",
"priority": "Priority",
@@ -955,7 +956,6 @@
"delete_dialog_title_other": "Delete {{count}} issues?",
"delete_dialog_desc_one": "This action cannot be undone. This will permanently delete the selected issue and all associated data.",
"delete_dialog_desc_other": "This action cannot be undone. This will permanently delete the selected issues and all associated data.",
- "delete_dialog_warning": "Any workspace member can delete issues.",
"cancel": "Cancel"
},
"card": {
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index be0119d3df..fd212bf548 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -938,6 +938,7 @@
"confirm": "Arrêter l'exécution"
},
"batch": {
+ "delete_restricted": "Vous pouvez supprimer les tâches créées par vous ou par vos agents. Les propriétaires et administrateurs peuvent supprimer toute tâche.",
"selected": "{{count}} sélectionnés",
"status": "Statut",
"priority": "Priorité",
@@ -955,7 +956,6 @@
"delete_dialog_title_other": "Supprimer {{count}} tâches ?",
"delete_dialog_desc_one": "Cette action est irréversible. La tâche sélectionnée et toutes ses données associées seront définitivement supprimées.",
"delete_dialog_desc_other": "Cette action est irréversible. Les tâches sélectionnées et toutes leurs données associées seront définitivement supprimées.",
- "delete_dialog_warning": "Tout membre de l'espace de travail peut supprimer des tâches.",
"cancel": "Annuler"
},
"card": {
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 315d6e5efb..4922f3600e 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -898,6 +898,7 @@
"confirm": "実行を停止"
},
"batch": {
+ "delete_restricted": "自分または所有するエージェントが作成したタスクを削除できます。ワークスペースの owner と admin はすべてのタスクを削除できます。",
"selected": "{{count}} 件選択中",
"status": "ステータス",
"priority": "優先度",
@@ -910,7 +911,6 @@
"delete_failed": "タスクを削除できませんでした",
"delete_dialog_title_other": "タスク {{count}} 件を削除しますか?",
"delete_dialog_desc_other": "この操作は元に戻せません。選択したタスクと関連データがすべて完全に削除されます。",
- "delete_dialog_warning": "ワークスペースのメンバーであれば誰でもタスクを削除できます。",
"cancel": "キャンセル"
},
"card": {
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index d32d4e35d9..d11133910e 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -898,6 +898,7 @@
"confirm": "실행 중지"
},
"batch": {
+ "delete_restricted": "본인 또는 본인 소유 에이전트가 만든 태스크를 삭제할 수 있습니다. 워크스페이스 owner와 admin은 모든 태스크를 삭제할 수 있습니다.",
"selected": "{{count}}개 선택됨",
"status": "상태",
"priority": "우선순위",
@@ -910,7 +911,6 @@
"delete_failed": "태스크를 삭제하지 못했습니다",
"delete_dialog_title_other": "태스크 {{count}}개를 삭제할까요?",
"delete_dialog_desc_other": "이 작업은 되돌릴 수 없습니다. 선택한 태스크와 관련 데이터가 영구 삭제됩니다.",
- "delete_dialog_warning": "워크스페이스 멤버라면 누구나 태스크를 삭제할 수 있습니다.",
"cancel": "취소"
},
"card": {
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 84dabec649..c86a4e2d9f 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -898,6 +898,7 @@
"confirm": "停止运行"
},
"batch": {
+ "delete_restricted": "你可以删除本人或本人拥有的智能体创建的任务。工作区 owner 和 admin 可以删除任意任务。",
"selected": "已选择 {{count}} 个",
"status": "状态",
"priority": "优先级",
@@ -910,7 +911,6 @@
"delete_failed": "删除任务失败",
"delete_dialog_title_other": "删除 {{count}} 个任务?",
"delete_dialog_desc_other": "此操作无法撤销,所选任务及其全部关联数据都会被永久删除。",
- "delete_dialog_warning": "任何工作区成员都可以删除任务。",
"cancel": "取消"
},
"card": {
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index b2276ff633..e2bfaa63df 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -898,6 +898,7 @@
"confirm": "停止執行"
},
"batch": {
+ "delete_restricted": "你可以刪除本人或本人擁有的智慧體建立的任務。工作區 owner 和 admin 可以刪除任意任務。",
"selected": "已選擇 {{count}} 個",
"status": "狀態",
"priority": "優先順序",
@@ -910,7 +911,6 @@
"delete_failed": "刪除任務失敗",
"delete_dialog_title_other": "刪除 {{count}} 個任務?",
"delete_dialog_desc_other": "此操作無法撤銷,所選任務及其全部關聯資料都會被永久刪除。",
- "delete_dialog_warning": "任何工作區成員都可以刪除任務。",
"cancel": "取消"
},
"card": {
diff --git a/packages/views/search/host-dialogs.tsx b/packages/views/search/host-dialogs.tsx
index 05bccbc827..bdff62856c 100644
--- a/packages/views/search/host-dialogs.tsx
+++ b/packages/views/search/host-dialogs.tsx
@@ -96,9 +96,6 @@ function BatchDeleteDialog({
<AlertDialogTitle>{t(($) => $.batch.delete_dialog_title, { count })}</AlertDialogTitle>
<AlertDialogDescription>
{t(($) => $.batch.delete_dialog_desc, { count })}
- <span className="mt-2 block text-caption text-muted-foreground">
- {t(($) => $.batch.delete_dialog_warning)}
- </span>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index eb7e58ee89..c2f7f716f9 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -4455,6 +4455,9 @@ func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ if !h.requireIssueDeletion(w, r, issue.WorkspaceID, []db.Issue{issue}) {
+ return
+ }
h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)
// Fail any linked autopilot runs before delete (ON DELETE SET NULL clears issue_id).
@@ -5056,6 +5059,11 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {
seenIssueIDs[issueUUID] = struct{}{}
issues = append(issues, issue)
excludedIDs = append(excludedIDs, issue.ID)
+ }
+ if !h.requireIssueDeletion(w, r, wsUUID, issues) {
+ return
+ }
+ for _, issue := range issues {
h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)
_ = h.AutopilotService.FailAutopilotRunsByIssue(r.Context(), issue.ID)
}
diff --git a/server/internal/handler/issue_delete_permissions.go b/server/internal/handler/issue_delete_permissions.go
new file mode 100644
index 0000000000..5578ac6d2e
--- /dev/null
+++ b/server/internal/handler/issue_delete_permissions.go
@@ -0,0 +1,53 @@
+package handler
+
+import (
+ "net/http"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// requireIssueDeletion checks the entire selection before cancelling runs or
+// deleting any records. Owners and admins may delete any issue; members may
+// delete issues they created or that agents they currently own created; an
+// agent may delete only issues it created. Agent requests never inherit the
+// role or ownership rights of their token's user.
+func (h *Handler) requireIssueDeletion(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, issues []db.Issue) bool {
+ // Cloud PATs have a user but no bound agent. They cannot claim that user's
+ // deletion rights; only task tokens identify a machine creator reliably.
+ if isMachineCredentialActor(r) && r.Header.Get("X-Actor-Source") != "task_token" {
+ writeError(w, http.StatusForbidden, "issue deletion requires a human or a bound agent identity")
+ return false
+ }
+ wsID := uuidToString(workspaceID)
+ actorType, actorID := h.resolveActor(r, requestUserID(r), wsID)
+ if actorType == "member" {
+ member, ok := h.workspaceMember(w, r, wsID)
+ if !ok {
+ return false
+ }
+ if roleAllowed(member.Role, "owner", "admin") {
+ return true
+ }
+ }
+ ownedAgents := make(map[pgtype.UUID]bool)
+ for _, issue := range issues {
+ if issue.CreatorType == actorType && uuidToString(issue.CreatorID) == actorID {
+ continue
+ }
+ if actorType == "member" && issue.CreatorType == "agent" {
+ owned, checked := ownedAgents[issue.CreatorID]
+ if !checked {
+ agent, err := h.Queries.GetAgent(r.Context(), issue.CreatorID)
+ owned = err == nil && agent.WorkspaceID == workspaceID && uuidToString(agent.OwnerID) == actorID
+ ownedAgents[issue.CreatorID] = owned
+ }
+ if owned {
+ continue
+ }
+ }
+ writeError(w, http.StatusForbidden, "issue deletion is restricted to its creator, the creating agent's owner, and workspace owners or admins")
+ return false
+ }
+ return true
+}
diff --git a/server/internal/handler/issue_delete_permissions_test.go b/server/internal/handler/issue_delete_permissions_test.go
new file mode 100644
index 0000000000..0b2a540a0b
--- /dev/null
+++ b/server/internal/handler/issue_delete_permissions_test.go
@@ -0,0 +1,113 @@
+package handler
+
+import (
+ "net/http"
+ "strconv"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func TestIssueDeletionPermissions(t *testing.T) {
+ for _, tc := range []struct {
+ name, role, actor, creator string
+ allowed bool
+ }{
+ {"cloud PAT denied admin rights", "admin", "cloud", "other", false},
+ {"cloud PAT denied owner rights", "owner", "cloud", "other", false},
+ {"cloud PAT denied member ownership", "member", "cloud", "self", false},
+ {"cloud PAT denied agent ownership", "owner", "cloud", "owned-agent", false},
+ {"member deletes own", "member", "member", "self", true},
+ {"member denied others", "member", "member", "other", false},
+ {"member deletes own agent issue", "member", "member", "owned-agent", true},
+ {"member denied other agent issue", "member", "member", "other-agent", false},
+ {"owner deletes others", "owner", "member", "other", true},
+ {"admin deletes others", "admin", "member", "other", true},
+ {"agent deletes own", "member", "agent", "owned-agent", true},
+ {"agent denied human issue", "owner", "agent", "self", false},
+ {"agent denied sibling issue", "owner", "agent", "other-agent", false},
+ {"member denied missing agent", "member", "member", "missing-agent", false},
+ {"admin deletes missing agent issue", "admin", "member", "missing-agent", true},
+ } {
+ for _, batch := range []bool{false, true} {
+ t.Run(tc.name+"/batch="+strconv.FormatBool(batch), func(t *testing.T) {
+ ws := dbfx.Workspace(t, "deletion permissions", "delete-"+uuid.NewString())
+ dbfx.Member(t, ws, testUserID, tc.role)
+ agent := dbfx.Agent(t, "own agent", "", testutil.Cols{"workspace_id": ws})
+ other := dbfx.User(t, "Other", "delete-"+uuid.NewString()+"@example.test")
+ otherAgent := dbfx.Agent(t, "other agent", "", testutil.Cols{"workspace_id": ws, "owner_id": other})
+ creatorType, creatorID := "member", testUserID
+ switch tc.creator {
+ case "other":
+ creatorID = other
+ case "owned-agent":
+ creatorType, creatorID = "agent", agent
+ case "other-agent":
+ creatorType, creatorID = "agent", otherAgent
+ case "missing-agent":
+ creatorType, creatorID = "agent", "00000000-0000-4000-8000-000000000001"
+ }
+ id := dbfx.Issue(t, "delete target", testutil.Cols{"workspace_id": ws, "creator_type": creatorType, "creator_id": creatorID})
+ req := withURLParam(newRequest(http.MethodDelete, "/api/issues/"+id, nil), "id", id)
+ req.Header.Set("X-Workspace-ID", ws)
+ if tc.actor == "agent" {
+ req.Header.Set("X-Actor-Source", "task_token")
+ req.Header.Set("X-Agent-ID", agent)
+ } else if tc.actor == "cloud" {
+ req.Header.Set("X-Actor-Source", "cloud_pat")
+ }
+ handler := testHandler.DeleteIssue
+ if batch {
+ req = newRequest(http.MethodPost, "/api/issues/batch-delete", map[string]any{"issue_ids": []string{id}})
+ req.Header.Set("X-Workspace-ID", ws)
+ if tc.actor == "agent" {
+ req.Header.Set("X-Actor-Source", "task_token")
+ req.Header.Set("X-Agent-ID", agent)
+ } else if tc.actor == "cloud" {
+ req.Header.Set("X-Actor-Source", "cloud_pat")
+ }
+ handler = testHandler.BatchDeleteIssues
+ }
+ want := http.StatusForbidden
+ if tc.allowed {
+ want = http.StatusNoContent
+ if batch {
+ want = http.StatusOK
+ }
+ }
+ testutil.Call(t, handler, req).Want(want)
+ count := dbfx.Count(t, "SELECT count(*) FROM issue WHERE id=$1", id)
+ if (count == 0) != tc.allowed {
+ t.Fatalf("remaining issues = %d, allowed = %v", count, tc.allowed)
+ }
+ })
+ }
+ }
+}
+
+func TestIssueDeletionBatchRejectsBeforeCancellingRuns(t *testing.T) {
+ ws := dbfx.Workspace(t, "batch deletion", "delete-"+uuid.NewString())
+ dbfx.Member(t, ws, testUserID, "member")
+ other := dbfx.User(t, "Other", "delete-"+uuid.NewString()+"@example.test")
+ owned := dbfx.Issue(t, "owned", testutil.Cols{"workspace_id": ws})
+ denied := dbfx.Issue(t, "denied", testutil.Cols{"workspace_id": ws, "creator_id": other})
+ runtime := dbfx.Runtime(t, "batch runtime", testutil.Cols{"workspace_id": ws})
+ agent := dbfx.Agent(t, "batch agent", runtime, testutil.Cols{"workspace_id": ws})
+ task := dbfx.Task(t, agent, testutil.Cols{"issue_id": owned, "runtime_id": runtime})
+ req := newRequest(http.MethodPost, "/api/issues/batch-delete", map[string]any{"issue_ids": []string{owned, denied}})
+ req.Header.Set("X-Workspace-ID", ws)
+ testutil.Call(t, testHandler.BatchDeleteIssues, req).Want(http.StatusForbidden)
+ if n := dbfx.Count(t, "SELECT count(*) FROM issue WHERE id = ANY($1::uuid[])", []string{owned, denied}); n != 2 {
+ t.Fatalf("remaining issues = %d", n)
+ }
+ var status string
+ dbfx.QueryRow(t, "SELECT status FROM agent_task_queue WHERE id=$1", task).Scan(&status)
+ if status != "queued" {
+ t.Fatalf("denied batch changed run to %s", status)
+ }
+ // Once the unauthorized entry is removed, the same endpoint remains usable.
+ req = newRequest(http.MethodPost, "/api/issues/batch-delete", map[string]any{"issue_ids": []string{owned}})
+ req.Header.Set("X-Workspace-ID", ws)
+ testutil.Call(t, testHandler.BatchDeleteIssues, req).Want(http.StatusOK)
+}