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.

fix(channels): scope deletion to owners and team admins (#9539)

Peter Chinmanbdf556c70615
diff --git a/.sqlx/query-4d8a57cf1b7120220ee124a5cefaa758ffd5f337e27cca9431d00537e8e81c6a.json b/.sqlx/query-4d8a57cf1b7120220ee124a5cefaa758ffd5f337e27cca9431d00537e8e81c6a.json
new file mode 100644
index 0000000000..d2e86f382c
--- /dev/null
+++ b/.sqlx/query-4d8a57cf1b7120220ee124a5cefaa758ffd5f337e27cca9431d00537e8e81c6a.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM comms_channels\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4d8a57cf1b7120220ee124a5cefaa758ffd5f337e27cca9431d00537e8e81c6a"
+}
diff --git a/.sqlx/query-c45d3a5053e31c82cb7484c9490d939efa1a1068f2ba2fd54b4486d6ea43bd24.json b/.sqlx/query-c45d3a5053e31c82cb7484c9490d939efa1a1068f2ba2fd54b4486d6ea43bd24.json
new file mode 100644
index 0000000000..be5b532829
--- /dev/null
+++ b/.sqlx/query-c45d3a5053e31c82cb7484c9490d939efa1a1068f2ba2fd54b4486d6ea43bd24.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM team_user\n WHERE user_id = $1 AND team_id = $2\n AND team_role IN ('admin'::team_role, 'owner'::team_role)\n ) AS \"is_admin!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "is_admin!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "c45d3a5053e31c82cb7484c9490d939efa1a1068f2ba2fd54b4486d6ea43bd24"
+}
diff --git a/.sqlx/query-f04a97eb13684a35daf6c5ff52890da499864d7f8e97a390a11b384d6429fa13.json b/.sqlx/query-f04a97eb13684a35daf6c5ff52890da499864d7f8e97a390a11b384d6429fa13.json
deleted file mode 100644
index 5b722afbd3..0000000000
--- a/.sqlx/query-f04a97eb13684a35daf6c5ff52890da499864d7f8e97a390a11b384d6429fa13.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM comms_channels\n WHERE id = $1\n AND EXISTS (\n SELECT 1\n FROM comms_channel_participants\n WHERE channel_id = $1\n AND user_id = $2\n AND role = 'owner'::comms_participant_role\n )\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "f04a97eb13684a35daf6c5ff52890da499864d7f8e97a390a11b384d6429fa13"
-}
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 0d7a971120..143553b06c 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -1,4 +1,5 @@
## Development Commands
+
- Use `bun` as the package manager and script runner (`bun run build`, `bunx tsc`).
- `bun run test`: run tests
- `bun run check`: check typescript changes
@@ -738,6 +739,12 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
## Rules
+- Channel Delete actions use the channel owner or admin/owner of the channel's
+ exact team (`channelType === 'team'`); pass the channel's `teamId` to the team
+ admin predicate. Keep rail/title menus, mobile long-press, and hotkeys on the
+ shared delete action and bulk mutation. Preserve confirmed deletions when
+ another item in the bulk deletion fails.
+
- Pass persistent touch row controls through `ListEntity.touchActions`; hover actions are hidden on touch, and the narrow inbox layout must retain the touch controls.
Conventions for this app live in `.agents/rules/web/` and load when you touch
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
index 5ee45bcdcc..702351fd02 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
@@ -151,6 +151,7 @@ function NewTop(props: { channelId: string }) {
name: ch.name ?? 'New Channel',
blockName: 'channel',
channelType: ch.channel_type,
+ teamId: ch.team_id ?? undefined,
ownerId: ch.owner_id,
isParticipant: participantsQuery.isSuccess
? (participantsQuery.data ?? []).some(
@@ -319,11 +320,24 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {
// The layout context exists during construction; its global signal is set later.
const splitLayout = useContext(SplitLayoutContext);
blockHotkeyScopeSignal.set(splitPanel.splitHotkeyScope);
- useBlockEntityCommands();
const canAutofocusSplitContent = useCanAutofocusSplitContent();
const { navigatedFromJK } = useNavigatedFromJK();
const channelId = useBlockId();
const conversationChannel = useChannel(channelId);
+ useBlockEntityCommands({
+ resolveEntity: () => {
+ const channel = conversationChannel();
+ if (!channel) return undefined;
+ return buildEntityData({
+ id: channelId,
+ name: channel.name ?? 'New Channel',
+ blockName: 'channel',
+ ownerId: channel.owner_id,
+ channelType: channel.channel_type,
+ teamId: channel.team_id ?? undefined,
+ });
+ },
+ });
const canCall = useChannelCanCall(channelId);
const blockHandle = blockHandleSignal.get;
const [searchParams, setSearchParams] = useSearchParams();
diff --git a/apps/web/src/features/entity/queries/bulk-delete-result.ts b/apps/web/src/features/entity/queries/bulk-delete-result.ts
index 05ad9cc32e..fb0bbae866 100644
--- a/apps/web/src/features/entity/queries/bulk-delete-result.ts
+++ b/apps/web/src/features/entity/queries/bulk-delete-result.ts
@@ -1,6 +1,6 @@
import type { EntityData } from '../types/entity';
-/** Per-item outcomes of a GraphQL-enabled bulk delete, including retry targets. */
+/** Per-item outcomes of a bulk delete, including retry targets. */
export class BulkDeleteFailure extends Error {
readonly deletedEntities: EntityData[];
readonly failedEntities: EntityData[];
diff --git a/apps/web/src/features/entity/queries/dss.test.tsx b/apps/web/src/features/entity/queries/dss.test.tsx
index 76cb04ccff..b59320eb38 100644
--- a/apps/web/src/features/entity/queries/dss.test.tsx
+++ b/apps/web/src/features/entity/queries/dss.test.tsx
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
graphqlEnabled: vi.fn(() => true),
deleteItem: vi.fn(),
deleteCall: vi.fn(),
+ deleteChannel: vi.fn(),
deleteCallGraphql: vi.fn(),
deleteReminder: vi.fn(),
deleteSchedule: vi.fn(),
@@ -75,7 +76,10 @@ vi.mock('@service-scheduled-action/client', () => ({
scheduledActionClient: { deleteSchedule: mocks.deleteSchedule },
}));
vi.mock('@service-storage/client', () => ({
- storageServiceClient: { reminders: { deleteReminder: mocks.deleteReminder } },
+ storageServiceClient: {
+ deleteChannel: mocks.deleteChannel,
+ reminders: { deleteReminder: mocks.deleteReminder },
+ },
}));
vi.mock('@service-storage/graphql-soup', () => ({
getEntityGraphqlClient: () => mocks.graphqlClient,
@@ -83,6 +87,7 @@ vi.mock('@service-storage/graphql-soup', () => ({
import { scheduledActionKeys } from '@app/features/routines/queries/keys';
import { callKeys } from '@queries/call/keys';
+import { channelKeys } from '@queries/channel/keys';
import {
GRAPHQL_SOUP_DELETE_MUTATION_KEY,
GRAPHQL_SOUP_DELETE_RETENTION_MS,
@@ -143,6 +148,7 @@ beforeEach(() => {
mocks.removeSearch.mockReturnValue({ rollback: mocks.rollbackSearch });
mocks.refresh.mockResolvedValue(undefined);
mocks.deleteItem.mockResolvedValue(true);
+ mocks.deleteChannel.mockReturnValue(okAsync(undefined));
mocks.trashDatabase.mockReturnValue(okAsync(undefined));
mocks.moveToFolder.mockResolvedValue(true);
mocks.copyItem.mockResolvedValue('copied-task');
@@ -440,24 +446,17 @@ describe('bulk delete GraphQL optimism', () => {
});
it.each([true, false])(
- 'handles boolean-only total failure without changing the disabled path (%s)',
+ 'restores a boolean-only total failure with GraphQL Soup enabled=%s',
async (graphql) => {
vi.spyOn(console, 'error').mockImplementation(() => {});
mocks.graphqlEnabled.mockReturnValue(graphql);
mocks.deleteItem.mockResolvedValue(false);
const { mutation } = mount();
const result = mutation.mutateAsync([entity('failed')]);
- if (graphql) {
- await expect(result).rejects.toThrow('Failed to delete items');
- expect(mocks.rollbackSoup).toHaveBeenCalledOnce();
- expect(mocks.rollbackSearch).toHaveBeenCalledOnce();
- expect(mocks.failure).toHaveBeenCalledWith('Failed to delete items');
- } else {
- await expect(result).resolves.toEqual([false]);
- expect(mocks.rollbackSoup).not.toHaveBeenCalled();
- expect(mocks.rollbackSearch).not.toHaveBeenCalled();
- expect(mocks.failure).not.toHaveBeenCalled();
- }
+ await expect(result).rejects.toThrow('Failed to delete items');
+ expect(mocks.rollbackSoup).toHaveBeenCalledOnce();
+ expect(mocks.rollbackSearch).toHaveBeenCalledOnce();
+ expect(mocks.failure).toHaveBeenCalledWith('Failed to delete items');
}
);
@@ -470,7 +469,7 @@ describe('bulk delete GraphQL optimism', () => {
const result = mutation.mutateAsync([
entity('task-1'),
entity('task-2'),
- entity('channel', 'channel'),
+ entity('message', 'channel_message'),
]);
await vi.waitFor(() =>
expect([...pendingKeys()]).toEqual([
@@ -778,3 +777,77 @@ describe('moving databases and forms between folders', () => {
]);
});
});
+
+describe('channel deletion', () => {
+ it.each([true, false])(
+ 'keeps confirmed channel deletions removed when a sibling fails (GraphQL: %s)',
+ async (graphql) => {
+ mocks.graphqlEnabled.mockReturnValue(graphql);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const soup = cacheRows(mocks.removeSoup, mocks.rollbackSoup, [
+ 'deleted-channel',
+ 'failed',
+ 'other',
+ ]);
+ const search = cacheRows(mocks.removeSearch, mocks.rollbackSearch, [
+ 'deleted-channel',
+ 'failed',
+ 'other',
+ ]);
+ const invalidate = vi.spyOn(client, 'invalidateQueries');
+ const failure = deferred<boolean>();
+ mocks.deleteItem.mockReturnValue(failure.promise);
+ const deleted = entity('deleted-channel', 'channel');
+ const failed = entity('failed');
+ const { mutation } = mount();
+
+ const result = expect(
+ mutation.mutateAsync([deleted, failed])
+ ).rejects.toMatchObject({
+ deletedEntities: [deleted],
+ failedEntities: [failed],
+ results: [true, false],
+ });
+ await vi.waitFor(() => expect(mocks.deleteItem).toHaveBeenCalledOnce());
+ expect(soup()).toEqual(['other']);
+ expect(search()).toEqual(['other']);
+ expect(mutation.isPending).toBe(true);
+ failure.reject(new Error('document delete failed'));
+ await result;
+
+ expect(soup()).toEqual(['failed', 'other']);
+ expect(search()).toEqual(['failed', 'other']);
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: channelKeys._def });
+ expect(mocks.failure).toHaveBeenCalledWith(
+ 'Deleted 1 of 2 items; 1 failed'
+ );
+ }
+ );
+
+ it.each([true, false])(
+ 'deletes channels and refreshes channel caches (GraphQL: %s)',
+ async (graphql) => {
+ mocks.graphqlEnabled.mockReturnValue(graphql);
+ const invalidate = vi.spyOn(client, 'invalidateQueries');
+ const { mutation } = mount();
+
+ await expect(
+ mutation.mutateAsync([entity('channel-id', 'channel')])
+ ).resolves.toEqual([true]);
+
+ if (graphql) {
+ expect(mocks.deleteCallGraphql).toHaveBeenCalledWith({
+ type: 'CHANNEL',
+ id: 'channel-id',
+ });
+ expect(mocks.deleteChannel).not.toHaveBeenCalled();
+ } else {
+ expect(mocks.deleteChannel).toHaveBeenCalledWith({
+ channel_id: 'channel-id',
+ });
+ expect(mocks.deleteCallGraphql).not.toHaveBeenCalled();
+ }
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: channelKeys._def });
+ }
+ );
+});
diff --git a/apps/web/src/features/entity/queries/dss.ts b/apps/web/src/features/entity/queries/dss.ts
index f0f6d323f1..585f1aa2d3 100644
--- a/apps/web/src/features/entity/queries/dss.ts
+++ b/apps/web/src/features/entity/queries/dss.ts
@@ -19,6 +19,7 @@ import { fireAndForget } from '@core/util/fireAndForget';
import { throwOnErr } from '@core/util/result';
import { deleteAgentSession } from '@queries/agent-session/entity-mutations';
import { callKeys } from '@queries/call/keys';
+import { channelKeys } from '@queries/channel/keys';
import { queryClient } from '@queries/client';
import {
getSoupEntityById,
@@ -42,6 +43,7 @@ import { permanentlyDeleteEntity } from '@queries/storage/entity-mutations';
import { databasesKeys, formsKeys } from '@queries/storage/keys';
import { callServiceClient } from '@service-call/client';
import { scheduledActionClient } from '@service-scheduled-action/client';
+import { storageServiceClient } from '@service-storage/client';
import type { ListedDatabase } from '@service-storage/generated/schemas/listedDatabase';
import type { ListedForm } from '@service-storage/generated/schemas/listedForm';
import { getEntityGraphqlClient } from '@service-storage/graphql-soup';
@@ -51,6 +53,9 @@ import { type EntityData, getEntityProjectId } from '../types/entity';
import { BulkDeleteFailure } from './bulk-delete-result';
function invalidateDeletedDssItems(entities: EntityData[]): void {
+ if (entities.some((e) => e.type === 'channel')) {
+ queryClient.invalidateQueries({ queryKey: channelKeys._def });
+ }
if (entities.some((e) => e.type === 'call')) {
queryClient.invalidateQueries({ queryKey: callKeys._def });
}
@@ -81,7 +86,7 @@ function invalidateDeletedDssItems(entities: EntityData[]): void {
}
}
-async function settleGraphqlDeletes(
+async function settleDssDeletes(
entities: EntityData[],
deletions: Promise<boolean>[]
): Promise<boolean[]> {
@@ -135,6 +140,7 @@ export function createBulkDeleteDssItemsMutation() {
const type = entity.type;
return (
type === 'agent_session' ||
+ type === 'channel' ||
type === 'chat' ||
type === 'document' ||
type === 'project' ||
@@ -162,6 +168,16 @@ export function createBulkDeleteDssItemsMutation() {
await deleteAgentSession(e.id);
return true;
}
+ if (e.type === 'channel') {
+ if (graphqlSoupEnabled) {
+ await permanentlyDeleteEntity({ type: 'CHANNEL', id: e.id });
+ } else {
+ await throwOnErr(() =>
+ storageServiceClient.deleteChannel({ channel_id: e.id })
+ );
+ }
+ return true;
+ }
if (e.type === 'call') {
if (isFeatureEnabled(enableGraphqlSoup)) {
await permanentlyDeleteEntity({ type: 'CALL', id: e.id });
@@ -189,11 +205,7 @@ export function createBulkDeleteDssItemsMutation() {
}
return deleteItem({ id: e.id, itemType: e.type });
});
- const results = graphqlSoupEnabled
- ? await settleGraphqlDeletes(deletable, deletions)
- : await Promise.all(deletions);
- if (!graphqlSoupEnabled) invalidateDeletedDssItems(deletable);
- return results;
+ return settleDssDeletes(deletable, deletions);
},
onMutate: async (entities: EntityData[]) => {
const deletable = entities.filter(isDeletable);
@@ -236,9 +248,7 @@ export function createBulkDeleteDssItemsMutation() {
return;
}
const partialFailure =
- graphqlSoupEnabled &&
- error instanceof BulkDeleteFailure &&
- error.deletedEntities.length > 0;
+ error instanceof BulkDeleteFailure && error.deletedEntities.length > 0;
if (partialFailure) {
// The legacy transactions hold whole snapshots. Restore failed rows,
// then reapply confirmed removals in one reactive batch so successes
@@ -246,7 +256,7 @@ export function createBulkDeleteDssItemsMutation() {
batch(() => {
context?.soupSnapshot.rollback();
context?.searchSnapshot.rollback();
- removeDssEntityCaches(error.deletedEntities, true);
+ removeDssEntityCaches(error.deletedEntities, graphqlSoupEnabled);
});
} else {
context?.soupSnapshot.rollback();
diff --git a/apps/web/src/features/entity/utils/buildEntityData.ts b/apps/web/src/features/entity/utils/buildEntityData.ts
index f643125a30..f44607b315 100644
--- a/apps/web/src/features/entity/utils/buildEntityData.ts
+++ b/apps/web/src/features/entity/utils/buildEntityData.ts
@@ -24,6 +24,7 @@ export type BuildEntityDataArgs = {
fileType?: string;
isCompleted?: boolean;
channelType?: ChannelEntity['channelType'];
+ teamId?: string;
isParticipant?: boolean;
cron?: string;
enabled?: boolean;
@@ -144,6 +145,7 @@ export function buildEntityData(
...base,
type: 'channel',
channelType: args.channelType,
+ ...(args.teamId === undefined ? {} : { teamId: args.teamId }),
...(args.isParticipant === undefined
? {}
: { isParticipant: args.isParticipant }),
diff --git a/apps/web/src/features/next-soup/actions/make-delete-action.test.ts b/apps/web/src/features/next-soup/actions/make-delete-action.test.ts
index 2937bcafb4..231eec77b5 100644
--- a/apps/web/src/features/next-soup/actions/make-delete-action.test.ts
+++ b/apps/web/src/features/next-soup/actions/make-delete-action.test.ts
@@ -1,6 +1,7 @@
import type { EntityData } from '@entity';
import { createRoot, createSignal } from 'solid-js';
import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';
+import { buildEntityData } from '../../entity/utils/buildEntityData';
const mocks = vi.hoisted(() => ({
openBulkEditModal: vi.fn(),
@@ -486,8 +487,66 @@ describe('makeDeleteAction.canExecute', () => {
);
});
- it('refuses channels and channel rows outright', () => {
- expect(canExecute(entity('channel'))).toBe(false);
+ it('allows channel owners and admins of the channels exact team', () => {
+ const action = makeDeleteAction({
+ userId: () => ME,
+ isTeamAdmin: (teamId) => teamId === 'team-a',
+ });
+ const blockChannel = buildEntityData({
+ id: 'team-channel',
+ name: 'Team channel',
+ blockName: 'channel',
+ channelType: 'team',
+ teamId: 'team-a',
+ ownerId: 'macro|[email protected]',
+ });
+ expect(blockChannel && action.canExecute(blockChannel)).toBe(true);
+ for (const channelType of [
+ 'private',
+ 'public',
+ 'team',
+ 'direct_message',
+ ] as const) {
+ expect(action.canExecute(entity('channel', { channelType }))).toBe(true);
+ expect(
+ action.canExecute(
+ entity('channel', {
+ channelType,
+ teamId: 'team-a',
+ ownerId: 'macro|[email protected]',
+ })
+ )
+ ).toBe(channelType === 'team');
+ }
+ expect(
+ action.canExecute(
+ entity('channel', {
+ channelType: 'team',
+ teamId: 'team-b',
+ ownerId: 'macro|[email protected]',
+ })
+ )
+ ).toBe(false);
+ expect(
+ action.canExecute(
+ entity('channel', {
+ channelType: 'team',
+ ownerId: 'macro|[email protected]',
+ })
+ )
+ ).toBe(false);
+ expect(
+ canExecute(
+ entity('channel', {
+ channelType: 'team',
+ teamId: 'team-a',
+ ownerId: 'macro|[email protected]',
+ })
+ )
+ ).toBe(false);
+ });
+
+ it('refuses channel message and thread rows', () => {
expect(canExecute(entity('channel_message'))).toBe(false);
expect(canExecute(entity('channel_thread'))).toBe(false);
});
diff --git a/apps/web/src/features/next-soup/actions/make-delete-action.ts b/apps/web/src/features/next-soup/actions/make-delete-action.ts
index d85d5d34cb..d5a3e5a2bd 100644
--- a/apps/web/src/features/next-soup/actions/make-delete-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-delete-action.ts
@@ -68,6 +68,7 @@ function reportTrashedEmails(
type MakeDeleteOptions = {
userId: () => string | undefined;
+ isTeamAdmin?: (teamId: string) => boolean;
onDeleted?: (entities: EntityData[]) => void;
};
@@ -103,6 +104,14 @@ export const makeDeleteAction = (options: MakeDeleteOptions) => {
if (entity.type === 'email') {
return true;
}
+ if (entity.type === 'channel') {
+ if (entity.ownerId === userId()) return true;
+ return (
+ entity.channelType === 'team' &&
+ !!entity.teamId &&
+ (options.isTeamAdmin?.(entity.teamId) ?? false)
+ );
+ }
// The types the delete mutation supports; it skips any other.
if (
entity.type !== 'agent_session' &&
diff --git a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts b/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts
index 36b3174ebc..874a8551f1 100644
--- a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts
+++ b/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts
@@ -21,6 +21,7 @@ import { type EntityData, isEmailEntity, isTaskEntity } from '@entity';
import { Telemetry } from '@macro-inc/observability';
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import type { Property, PropertyDefinitionDomain } from '@property/types';
+import { useIsTeamAdmin } from '@queries/team/teams';
import { createEffect, onCleanup } from 'solid-js';
import type { EntityActionNavigationEvent } from './entity-action-context';
import {
@@ -80,6 +81,7 @@ export const useBlockEntityCommands = (
const quickAccess = useQuickAccess();
const userId = useUserId();
+ const isTeamAdmin = useIsTeamAdmin();
const notificationSource = useGlobalNotificationSource();
const soup = useMaybeSoup();
const splitPanel = useSplitPanel();
@@ -90,6 +92,7 @@ export const useBlockEntityCommands = (
});
const deleteAction = makeDeleteAction({
+ isTeamAdmin,
userId: () => userId(),
onDeleted: options.onDeleted,
});
diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.test.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.test.ts
index 73eb5224a2..1d64b187e6 100644
--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.test.ts
+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.test.ts
@@ -36,6 +36,7 @@ vi.mock('@core/hotkey/hotkeys', () => ({
createHotkeyGroup: () => ({ dispose: vi.fn(), addDisposer: vi.fn() }),
}));
vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user' }));
+vi.mock('@queries/team/teams', () => ({ useIsTeamAdmin: () => () => false }));
vi.mock('@components/app/GlobalAppState', () => ({
useGlobalNotificationSource: () => ({}),
}));
diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts
index 0e37302728..01aede3680 100644
--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts
+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts
@@ -15,6 +15,7 @@ import { type EntityData, isEmailEntity, isTaskEntity } from '@entity';
import { Telemetry } from '@macro-inc/observability';
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import type { Property, PropertyDefinitionDomain } from '@property/types';
+import { useIsTeamAdmin } from '@queries/team/teams';
import { type Accessor, onCleanup } from 'solid-js';
import type {
EntityActionListState,
@@ -82,6 +83,7 @@ export const useEntityActionHotkeys = (
} = options;
const userId = useUserId();
+ const isTeamAdmin = useIsTeamAdmin();
const notificationSource = useGlobalNotificationSource();
const group = createHotkeyGroup();
@@ -101,6 +103,7 @@ export const useEntityActionHotkeys = (
const markUnread = makeMarkUnreadAction();
const deleteAction = makeDeleteAction({
+ isTeamAdmin,
userId: () => userId(),
});
diff --git a/apps/web/src/features/soup/createSoupEntityActions.test.ts b/apps/web/src/features/soup/createSoupEntityActions.test.ts
index 88857c744a..5355183be1 100644
--- a/apps/web/src/features/soup/createSoupEntityActions.test.ts
+++ b/apps/web/src/features/soup/createSoupEntityActions.test.ts
@@ -76,6 +76,7 @@ vi.mock('@components/app/GlobalAppState', () => ({
useGlobalNotificationSource: () => mocks.source,
}));
vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user' }));
+vi.mock('@queries/team/teams', () => ({ useIsTeamAdmin: () => () => false }));
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
const channel = {
diff --git a/apps/web/src/features/soup/createSoupEntityActions.ts b/apps/web/src/features/soup/createSoupEntityActions.ts
index 052f388b09..75c6b55d5b 100644
--- a/apps/web/src/features/soup/createSoupEntityActions.ts
+++ b/apps/web/src/features/soup/createSoupEntityActions.ts
@@ -52,6 +52,7 @@ import type { EntityData } from '@entity';
import { isEmailEntity, isGithubPrEntity, isTaskEntity } from '@entity';
import { markRowNotificationsSeenOnOpen } from '@notifications/mark-row-seen';
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
+import { useIsTeamAdmin } from '@queries/team/teams';
import type { Component, JSX } from 'solid-js';
type SoupEntityActionItem = {
@@ -113,6 +114,7 @@ export function createSoupEntityActions(
const analytics = useAnalytics();
const projectsFlag = useFeatureFlag(enableProjects);
const userId = useUserId();
+ const isTeamAdmin = useIsTeamAdmin();
const notificationSource = useGlobalNotificationSource();
const crmActions = createCrmEntityActionItems();
@@ -133,6 +135,7 @@ export function createSoupEntityActions(
});
const deleteAction = makeDeleteAction({
+ isTeamAdmin,
userId: () => userId(),
});
diff --git a/apps/web/src/lib/queries/soup/search.ts b/apps/web/src/lib/queries/soup/search.ts
index e303ad887b..62149c6eb2 100644
--- a/apps/web/src/lib/queries/soup/search.ts
+++ b/apps/web/src/lib/queries/soup/search.ts
@@ -37,10 +37,10 @@ export const validateSearchServiceText = (text: string) => {
return text.length >= 3;
};
-// Only plain request values and channel names enter the cached callbacks.
+// Only plain request values and channel metadata enter the cached callbacks.
function searchSoupQueryOptions(
args: SearchSoupQueryArgs,
- channels: ReadonlyArray<{ id: string; name?: string | null }>,
+ channels: Parameters<typeof createSearchResponseItemMapper>[0],
enabled: boolean,
staleTime: number | undefined
) {
@@ -110,14 +110,14 @@ export const useSearchSoupQuery = (
});
const { channels } = useChannelsContext();
- const channelNames = createMemo(() =>
- channels().map(({ id, name }) => ({ id, name }))
+ const channelMetadata = createMemo(() =>
+ channels().map(({ id, name, team_id }) => ({ id, name, team_id }))
);
return useInfiniteQuery(() =>
searchSoupQueryOptions(
{ params: args().params, body: request() },
- channelNames(),
+ channelMetadata(),
enabled(),
options?.().staleTime
)
diff --git a/apps/web/src/lib/queries/soup/transform-utils.ts b/apps/web/src/lib/queries/soup/transform-utils.ts
index 011ca8f799..3e78286cdf 100644
--- a/apps/web/src/lib/queries/soup/transform-utils.ts
+++ b/apps/web/src/lib/queries/soup/transform-utils.ts
@@ -330,7 +330,11 @@ export const useSearchResponseItemMapper = () => {
};
export const createSearchResponseItemMapper = (
- channels: ReadonlyArray<{ id: string; name?: string | null }>
+ channels: ReadonlyArray<{
+ id: string;
+ name?: string | null;
+ team_id?: string | null;
+ }>
) => {
return (
result: UnifiedSearchResponseItem,
@@ -503,8 +507,11 @@ export const createSearchResponseItemMapper = (
contentHitData: null,
source: 'service',
};
+ const channel = channels.find(
+ (channel) => channel.id === result.channel_id
+ );
const channelName =
- channels.find((channel) => channel.id === result.channel_id)?.name ??
+ channel?.name ??
(search.nameHighlight
? extractSearchSnippet(search.nameHighlight)
: blockNameToDefaultFile('channel'));
@@ -515,6 +522,7 @@ export const createSearchResponseItemMapper = (
name: channelName,
ownerId: result.owner_id ?? '',
channelType: result.channel_type as ChannelType,
+ teamId: channel?.team_id ?? undefined,
createdAt: result.metadata.created_at,
updatedAt: result.metadata.updated_at,
viewedAt: result.metadata.viewed_at,
diff --git a/apps/web/src/lib/queries/team/teams.ts b/apps/web/src/lib/queries/team/teams.ts
index e6fc7821e0..5b2929b77e 100644
--- a/apps/web/src/lib/queries/team/teams.ts
+++ b/apps/web/src/lib/queries/team/teams.ts
@@ -63,18 +63,19 @@ export function useCurrentTeamQuery(enabled?: Accessor<boolean>) {
/**
* Reactive boolean: true iff the current user has admin or owner team
- * role. Drives admin-gated UI (e.g. the companies → hidden tab and the
- * detail-page Hide button).
+ * role. When a team id is supplied, it must match that team. Drives
+ * admin-gated UI (e.g. the companies → hidden tab and detail-page Hide button).
*/
-export function useIsTeamAdmin(): Accessor<boolean> {
+export function useIsTeamAdmin(): (teamId?: string) => boolean {
const userId = useUserId();
const teamQuery = useCurrentTeamQuery();
- return () => {
+ return (teamId) => {
const uid = userId();
if (!uid) return false;
if (!queryReadyGate(teamQuery)) return false;
const team = teamQuery.data;
if (!team) return false;
+ if (teamId !== undefined && team.team.id !== teamId) return false;
const member = team.members.find((m) => m.user_id === uid);
return member?.role === TeamRole.admin || member?.role === TeamRole.owner;
};
diff --git a/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs b/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs
index 2a9c022c36..b4f2a6349b 100644
--- a/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs
+++ b/crates/agent_harness/src/domain/service/test/chat_reply/conversations.rs
@@ -166,10 +166,7 @@ async fn a_message_whose_conversation_was_deleted_is_acknowledged_instead_of_red
// Deleted after the trigger published the next message: the session row
// went with the channel, and every redelivery would be refused alike.
- channels
- .delete_channel(channel, owner.to_string())
- .await
- .unwrap();
+ channels.delete_channel(channel).await.unwrap();
mention_origin_mut(&mut command).message_id = macro_uuid::generate_uuid_v7();
assert!(
service
diff --git a/crates/channels/AGENTS.md b/crates/channels/AGENTS.md
index 72efde2fa5..2dbc549a8e 100644
--- a/crates/channels/AGENTS.md
+++ b/crates/channels/AGENTS.md
@@ -56,6 +56,12 @@ DMs, and the shared message store other domains discuss things on.
## Gotchas
+- Deletion is authorized in `ChannelServiceImpl::delete_channel`: the channel
+ participant owner may delete it; a team owner/admin may delete only a `team`
+ channel whose `team_id` matches their membership. Membership in a channel or
+ the channel creator's team never grants deletion authority on its own. Both
+ REST deletion and permanent entity deletion call this policy.
+
- Human DM messages to nonusers use immediate email, including mentions and replies; empty DM creation, bot messages, and silent/mentions-only policies do not trigger this path. Keep registered recipients on their normal notification routes.
- A person's message shares every item it links; a bot message posted for a
diff --git a/crates/channels/src/domain/entity_mutation.rs b/crates/channels/src/domain/entity_mutation.rs
index c2caac27d5..a126ccf09e 100644
--- a/crates/channels/src/domain/entity_mutation.rs
+++ b/crates/channels/src/domain/entity_mutation.rs
@@ -1,7 +1,7 @@
//! Unified entity-mutation capability impls for channels.
use entity_access::domain::models::{
- EntityAccessReceipt, MemberParticipantRole, OwnerParticipantRole, RequiredPermission,
+ EntityAccessReceipt, MemberParticipantRole, RequiredPermission, ViewOnly,
};
use entity_mutation::{
DeleteEntityPermanently, EntityMutationEffect, EntityMutationErrorCode, RenameEntity,
@@ -74,7 +74,8 @@ impl<R, E, P, F> DeleteEntityPermanently for ChannelServiceImpl<R, E, P, F>
where
Self: ChannelService,
{
- type Receipt = OwnerParticipantRole;
+ // The domain service checks ownership or admin access to this channel's team.
+ type Receipt = ViewOnly;
async fn delete_entity_permanently(
&self,
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index bda1c4445d..d46647080f 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -344,11 +344,17 @@ pub trait ChannelRepo: Send + Sync + 'static {
req: PatchChannelRequest,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
- /// Delete a channel.
+ /// Whether the user is an admin or owner of this exact team.
+ fn user_is_team_admin<'a>(
+ &self,
+ user_id: &MacroUserIdStr<'a>,
+ team_id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// Delete a channel after the domain service has authorized the caller.
fn delete_channel(
&self,
channel_id: Uuid,
- user_id: String,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
/// Atomically add or reactivate a participant, returning whether membership changed.
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index 7dfed55d54..7137539967 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -485,15 +485,45 @@ where
Ok(())
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(err, skip(self, actor))]
async fn delete_channel(
&self,
actor: Sender,
channel_id: Uuid,
) -> Result<(), ChannelMutationErr> {
let actor = require_user_actor(&actor)?;
+ let participants = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let is_owner = participants.iter().any(|participant| {
+ participant.user_id == actor.as_ref() && participant.role == ParticipantRole::Owner
+ });
+ if !is_owner {
+ let info = self
+ .repo
+ .get_channel_info(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let is_team_admin =
+ if let (ChannelType::Team, Some(team_id)) = (info.channel_type, info.team_id) {
+ self.repo
+ .user_is_team_admin(&actor, team_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ } else {
+ false
+ };
+ if !is_team_admin {
+ return Err(ChannelMutationErr::Forbidden(
+ "only the channel owner or an admin of the channel's team can delete it"
+ .to_string(),
+ ));
+ }
+ }
self.repo
- .delete_channel(channel_id, actor.as_ref().to_string())
+ .delete_channel(channel_id)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
self.events.dispatch(ChannelEvent::ChannelDeleted {
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index 1b5f9bfba3..97c529a34a 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -14,13 +14,15 @@ use crate::domain::{
},
};
use chrono::Utc;
-use entity_access::domain::models::ParticipantRole as AccessRole;
+use entity_access::domain::models::{ParticipantRole as AccessRole, TeamRole};
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use std::{
collections::HashSet,
sync::{Arc, Mutex},
};
+mod deletion;
+
fn empty_repo() -> MockChannelRepo {
let mut repo = MockChannelRepo::new();
repo.expect_get_channel_attachments()
@@ -43,6 +45,8 @@ struct FakeMutationRepoState {
channel_type: ChannelType,
channel_team_id: Option<Uuid>,
direct_agent: bool,
+ team_roles: HashMap<(String, Uuid), TeamRole>,
+ deleted_channels: Vec<Uuid>,
user_team_id: Option<Uuid>,
user_team_id_lookups: usize,
join_code: Option<Uuid>,
@@ -68,6 +72,8 @@ impl FakeMutationRepo {
channel_type: ChannelType::Private,
channel_team_id: None,
direct_agent: false,
+ team_roles: HashMap::new(),
+ deleted_channels: vec![],
user_team_id: None,
user_team_id_lookups: 0,
join_code: None,
@@ -319,7 +325,22 @@ impl ChannelRepo for FakeMutationRepo {
Ok(())
}
- async fn delete_channel(&self, _channel_id: Uuid, _user_id: String) -> Result<(), Self::Err> {
+ async fn user_is_team_admin(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team_id: Uuid,
+ ) -> Result<bool, Self::Err> {
+ Ok(self
+ .state
+ .lock()
+ .unwrap()
+ .team_roles
+ .get(&(user_id.to_string(), team_id))
+ .is_some_and(|role| *role >= TeamRole::Admin))
+ }
+
+ async fn delete_channel(&self, channel_id: Uuid) -> Result<(), Self::Err> {
+ self.state.lock().unwrap().deleted_channels.push(channel_id);
Ok(())
}
diff --git a/crates/channels/src/domain/service/test/deletion.rs b/crates/channels/src/domain/service/test/deletion.rs
new file mode 100644
index 0000000000..29d310a7f4
--- /dev/null
+++ b/crates/channels/src/domain/service/test/deletion.rs
@@ -0,0 +1,209 @@
+use super::*;
+
+#[tokio::test]
+async fn channel_owner_can_delete_every_channel_type() {
+ for channel_type in [
+ ChannelType::Private,
+ ChannelType::Public,
+ ChannelType::Team,
+ ChannelType::DirectMessage,
+ ] {
+ let channel_id = Uuid::now_v7();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().channel_type = channel_type;
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.delete_channel(sender("macro|[email protected]"), channel_id)
+ .await
+ .unwrap();
+
+ assert_eq!(repo.state.lock().unwrap().deleted_channels, [channel_id]);
+ assert!(
+ matches!(events.events.lock().unwrap().as_slice(), [ChannelEvent::ChannelDeleted { channel_id: id, .. }] if *id == channel_id)
+ );
+ }
+}
+
+#[tokio::test]
+async fn only_admins_of_the_channels_own_team_can_delete_without_ownership() {
+ let channel_team = Uuid::now_v7();
+ let other_team = Uuid::now_v7();
+ let actor = "macro|[email protected]";
+ for (channel_type, team_id, role_team, role, allowed) in [
+ (
+ ChannelType::Team,
+ Some(channel_team),
+ channel_team,
+ TeamRole::Admin,
+ true,
+ ),
+ (
+ ChannelType::Team,
+ Some(channel_team),
+ channel_team,
+ TeamRole::Owner,
+ true,
+ ),
+ (
+ ChannelType::Team,
+ Some(channel_team),
+ channel_team,
+ TeamRole::Member,
+ false,
+ ),
+ (
+ ChannelType::Team,
+ Some(channel_team),
+ other_team,
+ TeamRole::Admin,
+ false,
+ ),
+ (
+ ChannelType::Team,
+ Some(channel_team),
+ other_team,
+ TeamRole::Owner,
+ false,
+ ),
+ (
+ ChannelType::Team,
+ None,
+ channel_team,
+ TeamRole::Admin,
+ false,
+ ),
+ (
+ ChannelType::Private,
+ None,
+ channel_team,
+ TeamRole::Admin,
+ false,
+ ),
+ (
+ ChannelType::Public,
+ None,
+ channel_team,
+ TeamRole::Owner,
+ false,
+ ),
+ (
+ ChannelType::DirectMessage,
+ None,
+ channel_team,
+ TeamRole::Owner,
+ false,
+ ),
+ ] {
+ let channel_id = Uuid::now_v7();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ {
+ let mut state = repo.state.lock().unwrap();
+ state.channel_type = channel_type;
+ state.participants[1].user_id = actor.to_string();
+ state.channel_team_id = team_id;
+ state
+ .team_roles
+ .insert((actor.to_string(), role_team), role);
+ }
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ let result = svc.delete_channel(sender(actor), channel_id).await;
+
+ assert_eq!(
+ result.is_ok(),
+ allowed,
+ "{channel_type:?} {team_id:?} {role_team} {role:?}"
+ );
+ if allowed {
+ assert_eq!(repo.state.lock().unwrap().deleted_channels, [channel_id]);
+ assert_eq!(events.events.lock().unwrap().len(), 1);
+ } else {
+ assert!(matches!(result, Err(ChannelMutationErr::Forbidden(_))));
+ assert!(repo.state.lock().unwrap().deleted_channels.is_empty());
+ assert!(events.events.lock().unwrap().is_empty());
+ }
+ }
+}
+
+#[tokio::test]
+async fn channel_admin_is_not_a_team_admin() {
+ let channel_id = Uuid::now_v7();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ {
+ let mut state = repo.state.lock().unwrap();
+ state.channel_type = ChannelType::Team;
+ state.channel_team_id = Some(Uuid::now_v7());
+ state.participants[1].role = ParticipantRole::Admin;
+ state.participants[1].user_id = "macro|[email protected]".to_string();
+ }
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ let result = svc
+ .delete_channel(sender("macro|[email protected]"), channel_id)
+ .await;
+
+ assert!(matches!(result, Err(ChannelMutationErr::Forbidden(_))));
+ assert!(repo.state.lock().unwrap().deleted_channels.is_empty());
+}
+
+#[cfg(feature = "entity_mutation")]
+#[tokio::test]
+async fn permanent_delete_checks_team_authority_after_view_access() {
+ use entity_access::domain::models::{Entity, EntityPermission, ViewOnly};
+ use entity_mutation::DeleteEntityPermanently;
+
+ for allowed in [true, false] {
+ let channel_id = Uuid::now_v7();
+ let team_id = Uuid::now_v7();
+ let actor = "macro|[email protected]";
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ {
+ let mut state = repo.state.lock().unwrap();
+ state.channel_type = ChannelType::Team;
+ state.channel_team_id = Some(team_id);
+ if allowed {
+ state
+ .team_roles
+ .insert((actor.to_string(), team_id), TeamRole::Admin);
+ }
+ }
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+ let entity = Entity {
+ entity_id: channel_id.to_string(),
+ entity_type: EntityType::Channel,
+ };
+ let receipt = EntityAccessReceipt::<ViewOnly>::try_new_authenticated_user(
+ macro_id(actor),
+ entity.clone(),
+ EntityPermission::ChannelViewOnly,
+ )
+ .unwrap();
+
+ let entity = EntityType::Channel.with_entity_string(channel_id.to_string());
+ let result = svc.delete_entity_permanently(entity, receipt).await;
+
+ assert_eq!(result.is_ok(), allowed);
+ assert_eq!(
+ repo.state.lock().unwrap().deleted_channels.len(),
+ usize::from(allowed)
+ );
+ }
+}
diff --git a/crates/channels/src/inbound/axum_router.rs b/crates/channels/src/inbound/axum_router.rs
index ce19bb131a..2e7e29951b 100644
--- a/crates/channels/src/inbound/axum_router.rs
+++ b/crates/channels/src/inbound/axum_router.rs
@@ -31,7 +31,7 @@ use entity_access::{
domain::{
models::{
AccessError, AccessLevel, EntityAccessReceipt, EntityType, MemberParticipantRole,
- OwnerParticipantRole, RequiredPermission, ViewOnly,
+ RequiredPermission, ViewOnly,
},
ports::EntityAccessService,
},
@@ -393,7 +393,7 @@ pub async fn delete_channel_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractor<OwnerParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<ViewOnly, Svc, Auth>,
) -> Result<(StatusCode, String), ChannelsHandlerErr> {
let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;
let actor = user_actor_from_receipt(&access.entity_access_receipt)?;
diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rs
index e1dda24e1e..190a23ffab 100644
--- a/crates/channels/src/outbound/pg_channels_repo.rs
+++ b/crates/channels/src/outbound/pg_channels_repo.rs
@@ -2791,30 +2791,43 @@ impl ChannelRepo for PgChannelsRepo {
Ok(())
}
- async fn delete_channel(&self, channel_id: Uuid, user_id: String) -> Result<(), Self::Err> {
+ #[tracing::instrument(err, skip(self, user_id))]
+ async fn user_is_team_admin(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team_id: Uuid,
+ ) -> Result<bool, Self::Err> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM team_user
+ WHERE user_id = $1 AND team_id = $2
+ AND team_role IN ('admin'::team_role, 'owner'::team_role)
+ ) AS "is_admin!"
+ "#,
+ user_id.as_ref(),
+ team_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .context("failed to check team administration")
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn delete_channel(&self, channel_id: Uuid) -> Result<(), Self::Err> {
let result = sqlx::query!(
r#"
DELETE FROM comms_channels
WHERE id = $1
- AND EXISTS (
- SELECT 1
- FROM comms_channel_participants
- WHERE channel_id = $1
- AND user_id = $2
- AND role = 'owner'::comms_participant_role
- )
"#,
channel_id,
- user_id,
)
.execute(&self.pool)
.await
.context("failed to delete channel")?;
if result.rows_affected() == 0 {
- anyhow::bail!(
- "channel not deleted, either it didn't exist or the user_id provided was not the owner"
- );
+ anyhow::bail!("channel not deleted because it does not exist");
}
Ok(())
}
diff --git a/crates/channels/src/outbound/pg_channels_repo/tests.rs b/crates/channels/src/outbound/pg_channels_repo/tests.rs
index 5804bb7757..c209850bba 100644
--- a/crates/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/crates/channels/src/outbound/pg_channels_repo/tests.rs
@@ -62,6 +62,44 @@ fn macro_user_id(user_id: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(user_id.to_owned()).expect("valid macro user id")
}
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn team_admin_authority_is_scoped_to_exact_membership(pool: Pool<Postgres>) {
+ let repo = repo(pool.clone());
+ let team_b = Uuid::from_u128(0x22222222_2222_2222_2222_222222222222);
+ let actor = macro_user_id(LEFT_USER);
+ assert!(!repo.user_is_team_admin(&actor, TEAM_A).await.unwrap());
+
+ sqlx::query!(
+ "UPDATE team_user SET team_role = 'admin'::team_role WHERE user_id = $1",
+ LEFT_USER
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ assert!(repo.user_is_team_admin(&actor, TEAM_A).await.unwrap());
+ assert!(!repo.user_is_team_admin(&actor, team_b).await.unwrap());
+
+ sqlx::query!(
+ "UPDATE team_user SET team_role = 'owner'::team_role WHERE user_id = $1",
+ LEFT_USER
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ assert!(repo.user_is_team_admin(&actor, TEAM_A).await.unwrap());
+ assert!(
+ !repo
+ .user_is_team_admin(&macro_user_id(NON_MEMBER), TEAM_A)
+ .await
+ .unwrap()
+ );
+}
+
fn thread_rows_request(
user_id: &str,
filter: LiteralTree<ChannelThreadLiteral>,
@@ -2836,7 +2874,7 @@ async fn delete_channel_cascades_contacts_backfill_outbox_rows(pool: Pool<Postgr
.await
.unwrap();
- repo.delete_channel(created.id, USER_A.to_string())
+ repo.delete_channel(created.id)
.await
.expect("channel delete must succeed when contacts_backfill_outbox references the channel");
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index 78bb704952..8fbd95948a 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -1,5 +1,18 @@
# Channels and Messaging
+## Deleting a channel
+
+The channel owner can permanently delete their channel. A team owner or admin
+can also delete a team channel belonging to their own team. Being a participant,
+administering another team, or sharing a team with the channel creator does not
+grant permission to delete it.
+
+Use Delete from the channel row or title menu, or the mobile long-press menu.
+Confirm the deletion in the existing delete dialog; it removes the channel for
+everyone. The same permission rule applies to the delete hotkey and bulk action.
+If a bulk deletion partly succeeds, confirmed deletions stay removed and only
+failed items remain in the dialog for retry.
+
User mentions sent by integrations may contain only `userId`. For human user
IDs, messages and editors resolve the current name and fall back to the email
local part when lookup fails. Verify that these mentions remain intact when