Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agents): align private-agent invoke surfaces with the owner-only contract (MUL-6380) (#7202)
Bohan Jiangc2474e2fe139
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsxindex 61e2696e24..dffedde497 100644--- a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx@@ -50,6 +50,7 @@ import {hideQueuedChatMessages,removePendingChatTask,} from "@multica/core/chat/pending";+import { canAssignAgentToIssue } from "@multica/core/permissions";import { api } from "@/data/api";import { useAuthStore } from "@/data/auth-store";import { useWorkspaceStore } from "@/data/workspace-store";@@ -77,8 +78,8 @@ import {invalidatePendingTask,seedAcceptedPendingTask,} from "@/data/realtime/chat-ws-updaters";-import { canAssignAgent } from "@/lib/can-assign-agent";import { useWorkspaceAgentAvailability } from "@/lib/workspace-agent-availability";+import { sendFailureMessage } from "@/lib/dispatch-reason";import { useAgentPresence } from "@/lib/use-agent-presence";import { Header } from "@/components/ui/header";import { ChatTitleButton } from "@/components/chat/chat-title-button";@@ -154,14 +155,22 @@ export default function ChatTab() {// ── Derived ────────────────────────────────────────────────────────────const memberRole = useMemo(- () => members.find((m) => m.user_id === userId)?.role,+ () => members.find((m) => m.user_id === userId)?.role ?? null,[members, userId],);+ // The picker must list only agents this user can actually TRIGGER — sending+ // a message enqueues a run, so it clears the server's invoke gate+ // (`canInvokeAgent`), which has no admin bypass. Shared rule, not a mobile+ // copy: a local mirror drifted from it and let admins pick a teammate's+ // personal agent only to be 403'd on send (MUL-6380 / GH #7180).const availableAgents = useMemo(() =>agents.filter(- (a) => !a.archived_at && canAssignAgent(a, userId, memberRole),+ (a) =>+ !a.archived_at &&+ canAssignAgentToIssue(a, { userId: userId ?? null, role: memberRole })+ .allowed,),[agents, userId, memberRole],);@@ -183,6 +192,20 @@ export default function ChatTab() {return availableAgents[0] ?? null;}, [selectedAgentId, availableAgents, activeSession, agents]);+ // A session outlives the permission that created it: the agent can be flipped+ // to personal, change owner, or drop this member from its allow-list, and the+ // server then refuses every send with `invocation_not_allowed` while still+ // serving the transcript (MUL-4525 — read uses the view gate, send re-runs the+ // invoke gate). `currentAgent` deliberately resolves an open session's agent+ // from the FULL list so the header stays honest, which means the picker filter+ // above cannot cover this case — judge the bound agent too (MUL-6380).+ const accessRevoked =+ currentAgent !== null &&+ !canAssignAgentToIssue(currentAgent, {+ userId: userId ?? null,+ role: memberRole,+ }).allowed;+const availability = useWorkspaceAgentAvailability();const presenceDetail = useAgentPresence(wsId, currentAgent?.id);const presenceAvailability =@@ -259,6 +282,16 @@ export default function ChatTab() {options: { clearDraft?: boolean } = {},) => {if (!currentAgent) return;+ // Invoke permission was revoked while this session was open — the server+ // would refuse before persisting anything. The composer is disabled in+ // this state; this is the belt-and-braces guard.+ if (accessRevoked) {+ Alert.alert(+ "No permission to run this agent",+ "You no longer have permission to run this agent, so the message was not sent. Ask its owner for access.",+ );+ return;+ }if (!runtimeBound) {Alert.alert("Runtime required",@@ -268,7 +301,16 @@ export default function ChatTab() {}const isNewSession = !activeSessionId;- const sessionId = await ensureSession(content);+ let sessionId: string | null;+ try {+ sessionId = await ensureSession(content);+ } catch (err) {+ // Session create runs the same invoke gate as a send, so a permission+ // change refuses here too — and this is the only layer that sees the+ // reason code (MUL-6380).+ Alert.alert("Message not sent", sendFailureMessage(err));+ throw err;+ }if (!sessionId) return;const sentAt = new Date().toISOString();@@ -345,12 +387,17 @@ export default function ChatTab() {chatKeys.pendingTask(sessionId),(old) => removePendingChatTask(old, optimisticTaskId),);+ // The composer restores the draft on a thrown rejection but says nothing+ // about it, so a revoked-permission 403 used to read as a silent no-op+ // (MUL-6380). Name the cause here: only this layer sees the error body.+ Alert.alert("Message not sent", sendFailureMessage(err));throw err;}},[activeSessionId,currentAgent,+ accessRevoked,runtimeBound,ensureSession,qc,@@ -423,18 +470,21 @@ export default function ChatTab() {// ── Composer disabled-state ────────────────────────────────────────────const disabled =!currentAgent ||+ accessRevoked ||availability === "none" ||isArchived === true ||!runtimeBound;const disabledReason = !currentAgent? "No agent selected"- : availability === "none"- ? "No agents in this workspace"- : isArchived- ? "This chat is archived"- : !runtimeBound- ? "Agent needs a runtime"- : undefined;+ : accessRevoked+ ? "You can no longer run this agent"+ : availability === "none"+ ? "No agents in this workspace"+ : isArchived+ ? "This chat is archived"+ : !runtimeBound+ ? "Agent needs a runtime"+ : undefined;return (<View className="flex-1 bg-background">diff --git a/apps/mobile/components/chat/agent-picker-sheet.tsx b/apps/mobile/components/chat/agent-picker-sheet.tsxindex 66805a26da..27f3af300c 100644--- a/apps/mobile/components/chat/agent-picker-sheet.tsx+++ b/apps/mobile/components/chat/agent-picker-sheet.tsx@@ -5,8 +5,8 @@* sheet and goes straight to the blank state for that agent.** Filtering is delegated to the caller (the screen passes a pre-filtered- * `agents` list) so the same filter logic — archived + canAssignAgent +- * order — stays in one place.+ * `agents` list) so the same filter logic — archived + canAssignAgentToIssue+ * + order — stays in one place.** Layout mirrors `components/issue/my-issues-filter-sheet.tsx`: transparent* Modal + dimmed backdrop + centered card. Bottom-sheet anchoring would bediff --git a/apps/mobile/lib/can-assign-agent.ts b/apps/mobile/lib/can-assign-agent.tsdeleted file mode 100644index 1770e23f78..0000000000--- a/apps/mobile/lib/can-assign-agent.ts+++ /dev/null@@ -1,40 +0,0 @@-/**- * Mobile-owned mirror of the boolean shim- * `packages/views/issues/components/pickers/assignee-picker.tsx:canAssignAgent`- * — which in turn forwards to `packages/core/permissions/rules.ts:canAssignAgentToIssue`.- *- * We mirror (not import) per the apps/mobile/CLAUDE.md sharing rule: only- * `import type` from @multica/core; logic is duplicated to keep mobile- * independent. Any rule change must be applied here too.- *- * Rule (mirrors backend `server/internal/handler/issue.go:1471-1490`):- * - Workspace-visibility agents → assignable by any workspace member- * - Private agents → only owner + workspace admins/owners- *- * Used by the chat agent picker to filter "agents I can talk to" and by- * NoAgentBanner to detect the all-zero state.- */-import type { Agent } from "@multica/core/types";--type MemberRoleLike = "owner" | "admin" | "member" | null | undefined;--export function canAssignAgent(- agent: Agent,- userId: string | undefined | null,- memberRole: MemberRoleLike,-): boolean {- if (!userId) return false;-- const role: MemberRoleLike =- memberRole === "owner" || memberRole === "admin" || memberRole === "member"- ? memberRole- : null;-- if (agent.visibility === "workspace") {- return role !== null;- }- // visibility === "private" (or anything else — treat unknown as private,- // which is the safer side of an enum drift).- if (role === "owner" || role === "admin") return true;- return agent.owner_id !== null && agent.owner_id === userId;-}diff --git a/apps/mobile/lib/dispatch-reason.test.ts b/apps/mobile/lib/dispatch-reason.test.tsnew file mode 100644index 0000000000..dfbf85a445--- /dev/null+++ b/apps/mobile/lib/dispatch-reason.test.ts@@ -0,0 +1,53 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { dispatchReasonCode, sendFailureMessage } from "./dispatch-reason";++// Shaped like `apps/mobile/data/api.ts:ApiError` — a thrown Error carrying the+// parsed response body. Built inline rather than imported because `@/data/api`+// pulls react-native into a node-environment suite; the only field under test+// is `body`, which is what the helper reads.+const apiError = (body: unknown) => Object.assign(new Error("request failed"), { body });++describe("dispatchReasonCode", () => {+ it("reads reason_code off a structured rejection body", () => {+ const err = apiError({+ error: "invocation not allowed",+ reason_code: "invocation_not_allowed",+ });+ expect(dispatchReasonCode(err)).toBe("invocation_not_allowed");+ });++ it("returns undefined for an unstructured failure", () => {+ expect(dispatchReasonCode(new Error("network down"))).toBeUndefined();+ expect(dispatchReasonCode(apiError(undefined))).toBeUndefined();+ expect(dispatchReasonCode(apiError("plain text body"))).toBeUndefined();+ expect(dispatchReasonCode(null)).toBeUndefined();+ });++ it("ignores a non-string or empty reason_code", () => {+ expect(dispatchReasonCode(apiError({ reason_code: 7 }))).toBeUndefined();+ expect(dispatchReasonCode(apiError({ reason_code: "" }))).toBeUndefined();+ });+});++describe("sendFailureMessage", () => {+ // The point of the helper: a revoked permission must not read as a transient+ // failure the user should retry (MUL-6380).+ it("names revoked permission instead of suggesting a retry", () => {+ const message = sendFailureMessage(+ apiError({ reason_code: "invocation_not_allowed" }),+ );+ expect(message).toMatch(/no longer have permission/i);+ expect(message).not.toMatch(/try again/i);+ });++ it("names the runtime for agent_runtime_required", () => {+ expect(+ sendFailureMessage(apiError({ reason_code: "agent_runtime_required" })),+ ).toMatch(/runtime/i);+ });++ it("falls back to a retryable message for anything else", () => {+ expect(sendFailureMessage(new Error("timeout"))).toMatch(/try again/i);+ });+});diff --git a/apps/mobile/lib/dispatch-reason.ts b/apps/mobile/lib/dispatch-reason.tsnew file mode 100644index 0000000000..da0d192c08--- /dev/null+++ b/apps/mobile/lib/dispatch-reason.ts@@ -0,0 +1,34 @@+/**+ * Mobile-owned mirror of `packages/core/api/client.ts:dispatchReasonCode`.+ *+ * Why mirror instead of import: the core version narrows on core's own+ * `ApiError` class, and mobile throws `apps/mobile/data/api.ts:ApiError` — a+ * different constructor, so `instanceof` never matches across the two. The+ * extraction itself is identical: read the stable `reason_code` the admission+ * gate puts on a structured rejection body.+ */+export function dispatchReasonCode(err: unknown): string | undefined {+ const body = (err as { body?: unknown } | null)?.body;+ if (body && typeof body === "object") {+ const code = (body as { reason_code?: unknown }).reason_code;+ if (typeof code === "string" && code.length > 0) return code;+ }+ return undefined;+}++/**+ * User-facing sentence for a refused send. `invocation_not_allowed` is the+ * revoked-permission case (MUL-4525): the session was created while the user+ * could run the agent and the server now refuses, so it must not read as a+ * transient failure the user should retry.+ */+export function sendFailureMessage(err: unknown): string {+ switch (dispatchReasonCode(err)) {+ case "invocation_not_allowed":+ return "You no longer have permission to run this agent, so the message was not sent.";+ case "agent_runtime_required":+ return "Bind a runtime to this agent before sending a message.";+ default:+ return "Your message could not be sent. Please try again.";+ }+}diff --git a/apps/mobile/lib/workspace-agent-availability.ts b/apps/mobile/lib/workspace-agent-availability.tsindex 88ef4ad8ab..283652fe1e 100644--- a/apps/mobile/lib/workspace-agent-availability.ts+++ b/apps/mobile/lib/workspace-agent-availability.ts@@ -11,11 +11,11 @@* mount.*/import { useQuery } from "@tanstack/react-query";+import { canAssignAgentToIssue } from "@multica/core/permissions";import { useAuthStore } from "@/data/auth-store";import { useWorkspaceStore } from "@/data/workspace-store";import { agentListOptions } from "@/data/queries/agents";import { memberListOptions } from "@/data/queries/members";-import { canAssignAgent } from "./can-assign-agent";export type WorkspaceAgentAvailability = "loading" | "none" | "available";@@ -32,10 +32,12 @@ export function useWorkspaceAgentAvailability(): WorkspaceAgentAvailability {if (!agentsFetched || !membersFetched) return "loading";- const memberRole = members?.find((m) => m.user_id === userId)?.role;+ const role = members?.find((m) => m.user_id === userId)?.role ?? null;const hasVisibleAgent = (agents ?? []).some(- (a) => !a.archived_at && canAssignAgent(a, userId, memberRole),+ (a) =>+ !a.archived_at &&+ canAssignAgentToIssue(a, { userId: userId ?? null, role }).allowed,);return hasVisibleAgent ? "available" : "none";diff --git a/packages/core/agents/visibility-label.ts b/packages/core/agents/visibility-label.tsindex 007776ce54..ee2f64ead6 100644--- a/packages/core/agents/visibility-label.ts+++ b/packages/core/agents/visibility-label.ts@@ -2,8 +2,8 @@ import type { AgentVisibility } from "../types";/*** Display labels for agent visibility. The DB stores `private` as the value- * but the UI surface name is "Personal" — better matches what the field- * actually means now that workspace admins can also assign private agents.+ * but the UI surface name is "Personal" — it reads better next to "Workspace"+ * and matches the wording used in the access picker.*/export const VISIBILITY_LABEL: Record<AgentVisibility, string> = {workspace: "Workspace",@@ -11,19 +11,28 @@ export const VISIBILITY_LABEL: Record<AgentVisibility, string> = {};/**- * Honest descriptions for assignability. The previous "Only you can assign"- * text was a lie — workspace owners and admins can assign private agents too- * (server `issue.go:1471-1490`).+ * Descriptions for the visibility CHOICE (create dialog / picker), where+ * "Personal" is submitted as `permission_mode: "private"` — owner-only, with+ * no workspace-admin bypass since MUL-3963 (`canInvokeAgent` in+ * `server/internal/handler/agent_access.go`). The older+ * "…and workspace admins…" copy predates that gate and is no longer true.*/export const VISIBILITY_DESCRIPTION: Record<AgentVisibility, string> = {workspace: "All members can assign",- private: "Only you and workspace admins can assign",+ private: "Only you can assign",};-/** Tooltip suitable for read-only badges on hover/list rows. */+/**+ * Tooltip suitable for read-only badges on hover / list rows. Worded for an+ * EXISTING agent, where `visibility` is the lossy two-state projection of the+ * permission model: `private` covers both a truly owner-only agent and one+ * shared with specific people, so the copy names the owner's grants rather+ * than promising either extreme. It must not claim workspace admins can+ * assign — admins keep management + view access, not invocation.+ */export const VISIBILITY_TOOLTIP: Record<AgentVisibility, string> = {workspace: "Workspace — all members can assign",- private: "Personal — only you and workspace admins can assign",+ private: "Personal — only the owner and people they allow can assign",};export function visibilityLabel(v: AgentVisibility): string {diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsxindex 0cf66fe3e7..940580d4e5 100644--- a/packages/views/chat/chat-page.tsx+++ b/packages/views/chat/chat-page.tsx@@ -33,6 +33,7 @@ import { useChatController } from "./components/use-chat-controller";import { OfflineBanner } from "./components/offline-banner";import { NoAgentBanner } from "./components/no-agent-banner";import { ArchivedAgentBanner } from "./components/archived-agent-banner";+import { AgentAccessRevokedBanner } from "./components/agent-access-revoked-banner";import { RuntimeRequiredBanner } from "./components/runtime-required-banner";/**@@ -267,6 +268,7 @@ export function ChatPage() {!!c.pendingTaskId ||c.isSessionArchived ||c.isAgentArchived ||+ c.isAgentAccessRevoked ||!c.isAgentRuntimeBound ||c.noAgent}@@ -284,7 +286,9 @@ export function ChatPage() {<EmptyState agent={c.activeAgent} />)}- {c.noAgent ? (+ {c.isAgentAccessRevoked ? (+ <AgentAccessRevokedBanner agentName={c.activeAgent?.name} />+ ) : c.noAgent ? (<NoAgentBanner />) : c.isAgentArchived ? (<ArchivedAgentBanner agentName={c.activeAgent?.name} />@@ -301,6 +305,7 @@ export function ChatPage() {tasks={queuedTasks}headStatus={c.pendingTask?.status}onSendNow={c.handleSendQueuedTaskNow}+ sendNowDisabled={c.isAgentAccessRevoked}onEdit={c.handleEditQueuedTask}onRemove={c.handleRemoveQueuedTask}onClear={c.handleClearQueuedTasks}@@ -310,15 +315,19 @@ export function ChatPage() {onSend={c.handleSend}restoreDraftRequest={c.restoreDraftRequest}onRestoreDraftApplied={c.handleRestoreDraftApplied}- uploadEnabled={c.uploadEnabled}+ uploadEnabled={c.uploadEnabled && !c.isAgentAccessRevoked}onStop={c.handleStop}isRunning={!!c.pendingTaskId}allowSubmitWhileRunning={c.pendingTask?.supports_queue === true}disabled={- c.isSessionArchived || c.isAgentArchived || !c.isAgentRuntimeBound+ c.isSessionArchived ||+ c.isAgentArchived ||+ c.isAgentAccessRevoked ||+ !c.isAgentRuntimeBound}noAgent={c.noAgent}agentArchived={c.isAgentArchived}+ agentAccessRevoked={c.isAgentAccessRevoked}agentRuntimeRequired={!c.isAgentRuntimeBound}agentName={c.activeAgent?.name}projects={c.projects}diff --git a/packages/views/chat/components/agent-access-revoked-banner.tsx b/packages/views/chat/components/agent-access-revoked-banner.tsxnew file mode 100644index 0000000000..e430efc180--- /dev/null+++ b/packages/views/chat/components/agent-access-revoked-banner.tsx@@ -0,0 +1,30 @@+"use client";++import { Lock } from "lucide-react";+import { cn } from "@multica/ui/lib/utils";+import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";+import { useT } from "../../i18n";++// Sibling of ArchivedAgentBanner / OfflineBanner / NoAgentBanner, in the same+// banner slot above the chat input. Shown when the OPEN session's agent can no+// longer be invoked by this user — the agent was flipped to personal, its+// ownership moved, or the allow-list dropped them (MUL-6380).+//+// The transcript stays readable, because reading is gated by the softer view+// predicate; only running is gated by the invoke predicate the server re-checks+// on every send (MUL-4525). Without this banner the input looked live and the+// user learned about the change from a 403 after typing a message.+export function AgentAccessRevokedBanner({ agentName }: { agentName?: string }) {+ const { t } = useT("chat");+ const name = agentName?.trim() || t(($) => $.offline_banner.fallback_name);+ return (+ <div className={cn(CHAT_GUTTER, "mb-1.5")}>+ <div className={cn(CHAT_COLUMN, "flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-caption bg-muted text-muted-foreground ring-1 ring-border")}>+ <Lock className="size-3.5 shrink-0" />+ <span className="truncate">+ {t(($) => $.agent_access_revoked_banner, { name })}+ </span>+ </div>+ </div>+ );+}diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsxindex 19ea4db91c..4c104b530c 100644--- a/packages/views/chat/components/chat-input.test.tsx+++ b/packages/views/chat/components/chat-input.test.tsx@@ -1478,3 +1478,32 @@ describe("ChatInput send keeps composer focus", () => {expect(onStop).toHaveBeenCalledTimes(1);});});++// MUL-6380: the composer's placeholder is the only text on screen once the input+// is disabled, so it has to name the right reason. `agentAccessRevoked` wins over+// `noAgent` because both are true in the reported case — the workspace's only+// agent is the one this user may no longer run — and "create an agent" would then+// send them to build a second agent they do not need.+describe("ChatInput revoked-access placeholder", () => {+ it("names the revoked permission rather than the archived-session reason", () => {+ renderInput({ disabled: true, agentAccessRevoked: true });++ expect(editorProps.last?.placeholder).toBe(+ "You no longer have permission to run this agent",+ );+ });++ it("wins over noAgent when the revoked agent is the only one in the workspace", () => {+ renderInput({ disabled: true, agentAccessRevoked: true, noAgent: true });++ expect(editorProps.last?.placeholder).toBe(+ "You no longer have permission to run this agent",+ );+ });++ it("leaves the normal placeholder alone when access is intact", () => {+ renderInput({ agentName: "Multica" });++ expect(editorProps.last?.placeholder).toBe("Message Multica…");+ });+});diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsxindex 7e9bfefe7e..d261fac2bc 100644--- a/packages/views/chat/components/chat-input.tsx+++ b/packages/views/chat/components/chat-input.tsx@@ -99,6 +99,13 @@ interface ChatInputProps {* as opposed to the session itself being archived — swaps the placeholder* copy so the read-only reason reads accurately. */agentArchived?: boolean;+ /** True when `disabled` is because the caller may no longer INVOKE the bound+ * agent (flipped to personal, ownership moved, dropped from the allow-list).+ * Distinct from `noAgent`: an agent IS bound and its transcript is readable,+ * the caller just cannot run it (MUL-6380). Takes precedence over `noAgent`+ * in the placeholder — when the only agent in the workspace is the revoked+ * one, both are true and "create an agent" would be the wrong instruction. */+ agentAccessRevoked?: boolean;agentRuntimeRequired?: boolean;/** Name of the currently selected agent, used in the placeholder. */agentName?: string;@@ -141,6 +148,7 @@ export function ChatInput({disabled,noAgent,agentArchived,+ agentAccessRevoked,agentRuntimeRequired,agentName,leftAdornment,@@ -532,7 +540,9 @@ export function ChatInput({},});- const placeholder = noAgent+ const placeholder = agentAccessRevoked+ ? t(($) => $.input.placeholder_access_revoked)+ : noAgent? t(($) => $.input.placeholder_no_agent): disabled? agentArchiveddiff --git a/packages/views/chat/components/chat-queue.test.tsx b/packages/views/chat/components/chat-queue.test.tsxindex 01ee8881d3..11687a1fd7 100644--- a/packages/views/chat/components/chat-queue.test.tsx+++ b/packages/views/chat/components/chat-queue.test.tsx@@ -6,7 +6,7 @@ import { ChatQueue } from "./chat-queue";const TEST_RESOURCES = { en: { chat: enChat } };-function renderQueue(headStatus = "running") {+function renderQueue(headStatus = "running", sendNowDisabled = false) {const callbacks = {onSendNow: vi.fn<(taskId: string) => Promise<void>>().mockResolvedValue(),onEdit: vi.fn<(taskId: string) => Promise<void>>().mockResolvedValue(),@@ -17,6 +17,7 @@ function renderQueue(headStatus = "running") {<I18nProvider locale="en" resources={TEST_RESOURCES}><ChatQueueheadStatus={headStatus}+ sendNowDisabled={sendNowDisabled}tasks={[{task_id: "task-2",@@ -125,3 +126,27 @@ describe("ChatQueue", () => {expect(actions.onClear).toHaveBeenCalledTimes(1);});});++// MUL-6380: steering a queued message dispatches it now, so it has to clear the+// same invoke gate as a fresh send. When the caller has lost permission to run+// the agent, a live-looking Steer button just walks them into a 403.+describe("ChatQueue send-now gating", () => {+ it("blocks Steer when the caller may no longer invoke the agent", async () => {+ const { onSendNow } = renderQueue("running", true);++ // The label must state the real reason: "wait for the reply to start" would+ // send the user waiting for something waiting cannot fix.+ const steer = screen.getAllByRole("button", {+ name: "You no longer have permission to run this agent",+ })[0]!;+ expect(steer).toBeDisabled();+ fireEvent.click(steer);+ await waitFor(() => expect(onSendNow).not.toHaveBeenCalled());+ });++ it("leaves Steer available when the head task is dispatchable and permitted", () => {+ renderQueue("running", false);++ expect(screen.getAllByRole("button", { name: "Steer" })[0]!).not.toBeDisabled();+ });+});diff --git a/packages/views/chat/components/chat-queue.tsx b/packages/views/chat/components/chat-queue.tsxindex efe3950e3c..a936d656a9 100644--- a/packages/views/chat/components/chat-queue.tsx+++ b/packages/views/chat/components/chat-queue.tsx@@ -26,6 +26,10 @@ interface ChatQueueProps {tasks: ChatQueuedTask[];headStatus: string | undefined;onSendNow: (taskId: string) => Promise<void> | void;+ /** Blocks "send now" independently of the head task's status — used when the+ * caller may no longer invoke the agent, since steering a queued task+ * dispatches a run the server would refuse (MUL-6380). */+ sendNowDisabled?: boolean;onEdit: (taskId: string) => Promise<void> | void;onRemove: (taskId: string) => Promise<void> | void;onClear: () => Promise<void> | void;@@ -35,16 +39,28 @@ export function ChatQueue({tasks,headStatus,onSendNow,+ sendNowDisabled = false,onEdit,onRemove,onClear,}: ChatQueueProps) {const { t } = useT("chat");const [busyAction, setBusyAction] = useState<string | null>(null);- const canSendNow =+ const dispatchableHead =headStatus === "dispatched" ||headStatus === "running" ||headStatus === "waiting_local_directory";+ const canSendNow = !sendNowDisabled && dispatchableHead;+ // The two blocked states need different copy: "wait for the reply to start"+ // is actionable, "you cannot run this agent" is not — telling a user to wait+ // for something waiting cannot fix is the bug (MUL-6380).+ const sendNowLabel = t(($) =>+ canSendNow+ ? $.queue.steer+ : sendNowDisabled+ ? $.queue.steer_no_permission+ : $.queue.steer_unavailable,+ );if (tasks.length === 0) return null;@@ -109,20 +125,14 @@ export function ChatQueue({<div className="flex shrink-0 items-center gap-0.5"><spanclassName="shrink-0"- title={t(($) =>- canSendNow ? $.queue.steer : $.queue.steer_unavailable- )}+ title={sendNowLabel}><Buttonvariant="ghost"size="xs"className="px-1.5 font-normal text-muted-foreground"disabled={busyAction !== null || !canSendNow}- aria-label={t(($) =>- canSendNow- ? $.queue.steer- : $.queue.steer_unavailable- )}+ aria-label={sendNowLabel}onClick={() => void run(sendNowKey, () => onSendNow(task.task_id))}>{busyAction === sendNowKey ? (diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsxindex 682bd34176..4b9f25907e 100644--- a/packages/views/chat/components/chat-window.tsx+++ b/packages/views/chat/components/chat-window.tsx@@ -41,6 +41,7 @@ import { matchesPinyin } from "../../editor/extensions/pinyin-match";import { OfflineBanner } from "./offline-banner";import { NoAgentBanner } from "./no-agent-banner";import { ArchivedAgentBanner } from "./archived-agent-banner";+import { AgentAccessRevokedBanner } from "./agent-access-revoked-banner";import { RuntimeRequiredBanner } from "./runtime-required-banner";import {chatSessionsOptions,@@ -241,6 +242,15 @@ export function ChatWindow() {const activeAgentRuntimeBound =!!activeAgent && isAgentRuntimeBound(activeAgent);+ // A session outlives the permission that created it: the agent can be flipped+ // to personal, change owner, or drop this member from its allow-list, and the+ // server then refuses every send with `invocation_not_allowed` while still+ // serving the transcript (MUL-4525). Judge the SESSION's agent, not just the+ // picker list, so the composer goes read-only up front rather than after the+ // user types (MUL-6380). Mirrors use-chat-controller.ts.+ const isAgentAccessRevoked =+ !!activeAgent && !canAssignAgent(activeAgent, user?.id, memberRole);+const projectContextSupport = useChatProjectContextSupport(wsId, activeAgent);// Three-state availability — "loading" stays neutral (no banner, no@@ -412,6 +422,16 @@ export function ChatWindow() {});return false;}+ // Invoke permission was revoked while this session was open — the server+ // would refuse before persisting anything. Keep the draft, skip the+ // roundtrip. The input is disabled here; belt-and-braces guard.+ if (isAgentAccessRevoked) {+ apiLogger.warn("sendChatMessage skipped: invoke permission revoked", {+ sessionId: activeSessionId,+ agentId: activeAgent.id,+ });+ return false;+ }if (pendingTaskId && pendingTask?.supports_queue !== true) {apiLogger.warn("sendChatMessage skipped: server does not support follow-up queues", {sessionId: activeSessionId,@@ -560,6 +580,7 @@ export function ChatWindow() {activeAgent,activeAgentRuntimeBound,isAgentArchived,+ isAgentAccessRevoked,pendingTask,pendingTaskId,ensureSession,@@ -881,6 +902,7 @@ export function ChatWindow() {!!pendingTaskId ||isSessionArchived ||isAgentArchived ||+ isAgentAccessRevoked ||!activeAgentRuntimeBound ||noAgent}@@ -913,6 +935,8 @@ export function ChatWindow() {* first agent-list response stays banner-free. */}{noAgent ? (<NoAgentBanner />+ ) : isAgentAccessRevoked ? (+ <AgentAccessRevokedBanner agentName={activeAgent?.name} />) : isAgentArchived ? (<ArchivedAgentBanner agentName={activeAgent?.name} />) : !activeAgentRuntimeBound && activeAgent ? (@@ -928,6 +952,7 @@ export function ChatWindow() {tasks={queuedTasks}headStatus={pendingTask?.status}onSendNow={handleSendQueuedTaskNow}+ sendNowDisabled={isAgentAccessRevoked}onEdit={handleEditQueuedTask}onRemove={handleRemoveQueuedTask}onClear={handleClearQueuedTasks}@@ -940,15 +965,19 @@ export function ChatWindow() {onSend={handleSend}restoreDraftRequest={restoreDraftRequest}onRestoreDraftApplied={handleRestoreDraftApplied}- uploadEnabled={!!activeAgent}+ uploadEnabled={!!activeAgent && !isAgentAccessRevoked}onStop={handleStop}isRunning={!!pendingTaskId}allowSubmitWhileRunning={pendingTask?.supports_queue === true}disabled={- isSessionArchived || isAgentArchived || !activeAgentRuntimeBound+ isSessionArchived ||+ isAgentArchived ||+ isAgentAccessRevoked ||+ !activeAgentRuntimeBound}noAgent={noAgent}agentArchived={isAgentArchived}+ agentAccessRevoked={isAgentAccessRevoked}agentRuntimeRequired={!activeAgentRuntimeBound}agentName={activeAgent?.name}projects={projects}diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsxindex 8cc9e3dc15..f54e9ca658 100644--- a/packages/views/chat/components/use-chat-controller.test.tsx+++ b/packages/views/chat/components/use-chat-controller.test.tsx@@ -95,7 +95,14 @@ vi.mock("@multica/core/workspace/queries", () => ({vi.mock("@multica/core/projects/queries", () => ({projectListOptions: () => ({ queryKey: ["projects"] }),}));-vi.mock("@multica/views/issues/components", () => ({ canAssignAgent: () => true }));+// Steerable per test: the invoke rule is what decides whether an OPEN session's+// agent is still runnable. Default true so every existing case is unaffected.+const invokableAgentIds = vi.hoisted(() => ({ current: null as string[] | null }));+vi.mock("@multica/views/issues/components", () => ({+ canAssignAgent: (agent: { id: string }) =>+ invokableAgentIds.current === null ||+ invokableAgentIds.current.includes(agent.id),+}));vi.mock("@multica/core/api", () => ({ApiError: class ApiError extends Error {constructor(@@ -1170,3 +1177,54 @@ describe("useChatController.handleSend — compose target tracking", () => {);});});++// MUL-6380: a chat session outlives the permission that created it. The agent can+// be flipped to personal, change owner, or drop this member from its allow-list;+// the server keeps serving the transcript (view gate) but refuses every send+// (invoke gate, MUL-4525). The controller must reach that verdict up front so the+// composer is read-only, instead of the user learning it from a 403 after typing.+describe("useChatController revoked invoke permission", () => {+ const revokedSession = makeSession({ id: "revoked", agent_id: "agent-a" });++ beforeEach(() => {+ h.createSessionMutate.mockClear();+ vi.mocked(api.sendChatMessage).mockClear();+ });++ afterEach(() => {+ invokableAgentIds.current = null;+ });++ it("flags the open session's agent as revoked while still resolving it", () => {+ invokableAgentIds.current = [];+ const result = setup("revoked", [revokedSession], [agentA]);++ // Still bound — the transcript stays readable and the header keeps naming+ // the real agent; only running is refused.+ expect(result.current.activeAgent?.id).toBe("agent-a");+ expect(result.current.isAgentAccessRevoked).toBe(true);+ // Not conflated with the retired-agent state, which has different copy.+ expect(result.current.isAgentArchived).toBe(false);+ });++ it("does not flag an agent the user may still invoke", () => {+ invokableAgentIds.current = ["agent-a"];+ const result = setup("revoked", [revokedSession], [agentA]);++ expect(result.current.isAgentAccessRevoked).toBe(false);+ });++ it("refuses the send instead of letting the server reject it", async () => {+ invokableAgentIds.current = [];+ const result = setup("revoked", [revokedSession], [agentA]);++ let sent: boolean | undefined;+ await act(async () => {+ sent = await result.current.handleSend("are you there?");+ });++ expect(sent).toBe(false);+ expect(vi.mocked(api.sendChatMessage)).not.toHaveBeenCalled();+ expect(h.createSessionMutate).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex 8e78e21201..09b2d73b77 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -341,6 +341,16 @@ export function useChatController(opts?: { isActive?: boolean }) {null;const isAgentRuntimeBound = !!activeAgent && hasAgentRuntime(activeAgent);+ // A session outlives the permission that created it. The agent can be flipped+ // to personal, change owner, or drop this member from its allow-list, and the+ // server then refuses every send with `invocation_not_allowed` while still+ // serving the transcript (MUL-4525 — read uses the view gate, send re-runs the+ // invoke gate). Judge the SESSION's agent, not just the picker list, so the+ // composer goes read-only up front instead of after the user types+ // (MUL-6380). Same rule the server enforces, via the shared predicate.+ const isAgentAccessRevoked =+ !!activeAgent && !canAssignAgent(activeAgent, user?.id, memberRole);+const agentAvailability = useWorkspaceAgentAvailability();const noAgent = agentAvailability === "none";@@ -469,6 +479,17 @@ export function useChatController(opts?: { isActive?: boolean }) {});return false;}+ // Invoke permission was revoked while this session was open. The server+ // would refuse with a 403 before persisting anything; not attempting the+ // send keeps the draft and avoids a pointless roundtrip. The input is+ // disabled in this state — this is the belt-and-braces guard.+ if (isAgentAccessRevoked) {+ apiLogger.warn("sendChatMessage skipped: invoke permission revoked", {+ sessionId: activeSessionId,+ agentId: activeAgent.id,+ });+ return false;+ }if (pendingTaskId && pendingTask?.supports_queue !== true) {apiLogger.warn("sendChatMessage skipped: server does not support follow-up queues", {sessionId: activeSessionId,@@ -612,6 +633,7 @@ export function useChatController(opts?: { isActive?: boolean }) {activeSessionId,activeAgent,isAgentArchived,+ isAgentAccessRevoked,pendingTask,pendingTaskId,isAgentRuntimeBound,@@ -790,6 +812,7 @@ export function useChatController(opts?: { isActive?: boolean }) {currentSession,isSessionArchived,isAgentArchived,+ isAgentAccessRevoked,isAgentRuntimeBound,activeAgent,noAgent,diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 87919b36d9..5ee37fca64 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -736,7 +736,7 @@"visibility": {"private": {"label": "Personal",- "tooltip": "Personal · only you and workspace admins can use this agent"+ "tooltip": "Personal · only the owner and people they allow can run this agent"},"workspace": {"label": "Workspace",diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex 6439192bdd..c34f259f87 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -15,6 +15,7 @@"placeholder_archived": "This session is archived","placeholder_archived_agent": "This agent has been archived","placeholder_runtime_required": "Bind a runtime to continue",+ "placeholder_access_revoked": "You no longer have permission to run this agent","placeholder_named": "Message {{name}}…","placeholder_default": "Start a message…","send_tooltip": "Send",@@ -38,6 +39,7 @@"clear": "Clear all","steer": "Steer","steer_unavailable": "Steer is available after the current reply starts",+ "steer_no_permission": "You no longer have permission to run this agent","steer_unavailable_toast": "Steer is unavailable. Refreshing the queue.","edit": "Edit queued message","remove": "Remove queued message",@@ -175,6 +177,7 @@},"no_agent_banner": "You need an agent to start chatting.","archived_agent_banner": "{{name}} has been archived — this conversation is read-only.",+ "agent_access_revoked_banner": "You no longer have permission to run {{name}} — this conversation is read-only.","runtime_required_banner": {"fallback_name": "The agent","message": "{{name}} needs a runtime before it can reply.",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 496714db6e..5e77c10bca 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -615,7 +615,7 @@"visibility": {"private": {"label": "個人",- "tooltip": "個人 · 本人とワークスペースの admin のみがこのエージェントを使用できます"+ "tooltip": "個人 · オーナーとオーナーが許可した人のみがこのエージェントを実行できます"},"workspace": {"label": "ワークスペース",diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex a58f0ec9c6..e0978fe906 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -14,6 +14,7 @@"placeholder_archived": "このセッションはアーカイブされています","placeholder_archived_agent": "このエージェントはアーカイブされています","placeholder_runtime_required": "ランタイムを設定して続ける",+ "placeholder_access_revoked": "このエージェントを実行する権限がありません","placeholder_named": "{{name}} にメッセージ…","placeholder_default": "メッセージを入力…","send_tooltip": "送信",@@ -36,6 +37,7 @@"clear": "すべて削除","steer": "指示","steer_unavailable": "現在の返信が開始されると指示できます",+ "steer_no_permission": "このエージェントを実行する権限がありません","steer_unavailable_toast": "現在は指示できません。キューを更新しています。","edit": "キュー内のメッセージを編集","remove": "キューから削除",@@ -171,6 +173,7 @@},"no_agent_banner": "チャットを始めるにはエージェントが必要です。","archived_agent_banner": "{{name}} はアーカイブされました。この会話は読み取り専用です。",+ "agent_access_revoked_banner": "{{name}} を実行する権限がありません。この会話は読み取り専用です。","runtime_required_banner": {"fallback_name": "このエージェント","message": "{{name}} が返信するにはランタイムの設定が必要です。",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex b1d749c559..1c31d87844 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -623,7 +623,7 @@"visibility": {"private": {"label": "개인",- "tooltip": "개인 · 본인과 워크스페이스 관리자만 이 에이전트를 사용할 수 있습니다"+ "tooltip": "개인 · 소유자와 소유자가 허용한 사람만 이 에이전트를 실행할 수 있습니다"},"workspace": {"label": "워크스페이스",diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex 6f6c6e1131..161f6ca772 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -14,6 +14,7 @@"placeholder_archived": "보관된 세션입니다","placeholder_archived_agent": "보관된 에이전트입니다","placeholder_runtime_required": "런타임을 연결한 후 계속하세요",+ "placeholder_access_revoked": "이 에이전트를 실행할 권한이 없습니다","placeholder_named": "{{name}}에게 메시지 보내기…","placeholder_default": "메시지 입력…","send_tooltip": "보내기",@@ -36,6 +37,7 @@"clear": "모두 지우기","steer": "지시","steer_unavailable": "현재 답변이 시작되면 지시할 수 있습니다",+ "steer_no_permission": "이 에이전트를 실행할 권한이 없습니다","steer_unavailable_toast": "현재는 지시할 수 없습니다. 대기열을 새로 고치는 중입니다.","edit": "대기 중인 메시지 편집","remove": "대기열에서 삭제",@@ -171,6 +173,7 @@},"no_agent_banner": "채팅을 시작하려면 에이전트가 필요합니다.","archived_agent_banner": "{{name}}은(는) 보관되었습니다. 이 대화는 읽기 전용입니다.",+ "agent_access_revoked_banner": "{{name}}을(를) 실행할 권한이 없습니다. 이 대화는 읽기 전용입니다.","runtime_required_banner": {"fallback_name": "이 에이전트","message": "{{name}} 에이전트가 응답하려면 런타임을 연결해야 합니다.",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex a54c7d5475..0d6056ccd9 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -722,7 +722,7 @@"visibility": {"private": {"label": "个人",- "tooltip": "个人 · 仅你和工作区管理员可以使用该智能体"+ "tooltip": "个人 · 仅 owner 和其授权的人可以运行该智能体"},"workspace": {"label": "工作区",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex d9a8025c6e..e3ff6441e4 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -14,6 +14,7 @@"placeholder_archived": "此会话已归档","placeholder_archived_agent": "该智能体已归档","placeholder_runtime_required": "绑定运行时后继续",+ "placeholder_access_revoked": "你已没有运行该智能体的权限","placeholder_named": "给 {{name}} 发消息…","placeholder_default": "输入消息…","send_tooltip": "发送",@@ -36,6 +37,7 @@"clear": "全部清空","steer": "引导","steer_unavailable": "当前回复开始后才能引导",+ "steer_no_permission": "你已没有运行该智能体的权限","steer_unavailable_toast": "暂时无法引导,正在刷新队列。","edit": "编辑排队消息","remove": "移除排队消息",@@ -171,6 +173,7 @@},"no_agent_banner": "需要先有一个智能体才能开始对话。","archived_agent_banner": "{{name}} 已归档——此会话为只读。",+ "agent_access_revoked_banner": "你已没有运行 {{name}} 的权限——此会话为只读。","runtime_required_banner": {"fallback_name": "该智能体","message": "{{name}} 需要绑定运行时后才能回复。",diff --git a/server/internal/handler/agent_access_test.go b/server/internal/handler/agent_access_test.goindex 3fcec4d036..8c6d5f48d5 100644--- a/server/internal/handler/agent_access_test.go+++ b/server/internal/handler/agent_access_test.go@@ -512,11 +512,13 @@ func TestMentionAgent_RejectsCrossWorkspaceAgentUUID(t *testing.T) {// posting a plain (non-@mention) comment, bypassing the visibility gate that// #2359 added to chat / @mention / assignment.//-// The gate must:+// The gate must (as tightened by MUL-3963 — the cases below are the source of+// truth, this list only summarises them):// - reject plain workspace members (not owner, not admin, not agent owner)// - allow the agent owner-// - allow workspace owners/admins-// - allow agent-to-agent traffic regardless of agent visibility+// - reject workspace owners/admins: management access is not invoke access+// - reject an agent actor with no owner / allow-listed human originator —+// A2A is judged by the top of the chain, never by the immediate agentfunc TestShouldEnqueueOnComment_PrivateAgentGate(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")diff --git a/server/internal/handler/assign_invoke_denial_test.go b/server/internal/handler/assign_invoke_denial_test.gonew file mode 100644index 0000000000..8d899bf1ee--- /dev/null+++ b/server/internal/handler/assign_invoke_denial_test.go@@ -0,0 +1,130 @@+package handler++import (+ "net/http"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++// assertDenialReason decodes a rejection body and compares its `error` sentence+// to the one the CALLER states it expects, then checks a property that holds for+// every invoke denial: the sentence must not name the target's permission mode.+//+// The expected sentence stays an argument on purpose — the test making the claim+// keeps it. What the helper contributes is the leak scan, which is the same+// property in every case and is exactly what a status-only assertion missed:+// before MUL-6380 these endpoints answered "cannot assign to private agent",+// disclosing the mode to a caller just told they may not use the target, and+// mislabelling a `public_to` agent scoped to specific people as private.+func assertDenialReason(t *testing.T, resp *testutil.Response, want string) {+ t.Helper()+ var body struct {+ Error string `json:"error"`+ }+ resp.JSON(&body)+ if body.Error != want {+ t.Fatalf("denial reason = %q, want %q", body.Error, want)+ }+ for _, mode := range []string{"private", "public_to", "allow-list"} {+ if strings.Contains(strings.ToLower(body.Error), mode) {+ t.Fatalf("denial reason names the target's permission mode (%q): %q", mode, body.Error)+ }+ }+}++// TestAssignAgent_DenialReasonNamesPermissionNotMode pins the response BODY of+// the assignment invoke gate across every principal that can be refused by it.+// The sibling tests in agent_access_test.go / squad_private_leader_test.go pin+// the status code; a 403 alone does not stop the reason sentence from drifting+// back into describing the target instead of the caller's missing permission.+func TestAssignAgent_DenialReasonNamesPermissionNotMode(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ privateAgentID, agentOwnerID, plainMemberID := privateAgentTestFixture(t)+ const wantAgentReason = "you do not have permission to assign work to this agent"++ assignBody := func(agentID string) map[string]any {+ return map[string]any{+ "title": "invoke-denial body test",+ "status": "todo",+ "priority": "medium",+ "assignee_type": "agent",+ "assignee_id": agentID,+ }+ }++ // A workspace OWNER who does not own the agent. Management access is not+ // invoke access (MUL-3963), and the refusal must not tell them why in terms+ // of the agent's configuration.+ t.Run("workspace owner is refused without naming the mode", func(t *testing.T) {+ resp := testutil.Call(t, testHandler.CreateIssue,+ newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, assignBody(privateAgentID)),+ ).Want(http.StatusForbidden)+ assertDenialReason(t, resp, wantAgentReason)+ })++ t.Run("plain member is refused without naming the mode", func(t *testing.T) {+ resp := testutil.Call(t, testHandler.CreateIssue,+ newRequestAs(plainMemberID, "POST", "/api/issues?workspace_id="+testWorkspaceID, assignBody(privateAgentID)),+ ).Want(http.StatusForbidden)+ assertDenialReason(t, resp, wantAgentReason)+ })++ // An AGENT actor with no resolvable human originator (no X-Task-ID). A2A is+ // judged by the top of the chain, so this fails closed like any other+ // principal — there is no unconditional agent-to-agent bypass.+ t.Run("agent actor with no originator is refused without naming the mode", func(t *testing.T) {+ callerAgentID := createHandlerTestAgent(t, "assign-denial-caller-agent", nil)+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, assignBody(privateAgentID))+ req.Header.Set("X-Agent-ID", callerAgentID)+ resp := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusForbidden)+ assertDenialReason(t, resp, wantAgentReason)+ })++ // A `public_to` agent whose allow-list names someone else. This is the case+ // the old wording got factually wrong: the agent is not private, so calling+ // it that told the caller something untrue about the target.+ t.Run("public_to non-target member is refused without calling the agent private", func(t *testing.T) {+ scopedAgentID := dbfx.Agent(t, "assign-denial-scoped-agent", handlerTestRuntimeID(t), testutil.Cols{+ "visibility": "private",+ "permission_mode": "public_to",+ "owner_id": agentOwnerID,+ "instructions": "",+ "custom_env": testutil.Raw("'{}'::jsonb"),+ "custom_args": testutil.Raw("'[]'::jsonb"),+ })+ // Granted to the agent owner only — the plain member is deliberately+ // NOT on the list.+ dbfx.Exec(t, `+ INSERT INTO agent_invocation_target (agent_id, target_type, target_id)+ VALUES ($1, 'member', $2)+ ON CONFLICT (agent_id, target_type, target_id) DO NOTHING+ `, scopedAgentID, agentOwnerID)+ // No FK/cascade by project rule, so the grant outlives the agent row+ // dbfx deletes — drop it explicitly.+ dbfx.Cleanup(t, `DELETE FROM agent_invocation_target WHERE agent_id = $1`, scopedAgentID)++ resp := testutil.Call(t, testHandler.CreateIssue,+ newRequestAs(plainMemberID, "POST", "/api/issues?workspace_id="+testWorkspaceID, assignBody(scopedAgentID)),+ ).Want(http.StatusForbidden)+ assertDenialReason(t, resp, wantAgentReason)+ })++ // The squad branch has its own sentence, and must not disclose the leader's+ // mode either — "this squad" is all the caller gets.+ t.Run("private-leader squad is refused without naming the leader's mode", func(t *testing.T) {+ squadID := dbfx.Squad(t, "Assign Denial Private Leader", privateAgentID)+ resp := testutil.Call(t, testHandler.CreateIssue,+ newRequestAs(plainMemberID, "POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "invoke-denial squad body test",+ "assignee_type": "squad",+ "assignee_id": squadID,+ }),+ ).Want(http.StatusForbidden)+ assertDenialReason(t, resp, "you do not have permission to assign work to this squad")+ })+}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 06ad2253a1..84890b4e04 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -3583,11 +3583,13 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {}// validateAssigneePair verifies the (assignee_type, assignee_id) pair refers-// to an existing entity in the workspace. For agent assignees it also rejects-// archived agents and runs the private-agent gate via canAccessPrivateAgent-// — assigning an issue is a task-producing surface, so it must use the same-// predicate as chat / @-mention / history. Agent callers (X-Agent-ID) bypass-// the gate so A2A flows can still hand work off to private agents.+// to an existing entity in the workspace. For agent and squad assignees it+// also rejects archived targets and runs the INVOKE gate — canInvokeAgent, not+// the softer canAccessPrivateAgent view gate: assigning an issue produces a+// run, so it must clear the same predicate as chat / @-mention (MUL-3963).+// That means owner-only for a private agent, with NO workspace-admin bypass+// and NO unconditional agent-to-agent bypass — an agent caller (X-Agent-ID) is+// judged by the top-of-chain human originator like everywhere else.//// Returns (statusCode, errorMessage). statusCode == 0 means the pair is valid;// callers should treat any non-zero status as a rejection and surface it back@@ -3627,7 +3629,15 @@ func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, wor}actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)if !h.canInvokeAgent(ctx, agent, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {- return http.StatusForbidden, "cannot assign to private agent"+ // Names the missing permission, not the target's configuration: the+ // old "private agent" wording both disclosed the agent's permission+ // mode and was simply wrong for a `public_to` agent scoped to+ // specific people. This is NOT full enumeration-safety — the+ // not-in-workspace branch above still answers 400 where this+ // answers 403, so existence remains observable; the guarantee here+ // is only that the reason no longer names the target's permission+ // mode (MUL-6380 / GH #7180).+ return http.StatusForbidden, "you do not have permission to assign work to this agent"}return 0, ""case "squad":@@ -3647,7 +3657,9 @@ func (h *Handler) validateAssigneePair(ctx context.Context, r *http.Request, wor}actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)if !h.canInvokeAgent(ctx, leader, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {- return http.StatusForbidden, "cannot assign to squad with private leader"+ // Same wording rule as the agent branch above; "this squad"+ // avoids disclosing the leader agent's permission mode.+ return http.StatusForbidden, "you do not have permission to assign work to this squad"}return 0, ""default:diff --git a/server/internal/handler/squad_private_leader_test.go b/server/internal/handler/squad_private_leader_test.goindex 144e9e85c1..31db6070d8 100644--- a/server/internal/handler/squad_private_leader_test.go+++ b/server/internal/handler/squad_private_leader_test.go@@ -90,8 +90,11 @@ func TestUpdateIssue_SquadPrivateLeader_PlainMemberBlocked(t *testing.T) {}}-// TestCreateIssue_SquadPrivateLeader_OwnerAllowed verifies that a workspace-// owner CAN assign an issue to a squad with a private leader.+// TestCreateIssue_SquadPrivateLeader_OwnerAllowed verifies that the LEADER+// AGENT's owner can assign an issue to a squad with a private leader. Named+// "OwnerAllowed" for the agent owner — a workspace owner/admin who does not own+// the leader is denied (MUL-3963), which is what the sibling+// PlainMemberBlocked / assertInvokeForbidden cases pin.func TestCreateIssue_SquadPrivateLeader_OwnerAllowed(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")