Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(channels): restrict labels to team channels (#6801)
Eric Hayes7867c740f9c0
diff --git a/.sqlx/query-0935d6e6df07b7a7b05f9d284dc5c780ece714f7357c7e5d8430b298f7fd2ed8.json b/.sqlx/query-0935d6e6df07b7a7b05f9d284dc5c780ece714f7357c7e5d8430b298f7fd2ed8.jsonnew file mode 100644index 0000000000..b43d5fde9d--- /dev/null+++ b/.sqlx/query-0935d6e6df07b7a7b05f9d284dc5c780ece714f7357c7e5d8430b298f7fd2ed8.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_channel_participants (channel_id, role, user_id)\n VALUES ($1, 'member', $2)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "0935d6e6df07b7a7b05f9d284dc5c780ece714f7357c7e5d8430b298f7fd2ed8"+}diff --git a/.sqlx/query-0f6fb3b1db8347505a6104b4dcf3a9a1f918cc66344494c95e3bacffcdb418ad.json b/.sqlx/query-0f6fb3b1db8347505a6104b4dcf3a9a1f918cc66344494c95e3bacffcdb418ad.jsondeleted file mode 100644index 0a061a2db3..0000000000--- a/.sqlx/query-0f6fb3b1db8347505a6104b4dcf3a9a1f918cc66344494c95e3bacffcdb418ad.json+++ /dev/null@@ -1,29 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT c.id, c.channel_type::text as \"channel_type!\"\n FROM comms_channels c\n JOIN comms_channel_participants p ON p.channel_id = c.id\n WHERE c.id = ANY($1) AND p.user_id = $2 AND p.left_at IS NULL\n ORDER BY c.id FOR SHARE OF c, p",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "channel_type!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "UuidArray",- "Text"- ]- },- "nullable": [- false,- null- ]- },- "hash": "0f6fb3b1db8347505a6104b4dcf3a9a1f918cc66344494c95e3bacffcdb418ad"-}diff --git a/.sqlx/query-158f9b090edb519c7f9bcb11b4053878870558208d979eb90cde3d9b2c3b0c0a.json b/.sqlx/query-158f9b090edb519c7f9bcb11b4053878870558208d979eb90cde3d9b2c3b0c0a.jsondeleted file mode 100644index 5600624425..0000000000--- a/.sqlx/query-158f9b090edb519c7f9bcb11b4053878870558208d979eb90cde3d9b2c3b0c0a.json+++ /dev/null@@ -1,72 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n WITH labels AS (\n SELECT l.*, ARRAY(\n SELECT c.id\n FROM comms_channels c\n JOIN comms_channel_participants p\n ON p.channel_id = c.id AND p.user_id = $3 AND p.left_at IS NULL\n WHERE (\n l.name_contains IS NULL AND EXISTS (\n SELECT 1 FROM channel_label_channel lc\n WHERE lc.label_id = l.id AND lc.channel_id = c.id\n )\n ) OR (\n l.name_contains IS NOT NULL AND c.channel_type != 'direct_message'\n AND strpos(lower(c.name), lower(l.name_contains)) > 0\n )\n ORDER BY lower(c.name), c.id\n ) AS visible_ids\n FROM channel_label l\n WHERE l.scope_key = $1 AND ($2::uuid IS NULL OR l.id = $2)\n )\n SELECT\n l.id as \"id!\",\n l.team_id as \"team_id?\",\n l.name as \"name!\",\n l.name_contains as \"name_contains?\",\n l.sort_order as \"sort_order!\",\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n l.visible_ids as \"channel_ids!: Vec<Uuid>\",\n CASE WHEN l.name_contains IS NULL THEN\n (SELECT COUNT(*) FROM channel_label_channel lc WHERE lc.label_id = l.id)\n ELSE cardinality(l.visible_ids)::bigint END as \"channel_count!\"\n FROM labels l\n ORDER BY l.sort_order, l.created_at, l.id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id!",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id?",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "name!",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "name_contains?",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "sort_order!",- "type_info": "Float8"- },- {- "ordinal": 5,- "name": "created_at!",- "type_info": "Timestamptz"- },- {- "ordinal": 6,- "name": "updated_at!",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "channel_ids!: Vec<Uuid>",- "type_info": "UuidArray"- },- {- "ordinal": 8,- "name": "channel_count!",- "type_info": "Int8"- }- ],- "parameters": {- "Left": [- "Text",- "Uuid",- "Text"- ]- },- "nullable": [- false,- true,- false,- true,- false,- false,- false,- null,- null- ]- },- "hash": "158f9b090edb519c7f9bcb11b4053878870558208d979eb90cde3d9b2c3b0c0a"-}diff --git a/.sqlx/query-21a5251aafa52d9ef1be79a2d66f4cabbc5609b7e5d136489c1a8df3252277b0.json b/.sqlx/query-21a5251aafa52d9ef1be79a2d66f4cabbc5609b7e5d136489c1a8df3252277b0.jsonnew file mode 100644index 0000000000..48c8023eab--- /dev/null+++ b/.sqlx/query-21a5251aafa52d9ef1be79a2d66f4cabbc5609b7e5d136489c1a8df3252277b0.json@@ -0,0 +1,72 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH labels AS (\n SELECT l.*, ARRAY(\n SELECT c.id\n FROM comms_channels c\n JOIN comms_channel_participants p\n ON p.channel_id = c.id AND p.user_id = $3 AND p.left_at IS NULL\n WHERE c.channel_type = 'team'\n AND (l.team_id IS NULL OR c.team_id = l.team_id)\n AND ((\n l.name_contains IS NULL AND EXISTS (\n SELECT 1 FROM channel_label_channel lc\n WHERE lc.label_id = l.id AND lc.channel_id = c.id\n )\n ) OR (\n l.name_contains IS NOT NULL\n AND strpos(lower(c.name), lower(l.name_contains)) > 0\n ))\n ORDER BY lower(c.name), c.id\n ) AS visible_ids\n FROM channel_label l\n WHERE l.scope_key = $1 AND ($2::uuid IS NULL OR l.id = $2)\n )\n SELECT\n l.id as \"id!\",\n l.team_id as \"team_id?\",\n l.name as \"name!\",\n l.name_contains as \"name_contains?\",\n l.sort_order as \"sort_order!\",\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n l.visible_ids as \"channel_ids!: Vec<Uuid>\",\n CASE WHEN l.name_contains IS NULL THEN\n (SELECT COUNT(*) FROM channel_label_channel lc\n JOIN comms_channels c ON c.id = lc.channel_id\n WHERE lc.label_id = l.id AND c.channel_type = 'team'\n AND (l.team_id IS NULL OR c.team_id = l.team_id))\n ELSE cardinality(l.visible_ids)::bigint END as \"channel_count!\"\n FROM labels l\n ORDER BY l.sort_order, l.created_at, l.id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "name!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "name_contains?",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "sort_order!",+ "type_info": "Float8"+ },+ {+ "ordinal": 5,+ "name": "created_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "updated_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "channel_ids!: Vec<Uuid>",+ "type_info": "UuidArray"+ },+ {+ "ordinal": 8,+ "name": "channel_count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ false,+ true,+ false,+ false,+ false,+ null,+ null+ ]+ },+ "hash": "21a5251aafa52d9ef1be79a2d66f4cabbc5609b7e5d136489c1a8df3252277b0"+}diff --git a/.sqlx/query-240725f9f867a15d13b90008e42f8e41f01504c8bbeee1bd1c1b527d2457f8ad.json b/.sqlx/query-240725f9f867a15d13b90008e42f8e41f01504c8bbeee1bd1c1b527d2457f8ad.jsonnew file mode 100644index 0000000000..c5fcc1e2c6--- /dev/null+++ b/.sqlx/query-240725f9f867a15d13b90008e42f8e41f01504c8bbeee1bd1c1b527d2457f8ad.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT c.id, c.team_id\n FROM comms_channels c\n JOIN comms_channel_participants p ON p.channel_id = c.id\n WHERE c.id = ANY($1) AND p.user_id = $2 AND p.left_at IS NULL\n ORDER BY c.id FOR SHARE OF c, p",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "Text"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "240725f9f867a15d13b90008e42f8e41f01504c8bbeee1bd1c1b527d2457f8ad"+}diff --git a/.sqlx/query-26e90b7b244ce94450797f8e0ab9a2fb4ef12d63913566c24238b04fc9b88bff.json b/.sqlx/query-26e90b7b244ce94450797f8e0ab9a2fb4ef12d63913566c24238b04fc9b88bff.jsonnew file mode 100644index 0000000000..c675f3a89d--- /dev/null+++ b/.sqlx/query-26e90b7b244ce94450797f8e0ab9a2fb4ef12d63913566c24238b04fc9b88bff.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE comms_channels SET channel_type = 'public', team_id = NULL WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "26e90b7b244ce94450797f8e0ab9a2fb4ef12d63913566c24238b04fc9b88bff"+}diff --git a/.sqlx/query-751db03599259334fdab485abcbf6c29da6654f33853b600a208406f2ad17cb0.json b/.sqlx/query-751db03599259334fdab485abcbf6c29da6654f33853b600a208406f2ad17cb0.jsonnew file mode 100644index 0000000000..12aa2decbf--- /dev/null+++ b/.sqlx/query-751db03599259334fdab485abcbf6c29da6654f33853b600a208406f2ad17cb0.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT COUNT(*) AS \"count!\" FROM channel_label_channel WHERE label_id = $1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "751db03599259334fdab485abcbf6c29da6654f33853b600a208406f2ad17cb0"+}diff --git a/.sqlx/query-c201471a0db1e3c1c4871898d6b4ad3506323c17457531cca340fcfb84dcad35.json b/.sqlx/query-766c7c48742a815496b6d3faa7ed41cfcb8fe63995e99108f08584f60774961b.jsonsimilarity index 68%rename from .sqlx/query-c201471a0db1e3c1c4871898d6b4ad3506323c17457531cca340fcfb84dcad35.jsonrename to .sqlx/query-766c7c48742a815496b6d3faa7ed41cfcb8fe63995e99108f08584f60774961b.jsonindex 50eea93b71..a469d14ab5 100644--- a/.sqlx/query-c201471a0db1e3c1c4871898d6b4ad3506323c17457531cca340fcfb84dcad35.json+++ b/.sqlx/query-766c7c48742a815496b6d3faa7ed41cfcb8fe63995e99108f08584f60774961b.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "SELECT c.id, c.name as \"name!\", COUNT(*) OVER () as \"total_count!\"\n FROM comms_channels c\n JOIN comms_channel_participants p ON p.channel_id = c.id\n WHERE p.user_id = $1 AND p.left_at IS NULL\n AND c.channel_type != 'direct_message'\n AND strpos(lower(c.name), lower($2)) > 0\n ORDER BY lower(c.name), c.id\n LIMIT $3",+ "query": "SELECT c.id, c.name as \"name!\", COUNT(*) OVER () as \"total_count!\"\n FROM comms_channels c\n JOIN comms_channel_participants p ON p.channel_id = c.id\n WHERE p.user_id = $1 AND p.left_at IS NULL\n AND c.channel_type = 'team'\n AND ($4::uuid IS NULL OR c.team_id = $4)\n AND strpos(lower(c.name), lower($2)) > 0\n ORDER BY lower(c.name), c.id\n LIMIT $3","describe": {"columns": [{@@ -23,7 +23,8 @@"Left": ["Text","Text",- "Int8"+ "Int8",+ "Uuid"]},"nullable": [@@ -32,5 +33,5 @@null]},- "hash": "c201471a0db1e3c1c4871898d6b4ad3506323c17457531cca340fcfb84dcad35"+ "hash": "766c7c48742a815496b6d3faa7ed41cfcb8fe63995e99108f08584f60774961b"}diff --git a/.sqlx/query-7b26d0501d1026eeeaef076e7a6e9386f2ba163ba045d50954c4fddd397c97e7.json b/.sqlx/query-7b26d0501d1026eeeaef076e7a6e9386f2ba163ba045d50954c4fddd397c97e7.jsonnew file mode 100644index 0000000000..b8ec2d8008--- /dev/null+++ b/.sqlx/query-7b26d0501d1026eeeaef076e7a6e9386f2ba163ba045d50954c4fddd397c97e7.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE comms_channels SET team_id = $2 WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "7b26d0501d1026eeeaef076e7a6e9386f2ba163ba045d50954c4fddd397c97e7"+}diff --git a/.sqlx/query-9114619788863e612cd02ec5d12c6a5c585f731c6d5d6acf1fbc6bccc521d37f.json b/.sqlx/query-9114619788863e612cd02ec5d12c6a5c585f731c6d5d6acf1fbc6bccc521d37f.jsonnew file mode 100644index 0000000000..30dce9d166--- /dev/null+++ b/.sqlx/query-9114619788863e612cd02ec5d12c6a5c585f731c6d5d6acf1fbc6bccc521d37f.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_channels (id, name, channel_type, owner_id, team_id)\n VALUES ($1, $2, $3::text::comms_channel_type, $4, $5)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Varchar",+ "Text",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "9114619788863e612cd02ec5d12c6a5c585f731c6d5d6acf1fbc6bccc521d37f"+}diff --git a/.sqlx/query-f3ee355f36a75fc3cfd40e04a828d57334e6cf21008b7cc26c9e000fff21fc53.json b/.sqlx/query-f3ee355f36a75fc3cfd40e04a828d57334e6cf21008b7cc26c9e000fff21fc53.jsonnew file mode 100644index 0000000000..f0e5d9a90c--- /dev/null+++ b/.sqlx/query-f3ee355f36a75fc3cfd40e04a828d57334e6cf21008b7cc26c9e000fff21fc53.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO channel_label_channel (scope_key, channel_id, label_id)\n SELECT $1, channel_id, $2 FROM unnest($3::uuid[]) AS channel_id",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "f3ee355f36a75fc3cfd40e04a828d57334e6cf21008b7cc26c9e000fff21fc53"+}diff --git a/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.test.tsxindex 4c6ea08f86..209f3de6f0 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.test.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.test.tsx@@ -141,7 +141,7 @@ describe('channel tag flag in rail menus', () => {it('hides cached label actions when the flag changes without remounting', () => {const channel = {id: 'channel',- channelType: 'public',+ channelType: 'team',} as ChannelEntity;render(() => <ChannelLabelMenuItems channel={channel} />);@@ -159,4 +159,26 @@ describe('channel tag flag in rail menus', () => {expect(screen.queryByText('Ungroup from “Cached label”')).toBeNull();expect(rail.setChannelLabel).not.toHaveBeenCalled();});++ it.each(['public', 'private', 'direct_message'] as const)(+ 'hides all label actions for %s channels even with cached membership and the flag enabled',+ (channelType) => {+ setEnabled(true);+ const channel: ChannelEntity = {+ id: 'channel',+ name: 'Channel',+ ownerId: 'alice',+ type: 'channel',+ channelType,+ };+ const view = render(() => <ChannelLabelMenuItems channel={channel} />);++ expect(view.container.textContent).toBe('');+ expect(screen.queryByText('Move to label')).toBeNull();+ expect(screen.queryByText('Add to label')).toBeNull();+ expect(screen.queryByText('New label…')).toBeNull();+ expect(screen.queryByText('Ungroup from “Cached label”')).toBeNull();+ expect(rail.setChannelLabel).not.toHaveBeenCalled();+ }+ );});diff --git a/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsx b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsxindex ca215e6508..6102f7133d 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsx@@ -23,7 +23,7 @@ import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabimport { createDroppable } from '@thisbeyond/solid-dnd';import { cn, Dropdown } from '@ui';import { type Component, For, type JSX, Show } from 'solid-js';-import { isDirectMessage } from '../../utils';+import { canLabelChannel } from '../../core/channel-label-eligibility';import { isPrimaryMouseDown } from './ChannelRailItems';import {type ChannelLabelDropData,@@ -256,7 +256,7 @@ export function ChannelLabelMenuItems(props: { channel: ChannelEntity }) {<Showwhen={rail.channelTagsEnabled() &&- !isDirectMessage(props.channel) &&+ canLabelChannel(props.channel) &&rail.labelsAvailable()}>diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsxindex ae5b02566c..ed04c66976 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx@@ -48,7 +48,11 @@ import {} from 'solid-js';import type { VirtualizerHandle } from 'virtua/solid';import { useChannelsView } from '../../channels-view-context';-import { resolveSmartTagMemberships } from '../../core/smart-tags';+import {+ canLabelChannel,+ filterChannelLabelMembers,+} from '../../core/channel-label-eligibility';+import { resolveChannelLabelMemberships } from '../../core/smart-tags';import {type ChannelsSourceScope,type ChannelsSources,@@ -255,7 +259,7 @@ export function ChannelsRail(props: ChannelsRailProps) {// Shared or private labels; channel membership is always viewer-relative.const labelsQuery = useChannelLabelsQuery();const labels = createMemo<readonly ChannelLabel[]>(() =>- resolveSmartTagMemberships(+ resolveChannelLabelMemberships(channelTagsEnabled() && labelsQuery.isSuccess? labelsQuery.data.labels: [],@@ -338,7 +342,9 @@ export function ChannelsRail(props: ChannelsRailProps) {const labelUnreadCount = (label: ChannelLabel) => {const unread = channelActivity.unreadChannelIds();- return label.channelIds.filter((id) => unread.has(id)).length;+ return filterChannelLabelMembers(label.channelIds, channelsById()).filter(+ (id) => unread.has(id)+ ).length;};const visibleRows = createMemo(() => {@@ -745,10 +751,15 @@ export function ChannelsRail(props: ChannelsRailProps) {const message = error instanceof Error ? error.message : '';return message || fallback;};+ const labelChannelById = (channelId: string) =>+ channelsById().get(channelId) ??+ serviceSearchResults().find((channel) => channel.id === channelId);const channelName = (channelId: string) => {- const name = channelsById().get(channelId)?.name;+ const name = labelChannelById(channelId)?.name;return name ? `#${name}` : 'the channel';};+ const canLabelChannelId = (channelId: string) =>+ canLabelChannel(labelChannelById(channelId));const sharedLabels = () =>labelsQuery.isSuccess && Boolean(labelsQuery.data.teamId);@@ -759,12 +770,13 @@ export function ChannelsRail(props: ChannelsRailProps) {const createLabel = async (channelIds: string[]) => {if (!channelTagsEnabled()) return;+ if (!channelIds.every(canLabelChannelId)) return;if (!labelsAvailable()) {toast.failure(labelsUnavailableReason());return;}const names = channelIds- .map((id) => channelsById().get(id)?.name)+ .map((id) => labelChannelById(id)?.name).filter((name): name is string => Boolean(name)).map((name) => `#${name}`);const grouping =@@ -781,6 +793,8 @@ export function ChannelsRail(props: ChannelsRailProps) {onConfirm: async (name) => {if (!channelTagsEnabled())throw new Error('Channel tags are disabled.');+ if (!channelIds.every(canLabelChannelId))+ throw new Error('Only team channels can be added to labels.');const created = await createLabelMutation.mutateAsync({name,channelIds,@@ -895,7 +909,7 @@ export function ChannelsRail(props: ChannelsRailProps) {};const setChannelLabel = (channelId: string, labelId: string | undefined) => {- if (!channelTagsEnabled()) return;+ if (!channelTagsEnabled() || !canLabelChannelId(channelId)) return;const from = labels().find((label) => !label.rule && label.channelIds.includes(channelId));@@ -924,7 +938,9 @@ export function ChannelsRail(props: ChannelsRailProps) {const markLabelRead = (label: ChannelLabel) => {if (!channelTagsEnabled()) return;- const channelIds = new Set(label.channelIds);+ const channelIds = new Set(+ filterChannelLabelMembers(label.channelIds, channelsById())+ );const unread = notificationSource.notifications().filter(@@ -939,6 +955,8 @@ export function ChannelsRail(props: ChannelsRailProps) {// Drops are resolved here rather than per row so a channel dragged from// anywhere in the section lands the same way.const [dndState, dndActions] = useDragDropContext() ?? [];+ const canDropOnChannel = (sourceId: string, targetId: string) =>+ sourceId !== targetId && canLabelChannelId(targetId);// The highlight follows the whole target (a label with all its rows), not// the row under the cursor, so rows read this instead of their own state.const activeDropTarget = (): ChannelLabelDropTarget | undefined => {@@ -948,6 +966,7 @@ export function ChannelsRail(props: ChannelsRailProps) {| undefined;if (drag?.dragType !== 'channel-label' || drag.dndScope !== listDomId)return undefined;+ if (!canLabelChannelId(drag.channelId)) return undefined;const drop = dndState?.active.droppable?.data as| ChannelLabelDropData| undefined;@@ -959,7 +978,7 @@ export function ChannelsRail(props: ChannelsRailProps) {if (drop.target.kind === 'smart-tag') return undefined;if (drop.target.kind === 'channel' &&- drop.target.channelId === drag.channelId+ !canDropOnChannel(drag.channelId, drop.target.channelId))return undefined;if (drop.target.kind === 'label' && drop.target.labelId === drag.labelId)@@ -972,6 +991,7 @@ export function ChannelsRail(props: ChannelsRailProps) {const drag = draggable?.data as ChannelLabelDragData | undefined;if (drag?.dragType !== 'channel-label' || drag.dndScope !== listDomId)return;+ if (!canLabelChannelId(drag.channelId)) return;// With labels unavailable every target reports itself disabled, so the// drag ends on nothing; say why rather than silently doing nothing.if (!labelsAvailable()) {@@ -998,7 +1018,7 @@ export function ChannelsRail(props: ChannelsRailProps) {if (drag.labelId) setChannelLabel(drag.channelId, undefined);return;}- if (target.channelId === drag.channelId) return;+ if (!canDropOnChannel(drag.channelId, target.channelId)) return;// Dragging a labelled channel onto the plain list takes it out of its// label; dropping one plain channel on another starts a label with both.if (drag.labelId) {diff --git a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsxindex b3670098b1..690dd14adc 100644--- a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx@@ -30,6 +30,7 @@ import {Switch,} from 'solid-js';import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';+import { canLabelChannel } from '../../core/channel-label-eligibility';import type { ChannelListSort, ChannelsGroup } from '../../types';import { channelMentionsUser, formatDetailedTimestamp } from '../../utils';import { ChannelsEmptyState } from '../ChannelsEmptyState';@@ -260,7 +261,7 @@ function ChannelOption(props: {labelId?: string;/** Keep the timestamp visible instead of revealing it on hover. */alwaysShowTimestamp?: boolean;- /** Make the row draggable between labels (Channels section only). */+ /** Make a team-channel row draggable between labels (Channels section only). */draggable?: boolean;}) {const rail = useChannelsRail();@@ -274,7 +275,8 @@ function ChannelOption(props: {channel: props.channel,rowId: rowId(),labelId: () => props.labelId,- disabled: () => !rail.labelsAvailable(),+ disabled: () =>+ !rail.labelsAvailable() || !canLabelChannel(props.channel),}): undefined;@@ -302,7 +304,7 @@ function ChannelOption(props: {dnd?.draggable.ref(element);dnd?.droppable.ref(element);}}- {...(dnd?.draggable.dragActivators ?? {})}+ {...(canLabelChannel(props.channel) ? dnd?.draggable.dragActivators : {})}onPointerDown={() => {didDrag = false;}}@@ -738,7 +740,7 @@ function ChannelsSectionRows(props: {channelRow().channel.id,channelRow().labelId)}- draggable+ draggable={canLabelChannel(channelRow().channel)}/>)}</Match>diff --git a/apps/web/src/features/channels-view/components/rail/SmartTagDialog.tsx b/apps/web/src/features/channels-view/components/rail/SmartTagDialog.tsxindex 93e7ca2954..3fee9e3e64 100644--- a/apps/web/src/features/channels-view/components/rail/SmartTagDialog.tsx+++ b/apps/web/src/features/channels-view/components/rail/SmartTagDialog.tsx@@ -112,7 +112,7 @@ function SmartTagDialog(props: SmartTagDialogProps & ManagedDialogProps) {/></label><Dialog.Description class="sr-only">- {props.scopeDescription} Matching channels are grouped+ {props.scopeDescription} Matching team channels are groupedautomatically by name, ignoring capitalization.</Dialog.Description></div>diff --git a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.ts b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.tsindex c1636aaded..f412140ec2 100644--- a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.ts+++ b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.ts@@ -6,14 +6,18 @@ import {buildChannelSectionRows,} from './build-channel-rail-rows';-function channel(id: string, name = id): ChannelEntity {+function channel(+ id: string,+ name = id,+ channelType: ChannelEntity['channelType'] = 'team'+): ChannelEntity {return {id,name,type: 'channel',ownerId: 'alice',- channelType: 'public',- } as unknown as ChannelEntity;+ channelType,+ };}function label(@@ -117,6 +121,52 @@ describe('buildChannelSectionRows', () => {rows.some((row) => row.kind === 'conversation' && row.channel === hidden)).toBe(false);});++ it.each([true, false])(+ 'keeps non-team channels in the plain list when labels are open=%s, ignoring cached memberships',+ (isOpen) => {+ const publicChannel = channel('public', 'Public', 'public');+ const privateChannel = channel('private', 'Private', 'private');+ const channels = [publicChannel, privateChannel, acme];+ const rows = buildChannelSectionRows({+ labels: [+ label(+ 'manual',+ 'Manual',+ channels.map((channel) => channel.id)+ ),+ {+ ...label(+ 'smart',+ 'Smart',+ channels.map((channel) => channel.id)+ ),+ rule: { attribute: 'name', contains: 'support' },+ },+ ],+ channels,+ channelsById: new Map(channels.map((channel) => [channel.id, channel])),+ isLabelOpen: () => isOpen,+ });++ expect(+ rows.filter((row) => row.kind === 'conversation' && !row.labelId)+ ).toEqual([+ { kind: 'conversation', channel: publicChannel },+ { kind: 'conversation', channel: privateChannel },+ ]);+ expect(+ rows.filter((row) => row.kind === 'conversation' && row.labelId)+ ).toEqual(+ isOpen+ ? [+ { kind: 'conversation', channel: acme, labelId: 'manual' },+ { kind: 'conversation', channel: acme, labelId: 'smart' },+ ]+ : []+ );+ }+ );});describe('buildChannelRailRows', () => {diff --git a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.ts b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.tsindex 6ceecb2454..0ba5165da5 100644--- a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.ts+++ b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.ts@@ -1,6 +1,7 @@import type { ChannelEntity } from '@entity';import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';import type { Favorite } from '@service-storage/generated/schemas/favorite';+import { canLabelChannel } from '../../core/channel-label-eligibility';import type {ChannelsQueryScope,ChannelsRailSection,@@ -49,7 +50,10 @@ export function buildChannelSectionRows(options: {for (const label of options.labels) {const visible = label.channelIds.map((id) => options.channelsById.get(id))- .filter((channel): channel is ChannelEntity => channel !== undefined)+ .filter(+ (channel): channel is ChannelEntity =>+ channel !== undefined && canLabelChannel(channel)+ ).sort(compareChannelName);for (const channel of visible) labelled.add(channel.id);diff --git a/apps/web/src/features/channels-view/core/channel-label-eligibility.test.ts b/apps/web/src/features/channels-view/core/channel-label-eligibility.test.tsnew file mode 100644index 0000000000..1062f44a54--- /dev/null+++ b/apps/web/src/features/channels-view/core/channel-label-eligibility.test.ts@@ -0,0 +1,30 @@+import type { ChannelEntity } from '@entity';+import { describe, expect, it } from 'vitest';+import {+ canLabelChannel,+ filterChannelLabelMembers,+} from './channel-label-eligibility';++describe('channel label eligibility', () => {+ it('requires a known team channel', () => {+ expect(canLabelChannel({ channelType: 'team' })).toBe(true);+ expect(canLabelChannel({ channelType: 'public' })).toBe(false);+ expect(canLabelChannel({ channelType: 'private' })).toBe(false);+ expect(canLabelChannel({ channelType: 'direct_message' })).toBe(false);+ expect(canLabelChannel(undefined)).toBe(false);+ });++ it('retains unloaded server memberships for unread activity while removing known non-team channels', () => {+ const members = filterChannelLabelMembers(+ ['unloaded', 'public', 'team', 'private', 'dm'],+ new Map<string, Pick<ChannelEntity, 'channelType'>>([+ ['public', { channelType: 'public' }],+ ['team', { channelType: 'team' }],+ ['private', { channelType: 'private' }],+ ['dm', { channelType: 'direct_message' }],+ ])+ );++ expect(members).toEqual(['unloaded', 'team']);+ });+});diff --git a/apps/web/src/features/channels-view/core/channel-label-eligibility.ts b/apps/web/src/features/channels-view/core/channel-label-eligibility.tsnew file mode 100644index 0000000000..ce632e06a8--- /dev/null+++ b/apps/web/src/features/channels-view/core/channel-label-eligibility.ts@@ -0,0 +1,19 @@+import type { ChannelEntity } from '@entity';++/** Only team channels participate in manual or smart labels. */+export function canLabelChannel(+ channel: Pick<ChannelEntity, 'channelType'> | undefined+): boolean {+ return channel?.channelType === 'team';+}++/** Trust server memberships for unloaded channels; exclude known non-team channels. */+export function filterChannelLabelMembers(+ channelIds: readonly string[],+ channelsById: ReadonlyMap<string, Pick<ChannelEntity, 'channelType'>>+): string[] {+ return channelIds.filter((id) => {+ const channel = channelsById.get(id);+ return channel === undefined || canLabelChannel(channel);+ });+}diff --git a/apps/web/src/features/channels-view/core/smart-tags.test.ts b/apps/web/src/features/channels-view/core/smart-tags.test.tsindex 221b15e269..80fed94658 100644--- a/apps/web/src/features/channels-view/core/smart-tags.test.ts+++ b/apps/web/src/features/channels-view/core/smart-tags.test.ts@@ -3,16 +3,20 @@ import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabimport { describe, expect, it } from 'vitest';import {channelMatchesSmartTag,- resolveSmartTagMemberships,+ resolveChannelLabelMemberships,} from './smart-tags';-const channel = (id: string, name: string, channelType = 'public') =>- ({- id,- name,- channelType,- type: 'channel',- }) as ChannelEntity;+const channel = (+ id: string,+ name: string,+ channelType: ChannelEntity['channelType'] = 'team'+): ChannelEntity => ({+ id,+ name,+ channelType,+ type: 'channel',+ ownerId: 'alice',+});const rule = { attribute: 'name' as const, contains: 'support' };const label = (id: string, channelIds: string[]): ChannelLabel => ({id,@@ -26,7 +30,7 @@ const label = (id: string, channelIds: string[]): ChannelLabel => ({});describe('smart tag matching', () => {- it('matches literal substrings ignoring case, excluding DMs and empty patterns', () => {+ it('matches literal substrings ignoring case for team channels, excluding empty patterns', () => {expect(channelMatchesSmartTag(channel('a', 'Acme SUPPORT'), rule)).toBe(true);@@ -55,7 +59,7 @@ describe('smart tag matching', () => {it('updates loaded memberships on channel rename while retaining matches beyond loaded pages', () => {const manual = { ...label('manual', ['renamed']), rule: null };- const result = resolveSmartTagMemberships(+ const result = resolveChannelLabelMemberships([label('smart', ['unloaded', 'renamed']), manual],[channel('renamed', 'Sales'), channel('new', 'New Support')]);@@ -63,4 +67,51 @@ describe('smart tag matching', () => {expect(result[0].channelCount).toBe(2);expect(result[1]).toBe(manual);});++ it.each(['public', 'private', 'direct_message'] as const)(+ 'excludes %s channels from smart matching and cached manual or smart memberships',+ (channelType) => {+ const nonTeam = channel('non-team', 'Support', channelType);+ expect(channelMatchesSmartTag(nonTeam, rule)).toBe(false);+ const result = resolveChannelLabelMemberships(+ [+ { ...label('manual', ['unloaded', 'non-team', 'team']), rule: null },+ label('smart', ['unloaded', 'non-team', 'team']),+ ],+ [nonTeam, channel('team', 'Support')]+ );+ for (const resolved of result) {+ expect(resolved.channelIds).toEqual(['unloaded', 'team']);+ expect(resolved.channelCount).toBe(2);+ }+ }+ );++ it('preserves the manual count of assignments outside the loaded viewer-relative IDs', () => {+ const result = resolveChannelLabelMemberships(+ [{ ...label('manual', ['public', 'team']), rule: null, channelCount: 8 }],+ [channel('public', 'Public', 'public'), channel('team', 'Support')]+ );+ expect(result[0].channelIds).toEqual(['team']);+ expect(result[0].channelCount).toBe(7);+ });++ it('keeps new shared smart-label matches server-authoritative when channel team IDs are unavailable', () => {+ const result = resolveChannelLabelMemberships(+ [+ {+ ...label('shared', ['unloaded', 'renamed', 'member']),+ teamId: 'team',+ },+ ],+ [+ channel('renamed', 'Sales'),+ channel('member', 'Support'),+ channel('another-team', 'Support'),+ channel('new', 'Support'),+ ]+ );+ expect(result[0].channelIds).toEqual(['unloaded', 'member']);+ expect(result[0].channelCount).toBe(2);+ });});diff --git a/apps/web/src/features/channels-view/core/smart-tags.ts b/apps/web/src/features/channels-view/core/smart-tags.tsindex 788d36d348..5279d03367 100644--- a/apps/web/src/features/channels-view/core/smart-tags.ts+++ b/apps/web/src/features/channels-view/core/smart-tags.ts@@ -1,32 +1,58 @@import type { ChannelEntity } from '@entity';import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';import type { ChannelLabelRule } from '@service-storage/generated/schemas/channelLabelRule';+import { canLabelChannel } from './channel-label-eligibility';export function channelMatchesSmartTag(channel: ChannelEntity,rule: ChannelLabelRule): boolean {return (- channel.channelType !== 'direct_message' &&+ canLabelChannel(channel) &&rule.contains.length > 0 &&channel.name.toLowerCase().includes(rule.contains.toLowerCase()));}-/** Keep server matches beyond loaded pages, while reflecting live channel-name updates. */-export function resolveSmartTagMemberships(+/** Keep unloaded server matches, exclude non-team channels, and reflect live names. */+export function resolveChannelLabelMemberships(labels: readonly ChannelLabel[],channels: readonly ChannelEntity[]): ChannelLabel[] {const loadedIds = new Set(channels.map((channel) => channel.id));+ const ineligibleIds = new Set(+ channels+ .filter((channel) => !canLabelChannel(channel))+ .map((channel) => channel.id)+ );return labels.map((label) => {const rule = label.rule;- if (!rule) return label;+ if (!rule) {+ const channelIds = label.channelIds.filter(+ (id) => !ineligibleIds.has(id)+ );+ return channelIds.length === label.channelIds.length+ ? label+ : {+ ...label,+ channelIds,+ channelCount:+ label.channelCount -+ (label.channelIds.length - channelIds.length),+ };+ }+ // Channel entities have no team ID. Shared-label matches must come from+ // the server so a matching name cannot add another team's channel.+ const serverIds = new Set(label.channelIds);const channelIds = [...new Set([...label.channelIds.filter((id) => !loadedIds.has(id)),...channels- .filter((channel) => channelMatchesSmartTag(channel, rule))+ .filter(+ (channel) =>+ (!label.teamId || serverIds.has(channel.id)) &&+ channelMatchesSmartTag(channel, rule)+ ).map((channel) => channel.id),]),];diff --git a/crates/channel_labels/src/domain/models.rs b/crates/channel_labels/src/domain/models.rsindex 417eb118a9..08a5f13f2a 100644--- a/crates/channel_labels/src/domain/models.rs+++ b/crates/channel_labels/src/domain/models.rs@@ -1,5 +1,8 @@//! Domain models for channel labels.+#[cfg(test)]+mod test;+use chrono::{DateTime, Utc};use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use macro_user_id::user_id::MacroUserIdStr;@@ -115,7 +118,7 @@ pub enum LabelWriteOutcome {NameTaken,/// The label to rename does not exist in the scope.NotFound,- /// A requested channel is missing, inaccessible, or a direct message.+ /// A requested channel is missing, inaccessible, or ineligible for this scope.InvalidChannel(SetChannelLabelOutcome),}@@ -128,7 +131,7 @@ pub enum SetChannelLabelOutcome {ChannelNotFound,/// The target label does not exist in the scope.LabelNotFound,- /// The channel kind cannot be labelled (direct messages).+ /// Only team channels belonging to the label's scope can be labelled.ChannelNotLabelable,/// Smart tag membership is determined by its rule, not manual assignments.SmartTagReadOnly,@@ -144,6 +147,18 @@ pub enum ChannelLabelsScope {}impl ChannelLabelsScope {+ /// Whether a channel's owning team permits grouping it in this namespace.+ /// Non-team channels have no owning team and cannot be labelled. Shared+ /// labels accept only their own team's channels; private labels accept any+ /// team channel the viewer participates in.+ pub fn can_label_channel(&self, channel_team_id: Option<Uuid>) -> bool {+ match (self, channel_team_id) {+ (Self::Team(team_id), Some(channel_team_id)) => *team_id == channel_team_id,+ (Self::User(_), Some(_)) => true,+ (_, None) => false,+ }+ }+/// Stable persistence key for this namespace.pub fn key(&self) -> String {match self {diff --git a/crates/channel_labels/src/domain/models/test.rs b/crates/channel_labels/src/domain/models/test.rsnew file mode 100644index 0000000000..df5247ae2f--- /dev/null+++ b/crates/channel_labels/src/domain/models/test.rs@@ -0,0 +1,22 @@+use super::ChannelLabelsScope;+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++#[test]+fn shared_labels_accept_only_channels_owned_by_their_team() {+ let team_id = Uuid::now_v7();+ let scope = ChannelLabelsScope::Team(team_id);++ assert!(scope.can_label_channel(Some(team_id)));+ assert!(!scope.can_label_channel(Some(Uuid::now_v7())));+ assert!(!scope.can_label_channel(None));+}++#[test]+fn private_labels_accept_team_channels_and_reject_non_team_channels() {+ let user_id = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();+ let scope = ChannelLabelsScope::User(user_id);++ assert!(scope.can_label_channel(Some(Uuid::now_v7())));+ assert!(!scope.can_label_channel(None));+}diff --git a/crates/channel_labels/src/domain/ports.rs b/crates/channel_labels/src/domain/ports.rsindex 9087025c55..c82562a866 100644--- a/crates/channel_labels/src/domain/ports.rs+++ b/crates/channel_labels/src/domain/ports.rs@@ -14,8 +14,9 @@ pub trait ChannelLabelsRepo: Send + Sync + 'static {type Err: Send + std::fmt::Debug;/// Every label of the scope in manual order. `channel_ids` on each label- /// is restricted to channels `viewer` participates in. Manual counts include- /// all assignments; smart counts include only the viewer's active matches.+ /// is restricted to eligible team channels `viewer` participates in. Shared+ /// labels include only their own team's channels. Manual counts include all+ /// eligible assignments; smart counts include only the viewer's active matches./// Smart memberships are evaluated from current attributes, including matches/// already present in another smart tag or manual label.fn list_labels(@@ -34,7 +35,8 @@ pub trait ChannelLabelsRepo: Send + Sync + 'static {/// Append a label to the scope's list. `name` is already trimmed and/// validated. Creation and all channel assignments must commit atomically.- /// The viewer must actively participate in every requested non-DM channel;+ /// The viewer must actively participate in every requested channel, and+ /// [`ChannelLabelsScope::can_label_channel`] must allow its owning team;/// invalid channels must leave the label and all assignments unchanged./// A validated smart rule is persisted without any manual assignments.fn create_label(@@ -68,8 +70,10 @@ pub trait ChannelLabelsRepo: Send + Sync + 'static {/// Put `channel_id` into `label_id` (or into no label when `None`).///- /// The actor must actively participate in the non-DM channel. A label must- /// belong to the authorized scope; other scopes must remain unchanged.+ /// The actor must actively participate in the channel. Assignments require+ /// [`ChannelLabelsScope::can_label_channel`]; removals may clear historical+ /// ineligible assignments. A label must belong to the authorized scope;+ /// other scopes must remain unchanged./// Smart tags reject manual assignment with `SmartTagReadOnly`.fn set_channel_label(&self,@@ -79,11 +83,13 @@ pub trait ChannelLabelsRepo: Send + Sync + 'static {actor: &MacroUserIdStr<'_>,) -> impl Future<Output = Result<SetChannelLabelOutcome, Self::Err>> + Send;- /// Preview a validated rule using only the viewer's active non-DM memberships.+ /// Preview a validated rule using only the viewer's active channel memberships+ /// permitted by [`ChannelLabelsScope::can_label_channel`]./// Match literal substrings case-insensitively; return at most `limit` names/// and the full visible count. The same rule determines smart tag membership.fn preview_smart_tag(&self,+ scope: &ChannelLabelsScope,viewer: &MacroUserIdStr<'_>,rule: &ChannelLabelRule,limit: u16,diff --git a/crates/channel_labels/src/domain/service.rs b/crates/channel_labels/src/domain/service.rsindex 1932b26022..d229d701a0 100644--- a/crates/channel_labels/src/domain/service.rs+++ b/crates/channel_labels/src/domain/service.rs@@ -53,7 +53,7 @@ fn channel_write_result(outcome: SetChannelLabelOutcome) -> Result<(), ChannelLaErr(ChannelLabelsError::NotFound("label not found"))}SetChannelLabelOutcome::ChannelNotLabelable => Err(ChannelLabelsError::BadRequest(- "direct messages cannot be added to a label".to_string(),+ "only team channels in this label's scope can be added to a label".to_string(),)),SetChannelLabelOutcome::SmartTagReadOnly => Err(ChannelLabelsError::BadRequest("smart tag membership is determined by its rule".to_string(),@@ -231,7 +231,7 @@ wherelet rule = validate_rule(rule)?;Ok(self.repo- .preview_smart_tag(receipt.user_id(), &rule, 5)+ .preview_smart_tag(receipt.scope(), receipt.user_id(), &rule, 5).await.map_err(anyhow::Error::from)?)}diff --git a/crates/channel_labels/src/domain/service/test.rs b/crates/channel_labels/src/domain/service/test.rsindex da5a7cdaba..9a756a6a6b 100644--- a/crates/channel_labels/src/domain/service/test.rs+++ b/crates/channel_labels/src/domain/service/test.rs@@ -32,6 +32,9 @@ enum RepoCall {channel_id: Uuid,label_id: Option<Uuid>,},+ Preview {+ scope: ChannelLabelsScope,+ },}#[derive(Clone, Default)]@@ -167,10 +170,14 @@ impl ChannelLabelsRepo for FakeRepo {}async fn preview_smart_tag(&self,+ scope: &ChannelLabelsScope,_viewer: &MacroUserIdStr<'_>,_rule: &ChannelLabelRule,_limit: u16,) -> Result<SmartTagPreview, Self::Err> {+ self.record(RepoCall::Preview {+ scope: scope.clone(),+ });Ok(SmartTagPreview {channels: vec![],total_count: 0,@@ -178,6 +185,65 @@ impl ChannelLabelsRepo for FakeRepo {}}+#[tokio::test]+async fn preview_uses_the_same_authorized_scope_as_saved_labels() {+ let repo = FakeRepo::default();+ let service = ChannelLabelsServiceImpl::new(repo.clone());+ let (team_id, receipt) = receipt();++ service+ .preview_smart_tag(+ &receipt,+ ChannelLabelRule::Name {+ contains: "support".into(),+ },+ )+ .await+ .unwrap();++ assert_eq!(+ repo.calls(),+ vec![RepoCall::Preview {+ scope: ChannelLabelsScope::Team(team_id),+ }]+ );+}++#[tokio::test]+async fn creation_and_assignment_report_ineligible_channels() {+ let (_, receipt) = receipt();+ let repo = FakeRepo {+ create_outcome: Some(LabelWriteOutcome::InvalidChannel(+ SetChannelLabelOutcome::ChannelNotLabelable,+ )),+ set_outcome: Some(SetChannelLabelOutcome::ChannelNotLabelable),+ ..FakeRepo::default()+ };+ let service = ChannelLabelsServiceImpl::new(repo);+ let channel_id = Uuid::now_v7();++ let created = service+ .create_label(+ &receipt,+ NewChannelLabel {+ name: "Support".into(),+ channel_ids: vec![channel_id],+ rule: None,+ },+ )+ .await;+ let assigned = service+ .set_channel_label(&receipt, channel_id, Some(Uuid::now_v7()))+ .await;++ for result in [created.map(|_| ()), assigned] {+ assert!(matches!(+ result,+ Err(ChannelLabelsError::BadRequest(message)) if message.contains("only team channels")+ ));+ }+}+fn receipt() -> (Uuid, ChannelLabelsReceipt) {let team_id = Uuid::now_v7();(diff --git a/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs b/crates/channel_labels/src/outbound/pg_channel_labels_repo.rsindex 3ea7be6ee5..ac2b8ef50d 100644--- a/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs+++ b/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs@@ -97,15 +97,17 @@ impl PgChannelLabelsRepo {FROM comms_channels cJOIN comms_channel_participants pON p.channel_id = c.id AND p.user_id = $3 AND p.left_at IS NULL- WHERE (+ WHERE c.channel_type = 'team'+ AND (l.team_id IS NULL OR c.team_id = l.team_id)+ AND ((l.name_contains IS NULL AND EXISTS (SELECT 1 FROM channel_label_channel lcWHERE lc.label_id = l.id AND lc.channel_id = c.id)) OR (- l.name_contains IS NOT NULL AND c.channel_type != 'direct_message'+ l.name_contains IS NOT NULLAND strpos(lower(c.name), lower(l.name_contains)) > 0- )+ ))ORDER BY lower(c.name), c.id) AS visible_idsFROM channel_label l@@ -121,7 +123,10 @@ impl PgChannelLabelsRepo {l.updated_at as "updated_at!",l.visible_ids as "channel_ids!: Vec<Uuid>",CASE WHEN l.name_contains IS NULL THEN- (SELECT COUNT(*) FROM channel_label_channel lc WHERE lc.label_id = l.id)+ (SELECT COUNT(*) FROM channel_label_channel lc+ JOIN comms_channels c ON c.id = lc.channel_id+ WHERE lc.label_id = l.id AND c.channel_type = 'team'+ AND (l.team_id IS NULL OR c.team_id = l.team_id))ELSE cardinality(l.visible_ids)::bigint END as "channel_count!"FROM labels lORDER BY l.sort_order, l.created_at, l.id@@ -172,7 +177,7 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {let user_id = scope.owner_id();let name_contains = rule.map(ChannelLabelRule::name_contains);let mut tx = self.pool.begin().await?;- let validity = validate_channels(&mut tx, channel_ids, viewer).await?;+ let validity = validate_channels(&mut tx, channel_ids, viewer, Some(scope)).await?;if validity != SetChannelLabelOutcome::Updated {return Ok(LabelWriteOutcome::InvalidChannel(validity));}@@ -295,7 +300,8 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {return Ok(SetChannelLabelOutcome::SmartTagReadOnly);}}- let validity = validate_channels(&mut tx, &[channel_id], actor).await?;+ let validity =+ validate_channels(&mut tx, &[channel_id], actor, label_id.map(|_| scope)).await?;if validity != SetChannelLabelOutcome::Updated {return Ok(validity);}@@ -326,23 +332,27 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {#[tracing::instrument(err, skip(self))]async fn preview_smart_tag(&self,+ scope: &ChannelLabelsScope,viewer: &MacroUserIdStr<'_>,rule: &ChannelLabelRule,limit: u16,) -> Result<SmartTagPreview, Self::Err> {let name_contains = rule.name_contains();+ let team_id = scope.team_id();let rows = sqlx::query!(r#"SELECT c.id, c.name as "name!", COUNT(*) OVER () as "total_count!"FROM comms_channels cJOIN comms_channel_participants p ON p.channel_id = c.idWHERE p.user_id = $1 AND p.left_at IS NULL- AND c.channel_type != 'direct_message'+ AND c.channel_type = 'team'+ AND ($4::uuid IS NULL OR c.team_id = $4)AND strpos(lower(c.name), lower($2)) > 0ORDER BY lower(c.name), c.idLIMIT $3"#,viewer.as_ref(),name_contains,i64::from(limit),+ team_id,).fetch_all(&self.pool).await?;@@ -359,15 +369,19 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {}}-/// The port permits grouping only active participants' non-DM channels.-/// Lock the selected channels and memberships until all assignments commit.+/// Lock active memberships and channel attributes until assignments commit.+/// Apply the domain's eligibility policy for additions, while allowing removals+/// to clear historical assignments regardless of the channel's current team.async fn validate_channels(tx: &mut Transaction<'_, Postgres>,channel_ids: &[Uuid],actor: &MacroUserIdStr<'_>,+ assignment_scope: Option<&ChannelLabelsScope>,) -> Result<SetChannelLabelOutcome, ChannelLabelsRepoErr> {+ // The valid_team_channel constraint makes team_id present exactly when the+ // channel type is 'team', so it supplies the domain's eligibility fact.let channels = sqlx::query!(- r#"SELECT c.id, c.channel_type::text as "channel_type!"+ r#"SELECT c.id, c.team_idFROM comms_channels cJOIN comms_channel_participants p ON p.channel_id = c.idWHERE c.id = ANY($1) AND p.user_id = $2 AND p.left_at IS NULL@@ -380,7 +394,9 @@ async fn validate_channels(if channels.len() != channel_ids.len() {return Ok(SetChannelLabelOutcome::ChannelNotFound);}- if channels.iter().any(|c| c.channel_type == "direct_message") {+ if assignment_scope+ .is_some_and(|scope| channels.iter().any(|c| !scope.can_label_channel(c.team_id)))+ {return Ok(SetChannelLabelOutcome::ChannelNotLabelable);}Ok(SetChannelLabelOutcome::Updated)diff --git a/crates/channel_labels/src/outbound/pg_channel_labels_repo/test.rs b/crates/channel_labels/src/outbound/pg_channel_labels_repo/test.rsindex b7a5e9e34b..a4a7f2f307 100644--- a/crates/channel_labels/src/outbound/pg_channel_labels_repo/test.rs+++ b/crates/channel_labels/src/outbound/pg_channel_labels_repo/test.rs@@ -7,6 +7,8 @@ use super::PgChannelLabelsRepo;use crate::domain::models::{ChannelLabelsScope, LabelWriteOutcome, SetChannelLabelOutcome};use crate::domain::ports::ChannelLabelsRepo;+mod team_channels;+const USER_A: &str = "macro|[email protected]";const USER_B: &str = "macro|[email protected]";@@ -55,26 +57,48 @@ async fn insert_channel(channel_type: &str,owner: &str,participants: &[&str],+) -> Uuid {+ insert_channel_with_team(pool, name, channel_type, None, owner, participants).await+}++async fn insert_team_channel(+ pool: &PgPool,+ name: &str,+ team_id: Uuid,+ owner: &str,+ participants: &[&str],+) -> Uuid {+ insert_channel_with_team(pool, Some(name), "team", Some(team_id), owner, participants).await+}++async fn insert_channel_with_team(+ pool: &PgPool,+ name: Option<&str>,+ channel_type: &str,+ team_id: Option<Uuid>,+ owner: &str,+ participants: &[&str],) -> Uuid {let channel_id = Uuid::now_v7();- sqlx::query(- r#"INSERT INTO comms_channels (id, name, channel_type, owner_id)- VALUES ($1, $2, $3::comms_channel_type, $4)"#,+ sqlx::query!(+ r#"INSERT INTO comms_channels (id, name, channel_type, owner_id, team_id)+ VALUES ($1, $2, $3::text::comms_channel_type, $4, $5)"#,+ channel_id,+ name,+ channel_type,+ owner,+ team_id,)- .bind(channel_id)- .bind(name)- .bind(channel_type)- .bind(owner).execute(pool).await.expect("channel should insert");for participant in participants {- sqlx::query(+ sqlx::query!(r#"INSERT INTO comms_channel_participants (channel_id, role, user_id)VALUES ($1, 'member', $2)"#,+ channel_id,+ participant,)- .bind(channel_id)- .bind(participant).execute(pool).await.expect("participant should insert");@@ -268,16 +292,10 @@ async fn channels_in_a_label_are_viewer_relative_and_sorted_by_name(pool: PgPoolinsert_user(&pool, USER_A).await;insert_user(&pool, USER_B).await;let team_id = insert_team(&pool, USER_A).await;- let shared = insert_channel(- &pool,- Some("zeta-support"),- "public",- USER_A,- &[USER_A, USER_B],- )- .await;- let only_a = insert_channel(&pool, Some("acme-support"), "public", USER_A, &[USER_A]).await;- let only_b = insert_channel(&pool, Some("beta-support"), "public", USER_B, &[USER_B]).await;+ let shared =+ insert_team_channel(&pool, "zeta-support", team_id, USER_A, &[USER_A, USER_B]).await;+ let only_a = insert_team_channel(&pool, "acme-support", team_id, USER_A, &[USER_A]).await;+ let only_b = insert_team_channel(&pool, "beta-support", team_id, USER_B, &[USER_B]).await;let repo = PgChannelLabelsRepo::new(pool);let label = written(@@ -365,9 +383,9 @@ async fn set_channel_label_rejects_invisible_channels_dms_and_foreign_labels(pooinsert_user(&pool, USER_B).await;let team_a = insert_team(&pool, USER_A).await;let team_b = insert_team(&pool, USER_B).await;- let only_b = insert_channel(&pool, Some("beta-support"), "public", USER_B, &[USER_B]).await;+ let only_b = insert_team_channel(&pool, "beta-support", team_b, USER_B, &[USER_B]).await;let dm = insert_channel(&pool, None, "direct_message", USER_A, &[USER_A, USER_B]).await;- let mine = insert_channel(&pool, Some("acme-support"), "public", USER_A, &[USER_A]).await;+ let mine = insert_team_channel(&pool, "acme-support", team_a, USER_A, &[USER_A]).await;let repo = PgChannelLabelsRepo::new(pool);let label_a = written(@@ -443,10 +461,11 @@ async fn set_channel_label_rejects_invisible_channels_dms_and_foreign_labels(pooasync fn private_and_team_assignments_do_not_overwrite_each_other(pool: PgPool) {insert_user(&pool, USER_A).await;insert_user(&pool, USER_B).await;- let team = ChannelLabelsScope::Team(insert_team(&pool, USER_A).await);+ let team_id = insert_team(&pool, USER_A).await;+ let team = ChannelLabelsScope::Team(team_id);let a = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_A.to_owned()).unwrap());let b = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_B.to_owned()).unwrap());- let channel = insert_channel(&pool, Some("Shared"), "public", USER_A, &[USER_A, USER_B]).await;+ let channel = insert_team_channel(&pool, "Shared", team_id, USER_A, &[USER_A, USER_B]).await;let repo = PgChannelLabelsRepo::new(pool);let team_label = written(repo.create_label(&team, "Group", &[channel], &user(USER_A), None)@@ -501,7 +520,8 @@ async fn private_and_team_assignments_do_not_overwrite_each_other(pool: PgPool)async fn create_with_invalid_channel_leaves_no_partial_label_or_moves(pool: PgPool) {insert_user(&pool, USER_A).await;let scope = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_A.to_owned()).unwrap());- let channel = insert_channel(&pool, Some("Mine"), "public", USER_A, &[USER_A]).await;+ let team_id = insert_team(&pool, USER_A).await;+ let channel = insert_team_channel(&pool, "Mine", team_id, USER_A, &[USER_A]).await;let dm = insert_channel(&pool, None, "direct_message", USER_A, &[USER_A]).await;let repo = PgChannelLabelsRepo::new(pool);let original = written(@@ -548,7 +568,8 @@ async fn smart_tags_overlap_manual_groups_and_follow_channel_changes(pool: PgPooinsert_user(&pool, USER_A).await;let scope = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_A.to_owned()).unwrap());let repo = PgChannelLabelsRepo::new(pool.clone());- let channel = insert_channel(&pool, Some("Acme SUPPORT"), "public", USER_A, &[USER_A]).await;+ let team_id = insert_team(&pool, USER_A).await;+ let channel = insert_team_channel(&pool, "Acme SUPPORT", team_id, USER_A, &[USER_A]).await;let manual = written(repo.create_label(&scope, "Manual", &[channel], &user(USER_A), None).await@@ -616,7 +637,7 @@ async fn smart_tags_overlap_manual_groups_and_follow_channel_changes(pool: PgPoo.channel_ids,vec![channel]);- let added = insert_channel(&pool, Some("New support"), "public", USER_A, &[USER_A]).await;+ let added = insert_team_channel(&pool, "New support", team_id, USER_A, &[USER_A]).await;assert_eq!(repo.get_label(&scope, support.id, &user(USER_A)).await@@ -647,18 +668,11 @@ async fn smart_preview_is_bounded_literal_and_respects_membership(pool: PgPool)contains: "support".into(),};for n in 0..8 {- insert_channel(- &pool,- Some(&format!("SUPPORT {n}")),- "public",- USER_A,- &[USER_A],- )- .await;+ insert_team_channel(&pool, &format!("SUPPORT {n}"), team_id, USER_A, &[USER_A]).await;}- insert_channel(&pool, Some("support hidden"), "private", USER_B, &[USER_B]).await;+ insert_team_channel(&pool, "support hidden", team_id, USER_B, &[USER_B]).await;insert_channel(&pool, None, "direct_message", USER_A, &[USER_A]).await;- let left = insert_channel(&pool, Some("support left"), "public", USER_A, &[USER_A]).await;+ let left = insert_team_channel(&pool, "support left", team_id, USER_A, &[USER_A]).await;sqlx::query!("UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1",left@@ -667,7 +681,7 @@ async fn smart_preview_is_bounded_literal_and_respects_membership(pool: PgPool).await.unwrap();let preview = repo- .preview_smart_tag(&user(USER_A), &rule, 5)+ .preview_smart_tag(&ChannelLabelsScope::Team(team_id), &user(USER_A), &rule, 5).await.unwrap();assert_eq!(preview.total_count, 8);@@ -686,18 +700,28 @@ async fn smart_preview_is_bounded_literal_and_respects_membership(pool: PgPool));assert_eq!(saved.channel_ids.len(), 8);assert_eq!(saved.channel_count, 8);- let literal = insert_channel(&pool, Some("100%_support"), "public", USER_A, &[USER_A]).await;+ let literal = insert_team_channel(&pool, "100%_support", team_id, USER_A, &[USER_A]).await;let literal_rule = ChannelLabelRule::Name {contains: "%_".into(),};let literal_preview = repo- .preview_smart_tag(&user(USER_A), &literal_rule, 5)+ .preview_smart_tag(+ &ChannelLabelsScope::Team(team_id),+ &user(USER_A),+ &literal_rule,+ 5,+ ).await.unwrap();assert_eq!(literal_preview.total_count, 1);assert_eq!(literal_preview.channels[0].id, literal);let empty = repo- .preview_smart_tag(&user(USER_B), &literal_rule, 5)+ .preview_smart_tag(+ &ChannelLabelsScope::Team(team_id),+ &user(USER_B),+ &literal_rule,+ 5,+ ).await.unwrap();assert_eq!(empty.total_count, 0);diff --git a/crates/channel_labels/src/outbound/pg_channel_labels_repo/test/team_channels.rs b/crates/channel_labels/src/outbound/pg_channel_labels_repo/test/team_channels.rsnew file mode 100644index 0000000000..eae5930ae9--- /dev/null+++ b/crates/channel_labels/src/outbound/pg_channel_labels_repo/test/team_channels.rs@@ -0,0 +1,222 @@+use super::*;+use crate::domain::models::ChannelLabelRule;+use cowlike::CowLike;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn only_eligible_team_channels_can_be_assigned_or_moved_during_creation(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let team_id = insert_team(&pool, USER_A).await;+ let other_team_id = insert_team(&pool, USER_B).await;+ let scope = ChannelLabelsScope::Team(team_id);+ let channel = insert_team_channel(&pool, "Support", team_id, USER_A, &[USER_A]).await;+ let other_team =+ insert_team_channel(&pool, "Other support", other_team_id, USER_B, &[USER_A]).await;+ let public = insert_channel(&pool, Some("Public support"), "public", USER_A, &[USER_A]).await;+ let private =+ insert_channel(&pool, Some("Private support"), "private", USER_A, &[USER_A]).await;+ let dm = insert_channel(&pool, None, "direct_message", USER_A, &[USER_A]).await;+ let repo = PgChannelLabelsRepo::new(pool);+ let original = written(+ repo.create_label(&scope, "Original", &[channel], &user(USER_A), None)+ .await+ .unwrap(),+ );++ for invalid in [public, private, dm, other_team] {+ assert_eq!(+ repo.set_channel_label(&scope, invalid, Some(original.id), &user(USER_A))+ .await+ .unwrap(),+ SetChannelLabelOutcome::ChannelNotLabelable+ );+ assert_eq!(+ repo.create_label(&scope, "New", &[channel, invalid], &user(USER_A), None)+ .await+ .unwrap(),+ LabelWriteOutcome::InvalidChannel(SetChannelLabelOutcome::ChannelNotLabelable)+ );+ assert_eq!(+ repo.list_labels(&scope, &user(USER_A)).await.unwrap(),+ vec![original.clone()],+ "invalid creation must not create a label or move the eligible channel"+ );+ }++ let private_scope = ChannelLabelsScope::User(user(USER_A).into_owned());+ let private_label = written(+ repo.create_label(+ &private_scope,+ "Private",+ &[channel, other_team],+ &user(USER_A),+ None,+ )+ .await+ .unwrap(),+ );+ assert_eq!(private_label.channel_count, 2);+ for invalid in [public, private, dm] {+ assert_eq!(+ repo.set_channel_label(+ &private_scope,+ invalid,+ Some(private_label.id),+ &user(USER_A)+ )+ .await+ .unwrap(),+ SetChannelLabelOutcome::ChannelNotLabelable+ );+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn legacy_assignments_are_hidden_and_not_counted_but_can_be_removed(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let team_id = insert_team(&pool, USER_A).await;+ let other_team_id = insert_team(&pool, USER_B).await;+ let scope = ChannelLabelsScope::Team(team_id);+ let visible = insert_team_channel(&pool, "Support", team_id, USER_A, &[USER_A]).await;+ let hidden = insert_team_channel(&pool, "Hidden support", team_id, USER_B, &[USER_B]).await;+ let other_team =+ insert_team_channel(&pool, "Other support", other_team_id, USER_B, &[USER_A]).await;+ let public = insert_channel(&pool, Some("Public support"), "public", USER_A, &[USER_A]).await;+ let private =+ insert_channel(&pool, Some("Private support"), "private", USER_A, &[USER_A]).await;+ let dm = insert_channel(&pool, None, "direct_message", USER_A, &[USER_A]).await;+ let repo = PgChannelLabelsRepo::new(pool.clone());+ let manual = written(+ repo.create_label(&scope, "Manual", &[], &user(USER_A), None)+ .await+ .unwrap(),+ );+ let scope_key = scope.key();+ let legacy_channels = [visible, hidden, public, private, dm, other_team];+ sqlx::query!(+ r#"INSERT INTO channel_label_channel (scope_key, channel_id, label_id)+ SELECT $1, channel_id, $2 FROM unnest($3::uuid[]) AS channel_id"#,+ scope_key,+ manual.id,+ &legacy_channels,+ )+ .execute(&pool)+ .await+ .unwrap();++ let listed = repo.list_labels(&scope, &user(USER_A)).await.unwrap();+ assert_eq!(listed[0].channel_ids, vec![visible]);+ assert_eq!(+ listed[0].channel_count, 2,+ "count includes eligible hidden channels"+ );+ assert_eq!(+ repo.get_label(&scope, manual.id, &user(USER_A))+ .await+ .unwrap()+ .unwrap(),+ listed[0]+ );++ for invalid in [public, private, dm, other_team] {+ assert_eq!(+ repo.set_channel_label(&scope, invalid, None, &user(USER_A))+ .await+ .unwrap(),+ SetChannelLabelOutcome::Updated+ );+ }+ let remaining = sqlx::query_scalar!(+ r#"SELECT COUNT(*) AS "count!" FROM channel_label_channel WHERE label_id = $1"#,+ manual.id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(+ remaining, 2,+ "historical ineligible assignments were removed"+ );++ sqlx::query!(+ "UPDATE comms_channels SET channel_type = 'public', team_id = NULL WHERE id = $1",+ visible,+ )+ .execute(&pool)+ .await+ .unwrap();+ let changed = repo+ .get_label(&scope, manual.id, &user(USER_A))+ .await+ .unwrap()+ .unwrap();+ assert!(changed.channel_ids.is_empty());+ assert_eq!(changed.channel_count, 1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn smart_preview_and_membership_include_only_eligible_team_channels(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let team_id = insert_team(&pool, USER_A).await;+ let other_team_id = insert_team(&pool, USER_B).await;+ let scope = ChannelLabelsScope::Team(team_id);+ let channel = insert_team_channel(&pool, "Support", team_id, USER_A, &[USER_A]).await;+ let other_team =+ insert_team_channel(&pool, "Other support", other_team_id, USER_B, &[USER_A]).await;+ insert_channel(&pool, Some("Public support"), "public", USER_A, &[USER_A]).await;+ insert_channel(&pool, Some("Private support"), "private", USER_A, &[USER_A]).await;+ insert_channel(&pool, None, "direct_message", USER_A, &[USER_A]).await;+ let repo = PgChannelLabelsRepo::new(pool.clone());+ let rule = ChannelLabelRule::Name {+ contains: "support".into(),+ };++ for (scope, expected) in [+ (scope.clone(), vec![channel]),+ (+ ChannelLabelsScope::User(user(USER_A).into_owned()),+ vec![other_team, channel],+ ),+ ] {+ let preview = repo+ .preview_smart_tag(&scope, &user(USER_A), &rule, 5)+ .await+ .unwrap();+ let smart = written(+ repo.create_label(&scope, "Support", &[], &user(USER_A), Some(&rule))+ .await+ .unwrap(),+ );+ assert_eq!(+ preview+ .channels+ .iter()+ .map(|matched| matched.id)+ .collect::<Vec<_>>(),+ expected+ );+ assert_eq!(preview.total_count, expected.len() as i64);+ assert_eq!(smart.channel_ids, expected);+ assert_eq!(smart.channel_count, preview.total_count);+ }++ sqlx::query!(+ "UPDATE comms_channels SET team_id = $2 WHERE id = $1",+ channel,+ other_team_id,+ )+ .execute(&pool)+ .await+ .unwrap();+ let preview = repo+ .preview_smart_tag(&scope, &user(USER_A), &rule, 5)+ .await+ .unwrap();+ let listed = repo.list_labels(&scope, &user(USER_A)).await.unwrap();+ assert!(preview.channels.is_empty());+ assert_eq!(preview.total_count, 0);+ assert!(listed[0].channel_ids.is_empty());+ assert_eq!(listed[0].channel_count, 0);+}diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex c897e7c988..7d8affc03e 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -355,8 +355,13 @@ Labels group channels inside the `Channels` section. Team members share thesame labels and can create, rename, delete, or move their channels between them.Users without a team have labels private to their account. The naming and deletedialogs explain which scope applies. Collapse/expand state is per user.-Every label remains visible, including empty labels; only channels the viewer-actively participates in are shown inside it. Direct messages cannot be labelled.+Every label remains visible, including empty labels; only team channels the+viewer actively participates in are shown inside it. Shared labels accept only+channels belonging to the label's team. Private account labels also accept only+team channels. Public channels, private channels, and direct messages cannot be+labelled. They keep their normal navigation, have no label menu actions, and+cannot be dragged into labels. Existing ineligible assignments no longer group+channels, including non-team channels and other teams' channels in shared labels.Names are unique within the team or account, case-insensitively.Layout: labels come first in creation order, each showing its visible channels@@ -375,11 +380,11 @@ reload. Rename uses the same dialog prefilled. Delete asks for confirmation;its button says `Delete for everyone` for shared labels and `Delete label` forprivate ones. Channels remain accessible after deleting their label.-Moving: right-click a channel for `Add to label` / `Move to label`, including a+Moving: right-click a team channel for `Add to label` / `Move to label`, including a`New label…` option, or use `Ungroup from “<label>”`. Drag a channel onto a labelheading or one of its channels to move in. Drag a grouped channel onto a plain-channel, the Channels heading, or empty space below the list to ungroup it.-Dragging one ungrouped channel onto another opens a name dialog; saving creates+team channel, the Channels heading, or empty space below the list to ungroup it.+Dragging one ungrouped team channel onto another opens a name dialog; saving createsthe label with both channels atomically. A failed save changes neither channel.Dropping on the source channel or its current label does nothing; Escape fromthe naming dialog leaves both channels unchanged.@@ -398,21 +403,27 @@ Smart labels: use `Channels` → `+` → `New smart label`. Enter a label name aliterally; it does not use wildcards or regular expressions. The creation dialogshows up to five matching channels as you type, followed by `+N more channelsmatched` for overflow. Empty patterns cannot be saved; a valid pattern with no-current matches can be saved for future channels. Only channels you participate-in are matched, and direct messages are excluded.+current matches can be saved for future channels. Only team channels you+participate in are matched; shared labels match channels from their own team.+Public channels, private channels, and direct messages are excluded from both+the preview and saved results.Group headings have no icon in the sidebar; smart label creation uses a filtericon. Channels appear in every matching smart label and keep any manual labelassignment. A channel in any smart label is excludedfrom the ungrouped list, even when its matching labels are collapsed. Membership-follows channel names automatically. Loaded channels update with live name-changes; other matches refresh periodically. Use the heading's `···` →+follows channel names automatically. Existing matches update with live name+changes; new shared-label matches and unloaded channels refresh periodically.+Use the heading's `···` →`Edit smart label` to change the name or pattern and preview the new matches.Smart labels cannot be drag targets or manually assigned through `Move to label`.Deleting a smart label preserves channels, other labels, and manual assignments.Verify overlapping rules, collapsed labels, no matches, overflow, and quicklychanging patterns (an older response must not replace the latest preview).+Check public and private channels with matching names: they stay in the normal+list, have no label actions, and cannot be dragged into labels or used as a+second channel when grouping by drop. Team channels still support these actions.Open the same matched channel from two labels and verify keyboard focus remainson the chosen row. Check rule edits and persistence after reload.