Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(channels): improve sidebar section interactions (#9393)
dev-rb4054b6887bc0
diff --git a/.agents/rules/web/ui.md b/.agents/rules/web/ui.mdindex 3c70a26182..6f26fb23b6 100644--- a/.agents/rules/web/ui.md+++ b/.agents/rules/web/ui.md@@ -16,7 +16,8 @@ Components, styling, and interaction conventions.- **FE-23** Disclosure carets rotate 180° to point down when expanded, matchingDiscussion, SplitFileMenu, CollapsibleMessage, etc.- **FE-24** Truncated/collapsed controls get a tooltip (matching the app's- tooltip pattern) so the lost label stays discoverable.+ tooltip pattern) so the lost label stays discoverable. Use shared tooltips or+ popovers instead of native `title`; give each target one hint surface.- **FE-25** Semantic color tokens, not raw Tailwind palette classes — thedefault palette is disabled via `--color-*: initial` in`apps/web/src/index.css`, so classes like `text-red-500` silently renderdiff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex a0db5e061d..36f9d970f9 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -571,24 +571,29 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription tofor 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/`.- With the flag on, keep desktop Chat sections in a scrolling stack with Favorites first and DMs directly below; personal and team-shared section assignments remain independent, including when dragging a row out of its originating section.- Keep resize grips keyboard-accessible, preserve per-section heights in personal preferences, and route list navigation through the sectioned renderer's scroll handle rather than global virtualizer indexes.+ Default desktop Chat to Favorites, Direct messages, the team's channels, custom sections, then All channels; preserve personal section reordering without changing shared membership or the remaining public/private membership of All channels.+ Keep resize and reorder grips keyboard-accessible; overlay reorder grips in the left gutter without shifting section names. 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.Cap section heights at measured list content and available pane space; hide resize grips for two or fewer items, default Favorites and DMs to four rows, and default other sections to their maximum height.- Mobile retains the recent feed. Keep New channel and New direct message on their separate existing creation flows, independent of the sidebar flag.+ 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 all section content by 8px, including Favorites, custom sections, DMs, and empty states; keep unsectioned search results unindented.- Reuse shared collapsible section headers and their hidden-caret behavior without leading icons; keep a neutral Shared badge next to the name before the caret, apply focus backgrounds across the full header row, and omit trailing header padding.- Space sections with the stack's flex gap, not header padding; wrap each custom section's header and content in one drop target and highlight.+ 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.+ Reuse shared collapsible section headers and their hidden-caret behavior without leading section icons; keep Shared beside the name before the caret, replacing its badge with a users icon below 256px of section width. Use short, separate tooltips for names and sharing; apply focus backgrounds across the full header row and omit trailing header padding.+ Space sections with the stack's 2px flex gap, not header padding; wrap each section's header and content in one drop surface, show blocked drops with a not-allowed cursor and explanation, and keep Gantt's shared drag auto-scroll and wheel scrolling available while dragging.+ Animate section reorder with the shared layout animation engine; preserve unanimated measurement wrappers, reduced-motion preferences, and cancellation on scrolling. Show a card preview and subdued source while dragging.Name the team-channel section after the current team, falling back to Team channels while its name is unavailable.+ 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; 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.+ 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.Default Favorites to Custom order and persist drag reordering through the shared favorites mutation; preserve hidden and non-channel favorite positions, disable dragging under automatic sorts, show an insertion line at the actual destination edge, and keep the original rail unchanged.Share the sliders-icon section menu's Sort, Filter, and actions with a header context menu; use trailing `SingleSelectCheck` marks for sorting, keep the Unread only label left and its switch right, and keep the filter submenu open when toggled.Compose the section click and right-click menus with `ContextMenuContent`, `MenuItem`, `MenuGroup`, and `MenuSeparator`; do not nest padded `Dropdown.Group` elements inside a context-menu surface.Keep all section mute, unmute, and snooze actions personal to the viewer; use the complete current membership, not filtered or hydrated rows, and never apply the change to later additions. Resolve built-in membership through the complete channel list, preserving sidebar assignment exclusions and participant checks; Favorites targets channel favorites only. Reuse notification mutations and the shared snooze picker, preserving successful writes on partial failure.Use checkbox items in Add to section to toggle membership within each scope without changing the other scope.+ Carry team IDs into channel entities and require a matching team for new shared-section assignments; preserve server-authorized membership display while metadata hydrates.- Route supported move, trash, restore, permanent-delete, duplicate, and share-policywrites through `queries/storage/entity-mutations` when GraphQL Soup is enabled;never retry failed GraphQL writes through REST. Preserve non-owner history removaldiff --git a/apps/web/src/components/app/ItemDragAndDrop.tsx b/apps/web/src/components/app/ItemDragAndDrop.tsxindex e4fa456136..8b3541261d 100644--- a/apps/web/src/components/app/ItemDragAndDrop.tsx+++ b/apps/web/src/components/app/ItemDragAndDrop.tsx@@ -31,6 +31,7 @@ type DragOperationContextValue = {export type ItemDragOverlayData = {overlayIcon?: () => JSXElement;+ overlayContent?: () => JSXElement;};const DragOperationContext = createContext<DragOperationContextValue>();@@ -56,6 +57,10 @@ function ItemDragOverlay() {const overlayIcon = () =>(activeDraggable()?.data as ItemDragOverlayData | undefined)?.overlayIcon;+ const overlayContent = () =>+ (activeDraggable()?.data as ItemDragOverlayData | undefined)+ ?.overlayContent;+const iconType = createMemo((): EntityIconSelector => {const data = activeDraggable()?.data;if (!data) return 'default';@@ -91,17 +96,24 @@ function ItemDragOverlay() {class="w-auto max-w-75 flex flex-col gap-2 bg-surface p-2 rounded-lg z-drag shadow-md shadow-drop-shadow pointer-events-none"style={besidePointerStyle()}>- <div class="flex flex-row items-center gap-2">- <Show- when={overlayIcon()}- fallback={<EntityIcon size="xs" targetType={iconType()} />}- >- {(icon) => icon()()}- </Show>- <TruncatedText size="xs">- {activeDraggable()?.data.name}- </TruncatedText>- </div>+ <Show+ when={overlayContent()}+ fallback={+ <div class="flex flex-row items-center gap-2">+ <Show+ when={overlayIcon()}+ fallback={<EntityIcon size="xs" targetType={iconType()} />}+ >+ {(icon) => icon()()}+ </Show>+ <TruncatedText size="xs">+ {activeDraggable()?.data.name}+ </TruncatedText>+ </div>+ }+ >+ {(content) => content()()}+ </Show><Show when={additionalCount() > 0}><div class="pl-6 text-xs text-ink-muted">{t('entityActions.dragMoreItems', { count: additionalCount() })}diff --git a/apps/web/src/components/drag-drop/create-drag-auto-scroll.test.ts b/apps/web/src/components/drag-drop/create-drag-auto-scroll.test.tsindex 16445f04e3..1abd0fa122 100644--- a/apps/web/src/components/drag-drop/create-drag-auto-scroll.test.ts+++ b/apps/web/src/components/drag-drop/create-drag-auto-scroll.test.ts@@ -36,7 +36,7 @@ afterEach(() => {});function setup(- axis: 'x' | 'both' = 'x',+ axis: 'x' | 'y' | 'both' = 'x',nestedScroll?: { viewportSelector: string; horizontalOutside: boolean }) {const frames = new Map<number, FrameRequestCallback>();@@ -110,6 +110,22 @@ describe('drag auto-scroll', () => {expect(viewport.scrollLeft).toBeLessThan(600);});+ it('scrolls vertical sidebars without changing their horizontal offset', () => {+ const { viewport, setActive, frame, frames } = setup('y');+ viewport.scrollLeft = 40;+ drag.pointer = { x: 395, y: 495 };+ setActive(true);+ frame(0);+ frame(16);++ expect(viewport.scrollTop).toBeGreaterThan(0);+ expect(viewport.scrollLeft).toBe(40);+ expect(drag.detectCollisions).toHaveBeenCalledOnce();++ setActive(false);+ expect(frames.size).toBe(0);+ });+it('scrolls vertically for boards and cancels its frame on unmount', () => {const { viewport, setActive, frame, frames } = setup('both');drag.pointer = { x: 200, y: 495 };diff --git a/apps/web/src/components/drag-drop/create-drag-auto-scroll.ts b/apps/web/src/components/drag-drop/create-drag-auto-scroll.tsindex 11a8082bc7..eded56e845 100644--- a/apps/web/src/components/drag-drop/create-drag-auto-scroll.ts+++ b/apps/web/src/components/drag-drop/create-drag-auto-scroll.ts@@ -56,7 +56,7 @@ function scrollDragFrame(viewport: HTMLElement,pointer: Point,elapsed: number,- options: { axis: 'x' | 'both'; nestedScroll?: NestedScroll }+ options: { axis: 'x' | 'y' | 'both'; nestedScroll?: NestedScroll }) {const bounds = viewport.getBoundingClientRect();const edges = {@@ -77,7 +77,7 @@ function scrollDragFrame(? options.nestedScroll: undefined;const beforeX = viewport.scrollLeft;- if (inside || nested?.horizontalOutside) {+ if (options.axis !== 'y' && (inside || nested?.horizontalOutside)) {viewport.scrollLeft = Math.max(0,Math.min(@@ -88,7 +88,7 @@ function scrollDragFrame();}let scrolled = viewport.scrollLeft !== beforeX;- if (inside && options.axis === 'both' && !nested) {+ if (inside && options.axis !== 'x' && !nested) {const beforeY = viewport.scrollTop;viewport.scrollTop = Math.max(0,@@ -111,7 +111,7 @@ function scrollDragFrame(/** Scroll the active solid-dnd surface while the pointer rests near its edge. */export function createDragAutoScroll(options: {getViewport: () => HTMLElement | undefined;- axis: 'x' | 'both';+ axis: 'x' | 'y' | 'both';nestedScroll?: NestedScroll;}) {const context = useDragDropContext();diff --git a/apps/web/src/components/kanban/kanban-animation.ts b/apps/web/src/components/drag-drop/create-layout-animation.tssimilarity index 97%rename from apps/web/src/components/kanban/kanban-animation.tsrename to apps/web/src/components/drag-drop/create-layout-animation.tsindex dfbaa6a2e9..a43c7b2e7a 100644--- a/apps/web/src/components/kanban/kanban-animation.ts+++ b/apps/web/src/components/drag-drop/create-layout-animation.ts@@ -1,5 +1,5 @@import { fireAndForget } from '@core/util/fireAndForget';-export type KanbanAnimationItem = {+export type LayoutAnimationItem = {/** Unique placement, including the lane for cards with several placements. */key: string;/** Shared identity lets a card animate across remounted placements. */@@ -11,7 +11,7 @@ export type KanbanAnimationItem = {layout: HTMLElement;};-export type KanbanAnimationOrigin = {+export type LayoutAnimationOrigin = {/** Placement identity survives source virtualization at drag release. */key: string;element: HTMLElement;@@ -19,7 +19,7 @@ export type KanbanAnimationOrigin = {parentKey: string;};-type Snapshot = KanbanAnimationItem & {+type Snapshot = LayoutAnimationItem & {rect: DOMRect;clone?: HTMLElement;dragOrigin?: boolean;@@ -32,9 +32,9 @@ const TIMING: KeyframeAnimationOptions = {};/** Observe layout during a drag hover or host-owned move, never ordinary paging. */-export function createKanbanAnimation(options: {+export function createLayoutAnimation(options: {viewport(): HTMLElement | undefined;- items(): KanbanAnimationItem[];+ items(): LayoutAnimationItem[];}) {let snapshots = new Map<string, Snapshot>();let observer: MutationObserver | undefined;@@ -111,8 +111,8 @@ export function createKanbanAnimation(options: {// A wrapper inherits every animated ancestor, although it has no local animation.function normalizedRect(- item: KanbanAnimationItem,- byKey: Map<string, KanbanAnimationItem>+ item: LayoutAnimationItem,+ byKey: Map<string, LayoutAnimationItem>): DOMRect {const rect = item.layout.getBoundingClientRect();let x = rect.left;@@ -204,7 +204,7 @@ export function createKanbanAnimation(options: {}}};- fireAndForget(finish(), 'kanban-animation');+ fireAndForget(finish(), 'layout-animation');}function fly(@@ -500,7 +500,7 @@ export function createKanbanAnimation(options: {function begin(identity: string,destinationParentKey?: string,- origin?: KanbanAnimationOrigin+ origin?: LayoutAnimationOrigin) {const viewport = options.viewport();diff --git a/apps/web/src/components/kanban/kanban-animation-merge.test.ts b/apps/web/src/components/kanban/kanban-animation-merge.test.tsindex 2b1c829d79..7c5d5e37ef 100644--- a/apps/web/src/components/kanban/kanban-animation-merge.test.ts+++ b/apps/web/src/components/kanban/kanban-animation-merge.test.ts@@ -1,8 +1,8 @@import { afterEach, expect, it, vi } from 'vitest';import {- createKanbanAnimation,- type KanbanAnimationItem,-} from './kanban-animation';+ createLayoutAnimation,+ type LayoutAnimationItem,+} from '../drag-drop/create-layout-animation';let cancel: (() => void) | undefined;const originalAnimate = Object.getOwnPropertyDescriptor(@@ -46,7 +46,7 @@ function fixture() {const viewport = document.createElement('div');viewport.getBoundingClientRect = () => new DOMRect(0, 0, 900, 600);document.body.append(viewport);- let items: KanbanAnimationItem[] = [];+ let items: LayoutAnimationItem[] = [];function placement(key: string, x: number, parentKey?: string) {const layout = document.createElement('div');@@ -75,7 +75,7 @@ function fixture() {};}- const motion = createKanbanAnimation({+ const motion = createLayoutAnimation({viewport: () => viewport,items: () => items,});diff --git a/apps/web/src/components/kanban/kanban-animation.test.ts b/apps/web/src/components/kanban/kanban-animation.test.tsindex 13612a4102..7582f141b0 100644--- a/apps/web/src/components/kanban/kanban-animation.test.ts+++ b/apps/web/src/components/kanban/kanban-animation.test.ts@@ -1,8 +1,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {- createKanbanAnimation,- type KanbanAnimationItem,-} from './kanban-animation';+ createLayoutAnimation,+ type LayoutAnimationItem,+} from '../drag-drop/create-layout-animation';const cleanups: (() => void)[] = [];let animate: ReturnType<typeof vi.fn>;@@ -44,8 +44,8 @@ function fixture() {const viewport = document.createElement('div');viewport.getBoundingClientRect = () => new DOMRect(0, 0, 800, 600);document.body.append(viewport);- let items: KanbanAnimationItem[] = [];- const motion = createKanbanAnimation({+ let items: LayoutAnimationItem[] = [];+ const motion = createLayoutAnimation({viewport: () => viewport,items: () => items,});diff --git a/apps/web/src/components/kanban/kanban-board.tsx b/apps/web/src/components/kanban/kanban-board.tsxindex ebf44fbb3c..abfd3ade20 100644--- a/apps/web/src/components/kanban/kanban-board.tsx+++ b/apps/web/src/components/kanban/kanban-board.tsx@@ -14,6 +14,10 @@ import {Show,useContext,} from 'solid-js';+import {+ createLayoutAnimation,+ type LayoutAnimationItem,+} from '../drag-drop/create-layout-animation';import {Kanban,KanbanCard,@@ -23,10 +27,6 @@ import {KanbanLane,useKanbanDropTarget,} from './kanban';-import {- createKanbanAnimation,- type KanbanAnimationItem,-} from './kanban-animation';import {CardActions,CardFields,@@ -107,14 +107,14 @@ function Root(props: {revealGeneration += 1;setReveal({ kind, toLane, scope: props.animationScope });}- const motion = createKanbanAnimation({+ const motion = createLayoutAnimation({viewport: () => viewport,items: () => {if (!viewport) {return [];}- const items: KanbanAnimationItem[] = [];+ const items: LayoutAnimationItem[] = [];for (const layout of viewport.querySelectorAll<HTMLElement>('[data-kanban-board-column]'diff --git a/apps/web/src/features/channels-view/channels-view-context.tsx b/apps/web/src/features/channels-view/channels-view-context.tsxindex f70e18a8e2..7ae672371d 100644--- a/apps/web/src/features/channels-view/channels-view-context.tsx+++ b/apps/web/src/features/channels-view/channels-view-context.tsx@@ -75,6 +75,7 @@ export type ChannelsViewContext = {section: ChannelSectionKey,preferences: ChannelSectionPreferences) => void;+ setSectionOrder: (sections: ChannelSectionKey[]) => void;setAsideWidth: (width: number) => void;};@@ -101,6 +102,7 @@ function createInitialState(threads: initial.sortBy?.threads ?? CHANNELS_DEFAULT_SORT_BY.threads,},sectionPreferences: { ...initial.sectionPreferences },+ sectionOrder: initial.sectionOrder ?? [],asideWidth: clampChannelsRailWidth(initial.asideWidth ?? CHANNELS_DEFAULT_RAIL_WIDTH),@@ -134,6 +136,7 @@ export const [ChannelsViewProvider, useChannelsView] =restoreEntryState: props.initialState === undefined,restoreLocalState: props.initialState === undefined,restorePreferences: shouldRestorePreferences(initial),+ restoreSectionOrder: initial.sectionOrder === undefined,}));@@ -267,6 +270,7 @@ export const [ChannelsViewProvider, useChannelsView] =...current,[section]: { ...current[section], ...preferences },})),+ setSectionOrder: (sections) => setState('sectionOrder', sections),setAsideWidth: (width) =>setState('asideWidth', clampChannelsRailWidth(width)),};diff --git a/apps/web/src/features/channels-view/components/ConversationsCreateMenu.tsx b/apps/web/src/features/channels-view/components/ConversationsCreateMenu.tsxindex 6e6995a4b4..1412a238dd 100644--- a/apps/web/src/features/channels-view/components/ConversationsCreateMenu.tsx+++ b/apps/web/src/features/channels-view/components/ConversationsCreateMenu.tsx@@ -24,6 +24,7 @@ export function ConversationsCreateMenu(props: {return (<Dropdown+ sameWidth={props.presentation === 'sidebar'}placement={props.presentation === 'sidebar' ? 'bottom-start' : 'bottom-end'}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.tsxindex 18ee8de751..346f9496d9 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@@ -27,6 +27,8 @@ import {useFavoriteReorder,} from './next/useFavoriteReorder';+import { useSectionReorder } from './next/useSectionReorder';+const measurements = vi.hoisted(() => ({ contentHeight: (): number => 400 }));const rail = vi.hoisted(() => ({channelById: (_channelId: string): ChannelEntity | undefined => undefined,@@ -36,6 +38,8 @@ const rail = vi.hoisted(() => ({railId: 'rail',sectionPreferences: () => ({ sort: 'manual' }),setSectionPreferences: vi.fn(),+ setSectionOrder: vi.fn(),+ sectionOrder: (): readonly import('../../types').ChannelSectionKey[] => [],labels: (): ChannelLabel[] => [],labelsAvailable: () => true,sectionsEnabled: () => true,@@ -43,6 +47,7 @@ const rail = vi.hoisted(() => ({}));const drag = vi.hoisted(() => ({+ viewer: (): string => 'viewer',starts: [] as Array<(event: { draggable: { data: Record<string, unknown> } }) => void>,@@ -64,7 +69,7 @@ vi.mock('@queries/favorites/favorites', () => ({useFavoritesData: () => () => ({ favorites: drag.favorites }),useReorderFavoritesMutation: () => ({ mutateAsync: drag.reorder }),}));-vi.mock('@core/context/user', () => ({ useUserId: () => () => 'viewer' }));+vi.mock('@core/context/user', () => ({ useUserId: () => () => drag.viewer() }));vi.mock('@macro-inc/observability', () => ({Telemetry: {span: async (@@ -190,7 +195,8 @@ vi.mock('@app/components/view-shell', () => ({},}));vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));-vi.mock('@ui', () => ({+vi.mock('@ui', async () => ({+ Tooltip: (await import('@ui/components/Tooltip')).Tooltip,cn: (...values: unknown[]) => values.filter(Boolean).join(' '),}));@@ -215,7 +221,9 @@ beforeEach(() => {drag.ends.length = 0;drag.draggables.clear();rail.labels = () => [];+ rail.sectionOrder = () => [];drag.favorites = [];+ drag.viewer = () => 'viewer';const [loaded, update] = createSignal<ChannelEntity | undefined>(undefined);[measurements.contentHeight] = createSignal(400);setChannel = update;@@ -225,6 +233,16 @@ beforeEach(() => {afterEach(cleanup);describe('channel section drag sources', () => {+ it('keeps the drag identity current when a virtual row is reused', () => {+ const [current, setCurrent] = createSignal(channel);+ render(() => <ChannelOption channel={current()} draggable />);+ const data = drag.draggables.get('rail:channel-label:drag:channel:design');++ setCurrent({ ...channel, id: 'updated', name: 'Updated' });++ expect(data?.channelId).toBe('updated');+ expect(data?.name).toBe('Updated');+ });it('keeps each rendered section as the drag source when a channel belongs to both scopes', () => {rail.labels = () => [{@@ -435,6 +453,48 @@ describe('favorite reordering', () => {});});+describe('section reordering', () => {+ it('keeps absent sections in their saved positions during keyboard reordering', () => {+ rail.sectionOrder = () => ['favorites', 'channels', 'label:section'];+ const { result } = renderHook(() =>+ useSectionReorder(+ () => ['favorites', 'label:section'],+ (reorder) => reorder()+ )+ );+ result.move('label:section', -1);+ expect(rail.setSectionOrder).toHaveBeenCalledExactlyOnceWith([+ 'label:section',+ 'channels',+ 'favorites',+ ]);+ });++ it('preserves hidden sections and ignores stale drops after account changes', () => {+ const [viewer, setViewer] = createSignal('viewer');+ drag.viewer = viewer;+ const { result } = renderHook(() =>+ useSectionReorder(+ () => ['favorites', 'label:collapsed', 'channels'],+ (reorder) => reorder()+ )+ );+ const source = { data: { dndScope: result.scope, section: 'channels' } };+ const target = { data: { dndScope: result.scope, section: 'favorites' } };+ drag.starts.forEach((start) => start({ draggable: source }));+ drag.ends.forEach((end) => end({ draggable: source, droppable: target }));+ expect(rail.setSectionOrder).toHaveBeenCalledExactlyOnceWith([+ 'channels',+ 'favorites',+ 'label:collapsed',+ ]);++ setViewer('another-viewer');+ drag.ends.forEach((end) => end({ draggable: source, droppable: target }));+ expect(rail.setSectionOrder).toHaveBeenCalledTimes(1);+ });+});+describe('resizable chat sections', () => {it('saves the final zoom-adjusted size and can resize again after collapse cancels a drag', () => {const [open, setOpen] = createSignal(true);@@ -505,6 +565,99 @@ describe('resizable chat sections', () => {});});+ it('compensates for sidebar scrolling during a resize drag', () => {+ let top = 100;+ render(() => (+ <ResizableRailSection+ section="favorites"+ label="Favorites"+ open+ maxHeight={400}+ itemCount={12}+ header={<span>Section</span>}+ rootRef={() => {}}+ scrollRef={(element) => {+ Object.defineProperty(element, 'offsetHeight', { value: 136 });+ vi.spyOn(element, 'getBoundingClientRect').mockImplementation(+ () => new DOMRect(0, top, 200, 136)+ );+ }}+ >+ Conversations+ </ResizableRailSection>+ ));+ const handle = screen.getByRole('separator');+ Object.defineProperty(handle, 'setPointerCapture', { value: vi.fn() });+ const start = new MouseEvent('pointerdown', {+ bubbles: true,+ clientY: 236,+ });+ Object.defineProperty(start, 'pointerId', { value: 1 });+ handle.dispatchEvent(start);+ top = 50;+ const end = new MouseEvent('pointerup', { bubbles: true, clientY: 236 });+ Object.defineProperty(end, 'pointerId', { value: 1 });+ handle.dispatchEvent(end);++ expect(rail.setSectionPreferences).toHaveBeenLastCalledWith('favorites', {+ height: 186,+ });+ });++ it.each(['pointercancel', 'lostpointercapture'])(+ 'does not save after %s and accepts a later resize',+ (cancelEvent) => {+ render(() => (+ <ResizableRailSection+ section="favorites"+ label="Favorites"+ open+ maxHeight={400}+ itemCount={12}+ header={<span>Section</span>}+ rootRef={() => {}}+ scrollRef={(element) => {+ Object.defineProperty(element, 'offsetHeight', { value: 136 });+ vi.spyOn(element, 'getBoundingClientRect').mockReturnValue(+ new DOMRect(0, 0, 200, 136)+ );+ }}+ >+ Conversations+ </ResizableRailSection>+ ));+ const handle = screen.getByRole('separator');+ Object.defineProperty(handle, 'setPointerCapture', { value: vi.fn() });+ for (const type of [+ 'pointerdown',+ 'pointermove',+ cancelEvent,+ 'pointerup',+ ]) {+ const event = new MouseEvent(type, {+ bubbles: true,+ clientY: type === 'pointerdown' ? 136 : 200,+ });+ Object.defineProperty(event, 'pointerId', { value: 1 });+ handle.dispatchEvent(event);+ }+ expect(rail.setSectionPreferences).not.toHaveBeenCalled();++ for (const type of ['pointerdown', 'pointerup']) {+ const event = new MouseEvent(type, {+ bubbles: true,+ clientY: type === 'pointerdown' ? 136 : 180,+ });+ Object.defineProperty(event, 'pointerId', { value: 2 });+ handle.dispatchEvent(event);+ }+ expect(rail.setSectionPreferences).toHaveBeenCalledExactlyOnceWith(+ 'favorites',+ { height: 180 }+ );+ }+ );+it('clamps keyboard resizing and resets only the section height', () => {render(() => (<ResizableRailSectiondiff --git a/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.test.tsxindex f68fbd303d..32eb51ba4c 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@@ -9,11 +9,63 @@ import {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';++const availableChannels = vi.hoisted(() => [+ {+ id: 'first',+ name: 'First',+ channel_type: 'team',+ team_id: 'team',+ is_participant: true,+ },+ {+ id: 'second',+ name: 'Second',+ channel_type: 'team',+ team_id: 'team',+ is_participant: true,+ },+ {+ id: 'existing',+ name: 'Existing',+ channel_type: 'team',+ team_id: 'team',+ is_participant: true,+ },+ {+ id: 'private',+ name: 'Private',+ channel_type: 'private',+ is_participant: true,+ },+ {+ id: 'other-team',+ name: 'Other team',+ channel_type: 'team',+ team_id: 'other',+ is_participant: true,+ },+ {+ id: 'unjoined',+ name: 'Unjoined',+ channel_type: 'team',+ team_id: 'team',+ is_participant: false,+ },+]);+vi.mock('@queries/channel-labels/channel-labels', () => ({+ useAvailableSectionChannelsQuery: () => ({+ isPending: false,+ data: availableChannels,+ }),+}));vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));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')),cn: (...values: unknown[]) => values.filter(Boolean).join(' '),Layer: (props: ParentProps) => props.children,Surface: (props: ParentProps) => <div>{props.children}</div>,@@ -92,3 +144,37 @@ describe('label naming', () => {expect(onConfirm).toHaveBeenCalledWith('Second group');});});++describe('section channel selection', () => {+ it('offers only eligible additions and retries failed channels without replaying successful additions', async () => {+ render(() => <ImperativeDialogHost />);+ const onConfirm = vi+ .fn()+ .mockResolvedValueOnce(['second'])+ .mockResolvedValueOnce([]);+ const result = promptSectionChannels({+ label: {+ id: 'section',+ name: 'Section',+ teamId: 'team',+ channelIds: ['existing'],+ channelCount: 1,+ sortOrder: 0,+ createdAt: '2026-01-01',+ updatedAt: '2026-01-01',+ },+ onConfirm,+ });+ expect(screen.getAllByRole('checkbox')).toHaveLength(2);+ fireEvent.click(screen.getByRole('checkbox', { name: 'First' }));+ fireEvent.click(screen.getByRole('checkbox', { name: 'Second' }));+ fireEvent.click(screen.getByRole('button', { name: 'Add 2 channels' }));+ await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy());+ expect(onConfirm).toHaveBeenLastCalledWith(['first', 'second']);+ expect(screen.queryByRole('checkbox', { name: 'First' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Add 1 channel' }));+ await result;+ expect(onConfirm).toHaveBeenLastCalledWith(['second']);+ expect(screen.queryByRole('dialog')).toBeNull();+ });+});diff --git a/apps/web/src/features/channels-view/components/rail/ChannelOption.tsx b/apps/web/src/features/channels-view/components/rail/ChannelOption.tsxindex 2db397621a..132f6e9cd6 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelOption.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelOption.tsx@@ -48,7 +48,9 @@ function createChannelLabelDnd(props: {{dragType: 'channel-label',dndScope: rail.railId,- channelId: props.channel.id,+ get channelId() {+ return props.channel.id;+ },get labelId() {const labelId = props.labelId();@@ -63,7 +65,9 @@ function createChannelLabelDnd(props: {!label.rule && label.channelIds.includes(props.channel.id))?.id;},- name: props.channel.name,+ get name() {+ return props.channel.name;+ },iconType: 'channel',} satisfies ChannelLabelDragData);@@ -94,7 +98,7 @@ export function ChannelOption(props: {rowId?: ChannelRailRow['id'];/** Containing section for drag-and-drop targets. */labelId?: string;- /** Make a team-channel row draggable between labels (Team channels section only). */+ /** Make an eligible named channel draggable between sections. */draggable?: boolean;}) {const rail = useChannelsRail();@@ -105,7 +109,9 @@ export function ChannelOption(props: {// Whether a row participates in drag and drop is fixed per mount.const dnd = props.draggable? createChannelLabelDnd({- channel: props.channel,+ get channel() {+ return props.channel;+ },rowId: rowId(),labelId: () => props.labelId,disabled: () =>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.tsxindex 933a4cbc4c..34fd9c2c66 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@@ -887,7 +887,7 @@ describe('section notification actions', () => {expect(mocks.fetchGroupIds).toHaveBeenCalledExactlyOnceWith(section,- section === 'direct_messages' ? [] : label.channelIds,+ section === 'channels' ? label.channelIds : [],expect.any(AbortSignal));expect(mocks.source.unmuteEntity.mock.calls).toEqual([diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsxindex a090e112ec..f2f9653229 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx@@ -58,7 +58,7 @@ import {import type { VirtualizerHandle } from 'virtua/solid';import { useChannelsView } from '../../channels-view-context';import {- canLabelChannel,+ canAssignChannel,filterChannelLabelMembers,} from '../../core/channel-label-eligibility';import { resolveChannelLabelMemberships } from '../../core/smart-tags';@@ -143,6 +143,7 @@ export function ChannelsRail(props: ChannelsRailProps) {setSelectedChannel,setSortBy,setSectionPreferences,+ setSectionOrder,setTab,tab,threadsEnabled,@@ -543,6 +544,7 @@ export function ChannelsRail(props: ChannelsRailProps) {channelSectionRows(),{preferences: state.sectionPreferences,+ order: state.sectionOrder,channelById,unreadChannelIds: channelActivity.unreadChannelIds(),referenceStatuses: referenceStatuses(),@@ -1029,6 +1031,7 @@ export function ChannelsRail(props: ChannelsRailProps) {renameLabel,deleteLabel,setChannelLabel,+ addChannelsToLabel,markLabelRead,canLabelChannelId,labelChannelById,@@ -1105,7 +1108,10 @@ export function ChannelsRail(props: ChannelsRailProps) {const labelId = drop.target.labelId;const label = labels().find((label) => label.id === labelId);- if (!label || !canLabelChannel(labelChannelById(drag.channelId), label)) {+ if (+ !label ||+ !canAssignChannel(labelChannelById(drag.channelId), label)+ ) {return undefined;}}@@ -1246,6 +1252,7 @@ export function ChannelsRail(props: ChannelsRailProps) {createSmartTag,editSmartTag: renameLabel,canShareSections: () => sharedLabels(),+ addChannelsToLabel,renameLabel,deleteLabel,setChannelLabel,@@ -1256,6 +1263,8 @@ export function ChannelsRail(props: ChannelsRailProps) {sectionNotificationsDisabled,sortBy: (group) => state.sortBy[group],setSortBy,+ sectionOrder: () => state.sectionOrder,+ setSectionOrder,sectionPreferences: (section) => {let sort: ChannelSectionPreferences['sort'];diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.tsindex 8349fe217f..8ff1ab60f2 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts@@ -175,6 +175,8 @@ export type ChannelsRailContext = {createSmartTag: () => Promise<void>;editSmartTag: (label: ChannelLabel) => Promise<void>;canShareSections: Accessor<boolean>;+ /** Pick eligible channels to add to a manual section. */+ addChannelsToLabel: (label: ChannelLabel) => Promise<void>;renameLabel: (label: ChannelLabel) => Promise<void>;/** Delete after the user confirms; applies to the whole team. */deleteLabel: (label: ChannelLabel) => Promise<void>;@@ -199,6 +201,8 @@ export type ChannelsRailContext = {section: ChannelSectionKey,preferences: ChannelSectionPreferences) => void;+ sectionOrder: Accessor<readonly ChannelSectionKey[]>;+ setSectionOrder: (sections: ChannelSectionKey[]) => void;registerRootRef: (element: HTMLDivElement) => void;activateRow: (rowId: ChannelRailRow['id'], event?: MouseEvent) => void;/** Warm a channel row's messages on the press that may open it. */diff --git a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.ts b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.tsindex 04768b4082..77ac5c6ff3 100644--- a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.ts+++ b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.ts@@ -6,8 +6,10 @@ import {buildChannelSectionRows,} from './build-channel-rail-rows';import {+ buildChannelSectionRows as buildSectionedChannelRows,buildChannelRailRows as buildSectionedRailRows,groupChannelRailSections,+ orderChannelRailSections,} from './next/build-channel-rail-rows';function channel(@@ -507,12 +509,123 @@ it('keeps overlapping section members and loading rows in their own scroll regio'channel:deals','status:direct_messages',]);- expect(- grouped- .get('team_channels')- ?.rows.every((row) => row.kind !== 'conversation')- ).toBe(true);+ expect(grouped.get('team_channels')?.rows.map((row) => row.id)).toEqual([+ 'channel:acme',+ 'status:team_channels',+ ]);expect(rows.filter((row) => row.kind === 'conversation').map((row) => row.id)- ).toEqual(['channel:deals', 'channel:acme:label:first']);+ ).toEqual(['channel:deals', 'channel:acme', 'channel:acme:label:first']);+});++it.each([true, false])(+ 'keeps assigned team channels in the built-in section when custom sections are open=%s',+ (open) => {+ const labels: ChannelLabel[] = [+ label('manual', 'Manual', ['acme']),+ {+ ...label('smart', 'Smart', ['zeta']),+ rule: { attribute: 'name', contains: 'support' },+ },+ ];+ const sections = buildSectionedChannelRows({+ labels,+ channels: [acme, zeta, deals],+ channelsById: byId,+ isLabelOpen: () => open,+ });+ const rows = buildSectionedRailRows(+ 'browse',+ {+ favorites: true,+ direct_messages: true,+ team_channels: true,+ channels: true,+ },+ {+ favorites: [],+ direct_messages: [],+ team_channels: [acme, zeta, deals],+ channels: [],+ recents: [],+ threads: [],+ },+ sections+ );+ const grouped = groupChannelRailSections(rows);++ expect(grouped.get('team_channels')?.rows.map((row) => row.id)).toEqual([+ 'channel:acme',+ 'channel:zeta',+ 'channel:deals',+ 'status:team_channels',+ ]);+ expect(grouped.get('label:manual')?.rows.map((row) => row.id)).toEqual(+ open ? ['channel:acme:label:manual'] : []+ );+ expect(grouped.get('label:smart')?.rows.map((row) => row.id)).toEqual(+ open ? ['channel:zeta:label:smart'] : []+ );+ expect(new Set(rows.map((row) => row.id)).size).toBe(rows.length);+ }+);++it('keeps section membership and navigation together after reordering with stale or duplicate keys', () => {+ const rows = buildSectionedRailRows(+ 'browse',+ {+ favorites: true,+ direct_messages: true,+ team_channels: true,+ channels: true,+ },+ {+ favorites: [],+ direct_messages: [],+ team_channels: [deals],+ channels: [channel('private', 'Private', 'private')],+ recents: [],+ threads: [],+ },+ [+ { kind: 'label', label: label('first', 'First', ['acme']) },+ { kind: 'conversation', channel: acme, labelId: 'first' },+ ],+ {+ order: ['label:removed', 'label:first', 'team_channels', 'label:first'],+ preferences: {},+ channelById: (id) => byId.get(id),+ unreadChannelIds: new Set(),+ referenceStatuses: { 'label:first': 'loading' },+ }+ );+ const grouped = groupChannelRailSections(rows);++ expect([...grouped.keys()]).toEqual([+ 'label:first',+ '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'])+ ).keys(),+ ]).toEqual([+ 'favorites',+ 'label:first',+ 'team_channels',+ 'direct_messages',+ '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.tsindex 2715721e9d..74bfd60864 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@@ -20,11 +20,13 @@ import type { ChannelLabelScopeSelection } from '@service-storage/generated/scheimport { confirmDialog } from '@ui';import type { Accessor, Owner } from 'solid-js';import {+ canAssignChannel,canLabelChannel,filterChannelLabelMembers,} from '../../../core/channel-label-eligibility';import type { ChannelsRailSection } from '../../../types';import { promptLabelName } from '../ChannelLabelNameDialog';+import { promptSectionChannels } from '../next/SectionChannelsDialog';import { promptSection, type SectionDialogValue } from '../next/SectionDialog';import { promptSmartTag } from '../SmartTagDialog';@@ -360,6 +362,84 @@ export function useChannelLabelActions(options: ChannelLabelActionsOptions) {}};+ const addChannelsToLabel = async (label: ChannelLabel) => {+ if (!sectionsEnabled() || !channelTagsEnabled() || label.rule) {+ return;+ }++ if (!labelsAvailable()) {+ toast.failure(labelsUnavailableReason());+ return;+ }++ const actorId = userId();+ const scope = scopeForLabel(label);++ await promptSectionChannels(+ {+ label,+ onConfirm: (channelIds) =>+ Telemetry.span('channels.section.add_channels', async (span) => {+ span.setAttr('section.id', label.id);+ span.setAttr('section.scope', scope);+ span.setAttr('channel.ids', channelIds.join(','));++ const current = labels().find((item) => item.id === label.id);++ if (+ actorId !== userId() ||+ !sectionsEnabled() ||+ !channelTagsEnabled() ||+ !labelsAvailable() ||+ !current ||+ current.rule ||+ scopeForLabel(current) !== scope+ ) {+ throw new Error(t('channelSections.unavailable'));+ }++ const additions = [...new Set(channelIds)].filter(+ (id) => !current.channelIds.includes(id)+ );+ const results = await Promise.allSettled(+ additions.map((channelId) =>+ mutationsForScope(scope).assign.mutateAsync({+ channelId,+ labelId: label.id,+ actorId,+ })+ )+ );++ if (actorId !== userId() || !sectionsEnabled()) {+ throw new Error(t('channelSections.unavailable'));+ }++ const failed = additions.filter(+ (_, index) => results[index].status === 'rejected'+ );+ const added = additions.length - failed.length;+ span.setAttr('channels.added', added);+ span.setAttr('channels.failed', failed.length);++ if (failed.length) {+ span.error('Some channel assignments failed');+ }++ if (added > 0) {+ setLabelOpen(label.id, true);+ toast.success(+ t('channelSections.addedChannels', { count: added })+ );+ }++ return failed;+ }),+ },+ { owner: labelDialogOwner() }+ );+ };+const setChannelLabel = (channelId: string,labelId: string | undefined,@@ -378,7 +458,10 @@ export function useChannelLabelActions(options: ChannelLabelActionsOptions) {? labels().find((label) => label.id === fromLabelId): undefined;- if (labelId && (!to || !canLabelChannel(labelChannelById(channelId), to))) {+ if (+ labelId &&+ (!to || !canAssignChannel(labelChannelById(channelId), to))+ ) {return;}@@ -495,6 +578,7 @@ export function useChannelLabelActions(options: ChannelLabelActionsOptions) {createLabel,createSmartTag,renameLabel,+ addChannelsToLabel,deleteLabel,setChannelLabel,markLabelRead,diff --git a/apps/web/src/features/channels-view/components/rail/hooks/useChannelSectionNotifications.ts b/apps/web/src/features/channels-view/components/rail/hooks/useChannelSectionNotifications.tsindex 03927d7179..55d5fb836c 100644--- a/apps/web/src/features/channels-view/components/rail/hooks/useChannelSectionNotifications.ts+++ b/apps/web/src/features/channels-view/components/rail/hooks/useChannelSectionNotifications.ts@@ -82,12 +82,11 @@ export function useChannelSectionNotifications(section === 'team_channels' ||section === 'direct_messages') {- // Named channels assigned to custom sections no longer belong to the- // built-in section. DMs remain in their built-in section as well.+ // Only All channels excludes custom-section assignments.const excludedIds =- section === 'direct_messages'- ? []- : options.labels().flatMap((label) => label.channelIds);+ section === 'channels'+ ? options.labels().flatMap((label) => label.channelIds)+ : [];return Telemetry.span('channels.section.members', () =>fetchChannelGroupIds(section, excludedIds, signal)diff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelLabelRows.tsx b/apps/web/src/features/channels-view/components/rail/next/ChannelLabelRows.tsxindex 630afd54a9..77b7ba5c48 100644--- a/apps/web/src/features/channels-view/components/rail/next/ChannelLabelRows.tsx+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelLabelRows.tsx@@ -1,3 +1,4 @@+import { ViewSidebar } from '@app/components/view-shell';import { t } from '@app/lib/i18n';import {ContextMenuContent,@@ -14,66 +15,30 @@ import PlusIcon from '@icon/system/regular/plus.svg';import TagIcon from '@icon/system/regular/tag.svg';import TagSimpleIcon from '@icon/system/regular/tag-simple.svg';import TrashIcon from '@icon/system/regular/trash.svg';+import UsersIcon from '@icon/system/regular/users.svg';import { ContextMenu } from '@kobalte/core/context-menu';import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';-import { createDroppable } from '@thisbeyond/solid-dnd';-import { Badge, cn } from '@ui';+import { Badge, Button, Tooltip } from '@ui';import { For, type JSX, Show } from 'solid-js';-import { canLabelChannel } from '../../../core/channel-label-eligibility';-import { ChannelLabelMenuItems as OriginalChannelLabelMenuItems } from '../ChannelLabelRows';import {- type ChannelLabelDropData,- rowKeyForLabel,- useChannelsRail,-} from '../ChannelsRailContext';+ canAssignChannel,+ canLabelChannel,+} from '../../../core/channel-label-eligibility';+import { ChannelLabelMenuItems as OriginalChannelLabelMenuItems } from '../ChannelLabelRows';+import { rowKeyForLabel, useChannelsRail } from '../ChannelsRailContext';import { useChannelRailLabelState } from '../hooks/useChannelRailState';+import { ChannelSectionEmptyState } from './ChannelSectionEmptyState';import { ChannelSectionHeading } from './ChannelSectionHeading';import {ChannelSectionContextMenu,ChannelSectionDropdown,} from './ChannelSectionMenu';-/** One drop target and highlight around the full custom section. */-export function ChannelLabelDropZone(props: {+/** A custom section with the same heading and controls as built-in sections. */+export function ChannelLabelRow(props: {label: ChannelLabel;- children: JSX.Element;+ dragHandle?: JSX.Element;}) {- const rail = useChannelsRail();- const droppable = createDroppable(- `${rail.railId}:channel-label:label:${props.label.id}`,- {- dragType: 'channel-label-target',- dndScope: rail.railId,- get target() {- return {- kind: props.label.rule ? ('smart-tag' as const) : ('label' as const),- labelId: props.label.id,- };- },- isDropTargetDisabled: () => !rail.labelsAvailable(),- } satisfies ChannelLabelDropData- );-- const isDropTarget = () => {- const target = rail.activeDropTarget();- return target?.kind === 'label' && target.labelId === props.label.id;- };-- return (- <div- ref={droppable.ref}- class={cn(- 'group/channel-label relative min-w-0 shrink-0 rounded-lg',- isDropTarget() && 'bg-selected ring-1 ring-inset ring-accent'- )}- >- {props.children}- </div>- );-}--/** A custom section with the same heading and controls as built-in sections. */-export function ChannelLabelRow(props: { label: ChannelLabel }) {const rail = useChannelsRail();const state = useChannelRailLabelState(() => props.label);@@ -85,7 +50,7 @@ export function ChannelLabelRow(props: { label: ChannelLabel }) {<ChannelSectionHeadingid={state().domId}label={props.label.name}- title={+ tooltip={props.label.rule? t('channelLabels.nameContains', {text: props.label.rule.contains,@@ -96,14 +61,46 @@ export function ChannelLabelRow(props: { label: ChannelLabel }) {focused={state().focused}unreadCount={state().unreadCount}onToggle={() => rail.activateRow(rowKeyForLabel(props.label.id))}+ dragHandle={props.dragHandle}badge={<Show when={props.label.teamId}>- <Badge variant="secondary" size="xs">- {t('channelSections.sharedShort')}- </Badge>+ <Tooltip+ as="span"+ class="shrink-0"+ label={t('channelSections.sharedSectionHint')}+ >+ <span class="hidden @[16rem]/rail-section:inline-flex">+ <Badge variant="secondary" size="xs">+ {t('channelSections.sharedShort')}+ </Badge>+ </span>+ <UsersIcon+ class="size-3.5 @[16rem]/rail-section:hidden"+ aria-label={t('channelSections.sharedShort')}+ />+ </Tooltip></Show>}>+ <Show when={!props.label.rule}>+ <ViewSidebar.Control+ variant="ghost"+ size="icon-sm"+ aria-label={t('channelSections.addChannelsTo', {+ name: props.label.name,+ })}+ tooltip={t('channelSections.addChannels')}+ disabled={!rail.labelsAvailable()}+ onClick={() =>+ fireAndForget(+ rail.addChannelsToLabel(props.label),+ 'channels-view'+ )+ }+ >+ <PlusIcon class="size-3.5" />+ </ViewSidebar.Control>+ </Show><ChannelSectionDropdownsection={rowKeyForLabel(props.label.id)}label={props.label.name}@@ -115,6 +112,53 @@ export function ChannelLabelRow(props: { label: ChannelLabel }) {);}+export function ChannelLabelEmptyState(props: { label: ChannelLabel }) {+ const rail = useChannelsRail();+ const section = () => rowKeyForLabel(props.label.id);+ const unreadOnly = () => rail.sectionPreferences(section()).unreadOnly;+ const message = () => {+ if (unreadOnly()) return t('channelSections.noUnreadConversations');++ if (props.label.rule) return t('channelSections.emptySmartSection');++ return t('channelSections.emptySection');+ };++ const actionLabel = () => {+ if (unreadOnly()) return t('channelSections.showAllChannels');++ if (props.label.rule) return t('channelSections.editRule');++ return t('channelSections.addChannels');+ };++ const act = () => {+ if (unreadOnly()) {+ rail.setSectionPreferences(section(), { unreadOnly: false });+ return;+ }++ const action = props.label.rule+ ? rail.renameLabel(props.label)+ : rail.addChannelsToLabel(props.label);+ fireAndForget(action, 'channels-view');+ };++ return (+ <ChannelSectionEmptyState>+ <p class="font-medium text-ink">{message()}</p>+ <Button+ variant="secondary"+ size="sm"+ disabled={!rail.labelsAvailable()}+ onClick={act}+ >+ {actionLabel()}+ </Button>+ </ChannelSectionEmptyState>+ );+}+function ChannelLabelActions(props: { label: ChannelLabel }) {const rail = useChannelsRail();@@ -122,6 +166,19 @@ function ChannelLabelActions(props: { label: ChannelLabel }) {<><MenuSeparator /><MenuGroup>+ <Show when={!props.label.rule}>+ <MenuItem+ icon={PlusIcon}+ text={t('channelSections.addChannels')}+ disabled={!rail.labelsAvailable()}+ onClick={() =>+ fireAndForget(+ rail.addChannelsToLabel(props.label),+ 'channels-view'+ )+ }+ />+ </Show><MenuItemicon={PencilSimpleIcon}text={@@ -159,7 +216,12 @@ function SectionMenuItems(props: { channel: ChannelEntity }) {const labels = () =>rail.labels()- .filter((label) => !label.rule && canLabelChannel(props.channel, label));+ .filter(+ (label) =>+ !label.rule &&+ (label.channelIds.includes(props.channel.id) ||+ canAssignChannel(props.channel, label))+ );return (<Showdiff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelSectionDropZone.tsx b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionDropZone.tsxnew file mode 100644index 0000000000..a12525bce2--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionDropZone.tsx@@ -0,0 +1,128 @@+import { t } from '@app/lib/i18n';+import ProhibitIcon from '@icon/system/regular/prohibit.svg';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';+import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';+import { cn } from '@ui';+import { createSignal, type JSX, Show } from 'solid-js';+import { channelSectionDropError } from '../../../core/channel-label-eligibility';+import type { ChannelSectionKey } from '../../../types';+import {+ type ChannelLabelDropData,+ useChannelsRail,+} from '../ChannelsRailContext';++/** Keep valid and blocked drop feedback around the whole section. */+export function ChannelSectionDropZone(props: {+ section: ChannelSectionKey;+ label?: ChannelLabel;+ children: JSX.Element;+}) {+ const rail = useChannelsRail();+ const [state] = useDragDropContext() ?? [];+ const [hovered, setHovered] = createSignal(false);+ const dropError = () => {+ const source = state?.active.draggable?.data;++ if (!source || source.dragType === 'channel-section') {+ return;+ }++ if (+ props.section === 'favorites' &&+ source.dndScope === `${rail.railId}:favorites`+ ) {+ return;+ }++ if (+ source.dragType !== 'channel-label' ||+ source.dndScope !== rail.railId ||+ typeof source.channelId !== 'string'+ ) {+ return t('channelSections.cannotDropHere');+ }++ if (!rail.labelsAvailable()) {+ return rail.labelsUnavailableReason();+ }++ const reason = channelSectionDropError({+ section: props.section,+ label: props.label,+ channel: rail.channelById(source.channelId),+ sourceLabelId:+ typeof source.labelId === 'string' ? source.labelId : undefined,+ });++ if (reason === 'smart') return t('channelSections.smartSectionDropHint');+ if (reason === 'team-only') return t('channelSections.sharedSectionHint');+ if (reason === 'already-present')+ return t('channelSections.alreadyInSection');+ if (reason) return t('channelSections.cannotDropHere');+ };+ const rejected = () => hovered() && dropError();+ const supportsDrop = () =>+ Boolean(props.label) ||+ props.section === 'team_channels' ||+ props.section === 'channels';+ const droppable = createDroppable(+ `${rail.railId}:channel-label:section:${props.section}`,+ {+ dragType: 'channel-label-target',+ dndScope: rail.railId,+ get target() {+ if (props.label) {+ return {+ kind: props.label.rule+ ? ('smart-tag' as const)+ : ('label' as const),+ labelId: props.label.id,+ };+ }++ return { kind: 'unlabelled' as const };+ },+ isDropTargetDisabled: () =>+ !supportsDrop() || !rail.labelsAvailable() || Boolean(dropError()),+ } satisfies ChannelLabelDropData+ );+ const isDropTarget = () => {+ if (dropError()) return false;++ const target = rail.activeDropTarget();+ if (target?.kind === 'label') return target.labelId === props.label?.id;++ return (+ target?.kind === 'unlabelled' &&+ !props.label &&+ supportsDrop() &&+ hovered()+ );+ };++ return (+ <div+ ref={droppable.ref}+ onPointerEnter={() => setHovered(true)}+ onPointerLeave={() => setHovered(false)}+ class={cn(+ 'group/channel-label relative min-w-0 shrink-0 rounded-lg',+ isDropTarget() && 'bg-selected ring-1 ring-inset ring-accent',+ rejected() && 'cursor-not-allowed [&_*]:cursor-not-allowed!'+ )}+ >+ {props.children}+ <Show when={rejected()}>+ {(reason) => (+ <div+ role="status"+ class="pointer-events-none absolute inset-0 z-20 flex items-center justify-center gap-2 rounded-lg bg-surface/90 px-3 py-2 text-xs text-ink-muted ring-1 ring-inset ring-edge-muted"+ >+ <ProhibitIcon class="size-4 shrink-0" />+ <span>{reason()}</span>+ </div>+ )}+ </Show>+ </div>+ );+}diff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelSectionEmptyState.tsx b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionEmptyState.tsxnew file mode 100644index 0000000000..c3beecd911--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionEmptyState.tsx@@ -0,0 +1,11 @@+import type { JSX } from 'solid-js';++export function ChannelSectionEmptyState(props: { children: JSX.Element }) {+ return (+ <div class="px-2 py-2">+ <div class="flex flex-col items-start gap-2 rounded-lg border border-edge-muted bg-surface p-3 text-xs leading-relaxed text-ink-muted">+ {props.children}+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelSectionHeading.tsx b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionHeading.tsxindex bcdbc1078a..76879de575 100644--- a/apps/web/src/features/channels-view/components/rail/next/ChannelSectionHeading.tsx+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionHeading.tsx@@ -1,32 +1,47 @@import { CollapsibleSection } from '@app/components/view-shell';-import { cn } from '@ui';+import { t } from '@app/lib/i18n';+import DotsSixVerticalIcon from '@icon/system/regular/dots-six-vertical.svg';+import { createDraggable } from '@thisbeyond/solid-dnd';+import { Button, cn, Tooltip } from '@ui';import { type JSX, Show } from 'solid-js';+import type { ChannelSectionKey } from '../../../types';+import type { useSectionReorder } from './useSectionReorder';/** Shared heading for built-in and custom Chat sections. */export function ChannelSectionHeading(props: {id: string;label: string;- title?: string;+ tooltip?: string;open: boolean;focused: boolean;unreadCount: number;onToggle: () => void;badge?: JSX.Element;+ dragHandle?: JSX.Element;children?: JSX.Element;}) {return (<CollapsibleSection.Root open={props.open} onOpenChange={props.onToggle}><CollapsibleSection.Header- class={cn('rounded-lg pr-0', props.focused && 'bg-hover text-ink')}+ class={cn(+ 'relative rounded-lg pr-0',+ props.focused && 'bg-hover text-ink'+ )}>+ {props.dragHandle}<CollapsibleSection.Triggerid={props.id}role="treeitem"tabIndex={-1}- title={props.title}class={cn('flex-1', props.focused && 'text-ink')}>- <span class="min-w-0 truncate">{props.label}</span>+ <Tooltip+ as="span"+ class="relative z-20 min-w-0"+ label={props.tooltip ?? props.label}+ >+ <span class="truncate">{props.label}</span>+ </Tooltip>{props.badge}<CollapsibleSection.Indicator /><Show when={props.unreadCount > 0}>@@ -38,3 +53,55 @@ export function ChannelSectionHeading(props: {</CollapsibleSection.Root>);}++/** Keep disclosure clicks separate from section dragging and keyboard reordering. */+export function ChannelSectionDragHandle(props: {+ section: ChannelSectionKey;+ label: string;+ reorder: ReturnType<typeof useSectionReorder>;+}) {+ const draggable = createDraggable(`${props.reorder.scope}:${props.section}`, {+ dragType: 'channel-section',+ dndScope: props.reorder.scope,+ section: props.section,+ get name() {+ return props.label;+ },+ overlayContent: () => (+ <div class="w-56 p-1">+ <div class="flex min-w-0 items-center gap-2 text-xs font-medium text-ink">+ <DotsSixVerticalIcon class="size-3.5 shrink-0 text-ink-muted" />+ <span class="truncate">{props.label}</span>+ </div>+ <p class="mt-2 border-t border-edge-muted pt-2 text-xs text-ink-muted">+ {t('channelSections.reorderingSection')}+ </p>+ </div>+ ),+ });++ return (+ <Button+ ref={draggable.ref}+ {...draggable.dragActivators}+ variant="ghost"+ size="icon-xs"+ class="absolute -left-(--sidebar-gutter) top-1 z-10 cursor-grab opacity-0 group-hover/rail-section:opacity-100 focus-visible:opacity-100 active:cursor-grabbing"+ aria-label={t('channelSections.reorderSection', { name: props.label })}+ tooltip={t('channelSections.reorderSectionHint')}+ onClick={(event: MouseEvent) => event.stopPropagation()}+ onKeyDown={(event: KeyboardEvent) => {+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {+ return;+ }++ event.preventDefault();+ event.stopPropagation();+ event.stopImmediatePropagation();+ props.reorder.move(props.section, event.key === 'ArrowUp' ? -1 : 1);+ }}+ >+ <DotsSixVerticalIcon class="size-3 -translate-x-1" />+ </Button>+ );+}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.tsxindex 7028ffe77f..bdfbcd133b 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@@ -1,3 +1,5 @@+import { createDragAutoScroll } from '@app/components/drag-drop/create-drag-auto-scroll';+import { createLayoutAnimation } from '@app/components/drag-drop/create-layout-animation';import { SearchBar, ViewSidebar } from '@app/components/view-shell';import { SlackImportSidebar } from '@app/features/slack-import/slack-import-sidebar';import { t } from '@app/lib/i18n';@@ -7,6 +9,7 @@ import type { ChannelEntity } from '@entity';import { queryReadyGate } from '@queries/gate';import { useCurrentTeamQuery } from '@queries/team/teams';import { createElementSize } from '@solid-primitives/resize-observer';+import { createDroppable, useDragDropContext } from '@thisbeyond/solid-dnd';import { Button } from '@ui';import { tourTarget } from '@ui/components/Tour';import {@@ -15,6 +18,7 @@ import {createMemo,createSignal,For,+ type JSX,Match,on,onCleanup,@@ -49,14 +53,20 @@ import {groupChannelRailSections,} from './build-channel-rail-rows';import { ChannelFavoriteRow } from './ChannelFavoriteRow';-import { ChannelLabelDropZone, ChannelLabelRow } from './ChannelLabelRows';-import { ChannelSectionHeading } from './ChannelSectionHeading';+import { ChannelLabelEmptyState, ChannelLabelRow } from './ChannelLabelRows';+import { ChannelSectionDropZone } from './ChannelSectionDropZone';+import { ChannelSectionEmptyState } from './ChannelSectionEmptyState';+import {+ ChannelSectionDragHandle,+ ChannelSectionHeading,+} from './ChannelSectionHeading';import {ChannelSectionContextMenu,ChannelSectionDropdown,} from './ChannelSectionMenu';import { ResizableRailSection } from './ResizableRailSection';import { useFavoriteReorder } from './useFavoriteReorder';+import { useSectionReorder } from './useSectionReorder';type ChannelRailSearch = {isOpen: Accessor<boolean>;@@ -143,7 +153,10 @@ function ExpandedHeader(props: { search: ChannelRailSearch }) {);}-function SectionHeading(props: { group: 'favorites' | ChannelsGroup }) {+function SectionHeading(props: {+ group: 'favorites' | ChannelsGroup;+ dragHandle?: JSX.Element;+}) {const rail = useChannelsRail();const team = useCurrentTeamQuery(() => props.group === 'team_channels');const title = () => {@@ -155,6 +168,9 @@ function SectionHeading(props: { group: 'favorites' | ChannelsGroup }) {}}+ if (props.group === 'channels') {+ return t('channelSections.allChannels');+ }return t(`channelSections.${props.group}`);};@@ -171,11 +187,12 @@ function SectionHeading(props: { group: 'favorites' | ChannelsGroup }) {<ChannelSectionContextMenu section={props.group}><ChannelSectionHeadingid={domIdForRow(rail.railId, key())}- title={title()}+ tooltip={title()}label={title()}open={open()}focused={rail.list.focus.key() === key()}unreadCount={unreadCount()}+ dragHandle={props.dragHandle}onToggle={() => rail.toggleGroup(props.group)}><ChannelSectionDropdown section={props.group} label={title()} />@@ -216,11 +233,11 @@ function SectionStatus(props: { group: ChannelsGroup }) {</Button></Match><Match when={!hasConversations()}>- <p class="px-(--sidebar-item-inset) py-2 text-xs text-ink-extra-muted">+ <ChannelSectionEmptyState>{rail.sectionPreferences(props.group).unreadOnly? t('channelSections.noUnreadConversations'): t('channelSections.empty')}- </p>+ </ChannelSectionEmptyState></Match></Switch></div>@@ -230,18 +247,24 @@ function SectionStatus(props: { group: ChannelsGroup }) {function BrowseRow(props: {row: ChannelRailRow;favoriteReorder: ReturnType<typeof useFavoriteReorder>;+ dragHandle?: JSX.Element;}) {const rail = useChannelsRail();return (<divclassList={{- 'pl-2': props.row.kind !== 'section' && props.row.kind !== 'label',+ 'pl-2':+ props.row.kind === 'favorite' ||+ props.row.kind === 'conversation' ||+ props.row.kind === 'reference-status',}}><Switch><Match when={props.row.kind === 'section' ? props.row : undefined}>- {(row) => <SectionHeading group={row().group} />}+ {(row) => (+ <SectionHeading group={row().group} dragHandle={props.dragHandle} />+ )}</Match><Match when={props.row.kind === 'status' ? props.row : undefined}>{(row) => <SectionStatus group={row().group} />}@@ -261,7 +284,12 @@ function BrowseRow(props: {)}</Match><Match when={props.row.kind === 'label' ? props.row : undefined}>- {(row) => <ChannelLabelRow label={row().label} />}+ {(row) => (+ <ChannelLabelRow+ label={row().label}+ dragHandle={props.dragHandle}+ />+ )}</Match><Match when={props.row.kind === 'favorite' ? props.row : undefined}>{(row) => (@@ -287,6 +315,7 @@ function BrowseRow(props: {}type SectionHandle = {+ layout?: HTMLDivElement;root?: HTMLDivElement;virtualizer?: VirtualizerHandle;};@@ -296,6 +325,7 @@ function BrowseSection(props: {section: ChannelRailSectionRows;maxHeight: number;favoriteReorder: ReturnType<typeof useFavoriteReorder>;+ sectionReorder: ReturnType<typeof useSectionReorder>;register: (key: ChannelSectionKey, handle: SectionHandle) => () => void;}) {const rail = useChannelsRail();@@ -303,10 +333,22 @@ function BrowseSection(props: {const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();const size = createElementSize(scrollRoot);+ const droppable = createDroppable(+ `${props.sectionReorder.scope}:${props.sectionKey}`,+ {+ dragType: 'channel-section-target',+ dndScope: props.sectionReorder.scope,+ section: props.sectionKey,+ }+ );onCleanup(props.register(props.sectionKey, handle));const heading = () => props.section.heading;+ const customLabel = () => {+ const row = heading();+ return row.kind === 'label' ? row.label : undefined;+ };const open = () => {const row = heading();return row.kind === 'label'@@ -314,8 +356,16 @@ function BrowseSection(props: {: rail.isGroupOpen(row.group);};+ const itemCount = () =>+ props.section.rows.filter(+ (row) => row.kind === 'conversation' || row.kind === 'favorite'+ ).length;+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}`);@@ -383,13 +433,12 @@ function BrowseSection(props: {label={label()}open={open()}maxHeight={props.maxHeight}- itemCount={- props.section.rows.filter(- (row) => row.kind === 'conversation' || row.kind === 'favorite'- ).length- }+ dropEdge={props.sectionReorder.dropEdge(props.sectionKey)}+ dragging={props.sectionReorder.isDragging(props.sectionKey)}+ itemCount={itemCount()}rootRef={(element) => {handle.root = element;+ droppable.ref(element);}}scrollRef={(element) => {setScrollRoot(element);@@ -401,15 +450,32 @@ function BrowseSection(props: {}}}header={- <BrowseRow row={heading()} favoriteReorder={props.favoriteReorder} />+ <BrowseRow+ row={heading()}+ favoriteReorder={props.favoriteReorder}+ dragHandle={+ <ChannelSectionDragHandle+ section={props.sectionKey}+ label={label()}+ reorder={props.sectionReorder}+ />+ }+ />}><Showwhen={props.section.rows.length > 0}fallback={- <p class="py-2 pr-2 pl-4 text-xs text-ink-extra-muted">- {emptyMessage()}- </p>+ <Show+ when={customLabel()}+ fallback={+ <ChannelSectionEmptyState>+ {emptyMessage()}+ </ChannelSectionEmptyState>+ }+ >+ {(label) => <ChannelLabelEmptyState label={label()} />}+ </Show>}><Virtualizer@@ -433,18 +499,16 @@ function BrowseSection(props: {);return (- <Show- when={- props.section.heading.kind === 'label'- ? props.section.heading.label- : undefined- }- fallback={content}+ <div+ class="min-w-0 shrink-0"+ ref={(element) => {+ handle.layout = element;+ }}>- {(label) => (- <ChannelLabelDropZone label={label()}>{content}</ChannelLabelDropZone>- )}- </Show>+ <ChannelSectionDropZone section={props.sectionKey} label={customLabel()}>+ {content}+ </ChannelSectionDropZone>+ </div>);}@@ -457,6 +521,48 @@ function ExpandedBrowse() {);const keys = createMemo(() => [...sections().keys()]);const handles = new Map<ChannelSectionKey, SectionHandle>();+ const motion = createLayoutAnimation({+ viewport: scrollRoot,+ items: () =>+ [...handles].flatMap(([key, handle]) =>+ handle.root && handle.layout+ ? [{ key, element: handle.root, layout: handle.layout }]+ : []+ ),+ });+ onCleanup(motion.cancel);++ const sectionReorder = useSectionReorder(keys, (reorder) => {+ const finish = motion.beginHover();++ try {+ reorder();+ } finally {+ finish();+ }+ });+ const [dragState, dragActions] = useDragDropContext() ?? [];+ createDragAutoScroll({+ getViewport: () => {+ const scope = dragState?.active.draggable?.data.dndScope;++ if (+ scope === rail.railId ||+ scope === sectionReorder.scope ||+ scope === `${rail.railId}:favorites`+ ) {+ return scrollRoot();+ }+ },+ axis: 'y',+ });++ // Wheel scrolling changes nested drop target positions during a drag too.+ const updateDropTarget = () => {+ if (dragState?.active.draggable) {+ dragActions?.detectCollisions();+ }+ };const favoriteReorder = useFavoriteReorder(() =>sections()@@ -528,7 +634,8 @@ function ExpandedBrowse() {<div class="flex min-h-0 flex-1 flex-col"><divref={setScrollRoot}- class="scrollbar-hidden flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-(--sidebar-gutter)"+ class="scrollbar-hidden flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto px-(--sidebar-gutter) [&:has([data-resizing])]:[overflow-anchor:none]"+ on:scroll={{ capture: true, handleEvent: updateDropTarget }}><For each={keys()}>{(key) => (@@ -542,6 +649,7 @@ function ExpandedBrowse() {(scrollSize.height ?? 300) - 48)}favoriteReorder={favoriteReorder}+ sectionReorder={sectionReorder}register={register}/>)}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.tsxindex fc18e7346a..7e5330870f 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,6 +1,7 @@import { t } from '@app/lib/i18n';import { useUserId } from '@core/context/user';import { createElementSize } from '@solid-primitives/resize-observer';+import { cn, Tooltip } from '@ui';import { createMemo, createSignal, type JSX, onCleanup, Show } from 'solid-js';import {CHANNEL_SECTION_MAX_HEIGHT,@@ -19,6 +20,8 @@ export function ResizableRailSection(props: {open: boolean;maxHeight: number;itemCount: number;+ dropEdge?: 'top' | 'bottom';+ dragging?: boolean;header: JSX.Element;children: JSX.Element;rootRef: (element: HTMLDivElement) => void;@@ -36,8 +39,9 @@ export function ResizableRailSection(props: {Math.min(CHANNEL_SECTION_MAX_HEIGHT,props.maxHeight,- contentSize.height ??- Math.max(1, props.itemCount) * CHANNEL_SECTION_ROW_HEIGHT+ contentSize.height && contentSize.height > 0+ ? contentSize.height+ : Math.max(1, props.itemCount) * CHANNEL_SECTION_ROW_HEIGHT);const resizable = () =>props.itemCount > CHANNEL_SECTION_MIN_ITEMS &&@@ -70,18 +74,34 @@ export function ResizableRailSection(props: {y: number;height: number;zoom: number;+ top: number;+ handle: HTMLButtonElement;account: ReturnType<typeof account>;}| undefined;+ const draggedHeight = (event: PointerEvent) => {+ 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);+ };const finish = (event: PointerEvent, cancelled = false) => {if (!drag || event.pointerId !== drag.pointer) {return;}const current = drag;+ const nextHeight = draggedHeight(event);drag = undefined;+ if (current.handle.hasPointerCapture?.(current.pointer)) {+ current.handle.releasePointerCapture(current.pointer);+ }+if (!cancelled &&props.open &&@@ -89,9 +109,7 @@ export function ResizableRailSection(props: {current.account === account()) {rail.setSectionPreferences(props.section, {- height: clamp(- current.height + (event.clientY - current.y) / current.zoom- ),+ height: nextHeight,});}@@ -99,7 +117,26 @@ export function ResizableRailSection(props: {};return (- <div ref={props.rootRef} class="min-w-0 shrink-0">+ <div+ ref={props.rootRef}+ class={cn(+ '@container/rail-section group/rail-section relative min-w-0 shrink-0',+ props.dragging &&+ 'rounded-lg bg-surface opacity-40 ring-1 ring-edge-muted'+ )}+ data-resizing={preview() !== undefined ? '' : undefined}+ >+ <Show when={props.dropEdge}>+ {(edge) => (+ <div+ class="pointer-events-none absolute inset-x-0 z-10 h-0.5 rounded-full bg-accent"+ classList={{+ 'top-0': edge() === 'top',+ 'bottom-0': edge() === 'bottom',+ }}+ />+ )}+ </Show>{props.header}<Show when={props.open}><div@@ -122,80 +159,87 @@ export function ResizableRailSection(props: {});return (- <button- type="button"- role="separator"- aria-orientation="horizontal"- aria-label={t('channelSections.resizeSection', {- name: props.label,- })}- aria-valuemin={CHANNEL_SECTION_MIN_HEIGHT}- aria-valuemax={maximum()}- aria-valuenow={Math.round(height())}- title={t('channelSections.resizeSectionHint')}- class="group flex h-3 w-full touch-none cursor-row-resize items-center justify-center outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-edge-focus"- onPointerDown={(event) => {- const element = viewport();- if (event.button !== 0 || !element || drag) {- return;- }-- event.preventDefault();- event.stopPropagation();- drag = {- pointer: event.pointerId,- y: event.clientY,- height: element.offsetHeight,- zoom:- element.getBoundingClientRect().height /- element.offsetHeight || 1,- account: account(),- };- event.currentTarget.setPointerCapture(event.pointerId);- }}- onPointerMove={(event) => {- if (!drag || event.pointerId !== drag.pointer) {- return;+ <Tooltip.Root>+ <Tooltip.Trigger+ type="button"+ role="separator"+ aria-orientation="horizontal"+ aria-label={t('channelSections.resizeSection', {+ name: props.label,+ })}+ aria-valuemin={CHANNEL_SECTION_MIN_HEIGHT}+ aria-valuemax={maximum()}+ aria-valuenow={Math.round(height())}+ class="group flex h-3 w-full touch-none cursor-row-resize items-center justify-center rounded-full outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-edge-focus"+ onPointerDown={(event) => {+ const element = viewport();+ if (event.button !== 0 || !element || drag) {+ return;+ }++ event.preventDefault();+ event.stopPropagation();+ drag = {+ pointer: event.pointerId,+ y: event.clientY,+ height: element.offsetHeight,+ zoom:+ element.getBoundingClientRect().height /+ element.offsetHeight || 1,+ account: account(),+ top: element.getBoundingClientRect().top,+ handle: event.currentTarget,+ };+ setPreview(element.offsetHeight);+ event.currentTarget.setPointerCapture(event.pointerId);+ }}+ onPointerMove={(event) => {+ if (!drag || event.pointerId !== drag.pointer) {+ return;+ }++ if (drag.account !== account()) {+ finish(event, true);+ return;+ }++ setPreview(draggedHeight(event));+ }}+ onPointerUp={(event) => finish(event)}+ onPointerCancel={(event) => finish(event, true)}+ onLostPointerCapture={(event) => finish(event, true)}+ onMouseDown={(event) => event.stopPropagation()}+ onClick={(event) => event.stopPropagation()}+ onDblClick={() =>+ rail.setSectionPreferences(props.section, {+ height: undefined,+ })}-- if (drag.account !== account()) {- finish(event, true);- return;- }-- setPreview(- clamp(drag.height + (event.clientY - drag.y) / drag.zoom)- );- }}- onPointerUp={(event) => finish(event)}- onPointerCancel={(event) => finish(event, true)}- onLostPointerCapture={(event) => finish(event, true)}- onMouseDown={(event) => event.stopPropagation()}- onClick={(event) => event.stopPropagation()}- onDblClick={() =>- rail.setSectionPreferences(props.section, {- height: undefined,- })- }- onKeyDown={(event) => {- if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {- return;- }-- event.preventDefault();- event.stopPropagation();- event.stopImmediatePropagation();-- const direction = event.key === 'ArrowDown' ? 1 : -1;- const step = event.shiftKey ? 100 : 20;-- rail.setSectionPreferences(props.section, {- height: clamp(height() + direction * step),- });- }}- >- <span class="h-0.5 w-8 rounded-full bg-edge-muted group-hover:bg-accent group-focus-visible:bg-accent" />- </button>+ onKeyDown={(event) => {+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {+ return;+ }++ event.preventDefault();+ event.stopPropagation();+ event.stopImmediatePropagation();++ const direction = event.key === 'ArrowDown' ? 1 : -1;+ const step = event.shiftKey ? 100 : 20;++ rail.setSectionPreferences(props.section, {+ height: clamp(height() + direction * step),+ });+ }}+ >+ <span class="h-0.5 w-8 rounded-full bg-edge-muted group-hover:bg-accent group-focus-visible:bg-accent" />+ </Tooltip.Trigger>+ <Tooltip.Portal>+ <Tooltip.Content>+ {t('channelSections.resizeSectionHint')}+ </Tooltip.Content>+ </Tooltip.Portal>+ </Tooltip.Root>);}}</Show>diff --git a/apps/web/src/features/channels-view/components/rail/next/SectionChannelsDialog.tsx b/apps/web/src/features/channels-view/components/rail/next/SectionChannelsDialog.tsxnew file mode 100644index 0000000000..0f8932da17--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/next/SectionChannelsDialog.tsx@@ -0,0 +1,290 @@+import { t } from '@app/lib/i18n';+import { fireAndForget } from '@core/util/fireAndForget';+import { createFreshSearch, NAME_MATCH_RANKING } from '@core/util/freshSort';+import HashIcon from '@icon/system/regular/hash.svg';+import LockIcon from '@icon/system/regular/lock-simple.svg';+import { useAvailableSectionChannelsQuery } from '@queries/channel-labels/channel-labels';+import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';+import {+ Button,+ Checkbox,+ Dialog,+ Input,+ type ManagedDialogProps,+ type OpenDialogOptions,+ openDialog,+ Surface,+} from '@ui';+import {+ createMemo,+ createSignal,+ For,+ Match,+ onCleanup,+ Show,+ Switch,+} from 'solid-js';++const searchChannels = createFreshSearch<ApiChannelWithLatest>({+ config: {+ ...NAME_MATCH_RANKING,+ fuzzyWeight: 1,+ timeWeight: 0,+ brevityWeight: 0,+ },+ getName: (channel) => channel.name ?? '',+ getTimestamp: (channel) => ({ updatedAt: channel.updated_at }),+});++type SectionChannelsDialogProps = {+ label: ChannelLabel;+ onConfirm: (channelIds: string[]) => Promise<string[]>;+};++/** Select additions only; membership removal stays in the channel's section menu. */+function SectionChannelsDialog(+ props: SectionChannelsDialogProps & ManagedDialogProps+) {+ const query = useAvailableSectionChannelsQuery();+ const [search, setSearch] = createSignal('');+ const [selected, setSelected] = createSignal(new Set<string>());+ const [added, setAdded] = createSignal(new Set<string>());+ const [saving, setSaving] = createSignal(false);+ const [error, setError] = createSignal('');++ let disposed = false;+ onCleanup(() => {+ disposed = true;+ });++ const available = createMemo(() => {+ if (query.isPending) {+ return [];+ }++ return (query.data ?? [])+ .filter((channel) => {+ if (+ !channel.is_participant ||+ props.label.channelIds.includes(channel.id) ||+ added().has(channel.id)+ ) {+ return false;+ }++ if (props.label.teamId) {+ return (+ channel.channel_type === 'team' &&+ channel.team_id === props.label.teamId+ );+ }++ return (+ channel.channel_type === 'team' ||+ channel.channel_type === 'public' ||+ channel.channel_type === 'private'+ );+ })+ .sort((left, right) => (left.name ?? '').localeCompare(right.name ?? ''));+ });+ const visible = createMemo(() =>+ searchChannels(available(), search()).map((result) => result.item)+ );+ const chosen = () =>+ available()+ .filter((channel) => selected().has(channel.id))+ .map((channel) => channel.id);++ const toggleChannel = (id: string, checked: boolean) => {+ setSelected((current) => {+ const next = new Set(current);+ if (checked) {+ next.add(id);+ } else {+ next.delete(id);+ }++ return next;+ });+ };++ const submit = async (event: SubmitEvent) => {+ event.preventDefault();+ const ids = chosen();++ if (saving() || ids.length === 0) {+ return;+ }++ setSaving(true);+ setError('');++ try {+ const failed = await props.onConfirm(ids);++ if (disposed) {+ return;+ }++ if (failed.length === 0) {+ props.onOpenChange(false);+ return;+ }++ const failures = new Set(failed);+ setAdded(+ (previous) =>+ new Set([...previous, ...ids.filter((id) => !failures.has(id))])+ );+ setSelected(failures);+ setError(+ t('channelSections.addChannelsFailed', { count: failed.length })+ );+ } catch {+ if (!disposed) {+ setError(t('channelSections.unavailable'));+ }+ } finally {+ if (!disposed) {+ setSaving(false);+ }+ }+ };++ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => {+ if (!saving()) {+ props.onOpenChange(open);+ }+ }}+ class="w-[min(36rem,90vw)]"+ visibleScrim+ >+ <Surface+ depth={2}+ class="flex max-h-[min(30rem,65dvh)] flex-col overflow-hidden rounded-xl text-ink"+ >+ <form+ class="flex min-h-0 flex-col"+ onSubmit={(event) => fireAndForget(submit(event), 'channels-view')}+ aria-busy={saving()}+ >+ <div class="flex shrink-0 flex-col gap-2 px-5 pt-4 pb-3">+ <Dialog.Title class="text-base font-semibold">+ {t('channelSections.addChannelsTo', { name: props.label.name })}+ </Dialog.Title>+ <Dialog.Description class="text-xs leading-4 text-ink-muted">+ {props.label.teamId+ ? t('channelSections.addSharedChannelsHint')+ : t('channelSections.addPersonalChannelsHint')}+ </Dialog.Description>+ <Input+ aria-label={t('channelSections.searchChannels')}+ placeholder={t('channelSections.searchChannels')}+ value={search()}+ onInput={(event) => setSearch(event.currentTarget.value)}+ readOnly={saving()}+ />+ </div>+ <div+ class="min-h-0 overflow-y-auto px-3"+ aria-busy={query.isFetching}+ >+ <Switch>+ <Match when={query.isPending}>+ <p class="px-2 py-4 text-sm text-ink-muted">+ {t('channelSections.loadingChannels')}+ </p>+ </Match>+ <Match when={visible().length > 0}>+ <For each={visible()}>+ {(channel) => (+ <Checkbox+ class="flex w-full gap-2 rounded-lg px-2 py-2 hover:bg-hover"+ checked={selected().has(channel.id)}+ disabled={saving()}+ onChange={(checked) => toggleChannel(channel.id, checked)}+ >+ <Checkbox.Control />+ <Checkbox.Label class="flex min-w-0 flex-1 items-center gap-2 text-sm">+ <Show+ when={channel.channel_type === 'private'}+ fallback={+ <HashIcon class="size-4 shrink-0 text-ink-muted" />+ }+ >+ <LockIcon class="size-4 shrink-0 text-ink-muted" />+ </Show>+ <span class="truncate">+ {channel.name ?? t('channelSections.unnamedChannel')}+ </span>+ </Checkbox.Label>+ </Checkbox>+ )}+ </For>+ </Match>+ <Match when={!query.isError}>+ <p class="px-2 py-4 text-sm text-ink-muted">+ {search().trim()+ ? t('channelSections.noMatchingChannels')+ : t('channelSections.noChannelsToAdd')}+ </p>+ </Match>+ </Switch>+ <Show when={query.isError}>+ <div class="flex items-center justify-between gap-2 px-2 py-3 text-xs text-ink-muted">+ {t('channelSections.channelsUnavailable')}+ <Button+ variant="ghost"+ size="sm"+ onClick={() =>+ fireAndForget(query.refetch(), 'channels-view')+ }+ >+ {t('channelSections.retry')}+ </Button>+ </div>+ </Show>+ </div>+ <Show when={error()}>+ <p role="alert" class="px-5 pt-3 text-xs text-failure">+ {error()}+ </p>+ </Show>+ <div class="flex shrink-0 justify-end gap-2 px-5 py-3">+ <Button+ type="button"+ variant="ghost"+ disabled={saving()}+ onClick={() => props.onOpenChange(false)}+ >+ {t('channelSections.cancel')}+ </Button>+ <Button+ type="submit"+ variant="primary"+ disabled={saving() || chosen().length === 0}+ >+ {saving()+ ? t('channelSections.saving')+ : t('channelSections.addSelectedChannels', {+ count: chosen().length,+ })}+ </Button>+ </div>+ </form>+ </Surface>+ </Dialog>+ );+}++export async function promptSectionChannels(+ props: SectionChannelsDialogProps,+ options?: OpenDialogOptions+): Promise<void> {+ const handle = openDialog(SectionChannelsDialog, props, options);+ await handle.closed;+}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.tsxindex 18dae344f4..fadb9f30f9 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@@ -7,14 +7,23 @@ import type { ChannelLabelScopeSelection } from '@service-storage/generated/scheimport {Button,Dialog,+ HoverCard,Input,type ManagedDialogProps,type OpenDialogOptions,openDialog,Surface,ToggleSwitch,+ Tooltip,} from '@ui';-import { type Accessor, createSignal, For, Show } from 'solid-js';+import {+ type Accessor,+ createSignal,+ For,+ Match,+ Show,+ Switch,+} from 'solid-js';export type SectionDialogValue = {name: string;@@ -31,88 +40,98 @@ export type SectionDialogProps = {function SmartSectionPreview(props: {pattern: Accessor<string>;- scope: ChannelLabelScopeSelection;+ scope: Accessor<ChannelLabelScopeSelection>;}) {const preview = useSmartTagPreviewQuery(props.pattern, props.scope);- const data = () => (preview.isSuccess ? preview.data : undefined);+ const data = () => (!preview.isPending ? preview.data : undefined);+ const count = () => data()?.totalCount ?? 0;const matches = () => data()?.channels ?? [];- const totalCount = () => data()?.totalCount ?? 0;- const overflowCount = () => totalCount() - matches().length;+ const overflow = () => count() - matches().length;++ const retry = (+ <Button+ type="button"+ variant="ghost"+ size="xs"+ onClick={() => fireAndForget(preview.refetch(), 'channels-view')}+ >+ {t('channelSections.retry')}+ </Button>+ );return (- <section- aria-label={t('channelSections.matchedChannels')}+ <divaria-live="polite"- class="flex shrink-0 flex-col gap-0.5 text-sm"+ aria-busy={preview.isFetching}+ class="text-xs text-ink-muted">- <div class="flex items-center gap-1.5 px-2 py-1 text-xs font-medium text-ink-muted">- <HashIcon class="size-3.5 shrink-0" aria-hidden="true" />- <span>{t('channelSections.matchedChannels')}</span>- <Show when={data()}>- <span class="tabular-nums">{totalCount()}</span>- </Show>- </div>- <Show- when={!preview.isPending}- fallback={- <p class="px-2 py-2 text-xs text-ink-muted">- {t('channelSections.matchingChannelsLoading')}- </p>- }- >- <Show- when={!preview.isError}- fallback={- <div class="flex items-center justify-between gap-2 px-2 py-1 text-xs text-ink-muted">- <span>{t('channelSections.matchesUnavailable')}</span>- <Button- type="button"- variant="ghost"- size="sm"- onClick={() =>- fireAndForget(preview.refetch(), 'channels-view')- }- >- {t('channelSections.retry')}- </Button>- </div>- }- >- <Show- when={totalCount()}- fallback={- <p class="px-2 py-2 text-xs text-ink-muted">- {t('channelSections.noMatchingChannels')}- </p>+ <Switch>+ <Match when={preview.isPending}>+ {t('channelSections.matchingChannelsLoading')}+ </Match>+ <Match when={data()}>+ <HoverCard+ as="button"+ placement="bottom-start"+ triggerAriaLabel={t('channelSections.matchCount', {+ count: count(),+ })}+ triggerClass="underline decoration-dotted underline-offset-4"+ contentClass="block min-w-56 max-w-80"+ content={+ <div>+ <Show+ when={count() > 0}+ fallback={+ <p class="p-2">+ {props.scope() === 'team'+ ? t('channelSections.noMatchingTeamChannels')+ : t('channelSections.noMatchingChannels')}+ </p>+ }+ >+ <ul class="max-h-48 overflow-y-auto">+ <For each={matches()}>+ {(channel) => (+ <li class="flex min-w-0 items-center gap-2 p-2">+ <HashIcon class="size-3.5 shrink-0" />+ <Tooltip+ as="span"+ class="min-w-0"+ label={channel.name}+ >+ <span class="truncate">{channel.name}</span>+ </Tooltip>+ </li>+ )}+ </For>+ </ul>+ <Show when={overflow() > 0}>+ <p class="p-2">+ {t('channelSections.moreChannelsMatched', {+ count: overflow(),+ })}+ </p>+ </Show>+ </Show>+ </div>}>- <ul class="flex max-h-48 flex-col overflow-y-auto scrollbar-hidden">- <For each={matches()}>- {(channel) => (- <li- class="flex min-w-0 items-center gap-2 px-2 py-2"- title={channel.name}- >- <HashIcon- class="size-4 shrink-0 text-ink-muted"- aria-hidden="true"- />- <span class="truncate">{channel.name}</span>- </li>- )}- </For>- </ul>- <Show when={overflowCount() > 0}>- <p class="px-2 py-2 text-xs text-ink-muted">- {t('channelSections.moreChannelsMatched', {- count: overflowCount(),- })}- </p>- </Show>+ {t('channelSections.matchCount', { count: count() })}+ </HoverCard>+ <Show when={preview.isError}>+ <span class="ml-2">{t('channelSections.matchesUnavailable')}</span>+ {retry}</Show>- </Show>- </Show>- </section>+ </Match>+ <Match when={preview.isError}>+ <div class="flex items-center gap-2">+ {t('channelSections.matchesUnavailable')}+ {retry}+ </div>+ </Match>+ </Switch>+ </div>);}@@ -241,13 +260,9 @@ function SectionDialog(props: SectionDialogProps & ManagedDialogProps) {/></Show><Show when={kind() === 'smart'}>- <label class="flex flex-wrap items-center gap-x-3 gap-y-2 text-sm text-ink-muted focus-within:text-ink">- <span class="shrink-0">- {t('channelSections.nameContains')}- </span>+ <label class="flex flex-col gap-2 text-sm text-ink-muted">+ <span>{t('channelSections.nameContains')}</span><Input- variant="bare"- class="min-w-40 flex-1 px-0 text-sm"value={pattern()}onInput={(event) => setPattern(event.currentTarget.value)}maxLength={200}@@ -262,15 +277,13 @@ function SectionDialog(props: SectionDialogProps & ManagedDialogProps) {</p></Show><Show when={kind() === 'smart' && trimmedPattern().length > 0}>- <Show when={scope()} keyed>- {(selectedScope) => (- <SmartSectionPreview- pattern={trimmedPattern}- scope={selectedScope}- />- )}- </Show>+ <SmartSectionPreview pattern={trimmedPattern} scope={scope} /></Show>+ <p class="text-xs leading-5 text-ink-muted">+ {scope() === 'team'+ ? t('channelSections.teamChannelsOnly')+ : t('channelSections.personalChannelsHint')}+ </p></div><div class="flex flex-wrap items-center justify-end gap-3 px-5 py-3"><Show when={!props.initial && props.canShare}>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.tsindex 20541ef613..2d39f40cee 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@@ -84,6 +84,7 @@ export function buildChannelSectionRows(options: {type SectionOptions = {preferences: Partial<Record<ChannelSectionKey, ChannelSectionPreferences>>;+ order?: readonly ChannelSectionKey[];channelById: (id: string) => ChannelEntity | undefined;unreadChannelIds: ReadonlySet<string>;/** Referenced-channel feedback; include custom sections only while expanded. */@@ -287,7 +288,7 @@ export function buildChannelRailRows(for (const group of ['team_channels', 'channels'] as const) {const channels = items[group].filter(- (channel) => !labelledIds.has(channel.id)+ (channel) => group === 'team_channels' || !labelledIds.has(channel.id));if (group === 'channels' && channels.length === 0) {@@ -347,8 +348,10 @@ export function buildChannelRailRows(appendReferenceStatus(`label:${previousLabelId}`, 'team_channels');}+ const ordered = orderChannelRailSections(rows, sectionOptions?.order ?? []);+// Retain visual-order indexes for callers using the flat keyboard list.- rows.forEach((row, index) => {+ ordered.forEach((row, index) => {if ((row.kind === 'conversation' && row.group !== 'direct_messages') ||row.kind === 'label'@@ -357,7 +360,9 @@ export function buildChannelRailRows(}});- return sectionOptions ? applySectionPreferences(rows, sectionOptions) : rows;+ return sectionOptions+ ? applySectionPreferences(ordered, sectionOptions)+ : ordered;}export type ChannelRailSectionRows = {@@ -382,6 +387,29 @@ export function groupChannelRailSections(rows: readonly ChannelRailRow[]) {return sections;}+/** Keep saved sections in order and append new sections before All channels. */+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');+ }++ return keys.flatMap((key) => {+ const section = sections.get(key);+ return section ? [section.heading, ...section.rows] : [];+ });+}+/** Page at the rendered section boundary, not a source tail hidden by a label. */export function getChannelRailPaginationScope(row: ChannelRailRow,diff --git a/apps/web/src/features/channels-view/components/rail/next/useSectionReorder.ts b/apps/web/src/features/channels-view/components/rail/next/useSectionReorder.tsnew file mode 100644index 0000000000..2c718e7d2c--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/next/useSectionReorder.ts@@ -0,0 +1,99 @@+import { useUserId } from '@core/context/user';+import { useDragDropContext } from '@thisbeyond/solid-dnd';+import { type Accessor, createMemo } from 'solid-js';+import type { ChannelSectionKey } from '../../../types';+import { useChannelsRail } from '../ChannelsRailContext';++/** Reorder this viewer's sections without changing shared label data. */+export function useSectionReorder(+ keys: Accessor<readonly ChannelSectionKey[]>,+ animate: (reorder: () => void) => void+) {+ const rail = useChannelsRail();+ const userId = useUserId();+ const account = createMemo(() => ({ id: userId() }));+ const [state, actions] = useDragDropContext() ?? [];+ const scope = `${rail.railId}:sections`;+ let dragAccount: ReturnType<typeof account> | undefined;++ const dropEdge = (key: ChannelSectionKey) => {+ const source = state?.active.draggable;+ const target = state?.active.droppable;++ if (+ source?.data.dndScope !== scope ||+ target?.data.dndScope !== scope ||+ target.data.section !== key+ ) {+ return;+ }++ const sections = keys();+ const from = sections.indexOf(source.data.section);+ const to = sections.indexOf(key);++ if (from < 0 || to < 0 || from === to) {+ return;+ }++ return from < to ? 'bottom' : 'top';+ };++ actions?.onDragStart(({ draggable }) => {+ if (draggable.data.dndScope === scope) {+ dragAccount = account();+ }+ });++ const persist = (sections: ChannelSectionKey[]) => {+ const visible = new Set(sections);+ const all = [...new Set([...rail.sectionOrder(), ...sections])];+ let index = 0;++ animate(() =>+ rail.setSectionOrder(+ all.map((key) => (visible.has(key) ? sections[index++] : key))+ )+ );+ };++ actions?.onDragEnd(({ draggable, droppable }) => {+ if (+ dragAccount !== account() ||+ draggable.data.dndScope !== scope ||+ droppable?.data.dndScope !== scope+ ) {+ return;+ }++ const sections = [...keys()];+ const from = sections.indexOf(draggable.data.section);+ const to = sections.indexOf(droppable.data.section);++ if (from < 0 || to < 0 || from === to) {+ return;+ }++ sections.splice(to, 0, ...sections.splice(from, 1));+ persist(sections);+ });++ const move = (section: ChannelSectionKey, direction: -1 | 1) => {+ const sections = [...keys()];+ const from = sections.indexOf(section);+ const to = from + direction;++ if (from < 0 || to < 0 || to >= sections.length) {+ return;+ }++ sections.splice(to, 0, ...sections.splice(from, 1));+ persist(sections);+ };++ const isDragging = (key: ChannelSectionKey) =>+ state?.active.draggable?.data.dndScope === scope &&+ state.active.draggable.data.section === key;++ return { scope, dropEdge, move, isDragging };+}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.tsindex e329d888e7..60bddc0c0b 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@@ -1,7 +1,9 @@import type { ChannelEntity } from '@entity';import { describe, expect, it } from 'vitest';import {+ canAssignChannel,canLabelChannel,+ channelSectionDropError,filterChannelLabelMembers,} from './channel-label-eligibility';@@ -17,6 +19,13 @@ describe('channel label eligibility', () => {it('keeps shared sections restricted to team channels', () => {const shared = { teamId: 'team' };expect(canLabelChannel({ channelType: 'team' }, shared)).toBe(true);+ expect(+ canAssignChannel({ channelType: 'team', teamId: 'team' }, shared)+ ).toBe(true);+ expect(+ canAssignChannel({ channelType: 'team', teamId: 'another-team' }, shared)+ ).toBe(false);+ expect(canAssignChannel({ channelType: 'team' }, shared)).toBe(false);expect(canLabelChannel({ channelType: 'private' }, shared)).toBe(false);expect(canLabelChannel({ channelType: 'public' }, shared)).toBe(false);expect(canLabelChannel({ channelType: 'direct_message' }, shared)).toBe(@@ -39,3 +48,98 @@ describe('channel label eligibility', () => {expect(members).toEqual(['unloaded', 'team']);});});++describe('section drop eligibility', () => {+ it('rejects automatic membership and channels outside shared scope', () => {+ const channel = { id: 'channel', channelType: 'private' as const };+ const label = { id: 'section', channelIds: [], teamId: 'team' };++ expect(+ channelSectionDropError({ section: 'label:section', label, channel })+ ).toBe('team-only');+ expect(+ channelSectionDropError({+ section: 'label:section',+ channel,+ label: {+ ...label,+ teamId: undefined,+ rule: { attribute: 'name', contains: 'design' },+ },+ })+ ).toBe('smart');+ });++ it('accepts new manual membership and rejects existing membership', () => {+ const channel = {+ id: 'channel',+ channelType: 'team' as const,+ teamId: 'team',+ };+ const label = { id: 'section', channelIds: [], teamId: 'team' };++ expect(+ channelSectionDropError({ section: 'label:section', label, channel })+ ).toBeUndefined();+ expect(+ channelSectionDropError({+ section: 'label:section',+ label: { ...label, channelIds: ['channel'] },+ channel,+ })+ ).toBe('already-present');+ expect(+ channelSectionDropError({+ section: 'label:section',+ label,+ channel,+ sourceLabelId: 'section',+ })+ ).toBe('already-present');+ });++ it('only removes assignments into the matching built-in channel group', () => {+ const channel = { id: 'channel', channelType: 'private' as const };+ const sourceLabelId = 'section';++ expect(+ channelSectionDropError({ section: 'channels', channel, sourceLabelId })+ ).toBeUndefined();+ expect(channelSectionDropError({ section: 'channels', channel })).toBe(+ 'already-present'+ );+ expect(+ channelSectionDropError({+ section: 'team_channels',+ channel,+ sourceLabelId,+ })+ ).toBe('team-only');+ expect(+ channelSectionDropError({ section: 'favorites', channel, sourceLabelId })+ ).toBe('unsupported');+ expect(+ channelSectionDropError({+ section: 'direct_messages',+ channel,+ sourceLabelId,+ })+ ).toBe('unsupported');+ });++ it('does not accept an unloaded channel or a direct message', () => {+ expect(+ channelSectionDropError({+ section: 'label:section',+ label: { id: 'section', channelIds: [] },+ })+ ).toBe('unsupported');+ expect(+ channelSectionDropError({+ section: 'label:section',+ label: { id: 'section', channelIds: [] },+ channel: { id: 'dm', channelType: 'direct_message' },+ })+ ).toBe('unsupported');+ });+});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.tsindex 66f82f1986..3e92e52576 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@@ -1,5 +1,6 @@import type { ChannelEntity } from '@entity';import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';+import type { ChannelSectionKey } from '../types';/** Personal sections accept named conversations; shared sections stay team-only. */export function canLabelChannel(@@ -14,10 +15,24 @@ export function canLabelChannel();}+/** Writes require a known matching team, unlike server-authorized membership display. */+export function canAssignChannel(+ channel: Pick<ChannelEntity, 'channelType' | 'teamId'> | undefined,+ label?: Pick<ChannelLabel, 'teamId'>+): boolean {+ return (+ canLabelChannel(channel, label) &&+ (!label?.teamId || channel?.teamId === label.teamId)+ );+}+/** Preserve authorized server memberships until the channel metadata arrives. */export function filterChannelLabelMembers(channelIds: readonly string[],- channelsById: ReadonlyMap<string, Pick<ChannelEntity, 'channelType'>>,+ channelsById: ReadonlyMap<+ string,+ Pick<ChannelEntity, 'channelType' | 'teamId'>+ >,label?: Pick<ChannelLabel, 'teamId'>): string[] {return channelIds.filter((id) => {@@ -25,3 +40,45 @@ export function filterChannelLabelMembers(return channel === undefined || canLabelChannel(channel, label);});}++/** Explain blocked section drops with the same membership rules as the picker. */+export function channelSectionDropError(options: {+ section: ChannelSectionKey;+ label?: Pick<ChannelLabel, 'id' | 'teamId' | 'rule' | 'channelIds'>;+ channel?: Pick<ChannelEntity, 'id' | 'channelType' | 'teamId'>;+ sourceLabelId?: string;+}): 'unsupported' | 'smart' | 'team-only' | 'already-present' | undefined {+ const { section, label, channel, sourceLabelId } = options;++ if (label?.rule) {+ return 'smart';+ }++ if (!channel || !canAssignChannel(channel, label)) {+ return label?.teamId ? 'team-only' : 'unsupported';+ }++ if (label) {+ if (label.id === sourceLabelId || label.channelIds.includes(channel.id)) {+ return 'already-present';+ }++ return;+ }++ if (section === 'team_channels' && channel?.channelType !== 'team') {+ return 'team-only';+ }++ if (section === 'channels' && channel?.channelType === 'team') {+ return 'unsupported';+ }++ if (section !== 'team_channels' && section !== 'channels') {+ return 'unsupported';+ }++ if (!sourceLabelId) {+ return 'already-present';+ }+}diff --git a/apps/web/src/features/channels-view/persistence.ts b/apps/web/src/features/channels-view/persistence.tsindex 479c33a259..b30a7b0e9f 100644--- a/apps/web/src/features/channels-view/persistence.ts+++ b/apps/web/src/features/channels-view/persistence.ts@@ -114,6 +114,16 @@ const channelsPreferencesSchema = z.object({.optional()).default({}),+ sectionOrder: z+ .array(+ z.union([+ z.enum(['favorites', 'direct_messages', 'team_channels', 'channels']),+ z.custom<`label:${string}`>(+ (value) => typeof value === 'string' && value.startsWith('label:')+ ),+ ])+ )+ .default([]),});type ChannelsPreferences = z.infer<typeof channelsPreferencesSchema>;@@ -123,6 +133,7 @@ const DEFAULT_CHANNELS_PREFERENCES = {asideWidth: CHANNELS_DEFAULT_RAIL_WIDTH,sortBy: CHANNELS_DEFAULT_SORT_BY,sectionPreferences: {},+ sectionOrder: [],} satisfies ChannelsPreferences;function selectEntryState(state: ChannelsViewState): ChannelsEntryState {@@ -210,6 +221,7 @@ function createChannelsLocalStateStorage(options: {function createChannelsPreferencesStorage(options: {userId: Accessor<string | undefined>;restore: boolean;+ restoreSectionOrder: boolean;}): PersistenceStorage<ChannelsViewState> {let previous: string | undefined;const serialize = (state: ChannelsViewState) =>@@ -218,6 +230,7 @@ function createChannelsPreferencesStorage(options: {asideWidth: clampChannelsRailWidth(state.asideWidth),sortBy: state.sortBy,sectionPreferences: state.sectionPreferences,+ sectionOrder: state.sectionOrder,} satisfies ChannelsPreferences);return {@@ -241,6 +254,9 @@ function createChannelsPreferencesStorage(options: {asideWidth: restored.asideWidth,sortBy: restored.sortBy,sectionPreferences: restored.sectionPreferences,+ sectionOrder: options.restoreSectionOrder+ ? restored.sectionOrder+ : current.sectionOrder,};} catch {return {@@ -248,6 +264,9 @@ function createChannelsPreferencesStorage(options: {asideWidth: DEFAULT_CHANNELS_PREFERENCES.asideWidth,sortBy: DEFAULT_CHANNELS_PREFERENCES.sortBy,sectionPreferences: DEFAULT_CHANNELS_PREFERENCES.sectionPreferences,+ sectionOrder: options.restoreSectionOrder+ ? DEFAULT_CHANNELS_PREFERENCES.sectionOrder+ : current.sectionOrder,};}},@@ -273,12 +292,14 @@ export function createChannelsViewPersistence(options: {restoreEntryState?: boolean;restoreLocalState?: boolean;restorePreferences?: boolean;+ restoreSectionOrder?: boolean;}): MakePersistedStateOptions<ChannelsViewState> {return {storages: [createChannelsPreferencesStorage({userId: options.userId,restore: options.restorePreferences ?? true,+ restoreSectionOrder: options.restoreSectionOrder ?? true,}),createChannelsLocalStateStorage({userId: options.userId,diff --git a/apps/web/src/features/channels-view/queries/channel-list-search-pool.ts b/apps/web/src/features/channels-view/queries/channel-list-search-pool.tsindex 4eda810555..7a0d0eb145 100644--- a/apps/web/src/features/channels-view/queries/channel-list-search-pool.ts+++ b/apps/web/src/features/channels-view/queries/channel-list-search-pool.ts@@ -17,6 +17,7 @@ export function useChannelListSearchPool() {type: 'channel',name: channel.agent_dm?.name ?? (channel.name || 'Unknown Channel'),channelType: channel.channel_type,+ teamId: channel.team_id ?? undefined,ownerId: channel.owner_id,isParticipant: channel.is_participant,participantIds: channel.participants.map(diff --git a/apps/web/src/features/channels-view/types.ts b/apps/web/src/features/channels-view/types.tsindex 6b1cebc53f..6439f8765c 100644--- a/apps/web/src/features/channels-view/types.ts+++ b/apps/web/src/features/channels-view/types.ts@@ -39,6 +39,8 @@ export type ChannelsViewState = {sectionPreferences: Partial<Record<ChannelSectionKey, ChannelSectionPreferences>>;+ /** Personal display order, independent of shared section membership. */+ sectionOrder: ChannelSectionKey[];asideWidth: number;};diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.tsindex 7168ac4db3..3a191c677c 100644--- a/apps/web/src/features/entity/types/entity.ts+++ b/apps/web/src/features/entity/types/entity.ts@@ -138,6 +138,7 @@ export type ChannelEntity = EntityBase & {createdAt: DateValue;}[];channelType: 'direct_message' | 'private' | 'public' | 'team';+ teamId?: string;interactedAt?: DateValue | null;participantIds?: string[];/**diff --git a/apps/web/src/lib/i18n/locales/en/channel-sections.ts b/apps/web/src/lib/i18n/locales/en/channel-sections.tsindex 031bd087b0..3aade5c8bd 100644--- a/apps/web/src/lib/i18n/locales/en/channel-sections.ts+++ b/apps/web/src/lib/i18n/locales/en/channel-sections.ts@@ -6,10 +6,11 @@ export default {team_channels: 'Team channels',namedTeamChannels: '{{name}} channels',channels: 'Channels',+ allChannels: 'All channels',direct_messages: 'Direct messages',empty: 'No conversations yet',emptyFavorites: 'Star conversations to keep them here.',- emptySection: 'Drag conversations here to organize them.',+ emptySection: 'No channels in this section.',emptySmartSection: 'No conversations match this rule.',noResults: 'No matching conversations',loadMore: 'Load more',@@ -47,6 +48,8 @@ export default {collapseSection: 'Collapse section',resizeSection: 'Resize {{name}}',resizeSectionHint: 'Drag to resize. Double-click to reset.',+ reorderSection: 'Reorder {{name}}',+ reorderSectionHint: 'Drag to reorder. Use arrow keys to move up or down.',expandAllSections: 'Expand all sections',collapseAllSections: 'Collapse all sections',loading: 'Loading sections…',@@ -63,6 +66,11 @@ export default {sharedShort: 'Shared',personal: 'Personal',shared: 'Shared with team',+ 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.',+ alreadyInSection: 'This channel is already in this section.',+ reorderingSection: 'Reordering section',personalDescription: 'Only you can see and organize this section.',teamDescription: 'Everyone on your team can see and organize this section.',addToSection: 'Add to section',@@ -98,5 +106,39 @@ export default {reorderFavoritesFailed: 'Could not reorder favorites. Please try again.',unreadOnly: 'Unread only',noUnreadConversations: 'No unread conversations',+ addChannels: 'Add channels',+ addChannelsTo: 'Add channels to “{{name}}”',+ searchChannels: 'Search channels',+ 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.',+ addPersonalChannelsHint:+ 'Add any joined channel. Moves channels from other personal sections.',+ addSharedChannelsHint:+ 'Add joined team channels. Moves channels from other shared sections.',+ addSelectedChannels: {+ one: 'Add {{count}} channel',+ other: 'Add {{count}} channels',+ },+ addedChannels: {+ one: 'Added {{count}} channel',+ other: 'Added {{count}} channels',+ },+ addChannelsFailed: {+ one: '{{count}} channel could not be added. Retry to add it.',+ other: '{{count}} channels could not be added. Retry to add them.',+ },+ editRule: 'Edit rule',+ showAllChannels: 'Show all channels',+ matchCount: {+ one: '{{count}} matching channel',+ other: '{{count}} matching channels',+ },+ noMatchingTeamChannels:+ 'No joined team channels match this name. Try a different rule or use a personal section.',cancel: 'Cancel',};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.tsxindex ef487c2cd0..66eac22a98 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@@ -1,12 +1,16 @@import { catchToResult } from '@core/util/result';+import type { ChannelLabelScopeSelection } from '@service-storage/generated/schemas/channelLabelScopeSelection';import type { ChannelLabelsList } from '@service-storage/generated/schemas/channelLabelsList';+import type { SmartTagPreview } from '@service-storage/generated/schemas/smartTagPreview';import { cleanup, render, waitFor } from '@solidjs/testing-library';import { type QueryClient, QueryClientProvider } from '@tanstack/solid-query';import { type Ok, ok } from 'neverthrow';import { createSignal } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { channelKeys } from '../channel/keys';import { queryClient } from '../client';import {+ useAvailableSectionChannelsQuery,useChannelLabelsData,useChannelLabelsQuery,useSetChannelLabelMutation,@@ -20,6 +24,7 @@ const mocks = vi.hoisted(() => ({list: vi.fn(),preview: vi.fn(),assign: vi.fn(),+ channels: vi.fn(),}));vi.mock('@app/lib/analytics/posthog', () => ({useFeatureFlag: () => () => ({ enabled: mocks.enabled() }),@@ -36,6 +41,7 @@ vi.mock('@service-storage/client', () => ({},},}));+vi.mock('../channel/channels', () => ({ fetchAllChannels: mocks.channels }));vi.mock('../client', async () => {const { QueryClient } = await import('@tanstack/solid-query');return { queryClient: new QueryClient() };@@ -60,6 +66,7 @@ let client: QueryClient;beforeEach(() => {mocks.userId = () => 'viewer';mocks.assign.mockReset().mockResolvedValue(ok(undefined));+ mocks.channels.mockReset().mockResolvedValue([]);mocks.list.mockReset().mockResolvedValue(ok(labels));mocks.preview.mockReset()@@ -76,6 +83,43 @@ afterEach(() => {});describe('channel tag query rollout', () => {+ it('isolates available channels by account and follows channel-list invalidation', async () => {+ mocks.enabled = () => true;+ const [userId, setUserId] = createSignal('viewer');+ mocks.userId = userId;+ let finishOld!: (channels: { id: string }[]) => void;+ mocks.channels.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishOld = resolve;+ })+ );+ mocks.channels.mockResolvedValueOnce([{ id: 'current' }]);+ let query!: ReturnType<typeof useAvailableSectionChannelsQuery>;+ const Probe = () => {+ query = useAvailableSectionChannelsQuery();+ return null;+ };+ render(() => (+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>+ ));+ await waitFor(() => expect(mocks.channels).toHaveBeenCalledTimes(1));+ setUserId('new-viewer');+ await waitFor(() => expect(query.isPending).toBe(false));+ expect(query.data?.map((channel) => channel.id)).toEqual(['current']);+ finishOld([{ id: 'old-account' }]);+ await waitFor(() => expect(client.isFetching()).toBe(0));+ expect(query.data?.map((channel) => channel.id)).toEqual(['current']);++ mocks.channels.mockResolvedValueOnce([{ id: 'joined' }]);+ await client.invalidateQueries({+ queryKey: channelKeys.listChannels.queryKey,+ });+ expect(query.data?.map((channel) => channel.id)).toEqual(['joined']);+ });+it('does not fetch while disabled and hides cached labels when switched off', async () => {const [enabled, setEnabled] = createSignal(false);mocks.enabled = enabled;@@ -194,6 +238,57 @@ describe('channel tag query rollout', () => {await client.invalidateQueries({ queryKey: channelLabelKeys._def });expect(mocks.preview).toHaveBeenCalledTimes(1);});+ it('switches smart preview scope without remounting and ignores the old scope response', async () => {+ mocks.enabled = () => true;+ const [scope, setScope] =+ createSignal<ChannelLabelScopeSelection>('personal');+ let finishPersonal!: (value: Ok<SmartTagPreview, never>) => void;+ mocks.preview.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishPersonal = resolve;+ })+ );+ mocks.preview.mockResolvedValueOnce(+ ok({+ channels: [{ id: 'team-channel', name: 'Team channel' }],+ totalCount: 1,+ })+ );+ let preview!: ReturnType<typeof useSmartTagPreviewQuery>;+ const Probe = () => {+ preview = useSmartTagPreviewQuery(() => 'channel', scope);+ return null;+ };+ render(() => (+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>+ ));+ await waitFor(() => expect(mocks.preview).toHaveBeenCalledTimes(1));+ setScope('team');+ await waitFor(() => expect(preview.isPending).toBe(false));+ expect(mocks.preview).toHaveBeenLastCalledWith(+ { attribute: 'name', contains: 'channel' },+ expect.any(AbortSignal),+ 'team'+ );+ expect(preview.data?.channels.map((channel) => channel.id)).toEqual([+ 'team-channel',+ ]);++ finishPersonal(+ ok({+ channels: [{ id: 'private-channel', name: 'Private channel' }],+ totalCount: 1,+ })+ );+ await waitFor(() => expect(client.isFetching()).toBe(0));+ expect(preview.data?.channels.map((channel) => channel.id)).toEqual([+ 'team-channel',+ ]);+ });+it('does not publish late reads into another account', 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.tsindex 723a493484..0a629e3b8f 100644--- a/apps/web/src/lib/queries/channel-labels/channel-labels.ts+++ b/apps/web/src/lib/queries/channel-labels/channel-labels.ts@@ -10,6 +10,8 @@ import type { ChannelLabelScopeSelection } from '@service-storage/generated/scheimport type { ChannelLabelsList } from '@service-storage/generated/schemas/channelLabelsList';import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';+import { fetchAllChannels } from '../channel/channels';+import { channelKeys } from '../channel/keys';import { queryClient } from '../client';import { withCallbacks } from '../utils';import { channelLabelKeys } from './keys';@@ -117,24 +119,39 @@ function smartTagPreviewQueryOptions(export function useSmartTagPreviewQuery(pattern: Accessor<string>,- scope?: ChannelLabelScopeSelection+ scope?: ChannelLabelScopeSelection | Accessor<ChannelLabelScopeSelection>) {const channelTagsFlag = useFeatureFlag(enableChannelTags);const userId = useUserId();const debouncedPattern = debouncedDependent(pattern, 150);return useQuery(() => {- const contains = pattern();+ const contains = debouncedPattern().trim();+ const selectedScope = typeof scope === 'function' ? scope() : scope;return smartTagPreviewQueryOptions(contains,- channelTagsFlag().enabled &&- contains.length > 0 &&- contains === debouncedPattern(),- scope,+ channelTagsFlag().enabled && contains.length > 0,+ selectedScope,userId());});}+function availableSectionChannelsQueryOptions(actorId: string | undefined) {+ return queryOptions({+ queryKey: channelKeys.listChannels._ctx.account(actorId).queryKey,+ queryFn: ({ signal }) => fetchAllChannels(signal),+ enabled: Boolean(actorId),+ reconcile: 'id',+ staleTime: 0,+ });+}++/** Full authorized channel membership, scoped to the current account. */+export function useAvailableSectionChannelsQuery() {+ const userId = useUserId();+ return useQuery(() => availableSectionChannelsQueryOptions(userId()));+}+export type CreateChannelLabelArgs = {actorId: string | undefined;name: string;diff --git a/apps/web/src/lib/queries/channel/keys.ts b/apps/web/src/lib/queries/channel/keys.tsindex f5a6bdbaaf..aaa212f877 100644--- a/apps/web/src/lib/queries/channel/keys.ts+++ b/apps/web/src/lib/queries/channel/keys.ts@@ -18,7 +18,12 @@ export const channelKeys = createQueryKeys('channel', {queryKey: [channelID],}),activity: null,- listChannels: null,+ listChannels: {+ queryKey: null,+ contextQueries: {+ account: (actorId?: string) => [actorId ?? 'signed-out'],+ },+ },quickAccessGraphql: (cacheClientId: string) => ({queryKey: [cacheClientId],}),diff --git a/apps/web/src/lib/queries/soup/transform-utils.test.ts b/apps/web/src/lib/queries/soup/transform-utils.test.tsindex e510e39bee..2466acfccf 100644--- a/apps/web/src/lib/queries/soup/transform-utils.test.ts+++ b/apps/web/src/lib/queries/soup/transform-utils.test.ts@@ -13,6 +13,33 @@ vi.mock('@core/constant/allBlocks', () => ({vi.mock('@core/context/channels', () => ({ useChannelsContext: vi.fn() }));vi.mock('@core/user', () => ({ emailToId: vi.fn() }));+it('preserves channel team identity for section assignment checks', () => {+ const item = {+ tag: 'channel',+ frecency_score: 0,+ is_favorited: false,+ data: {+ channel: {+ id: 'channel',+ name: 'Design',+ channel_type: 'team',+ team_id: 'team',+ owner_id: 'owner',+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ },+ participants: [],+ is_participant: true,+ },+ } satisfies SoupApiItem;++ expect(mapApiSoupItemToEntity(item)).toMatchObject({+ type: 'channel',+ channelType: 'team',+ teamId: 'team',+ });+});+describe('email soup entities', () => {it.each([true, false])('preserves server Signal membership (%s) for Home activity',diff --git a/apps/web/src/lib/queries/soup/transform-utils.ts b/apps/web/src/lib/queries/soup/transform-utils.tsindex e4c8f1eb57..6ebf9847b3 100644--- a/apps/web/src/lib/queries/soup/transform-utils.ts+++ b/apps/web/src/lib/queries/soup/transform-utils.ts@@ -891,6 +891,7 @@ export const mapApiSoupItemToEntity = (id: item.data.channel.id,name: item.data.channel.name || 'Unknown Channel',channelType: item.data.channel.channel_type,+ teamId: item.data.channel.team_id ?? undefined,ownerId: item.data.channel.owner_id,frecencyScore: item.frecency_score ?? 0,updatedAt: item.data.channel.updated_at,diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 87cfa4da73..76cd0d9ef4 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -962,26 +962,32 @@ between Threads, All, and Recent preserves an already-open navigation overlay.### Sectioned sidebar (flag on)With the flag on, desktop Chat has one conversation sidebar, without All, Recent,-or Threads view tabs. Favorites appears first, followed by Direct messages, the-team's channels, and custom sections. The team heading is **[Team name] channels**,-with **Team channels** as the fallback while the name is unavailable.-Other joined public and private channels remain in Channels until assigned to a-personal section. Each custom section is a top-level heading, independent of the-Team channels disclosure. Empty sections remain visible with a short hint; empty-Favorites explains how to add a favorite. Private conversations use a lock icon in-the sidebar and mobile feed, including favorited private conversations.+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 is the renamed+remaining-public/private list: its membership is unchanged, so it excludes team+channels and channels assigned to 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+conversations.All section headers use the shared collapsible-section styling without leading-icons or top padding; the section stack supplies an 8px flex gap. Custom-section-drop zones and highlights cover both the header and its content, including the+icons or top padding; the section stack supplies a compact 2px flex gap.+Custom-section drop zones and highlights cover both the header and its content, including theempty state.Section, DM, and search containers use the 8px outer sidebar gutter; headingsand rows add their own item padding so headings align with the Chat title.-Content is indented by 8px under every section, including Favorites, custom-sections, DMs, and empty states. Search results remain unindented. The+Rows are indented by 8px under every section, including Favorites, custom+sections, and DMs. Empty-state actions and search results avoid this extra indent. Thecaret stays hidden in expanded sections until hover and remains visible whencollapsed. Team-shared sections show a neutral Shared-badge next to the name, before the caret. Personal sections have no scope icon or-badge. Header focus backgrounds fill the entire header row, including its+badge next to the name, before the caret. Below 256px of section width, a users+icon replaces the badge to leave more room for the name. Separate short tooltips+explain the name and sharing, without overlapping native title hints. Personal+sections have no scope icon or badge. Header focus backgrounds fill the entire header row, including itstrailing controls, with no extra right padding.The sidebar scrolls through all sections. Each expanded section has its own@@ -997,6 +1003,16 @@ the saved preference. Search covers channels and DMs regardless of sectionplacement and restores the selected row in its section when closed. Mobileretains the recent-conversation feed below.+Use the drag grip in the left gutter before the section name to reorder sections,+or focus the grip and use Up/Down. The grip does not shift the header's text or+controls. An insertion line shows the destination. Section order is a personal+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.+Section membership comes from the server's complete visible channel-ID lists.The sidebar shows available channel rows immediately. One shared by-ID queryper batch supplies cached channel data and fetches only missing records using@@ -1033,7 +1049,11 @@ the label service and its feature flag.Use **New → New section** to create a section. The wider dialog has a name fieldand a **Smart section** switch in its body. **Shared with team** sits on the leftof the footer, with the action buttons on the right. With both switches off, the-section is personal and manual; smart grouping reveals its name rule and preview.+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 areprivate to the account, including for team members, and accept joined team,public, or private channels. Shared sections@@ -1045,7 +1065,16 @@ Each heading has one sliders-icon menu, also available by right-clicking the hea**Sort** opens its independent single-select options with a checkmark on the right.**Filter** contains **Unread only**. The unread label sits on the left and itsswitch on the right; toggling it keeps the submenu open.-Custom sections include editing, Mark all as read, notification actions, and a+Manual sections have a **+** header action and **Add channels** menu entry.+The picker searches all eligible joined channels, not just rows loaded in the+sidebar, and excludes channels already in the section. The wider, shorter picker+keeps its actions visible while the channel list scrolls. Compact helper text+explains the scope and assignment move. Adding a channel moves its+manual assignment within the same scope without changing the other scope.+Partial failures keep successful additions and retry only the failed selection.+Empty manual sections offer **Add channels**, empty smart sections offer **Edit+rule**, and unread-filtered empty sections offer **Show all channels**.+Custom sections also include editing, Mark all as read, notification actions, and adestructive Delete action in the same menu. Click and right-click menus use thesame standard context-menu rows, spacing, and selection indicators. Use the heading's caretto expand/collapse it; this is not repeated@@ -1056,15 +1085,16 @@ 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**, **Channels**,+Every desktop section menu, including **Favorites**, **All channels**,**[team name] channels**, and **Direct messages**, offers **Mute all channels**,**Unmute all channels**, and **Snooze all channels…**. These update only yournotifications, including for shared sections. Each action uses the section'scomplete 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, exclude channels assigned to custom sections just as-the sidebar does, and never include unjoined channels. Favorites targets only-channel favorites, not documents or other favorite types. Snooze uses the usual+before applying an action and never include unjoined channels. The team section+includes custom-section members; only All channels excludes those assignments.+Favorites targets only channel favorites, not documents or other favorite types.+Snooze uses the usualduration/date picker and resumes notifications at the chosen time. A partialfailure keeps successful updates and reports the failures; snooze retries onlyfailed channels. Empty or unavailable custom sections and empty Favorites disable@@ -1078,6 +1108,10 @@ and shared assignments remain independent.Choose smart grouping in the section dialog for automatic name matching.Smart sections match channel names literally and without regard to capitalization. They preserve ordinary section permissions and are not manualdrop targets. Channels can appear in multiple matching smart sections.+Hovering an incompatible item over a section shows a not-allowed cursor and an+explanation over the section, including automatic membership, shared-scope+restrictions, and channels already in the section. Returning a channel to its+matching built-in channel group removes only its existing manual assignment.Support is organized manually through a personal section. The app does notclassify support channels by their names or silently create a Support section.@@ -1089,10 +1123,10 @@ empty sections, assignment failures, and one channel in both scopes. Check theNew menu, both dialog switches, keyboard access, edit-dialog focus, destructivedeletion, and per-section unread and sort preferences after reload. Confirmunread filtering does not change section-membership or another section's rows. Scroll a long sidebar with many sections-and confirm that Direct messages remains immediately below Favorites. Keyboard-navigation and section shortcuts must follow-the same order as the rendered rows.+membership or another section's rows. Scroll a long sidebar with many sections,+reorder both custom and built-in sections, and confirm the order survives reload.+Keyboard navigation and section shortcuts must follow the same order as the+rendered rows.Drag a channel between sections and confirm the sidebar stays visible whilelookups refetch, including with a slow or paused connection.When a channel belongs to both a personal and a shared section, drag its@@ -1102,6 +1136,7 @@ verify the opposite scope.### Creation actions+The sidebar's **New** dropdown spans its button's full width.**New** offers separate **New channel** and **New direct message** actions inboth sidebar layouts. **New channel** opens the existing[name, visibility, and optional invitations flow](#create-a-channel).