Skip to content

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

Go

fix(wakeups): only offer agents you can run when creating a wakeup (MUL-10082) (#11527)

Bohan Jiangde2c887163ad
diff --git a/apps/docs/content/docs/issue-wakeups.fr.mdx b/apps/docs/content/docs/issue-wakeups.fr.mdx
index b24648556f..99bcec38cf 100644
--- a/apps/docs/content/docs/issue-wakeups.fr.mdx
+++ b/apps/docs/content/docs/issue-wakeups.fr.mdx
@@ -25,7 +25,7 @@ Après **Quand**, choisissez une condition et complétez ce qu'elle demande : un
</Step>
<Step>
-Après **Réveiller**, choisissez l'agent. Si l'assigné de la tâche est un agent, il est déjà sélectionné. Seuls les agents liés à un runtime et que vous avez le droit d'exécuter sont proposés ; voir [Permissions et accès](/agents#permissions-et-accès).
+Après **Réveiller**, choisissez l'agent. Si l'assigné de la tâche est un agent que vous pouvez exécuter, il est déjà sélectionné. Seuls les agents liés à un runtime et que vous avez le droit d'exécuter sont proposés ; voir [Permissions et accès](/agents#permissions-et-accès).
</Step>
<Step>
diff --git a/apps/docs/content/docs/issue-wakeups.ja.mdx b/apps/docs/content/docs/issue-wakeups.ja.mdx
index 6570a2ddb7..0bc0f5379b 100644
--- a/apps/docs/content/docs/issue-wakeups.ja.mdx
+++ b/apps/docs/content/docs/issue-wakeups.ja.mdx
@@ -25,7 +25,7 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";
</Step>
<Step>
-**起こす**でエージェントを選びます。タスクの担当者がエージェントなら、最初から選ばれています。選べるのは、ランタイムに紐づいていて、あなたが実行する権限を持つエージェントだけです。[権限と Access](/agents#権限と-access) を参照してください。
+**起こす**でエージェントを選びます。タスクの担当者があなたが実行できるエージェントなら、最初から選ばれています。選べるのは、ランタイムに紐づいていて、あなたが実行する権限を持つエージェントだけです。[権限と Access](/agents#権限と-access) を参照してください。
</Step>
<Step>
diff --git a/apps/docs/content/docs/issue-wakeups.ko.mdx b/apps/docs/content/docs/issue-wakeups.ko.mdx
index bc1e48f020..4eba677f46 100644
--- a/apps/docs/content/docs/issue-wakeups.ko.mdx
+++ b/apps/docs/content/docs/issue-wakeups.ko.mdx
@@ -25,7 +25,7 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";
</Step>
<Step>
-**깨울 대상**에서 에이전트를 고릅니다. 태스크 담당자가 에이전트라면 이미 선택되어 있습니다. 런타임에 연결되어 있고 내가 실행할 권한이 있는 에이전트만 고를 수 있습니다. [권한과 Access](/agents#권한과-access)를 참고하세요.
+**깨울 대상**에서 에이전트를 고릅니다. 태스크 담당자가 내가 실행할 수 있는 에이전트라면 이미 선택되어 있습니다. 런타임에 연결되어 있고 내가 실행할 권한이 있는 에이전트만 고를 수 있습니다. [권한과 Access](/agents#권한과-access)를 참고하세요.
</Step>
<Step>
diff --git a/apps/docs/content/docs/issue-wakeups.mdx b/apps/docs/content/docs/issue-wakeups.mdx
index 5e1af02528..aecc28a20c 100644
--- a/apps/docs/content/docs/issue-wakeups.mdx
+++ b/apps/docs/content/docs/issue-wakeups.mdx
@@ -25,7 +25,7 @@ After **When**, choose a condition and fill in what it needs, such as a time, th
</Step>
<Step>
-After **Wake**, choose the agent. If the issue's assignee is an agent, it is already selected. You can only choose agents that are bound to a runtime and that you are allowed to run; see [Permissions and Access](/agents#permissions-and-access).
+After **Wake**, choose the agent. If the issue's assignee is an agent you can run, it is already selected. You can only choose agents that are bound to a runtime and that you are allowed to run; see [Permissions and Access](/agents#permissions-and-access).
</Step>
<Step>
diff --git a/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx b/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx
index 8864851311..aee24e8d0b 100644
--- a/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx
+++ b/apps/docs/content/docs/issue-wakeups.zh-Hant.mdx
@@ -25,7 +25,7 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";
</Step>
<Step>
-在**喚醒**後面選擇 AI 代理。任務負責人是 AI 代理時,這裡已經預選了它。只能選已繫結執行時、並且你有權限執行的 AI 代理,見[權限與 Access](/agents#權限與-access)。
+在**喚醒**後面選擇 AI 代理。任務負責人是你能執行的 AI 代理時,這裡已經預選了它。只能選已繫結執行時、並且你有權限執行的 AI 代理,見[權限與 Access](/agents#權限與-access)。
</Step>
<Step>
diff --git a/apps/docs/content/docs/issue-wakeups.zh.mdx b/apps/docs/content/docs/issue-wakeups.zh.mdx
index c34ce7b76b..961c98e2c5 100644
--- a/apps/docs/content/docs/issue-wakeups.zh.mdx
+++ b/apps/docs/content/docs/issue-wakeups.zh.mdx
@@ -25,7 +25,7 @@ import { WakeupDemo } from "@/components/demos/wakeup-demo";
</Step>
<Step>
-在**唤醒**后面选择智能体。任务负责人是智能体时,这里已经预选了它。只能选已绑定运行时、并且你有权限运行的智能体,见[权限与 Access](/agents#权限与-access)。
+在**唤醒**后面选择智能体。任务负责人是你能运行的智能体时,这里已经预选了它。只能选已绑定运行时、并且你有权限运行的智能体,见[权限与 Access](/agents#权限与-access)。
</Step>
<Step>
diff --git a/packages/views/issues/components/wakeup-create.test.tsx b/packages/views/issues/components/wakeup-create.test.tsx
index 46e2e4e1a0..4b07636ca8 100644
--- a/packages/views/issues/components/wakeup-create.test.tsx
+++ b/packages/views/issues/components/wakeup-create.test.tsx
@@ -7,6 +7,13 @@ import { WakeupCreate } from "./wakeup-create";
const create = vi.fn();
let assigneeAgent = "emacs";
+const authState = { user: { id: "user-j" } };
+const shared = { owner_id: "user-o", permission_mode: "public_to", invocation_targets: [{ target_type: "workspace", target_id: null }] };
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: Object.assign((select: (s: typeof authState) => unknown) => select(authState), {
+ getState: () => authState,
+ }),
+}));
vi.mock("./wakeup-condition-names", () => ({
useConditionNames: () => ({ status: (key: string) => key, label: () => undefined, property: () => undefined, actor: (_type: string, id: string) => id }),
}));
@@ -19,12 +26,14 @@ vi.mock("@tanstack/react-query", async (importOriginal) => ({
...(await importOriginal<typeof import("@tanstack/react-query")>()),
useQuery: ({ queryKey }: { queryKey: unknown[] }) => ({
data: JSON.stringify(queryKey).includes("members")
- ? [{ user_id: "user-j", name: "Jiayuan" }]
+ ? [{ user_id: "user-j", name: "Jiayuan", role: "admin" }]
: JSON.stringify(queryKey).includes("issue-detail")
? { id: "issue", assignee_type: "agent", assignee_id: assigneeAgent }
: [
- { id: "emacs", name: "Emacs", archived_at: null, runtime_id: "rt" },
- { id: "grok", name: "Grok", archived_at: null, runtime_id: "rt" },
+ { id: "emacs", name: "Emacs", archived_at: null, runtime_id: "rt", ...shared },
+ { id: "grok", name: "Grok", archived_at: null, runtime_id: "rt", ...shared },
+ // Someone else's private agent: even a workspace admin may not run it.
+ { id: "secret", name: "Secret", archived_at: null, runtime_id: "rt", owner_id: "user-o", permission_mode: "private", invocation_targets: [] },
],
}),
}));
@@ -132,6 +141,42 @@ describe("WakeupCreateForm", () => {
expect(screen.getByRole("alert")).toHaveTextContent("请选择要唤醒的智能体");
});
+ it("asks for an agent instead of preselecting an assignee this member cannot run", async () => {
+ await renderForm("secret");
+ expect(screen.getByRole("button", { name: /选择智能体/ })).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: /选择智能体/ }));
+ expect(await screen.findByText("Emacs")).toBeVisible();
+ expect(screen.queryByText("Secret")).toBeNull();
+ fireEvent.keyDown(document.activeElement ?? document.body, { key: "Escape" });
+ await chooseCondition("在某个时间");
+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "看一下 CI" } });
+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));
+ expect(screen.getByRole("alert")).toHaveTextContent("请选择要唤醒的智能体");
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it("points an agent refusal at the agent and keeps the draft", async () => {
+ create.mockRejectedValue(
+ new ApiError("wakeup permission denied: the agent cannot be run", 403, "Forbidden", { code: "wakeup_agent_not_invocable" }),
+ );
+ await renderForm();
+ await chooseCondition("在某个时间");
+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "看一下 CI" } });
+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));
+ expect(await screen.findByRole("alert")).toHaveTextContent("你无权运行这个智能体");
+ expect(screen.getByLabelText("唤醒后要做什么")).toHaveValue("看一下 CI");
+ expect(screen.getByRole("form", { name: "新建唤醒" })).toBeVisible();
+ });
+
+ it("does not blame rule management for another refusal on create", async () => {
+ create.mockRejectedValue(new ApiError("wakeup permission denied", 403, "Forbidden"));
+ await renderForm();
+ await chooseCondition("在某个时间");
+ fireEvent.change(screen.getByLabelText("唤醒后要做什么"), { target: { value: "看一下 CI" } });
+ fireEvent.click(screen.getByRole("button", { name: /创建/ }));
+ expect(await screen.findByRole("alert")).toHaveTextContent("无法创建唤醒,请检查设置后重试。");
+ });
+
it("gives a recurring check an end date and no timeout choice", async () => {
await renderForm();
await chooseCondition("定期检查");
diff --git a/packages/views/issues/components/wakeup-create.tsx b/packages/views/issues/components/wakeup-create.tsx
index 87709c1449..74a50b0677 100644
--- a/packages/views/issues/components/wakeup-create.tsx
+++ b/packages/views/issues/components/wakeup-create.tsx
@@ -23,6 +23,7 @@ import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { labelListOptions } from "@multica/core/labels/queries";
import { propertyListOptions } from "@multica/core/properties/queries";
import { isAgentRuntimeBound } from "@multica/core/agents";
+import { canAssignAgentToIssue, useCurrentMember } from "@multica/core/permissions";
import { ApiError } from "@multica/core/api";
import { agentListOptions, memberListOptions, squadListOptions } from "@multica/core/workspace/queries";
import { shortcutMatchesEvent, useShortcut } from "@multica/core/shortcuts";
@@ -163,13 +164,17 @@ export function WakeupCreateForm({
const text = useWakeupText();
const timezone = useViewingTimezone();
const id = useId();
- const [draft, setDraft] = useState(() => emptyWakeupDraft(defaultAgentId, timezone));
+ const [rawDraft, setDraft] = useState(() => emptyWakeupDraft(defaultAgentId, timezone));
const [error, setError] = useState("");
const create = useCreateIssueWakeup(workspaceId, issueId);
const sendShortcut = useShortcut("send");
- const { data: agents = [] } = useQuery(agentListOptions(workspaceId));
+ const agents = useRunnableAgents(workspaceId);
const { data: properties = [] } = useQuery(propertyListOptions(workspaceId));
const { data: issue } = useQuery(issueDetailOptions(workspaceId, issueId));
+ // The default is the issue's agent assignee, which may be an agent this
+ // member cannot run. Only a runnable agent counts as chosen, so the form
+ // asks for one up front instead of failing on submit.
+ const draft = agents.some((a) => a.id === rawDraft.agentId) ? rawDraft : { ...rawDraft, agentId: "" };
const update = (patch: Partial<WakeupDraft>) => {
setDraft((prev) => ({ ...prev, ...patch }));
setError("");
@@ -207,7 +212,14 @@ export function WakeupCreateForm({
setError(
code === "wakeup_capacity_exceeded"
? t(($) => $.wakeups.create.capacity_error)
- : text.error(err, t(($) => $.wakeups.create.error)),
+ : code === "wakeup_agent_not_invocable"
+ ? t(($) => $.wakeups.create.agent_error)
+ : // Any other refusal is about the rule's settings, such as a
+ // member or agent it waits on that left the workspace, not
+ // about managing a rule that does not exist yet.
+ err instanceof ApiError && err.status === 403
+ ? t(($) => $.wakeups.create.error)
+ : text.error(err, t(($) => $.wakeups.create.error)),
);
} finally {
onBusy?.(false);
@@ -244,6 +256,7 @@ export function WakeupCreateForm({
value={draft.agentId}
onChange={(agentId) => update({ agentId })}
placeholder={t(($) => $.wakeups.create.choose_agent)}
+ runnableOnly
/>
</div>
</div>
@@ -635,23 +648,44 @@ function useMatches() {
return { setFilter, matches };
}
+/**
+ * Agents this member can wake. The server refuses a wakeup whose agent is
+ * archived, has no runtime, or that the member may not invoke; the assignee
+ * picker lists agents by the same rule.
+ */
+function useRunnableAgents(workspaceId: string) {
+ const { data = [] } = useQuery(agentListOptions(workspaceId));
+ const { userId, role } = useCurrentMember(workspaceId);
+ return useMemo(
+ () =>
+ data.filter(
+ (a) => !a.archived_at && isAgentRuntimeBound(a) && canAssignAgentToIssue(a, { userId, role }).allowed,
+ ),
+ [data, userId, role],
+ );
+}
+
function AgentChoice({
workspaceId,
value,
onChange,
placeholder,
allowAny = false,
+ runnableOnly = false,
}: {
workspaceId: string;
value: string;
onChange: (id: string) => void;
placeholder: string;
allowAny?: boolean;
+ /** List only agents this member can wake; otherwise any unarchived agent. */
+ runnableOnly?: boolean;
}) {
const [open, setOpen] = useState(false);
const { setFilter, matches } = useMatches();
const { data = [] } = useQuery(agentListOptions(workspaceId));
- const agents = useMemo(() => data.filter((a) => !a.archived_at), [data]);
+ const runnable = useRunnableAgents(workspaceId);
+ const agents = useMemo(() => (runnableOnly ? runnable : data.filter((a) => !a.archived_at)), [runnableOnly, runnable, data]);
const selected = agents.find((a) => a.id === value);
const pick = (id: string) => {
onChange(id);
@@ -693,7 +727,6 @@ function AgentChoice({
<PickerItem
key={a.id}
selected={a.id === value}
- disabled={!allowAny && !isAgentRuntimeBound(a)}
onClick={() => pick(a.id)}
>
<ActorAvatar actorType="agent" actorId={a.id} size="sm" showStatusDot />
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index d275c0fd7e..2279aac04d 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -1448,6 +1448,7 @@
"cancel": "Cancel",
"error": "Could not create the wakeup. Check the settings and try again.",
"capacity_error": "This issue or workspace already has the maximum number of enabled wakeups.",
+ "agent_error": "You can't run this agent. Ask its owner for access, or choose another agent.",
"missing_condition": "Choose a condition.",
"missing_agent": "Choose an agent to wake.",
"missing_events": "Choose at least one event.",
diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.json
index 826caabf5c..25e3b8f6a2 100644
--- a/packages/views/locales/es/issues.json
+++ b/packages/views/locales/es/issues.json
@@ -1362,6 +1362,7 @@
"cancel": "Cancelar",
"error": "No se ha podido crear la activación. Revisa los ajustes e inténtalo de nuevo.",
"capacity_error": "Esta tarea o este espacio de trabajo ya tiene el máximo número de activaciones habilitadas.",
+ "agent_error": "No puedes ejecutar este agente. Pide acceso a su propietario o elige otro agente.",
"missing_condition": "Elige una condición.",
"missing_agent": "Elige un agente para activar.",
"missing_events": "Elige al menos un evento.",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 19e5c7e876..529222cab2 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -1448,6 +1448,7 @@
"cancel": "Annuler",
"error": "Impossible de créer le réveil. Vérifiez les réglages et réessayez.",
"capacity_error": "Cette tâche ou cet espace a atteint le nombre maximal de réveils actifs.",
+ "agent_error": "Vous ne pouvez pas exécuter cet agent. Demandez l’accès à son propriétaire ou choisissez un autre agent.",
"missing_condition": "Choisissez une condition.",
"missing_agent": "Choisissez l’agent à réveiller.",
"missing_events": "Choisissez au moins un événement.",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index b551de88d9..dcb317798e 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -1389,6 +1389,7 @@
"cancel": "キャンセル",
"error": "ウェイクアップを作成できませんでした。設定を確認して再試行してください。",
"capacity_error": "このタスクまたはワークスペースの有効なウェイクアップは上限に達しています。",
+ "agent_error": "このエージェントを実行する権限がありません。オーナーにアクセスを依頼するか、別のエージェントを選択してください。",
"missing_condition": "条件を選択してください。",
"missing_agent": "起こすエージェントを選択してください。",
"missing_events": "イベントを 1 つ以上選択してください。",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 6810dfe8ec..f4fe4ecf7d 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -1389,6 +1389,7 @@
"cancel": "취소",
"error": "웨이크업을 만들 수 없습니다. 설정을 확인하고 다시 시도하세요.",
"capacity_error": "이 태스크 또는 워크스페이스의 활성 웨이크업이 한도에 도달했습니다.",
+ "agent_error": "이 에이전트를 실행할 권한이 없습니다. 소유자에게 접근 권한을 요청하거나 다른 에이전트를 선택하세요.",
"missing_condition": "조건을 선택하세요.",
"missing_agent": "깨울 에이전트를 선택하세요.",
"missing_events": "이벤트를 하나 이상 선택하세요.",
diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.json
index ead02bb373..87c69b178e 100644
--- a/packages/views/locales/ru/issues.json
+++ b/packages/views/locales/ru/issues.json
@@ -1563,6 +1563,7 @@
"cancel": "Отмена",
"error": "Не удалось создать пробуждение. Проверьте настройки и попробуйте снова.",
"capacity_error": "В этой задаче или рабочем пространстве уже достигнут максимум включённых пробуждений.",
+ "agent_error": "Вы не можете запускать этого агента. Попросите доступ у его владельца или выберите другого агента.",
"missing_condition": "Выберите условие.",
"missing_agent": "Выберите агента для пробуждения.",
"missing_events": "Выберите хотя бы одно событие.",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 8a9813da0a..96451b4b39 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -1389,6 +1389,7 @@
"cancel": "取消",
"error": "无法创建唤醒,请检查设置后重试。",
"capacity_error": "此任务或工作区开启的唤醒已达上限。",
+ "agent_error": "你无权运行这个智能体。请联系它的所有者开通权限,或选择其他智能体。",
"missing_condition": "请选择条件。",
"missing_agent": "请选择要唤醒的智能体。",
"missing_events": "请至少选择一个事件。",
diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.json
index 0c88c8b577..eb1979fc29 100644
--- a/packages/views/locales/zh-Hant/issues.json
+++ b/packages/views/locales/zh-Hant/issues.json
@@ -1389,6 +1389,7 @@
"cancel": "取消",
"error": "無法建立喚醒,請檢查設定後重試。",
"capacity_error": "此任務或工作區開啟的喚醒已達上限。",
+ "agent_error": "你無權執行這個 AI 代理。請聯絡它的擁有者開通權限,或選擇其他 AI 代理。",
"missing_condition": "請選擇條件。",
"missing_agent": "請選擇要喚醒的 AI 代理。",
"missing_events": "請至少選擇一個事件。",
diff --git a/server/internal/handler/issue_wakeup.go b/server/internal/handler/issue_wakeup.go
index 4e1c2f476b..50ebe06d32 100644
--- a/server/internal/handler/issue_wakeup.go
+++ b/server/internal/handler/issue_wakeup.go
@@ -120,6 +120,8 @@ func wakeupError(w http.ResponseWriter, err error) {
writeError(w, 409, err.Error())
case errors.Is(err, service.ErrWakeupInput):
writeError(w, 400, err.Error())
+ case errors.Is(err, service.ErrWakeupAgentNotInvocable):
+ writeErrorCode(w, 403, "wakeup_agent_not_invocable", err.Error())
case errors.Is(err, service.ErrWakeupForbidden):
writeError(w, 403, "wakeup permission denied")
case errors.Is(err, pgx.ErrNoRows):
diff --git a/server/internal/handler/issue_wakeup_test.go b/server/internal/handler/issue_wakeup_test.go
index 429779d39f..ea810b528e 100644
--- a/server/internal/handler/issue_wakeup_test.go
+++ b/server/internal/handler/issue_wakeup_test.go
@@ -102,6 +102,43 @@ func TestIssueWakeupAPIAndTrustedOrigin(t *testing.T) {
}
}
+// A refusal caused by the agent carries its own code, so the form can point
+// at the agent; other refusals keep the plain 403.
+func TestCreateIssueWakeupAgentNotInvocableCode(t *testing.T) {
+ issue := dbfx.Issue(t, "wake private agent")
+ owner := dbfx.User(t, "wake agent owner", "[email protected]")
+ dbfx.Member(t, testWorkspaceID, owner, "member")
+ private := dbfx.Agent(t, "someone else's private agent", testRuntimeID, testutil.Cols{"owner_id": owner})
+ runnable := dbfx.Agent(t, "wake runnable agent", testRuntimeID)
+ dbfx.Cleanup(t, "DELETE FROM issue_wakeup WHERE issue_id=$1", issue)
+ for _, tc := range []struct {
+ name string
+ body map[string]any
+ code string
+ }{
+ {"private agent", map[string]any{"agent_id": private, "kind": "at", "after_seconds": 600, "instruction": "check"}, "wakeup_agent_not_invocable"},
+ {"unknown agent", map[string]any{"agent_id": "00000000-0000-0000-0000-000000000001", "kind": "at", "after_seconds": 600, "instruction": "check"}, "wakeup_agent_not_invocable"},
+ {"departed reply actor", map[string]any{"agent_id": runnable, "kind": "event", "event_types": []string{"comment.created"}, "filter_actor_type": "member", "filter_actor_id": "00000000-0000-0000-0000-000000000002", "instruction": "check"}, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ testHandler.CreateIssueWakeup(rec, withURLParam(newRequest("POST", "/", tc.body), "id", issue))
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
+ }
+ var body struct {
+ Code string `json:"code"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatal(err)
+ }
+ if body.Code != tc.code {
+ t.Fatalf("code = %q, want %q", body.Code, tc.code)
+ }
+ })
+ }
+}
+
func TestWorkspaceWakeupSummariesScopeAndBounds(t *testing.T) {
issue := dbfx.Issue(t, "wakeup summary")
agent := dbfx.Agent(t, "summary target", testRuntimeID)
diff --git a/server/internal/service/issue_wakeup.go b/server/internal/service/issue_wakeup.go
index 6eebc6cc1f..92db4073bc 100644
--- a/server/internal/service/issue_wakeup.go
+++ b/server/internal/service/issue_wakeup.go
@@ -25,6 +25,11 @@ var ErrWakeupInput = errors.New("invalid wakeup")
var ErrWakeupConflict = errors.New("wakeup changed; refresh and retry")
var ErrWakeupForbidden = errors.New("wakeup permission denied")
+// ErrWakeupAgentNotInvocable is the ErrWakeupForbidden case where the rule's
+// agent is missing, archived, has no runtime, or may not be run by the member,
+// so a client can point the user at the agent instead of at the rule.
+var ErrWakeupAgentNotInvocable = fmt.Errorf("%w: the agent cannot be run", ErrWakeupForbidden)
+
// WakeupEventTypes is independent of plugin availability. These facts have
// transactional capture into matching receipts, including non-HTTP writers.
var WakeupEventTypes = eventcontract.WakeupTypes
@@ -322,7 +327,7 @@ func (s *IssueWakeupService) EditInstruction(ctx context.Context, issueID, id, m
}
agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: w.AgentID, WorkspaceID: issue.WorkspaceID})
if err != nil {
- return ErrWakeupForbidden
+ return ErrWakeupAgentNotInvocable
}
if err = s.authorize(ctx, q, issue.WorkspaceID, member, agent); err != nil {
return err
@@ -469,7 +474,7 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,
}
agent, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: agentID, WorkspaceID: issue.WorkspaceID})
if err != nil {
- return out, ErrWakeupForbidden
+ return out, ErrWakeupAgentNotInvocable
}
if err = s.authorize(ctx, q, issue.WorkspaceID, member, agent); err != nil {
return out, err
@@ -632,7 +637,7 @@ func (s *IssueWakeupService) save(ctx context.Context, issueID, member, source,
}
func (s *IssueWakeupService) authorize(ctx context.Context, q *db.Queries, ws, member pgtype.UUID, a db.Agent) error {
- if !member.Valid || a.ArchivedAt.Valid || !a.RuntimeID.Valid {
+ if !member.Valid {
return ErrWakeupForbidden
}
if _, err := q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: member, WorkspaceID: ws}); err != nil {
@@ -641,8 +646,8 @@ func (s *IssueWakeupService) authorize(ctx context.Context, q *db.Queries, ws, m
}
return err
}
- if !CanMemberInvokeAgent(ctx, q, a, member, ws) {
- return ErrWakeupForbidden
+ if a.ArchivedAt.Valid || !a.RuntimeID.Valid || !CanMemberInvokeAgent(ctx, q, a, member, ws) {
+ return ErrWakeupAgentNotInvocable
}
return nil
}