Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agents): let team admins delete team agents (#8590)

Eric Hayesce8a11a42177
diff --git a/apps/web/src/features/channel/Bots/BotDetailPage.tsx b/apps/web/src/features/channel/Bots/BotDetailPage.tsx
index 3539d3155a..6f5ab74c76 100644
--- a/apps/web/src/features/channel/Bots/BotDetailPage.tsx
+++ b/apps/web/src/features/channel/Bots/BotDetailPage.tsx
@@ -14,7 +14,11 @@ import {
useUpdateBotMutation,
} from '@queries/bots/bots';
import { useSyncBotChannelsMutation } from '@queries/channel/channel-bots';
-import { useCurrentTeamQuery, useIsTeamOwner } from '@queries/team/teams';
+import {
+ useCurrentTeamQuery,
+ useIsTeamAdmin,
+ useIsTeamOwner,
+} from '@queries/team/teams';
import { Button } from '@ui';
import { createEffect, createMemo, createSignal, on, Show } from 'solid-js';
import { createStore } from 'solid-js/store';
@@ -47,6 +51,7 @@ export function BotDetail(props: { botId: string; onBack: () => void }) {
const currentUserId = useUserId();
const currentTeamQuery = useCurrentTeamQuery();
const isTeamOwner = useIsTeamOwner();
+ const isTeamAdmin = useIsTeamAdmin();
const botQuery = useBotQuery(() => props.botId);
const botChannelsQuery = useBotChannelsQuery(() => props.botId);
const updateBotMutation = useUpdateBotMutation();
@@ -122,7 +127,8 @@ export function BotDetail(props: { botId: string; onBack: () => void }) {
bot,
currentUserId(),
currentTeamQuery.data?.team.id,
- isTeamOwner()
+ isTeamOwner(),
+ isTeamAdmin()
)
);
};
diff --git a/apps/web/src/features/channel/Bots/botPermissions.ts b/apps/web/src/features/channel/Bots/botPermissions.ts
index 1e7047b3d5..df3b3215f4 100644
--- a/apps/web/src/features/channel/Bots/botPermissions.ts
+++ b/apps/web/src/features/channel/Bots/botPermissions.ts
@@ -1,21 +1,25 @@
import type { Bot } from '@service-storage/generated/schemas/bot';
-type BotOwnership = Pick<Bot, 'created_by' | 'owner'>;
+type BotOwnership = Pick<Bot, 'created_by' | 'owner'> &
+ Partial<Pick<Bot, 'has_agent'>>;
/** Whether the current user may delete an owned bot. */
export function canDeleteBot(
bot: BotOwnership,
currentUserId: string | undefined,
currentTeamId: string | undefined,
- isCurrentTeamOwner: boolean
+ isCurrentTeamOwner: boolean,
+ isCurrentTeamAdmin = false
): boolean {
if (!currentUserId || !bot.owner) return false;
if (bot.owner.type === 'user') {
return bot.owner.user_id === currentUserId;
}
return (
- bot.created_by === currentUserId ||
- (bot.owner.team_id === currentTeamId && isCurrentTeamOwner)
+ bot.owner.team_id === currentTeamId &&
+ (bot.created_by === currentUserId ||
+ isCurrentTeamOwner ||
+ (bot.has_agent === true && isCurrentTeamAdmin))
);
}
diff --git a/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts b/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts
index c72f18f469..2b4d3ec0a9 100644
--- a/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts
+++ b/apps/web/src/features/channel/Bots/tests/bot-permissions.test.ts
@@ -39,6 +39,26 @@ describe('canDeleteBot', () => {
expect(canDeleteBot(bot, CURRENT_USER, TEAM_ID, false)).toBe(false);
expect(canDeleteBot(bot, CURRENT_USER, 'team-2', true)).toBe(false);
});
+
+ it('allows team admins to delete agents but not other bots', () => {
+ const bot = {
+ owner: { type: 'team' as const, team_id: TEAM_ID },
+ created_by: CREATOR,
+ has_agent: true,
+ };
+
+ expect(canDeleteBot(bot, CURRENT_USER, TEAM_ID, false, true)).toBe(true);
+ expect(canDeleteBot(bot, CURRENT_USER, 'team-2', false, true)).toBe(false);
+ expect(
+ canDeleteBot(
+ { ...bot, has_agent: false },
+ CURRENT_USER,
+ TEAM_ID,
+ false,
+ true
+ )
+ ).toBe(false);
+ });
});
describe('canManageAgent', () => {
diff --git a/apps/web/src/features/settings/Agents.test.tsx b/apps/web/src/features/settings/Agents.test.tsx
index c96d433fd3..257f1fad75 100644
--- a/apps/web/src/features/settings/Agents.test.tsx
+++ b/apps/web/src/features/settings/Agents.test.tsx
@@ -90,6 +90,7 @@ const agentMocks = vi.hoisted(() => ({
currentUserId: 'macro|[email protected]',
currentTeam: { team: { id: 'team-1' } } as { team: { id: string } } | null,
isTeamOwner: false,
+ isTeamAdmin: false,
}));
const avatarMocks = vi.hoisted(() => ({ upload: vi.fn() }));
@@ -196,6 +197,7 @@ vi.mock('@queries/team/teams', () => ({
isSuccess: true,
}),
useIsTeamOwner: () => () => agentMocks.isTeamOwner,
+ useIsTeamAdmin: () => () => agentMocks.isTeamAdmin,
}));
vi.mock('@core/context/user', () => ({
@@ -298,6 +300,7 @@ beforeEach(() => {
agentMocks.currentUserId = 'macro|[email protected]';
agentMocks.currentTeam = { team: { id: 'team-1' } };
agentMocks.isTeamOwner = false;
+ agentMocks.isTeamAdmin = false;
harnessMocks.query.data = [];
pipedreamMocks.enabled = true;
pipedreamMocks.connected = [];
@@ -918,9 +921,12 @@ describe('Agents', () => {
expect(
within(dialog).getByText('Only the agent creator can make it private.')
).toBeTruthy();
+ expect(
+ within(dialog).queryByRole('button', { name: 'Delete agent' })
+ ).toBeNull();
});
- it('lets the creator privatize and the team owner delete a team agent', () => {
+ it('lets the creator privatize and admins delete a team agent from its editor', async () => {
agentMocks.query.data = [
{
bot: {
@@ -954,10 +960,44 @@ describe('Agents', () => {
agentMocks.currentUserId = 'macro|[email protected]';
agentMocks.isTeamOwner = true;
- render(() => <Agents {...agentsPageProps} />);
+ const ownerView = render(() => <Agents {...agentsPageProps} />);
expect(
screen.getByRole('button', { name: 'Delete Bug fixer' })
).toBeTruthy();
+ ownerView.unmount();
+
+ agentMocks.isTeamOwner = false;
+ agentMocks.isTeamAdmin = true;
+ render(() => <Agents {...agentsPageProps} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Edit Bug fixer' }));
+ const editor = screen.getByRole('region', { name: 'Edit agent' });
+ fireEvent.click(
+ within(editor).getByRole('button', { name: 'Delete agent' })
+ );
+ expect(agentMocks.delete).not.toHaveBeenCalled();
+ fireEvent.click(
+ within(screen.getByRole('dialog')).getByRole('button', {
+ name: 'Cancel',
+ })
+ );
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(screen.getByRole('region', { name: 'Edit agent' })).toBeTruthy();
+
+ fireEvent.click(
+ within(editor).getByRole('button', { name: 'Delete agent' })
+ );
+ fireEvent.click(
+ within(screen.getByRole('dialog')).getByRole('button', {
+ name: 'Delete agent',
+ })
+ );
+ await waitFor(() => {
+ expect(agentMocks.delete).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ channelIds: [],
+ });
+ expect(screen.queryByRole('region', { name: 'Edit agent' })).toBeNull();
+ });
});
it('confirms before deleting a created agent', async () => {
diff --git a/apps/web/src/features/settings/Agents.tsx b/apps/web/src/features/settings/Agents.tsx
index c2a2d85a1d..73c616b282 100644
--- a/apps/web/src/features/settings/Agents.tsx
+++ b/apps/web/src/features/settings/Agents.tsx
@@ -42,7 +42,11 @@ import {
import { useCursorApiKeyStatusQuery } from '@queries/auth/cursor-api-key';
import { useHarnessesQuery } from '@queries/harnesses/harnesses';
import { usePipedreamConnectedSlugs } from '@queries/pipedream-connectors';
-import { useCurrentTeamQuery, useIsTeamOwner } from '@queries/team/teams';
+import {
+ useCurrentTeamQuery,
+ useIsTeamAdmin,
+ useIsTeamOwner,
+} from '@queries/team/teams';
import type { AgentMcpServer } from '@service-storage/generated/schemas/agentMcpServer';
import type { AgentMcpServers } from '@service-storage/generated/schemas/agentMcpServers';
import { useSearchParams } from '@solidjs/router';
@@ -153,6 +157,7 @@ export function Agents(props: {
const updateAgentMutation = useUpdateAgentMutation();
const currentTeamQuery = useCurrentTeamQuery();
const isTeamOwner = useIsTeamOwner();
+ const isTeamAdmin = useIsTeamAdmin();
const cursorStatus = useCursorApiKeyStatusQuery();
const cursorConnected = () =>
cursorStatus.isSuccess ? cursorStatus.data.registered : false;
@@ -200,7 +205,13 @@ export function Agents(props: {
const canMakePrivate = (agent: AgentWithHarnessId) =>
agent.bot.owner?.type !== 'team' || isAgentCreator(agent);
const canDeleteAgent = (agent: AgentWithHarnessId) =>
- canDeleteBot(agent.bot, currentUserId(), currentTeamId(), isTeamOwner());
+ canDeleteBot(
+ agent.bot,
+ currentUserId(),
+ currentTeamId(),
+ isTeamOwner(),
+ isTeamAdmin()
+ );
const agents = createMemo(() =>
(agentsQuery.isSuccess ? agentsQuery.data : [])
.filter((agent) =>
@@ -259,6 +270,7 @@ export function Agents(props: {
channelIds: current.channel_ids,
});
setDeletingAgent(undefined);
+ if (editingAgent()?.bot.id === current.bot.id) setEditingAgent(undefined);
toast.success('Agent deleted');
} catch {
toast.failure('Failed to delete agent');
@@ -364,6 +376,9 @@ export function Agents(props: {
pending={updateAgentMutation.isPending}
onClose={() => setEditingAgent(undefined)}
onSave={updateAgent}
+ onDelete={
+ canDeleteAgent(agent) ? () => setDeletingAgent(agent) : undefined
+ }
/>
)}
</Show>
@@ -582,6 +597,7 @@ function AgentEditorPage(props: {
pending: boolean;
onClose: () => void;
onSave: (agent: CreateAgentParams) => Promise<boolean>;
+ onDelete?: () => void;
}) {
const [name, setName] = createSignal(props.agent?.bot.name ?? '');
const [tag, setTag] = createSignal(props.agent?.bot.handle ?? '');
@@ -1343,31 +1359,47 @@ function AgentEditorPage(props: {
</Show>
</AgentFormSection>
</form>
- <div class="mt-6 flex justify-end gap-2 border-t border-edge-muted pt-4">
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={close}
- disabled={busy()}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- form="agent-form"
- variant="strong"
- size="sm"
- disabled={!canCreate()}
- >
- {props.pending
- ? props.agent
- ? 'Saving…'
- : 'Creating…'
- : props.agent
- ? 'Save changes'
- : 'Create agent'}
- </Button>
+ <div class="mt-6 flex flex-wrap items-center gap-2 border-t border-edge-muted pt-4">
+ <Show when={props.onDelete}>
+ {(onDelete) => (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ class="text-negative"
+ disabled={busy()}
+ onClick={onDelete()}
+ >
+ <TrashIcon /> Delete agent
+ </Button>
+ )}
+ </Show>
+ <div class="ml-auto flex gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={close}
+ disabled={busy()}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ form="agent-form"
+ variant="strong"
+ size="sm"
+ disabled={!canCreate()}
+ >
+ {props.pending
+ ? props.agent
+ ? 'Saving…'
+ : 'Creating…'
+ : props.agent
+ ? 'Save changes'
+ : 'Create agent'}
+ </Button>
+ </div>
</div>
</section>
</SettingsPage>
diff --git a/crates/bots/AGENTS.md b/crates/bots/AGENTS.md
index 75dea975d0..5aa4c2d583 100644
--- a/crates/bots/AGENTS.md
+++ b/crates/bots/AGENTS.md
@@ -9,6 +9,8 @@ for bot mutations that channel bots, agent triggers, and memory build on.
## Start here
- `src/domain/service.rs` + `src/domain/models.rs`: bot CRUD policy and model.
+ Team admins may delete team agents; other team bots require the creator or
+ team owner.
- `src/domain/events.rs`: `bot.created`/`bot.updated`/`bot.deleted` events published
to the `macro.bots` Kafka topic (see `README.md` for the wire schema).
- `src/inbound/axum_router.rs`, `src/inbound/channel_webhook_router.rs`,
diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rs
index f1091a3b12..9ea8bd67b9 100644
--- a/crates/bots/src/domain/service.rs
+++ b/crates/bots/src/domain/service.rs
@@ -782,13 +782,18 @@ where
let bot = self.ensure_manageable(caller.clone(), bot_id).await?;
if let Some(BotOwner::Team { team_id }) = &bot.owner
&& bot.created_by.as_deref() != Some(caller.as_ref())
- && !self
- .repo
- .user_owns_team(caller.clone(), *team_id)
- .await
- .map_err(|err| BotError::Repo(err.into()))?
{
- return Err(BotError::Unauthorized);
+ let allowed = if bot.has_agent {
+ self.repo
+ .user_can_administer_team(caller.clone(), *team_id)
+ .await
+ } else {
+ self.repo.user_owns_team(caller.clone(), *team_id).await
+ }
+ .map_err(|err| BotError::Repo(err.into()))?;
+ if !allowed {
+ return Err(BotError::Unauthorized);
+ }
}
if !self
.repo
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index a0257d454e..8c82f3bf36 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -1342,7 +1342,7 @@ async fn create_team_owned_bot_requires_team_admin_or_owner(pool: PgPool) -> any
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn only_creator_or_team_owner_can_delete_team_bots(pool: PgPool) -> anyhow::Result<()> {
+async fn team_admins_can_delete_agents_but_not_other_team_bots(pool: PgPool) -> anyhow::Result<()> {
let service = service(&pool);
let team_id = Uuid::new_v4();
insert_team_user(&pool, team_id, TEAM_OWNER, "owner").await?;
@@ -1376,12 +1376,27 @@ async fn only_creator_or_team_owner_can_delete_team_bots(pool: PgPool) -> anyhow
.create_agent(user_id(TEAM_MEMBER), member_agent_request)
.await?;
- let admin_delete = service
+ service
.delete_bot(user_id(TEAM_ADMIN), member_agent.bot.id)
+ .await?;
+
+ let mut owner_agent_request = create_agent_req("owner-team-agent", AgentChannelScope::All);
+ owner_agent_request.team_id = Some(team_id);
+ let owner_agent = service
+ .create_agent(user_id(TEAM_OWNER), owner_agent_request)
+ .await?;
+ let member_delete = service
+ .delete_bot(user_id(TEAM_MEMBER), owner_agent.bot.id)
.await;
- assert!(matches!(admin_delete, Err(BotError::Unauthorized)));
+ assert!(matches!(member_delete, Err(BotError::Unauthorized)));
+
+ let mut creator_agent_request = create_agent_req("creator-team-agent", AgentChannelScope::All);
+ creator_agent_request.team_id = Some(team_id);
+ let creator_agent = service
+ .create_agent(user_id(TEAM_MEMBER), creator_agent_request)
+ .await?;
service
- .delete_bot(user_id(TEAM_MEMBER), member_agent.bot.id)
+ .delete_bot(user_id(TEAM_MEMBER), creator_agent.bot.id)
.await?;
Ok(())
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
index 1724a57439..543d2b8809 100644
--- a/docs/agent-guide/settings.md
+++ b/docs/agent-guide/settings.md
@@ -578,6 +578,10 @@ available when `pipedream-mcp` is disabled.
Open Settings with the rail's gear button or `Ctrl+;`; leave it by picking any other rail item.
`Agents` → `New agent` (or edit an existing agent) opens a full-page form. The
+edit form offers `Delete agent` to the agent's creator, the team owner, and
+team admins for team agents. Confirming removes it from channels and returns
+to the agent list; Cancel keeps the edit form open. Other team members can edit
+the agent but cannot delete it. The
`Instructions` field is a Lexical contenteditable textbox, not a textarea. It
supports Markdown headings, lists, emphasis, code, links, and the normal `@`
mention picker; select text to open the formatting menu. Saved instructions