Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(channels): improve sidebar sharing and interactions (#9498)

dev-rb663d2ee7c4d9
diff --git a/.sqlx/query-03ad2dfdae674337e6d9743a4ab8fd8045dade9db2f7b22704c2d9401574e472.json b/.sqlx/query-03ad2dfdae674337e6d9743a4ab8fd8045dade9db2f7b22704c2d9401574e472.json
new file mode 100644
index 0000000000..0a50256a58
--- /dev/null
+++ b/.sqlx/query-03ad2dfdae674337e6d9743a4ab8fd8045dade9db2f7b22704c2d9401574e472.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM channel_label_channel WHERE scope_key = $1 AND label_id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "03ad2dfdae674337e6d9743a4ab8fd8045dade9db2f7b22704c2d9401574e472"
+}
diff --git a/.sqlx/query-33b151c9b58164d8f91cf916f1505f564db920861622159549b4bfd38964bc04.json b/.sqlx/query-33b151c9b58164d8f91cf916f1505f564db920861622159549b4bfd38964bc04.json
new file mode 100644
index 0000000000..4acd87cb0a
--- /dev/null
+++ b/.sqlx/query-33b151c9b58164d8f91cf916f1505f564db920861622159549b4bfd38964bc04.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT c.id 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 (($3::uuid IS NULL AND c.channel_type IN ('team', 'public', 'private'))\n OR (c.channel_type = 'team' AND c.team_id = $3))\n AND strpos(lower(c.name), lower($2)) > 0\n ORDER BY c.id FOR SHARE OF c, p",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "33b151c9b58164d8f91cf916f1505f564db920861622159549b4bfd38964bc04"
+}
diff --git a/.sqlx/query-5a878591e653d0211a7c961b4a45fdaad52eb8c9faae1f239f2cb7ac65836df4.json b/.sqlx/query-5a878591e653d0211a7c961b4a45fdaad52eb8c9faae1f239f2cb7ac65836df4.json
new file mode 100644
index 0000000000..04d31da056
--- /dev/null
+++ b/.sqlx/query-5a878591e653d0211a7c961b4a45fdaad52eb8c9faae1f239f2cb7ac65836df4.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE channel_label\n SET team_id = $3, user_id = $4, name = $5,\n name_contains = COALESCE($6, name_contains),\n sort_order = COALESCE((SELECT MAX(sort_order) + 1 FROM channel_label WHERE scope_key = $7), 0),\n updated_at = now()\n WHERE scope_key = $1 AND id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5a878591e653d0211a7c961b4a45fdaad52eb8c9faae1f239f2cb7ac65836df4"
+}
diff --git a/.sqlx/query-7d7dea257aca1956dd9c75f9600d6b25c5df3beadda86f580e889c87b42ce688.json b/.sqlx/query-7d7dea257aca1956dd9c75f9600d6b25c5df3beadda86f580e889c87b42ce688.json
new file mode 100644
index 0000000000..3558faa3d9
--- /dev/null
+++ b/.sqlx/query-7d7dea257aca1956dd9c75f9600d6b25c5df3beadda86f580e889c87b42ce688.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\n ON CONFLICT (scope_key, channel_id) DO UPDATE SET label_id = EXCLUDED.label_id",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7d7dea257aca1956dd9c75f9600d6b25c5df3beadda86f580e889c87b42ce688"
+}
diff --git a/.sqlx/query-9c972009a05e7e528a37e044cb3a29fbfa4e134e093fd7bc56406b2aaf6d3630.json b/.sqlx/query-9c972009a05e7e528a37e044cb3a29fbfa4e134e093fd7bc56406b2aaf6d3630.json
new file mode 100644
index 0000000000..f2a16fd527
--- /dev/null
+++ b/.sqlx/query-9c972009a05e7e528a37e044cb3a29fbfa4e134e093fd7bc56406b2aaf6d3630.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT pg_advisory_xact_lock(hashtextextended('channel-labels:' || $1, 0))",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "pg_advisory_xact_lock",
+ "type_info": "Void"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "9c972009a05e7e528a37e044cb3a29fbfa4e134e093fd7bc56406b2aaf6d3630"
+}
diff --git a/.sqlx/query-a6f2e435a019b9f85cff7936d69eb339e1b6d4d7a292d7d346d447a23d2be2a8.json b/.sqlx/query-a6f2e435a019b9f85cff7936d69eb339e1b6d4d7a292d7d346d447a23d2be2a8.json
new file mode 100644
index 0000000000..e1f39e4fde
--- /dev/null
+++ b/.sqlx/query-a6f2e435a019b9f85cff7936d69eb339e1b6d4d7a292d7d346d447a23d2be2a8.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT channel_id FROM channel_label_channel WHERE scope_key = $1 AND label_id = $2 ORDER BY channel_id FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "a6f2e435a019b9f85cff7936d69eb339e1b6d4d7a292d7d346d447a23d2be2a8"
+}
diff --git a/.sqlx/query-e83cbe750bb8e23eaa002ad6b1d2266f6f092db437cec5a3233bbe58defb4525.json b/.sqlx/query-e83cbe750bb8e23eaa002ad6b1d2266f6f092db437cec5a3233bbe58defb4525.json
new file mode 100644
index 0000000000..5b9964b6ed
--- /dev/null
+++ b/.sqlx/query-e83cbe750bb8e23eaa002ad6b1d2266f6f092db437cec5a3233bbe58defb4525.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT name_contains FROM channel_label WHERE scope_key = $1 AND id = $2 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "name_contains",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "e83cbe750bb8e23eaa002ad6b1d2266f6f092db437cec5a3233bbe58defb4525"
+}
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 143553b06c..3571cb9294 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -656,9 +656,9 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
for a notification (Home, Inbox) wait for it to choose a target.
- Gate the Chat redesign with `enable-chat-sidebar-sections`; wait for its result, restore the tabbed rail when off, and keep mobile unchanged.
Keep the original rail renderer and label dialogs in `components/rail/`; build the redesigned rail and section dialogs in `components/rail/next/`, with shared controller, context, and row primitives outside `next/`.
- Default desktop Chat to Favorites, Direct messages, the team's channels, custom sections, then All channels; preserve personal section reordering and keep public/private channels in All channels regardless of custom-section assignments.
- Keep resize and reorder grips keyboard-accessible; reveal bare reorder grips only on header hover or keyboard focus, keep them fixed in the left gutter without shifting section names, and include them within the drag highlight. Allow dragging from the whole heading while preserving normal collapse clicks and excluding action buttons. Preserve personal section heights/order, compensate resize drags for scrolling, disable stack scroll anchoring only during resizing, and route list navigation through the sectioned renderer's scroll handle. Scroll keyboard targets immediately without animation, keeping two rows of context on either side, clamped to the viewport.
- Cap section heights at measured list content and available pane space; hide resize grips for two or fewer items and default Favorites and DMs to four rows. Let final All channels fill its content by default, but preserve saved heights and cap it normally when another section follows. Use TanStack Virtual for the redesigned section stack, channel rows, and search results; keep full-height channel rows virtualized against the outer viewport and retain stable keys, focused rows, and drag sources.
+ Default desktop Chat to Favorites, Direct messages, the team's channels, then custom sections; preserve personal section reordering and omit All channels. Keep joined public/private conversations outside these sections available through sidebar search.
+ Keep resize and reorder grips keyboard-accessible; reveal bare reorder grips only on header hover or keyboard focus, keep them fixed in the left gutter without shifting section names, and include them within the drag highlight. Allow dragging from the whole heading while preserving normal collapse clicks and excluding action buttons. Preserve personal section heights/order, edge-scroll the sidebar while resizing and compensate resize drags for scrolling, disable stack scroll anchoring only during resizing, and route list navigation through the sectioned renderer's scroll handle. Scroll keyboard targets immediately without animation, keeping two rows of context on either side, clamped to the viewport.
+ Cap section heights at measured list content and available pane space; keep each list independently scrollable, hide resize grips for two or fewer items, and default Favorites and DMs to four rows. Use TanStack Virtual for the redesigned section stack, channel rows, and search results; snapshot its index-reconciled rows before keying by identity, and retain focused rows and drag sources.
Mobile retains the recent feed. Keep New channel and New direct message on their separate existing creation flows, independent of the sidebar flag; size the sidebar's New dropdown to its trigger width.
Use `--sidebar-gutter` for the outer section, DM, and search containers; shared headings and rows provide their own item padding.
Indent section rows by 8px; style empty states like saved views with a padded, bordered surface and secondary actions, without the extra row indentation. Keep unsectioned search results unindented.
@@ -669,7 +669,7 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
Keep every joined team channel in the team section regardless of custom-section assignments; use the same complete membership for bulk notification actions.
Keep available channel rows visible during section hydration and refetches; key virtualized rows by stable IDs so data updates cannot interrupt a click. Pass server-returned member IDs to `queries/channel/by-ids`, whose single Soup owner selects cached rows and fetches missing records. Keep entity-ID hydration generic in Soup, with channel identities, batching, and unread refreshes in the channel query layer; append per-section skeletons only while unresolved members load.
Show lock icons for private conversations and visible per-section options; keep empty sections usable as drop targets without an all-sections management menu.
- Create all section types through New → New section in a wider dialog with Smart in the body and Shared in the footer; keep collapse on the header and style deletion as destructive.
+ Create all section types through New → New section in a wider dialog with Smart in the body and Shared in the footer; explain team visibility and team-only channels in hover/tap-accessible sharing help, show the warning-colored Team channels only hint only while sharing is on, keep collapse on the header and style deletion as destructive. Editing can change sharing only after complete membership eligibility checks; preserve section identity, confirm unsharing, and reconcile both scope caches after success.
Offer Add channels on manual-section headers and empty states; keep the picker scoped to eligible joined channels, explain scope and assignment moves in concise helper text, and leave smart membership rule-driven.
Place the smart rule Input below Name contains; show a match count with hover/focus channel preview, and keep preview queries reactive to the selected scope without briefly reporting pending matches as empty.
Keep per-section sorting and unread filters personal, and filter after membership assignment so hidden rows never leak into another section.
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx
index 674a2a7ce6..b81a70cdb5 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx
@@ -584,16 +584,16 @@ describe('section reordering', () => {
});
describe('resizable chat sections', () => {
- it('grows the last All channels list to its content while preserving manual heights', () => {
- const [maximum, setMaximum] = createSignal(Number.POSITIVE_INFINITY);
+ it('caps every section to its available height while preserving manual heights', () => {
+ const [maximum, setMaximum] = createSignal(400);
const [savedHeight, setSavedHeight] = createSignal<number>();
rail.sectionPreferences = () => ({ sort: 'manual', height: savedHeight() });
measurements.contentHeight = () => 1360;
let viewport!: HTMLDivElement;
render(() => (
<ResizableRailSection
- section="channels"
- label="All channels"
+ section="team_channels"
+ label="Team channels"
open
maxHeight={maximum()}
itemCount={40}
@@ -607,23 +607,22 @@ describe('resizable chat sections', () => {
</ResizableRailSection>
));
- expect(viewport.style.height).toBe('1360px');
+ expect(viewport.style.height).toBe('400px');
setMaximum(252);
expect(viewport.style.height).toBe('252px');
setSavedHeight(180);
- setMaximum(Number.POSITIVE_INFINITY);
expect(viewport.style.height).toBe('180px');
- setMaximum(252);
+ setMaximum(400);
expect(viewport.style.height).toBe('180px');
- setMaximum(Number.POSITIVE_INFINITY);
setSavedHeight(1100);
- expect(viewport.style.height).toBe('1100px');
+ expect(viewport.style.height).toBe('400px');
expect(clampChannelSectionHeight(1100)).toBe(1100);
+ setSavedHeight(180);
fireEvent.keyDown(screen.getByRole('separator'), { key: 'ArrowDown' });
- expect(rail.setSectionPreferences).toHaveBeenCalledWith('channels', {
- height: 1120,
+ expect(rail.setSectionPreferences).toHaveBeenCalledWith('team_channels', {
+ height: 200,
});
});
@@ -735,6 +734,95 @@ describe('resizable chat sections', () => {
});
});
+ it.each(['pointerup', 'pointercancel'])(
+ 'scrolls while resizing near the sidebar edge and stops on %s',
+ (endEvent) => {
+ const frames = new Map<number, FrameRequestCallback>();
+ let frameId = 0;
+ const request = vi
+ .spyOn(window, 'requestAnimationFrame')
+ .mockImplementation((callback) => {
+ frames.set(++frameId, callback);
+ return frameId;
+ });
+ const cancel = vi
+ .spyOn(window, 'cancelAnimationFrame')
+ .mockImplementation((id) => {
+ frames.delete(id);
+ });
+ const outer = document.createElement('div');
+ Object.defineProperties(outer, {
+ clientHeight: { value: 280 },
+ scrollHeight: { value: 800 },
+ });
+ vi.spyOn(outer, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(0, 0, 200, 280)
+ );
+ let viewport!: HTMLDivElement;
+ const view = render(() => (
+ <ResizableRailSection
+ section="favorites"
+ label="Favorites"
+ open
+ maxHeight={400}
+ itemCount={12}
+ outerScrollRoot={outer}
+ header={<span>Section</span>}
+ rootRef={() => {}}
+ scrollRef={(element) => {
+ viewport = element;
+ Object.defineProperty(element, 'offsetHeight', { value: 136 });
+ vi.spyOn(element, 'getBoundingClientRect').mockImplementation(
+ () => new DOMRect(0, 132 - outer.scrollTop, 200, 136)
+ );
+ }}
+ >
+ Conversations
+ </ResizableRailSection>
+ ));
+ const handle = screen.getByRole('separator');
+ Object.defineProperty(handle, 'setPointerCapture', { value: vi.fn() });
+ const start = new MouseEvent('pointerdown', {
+ bubbles: true,
+ clientX: 100,
+ clientY: 268,
+ });
+ Object.defineProperty(start, 'pointerId', { value: 1 });
+ handle.dispatchEvent(start);
+
+ for (const time of [0, 16, 32]) {
+ const pending = [...frames.values()];
+ frames.clear();
+ for (const callback of pending) callback(time);
+ }
+
+ expect(outer.scrollTop).toBeGreaterThan(0);
+ expect(Number.parseFloat(viewport.style.height)).toBe(
+ Math.round(136 + outer.scrollTop)
+ );
+ const end = new MouseEvent(endEvent, {
+ bubbles: true,
+ clientX: 100,
+ clientY: 268,
+ });
+ Object.defineProperty(end, 'pointerId', { value: 1 });
+ handle.dispatchEvent(end);
+ expect(frames.size).toBe(0);
+ if (endEvent === 'pointerup') {
+ expect(rail.setSectionPreferences).toHaveBeenCalledExactlyOnceWith(
+ 'favorites',
+ { height: Math.round(136 + outer.scrollTop) }
+ );
+ } else {
+ expect(rail.setSectionPreferences).not.toHaveBeenCalled();
+ }
+
+ view.unmount();
+ request.mockRestore();
+ cancel.mockRestore();
+ }
+ );
+
it.each(['pointercancel', 'lostpointercapture'])(
'does not save after %s and accepts a later resize',
(cancelEvent) => {
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.test.tsx
index 32eb51ba4c..7fd476c3ea 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.test.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.test.tsx
@@ -10,6 +10,9 @@ import type { ComponentProps, ParentProps } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { promptLabelName } from './ChannelLabelNameDialog';
import { promptSectionChannels } from './next/SectionChannelsDialog';
+import { promptSection } from './next/SectionDialog';
+
+const confirmSharing = vi.hoisted(() => vi.fn());
const availableChannels = vi.hoisted(() => [
{
@@ -59,6 +62,7 @@ vi.mock('@queries/channel-labels/channel-labels', () => ({
isPending: false,
data: availableChannels,
}),
+ useChannelLabelsQuery: () => ({ isPending: false, data: { teamId: 'team' } }),
}));
vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
@@ -66,6 +70,8 @@ vi.mock('@ui', async () => ({
...(await import('@app/components/ui/components/ImperativeDialog')),
...(await import('@app/components/ui/components/Dialog')),
...(await import('@app/components/ui/components/Checkbox')),
+ ...(await import('@app/components/ui/components/ToggleSwitch')),
+ confirmDialog: confirmSharing,
cn: (...values: unknown[]) => values.filter(Boolean).join(' '),
Layer: (props: ParentProps) => props.children,
Surface: (props: ParentProps) => <div>{props.children}</div>,
@@ -76,7 +82,10 @@ vi.mock('@ui', async () => ({
</button>
),
}));
-beforeEach(() => vi.stubGlobal('scrollTo', vi.fn()));
+beforeEach(() => {
+ vi.stubGlobal('scrollTo', vi.fn());
+ confirmSharing.mockReset().mockResolvedValue(true);
+});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
@@ -145,6 +154,67 @@ describe('label naming', () => {
});
});
+describe('section sharing changes', () => {
+ it('blocks sharing an existing section with ineligible channels', async () => {
+ render(() => <ImperativeDialogHost />);
+ const onConfirm = vi.fn(async () => {});
+ const dialog = promptSection({
+ scope: 'personal',
+ canShare: true,
+ initial: {
+ id: 'section',
+ name: 'Section',
+ channelIds: ['private'],
+ channelCount: 1,
+ sortOrder: 0,
+ createdAt: '2026-01-01',
+ updatedAt: '2026-01-01',
+ },
+ onConfirm,
+ });
+ const sharing = screen.getByRole('switch', { name: 'Shared with team' });
+ expect(sharing).toHaveProperty('disabled', true);
+ fireEvent.click(sharing);
+ expect(sharing).toHaveProperty('checked', false);
+ expect(onConfirm).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
+ await dialog;
+ });
+
+ it('keeps an unshared edit open when confirmation is cancelled and saves after confirmation', async () => {
+ render(() => <ImperativeDialogHost />);
+ confirmSharing.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+ const onConfirm = vi.fn(async () => {});
+ const dialog = promptSection({
+ scope: 'team',
+ canShare: true,
+ initial: {
+ id: 'section',
+ name: 'Section',
+ teamId: 'team',
+ channelIds: ['first'],
+ channelCount: 1,
+ sortOrder: 0,
+ createdAt: '2026-01-01',
+ updatedAt: '2026-01-01',
+ },
+ onConfirm,
+ });
+ fireEvent.click(screen.getByRole('switch', { name: 'Shared with team' }));
+ const save = screen.getByRole('button', { name: 'Save section' });
+ fireEvent.click(save);
+ await waitFor(() => expect(confirmSharing).toHaveBeenCalledTimes(1));
+ expect(onConfirm).not.toHaveBeenCalled();
+ await waitFor(() => expect(save).toHaveProperty('disabled', false));
+ fireEvent.click(save);
+ await dialog;
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith({
+ name: 'Section',
+ scope: 'personal',
+ });
+ });
+});
+
describe('section channel selection', () => {
it('offers only eligible additions and retries failed channels without replaying successful additions', async () => {
render(() => <ImperativeDialogHost />);
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx
index 67ae820071..038f75d7f9 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx
@@ -236,7 +236,11 @@ vi.mock('../../channels-view-context', () => ({
useChannelsView: () => ({
state: {
tab: 'browse',
- expandedGroups: { channels: true, direct_messages: true },
+ expandedGroups: {
+ channels: true,
+ team_channels: true,
+ direct_messages: true,
+ },
collapsedLabels: [],
sectionPreferences: {},
sortBy: {
@@ -537,7 +541,7 @@ it('keeps a pressed channel row attached through a live data refresh and activat
const [channels, setChannels] = createSignal([channel]);
const liveSources: ChannelsSources = {
...sources,
- channels: { ...source, items: channels },
+ team_channels: { ...source, items: channels },
direct_messages: { ...source, items: () => [] },
};
const { container } = render(() => (
@@ -594,7 +598,7 @@ describe('section heading navigation', () => {
it.each([
['label:first', ']', 'label:second'],
['label:second', '[', 'label:first'],
- ['section:team_channels', ']', 'section:channels'],
+ ['section:team_channels', ']', 'label:first'],
['channel:one:label:first', ']', 'label:second'],
])('jumps from %s with %s to %s', (from, hotkey, to) => {
const first: ChannelLabel = {
@@ -608,12 +612,11 @@ describe('section heading navigation', () => {
};
mocks.listRows = [
{ kind: 'section', id: 'section:team_channels', group: 'team_channels' },
- { kind: 'section', id: 'section:channels', group: 'channels' },
{
kind: 'label',
id: 'label:first',
group: 'team_channels',
- localIndex: 2,
+ localIndex: 1,
label: first,
},
{
@@ -621,7 +624,7 @@ describe('section heading navigation', () => {
id: 'channel:one:label:first',
group: 'team_channels',
scope: 'team_channels',
- localIndex: 3,
+ localIndex: 2,
channel,
labelId: 'first',
},
@@ -629,7 +632,7 @@ describe('section heading navigation', () => {
kind: 'label',
id: 'label:second',
group: 'team_channels',
- localIndex: 4,
+ localIndex: 3,
label: { ...first, id: 'second', name: 'Second' },
},
];
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.ts
index 282488f002..5494fb16a2 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
@@ -571,7 +571,7 @@ it.each([true, false])(
);
it.each([true, false])(
- 'keeps assigned public and private channels in All channels when custom sections are open=%s',
+ 'omits All channels while keeping custom public and private channel sections open=%s',
(open) => {
const publicChannel = channel('public', 'Public', 'public');
const privateChannel = channel('private', 'Private', 'private');
@@ -610,10 +610,15 @@ it.each([true, false])(
);
const grouped = groupChannelRailSections(rows);
- expect(grouped.get('channels')?.rows.map((row) => row.id)).toEqual([
- 'channel:public',
- 'channel:private',
- 'status:channels',
+ expect([...grouped.keys()]).toEqual([
+ 'favorites',
+ 'direct_messages',
+ 'team_channels',
+ 'label:manual',
+ 'label:smart',
+ ]);
+ expect(grouped.get('team_channels')?.rows.map((row) => row.id)).toEqual([
+ 'status:team_channels',
]);
expect(grouped.get('label:manual')?.rows.map((row) => row.id)).toEqual(
open ? ['channel:public:label:manual'] : []
@@ -661,26 +666,15 @@ it('keeps section membership and navigation together after reordering with stale
'team_channels',
'favorites',
'direct_messages',
- 'channels',
]);
expect(grouped.get('label:first')?.rows.map((row) => row.id)).toEqual([
'channel:acme:label:first',
'reference-status:label:first',
]);
- expect(grouped.get('channels')?.rows.map((row) => row.id)).toEqual([
- 'channel:private',
- 'status:channels',
- ]);
expect(new Set(rows.map((row) => row.id)).size).toBe(rows.length);
expect([
...groupChannelRailSections(
- orderChannelRailSections(rows, ['favorites', 'channels'])
+ orderChannelRailSections(rows, ['favorites', 'direct_messages'])
).keys(),
- ]).toEqual([
- 'favorites',
- 'label:first',
- 'team_channels',
- 'direct_messages',
- 'channels',
- ]);
+ ]).toEqual(['favorites', 'direct_messages', 'label:first', 'team_channels']);
});
diff --git a/apps/web/src/features/channels-view/components/rail/hooks/useChannelLabelActions.ts b/apps/web/src/features/channels-view/components/rail/hooks/useChannelLabelActions.ts
index 74bfd60864..0ff61c1c96 100644
--- a/apps/web/src/features/channels-view/components/rail/hooks/useChannelLabelActions.ts
+++ b/apps/web/src/features/channels-view/components/rail/hooks/useChannelLabelActions.ts
@@ -231,16 +231,29 @@ export function useChannelLabelActions(options: ChannelLabelActionsOptions) {
}
const scope = scopeForLabel(label);
- const save = ({ name, rule }: { name: string; rule?: ChannelLabelRule }) =>
+ const save = ({
+ name,
+ rule,
+ scope: nextScope = scope,
+ }: {
+ name: string;
+ rule?: ChannelLabelRule;
+ scope?: ChannelLabelScopeSelection;
+ }) =>
Telemetry.span('channels.section.update', async (span) => {
span.setAttr('section.id', label.id);
span.setAttr('section.scope', scope);
span.setAttr('section.smart', Boolean(rule));
+ span.setAttr('section.target_scope', nextScope);
+
+ const current = labels().find((item) => item.id === label.id);
if (
actorId !== userId() ||
sectionMode !== sectionsEnabled() ||
!channelTagsEnabled() ||
+ !current ||
+ scopeForLabel(current) !== scope ||
!labelsAvailable()
) {
throw new Error(t('channelSections.unavailable'));
@@ -250,6 +263,7 @@ export function useChannelLabelActions(options: ChannelLabelActionsOptions) {
labelId: label.id,
name,
rule,
+ targetScope: nextScope === scope ? undefined : nextScope,
actorId,
});
@@ -265,7 +279,7 @@ export function useChannelLabelActions(options: ChannelLabelActionsOptions) {
{
scope,
canShare: sharedLabels(),
- initial: { name: label.name, rule: label.rule ?? undefined },
+ initial: label,
onConfirm: save,
},
{ owner: labelDialogOwner() }
diff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelRailVirtualizer.test.ts b/apps/web/src/features/channels-view/components/rail/next/ChannelRailVirtualizer.test.ts
index 9779f95f14..4e44526f27 100644
--- a/apps/web/src/features/channels-view/components/rail/next/ChannelRailVirtualizer.test.ts
+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelRailVirtualizer.test.ts
@@ -254,6 +254,57 @@ describe('channel rail virtualizer', () => {
expect(view.getByText('row-0')).toBe(row);
});
+ it('measures unequal section heights before and after reordering', () => {
+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(
+ function (this: HTMLElement) {
+ if (this.hasAttribute('data-viewport')) return 200;
+ return Number(
+ this.firstElementChild?.getAttribute('data-height') ?? 32
+ );
+ }
+ );
+ const viewport = document.createElement('div');
+ viewport.setAttribute('data-viewport', '');
+ Object.defineProperty(viewport, 'clientHeight', { value: 200 });
+ document.body.append(viewport);
+ const [keys, setKeys] = createSignal(['short', 'long', 'last']);
+ let handle: ChannelRailVirtualizerHandle | undefined;
+ const view = render(
+ () =>
+ createComponent(ChannelRailVirtualizer<string>, {
+ get keys() {
+ return keys();
+ },
+ scrollRoot: viewport,
+ estimateSize: 200,
+ keepMounted: [0, 1, 2],
+ ref: (current) => {
+ handle = current;
+ },
+ children: (key) => {
+ const button = document.createElement('button');
+ button.textContent = key;
+ button.setAttribute('data-height', key === 'long' ? '260' : '40');
+ return button;
+ },
+ }),
+ { container: viewport }
+ );
+ const short = view.getByText('short');
+ const long = view.getByText('long');
+ expect(handle?.scrollMetrics().size).toBe(340);
+ expect(long.parentElement?.style.top).toBe('40px');
+
+ setKeys(['long', 'short', 'last']);
+
+ expect(view.getByText('short')).toBe(short);
+ expect(view.getByText('long')).toBe(long);
+ expect(handle?.scrollMetrics().size).toBe(340);
+ expect(long.parentElement?.style.top).toBe('0px');
+ expect(short.parentElement?.style.top).toBe('260px');
+ expect(view.getByText('last').parentElement?.style.top).toBe('300px');
+ });
+
it('retains focused or dragged rows outside the viewport', () => {
const view = mount(0);
measure(200);
diff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelRailVirtualizer.tsx b/apps/web/src/features/channels-view/components/rail/next/ChannelRailVirtualizer.tsx
index d985a714df..57663565fc 100644
--- a/apps/web/src/features/channels-view/components/rail/next/ChannelRailVirtualizer.tsx
+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelRailVirtualizer.tsx
@@ -9,6 +9,7 @@ import {
} from '@tanstack/solid-virtual';
import {
createEffect,
+ createMemo,
createSignal,
type JSX,
on,
@@ -120,6 +121,11 @@ function VirtualRows<K extends string>(
},
});
+ // TanStack reconciles its store by index; snapshot rows before keying by identity.
+ const virtualRows = createMemo(() =>
+ virtualizer.getVirtualItems().map((row) => ({ ...row }))
+ );
+
const handle: ChannelRailVirtualizerHandle = {
scrollToIndex: (index, options) => {
const align = options?.align;
@@ -169,7 +175,7 @@ function VirtualRows<K extends string>(
class="relative w-full"
style={{ height: `${virtualizer.getTotalSize()}px` }}
>
- <Key each={virtualizer.getVirtualItems()} by="key">
+ <Key each={virtualRows()} by="key">
{(row) => {
const key = untrack(() => props.keys[row().index]);
let element: HTMLDivElement | undefined;
diff --git a/apps/web/src/features/channels-view/components/rail/next/ExpandedChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/next/ExpandedChannelsRail.tsx
index 8bf78e2437..79021b1802 100644
--- a/apps/web/src/features/channels-view/components/rail/next/ExpandedChannelsRail.tsx
+++ b/apps/web/src/features/channels-view/components/rail/next/ExpandedChannelsRail.tsx
@@ -170,9 +170,6 @@ function SectionHeading(props: { group: 'favorites' | ChannelsGroup }) {
}
}
- if (props.group === 'channels') {
- return t('channelSections.allChannels');
- }
return t(`channelSections.${props.group}`);
};
@@ -313,7 +310,6 @@ type SectionHandle = {
root?: HTMLDivElement;
virtualizer?: ChannelRailVirtualizerHandle;
viewport?: HTMLDivElement;
- outerScroll?: boolean;
};
function BrowseSection(props: {
@@ -321,8 +317,6 @@ function BrowseSection(props: {
section: ChannelRailSectionRows;
maxHeight: number;
outerScrollRoot: HTMLDivElement | undefined;
- layoutVersion: number;
- sectionOrder: readonly ChannelSectionKey[];
scrollVersion: number;
savedScrollTop: number;
onReady: () => void;
@@ -337,14 +331,6 @@ function BrowseSection(props: {
const [virtualizer, setVirtualizer] =
createSignal<ChannelRailVirtualizerHandle>();
const size = createElementSize(scrollRoot);
- const [resizing, setResizing] = createSignal(false);
- const [startMargin, setStartMargin] = createSignal(0);
- const outerScroll = () =>
- props.maxHeight === Number.POSITIVE_INFINITY &&
- rail.sectionPreferences(props.sectionKey).height === undefined &&
- !resizing();
- const rowsScrollRoot = () =>
- outerScroll() ? props.outerScrollRoot : scrollRoot();
const droppable = createDroppable(
`${props.sectionReorder.scope}:${props.sectionKey}`,
{
@@ -357,38 +343,10 @@ function BrowseSection(props: {
onCleanup(props.register(props.sectionKey, handle));
onMount(() => {
const viewport = scrollRoot();
- if (viewport && !outerScroll()) viewport.scrollTop = props.savedScrollTop;
+ if (viewport) viewport.scrollTop = props.savedScrollTop;
props.onReady();
});
- createEffect(
- on(
- [
- scrollRoot,
- outerScroll,
- () => props.layoutVersion,
- () => props.sectionOrder,
- () => size.height,
- ],
- () => {
- if (!outerScroll()) return;
- const frame = requestAnimationFrame(() => {
- let element: HTMLElement | undefined = scrollRoot();
- let offset = 0;
- while (element && element !== props.outerScrollRoot) {
- offset += element.offsetTop;
- element =
- element.offsetParent instanceof HTMLElement
- ? element.offsetParent
- : undefined;
- }
- setStartMargin(offset);
- });
- onCleanup(() => cancelAnimationFrame(frame));
- }
- )
- );
-
// Stable row IDs preserve in-flight pointer gestures during live updates.
const rowsById = createMemo(
() => new Map(props.section.rows.map((row) => [row.id, row]))
@@ -413,9 +371,6 @@ function BrowseSection(props: {
const label = () => {
const row = heading();
- if (row.kind === 'section' && row.group === 'channels') {
- return t('channelSections.allChannels');
- }
return row.kind === 'label'
? row.label.name
: t(`channelSections.${row.group}`);
@@ -509,8 +464,8 @@ function BrowseSection(props: {
maxHeight={props.maxHeight}
dropEdge={props.sectionReorder.dropEdge(props.sectionKey)}
dragging={props.sectionReorder.isDragging(props.sectionKey)}
+ outerScrollRoot={props.outerScrollRoot}
itemCount={itemCount()}
- onResizingChange={setResizing}
rootRef={(element) => {
handle.root = element;
droppable.ref(element);
@@ -553,13 +508,11 @@ function BrowseSection(props: {
<ChannelRailVirtualizer
ref={(current) => {
handle.virtualizer = current;
- handle.outerScroll = outerScroll();
setVirtualizer(current);
if (current) props.onReady();
}}
keys={rowIds()}
- scrollRoot={rowsScrollRoot()}
- scrollMargin={outerScroll() ? startMargin() : 0}
+ scrollRoot={scrollRoot()}
scrollPadding={CHANNEL_SECTION_ROW_HEIGHT * 2}
estimateSize={CHANNEL_SECTION_ROW_HEIGHT}
keepMounted={keepRows()}
@@ -598,7 +551,6 @@ function BrowseSection(props: {
function ExpandedBrowse() {
const rail = useChannelsRail();
const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();
- const [stackContent, setStackContent] = createSignal<HTMLDivElement>();
const [scrollVersion, setScrollVersion] = createSignal(0);
const [handlesVersion, setHandlesVersion] = createSignal(0);
const [gestureSection, setGestureSection] = createSignal<ChannelSectionKey>();
@@ -610,7 +562,6 @@ function ExpandedBrowse() {
}>();
const userId = useUserId();
const scrollSize = createElementSize(scrollRoot);
- const stackSize = createElementSize(stackContent);
const scrollOffsets = new Map<ChannelSectionKey, number>();
const sections = createMemo(() =>
groupChannelRailSections(rail.list.items.all())
@@ -624,22 +575,11 @@ function ExpandedBrowse() {
}
return lookup;
});
- const maximumHeight = (key: ChannelSectionKey) => {
- const paneHeight = Math.min(
+ const maximumHeight = () =>
+ Math.min(
CHANNEL_SECTION_MAX_HEIGHT,
Math.max(CHANNEL_SECTION_MIN_HEIGHT, (scrollSize.height ?? 300) - 48)
);
-
- if (key !== 'channels') {
- return paneHeight;
- }
-
- if (keys().at(-1) === key) {
- return Number.POSITIVE_INFINITY;
- }
-
- return Math.max(paneHeight, rail.sectionPreferences(key).height ?? 0);
- };
const handles = new Map<ChannelSectionKey, SectionHandle>();
const motion = createLayoutAnimation({
viewport: scrollRoot,
@@ -751,7 +691,7 @@ function ExpandedBrowse() {
handles.set(key, handle);
return () => {
if (handles.get(key) === handle) {
- if (handle.viewport && !handle.outerScroll) {
+ if (handle.viewport) {
scrollOffsets.set(key, handle.viewport.scrollTop);
}
handles.delete(key);
@@ -802,7 +742,7 @@ function ExpandedBrowse() {
const target = document.getElementById(
domIdForRow(rail.railId, request.rowId)
);
- if (container && target && (!handle.outerScroll || currentIndex < 0)) {
+ if (container && target) {
const nextOffset =
currentIndex >= 0
? handle.virtualizer?.getScrollOffsetForIndex(
@@ -837,7 +777,7 @@ function ExpandedBrowse() {
class="scrollbar-hidden relative min-h-0 flex-1 overflow-y-auto px-(--sidebar-gutter) [&:has([data-resizing])]:[overflow-anchor:none]"
on:scroll={{ capture: true, handleEvent: updateDropTarget }}
>
- <div ref={setStackContent}>
+ <div>
<ChannelRailVirtualizer
scrollRoot={scrollRoot()}
keys={keys()}
@@ -851,10 +791,8 @@ function ExpandedBrowse() {
<BrowseSection
sectionKey={key}
section={section()}
- maxHeight={maximumHeight(key)}
+ maxHeight={maximumHeight()}
outerScrollRoot={scrollRoot()}
- layoutVersion={stackSize.height ?? 0}
- sectionOrder={keys()}
scrollVersion={scrollVersion()}
savedScrollTop={scrollOffsets.get(key) ?? 0}
onReady={ready}
diff --git a/apps/web/src/features/channels-view/components/rail/next/ResizableRailSection.tsx b/apps/web/src/features/channels-view/components/rail/next/ResizableRailSection.tsx
index 365f295d79..d0191403c1 100644
--- a/apps/web/src/features/channels-view/components/rail/next/ResizableRailSection.tsx
+++ b/apps/web/src/features/channels-view/components/rail/next/ResizableRailSection.tsx
@@ -1,3 +1,4 @@
+import { createPointerAutoScroll } from '@app/components/drag-drop/create-pointer-auto-scroll';
import { t } from '@app/lib/i18n';
import { useUserId } from '@core/context/user';
import { createElementSize } from '@solid-primitives/resize-observer';
@@ -21,6 +22,7 @@ export function ResizableRailSection(props: {
itemCount: number;
dropEdge?: 'top' | 'bottom';
dragging?: boolean;
+ outerScrollRoot?: HTMLDivElement;
onResizingChange?: (resizing: boolean) => void;
header: JSX.Element;
children: JSX.Element;
@@ -71,6 +73,7 @@ export function ResizableRailSection(props: {
| {
pointer: number;
y: number;
+ current: { x: number; y: number };
height: number;
zoom: number;
top: number;
@@ -79,23 +82,35 @@ export function ResizableRailSection(props: {
}
| undefined;
- const draggedHeight = (event: PointerEvent) => {
+ const draggedHeight = (clientY: number) => {
const element = viewport();
if (!drag || !element) {
return height();
}
const shift = element.getBoundingClientRect().top - drag.top;
- return clamp(drag.height + (event.clientY - drag.y - shift) / drag.zoom);
+ return clamp(drag.height + (clientY - drag.y - shift) / drag.zoom);
};
+
+ const autoScroll = createPointerAutoScroll({
+ getViewport: () => props.outerScrollRoot,
+ getPointer: () => (drag?.account === account() ? drag.current : undefined),
+ axis: 'y',
+ allowOutside: true,
+ onScroll: () => {
+ if (drag) setPreview(draggedHeight(drag.current.y));
+ },
+ });
+
const finish = (event: PointerEvent, cancelled = false) => {
if (!drag || event.pointerId !== drag.pointer) {
return;
}
const current = drag;
- const nextHeight = draggedHeight(event);
+ const nextHeight = draggedHeight(event.clientY);
drag = undefined;
+ autoScroll.stop();
if (current.handle.hasPointerCapture?.(current.pointer)) {
current.handle.releasePointerCapture(current.pointer);
@@ -160,6 +175,7 @@ export function ResizableRailSection(props: {
{(_resizable) => {
onCleanup(() => {
drag = undefined;
+ autoScroll.stop();
setPreview(undefined);
props.onResizingChange?.(false);
});
@@ -188,6 +204,7 @@ export function ResizableRailSection(props: {
drag = {
pointer: event.pointerId,
y: event.clientY,
+ current: { x: event.clientX, y: event.clientY },
height: element.offsetHeight,
zoom:
element.getBoundingClientRect().height /
@@ -199,6 +216,7 @@ export function ResizableRailSection(props: {
setPreview(element.offsetHeight);
props.onResizingChange?.(true);
event.currentTarget.setPointerCapture(event.pointerId);
+ autoScroll.start();
}}
onPointerMove={(event) => {
if (!drag || event.pointerId !== drag.pointer) {
@@ -210,7 +228,8 @@ export function ResizableRailSection(props: {
return;
}
- setPreview(draggedHeight(event));
+ drag.current = { x: event.clientX, y: event.clientY };
+ setPreview(draggedHeight(event.clientY));
}}
onPointerUp={(event) => finish(event)}
onPointerCancel={(event) => finish(event, true)}
diff --git a/apps/web/src/features/channels-view/components/rail/next/SectionDialog.tsx b/apps/web/src/features/channels-view/components/rail/next/SectionDialog.tsx
index fadb9f30f9..162668a766 100644
--- a/apps/web/src/features/channels-view/components/rail/next/SectionDialog.tsx
+++ b/apps/web/src/features/channels-view/components/rail/next/SectionDialog.tsx
@@ -1,11 +1,18 @@
import { t } from '@app/lib/i18n';
import { fireAndForget } from '@core/util/fireAndForget';
import HashIcon from '@icon/system/regular/hash.svg';
-import { useSmartTagPreviewQuery } from '@queries/channel-labels/channel-labels';
+import QuestionMarkIcon from '@icon/system/regular/question-mark.svg';
+import {
+ useAvailableSectionChannelsQuery,
+ useChannelLabelsQuery,
+ useSmartTagPreviewQuery,
+} from '@queries/channel-labels/channel-labels';
+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
import type { ChannelLabelRule } from '@service-storage/generated/schemas/channelLabelRule';
import type { ChannelLabelScopeSelection } from '@service-storage/generated/schemas/channelLabelScopeSelection';
import {
Button,
+ confirmDialog,
Dialog,
HoverCard,
Input,
@@ -18,12 +25,16 @@ import {
} from '@ui';
import {
type Accessor,
+ createMemo,
createSignal,
+ createUniqueId,
For,
+ getOwner,
Match,
Show,
Switch,
} from 'solid-js';
+import { channelSectionScopeChangeError } from '../../../core/channel-label-eligibility';
export type SectionDialogValue = {
name: string;
@@ -34,7 +45,7 @@ export type SectionDialogValue = {
export type SectionDialogProps = {
scope?: ChannelLabelScopeSelection;
canShare: boolean;
- initial?: { name: string; rule?: ChannelLabelRule };
+ initial?: ChannelLabel;
onConfirm: (value: SectionDialogValue) => Promise<void>;
};
@@ -136,6 +147,12 @@ function SmartSectionPreview(props: {
}
function SectionDialog(props: SectionDialogProps & ManagedDialogProps) {
+ const dialogOwner = getOwner();
+ const initialScope = props.scope ?? 'personal';
+ const teamLabels = useChannelLabelsQuery();
+ const channels = useAvailableSectionChannelsQuery(
+ () => props.canShare && Boolean(props.initial?.channelCount)
+ );
const [name, setName] = createSignal(props.initial?.name ?? '');
const [scope, setScope] = createSignal<ChannelLabelScopeSelection>(
props.scope ?? 'personal'
@@ -148,9 +165,52 @@ function SectionDialog(props: SectionDialogProps & ManagedDialogProps) {
);
const [saving, setSaving] = createSignal(false);
const [error, setError] = createSignal('');
+ const [sharingHelpOpen, setSharingHelpOpen] = createSignal(false);
+ const sharingHelpId = createUniqueId();
+
+ const channelsById = createMemo(
+ () =>
+ new Map(
+ (channels.isPending ? [] : (channels.data ?? [])).map((channel) => [
+ channel.id,
+ {
+ channelType: channel.channel_type,
+ teamId: channel.team_id ?? undefined,
+ isParticipant: channel.is_participant,
+ },
+ ])
+ )
+ );
+ const scopeChangeError = (target: ChannelLabelScopeSelection) => {
+ const initial = props.initial;
+ if (!initial) return;
+
+ const teamId = !teamLabels.isPending ? teamLabels.data?.teamId : undefined;
+ if (target === 'team' && !teamId) return t('channelSections.noAccess');
+ if (initial.channelCount > 0 && channels.isPending)
+ return t('channelSections.checkingSharing');
+ if (initial.channelCount > 0 && channels.isError)
+ return t('channelSections.channelsUnavailable');
+
+ const error = channelSectionScopeChangeError(initial, channelsById(), {
+ teamId: target === 'team' ? teamId : undefined,
+ });
+ if (error === 'team-only')
+ return t('channelSections.sharingIneligibleChannels');
+ if (error === 'unavailable')
+ return t('channelSections.sharingUnavailableChannels');
+ };
+ const sharingDisabledReason = () => {
+ if (scope() !== initialScope) return;
+ return scopeChangeError(initialScope === 'personal' ? 'team' : 'personal');
+ };
+ const selectedScopeError = () =>
+ scope() !== initialScope ? scopeChangeError(scope()) : undefined;
const trimmedPattern = () => pattern().trim();
const canSubmit = () => {
+ if (selectedScopeError()) return false;
+
if (name().trim().length === 0) {
return false;
}
@@ -159,7 +219,11 @@ function SectionDialog(props: SectionDialogProps & ManagedDialogProps) {
return false;
}
- if (!props.initial || name().trim() !== props.initial.name.trim()) {
+ if (
+ !props.initial ||
+ scope() !== initialScope ||
+ name().trim() !== props.initial.name.trim()
+ ) {
return true;
}
@@ -189,6 +253,28 @@ function SectionDialog(props: SectionDialogProps & ManagedDialogProps) {
setError('');
try {
+ if (props.initial && initialScope === 'team' && scope() === 'personal') {
+ const confirmed = await confirmDialog(
+ {
+ title: t('channelSections.makePersonalTitle'),
+ body: t('channelSections.makePersonalBody', {
+ name: props.initial.name,
+ }),
+ confirmLabel: t('channelSections.makePersonal'),
+ cancelLabel: t('channelSections.cancel'),
+ tone: 'danger',
+ },
+ { owner: dialogOwner }
+ );
+ if (!confirmed) return;
+ }
+
+ const scopeError = selectedScopeError();
+ if (scopeError) {
+ setError(scopeError);
+ return;
+ }
+
const value: SectionDialogValue = {
name: name().trim(),
scope: scope(),
@@ -279,22 +365,40 @@ function SectionDialog(props: SectionDialogProps & ManagedDialogProps) {
<Show when={kind() === 'smart' && trimmedPattern().length > 0}>
<SmartSectionPreview pattern={trimmedPattern} scope={scope} />
</Show>
- <p class="text-xs leading-5 text-ink-muted">
- {scope() === 'team'
- ? t('channelSections.teamChannelsOnly')
- : t('channelSections.personalChannelsHint')}
- </p>
+ <Show when={scope() === 'team'}>
+ <p class="text-xs leading-5 text-warning">
+ {t('channelSections.teamChannelsOnly')}
+ </p>
+ </Show>
</div>
<div class="flex flex-wrap items-center justify-end gap-3 px-5 py-3">
- <Show when={!props.initial && props.canShare}>
- <ToggleSwitch
- class="mr-auto shrink-0"
- label={t('channelSections.shared')}
- labelClass="text-xs text-ink-muted font-normal whitespace-nowrap"
- checked={scope() === 'team'}
- onChange={(checked) => setScope(checked ? 'team' : 'personal')}
- disabled={saving()}
- />
+ <Show when={props.canShare}>
+ <div class="mr-auto flex shrink-0 items-center gap-1">
+ <ToggleSwitch
+ label={t('channelSections.shared')}
+ labelClass="text-xs text-ink-muted font-normal whitespace-nowrap"
+ checked={scope() === 'team'}
+ onChange={(checked) =>
+ setScope(checked ? 'team' : 'personal')
+ }
+ disabled={saving() || Boolean(sharingDisabledReason())}
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t('channelSections.sharingHelpLabel')}
+ aria-expanded={sharingHelpOpen()}
+ aria-controls={sharingHelpId}
+ onClick={() => setSharingHelpOpen((open) => !open)}
+ tooltip={{
+ content: t('channelSections.sharingHelp'),
+ disabled: sharingHelpOpen(),
+ }}
+ >
+ <QuestionMarkIcon class="size-3.5" />
+ </Button>
+ </div>
</Show>
<div class="ml-auto flex shrink-0 items-center gap-2">
<Button
@@ -313,6 +417,31 @@ function SectionDialog(props: SectionDialogProps & ManagedDialogProps) {
{submitLabel()}
</Button>
</div>
+ <Show when={sharingDisabledReason() || selectedScopeError()}>
+ {(reason) => (
+ <p class="w-full text-xs leading-5 text-warning">{reason()}</p>
+ )}
+ </Show>
+ <Show when={channels.isError}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() =>
+ fireAndForget(channels.refetch(), 'channels-view')
+ }
+ >
+ {t('channelSections.retry')}
+ </Button>
+ </Show>
+ <Show when={sharingHelpOpen()}>
+ <p
+ id={sharingHelpId}
+ class="w-full text-xs leading-5 text-ink-muted"
+ >
+ {t('channelSections.sharingHelp')}
+ </p>
+ </Show>
</div>
</form>
</Surface>
diff --git a/apps/web/src/features/channels-view/components/rail/next/build-channel-rail-rows.ts b/apps/web/src/features/channels-view/components/rail/next/build-channel-rail-rows.ts
index e07f8007b8..de290b703f 100644
--- a/apps/web/src/features/channels-view/components/rail/next/build-channel-rail-rows.ts
+++ b/apps/web/src/features/channels-view/components/rail/next/build-channel-rail-rows.ts
@@ -272,31 +272,29 @@ export function buildChannelRailRows(
});
}
- for (const group of ['team_channels', 'channels'] as const) {
- const channels = items[group];
-
- if (group === 'channels' && channels.length === 0) {
- continue;
- }
-
- rows.push({ kind: 'section', id: `section:${group}`, group });
-
- if (!expandedGroups[group]) {
- continue;
- }
+ rows.push({
+ kind: 'section',
+ id: 'section:team_channels',
+ group: 'team_channels',
+ });
- for (const channel of channels) {
+ if (expandedGroups.team_channels) {
+ for (const channel of items.team_channels) {
rows.push({
kind: 'conversation',
id: rowKeyForChannel(channel.id),
- group,
- scope: group,
+ group: 'team_channels',
+ scope: 'team_channels',
localIndex: 0,
channel,
});
}
- rows.push({ kind: 'status', id: `status:${group}`, group });
+ rows.push({
+ kind: 'status',
+ id: 'status:team_channels',
+ group: 'team_channels',
+ });
}
let previousLabelId: string | undefined;
@@ -371,22 +369,15 @@ export function groupChannelRailSections(rows: readonly ChannelRailRow[]) {
return sections;
}
-/** Keep saved sections in order and append new sections before All channels. */
+/** Keep saved sections in order and append new sections in source order. */
export function orderChannelRailSections(
rows: readonly ChannelRailRow[],
order: readonly ChannelSectionKey[]
): ChannelRailRow[] {
const sections = groupChannelRailSections(rows);
const keys = [...new Set(order)].filter((key) => sections.has(key));
- const missing = [...sections.keys()].filter(
- (key) => key !== 'channels' && !keys.includes(key)
- );
- const insertion = keys.at(-1) === 'channels' ? keys.length - 1 : keys.length;
- keys.splice(insertion, 0, ...missing);
-
- if (sections.has('channels') && !keys.includes('channels')) {
- keys.push('channels');
- }
+ const missing = [...sections.keys()].filter((key) => !keys.includes(key));
+ keys.push(...missing);
return keys.flatMap((key) => {
const section = sections.get(key);
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.ts
index 60bddc0c0b..1fa42ce39c 100644
--- 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.ts
@@ -4,6 +4,7 @@ import {
canAssignChannel,
canLabelChannel,
channelSectionDropError,
+ channelSectionScopeChangeError,
filterChannelLabelMembers,
} from './channel-label-eligibility';
@@ -49,6 +50,94 @@ describe('channel label eligibility', () => {
});
});
+describe('section scope change eligibility', () => {
+ const channels = new Map<
+ string,
+ Pick<ChannelEntity, 'channelType' | 'teamId' | 'isParticipant'>
+ >([
+ [
+ 'team-channel',
+ { channelType: 'team' as const, teamId: 'team', isParticipant: true },
+ ],
+ [
+ 'other-team',
+ { channelType: 'team' as const, teamId: 'other', isParticipant: true },
+ ],
+ ['private', { channelType: 'private' as const, isParticipant: true }],
+ [
+ 'left',
+ { channelType: 'team' as const, teamId: 'team', isParticipant: false },
+ ],
+ ]);
+
+ it('allows empty sections and complete eligible membership', () => {
+ expect(
+ channelSectionScopeChangeError(
+ { channelIds: [], channelCount: 0 },
+ channels,
+ { teamId: 'team' }
+ )
+ ).toBeUndefined();
+ expect(
+ channelSectionScopeChangeError(
+ { channelIds: ['team-channel'], channelCount: 1 },
+ channels,
+ { teamId: 'team' }
+ )
+ ).toBeUndefined();
+ expect(
+ channelSectionScopeChangeError(
+ { channelIds: ['team-channel'], channelCount: 1 },
+ channels,
+ {}
+ )
+ ).toBeUndefined();
+ });
+
+ it('rejects private channels and channels from another team without dropping members', () => {
+ expect(
+ channelSectionScopeChangeError(
+ { channelIds: ['team-channel', 'private'], channelCount: 2 },
+ channels,
+ { teamId: 'team' }
+ )
+ ).toBe('team-only');
+ expect(
+ channelSectionScopeChangeError(
+ { channelIds: ['other-team'], channelCount: 1 },
+ channels,
+ { teamId: 'team' }
+ )
+ ).toBe('team-only');
+ });
+
+ it('requires the complete membership and current participation for both scopes', () => {
+ for (const target of [{ teamId: 'team' }, {}]) {
+ expect(
+ channelSectionScopeChangeError(
+ { channelIds: ['team-channel'], channelCount: 2 },
+ channels,
+ target
+ )
+ ).toBe('unavailable');
+ expect(
+ channelSectionScopeChangeError(
+ { channelIds: ['missing'], channelCount: 1 },
+ channels,
+ target
+ )
+ ).toBe('unavailable');
+ expect(
+ channelSectionScopeChangeError(
+ { channelIds: ['left'], channelCount: 1 },
+ channels,
+ target
+ )
+ ).toBe('unavailable');
+ }
+ });
+});
+
describe('section drop eligibility', () => {
it('rejects automatic membership and channels outside shared scope', () => {
const channel = { id: 'channel', channelType: 'private' as const };
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.ts
index 3e92e52576..85939a3057 100644
--- a/apps/web/src/features/channels-view/core/channel-label-eligibility.ts
+++ b/apps/web/src/features/channels-view/core/channel-label-eligibility.ts
@@ -41,6 +41,31 @@ export function filterChannelLabelMembers(
});
}
+/** Scope changes keep every member; unavailable channels cannot be silently dropped. */
+export function channelSectionScopeChangeError(
+ label: Pick<ChannelLabel, 'channelIds' | 'channelCount'>,
+ channelsById: ReadonlyMap<
+ string,
+ Pick<ChannelEntity, 'channelType' | 'teamId' | 'isParticipant'>
+ >,
+ target: Pick<ChannelLabel, 'teamId'>
+): 'unavailable' | 'team-only' | undefined {
+ if (new Set(label.channelIds).size !== label.channelCount) {
+ return 'unavailable';
+ }
+
+ for (const id of label.channelIds) {
+ const channel = channelsById.get(id);
+ if (!channel || channel.isParticipant === false) {
+ return 'unavailable';
+ }
+
+ if (!canAssignChannel(channel, target)) {
+ return target.teamId ? 'team-only' : 'unavailable';
+ }
+ }
+}
+
/** Explain blocked section drops with the same membership rules as the picker. */
export function channelSectionDropError(options: {
section: ChannelSectionKey;
diff --git a/apps/web/src/lib/i18n/locales/en/channel-sections.ts b/apps/web/src/lib/i18n/locales/en/channel-sections.ts
index 546a953665..465e286b74 100644
--- a/apps/web/src/lib/i18n/locales/en/channel-sections.ts
+++ b/apps/web/src/lib/i18n/locales/en/channel-sections.ts
@@ -66,6 +66,18 @@ export default {
sharedShort: 'Shared',
personal: 'Personal',
shared: 'Shared with team',
+ sharingHelpLabel: 'About shared sections',
+ sharingHelp:
+ 'Team members can see and organize shared sections. Only team channels can be added.',
+ checkingSharing: 'Checking channel eligibility…',
+ sharingIneligibleChannels:
+ 'This section contains channels outside your team. Remove them before sharing.',
+ sharingUnavailableChannels:
+ 'All section channels must be available to you before changing sharing.',
+ makePersonalTitle: 'Make section personal?',
+ makePersonalBody:
+ '“{{name}}” will disappear from your teammates’ sidebars. Its channels will remain unchanged.',
+ makePersonal: 'Make personal',
sharedSectionHint: 'Shared with your team. Team channels only.',
cannotDropHere: 'This item cannot be added here.',
smartSectionDropHint: 'Smart sections add channels by name, not by dragging.',
@@ -112,10 +124,7 @@ export default {
loadingChannels: 'Loading channels…',
channelsUnavailable: 'Could not load channels.',
noChannelsToAdd: 'No more channels are available to add.',
- teamChannelsOnly:
- 'Shared sections only include channels from your team that you have joined. Private and public channels belong in personal sections.',
- personalChannelsHint:
- 'Personal sections can include team, public, and private channels you have joined.',
+ teamChannelsOnly: 'Team channels only',
addPersonalChannelsHint:
'Add any joined channel. Moves channels from other personal sections.',
addSharedChannelsHint:
diff --git a/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx b/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx
index 2d991e22e2..fecee31eff 100644
--- a/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx
+++ b/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx
@@ -17,6 +17,7 @@ import {
useAvailableSectionChannelsQuery,
useChannelLabelsData,
useChannelLabelsQuery,
+ useRenameChannelLabelMutation,
useSetChannelLabelMutation,
useSmartTagPreviewQuery,
} from './channel-labels';
@@ -28,6 +29,7 @@ const mocks = vi.hoisted(() => ({
list: vi.fn(),
preview: vi.fn(),
assign: vi.fn(),
+ rename: vi.fn(),
channels: vi.fn(),
}));
vi.mock('@app/lib/analytics/posthog', () => ({
@@ -42,6 +44,7 @@ vi.mock('@service-storage/client', () => ({
list: mocks.list,
preview: mocks.preview,
setChannelLabel: mocks.assign,
+ rename: mocks.rename,
},
},
}));
@@ -70,6 +73,7 @@ let client: QueryClient;
beforeEach(() => {
mocks.userId = () => 'viewer';
mocks.assign.mockReset().mockResolvedValue(ok(undefined));
+ mocks.rename.mockReset();
mocks.channels.mockReset().mockResolvedValue([]);
mocks.list.mockReset().mockResolvedValue(ok(labels));
mocks.preview
@@ -390,6 +394,102 @@ describe('channel tag query rollout', () => {
expect(data()).toEqual([]);
});
+ it('moves the same section between caches and reconciles destination assignments', async () => {
+ const section = labels.labels[0];
+ const moved = { ...section, name: 'Moved', teamId: 'team' };
+ const personalKey = channelLabelKeys.list('personal', 'viewer').queryKey;
+ const teamKey = channelLabelKeys.list(undefined, 'viewer').queryKey;
+ client.setQueryData(personalKey, labels);
+ client.setQueryData<ChannelLabelsList>(teamKey, {
+ scope: 'team',
+ teamId: 'team',
+ labels: [
+ {
+ ...section,
+ id: 'existing',
+ channelIds: ['channel-1', 'channel-2'],
+ channelCount: 2,
+ },
+ ],
+ });
+ mocks.rename.mockResolvedValue(ok(moved));
+ let rename!: ReturnType<typeof useRenameChannelLabelMutation>;
+ const Probe = () => {
+ rename = useRenameChannelLabelMutation('personal');
+ return null;
+ };
+ render(() => (
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ ));
+
+ await rename.mutateAsync({
+ actorId: 'viewer',
+ labelId: section.id,
+ name: 'Moved',
+ targetScope: 'team',
+ });
+
+ expect(mocks.rename).toHaveBeenCalledWith(
+ section.id,
+ { name: 'Moved', rule: undefined, targetScope: 'team' },
+ 'personal'
+ );
+ expect(client.getQueryData<ChannelLabelsList>(personalKey)?.labels).toEqual(
+ []
+ );
+ expect(client.getQueryData<ChannelLabelsList>(teamKey)?.labels).toEqual([
+ {
+ ...section,
+ id: 'existing',
+ channelIds: ['channel-2'],
+ channelCount: 1,
+ },
+ moved,
+ ]);
+ });
+
+ it('does not publish a scope change after the acting account changes', async () => {
+ const [userId, setUserId] = createSignal('viewer');
+ mocks.userId = userId;
+ const section = labels.labels[0];
+ const personalKey = channelLabelKeys.list('personal', 'viewer').queryKey;
+ const teamKey = channelLabelKeys.list(undefined, 'viewer').queryKey;
+ client.setQueryData(personalKey, labels);
+ client.setQueryData(teamKey, { scope: 'team', teamId: 'team', labels: [] });
+ let finish!: (result: Ok<typeof section, never>) => void;
+ mocks.rename.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ let rename!: ReturnType<typeof useRenameChannelLabelMutation>;
+ const Probe = () => {
+ rename = useRenameChannelLabelMutation('personal');
+ return null;
+ };
+ render(() => (
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ ));
+ const request = rename.mutateAsync({
+ actorId: 'viewer',
+ labelId: section.id,
+ name: section.name,
+ targetScope: 'team',
+ });
+ await waitFor(() => expect(mocks.rename).toHaveBeenCalledTimes(1));
+ setUserId('another-viewer');
+ finish(ok({ ...section, teamId: 'team' }));
+ await request;
+
+ expect(client.getQueryData<ChannelLabelsList>(personalKey)).toEqual(labels);
+ expect(client.getQueryData<ChannelLabelsList>(teamKey)?.labels).toEqual([]);
+ });
+
it('rejects queued assignments after an account change', async () => {
const [userId, setUserId] = createSignal('viewer');
mocks.userId = userId;
diff --git a/apps/web/src/lib/queries/channel-labels/channel-labels.ts b/apps/web/src/lib/queries/channel-labels/channel-labels.ts
index 88084082d5..1d8a4db2e7 100644
--- a/apps/web/src/lib/queries/channel-labels/channel-labels.ts
+++ b/apps/web/src/lib/queries/channel-labels/channel-labels.ts
@@ -137,20 +137,27 @@ export function useSmartTagPreviewQuery(
});
}
-function availableSectionChannelsQueryOptions(actorId: string | undefined) {
+function availableSectionChannelsQueryOptions(
+ actorId: string | undefined,
+ enabled: boolean
+) {
return queryOptions({
queryKey: channelKeys.listChannels._ctx.account(actorId).queryKey,
queryFn: ({ signal }) => fetchAllChannels(signal),
- enabled: Boolean(actorId),
+ enabled: enabled && Boolean(actorId),
reconcile: 'id',
staleTime: 0,
});
}
/** Full authorized channel membership, scoped to the current account. */
-export function useAvailableSectionChannelsQuery() {
+export function useAvailableSectionChannelsQuery(
+ enabled: Accessor<boolean> = () => true
+) {
const userId = useUserId();
- return useQuery(() => availableSectionChannelsQueryOptions(userId()));
+ return useQuery(() =>
+ availableSectionChannelsQueryOptions(userId(), enabled())
+ );
}
export type CreateChannelLabelArgs = {
@@ -216,6 +223,7 @@ export type RenameChannelLabelArgs = {
labelId: string;
name: string;
rule?: ChannelLabelRule;
+ targetScope?: ChannelLabelScopeSelection;
};
export function useRenameChannelLabelMutation(
scope?: ChannelLabelScopeSelection
@@ -232,6 +240,7 @@ export function useRenameChannelLabelMutation(
{
name: args.name,
rule: args.rule,
+ targetScope: args.targetScope,
},
scope
)
@@ -242,13 +251,51 @@ export function useRenameChannelLabelMutation(
if (args.actorId !== userId()) return;
await cancelLabelFetch(scope, args.actorId);
if (args.actorId !== userId()) return;
+ const destinationScope =
+ args.targetScope === 'team' ? undefined : args.targetScope;
+ const changesScope =
+ args.targetScope && args.targetScope !== (scope ?? 'team');
+ if (!changesScope) {
+ writeLabels(scope, args.actorId, (labels) =>
+ labels.map((label) => (label.id === renamed.id ? renamed : label))
+ );
+ return;
+ }
+
+ await cancelLabelFetch(destinationScope, args.actorId);
+ if (args.actorId !== userId()) return;
+
writeLabels(scope, args.actorId, (labels) =>
- labels.map((label) => (label.id === renamed.id ? renamed : label))
+ labels.filter((label) => label.id !== renamed.id)
+ );
+ writeLabels(destinationScope, args.actorId, (labels) =>
+ labels
+ .filter((label) => label.id !== renamed.id)
+ .map((label) => {
+ if (renamed.rule || label.rule) return label;
+ const channelIds = label.channelIds.filter(
+ (id) => !renamed.channelIds.includes(id)
+ );
+ return {
+ ...label,
+ channelIds,
+ channelCount:
+ label.channelCount -
+ (label.channelIds.length - channelIds.length),
+ };
+ })
+ .concat(renamed)
);
},
onSettled: (_data, _error, args) => {
- if (args.actorId === userId())
- return invalidateChannelLabels(scope, args.actorId);
+ if (args.actorId !== userId()) return;
+ const refresh = [invalidateChannelLabels(scope, args.actorId)];
+ if (args.targetScope && args.targetScope !== (scope ?? 'team')) {
+ const destinationScope =
+ args.targetScope === 'team' ? undefined : args.targetScope;
+ refresh.push(invalidateChannelLabels(destinationScope, args.actorId));
+ }
+ return Promise.all(refresh);
},
}),
}));
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabel.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabel.ts
index 2430911458..b13b9057ef 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabel.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabel.ts
@@ -30,6 +30,6 @@ export interface ChannelLabel {
sortOrder: number;
/** Owning team, or `None` for account-private labels. */
teamId?: ChannelLabelTeamId;
- /** When the label was last renamed or reordered. */
+ /** When the label's name, rule, scope, or order last changed. */
updatedAt: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 75f7691f89..da4a9e1c92 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -1701,6 +1701,7 @@ export * from './removeParticipantsRequest';
export * from './renameChannelLabelParams';
export * from './renameChannelLabelRequest';
export * from './renameChannelLabelRequestRule';
+export * from './renameChannelLabelRequestTargetScope';
export * from './renamePipeline';
export * from './reorderFavoritesRequest';
export * from './reorderPinRequest';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequest.ts
index 116ed60f07..9bf22daec1 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequest.ts
@@ -5,12 +5,14 @@
* OpenAPI spec version: 0.1.0
*/
import type { RenameChannelLabelRequestRule } from './renameChannelLabelRequestRule';
+import type { RenameChannelLabelRequestTargetScope } from './renameChannelLabelRequestTargetScope';
/**
- * Request body for renaming a label.
+ * Request body for updating a label's name, smart rule, or sharing scope.
*/
export interface RenameChannelLabelRequest {
/** New display name. */
name: string;
rule?: RenameChannelLabelRequestRule;
+ targetScope?: RenameChannelLabelRequestTargetScope;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequestTargetScope.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequestTargetScope.ts
new file mode 100644
index 0000000000..66e1ab1a43
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequestTargetScope.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelLabelScopeSelection } from './channelLabelScopeSelection';
+
+export type RenameChannelLabelRequestTargetScope =
+ null | ChannelLabelScopeSelection;
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 e4c4fcdd20..3670e3c79c 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
@@ -3151,7 +3151,9 @@ export const listChannelLabelsResponse = zod
.describe('Owning team, or `None` for account-private labels.'),
updatedAt: zod.iso
.datetime({})
- .describe('When the label was last renamed or reordered.'),
+ .describe(
+ "When the label's name, rule, scope, or order last changed."
+ ),
})
.describe(
'A shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.'
@@ -3258,7 +3260,7 @@ export const createChannelLabelResponse = zod
.describe('Owning team, or `None` for account-private labels.'),
updatedAt: zod.iso
.datetime({})
- .describe('When the label was last renamed or reordered.'),
+ .describe("When the label's name, rule, scope, or order last changed."),
})
.describe(
'A shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.'
@@ -3354,7 +3356,7 @@ export const deleteChannelLabelQueryParams = zod.object({
});
/**
- * @summary Rename a label of the caller's authorized scope.
+ * @summary Update a label, optionally moving it to another authorized scope.
*/
export const renameChannelLabelParams = zod.object({
label_id: zod.uuid().describe('The label id.'),
@@ -3390,8 +3392,20 @@ export const renameChannelLabelBody = zod
),
])
.optional(),
+ targetScope: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['personal', 'team'])
+ .describe(
+ 'Requested label namespace. Omission retains the deployed automatic selection.'
+ ),
+ ])
+ .optional(),
})
- .describe('Request body for renaming a label.');
+ .describe(
+ "Request body for updating a label's name, smart rule, or sharing scope."
+ );
export const renameChannelLabelResponse = zod
.object({
@@ -3437,7 +3451,7 @@ export const renameChannelLabelResponse = zod
.describe('Owning team, or `None` for account-private labels.'),
updatedAt: zod.iso
.datetime({})
- .describe('When the label was last renamed or reordered.'),
+ .describe("When the label's name, rule, scope, or order last changed."),
})
.describe(
'A shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.'
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 f358bb5b48..8e4e1b83d0 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -3419,7 +3419,7 @@
},
"patch": {
"tags": ["channel_labels"],
- "summary": "Rename a label of the caller's authorized scope.",
+ "summary": "Update a label, optionally moving it to another authorized scope.",
"operationId": "rename_channel_label",
"parameters": [
{
@@ -24357,7 +24357,7 @@
"updatedAt": {
"type": "string",
"format": "date-time",
- "description": "When the label was last renamed or reordered."
+ "description": "When the label's name, rule, scope, or order last changed."
}
}
},
@@ -39465,7 +39465,7 @@
},
"RenameChannelLabelRequest": {
"type": "object",
- "description": "Request body for renaming a label.",
+ "description": "Request body for updating a label's name, smart rule, or sharing scope.",
"required": ["name"],
"properties": {
"name": {
@@ -39482,6 +39482,17 @@
"description": "Automatic name-matching rule; omitted for manual labels or a name-only rename."
}
]
+ },
+ "targetScope": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection",
+ "description": "Destination namespace; omitted to preserve the current scope."
+ }
+ ]
}
}
},
diff --git a/crates/channel_labels/AGENTS.md b/crates/channel_labels/AGENTS.md
index 1be0803b8e..55e1167142 100644
--- a/crates/channel_labels/AGENTS.md
+++ b/crates/channel_labels/AGENTS.md
@@ -31,7 +31,8 @@ Chat sidebar, following the standard hexagonal crate layout.
## Checks
-- `cargo test -p channel_labels` (`SQLX_OFFLINE` unset).
+- `cargo test -p channel_labels --features postgres` (`SQLX_OFFLINE` unset).
+- `SQLX_OFFLINE=true cargo check -p channel_labels --all-features`.
## Gotchas
@@ -41,6 +42,12 @@ Chat sidebar, following the standard hexagonal crate layout.
per-user.
- Team labels remain restricted to channels in the same team; personal labels require active channel membership.
+- PATCH `{label_id}` accepts optional `targetScope: "personal" | "team"` with
+ the existing `name` and optional `rule`; omission keeps rename behavior.
+ Transferring a section preserves its ID and contents, but rejects any member
+ the actor cannot access or the destination cannot label. Conflicting manual
+ destination assignments move to the transferred section atomically.
+
## Related
- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/channel_labels/src/domain/models.rs b/crates/channel_labels/src/domain/models.rs
index 59b5a25d8f..8b2f3762fa 100644
--- a/crates/channel_labels/src/domain/models.rs
+++ b/crates/channel_labels/src/domain/models.rs
@@ -83,7 +83,7 @@ pub struct ChannelLabel {
pub channel_count: i64,
/// When the label was created.
pub created_at: DateTime<Utc>,
- /// When the label was last renamed or reordered.
+ /// When the label's name, rule, scope, or order last changed.
pub updated_at: DateTime<Utc>,
}
diff --git a/crates/channel_labels/src/domain/ports.rs b/crates/channel_labels/src/domain/ports.rs
index c287d93fa6..040f18f133 100644
--- a/crates/channel_labels/src/domain/ports.rs
+++ b/crates/channel_labels/src/domain/ports.rs
@@ -59,6 +59,19 @@ pub trait ChannelLabelsRepo: Send + Sync + 'static {
rule: Option<&ChannelLabelRule>,
) -> impl Future<Output = Result<LabelWriteOutcome, Self::Err>> + Send;
+ /// Atomically rename and transfer a label to another authorized namespace.
+ /// Validate every source assignment, or every current personal smart match,
+ /// against the target before moving any assignment or changing the label.
+ fn transfer_label(
+ &self,
+ source: &ChannelLabelsScope,
+ target: &ChannelLabelsScope,
+ label_id: Uuid,
+ name: &str,
+ viewer: &MacroUserIdStr<'_>,
+ rule: Option<&ChannelLabelRule>,
+ ) -> impl Future<Output = Result<LabelWriteOutcome, Self::Err>> + Send;
+
/// Delete a label of the scope; its channels become unlabelled.
///
/// Returns `true` when a row was removed.
@@ -121,6 +134,16 @@ pub trait ChannelLabelsService: Send + Sync + 'static {
rule: Option<ChannelLabelRule>,
) -> impl Future<Output = Result<ChannelLabel, ChannelLabelsError>> + Send;
+ /// Update a label and optionally transfer it to another authorized namespace.
+ fn update_label(
+ &self,
+ source: &ChannelLabelsReceipt,
+ target: Option<&ChannelLabelsReceipt>,
+ label_id: Uuid,
+ name: String,
+ rule: Option<ChannelLabelRule>,
+ ) -> impl Future<Output = Result<ChannelLabel, ChannelLabelsError>> + Send;
+
/// Delete a label of the caller's authorized scope; its channels return to the plain list.
fn delete_label(
&self,
diff --git a/crates/channel_labels/src/domain/service.rs b/crates/channel_labels/src/domain/service.rs
index b9290e1580..cf95e5d336 100644
--- a/crates/channel_labels/src/domain/service.rs
+++ b/crates/channel_labels/src/domain/service.rs
@@ -193,6 +193,63 @@ where
)
}
+ #[tracing::instrument(
+ skip_all,
+ err,
+ fields(
+ label.id = %label_id,
+ source.scope = ?source.scope().selection(),
+ target.scope = ?target.map(|receipt| receipt.scope().selection()),
+ ),
+ )]
+ async fn update_label(
+ &self,
+ source: &ChannelLabelsReceipt,
+ target: Option<&ChannelLabelsReceipt>,
+ label_id: Uuid,
+ name: String,
+ rule: Option<ChannelLabelRule>,
+ ) -> Result<ChannelLabel, ChannelLabelsError> {
+ let Some(target) = target else {
+ return self.rename_label(source, label_id, name, rule).await;
+ };
+ if source.user_id() != target.user_id() {
+ return Err(ChannelLabelsError::Unauthorized);
+ }
+ if source.scope() == target.scope() {
+ return self.rename_label(source, label_id, name, rule).await;
+ }
+ let name = validate_name(&name)?;
+ let rule = rule.map(validate_rule).transpose()?;
+ if rule.is_some() {
+ let existing = self
+ .repo
+ .get_label(source.scope(), label_id, source.user_id())
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or(ChannelLabelsError::NotFound("label not found"))?;
+ if existing.rule.is_none() {
+ return Err(ChannelLabelsError::BadRequest(
+ "only smart tags have editable rules".into(),
+ ));
+ }
+ }
+ written(
+ self.repo
+ .transfer_label(
+ source.scope(),
+ target.scope(),
+ label_id,
+ &name,
+ source.user_id(),
+ rule.as_ref(),
+ )
+ .await
+ .map_err(anyhow::Error::from)?,
+ &name,
+ )
+ }
+
#[tracing::instrument(skip_all, err)]
async fn delete_label(
&self,
diff --git a/crates/channel_labels/src/domain/service/test.rs b/crates/channel_labels/src/domain/service/test.rs
index 3b4258f0a6..5c0d7d77c1 100644
--- a/crates/channel_labels/src/domain/service/test.rs
+++ b/crates/channel_labels/src/domain/service/test.rs
@@ -25,6 +25,11 @@ enum RepoCall {
label_id: Uuid,
name: String,
},
+ Transfer {
+ source: ChannelLabelsScope,
+ target: ChannelLabelsScope,
+ label_id: Uuid,
+ },
Delete {
label_id: Uuid,
},
@@ -146,6 +151,28 @@ impl ChannelLabelsRepo for FakeRepo {
}))
}
+ async fn transfer_label(
+ &self,
+ source: &ChannelLabelsScope,
+ target: &ChannelLabelsScope,
+ label_id: Uuid,
+ name: &str,
+ _viewer: &MacroUserIdStr<'_>,
+ _rule: Option<&ChannelLabelRule>,
+ ) -> Result<LabelWriteOutcome, Self::Err> {
+ self.record(RepoCall::Transfer {
+ source: source.clone(),
+ target: target.clone(),
+ label_id,
+ });
+ Ok(self.rename_outcome.clone().unwrap_or_else(|| {
+ let mut result = label(target.team_id().unwrap_or_default(), name);
+ result.id = label_id;
+ result.team_id = target.team_id();
+ LabelWriteOutcome::Written(result)
+ }))
+ }
+
async fn delete_label(
&self,
_scope: &ChannelLabelsScope,
@@ -588,3 +615,40 @@ fn explicit_scope_requires_verified_team_membership() {
.unwrap();
assert!(matches!(personal.scope(), ChannelLabelsScope::User(id) if id == &actor));
}
+
+#[tokio::test]
+async fn scope_transfer_uses_one_atomic_repo_call_and_checks_actor() {
+ let (team_id, source) = receipt();
+ let actor = MacroUserIdStr::try_from(USER_ID.to_owned()).unwrap();
+ let target = ChannelLabelsReceipt::from_access(actor, None, None).unwrap();
+ let label_id = Uuid::now_v7();
+ let repo = FakeRepo::default();
+ let service = ChannelLabelsServiceImpl::new(repo.clone());
+ let moved = service
+ .update_label(&source, Some(&target), label_id, " Private ".into(), None)
+ .await
+ .unwrap();
+ assert_eq!(moved.id, label_id);
+ assert_eq!(moved.team_id, None);
+ assert_eq!(
+ repo.calls(),
+ vec![RepoCall::Transfer {
+ source: ChannelLabelsScope::Team(team_id),
+ target: target.scope().clone(),
+ label_id,
+ }]
+ );
+ let other = ChannelLabelsReceipt::from_access(
+ MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap(),
+ None,
+ None,
+ )
+ .unwrap();
+ assert!(matches!(
+ service
+ .update_label(&source, Some(&other), label_id, "Private".into(), None)
+ .await,
+ Err(ChannelLabelsError::Unauthorized)
+ ));
+ assert_eq!(repo.calls().len(), 1);
+}
diff --git a/crates/channel_labels/src/inbound/axum_router.rs b/crates/channel_labels/src/inbound/axum_router.rs
index d0fdbdff34..40a58f3f58 100644
--- a/crates/channel_labels/src/inbound/axum_router.rs
+++ b/crates/channel_labels/src/inbound/axum_router.rs
@@ -86,7 +86,7 @@ impl<S, Eas, Auth> FromRef<ChannelLabelsRouterState<S, Eas, Auth>>
/// Routes:
/// - `GET /` — list the caller's shared or private labels.
/// - `POST /` — create a label, optionally moving channels into it.
-/// - `PATCH /{label_id}` — rename a label.
+/// - `PATCH /{label_id}` — rename or transfer a label.
/// - `DELETE /{label_id}` — delete a label.
/// - `PUT /channels/{channel_id}` — move a channel into or out of a label.
pub fn channel_labels_router<S, Eas, Auth, T>(
@@ -139,7 +139,7 @@ pub struct CreateChannelLabelRequest {
pub channel_ids: Vec<Uuid>,
}
-/// Request body for renaming a label.
+/// Request body for updating a label's name, smart rule, or sharing scope.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct RenameChannelLabelRequest {
@@ -148,6 +148,9 @@ pub struct RenameChannelLabelRequest {
/// Automatic name-matching rule; omitted for manual labels or a name-only rename.
#[serde(default)]
pub rule: Option<ChannelLabelRule>,
+ /// Destination namespace; omitted to preserve the current scope.
+ #[serde(default)]
+ pub target_scope: Option<ChannelLabelScopeSelection>,
}
/// Request body for moving a channel between labels.
@@ -264,7 +267,7 @@ where
Ok(Json(label))
}
-/// Rename a label of the caller's authorized scope.
+/// Update a label, optionally moving it to another authorized scope.
#[utoipa::path(
patch,
tag = "channel_labels",
@@ -296,14 +299,28 @@ where
Eas: EntityAccessService,
Auth: MacroAuthorizationService,
{
- let receipt = ChannelLabelsReceipt::from_access(
- user.authorization.macro_user_id,
- access.entity_access_receipt,
- scope.scope,
- )?;
+ let actor = user.authorization.macro_user_id;
+ let target = req
+ .target_scope
+ .map(|selection| {
+ ChannelLabelsReceipt::from_access(
+ actor.clone(),
+ access.entity_access_receipt.clone(),
+ Some(selection),
+ )
+ })
+ .transpose()?;
+ let receipt =
+ ChannelLabelsReceipt::from_access(actor, access.entity_access_receipt, scope.scope)?;
let label = state
.service
- .rename_label(&receipt, params.label_id, req.name, req.rule)
+ .update_label(
+ &receipt,
+ target.as_ref(),
+ params.label_id,
+ req.name,
+ req.rule,
+ )
.await?;
Ok(Json(label))
}
diff --git a/crates/channel_labels/src/lib.rs b/crates/channel_labels/src/lib.rs
index 334cff7586..85808c2f81 100644
--- a/crates/channel_labels/src/lib.rs
+++ b/crates/channel_labels/src/lib.rs
@@ -9,6 +9,8 @@
//! the channels inside a label that they participate in. Empty labels stay
//! visible. Personal labels accept joined team, public, and private channels,
//! but never direct messages.
+//! Scope transfers keep the label and its eligible contents together; shared
+//! sections transferred to personal scope leave the team sidebar.
//! Smart tags match current channel attributes automatically. Their memberships
//! may overlap other tags and manual labels, and only include visible channels.
//!
diff --git a/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs b/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs
index 1840d1508b..6b5bc79535 100644
--- a/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs
+++ b/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs
@@ -177,6 +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?;
+ lock_scope(&mut tx, &scope_key).await?;
let validity = validate_channels(&mut tx, channel_ids, viewer, Some(scope)).await?;
if validity != SetChannelLabelOutcome::Updated {
return Ok(LabelWriteOutcome::InvalidChannel(validity));
@@ -230,6 +231,8 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
) -> Result<LabelWriteOutcome, Self::Err> {
let scope_key = scope.key();
let name_contains = rule.map(ChannelLabelRule::name_contains);
+ let mut tx = self.pool.begin().await?;
+ lock_scope(&mut tx, &scope_key).await?;
let result = sqlx::query!(
r#"
UPDATE channel_label
@@ -241,7 +244,7 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
name,
name_contains,
)
- .execute(&self.pool)
+ .execute(&mut *tx)
.await;
match result {
Ok(done) if done.rows_affected() == 0 => return Ok(LabelWriteOutcome::NotFound),
@@ -251,12 +254,127 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
}
Err(error) => return Err(error.into()),
}
+ tx.commit().await?;
match self.get_label(scope, label_id, viewer).await? {
Some(label) => Ok(LabelWriteOutcome::Written(label)),
None => Ok(LabelWriteOutcome::NotFound),
}
}
+ #[tracing::instrument(skip_all, err)]
+ async fn transfer_label(
+ &self,
+ source: &ChannelLabelsScope,
+ target: &ChannelLabelsScope,
+ label_id: Uuid,
+ name: &str,
+ viewer: &MacroUserIdStr<'_>,
+ rule: Option<&ChannelLabelRule>,
+ ) -> Result<LabelWriteOutcome, Self::Err> {
+ let source_key = source.key();
+ let target_key = target.key();
+ let mut tx = self.pool.begin().await?;
+ // Lock both namespaces in a stable order, including concurrent creates
+ // and assignment writes, before inspecting the source's full contents.
+ let mut keys = [&source_key, &target_key];
+ keys.sort();
+ for key in keys {
+ lock_scope(&mut tx, key).await?;
+ }
+ let existing = sqlx::query!(
+ "SELECT name_contains FROM channel_label WHERE scope_key = $1 AND id = $2 FOR UPDATE",
+ source_key,
+ label_id,
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+ let Some(existing) = existing else {
+ return Ok(LabelWriteOutcome::NotFound);
+ };
+ let channel_ids: Vec<Uuid> = if let Some(pattern) = rule
+ .map(ChannelLabelRule::name_contains)
+ .or(existing.name_contains.as_deref())
+ {
+ // Smart tags have no stored assignments. Inspect all current personal
+ // matches, not a bounded preview or a viewer-relative response.
+ sqlx::query_scalar!(
+ r#"SELECT c.id FROM comms_channels c
+ JOIN comms_channel_participants p ON p.channel_id = c.id
+ WHERE p.user_id = $1 AND p.left_at IS NULL
+ AND (($3::uuid IS NULL AND c.channel_type IN ('team', 'public', 'private'))
+ OR (c.channel_type = 'team' AND c.team_id = $3))
+ AND strpos(lower(c.name), lower($2)) > 0
+ ORDER BY c.id FOR SHARE OF c, p"#,
+ viewer.as_ref(),
+ pattern,
+ source.team_id(),
+ )
+ .fetch_all(&mut *tx)
+ .await?
+ } else {
+ sqlx::query_scalar!(
+ "SELECT channel_id FROM channel_label_channel WHERE scope_key = $1 AND label_id = $2 ORDER BY channel_id FOR UPDATE",
+ source_key,
+ label_id,
+ )
+ .fetch_all(&mut *tx)
+ .await?
+ };
+ let validity = validate_channels(&mut tx, &channel_ids, viewer, Some(target)).await?;
+ if validity != SetChannelLabelOutcome::Updated {
+ return Ok(LabelWriteOutcome::InvalidChannel(validity));
+ }
+ // The composite foreign key is immediate. Remove the old assignment
+ // keys before changing the label's generated scope key, then upsert all
+ // destination assignments in the same transaction.
+ sqlx::query!(
+ "DELETE FROM channel_label_channel WHERE scope_key = $1 AND label_id = $2",
+ source_key,
+ label_id,
+ )
+ .execute(&mut *tx)
+ .await?;
+ let updated = sqlx::query!(
+ r#"UPDATE channel_label
+ SET team_id = $3, user_id = $4, name = $5,
+ name_contains = COALESCE($6, name_contains),
+ sort_order = COALESCE((SELECT MAX(sort_order) + 1 FROM channel_label WHERE scope_key = $7), 0),
+ updated_at = now()
+ WHERE scope_key = $1 AND id = $2"#,
+ source_key,
+ label_id,
+ target.team_id(),
+ target.owner_id(),
+ name,
+ rule.map(ChannelLabelRule::name_contains),
+ target_key,
+ )
+ .execute(&mut *tx)
+ .await;
+ match updated {
+ Ok(_) => {}
+ Err(error) if is_unique_violation(&error) => return Ok(LabelWriteOutcome::NameTaken),
+ Err(error) => return Err(error.into()),
+ }
+ if existing.name_contains.is_none() {
+ 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
+ ON CONFLICT (scope_key, channel_id) DO UPDATE SET label_id = EXCLUDED.label_id"#,
+ target_key,
+ label_id,
+ &channel_ids,
+ )
+ .execute(&mut *tx)
+ .await?;
+ }
+ tx.commit().await?;
+ match self.get_label(target, label_id, viewer).await? {
+ Some(label) => Ok(LabelWriteOutcome::Written(label)),
+ None => Ok(LabelWriteOutcome::NotFound),
+ }
+ }
+
#[tracing::instrument(skip_all, err)]
async fn delete_label(
&self,
@@ -264,14 +382,17 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
label_id: Uuid,
) -> Result<bool, Self::Err> {
let scope_key = scope.key();
+ let mut tx = self.pool.begin().await?;
+ lock_scope(&mut tx, &scope_key).await?;
// Assignments cascade; channels and other scopes are unaffected.
let done = sqlx::query!(
r#"DELETE FROM channel_label WHERE id = $2 AND scope_key = $1"#,
scope_key,
label_id,
)
- .execute(&self.pool)
+ .execute(&mut *tx)
.await?;
+ tx.commit().await?;
Ok(done.rows_affected() > 0)
}
@@ -285,6 +406,7 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
) -> Result<SetChannelLabelOutcome, Self::Err> {
let scope_key = scope.key();
let mut tx = self.pool.begin().await?;
+ lock_scope(&mut tx, &scope_key).await?;
if let Some(label_id) = label_id {
let label = sqlx::query!(
"SELECT id, name_contains FROM channel_label WHERE id = $2 AND scope_key = $1 FOR KEY SHARE",
@@ -402,3 +524,17 @@ async fn validate_channels(
}
Ok(SetChannelLabelOutcome::Updated)
}
+
+/// Serialize writes in a namespace before acquiring label and assignment locks.
+async fn lock_scope(
+ tx: &mut Transaction<'_, Postgres>,
+ scope_key: &str,
+) -> Result<(), ChannelLabelsRepoErr> {
+ sqlx::query!(
+ "SELECT pg_advisory_xact_lock(hashtextextended('channel-labels:' || $1, 0))",
+ scope_key,
+ )
+ .execute(&mut **tx)
+ .await?;
+ Ok(())
+}
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.rs
index a4a7f2f307..bf12ac954e 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
@@ -727,3 +727,212 @@ async fn smart_preview_is_bounded_literal_and_respects_membership(pool: PgPool)
assert_eq!(empty.total_count, 0);
assert!(empty.channels.is_empty());
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn transfer_preserves_identity_and_moves_conflicting_destination_assignments(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ insert_user(&pool, USER_B).await;
+ let team_id = insert_team(&pool, USER_A).await;
+ let team = ChannelLabelsScope::Team(team_id);
+ let personal = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_A.to_owned()).unwrap());
+ let shared = insert_team_channel(&pool, "Shared", team_id, USER_A, &[USER_A, USER_B]).await;
+ let hidden = insert_team_channel(&pool, "Hidden", team_id, USER_B, &[USER_B]).await;
+ let repo = PgChannelLabelsRepo::new(pool.clone());
+ let original = written(
+ repo.create_label(&personal, "Mine", &[shared], &user(USER_A), None)
+ .await
+ .unwrap(),
+ );
+ let conflict = written(
+ repo.create_label(&team, "Existing", &[shared], &user(USER_A), None)
+ .await
+ .unwrap(),
+ );
+ let moved = written(
+ repo.transfer_label(&personal, &team, original.id, "Moved", &user(USER_A), None)
+ .await
+ .unwrap(),
+ );
+ assert_eq!(moved.id, original.id);
+ assert_eq!(moved.team_id, Some(team_id));
+ assert_eq!(moved.channel_ids, vec![shared]);
+ assert!(
+ repo.get_label(&personal, original.id, &user(USER_A))
+ .await
+ .unwrap()
+ .is_none()
+ );
+ assert!(
+ repo.get_label(&team, conflict.id, &user(USER_A))
+ .await
+ .unwrap()
+ .unwrap()
+ .channel_ids
+ .is_empty()
+ );
+ repo.set_channel_label(&team, hidden, Some(original.id), &user(USER_B))
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.transfer_label(&team, &personal, original.id, "Back", &user(USER_A), None)
+ .await
+ .unwrap(),
+ LabelWriteOutcome::InvalidChannel(SetChannelLabelOutcome::ChannelNotFound)
+ );
+ assert_eq!(
+ repo.get_label(&team, original.id, &user(USER_B))
+ .await
+ .unwrap()
+ .unwrap()
+ .channel_count,
+ 2
+ );
+ repo.set_channel_label(&team, hidden, None, &user(USER_B))
+ .await
+ .unwrap();
+ let returned = written(
+ repo.transfer_label(&team, &personal, original.id, "Back", &user(USER_A), None)
+ .await
+ .unwrap(),
+ );
+ assert_eq!(returned.id, original.id);
+ assert_eq!(returned.team_id, None);
+ assert_eq!(returned.channel_ids, vec![shared]);
+ assert!(
+ repo.get_label(&team, original.id, &user(USER_B))
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn transfer_rejects_hidden_and_ineligible_members_and_name_collisions(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ insert_user(&pool, USER_B).await;
+ let team_id = insert_team(&pool, USER_A).await;
+ let team = ChannelLabelsScope::Team(team_id);
+ let personal = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_A.to_owned()).unwrap());
+ let shared = insert_team_channel(&pool, "Shared", team_id, USER_A, &[USER_A]).await;
+ let other_team = insert_team(&pool, USER_B).await;
+ let ineligible = insert_team_channel(&pool, "Other", other_team, USER_A, &[USER_A]).await;
+ let repo = PgChannelLabelsRepo::new(pool.clone());
+ let original = written(
+ repo.create_label(&personal, "Original", &[shared], &user(USER_A), None)
+ .await
+ .unwrap(),
+ );
+ written(
+ repo.create_label(&team, "Taken", &[], &user(USER_A), None)
+ .await
+ .unwrap(),
+ );
+ assert_eq!(
+ repo.transfer_label(&personal, &team, original.id, "Taken", &user(USER_A), None)
+ .await
+ .unwrap(),
+ LabelWriteOutcome::NameTaken
+ );
+ assert_eq!(
+ repo.get_label(&personal, original.id, &user(USER_A))
+ .await
+ .unwrap()
+ .unwrap()
+ .channel_ids,
+ vec![shared]
+ );
+ repo.set_channel_label(&personal, ineligible, Some(original.id), &user(USER_A))
+ .await
+ .unwrap();
+ assert_eq!(
+ repo.transfer_label(&personal, &team, original.id, "New", &user(USER_A), None)
+ .await
+ .unwrap(),
+ LabelWriteOutcome::InvalidChannel(SetChannelLabelOutcome::ChannelNotLabelable)
+ );
+ assert_eq!(
+ repo.get_label(&personal, original.id, &user(USER_A))
+ .await
+ .unwrap()
+ .unwrap()
+ .channel_count,
+ 2
+ );
+ let hidden = insert_team_channel(&pool, "Hidden", team_id, USER_B, &[USER_B]).await;
+ let team_label = written(
+ repo.create_label(&team, "Hidden label", &[hidden], &user(USER_B), None)
+ .await
+ .unwrap(),
+ );
+ assert_eq!(
+ repo.transfer_label(
+ &team,
+ &personal,
+ team_label.id,
+ "Hidden moved",
+ &user(USER_A),
+ None
+ )
+ .await
+ .unwrap(),
+ LabelWriteOutcome::InvalidChannel(SetChannelLabelOutcome::ChannelNotFound)
+ );
+ assert_eq!(
+ repo.get_label(&team, team_label.id, &user(USER_B))
+ .await
+ .unwrap()
+ .unwrap()
+ .channel_ids,
+ vec![hidden]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn sharing_smart_tag_rejects_personal_matches_outside_team(pool: PgPool) {
+ use crate::domain::models::ChannelLabelRule;
+ insert_user(&pool, USER_A).await;
+ insert_user(&pool, USER_B).await;
+ let team_id = insert_team(&pool, USER_A).await;
+ let team = ChannelLabelsScope::Team(team_id);
+ let personal = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_A.to_owned()).unwrap());
+ let channel = insert_team_channel(&pool, "Support", team_id, USER_A, &[USER_A]).await;
+ let other_team = insert_team(&pool, USER_B).await;
+ let ineligible =
+ insert_team_channel(&pool, "Support elsewhere", other_team, USER_A, &[USER_A]).await;
+ let repo = PgChannelLabelsRepo::new(pool.clone());
+ let rule = ChannelLabelRule::Name {
+ contains: "support".into(),
+ };
+ let label = written(
+ repo.create_label(&personal, "Smart", &[], &user(USER_A), Some(&rule))
+ .await
+ .unwrap(),
+ );
+ assert_eq!(
+ repo.transfer_label(
+ &personal,
+ &team,
+ label.id,
+ "Shared smart",
+ &user(USER_A),
+ None
+ )
+ .await
+ .unwrap(),
+ LabelWriteOutcome::InvalidChannel(SetChannelLabelOutcome::ChannelNotLabelable)
+ );
+ assert_eq!(
+ repo.get_label(&personal, label.id, &user(USER_A))
+ .await
+ .unwrap()
+ .unwrap()
+ .channel_ids,
+ vec![channel, ineligible]
+ );
+ assert!(
+ repo.get_label(&team, label.id, &user(USER_A))
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index 8fbd95948a..af24a4bd83 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -1019,13 +1019,12 @@ between Threads, All, and Recent preserves an already-open navigation overlay.
With the flag on, desktop Chat has one conversation sidebar, without All, Recent,
or Threads view tabs. The default order is Favorites, Direct messages, the
-team's channels, custom sections, then **All channels**. The team heading is
-**[Team name] channels**, with **Team channels** as the fallback while the name
-is unavailable. The team section always shows joined team channels, including
-channels assigned to manual or smart custom sections. All channels shows joined
-public/private channels, including custom-section members; it excludes team
-channels and DMs. Each custom section is a top-level heading, independent of the
-Team channels disclosure. Empty sections
+team's channels, then custom sections. There is no All channels section; search
+still finds joined public/private conversations outside these sections. The team
+heading is **[Team name] channels**, with **Team channels** as the fallback while
+its name is unavailable. The team section always shows joined team channels,
+including channels assigned to manual or smart custom sections. Each custom
+section is a top-level heading, independent of the Team channels disclosure. Empty sections
use padded, bordered cards like saved views, with a subtle background and secondary
actions; empty Favorites explains how to add a favorite. Private conversations
use a lock icon in the sidebar and mobile feed, including favorited private
@@ -1048,22 +1047,20 @@ sections have no scope icon or badge. Header focus backgrounds fill the entire h
trailing controls, with no extra right padding.
The sidebar uses TanStack Virtual for the section stack, each expanded channel
-list, and search results. Rows retain stable identities through live refreshes;
-focused and dragged rows remain mounted when they leave the visible range.
+list, and search results. Rows retain stable identities and measured positions
+through live refreshes and section reordering; focused and dragged rows remain
+mounted when they leave the visible range.
Keyboard navigation scrolls immediately, without animation, only when the
highlighted row enters the viewport's two-row context margin, leaving neighboring
rows visible above and below. The margin shrinks in short sections.
Section jumps also reveal the heading with surrounding context.
-Capped sections scroll independently. When All channels is last and has no saved
-height, it grows to show its full list while rows remain virtualized against the
-outer sidebar scroll. Moving another section below it restores the normal height
-cap. A manually saved All channels height takes precedence in either position.
-Lists with more than two items have a resize grip; drag it to choose a height
-between two rows (68px) and the end of the list, capped by the section's maximum. Shorter lists fit their content and have no
+Every section scrolls independently. Lists with more than two items have a resize
+grip; drag it to choose a height between two rows (68px) and the end of the list,
+capped by the section's maximum. Shorter lists fit their content and have no
resize grip. Favorites and Direct messages default to four visible rows;
-other sections default to their maximum height within the pane, except the
-unresized final All channels section. Focus the grip and use Up/Down
-to resize by 20px (100px with Shift), or double-click to restore the default.
+other sections default to their maximum height within the pane. Focus the grip
+and use Up/Down to resize by 20px (100px with Shift), or double-click to restore
+the default.
Section heights persist as personal preferences alongside sorting and sidebar
width. Heights adapt to filtered content and smaller panes without discarding
the saved preference. Search covers channels and DMs regardless of section
@@ -1082,8 +1079,10 @@ preference, including for shared sections, and survives reloads. The dragged
section appears as a card preview while its source is subdued. Other sections
animate into their new positions on drop or keyboard reorder, except with reduced
motion enabled. Dragging near the sidebar's top or bottom uses the same edge-scroll
-mechanism as Gantt; wheel scrolling remains available during a drag. Resize drags compensate for sidebar scroll movement,
-and the rounded resize grips retain pointer capture until release or cancellation.
+mechanism as Gantt; wheel scrolling remains available during a drag. Resizing near
+the sidebar's top or bottom also scrolls the sidebar, including while the pointer
+stays still. Resize drags compensate for that movement, and the rounded resize
+grips retain pointer capture until release or cancellation.
Section membership comes from the server's complete visible channel-ID lists.
The sidebar shows available channel rows immediately. One shared by-ID query
@@ -1128,18 +1127,31 @@ the label service and its feature flag.
Use **New → New section** to create a section. The wider dialog has a name field
and a **Smart section** switch in its body. **Shared with team** sits on the left
-of the footer, with the action buttons on the right. With both switches off, the
-section is personal and manual. Smart grouping reveals a separate input below
+of the footer, with the action buttons on the right. The question-mark tooltip
+beside sharing explains that team members can see and organize the section and
+only team channels can be added; clicking or tapping the help button also reveals
+the explanation below the footer controls. The form shows a warning-colored
+**Team channels only** hint when sharing is on and no scope hint when it is off.
+With both switches off, the section is personal and manual. Smart grouping reveals a separate input below
**Name contains** and a matching-channel count. Hover or focus that count to preview
matched channels; larger results show the remaining count. Switching sharing scope
refreshes the preview without replacing the form. A zero shared count explains
that only joined team channels match; public and private channels remain personal.
-Edit and delete through each section's sliders menu. Personal sections are
-private to the account, including for team members, and accept joined team,
-public, or private channels. Shared sections
-retain the team's existing label permissions and accept only channels from that
-team. Neither kind accepts DMs. A personal assignment never changes a shared
-assignment. Names are unique within each scope, case-insensitively.
+Edit and delete through each section's sliders menu. Editing also exposes
+**Shared with team**. Turning it on or off preserves the section ID; turning it
+off requires confirmation and makes the section personal to the current account,
+removing it from teammates' sidebars. The toggle is disabled with an explanation
+while channel eligibility is loading or when any current member is unavailable
+or ineligible for the destination scope. No channels are silently dropped.
+Personal sections are private to the account, including for team members, and
+accept joined team, public, or private channels. Shared sections accept only
+channels from that team. Any current team member can create, edit, change sharing,
+or delete a shared section; these actions are not admin-only. Neither kind accepts DMs.
+Scope changes reject duplicate destination names and atomically move manual
+assignments into the destination scope, replacing other manual assignments there.
+Smart sections keep their rule and reevaluate matches in the new scope.
+Ordinary channel assignments stay isolated between personal and shared scopes.
+Names are unique within each scope, case-insensitively.
Each heading has one sliders-icon menu, also available by right-clicking the header.
**Sort** opens its independent single-select options with a checkmark on the right.
@@ -1165,14 +1177,14 @@ Filtered-out channels retain their membership and do not reappear ungrouped.
Shared name and rule edits apply to the team; personal edits affect only the account.
Deleting a section does not delete its conversations or change channel access.
-Every desktop section menu, including **Favorites**, **All channels**,
-**[team name] channels**, and **Direct messages**, offers **Mute all channels**,
+Every desktop section menu, including **Favorites**, **[team name] channels**,
+and **Direct messages**, offers **Mute all channels**,
**Unmute all channels**, and **Snooze all channels**. These update only your
notifications, including for shared sections. Each action uses the section's
complete current membership, including filtered-out and unloaded channels;
channels added later do not inherit the change. Built-in lists resolve all pages
-before applying an action and never include unjoined channels. Both the team
-section and All channels include their custom-section members.
+before applying an action and never include unjoined channels. The team
+section includes its custom-section members.
Favorites targets only channel favorites, not documents or other favorite types.
Snooze uses the usual
duration/date picker and resumes notifications at the chosen time. A partial
diff --git a/packages/code-mode-sdk/scripts/generate.ts b/packages/code-mode-sdk/scripts/generate.ts
index 4534068a18..35e0e728cc 100644
--- a/packages/code-mode-sdk/scripts/generate.ts
+++ b/packages/code-mode-sdk/scripts/generate.ts
@@ -72,10 +72,7 @@ try {
const notes = await renderSdkDocs(root, rendered);
const pages = await readMarkdownPages(join(rendered, 'markdown'));
const docs = packageEntityDocs(pages, entityDirectories, notes);
- await artifact(
- 'documentation.json',
- `${JSON.stringify(docs, null, 2)}\n`
- );
+ await artifact('documentation.json', `${JSON.stringify(docs, null, 2)}\n`);
} finally {
await rm(rendered, { recursive: true, force: true });
}
@@ -120,7 +117,4 @@ for (const [service, directory] of Object.entries({
.trim();
}
}
-await artifact(
- 'operations.json',
- `${JSON.stringify(operations, null, 2)}\n`
-);
+await artifact('operations.json', `${JSON.stringify(operations, null, 2)}\n`);
diff --git a/packages/code-mode-sdk/scripts/typedoc.ts b/packages/code-mode-sdk/scripts/typedoc.ts
index 8afcea5cac..16c1671ce5 100644
--- a/packages/code-mode-sdk/scripts/typedoc.ts
+++ b/packages/code-mode-sdk/scripts/typedoc.ts
@@ -235,7 +235,9 @@ export function packageEntityDocs(
}
const { header, methods } = splitClass(markdown);
const guide = guideByPage.get(path);
- symbols[symbol] = guide ? `${header}\n\n${GUIDE_HEADING}\n\n${guide}` : header;
+ symbols[symbol] = guide
+ ? `${header}\n\n${GUIDE_HEADING}\n\n${guide}`
+ : header;
for (const method of methods)
symbols[`${symbol}.${method.name}`] = method.markdown;
}
diff --git a/packages/code-mode-sdk/src/documentation.test.ts b/packages/code-mode-sdk/src/documentation.test.ts
index 6bc76919b9..6050df60de 100644
--- a/packages/code-mode-sdk/src/documentation.test.ts
+++ b/packages/code-mode-sdk/src/documentation.test.ts
@@ -229,7 +229,9 @@ describe('TypeDoc documentation packaging', () => {
);
expect(guide('channels')).toContain('A form for a channel is a poll:');
expect(guide('tasks')).toContain('Never edit, merge or delete');
- expect(guide('agentSessions')).toContain('macro.agentSessions.createManaged');
+ expect(guide('agentSessions')).toContain(
+ 'macro.agentSessions.createManaged'
+ );
expect(guide('routines')).toContain('never sees this conversation');
expect(guide('documents')).toContain('<m-document-mention>');
expect(guide('core')).toContain('macro.documents.search');
diff --git a/packages/sdk-docs/src/render.ts b/packages/sdk-docs/src/render.ts
index 84cb64ce2b..c4126842fb 100644
--- a/packages/sdk-docs/src/render.ts
+++ b/packages/sdk-docs/src/render.ts
@@ -32,9 +32,8 @@ export async function renderSdkDocs(
const plugin = createRequire(import.meta.url).resolve(
'typedoc-plugin-markdown'
);
- const { Application, Comment, OptionDefaults, ReflectionKind } = (await import(
- createRequire(plugin).resolve('typedoc')
- )) as typeof TypeDoc;
+ const { Application, Comment, OptionDefaults, ReflectionKind } =
+ (await import(createRequire(plugin).resolve('typedoc'))) as typeof TypeDoc;
const sdk = join(root, 'packages/sdk');
const entryPoints = [
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index fc4d545189..9db9247d80 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -662,7 +662,7 @@ export class Sdk extends HeyApiClient {
}
/**
- * Rename a label of the caller's authorized scope.
+ * Update a label, optionally moving it to another authorized scope.
*/
public renameChannelLabel<ThrowOnError extends boolean = false>(options: Options<RenameChannelLabelData, ThrowOnError>): RequestResult<RenameChannelLabelResponses, RenameChannelLabelErrors, ThrowOnError> {
return (options.client ?? this.client).patch<RenameChannelLabelResponses, RenameChannelLabelErrors, ThrowOnError>({
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index dd0f7b478d..d9006d265c 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -2793,7 +2793,7 @@ export type ChannelLabel = {
*/
teamId?: string | null;
/**
- * When the label was last renamed or reordered.
+ * When the label's name, rule, scope, or order last changed.
*/
updatedAt: string;
};
@@ -12211,7 +12211,7 @@ export type RemoveParticipantsRequest = {
};
/**
- * Request body for renaming a label.
+ * Request body for updating a label's name, smart rule, or sharing scope.
*/
export type RenameChannelLabelRequest = {
/**
@@ -12219,6 +12219,7 @@ export type RenameChannelLabelRequest = {
*/
name: string;
rule?: null | ChannelLabelRule;
+ targetScope?: null | ChannelLabelScopeSelection;
};
/**
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index f358bb5b48..8e4e1b83d0 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -3419,7 +3419,7 @@
},
"patch": {
"tags": ["channel_labels"],
- "summary": "Rename a label of the caller's authorized scope.",
+ "summary": "Update a label, optionally moving it to another authorized scope.",
"operationId": "rename_channel_label",
"parameters": [
{
@@ -24357,7 +24357,7 @@
"updatedAt": {
"type": "string",
"format": "date-time",
- "description": "When the label was last renamed or reordered."
+ "description": "When the label's name, rule, scope, or order last changed."
}
}
},
@@ -39465,7 +39465,7 @@
},
"RenameChannelLabelRequest": {
"type": "object",
- "description": "Request body for renaming a label.",
+ "description": "Request body for updating a label's name, smart rule, or sharing scope.",
"required": ["name"],
"properties": {
"name": {
@@ -39482,6 +39482,17 @@
"description": "Automatic name-matching rule; omitted for manual labels or a name-only rename."
}
]
+ },
+ "targetScope": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection",
+ "description": "Destination namespace; omitted to preserve the current scope."
+ }
+ ]
}
}
},