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): restore channel picture actions and let any participant set them (#7518)

Peter Chinman9a4ca4657ad6
diff --git a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
index 8d435cb612..fc6835ff69 100644
--- a/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
+++ b/apps/web/src/features/block-channel/component/NewChannelBlockAdapter.tsx
@@ -75,13 +75,12 @@ import { isMobile } from '@core/mobile/isMobile';
import { createMethodRegistration } from '@core/orchestrator';
import { blockHotkeyScopeSignal } from '@core/signal/blockElement';
import { blockHandleSignal } from '@core/signal/load';
-import { buildEntityData } from '@entity';
+import { buildEntityData, canEditChannelIdentity } from '@entity';
import PictureIcon from '@phosphor/image.svg';
import RenameIcon from '@phosphor/pencil-line.svg';
import TrashIcon from '@phosphor/trash.svg';
import { useActiveCallQuery } from '@queries/call/call';
import { useChannelParticipantsQuery } from '@queries/channel/channel-participants';
-import { ChannelType } from '@service-storage/generated/schemas/channelType';
import { useSearchParams } from '@solidjs/router';
import { cn } from '@ui';
import {
@@ -138,16 +137,6 @@ function NewTop(props: { channelId: string }) {
const activeCallQuery = useActiveCallQuery(() => props.channelId);
const participants = () =>
participantsQuery.isLoading ? [] : participantsQuery.data;
- const picture = useChannelPictureActions({
- channelId: () => props.channelId,
- canEdit: () =>
- channelType() !== ChannelType.direct_message &&
- (participants() ?? []).some(
- (participant) =>
- participant.user_id === userId() &&
- (participant.role === 'admin' || participant.role === 'owner')
- ),
- });
const tabs = useChannelTabItems(props.channelId);
const channelEntity = () => {
@@ -167,6 +156,14 @@ function NewTop(props: { channelId: string }) {
});
};
+ const picture = useChannelPictureActions({
+ channelId: () => props.channelId,
+ canEdit: () => {
+ const entity = channelEntity();
+ return !!entity && canEditChannelIdentity(entity);
+ },
+ });
+
// Seed for "Ask Macro": a new chat with this channel @mentioned, so the
// user does not have to create an agent and mention the channel by hand.
const askMacroEntity = () => {
diff --git a/apps/web/src/features/channel/channel-picture.ts b/apps/web/src/features/channel/channel-picture.ts
index f6974cd37c..e619690c6e 100644
--- a/apps/web/src/features/channel/channel-picture.ts
+++ b/apps/web/src/features/channel/channel-picture.ts
@@ -7,22 +7,24 @@ import {
} from '@queries/channel/picture';
import type { Accessor } from 'solid-js';
-export function useChannelPictureActions(options: {
- channelId: Accessor<string>;
- canEdit: Accessor<boolean>;
-}) {
- const picture = useChannelPicture(options.channelId);
+const PICTURE_MIME_TYPES = [
+ 'image/jpeg',
+ 'image/png',
+ 'image/webp',
+ 'image/gif',
+];
+
+/**
+ * Upload and clear channel pictures, for menus that learn their channel when
+ * the user acts rather than when the menu is built. Callers own the permission
+ * check; `canEditChannelIdentity` is the rule the server enforces.
+ */
+export function useChannelPictureEditor() {
const mutation = useSetChannelPictureMutation(createStaticFile);
- const save = async (file: File | null) => {
- if (!options.canEdit() || mutation.isPending) return;
- if (
- file &&
- (!['image/jpeg', 'image/png', 'image/webp', 'image/gif'].includes(
- file.type
- ) ||
- file.size === 0)
- ) {
+ const save = async (channelId: string, file: File | null) => {
+ if (mutation.isPending) return;
+ if (file && (!PICTURE_MIME_TYPES.includes(file.type) || file.size === 0)) {
toast.failure('Choose a PNG, JPG, WebP, or GIF image');
return;
}
@@ -31,7 +33,7 @@ export function useChannelPictureActions(options: {
return;
}
try {
- await mutation.mutateAsync({ channelId: options.channelId(), file });
+ await mutation.mutateAsync({ channelId, file });
toast.success(
file ? 'Channel picture updated' : 'Channel picture removed'
);
@@ -40,29 +42,44 @@ export function useChannelPictureActions(options: {
}
};
- const pickFile = () => {
- if (!options.canEdit() || mutation.isPending) return;
+ const pickFile = (channelId: string) => {
+ if (mutation.isPending) return;
openFilePicker(
{
- acceptedMimeTypes: [
- 'image/jpeg',
- 'image/png',
- 'image/webp',
- 'image/gif',
- ],
+ acceptedMimeTypes: PICTURE_MIME_TYPES,
acceptedFileExtensions: ['jpg', 'jpeg', 'png', 'webp', 'gif'],
},
async (files) => {
- if (files[0]) await save(files[0]);
+ if (files[0]) await save(channelId, files[0]);
}
);
};
return {
- hasPicture: () => !!picture.url(),
- isAvailable: () =>
- options.canEdit() && !mutation.isPending && !picture.isLoading(),
+ isPending: () => mutation.isPending,
pickFile,
- remove: () => void save(null),
+ remove: (channelId: string) => void save(channelId, null),
+ };
+}
+
+export function useChannelPictureActions(options: {
+ channelId: Accessor<string>;
+ canEdit: Accessor<boolean>;
+}) {
+ const picture = useChannelPicture(options.channelId);
+ const editor = useChannelPictureEditor();
+
+ const isAvailable = () =>
+ options.canEdit() && !editor.isPending() && !picture.isLoading();
+
+ return {
+ hasPicture: () => !!picture.url(),
+ isAvailable,
+ pickFile: () => {
+ if (isAvailable()) editor.pickFile(options.channelId());
+ },
+ remove: () => {
+ if (isAvailable()) editor.remove(options.channelId());
+ },
};
}
diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.ts
index cc4a05c641..14049ec415 100644
--- a/apps/web/src/features/entity/types/entity.ts
+++ b/apps/web/src/features/entity/types/entity.ts
@@ -574,6 +574,21 @@ export const isNonMemberChannelEntity = (entity: EntityData): boolean => {
return isChannelEntity(entity) && entity.isParticipant === false;
};
+/**
+ * Whether the viewer may edit a channel's identity — its name and its picture.
+ *
+ * Any active participant of a named channel qualifies, which is what the server
+ * enforces for both the rename and the picture endpoints. A direct message
+ * takes its name and picture from the other participant, so neither applies.
+ */
+export const canEditChannelIdentity = (entity: EntityData): boolean => {
+ return (
+ isChannelEntity(entity) &&
+ entity.channelType !== 'direct_message' &&
+ entity.isParticipant !== false
+ );
+};
+
export const isChannelMessageEntity = (
entity: EntityData
): entity is ChannelMessageEntity => {
diff --git a/apps/web/src/features/next-soup/actions/index.ts b/apps/web/src/features/next-soup/actions/index.ts
index 075f879b2a..52731ae369 100644
--- a/apps/web/src/features/next-soup/actions/index.ts
+++ b/apps/web/src/features/next-soup/actions/index.ts
@@ -12,6 +12,7 @@ export {
} from './entity-action-context';
export { makeAddTagAction } from './make-add-tag-action';
export { makeBlockSenderAction } from './make-block-sender-action';
+export { makeChannelPictureAction } from './make-channel-picture-action';
export { makeCopyAction } from './make-copy-action';
export { makeCopyBranchNameAction } from './make-copy-branch-name-action';
export { makeCopyEntityIdAction } from './make-copy-entity-id-action';
diff --git a/apps/web/src/features/next-soup/actions/make-channel-picture-action.test.ts b/apps/web/src/features/next-soup/actions/make-channel-picture-action.test.ts
new file mode 100644
index 0000000000..c63176e973
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/make-channel-picture-action.test.ts
@@ -0,0 +1,109 @@
+import type { EntityData } from '@entity';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const pickFile = vi.fn();
+const remove = vi.fn();
+let isPending = false;
+let cachedPictureId: string | null | undefined;
+
+vi.mock('@channel/channel-picture', () => ({
+ useChannelPictureEditor: () => ({
+ isPending: () => isPending,
+ pickFile,
+ remove,
+ }),
+}));
+vi.mock('@queries/channel/picture', () => ({
+ createCachedChannelPicture: () => () => cachedPictureId,
+}));
+
+import { makeChannelPictureAction } from './make-channel-picture-action';
+
+const channel = (
+ overrides: Partial<Extract<EntityData, { type: 'channel' }>> = {}
+) =>
+ ({
+ type: 'channel',
+ id: 'c1',
+ name: 'Design',
+ ownerId: 'macro|[email protected]',
+ channelType: 'private',
+ ...overrides,
+ }) as EntityData;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ isPending = false;
+ cachedPictureId = undefined;
+});
+
+describe('makeChannelPictureAction.canExecute', () => {
+ it('allows any participant of a named channel, matching Rename', () => {
+ const { canExecute } = makeChannelPictureAction();
+ expect(canExecute(channel({ isParticipant: true }))).toBe(true);
+ expect(canExecute(channel({ channelType: 'team' }))).toBe(true);
+ });
+
+ it('refuses direct messages and channels the viewer has not joined', () => {
+ const { canExecute } = makeChannelPictureAction();
+ expect(canExecute(channel({ channelType: 'direct_message' }))).toBe(false);
+ expect(
+ canExecute(channel({ channelType: 'team', isParticipant: false }))
+ ).toBe(false);
+ });
+
+ it('refuses entities that are not channels', () => {
+ const { canExecute } = makeChannelPictureAction();
+ expect(canExecute({ type: 'document', id: 'd1' } as EntityData)).toBe(
+ false
+ );
+ });
+
+ it('refuses while an upload is still settling', () => {
+ isPending = true;
+ const { canExecute } = makeChannelPictureAction();
+ expect(canExecute(channel())).toBe(false);
+ });
+});
+
+describe('makeChannelPictureAction.hasPicture', () => {
+ it('reports a picture the cache already knows about', () => {
+ cachedPictureId = 'picture-1';
+ expect(makeChannelPictureAction().hasPicture(channel())).toBe(true);
+ });
+
+ it('stays quiet for an unknown or absent picture', () => {
+ const { hasPicture } = makeChannelPictureAction();
+ expect(hasPicture(channel())).toBe(false);
+ cachedPictureId = null;
+ expect(hasPicture(channel())).toBe(false);
+ });
+});
+
+describe('makeChannelPictureAction.execute', () => {
+ it('opens the picker for the one channel it was given', () => {
+ makeChannelPictureAction().execute([channel()]);
+ expect(pickFile).toHaveBeenCalledWith('c1');
+ });
+
+ it('does nothing for a multi-row selection or an ineligible channel', () => {
+ const { execute } = makeChannelPictureAction();
+ execute([channel(), channel({ id: 'c2' })]);
+ execute([channel({ channelType: 'direct_message' })]);
+ execute([]);
+ expect(pickFile).not.toHaveBeenCalled();
+ });
+});
+
+describe('makeChannelPictureAction.remove', () => {
+ it('clears a picture the cache knows about', () => {
+ cachedPictureId = 'picture-1';
+ makeChannelPictureAction().remove([channel()]);
+ expect(remove).toHaveBeenCalledWith('c1');
+ });
+
+ it('does nothing when there is no picture to clear', () => {
+ makeChannelPictureAction().remove([channel()]);
+ expect(remove).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/next-soup/actions/make-channel-picture-action.ts b/apps/web/src/features/next-soup/actions/make-channel-picture-action.ts
new file mode 100644
index 0000000000..1743f7852d
--- /dev/null
+++ b/apps/web/src/features/next-soup/actions/make-channel-picture-action.ts
@@ -0,0 +1,40 @@
+import { useChannelPictureEditor } from '@channel/channel-picture';
+import { canEditChannelIdentity, type EntityData } from '@entity/types/entity';
+import { createCachedChannelPicture } from '@queries/channel/picture';
+
+/**
+ * Set or clear a channel's picture.
+ *
+ * Gated exactly like Rename — any participant of a named channel — because the
+ * picture is part of the same channel identity the server lets members edit.
+ */
+export const makeChannelPictureAction = () => {
+ const editor = useChannelPictureEditor();
+ const cachedPictureId = createCachedChannelPicture();
+
+ const canExecute = (entity: EntityData): boolean =>
+ canEditChannelIdentity(entity) && !editor.isPending();
+
+ /**
+ * Whether removal is worth offering. The id comes from cache because a menu
+ * is built synchronously, and the read is tracked, so a menu built before the
+ * channel's avatar resolved gains the item once the picture arrives.
+ */
+ const hasPicture = (entity: EntityData): boolean =>
+ canExecute(entity) && !!cachedPictureId(entity.id);
+
+ // Single entity only: the file picker uploads one image for one channel.
+ const execute = (entities: EntityData[]) => {
+ const entity = entities[0];
+ if (!entity || entities.length !== 1 || !canExecute(entity)) return;
+ editor.pickFile(entity.id);
+ };
+
+ const remove = (entities: EntityData[]) => {
+ const entity = entities[0];
+ if (!entity || entities.length !== 1 || !hasPicture(entity)) return;
+ editor.remove(entity.id);
+ };
+
+ return { canExecute, hasPicture, execute, remove };
+};
diff --git a/apps/web/src/features/next-soup/actions/make-rename-action.ts b/apps/web/src/features/next-soup/actions/make-rename-action.ts
index 65579e8f70..faf117418e 100644
--- a/apps/web/src/features/next-soup/actions/make-rename-action.ts
+++ b/apps/web/src/features/next-soup/actions/make-rename-action.ts
@@ -1,6 +1,6 @@
import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';
import { toast } from '@core/component/Toast/Toast';
-import type { EntityData } from '@entity';
+import { canEditChannelIdentity, type EntityData } from '@entity/types/entity';
import { restoreSoupFocus } from '../utils';
import type { EntityActionListState } from './entity-action-context';
@@ -24,10 +24,7 @@ export const makeRenameAction = (options: MakeRenameOptions) => {
}
if (entity.type === 'foreign') return false;
- if (entity.type === 'channel') {
- if (entity.channelType === 'direct_message') return false;
- return entity.isParticipant !== false;
- }
+ if (entity.type === 'channel') return canEditChannelIdentity(entity);
return entity.ownerId === userId();
};
diff --git a/apps/web/src/features/soup/createSoupEntityActions.ts b/apps/web/src/features/soup/createSoupEntityActions.ts
index 814418b064..1a79556de7 100644
--- a/apps/web/src/features/soup/createSoupEntityActions.ts
+++ b/apps/web/src/features/soup/createSoupEntityActions.ts
@@ -4,6 +4,7 @@ import {
type EntityActionNavigationHandler,
type EntityActionViewContext,
makeBlockSenderAction,
+ makeChannelPictureAction,
makeCopyAction,
makeCopyBranchNameAction,
makeCopyEntityIdAction,
@@ -129,6 +130,8 @@ export function createSoupEntityActions(
userId: () => userId(),
});
+ const channelPictureAction = makeChannelPictureAction();
+
const copyAction = makeCopyAction();
const favoriteAction = makeFavoriteAction();
const muteAction = makeMuteAction({
@@ -302,6 +305,23 @@ export function createSoupEntityActions(
});
}
+ // Sits with Rename because it edits the same channel identity, under the
+ // same participant rule. Single-entity only: one upload, one channel.
+ if (entities.length === 1 && channelPictureAction.canExecute(entities[0])) {
+ middleItems.push({
+ id: 'set-channel-picture',
+ label: 'Set channel picture',
+ onClick: () => channelPictureAction.execute(entities),
+ });
+ if (channelPictureAction.hasPicture(entities[0])) {
+ middleItems.push({
+ id: 'remove-channel-picture',
+ label: 'Remove channel picture',
+ onClick: () => channelPictureAction.remove(entities),
+ });
+ }
+ }
+
if (canExecuteAll(favoriteAction.canExecute)) {
const allFavorited = entities.every((entity) =>
favoriteAction.isFavorited(entity)
diff --git a/apps/web/src/lib/queries/channel/picture.ts b/apps/web/src/lib/queries/channel/picture.ts
index 6c6cac0536..cd060280d1 100644
--- a/apps/web/src/lib/queries/channel/picture.ts
+++ b/apps/web/src/lib/queries/channel/picture.ts
@@ -3,7 +3,7 @@ import { throwOnErr } from '@core/util/result';
import { staticFileClient } from '@service-static-files/client';
import { storageServiceClient } from '@service-storage/client';
import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
-import type { Accessor } from 'solid-js';
+import { type Accessor, createSignal, onCleanup } from 'solid-js';
import { queryClient } from '../client';
import { previewDataLoader } from '../preview/dataloader';
import { isChannelPreviewItem } from '../preview/types';
@@ -66,6 +66,37 @@ export function useChannelPicture(channelId: Accessor<string>) {
};
}
+/**
+ * Reactive reader for the picture ids already in cache, for menus that are
+ * built synchronously and so cannot own a query per channel they list.
+ *
+ * Reads are tracked, so a menu built before a channel's picture loaded
+ * recomputes once it arrives. `undefined` means unknown rather than absent, so
+ * a caller gating a "remove" item stays silent until then rather than claiming
+ * there is no picture.
+ */
+export function createCachedChannelPicture() {
+ const [revision, setRevision] = createSignal(0);
+ const scope = channelKeys.picture._def;
+ const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
+ // Observer churn (every avatar mounting in a long list) cannot change the
+ // cached id, so only data events are worth a recompute.
+ if (!['added', 'updated', 'removed'].includes(event.type)) return;
+ if (scope.some((part, index) => event.query.queryKey[index] !== part)) {
+ return;
+ }
+ setRevision((current) => current + 1);
+ });
+ onCleanup(unsubscribe);
+
+ return (channelId: string) => {
+ revision();
+ return queryClient.getQueryData<string | null>(
+ channelKeys.picture(channelId).queryKey
+ );
+ };
+}
+
export function useSetChannelPictureMutation(
upload: (file: File) => Promise<string>
) {
diff --git a/apps/web/src/lib/queries/channel/tests/picture.test.tsx b/apps/web/src/lib/queries/channel/tests/picture.test.tsx
index d48e428d33..7a93e4e146 100644
--- a/apps/web/src/lib/queries/channel/tests/picture.test.tsx
+++ b/apps/web/src/lib/queries/channel/tests/picture.test.tsx
@@ -6,6 +6,7 @@ import { storageServiceClient } from '@service-storage/client';
import { QueryObserver } from '@tanstack/query-core';
import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
import { ok } from 'neverthrow';
+import { createMemo, createRoot } from 'solid-js';
import { render } from 'solid-js/web';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { previewDataLoader } from '../../preview/dataloader';
@@ -35,6 +36,7 @@ vi.mock('@ui', async () => ({
}));
import {
+ createCachedChannelPicture,
handleChannelPictureChanged,
invalidateChannelPictures,
useSetChannelPictureMutation,
@@ -217,6 +219,42 @@ it('preserves the existing picture if upload confirmation fails', async () => {
);
});
+it('tracks cached picture ids so a menu built before one loads recomputes', () => {
+ createRoot((dispose) => {
+ const cachedPictureId = createCachedChannelPicture();
+ // What a "Remove channel picture" item is gated on. A menu opened against
+ // a cold cache has to pick the item up once the avatar's query lands.
+ const offersRemoval = createMemo(() => !!cachedPictureId('channel'));
+ expect(offersRemoval()).toBe(false);
+
+ client.setQueryData(channelKeys.picture('channel').queryKey, 'picture-1');
+ expect(offersRemoval()).toBe(true);
+
+ client.setQueryData(channelKeys.picture('channel').queryKey, null);
+ expect(offersRemoval()).toBe(false);
+
+ // Another channel's picture must not make this one look removable.
+ client.setQueryData(channelKeys.picture('other').queryKey, 'picture-2');
+ expect(offersRemoval()).toBe(false);
+ dispose();
+ });
+});
+
+it('stops tracking the cache once its owner is disposed', () => {
+ const unsubscribe = vi.fn();
+ const subscribe = vi
+ .spyOn(client.getQueryCache(), 'subscribe')
+ .mockReturnValue(unsubscribe);
+ createRoot((dispose) => {
+ createCachedChannelPicture();
+ expect(subscribe).toHaveBeenCalledTimes(1);
+ expect(unsubscribe).not.toHaveBeenCalled();
+ dispose();
+ });
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ subscribe.mockRestore();
+});
+
it('refreshes another session immediately on picture events and after reconnect', async () => {
const queryKey = channelKeys.picture('channel').queryKey;
client.setQueryData(queryKey, 'old-picture');
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index bfb286e311..6fc82eb32b 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -3703,7 +3703,7 @@ export const removeParticipantsBody = zod
.describe('Request to remove participants.');
/**
- * @summary Set a channel or group chat profile picture. Requires channel admin or owner access.
+ * @summary Set a channel or group chat profile picture. Requires channel participation.
*/
export const setChannelPictureParams = zod.object({
channel_id: zod.uuid().describe('Channel ID'),
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 1efc8056d7..0f7f4a92e9 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -4754,7 +4754,7 @@
"/channels/{channel_id}/profile_picture": {
"put": {
"tags": ["channels::inbound::axum_router::profile_picture"],
- "summary": "Set a channel or group chat profile picture. Requires channel admin or owner access.",
+ "summary": "Set a channel or group chat profile picture. Requires channel participation.",
"operationId": "set_channel_picture",
"parameters": [
{
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index 4f8b5051af..683b5d4c41 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -33,9 +33,11 @@ use std::collections::HashMap;
use std::collections::HashSet;
use uuid::Uuid;
-/// Verified channel administration access required to change a channel picture.
-pub type ChannelPictureAccess =
- EntityAccessReceipt<entity_access::domain::models::AdminParticipantRole>;
+/// Verified channel participation required to change a channel picture.
+///
+/// The picture is part of the channel identity any participant may edit, so it
+/// carries the same requirement as renaming rather than an admin-only one.
+pub type ChannelPictureAccess = EntityAccessReceipt<MemberParticipantRole>;
/// Repository for channel list persistence and query data.
#[cfg(feature = "list")]
@@ -419,7 +421,7 @@ pub trait ChannelRepo: Send + Sync + 'static {
/// Service for channel reads and mutations.
pub trait ChannelService: Send + Sync + 'static {
- /// Set a channel picture using verified channel administration access.
+ /// Set a channel picture using verified channel participation.
fn set_channel_picture(
&self,
access: ChannelPictureAccess,
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index 13540458a6..2e09557d65 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -11,8 +11,8 @@ use crate::domain::{
},
ports::{
ChannelAttachmentsPage, ChannelEventDispatcher, ChannelMessagesErr, ChannelMutationErr,
- ChannelPictureFile, ChannelPictureFiles, ChannelReferenceSharePermissions, ChannelRepo,
- ChannelService,
+ ChannelPictureAccess, ChannelPictureFile, ChannelPictureFiles,
+ ChannelReferenceSharePermissions, ChannelRepo, ChannelService,
},
};
use bot_id::{BotId, cowlike::CowLike};
@@ -843,7 +843,7 @@ where
#[tracing::instrument(err, skip(self, access))]
async fn set_channel_picture(
&self,
- access: EntityAccessReceipt<entity_access::domain::models::AdminParticipantRole>,
+ access: ChannelPictureAccess,
picture_id: Option<Uuid>,
) -> Result<(), ChannelMutationErr> {
if access.entity().entity_type != EntityType::Channel {
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index 95016929fd..531ce292c5 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -1821,11 +1821,11 @@ fn owned_picture_file() -> ChannelPictureFile {
}
#[tokio::test]
-async fn channel_picture_can_be_set_replaced_and_removed_by_admins_and_owners() {
+async fn channel_picture_can_be_set_replaced_and_removed_by_any_participant() {
use entity_access::domain::models::{
- AdminParticipantRole, Entity, EntityPermission, ParticipantRole as AccessRole,
+ Entity, EntityPermission, MemberParticipantRole, ParticipantRole as AccessRole,
};
- for role in [AccessRole::Admin, AccessRole::Owner] {
+ for role in [AccessRole::Member, AccessRole::Admin, AccessRole::Owner] {
let channel_id = Uuid::new_v4();
let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
let events = FakeEvents::default();
@@ -1840,7 +1840,7 @@ async fn channel_picture_can_be_set_replaced_and_removed_by_admins_and_owners()
});
let pictures = [Some(Uuid::new_v4()), Some(Uuid::new_v4()), None];
for picture in pictures {
- let access = EntityAccessReceipt::<AdminParticipantRole>::try_new_authenticated_user(
+ let access = EntityAccessReceipt::<MemberParticipantRole>::try_new_authenticated_user(
macro_id("macro|[email protected]"),
Entity {
entity_id: channel_id.to_string(),
@@ -1867,7 +1867,7 @@ async fn channel_picture_can_be_set_replaced_and_removed_by_admins_and_owners()
#[tokio::test]
async fn repeated_channel_picture_updates_do_not_publish_false_activity() {
- use entity_access::domain::models::AdminParticipantRole;
+ use entity_access::domain::models::MemberParticipantRole;
let channel_id = Uuid::new_v4();
let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
let events = FakeEvents::default();
@@ -1879,7 +1879,7 @@ async fn repeated_channel_picture_updates_do_not_publish_false_activity() {
let picture = Some(Uuid::new_v4());
for (value, expected_events) in [(None, 0), (picture, 1), (picture, 1), (None, 2), (None, 2)] {
let access =
- EntityAccessReceipt::<AdminParticipantRole>::dangerously_assert_authenticated_user(
+ EntityAccessReceipt::<MemberParticipantRole>::dangerously_assert_authenticated_user(
macro_id("macro|[email protected]"),
&channel_id.to_string(),
EntityType::Channel,
@@ -1890,35 +1890,45 @@ async fn repeated_channel_picture_updates_do_not_publish_false_activity() {
}
#[test]
-fn channel_members_cannot_obtain_picture_write_access() {
+fn channel_picture_write_access_requires_an_active_participant_role() {
use entity_access::domain::models::{
- AdminParticipantRole, Entity, EntityPermission, ParticipantRole as AccessRole,
+ Entity, EntityPermission, MemberParticipantRole, ParticipantRole as AccessRole,
+ };
+ let entity = || Entity {
+ entity_id: Uuid::new_v4().to_string(),
+ entity_type: EntityType::Channel,
};
assert!(
- EntityAccessReceipt::<AdminParticipantRole>::try_new_authenticated_user(
+ EntityAccessReceipt::<MemberParticipantRole>::try_new_authenticated_user(
macro_id("macro|[email protected]"),
- Entity {
- entity_id: Uuid::new_v4().to_string(),
- entity_type: EntityType::Channel
- },
+ entity(),
EntityPermission::ChannelRole {
role: AccessRole::Member
},
)
+ .is_ok()
+ );
+ // A viewer of a team channel they have not joined cannot edit its picture.
+ assert!(
+ EntityAccessReceipt::<MemberParticipantRole>::try_new_authenticated_user(
+ macro_id("macro|[email protected]"),
+ entity(),
+ EntityPermission::ChannelViewOnly,
+ )
.is_err()
);
}
#[tokio::test]
async fn channel_picture_rejects_direct_messages_and_non_channel_receipts() {
- use entity_access::domain::models::AdminParticipantRole;
+ use entity_access::domain::models::MemberParticipantRole;
let channel_id = Uuid::new_v4();
let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
repo.state.lock().unwrap().channel_type = ChannelType::DirectMessage;
let svc = ChannelServiceImpl::new(repo.clone());
for entity_type in [EntityType::Channel, EntityType::Document] {
let access =
- EntityAccessReceipt::<AdminParticipantRole>::dangerously_assert_authenticated_user(
+ EntityAccessReceipt::<MemberParticipantRole>::dangerously_assert_authenticated_user(
macro_id("macro|[email protected]"),
&channel_id.to_string(),
entity_type,
@@ -1933,7 +1943,7 @@ async fn channel_picture_rejects_direct_messages_and_non_channel_receipts() {
#[tokio::test]
async fn channel_picture_rejects_foreign_missing_pending_non_image_and_unavailable_files() {
- use entity_access::domain::models::AdminParticipantRole;
+ use entity_access::domain::models::MemberParticipantRole;
let files = [
FakePictureFiles {
file: Some(ChannelPictureFile {
@@ -1976,7 +1986,7 @@ async fn channel_picture_rejects_foreign_missing_pending_non_image_and_unavailab
)
.with_picture_files(file);
let access =
- EntityAccessReceipt::<AdminParticipantRole>::dangerously_assert_authenticated_user(
+ EntityAccessReceipt::<MemberParticipantRole>::dangerously_assert_authenticated_user(
macro_id("macro|[email protected]"),
&channel_id.to_string(),
EntityType::Channel,
@@ -1993,15 +2003,16 @@ async fn channel_picture_rejects_foreign_missing_pending_non_image_and_unavailab
#[tokio::test]
async fn channel_picture_removal_does_not_require_static_file_availability() {
- use entity_access::domain::models::AdminParticipantRole;
+ use entity_access::domain::models::MemberParticipantRole;
let channel_id = Uuid::new_v4();
let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
let svc = ChannelServiceImpl::new(repo.clone());
- let access = EntityAccessReceipt::<AdminParticipantRole>::dangerously_assert_authenticated_user(
- macro_id("macro|[email protected]"),
- &channel_id.to_string(),
- EntityType::Channel,
- );
+ let access =
+ EntityAccessReceipt::<MemberParticipantRole>::dangerously_assert_authenticated_user(
+ macro_id("macro|[email protected]"),
+ &channel_id.to_string(),
+ EntityType::Channel,
+ );
svc.set_channel_picture(access, None).await.unwrap();
assert_eq!(*repo.picture_updates.lock().unwrap(), [(channel_id, None)]);
}
diff --git a/crates/channels/src/inbound/axum_router/profile_picture.rs b/crates/channels/src/inbound/axum_router/profile_picture.rs
index 7ba0074e68..2da72cad36 100644
--- a/crates/channels/src/inbound/axum_router/profile_picture.rs
+++ b/crates/channels/src/inbound/axum_router/profile_picture.rs
@@ -1,5 +1,5 @@
use super::*;
-use entity_access::domain::models::AdminParticipantRole;
+use entity_access::domain::models::MemberParticipantRole;
/// Replace a channel's picture, or remove it by sending a null file id.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
@@ -8,7 +8,7 @@ pub struct SetChannelPictureRequest {
pub profile_picture_id: Option<Uuid>,
}
-/// Set a channel or group chat profile picture. Requires channel admin or owner access.
+/// Set a channel or group chat profile picture. Requires channel participation.
#[utoipa::path(
put,
path = "/channels/{channel_id}/profile_picture",
@@ -31,7 +31,7 @@ pub async fn set_channel_picture_handler<
Auth: MacroAuthorizationService,
>(
State(state): State<ChannelsRouterState<S, Svc, Auth>>,
- access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc, Auth>,
+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc, Auth>,
Json(request): Json<SetChannelPictureRequest>,
) -> Result<StatusCode, ChannelsHandlerErr> {
state
diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rs
index 166b429ad2..5580f06ee0 100644
--- a/crates/channels/src/inbound/axum_router/test.rs
+++ b/crates/channels/src/inbound/axum_router/test.rs
@@ -5,7 +5,8 @@ use crate::domain::models::{
RemoveParticipantsRequest, Sender,
};
use crate::domain::ports::{
- ChannelAttachmentsPage, ChannelMessagesErr, ChannelMutationErr, ChannelService,
+ ChannelAttachmentsPage, ChannelMessagesErr, ChannelMutationErr, ChannelPictureAccess,
+ ChannelService,
};
use axum::{
Router,
@@ -15,8 +16,8 @@ use axum::{
use entity_access::domain::models::TeamRole;
use entity_access::domain::{
models::{
- AccessError, AccessLevel, AdminParticipantRole, BotAccessScope, BotId, Entity,
- EntityAccessReceipt, EntityPermission, EntityType, MemberParticipantRole,
+ AccessError, AccessLevel, BotAccessScope, BotId, Entity, EntityAccessReceipt,
+ EntityPermission, EntityType, MemberParticipantRole,
ParticipantRole as EntityParticipantRole, RequiredPermission, UserTeamInfo,
},
ports::EntityAccessService,
@@ -266,9 +267,7 @@ struct MockService;
impl ChannelService for MockService {
async fn set_channel_picture(
&self,
- _access: entity_access::domain::models::EntityAccessReceipt<
- entity_access::domain::models::AdminParticipantRole,
- >,
+ _access: crate::domain::ports::ChannelPictureAccess,
_picture_id: Option<uuid::Uuid>,
) -> Result<(), crate::domain::ports::ChannelMutationErr> {
unimplemented!("picture mutation is not used by this fixture")
@@ -334,9 +333,7 @@ struct ErrorService;
impl ChannelService for ErrorService {
async fn set_channel_picture(
&self,
- _access: entity_access::domain::models::EntityAccessReceipt<
- entity_access::domain::models::AdminParticipantRole,
- >,
+ _access: crate::domain::ports::ChannelPictureAccess,
_picture_id: Option<uuid::Uuid>,
) -> Result<(), crate::domain::ports::ChannelMutationErr> {
unimplemented!("picture mutation is not used by this fixture")
@@ -374,9 +371,7 @@ struct ParticipantsService;
impl ChannelService for ParticipantsService {
async fn set_channel_picture(
&self,
- _access: entity_access::domain::models::EntityAccessReceipt<
- entity_access::domain::models::AdminParticipantRole,
- >,
+ _access: crate::domain::ports::ChannelPictureAccess,
_picture_id: Option<uuid::Uuid>,
) -> Result<(), crate::domain::ports::ChannelMutationErr> {
unimplemented!("picture mutation is not used by this fixture")
@@ -452,9 +447,7 @@ impl JoinLinkService {
impl ChannelService for JoinLinkService {
async fn set_channel_picture(
&self,
- _access: entity_access::domain::models::EntityAccessReceipt<
- entity_access::domain::models::AdminParticipantRole,
- >,
+ _access: crate::domain::ports::ChannelPictureAccess,
_picture_id: Option<uuid::Uuid>,
) -> Result<(), crate::domain::ports::ChannelMutationErr> {
unimplemented!("picture mutation is not used by this fixture")
@@ -530,7 +523,7 @@ struct RecordingMutationService {
impl ChannelService for RecordingMutationService {
async fn set_channel_picture(
&self,
- access: EntityAccessReceipt<AdminParticipantRole>,
+ access: ChannelPictureAccess,
picture_id: Option<Uuid>,
) -> Result<(), ChannelMutationErr> {
self.pictures
@@ -1363,9 +1356,7 @@ struct ActivityService {
impl ChannelService for ActivityService {
async fn set_channel_picture(
&self,
- _access: entity_access::domain::models::EntityAccessReceipt<
- entity_access::domain::models::AdminParticipantRole,
- >,
+ _access: crate::domain::ports::ChannelPictureAccess,
_picture_id: Option<uuid::Uuid>,
) -> Result<(), crate::domain::ports::ChannelMutationErr> {
unimplemented!("picture mutation is not used by this fixture")
@@ -1545,7 +1536,7 @@ async fn post_activity_rejects_invalid_channel_id() {
}
#[tokio::test]
-async fn picture_endpoint_requires_channel_admin_and_passes_the_verified_channel() {
+async fn picture_endpoint_accepts_any_participant_and_passes_the_verified_channel() {
for role in [
EntityParticipantRole::Member,
EntityParticipantRole::Admin,
@@ -1577,15 +1568,39 @@ async fn picture_endpoint_requires_channel_admin_and_passes_the_verified_channel
)
.await
.unwrap();
- if role == EntityParticipantRole::Member {
- assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
- assert!(pictures.lock().unwrap().is_empty());
- } else {
- assert_eq!(response.status(), StatusCode::NO_CONTENT);
- assert_eq!(
- *pictures.lock().unwrap(),
- vec![(channel_id.to_string(), Some(picture_id))]
- );
- }
+ assert_eq!(response.status(), StatusCode::NO_CONTENT);
+ assert_eq!(
+ *pictures.lock().unwrap(),
+ vec![(channel_id.to_string(), Some(picture_id))]
+ );
}
}
+
+#[tokio::test]
+async fn picture_endpoint_rejects_a_viewer_who_is_not_a_participant() {
+ let service = RecordingMutationService::default();
+ let pictures = service.pictures.clone();
+ let app = channels_router(ChannelsRouterState::new(
+ service,
+ TestAccessService::channel_view_only(),
+ authorization_state(),
+ ));
+ let response = app
+ .oneshot(
+ Request::put(format!("/{}/profile_picture", Uuid::new_v4()))
+ .header(
+ header::AUTHORIZATION,
+ format!("Bearer {VALID_BEARER_TOKEN}"),
+ )
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(
+ serde_json::json!({"profile_picture_id": Uuid::new_v4()}).to_string(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(pictures.lock().unwrap().is_empty());
+}
diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rs
index 1cb90f1144..547b64e188 100644
--- a/crates/channels/src/inbound/toolset/test.rs
+++ b/crates/channels/src/inbound/toolset/test.rs
@@ -365,9 +365,7 @@ impl ChannelService for ToolTestChannelService {
async fn set_channel_picture(
&self,
- _access: entity_access::domain::models::EntityAccessReceipt<
- entity_access::domain::models::AdminParticipantRole,
- >,
+ _access: crate::domain::ports::ChannelPictureAccess,
_picture_id: Option<uuid::Uuid>,
) -> Result<(), crate::domain::ports::ChannelMutationErr> {
unimplemented!("picture mutation is not used by this fixture")
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index 7f524a441d..a6a32e5d19 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -1121,12 +1121,12 @@ conversation renders an inline detail whose top bar holds the channel avatar
and name, the same inset tab strip, live viewer avatars, and the `Call` and
`Ask Macro` buttons. In Chat an ellipsis follows the name and opens the same
entity actions as right-clicking the conversation's rail row — `Open in new
-split`, `Rename`, `Favorite`/`Unfavorite`, `Snooze notifications…`, `Mute
-notifications`, `Remind me`, `Copy Link`, `Copy ID` — so a channel can be
-favorited without finding its row. A channel inlined in another view's detail
-stack has no such menu. Channel-picture actions are in neither: they belong to
-the split's own title `...` menu, so open the channel as a split (shift-click a
-rail row) to reach them.
+split`, `Rename`, `Set channel picture`, `Remove channel picture` (only when the
+channel has one), `Favorite`/`Unfavorite`, `Remind me`, `Snooze notifications…`, `Mute
+notifications`, `Copy Link`, `Copy ID` — so a channel can be favorited or given
+a picture without finding its row. A channel inlined in
+another view's detail stack has no such menu. The split's own title `...` menu
+offers the same picture actions.
`Calls` tab: recordings, transcriptions, and summaries for this channel. Click a
row to open the call. The search field above the list matches call names and
@@ -1218,18 +1218,21 @@ message or acknowledgement and verify that it does not pull you to latest.
## Channel pictures
-Channels and group chats can have a custom picture. Any active participant can
-`Rename` a named channel from the title menu. Direct messages cannot be renamed.
-Only admins and owners also get `Set channel picture` and `Remove channel
-picture`. Choose `Set channel picture` to add or replace a picture. Select a PNG, JPG,
-WebP, or GIF up to 16 MB. The upload must finish before the picture is saved;
-the server accepts only supported images uploaded by the person setting the
-picture. An error leaves the previous picture in place. When a picture is set, the menu also offers
-`Remove channel picture` to restore the standard channel icon. The picture
+Channels and group chats can have a custom picture. Anyone who can `Rename` a
+channel can also set its picture: any active participant of a named channel,
+from the channel's rail context menu, the Chat title ellipsis, or the split's
+own title `...` menu. Direct messages can be neither renamed nor given a
+picture. Choose `Set channel picture` to add or replace a picture. Select a PNG,
+JPG, WebP, or GIF up to 16 MB. The upload must finish before the picture is
+saved; the server accepts only supported images uploaded by the person setting
+the picture. An error leaves the previous picture in place. When a picture is
+set, the menu also offers `Remove channel picture` to restore the standard
+channel icon. The picture
beside the title is display-only and also appears in shared channel rows.
Picture changes refresh other participants' open sessions, including after
reconnecting.
-Members see the picture without editing controls. One-to-one direct messages
+A team channel the viewer has not joined shows its picture without editing
+controls. One-to-one direct messages
continue to show the other person's user picture.
Opening the slash menu with `/` lists Normal Text, headings, and the other
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index e8b768a03d..0642f69db8 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -847,7 +847,7 @@ export class Sdk extends HeyApiClient {
}
/**
- * Set a channel or group chat profile picture. Requires channel admin or owner access.
+ * Set a channel or group chat profile picture. Requires channel participation.
*/
public setChannelPicture<ThrowOnError extends boolean = false>(options: Options<SetChannelPictureData, ThrowOnError>): RequestResult<SetChannelPictureResponses, SetChannelPictureErrors, ThrowOnError> {
return (options.client ?? this.client).put<SetChannelPictureResponses, SetChannelPictureErrors, ThrowOnError>({
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 1efc8056d7..0f7f4a92e9 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -4754,7 +4754,7 @@
"/channels/{channel_id}/profile_picture": {
"put": {
"tags": ["channels::inbound::axum_router::profile_picture"],
- "summary": "Set a channel or group chat profile picture. Requires channel admin or owner access.",
+ "summary": "Set a channel or group chat profile picture. Requires channel participation.",
"operationId": "set_channel_picture",
"parameters": [
{