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
feat(channels): add Threads tab to the chat view (#7235)
dev-rb2259ccf92055
diff --git a/apps/web/src/features/channels-view/channels-route.ts b/apps/web/src/features/channels-view/channels-route.tsindex bbc61ace81..aae666c972 100644--- a/apps/web/src/features/channels-view/channels-route.ts+++ b/apps/web/src/features/channels-view/channels-route.ts@@ -5,7 +5,7 @@ import type { ChannelsQueryScope, ChannelsTab } from './types';export const channelsSearch = {namespace: 'channels',schema: z.object({- tab: z.enum(['browse', 'recents']),+ tab: z.enum(['browse', 'recents', 'threads']),mobileTab: z.enum(['channels', 'direct_messages', 'recents']),messageId: z.string(),threadId: z.string(),diff --git a/apps/web/src/features/channels-view/channels-view-context.tsx b/apps/web/src/features/channels-view/channels-view-context.tsxindex ecc7f56b6b..c449387c37 100644--- a/apps/web/src/features/channels-view/channels-view-context.tsx+++ b/apps/web/src/features/channels-view/channels-view-context.tsx@@ -3,6 +3,7 @@ import {channelIdForPreviewNavigation,getChannelEntityTarget,} from '@app/features/next-soup/utils';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { makePersistedState } from '@app/lib/persistence';import {createSearchParams,@@ -11,6 +12,7 @@ import {} from '@app/lib/split-router';import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';+import { enableChannelThreadsPreview } from '@core/constant/featureFlags';import { createAssertedContextProvider } from '@core/context/createContext';import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';@@ -27,13 +29,14 @@ import { createChannelsViewPersistence } from './persistence';import { channelDetailRoute, channelsSplitRoute } from './route';import type {ChannelListSort,- ChannelsGroup,ChannelsQueryScope,ChannelsRailSection,+ ChannelsSortGroup,ChannelsTab,ChannelsViewState,ChannelsViewStateOptions,} from './types';+import { activeChannelsTab } from './utils';type ChannelsViewProviderProps = ContextProviderProps & {initialState?: ChannelsViewStateOptions;@@ -44,13 +47,24 @@ export type ChannelsViewContext = {/** The mobile list opens channels in the split; only desktop renders detail. */mobileLayout: () => boolean;selectedChannel: Accessor<ChannelPreviewSelection | undefined>;+ /** Whether the Threads tab is available to this user. */+ threadsEnabled: Accessor<boolean>;+ /**+ * The tab to render. A stored or linked Threads tab shows All while the flag+ * is off or still loading, and returns once it resolves on; `state.tab`+ * keeps the choice so persistence and URLs are not rewritten.+ */+ tab: Accessor<ChannelsTab>;+ /** Threads tab filter: the conversation whose threads are shown, or all. */+ threadsChannelId: Accessor<string | undefined>;+ setThreadsChannelId: (channelId: string | undefined) => void;setTab: (tab: ChannelsTab) => void;setMobileTab: (tab: ChannelsQueryScope) => void;setSelectedChannel: (channel: ChannelPreviewSelection | undefined) => boolean;setGroupOpen: (group: ChannelsRailSection, open: boolean) => void;/** Per-user collapse state of a team channel label. */setLabelOpen: (labelId: string, open: boolean) => void;- setSortBy: (group: ChannelsGroup, sort: ChannelListSort) => void;+ setSortBy: (group: ChannelsSortGroup, sort: ChannelListSort) => void;setAsideWidth: (width: number) => void;};@@ -67,11 +81,13 @@ function createInitialState(direct_messages: initial.expandedGroups?.direct_messages ?? true,},collapsedLabels: initial.collapsedLabels ?? [],+ threadsChannelId: initial.threadsChannelId,sortBy: {channels: initial.sortBy?.channels ?? CHANNELS_DEFAULT_SORT_BY.channels,direct_messages:initial.sortBy?.direct_messages ??CHANNELS_DEFAULT_SORT_BY.direct_messages,+ threads: initial.sortBy?.threads ?? CHANNELS_DEFAULT_SORT_BY.threads,},asideWidth: clampChannelsRailWidth(initial.asideWidth ?? CHANNELS_DEFAULT_RAIL_WIDTH@@ -92,6 +108,8 @@ export const [ChannelsViewProvider, useChannelsView] =const navigate = useNavigate();const params = useRouteParams(channelDetailRoute);const [search, setSearch] = createSearchParams(channelsSearch);+ const threadsFlag = useFeatureFlag(enableChannelThreadsPreview);+ const threadsEnabled = () => threadsFlag().enabled;const selectPreview = createPreviewSelectionGuard();const initial = props.initialState ?? {};const [state, setState] = makePersistedState(@@ -193,6 +211,13 @@ export const [ChannelsViewProvider, useChannelsView] =state,mobileLayout,selectedChannel,+ threadsEnabled,+ tab: () => activeChannelsTab(state.tab, threadsEnabled()),+ threadsChannelId: () => state.threadsChannelId,+ setThreadsChannelId: (channelId) => {+ if (state.threadsChannelId === channelId) return;+ setState('threadsChannelId', channelId);+ },setTab: (tab) => {if (state.tab === tab) return;setState('tab', tab);diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsxindex 50062e5fe9..46728f11c9 100644--- a/apps/web/src/features/channels-view/channels-view.test.tsx+++ b/apps/web/src/features/channels-view/channels-view.test.tsx@@ -115,6 +115,9 @@ vi.mock('./components/ChannelDetailView', () => ({</div>),}));+vi.mock('./components/ChannelThreadsView', () => ({+ ChannelThreadsView: () => <div data-testid="channel-threads" />,+}));vi.mock('./components/ChannelsMobileView', () => ({ChannelsMobileView: (props: {source: ChannelsDataSource;@@ -145,6 +148,7 @@ vi.mock('./channels-view-context', () => ({},sortBy: { channels: 'updated_at', direct_messages: 'updated_at' },},+ tab: () => 'browse',mobileLayout: () => mocks.mobileLayout(),selectedChannel: () =>mocks.selectedId()diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsxindex 1a158c9b62..5deab72c27 100644--- a/apps/web/src/features/channels-view/channels-view.tsx+++ b/apps/web/src/features/channels-view/channels-view.tsx@@ -24,6 +24,7 @@ import {import { ChannelsViewProvider, useChannelsView } from './channels-view-context';import { ChannelDetailView } from './components/ChannelDetailView';import { ChannelsMobileView } from './components/ChannelsMobileView';+import { ChannelThreadsView } from './components/ChannelThreadsView';import { ChannelsRail } from './components/rail/ChannelsRail';import { createChannelDetail } from './primitives/create-channel-detail';import {@@ -91,10 +92,37 @@ function DesktopChannelsRail(props: {);}+function DesktopChannelThreads(props: { sources: ChannelsSources }) {+ const { threadsChannelId, setTab, setSelectedChannel } = useChannelsView();+ const channelsById = createMemo(+ () =>+ new Map(+ deduplicateChannels([+ props.sources.threads.items(),+ props.sources.channels.items(),+ props.sources.direct_messages.items(),+ props.sources.recents.items(),+ ]).map((channel) => [channel.id, channel])+ )+ );++ return (+ <ChannelThreadsView+ channelId={threadsChannelId()}+ resolveChannel={(channelId) => channelsById().get(channelId)}+ onOpenThread={(thread) => {+ setTab('browse');+ setSelectedChannel(thread);+ }}+ />+ );+}+function ChannelsViewRoot() {const panel = useSplitPanelOrThrow();- const { state, mobileLayout, selectedChannel, setAsideWidth } =+ const { state, tab, mobileLayout, selectedChannel, setAsideWidth } =useChannelsView();+ const threadsTab = () => !mobileLayout() && tab() === 'threads';const [railSearchOpen, setRailSearchOpen] = createSignal(false);const sources = useChannelsSources(@@ -103,8 +131,9 @@ function ChannelsViewRoot() {return scope !== 'search' && state.mobileTab === scope;if (railSearchOpen()) return scope === 'search';if (scope === 'search') return false;- if (scope === 'recents') return state.tab === 'recents';- return state.tab === 'browse';+ if (scope === 'recents') return tab() === 'recents';+ if (scope === 'threads') return tab() === 'threads';+ return tab() === 'browse';},(group) => state.sortBy[group]);@@ -122,7 +151,9 @@ function ChannelsViewRoot() {<ViewShell.RootasidePreferenceKey="channels"// The empty state only points at the rail, so keep it open.- asideRequired={selectedChannel() === undefined}+ asideRequired={+ threadsTab() || selectedChannel() === undefined+ }aside={{width: state.asideWidth,preserveDuringResize: false,@@ -149,32 +180,41 @@ function ChannelsViewRoot() {</ViewShell.Aside><ViewShell.Main class="overflow-hidden"><ViewTour tour={channelsTour} />- <ChannelSourcesContext.Provider value={sources}>- <DebugSuspense name="ChannelsView.outlet">- <SplitRouter.Outlet- fallback={() => (- <>- <ViewShell.TopBar>- <span class="text-sm font-semibold">- Chat- </span>- </ViewShell.TopBar>- <div class="flex min-h-0 flex-1 items-center justify-center px-6 text-center">- <div class="flex max-w-sm flex-col gap-2">- <h2 class="text-base font-semibold text-ink">- Select a conversation- </h2>- <p class="text-sm leading-5 text-ink-muted">- Choose a channel or person from the- sidebar to open the conversation here.- </p>+ <Show+ when={!threadsTab()}+ fallback={+ <DebugSuspense name="ChannelsView.threads">+ <DesktopChannelThreads sources={sources} />+ </DebugSuspense>+ }+ >+ <ChannelSourcesContext.Provider value={sources}>+ <DebugSuspense name="ChannelsView.outlet">+ <SplitRouter.Outlet+ fallback={() => (+ <>+ <ViewShell.TopBar>+ <span class="text-sm font-semibold">+ Chat+ </span>+ </ViewShell.TopBar>+ <div class="flex min-h-0 flex-1 items-center justify-center px-6 text-center">+ <div class="flex max-w-sm flex-col gap-2">+ <h2 class="text-base font-semibold text-ink">+ Select a conversation+ </h2>+ <p class="text-sm leading-5 text-ink-muted">+ Choose a channel or person from the+ sidebar to open the conversation here.+ </p>+ </div></div>- </div>- </>- )}- />- </DebugSuspense>- </ChannelSourcesContext.Provider>+ </>+ )}+ />+ </DebugSuspense>+ </ChannelSourcesContext.Provider>+ </Show></ViewShell.Main></ViewShell.Root></div>diff --git a/apps/web/src/features/channels-view/components/ChannelThreadsView.tsx b/apps/web/src/features/channels-view/components/ChannelThreadsView.tsxnew file mode 100644index 0000000000..adcce25102--- /dev/null+++ b/apps/web/src/features/channels-view/components/ChannelThreadsView.tsx@@ -0,0 +1,338 @@+import { ViewShell } from '@app/components/view-shell';+import { DebugSuspense } from '@channel/DebugSuspense';+import { MessageThread, threadListItem } from '@core/messages/MessageThread';+import type { ChannelEntity, ChannelThreadEntity } from '@entity';+import ArrowSquareOutIcon from '@phosphor/arrow-square-out.svg';+import { useMessageThreadQuery } from '@queries/messages/thread-replies';+import { Button, cn, Scroll } from '@ui';+import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';+import { useChannelThreadsQuery } from '../queries/channel-threads';+import { ChannelAvatar } from './rail/ChannelRailItems';++/** Load the next page once the list is within this many pixels of its end. */+const LOAD_MORE_THRESHOLD = 600;+const LIST_SKELETON_CARDS = [0, 1, 2];+/** Reply rows sketched under the root while a card loads, as width classes. */+const CARD_SKELETON_REPLIES = ['w-2/3', 'w-1/2'];+const CARD_CLASS =+ 'relative flex flex-col gap-2 rounded-xl border border-edge-muted bg-surface p-3';++/** One sketched message row: avatar, name, and a line of text. */+function MessageSkeleton(props: { textWidth: string; indent?: boolean }) {+ return (+ <div class={cn('flex items-start gap-2', props.indent && 'pl-8')}>+ <div class="skeleton-shimmer size-7 shrink-0 rounded-full bg-skeleton" />+ <div class="flex min-w-0 flex-1 flex-col gap-2 pt-1">+ <div class="skeleton-shimmer h-2.5 w-24 rounded-full bg-skeleton" />+ <div+ class={cn(+ 'skeleton-shimmer h-2.5 rounded-full bg-skeleton',+ props.textWidth+ )}+ />+ </div>+ </div>+ );+}++/** The body of a card whose thread is still loading: a root and two replies. */+function ThreadSkeleton() {+ return (+ <div aria-hidden="true" class="flex flex-col gap-3">+ <MessageSkeleton textWidth="w-4/5" />+ <For each={CARD_SKELETON_REPLIES}>+ {(width) => <MessageSkeleton textWidth={width} indent />}+ </For>+ </div>+ );+}++function ThreadListSkeleton() {+ return (+ <div role="status" aria-label="Loading threads" class="flex flex-col gap-6">+ <For each={LIST_SKELETON_CARDS}>+ {() => (+ <div class={CARD_CLASS}>+ <ThreadSkeleton />+ </div>+ )}+ </For>+ </div>+ );+}++export type ChannelThreadsViewProps = {+ /** The conversation whose threads are shown; all threads when unset. */+ channelId: string | undefined;+ /** Channel metadata already loaded by the rail, for names and access. */+ resolveChannel: (channelId: string) => ChannelEntity | undefined;+ onOpenThread: (thread: ChannelThreadEntity) => void;+};++type ThreadQuery = ReturnType<typeof useMessageThreadQuery>;++/**+ * Rendered inside the card's Suspense boundary, so reading the thread suspends+ * only this card. The list item is memoized: as a JSX prop expression it would+ * be rebuilt on every read of `data`, and the thread re-derives everything from+ * each new object.+ */+function ThreadCardBody(props: { query: ThreadQuery; canWrite: boolean }) {+ // A pending read suspends the card but still returns undefined to this+ // read, so every use is guarded.+ const item = createMemo(() => {+ const data = props.query.data;+ return data && !data.state.deleted_at ? threadListItem(data) : undefined;+ });+ return (+ <Show when={item()}>+ {(data) => (+ <MessageThread+ data={data()}+ canWrite={props.canWrite}+ // Collapsed like a channel timeline: the first replies, then a "more+ // replies" control that expands the rest.+ expanded={false}+ />+ )}+ </Show>+ );+}++function ThreadCard(props: {+ thread: ChannelThreadEntity;+ channel: ChannelEntity | undefined;+ showChannel: boolean;+ onOpen: () => void;+}) {+ const parent = () => ({+ type: 'channel' as const,+ id: props.thread.channelId,+ });+ const query = useMessageThreadQuery(parent, () => props.thread.id);++ return (+ <article+ class={cn(CARD_CLASS, 'group/thread-card')}+ data-channel-thread={props.thread.id}+ >+ <Show when={props.showChannel && props.channel}>+ {(channel) => (+ <header class="flex min-w-0 items-center gap-2 text-xs">+ <ChannelAvatar channel={channel()} />+ <span class="min-w-0 truncate font-medium text-ink">+ {channel().name}+ </span>+ </header>+ )}+ </Show>+ <Switch>+ <Match when={query.isError}>+ <div class="flex items-center gap-2 text-xs text-ink-muted">+ <span>Couldn’t load this thread.</span>+ <Button+ variant="outline"+ size="xs"+ onClick={() => void query.refetch()}+ >+ Try again+ </Button>+ </div>+ </Match>+ <Match when={true}>+ {/* A boundary per card: one around the virtualized list would blank+ every card whenever a newly scrolled one fetched. */}+ <DebugSuspense+ name="ChannelThreadsView.card"+ fallback={<ThreadSkeleton />}+ >+ <ThreadCardBody+ query={query}+ // Channels the rail knows about say whether the viewer can post;+ // anything else is left to the server to refuse.+ canWrite={props.channel?.isParticipant !== false}+ />+ </DebugSuspense>+ </Match>+ </Switch>+ {/* The wrapper carries the position: the button's tooltip anchors to+ it, and the thread keeps the card's full width underneath. It shows+ on hover or keyboard focus, and always on touch, which cannot hover. */}+ <div class="absolute top-2 right-2 opacity-0 transition-opacity group-hover/thread-card:opacity-100 group-focus-within/thread-card:opacity-100 touch:opacity-100 motion-reduce:transition-none">+ <Button+ variant="ghost"+ size="icon-md"+ label="View in channel"+ onClick={() => props.onOpen()}+ >+ <ArrowSquareOutIcon />+ </Button>+ </div>+ </article>+ );+}++/** Keys the list body when every conversation's threads are shown. */+const ALL_THREADS_KEY = 'all';++type ThreadsQuery = ReturnType<typeof useChannelThreadsQuery>;++/**+ * The scrollable list for one filter. It is keyed by conversation, so a switch+ * starts a fresh scroll container at the top instead of writing `scrollTop`+ * after the DOM changed, which forced a synchronous layout on every click.+ */+function ThreadList(props: {+ query: ThreadsQuery['query'];+ threads: ThreadsQuery['threads'];+ isPending: ThreadsQuery['isPending'];+ channelId: string | undefined;+ resolveChannel: ChannelThreadsViewProps['resolveChannel'];+ onOpenThread: ChannelThreadsViewProps['onOpenThread'];+}) {+ const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();+ const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();+ // A card being replied to stays mounted while scrolled away, so its draft+ // and focus survive virtualization.+ const [activeIndex, setActiveIndex] = createSignal<number>();+ const loadMoreNearEnd = (offset: number) => {+ const handle = virtualizer();+ if (+ !handle ||+ props.isPending() ||+ !props.query.hasNextPage ||+ props.query.isFetchingNextPage ||+ props.query.error ||+ handle.scrollSize - handle.viewportSize - offset > LOAD_MORE_THRESHOLD+ )+ return;+ void props.query.fetchNextPage();+ };++ return (+ <Scroll scrollRef={setScrollRoot}>+ <div class="mx-auto flex w-full max-w-3xl flex-col px-4 py-4">+ <Switch>+ <Match when={props.isPending()}>+ <ThreadListSkeleton />+ </Match>+ <Match when={props.query.error && props.threads().length === 0}>+ <div class="flex min-h-40 flex-col items-center justify-center gap-2 text-sm text-ink-muted">+ <span>Couldn’t load threads.</span>+ <Button+ variant="outline"+ size="xs"+ onClick={() => void props.query.refresh()}+ >+ Try again+ </Button>+ </div>+ </Match>+ <Match when={props.threads().length === 0}>+ <div class="flex min-h-40 flex-col items-center justify-center gap-1 text-center">+ <h2 class="text-base font-semibold text-ink">No threads yet</h2>+ <p class="text-sm text-ink-muted">+ {props.channelId+ ? 'Replies to messages in this conversation show up here.'+ : 'Replies to messages in your conversations show up here.'}+ </p>+ </div>+ </Match>+ <Match when={true}>+ <Virtualizer+ ref={setVirtualizer}+ data={props.threads()}+ scrollRef={scrollRoot()}+ startMargin={16}+ keepMounted={+ activeIndex() === undefined ? undefined : [activeIndex()!]+ }+ onScroll={loadMoreNearEnd}+ >+ {(thread, index) => (+ <div+ class="pb-6"+ onFocusIn={() => setActiveIndex(index())}+ onFocusOut={(event) => {+ const next = event.relatedTarget;+ if (+ !(next instanceof Node) ||+ !event.currentTarget.contains(next)+ )+ setActiveIndex(undefined);+ }}+ >+ <ThreadCard+ thread={thread}+ channel={props.resolveChannel(thread.channelId)}+ showChannel={props.channelId === undefined}+ onOpen={() => props.onOpenThread(thread)}+ />+ </div>+ )}+ </Virtualizer>+ {/* A failed page or refetch keeps the loaded threads. */}+ <Show when={props.query.error && !props.query.isFetchingNextPage}>+ <div class="flex items-center justify-center gap-2 py-3 text-xs text-ink-muted">+ <span>Couldn’t load more threads.</span>+ <Button+ variant="outline"+ size="xs"+ onClick={() => void props.query.refresh()}+ >+ Try again+ </Button>+ </div>+ </Show>+ <Show when={props.query.isFetchingNextPage}>+ <div+ role="status"+ aria-label="Loading more threads"+ class={CARD_CLASS}+ >+ <ThreadSkeleton />+ </div>+ </Show>+ </Match>+ </Switch>+ </div>+ </Scroll>+ );+}++/** Channel threads, newest reply first, each with its replies and reply input. */+export function ChannelThreadsView(props: ChannelThreadsViewProps) {+ const { query, threads, isPending } = useChannelThreadsQuery(+ () => props.channelId,+ () => true+ );+ const selectedChannel = () =>+ props.channelId ? props.resolveChannel(props.channelId) : undefined;+ const title = () =>+ props.channelId+ ? (selectedChannel()?.name ?? 'Conversation threads')+ : 'All threads';++ return (+ <>+ <ViewShell.TopBar>+ <span class="min-w-0 truncate text-sm font-semibold">{title()}</span>+ </ViewShell.TopBar>+ <div class="relative min-h-0 flex-1">+ <Show when={props.channelId ?? ALL_THREADS_KEY} keyed>+ {(_key) => (+ <ThreadList+ query={query}+ threads={threads}+ isPending={isPending}+ channelId={props.channelId}+ resolveChannel={props.resolveChannel}+ onOpenThread={props.onOpenThread}+ />+ )}+ </Show>+ </div>+ </>+ );+}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 86f7e94cd9..bc6603bb11 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@@ -161,6 +161,8 @@ vi.mock('../../channels-view-context', () => ({expandedGroups: { channels: true, direct_messages: true },collapsedLabels: [],},+ tab: () => 'browse',+ threadsEnabled: () => false,selectedChannel: () => mocks.selected,setSelectedChannel: mocks.select,}),@@ -220,6 +222,7 @@ const sources: ChannelsSources = {direct_messages: source,recents: source,search: source,+ threads: source,};const mount = () =>render(() => (diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsxindex e1f6e39c03..456b409676 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx@@ -115,6 +115,10 @@ const CHANNEL_RAIL_SECTIONS: ChannelsRailSection[] = [const LABEL_KEY_PREFIX = 'label:';const BROWSE_QUERY_SCOPES = ['channels', 'direct_messages'] as const;const CHANNEL_TAB_IDS: ChannelsTab[] = ['browse', 'recents'];+const CHANNEL_TAB_IDS_WITH_THREADS: ChannelsTab[] = [+ ...CHANNEL_TAB_IDS,+ 'threads',+];const DM_LOADING_PREVIEW_OFFSET = 80;export type ChannelsRailProps = {@@ -141,6 +145,10 @@ export function ChannelsRail(props: ChannelsRailProps) {setSelectedChannel,setSortBy,setTab,+ tab,+ threadsEnabled,+ threadsChannelId,+ setThreadsChannelId,} = useChannelsView();const panel = useSplitPanelOrThrow();@@ -258,7 +266,7 @@ export function ChannelsRail(props: ChannelsRailProps) {const listDomId = createUniqueId();const [sectionScrollRoots, setSectionScrollRoots] = createSignal<- Partial<Record<ChannelsRailSection, HTMLDivElement>>+ Partial<Record<ChannelsRailSection | 'threads', HTMLDivElement>>>({});const [listRoot, setListRoot] = createSignal<HTMLDivElement>();@@ -406,13 +414,14 @@ export function ChannelsRail(props: ChannelsRailProps) {}return buildChannelRailRows(- state.tab,+ tab(),state.expandedGroups,{favorites: favorites(),channels: props.sources.channels.items(),direct_messages: props.sources.direct_messages.items(),recents: props.sources.recents.items(),+ threads: props.sources.threads.items(),},channelSectionRows());@@ -435,6 +444,19 @@ export function ChannelsRail(props: ChannelsRailProps) {const openInNewSplit =metadata?.newSplit === true || metadata?.event?.shiftKey === true;+ if (item.kind === 'all-threads') {+ setThreadsChannelId(undefined);+ return;+ }++ // In the Threads tab, conversation rows (including search results)+ // filter the thread list; they open only into a new split.+ if (item.kind === 'conversation' && tab() === 'threads') {+ if (openInNewSplit) activateChannel(item.channel, true);+ else setThreadsChannelId(item.channel.id);+ return;+ }+if (item.kind === 'section') {setGroupOpen(item.group, !state.expandedGroups[item.group]);return;@@ -500,9 +522,11 @@ export function ChannelsRail(props: ChannelsRailProps) {? sectionScrollRoots().favorites: row.kind === 'conversation' && row.group? sectionScrollRoots()[row.group]- : state.tab === 'recents'+ : tab() === 'recents'? listRoot()- : undefined;+ : tab() === 'threads'+ ? sectionScrollRoots().threads+ : undefined;if (!element || !scrollRoot) return;const elementBounds = element.getBoundingClientRect();@@ -542,6 +566,19 @@ export function ChannelsRail(props: ChannelsRailProps) {if (scrollRoot?.isConnected) scrollRoot.scrollTop = 0;};+ const scrollThreadsToSelectedOrStart = () => {+ const items = props.sources.threads.items();+ const selectedIndex = items.findIndex(+ (channel) => channel.id === threadsChannelId()+ );+ const virtualizer = virtualizers().threads;+ if (!virtualizer || items.length === 0) return;++ virtualizer.scrollToIndex(selectedIndex >= 0 ? selectedIndex : 0, {+ align: selectedIndex >= 0 ? 'nearest' : 'start',+ });+ };+const scrollSearchToSelectedOrStart = () => {const items = searchResults();@@ -588,11 +625,13 @@ export function ChannelsRail(props: ChannelsRailProps) {const searchOpen = props.searchOpen;const sourcesReady = searchOpen? !props.sources.search.isLoading()- : state.tab === 'recents'+ : tab() === 'recents'? !props.sources.recents.isLoading()- : BROWSE_QUERY_SCOPES.every(- (scope) => !props.sources[scope].isLoading()- );+ : tab() === 'threads'+ ? !props.sources.threads.isLoading()+ : BROWSE_QUERY_SCOPES.every(+ (scope) => !props.sources[scope].isLoading()+ );if (!sourcesReady) return;const frame = requestAnimationFrame(() => {@@ -600,8 +639,10 @@ export function ChannelsRail(props: ChannelsRailProps) {if (searchOpen) {scrollSearchToSelectedOrStart();- } else if (state.tab === 'recents') {+ } else if (tab() === 'recents') {scrollScopeToSelectedOrStart('recents');+ } else if (tab() === 'threads') {+ scrollThreadsToSelectedOrStart();} else {scrollFavoritesToSelectedOrStart();for (const scope of BROWSE_QUERY_SCOPES) {@@ -616,8 +657,9 @@ export function ChannelsRail(props: ChannelsRailProps) {useViewTabHotkeys({scopeId: panel.splitHotkeyScope,enabled: panel.isPanelActive,- ids: () => CHANNEL_TAB_IDS,- activeId: () => state.tab,+ ids: () =>+ threadsEnabled() ? CHANNEL_TAB_IDS_WITH_THREADS : CHANNEL_TAB_IDS,+ activeId: () => tab(),setActiveId: selectTab,});@@ -694,7 +736,11 @@ export function ChannelsRail(props: ChannelsRailProps) {previewAfterNavigation.clear();const row = event.result?.item;- if (row?.kind === 'conversation') {+ if (tab() === 'threads') {+ if (row?.kind === 'all-threads') setThreadsChannelId(undefined);+ else if (row?.kind === 'conversation')+ setThreadsChannelId(row.channel.id);+ } else if (row?.kind === 'conversation') {previewAfterNavigation(row.channel);} else if (row?.kind === 'favorite' &&@@ -761,7 +807,7 @@ export function ChannelsRail(props: ChannelsRailProps) {const sectionHotkeys = createHotkeyGroup();const sectionHotkeysEnabled = () =>- panel.isPanelActive() && !props.searchOpen && state.tab === 'browse';+ panel.isPanelActive() && !props.searchOpen && tab() === 'browse';registerHotkey({hotkey: ']',@@ -1107,11 +1153,13 @@ export function ChannelsRail(props: ChannelsRailProps) {const rail: ChannelsRailContext = {railId: listDomId,list,- tab: () => state.tab,+ tab,selectTab,sources: props.sources,favorites,selectedChannel,+ threadsEnabled,+ threadsChannelId,isGroupOpen: (group) => state.expandedGroups[group],toggleGroup: (group) => setGroupOpen(group, !state.expandedGroups[group]),channelTagsEnabled,diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.tsindex 644a901deb..e712b5b138 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts@@ -12,13 +12,22 @@ import type {ChannelListSort,ChannelsGroup,ChannelsRailSection,+ ChannelsSortGroup,ChannelsTab,} from '../../types';import type { useChannelRailActivity } from './hooks/useChannelRailActivity';type ChannelRailActivity = ReturnType<typeof useChannelRailActivity>;+export const ALL_THREADS_ROW_ID = 'all-threads';+export type ChannelRailRow =+ | {+ /** The Threads tab's unfiltered entry above the conversation list. */+ kind: 'all-threads';+ id: typeof ALL_THREADS_ROW_ID;+ group?: undefined;+ }| {kind: 'section';id: `section:${ChannelsRailSection}`;@@ -117,6 +126,10 @@ export type ChannelsRailContext = {sources: ChannelsSources;favorites: Accessor<readonly Favorite[]>;selectedChannel: Accessor<ChannelPreviewSelection | undefined>;+ /** Whether the Threads tab is available to this user. */+ threadsEnabled: Accessor<boolean>;+ /** Threads tab filter: the conversation whose threads are shown, or all. */+ threadsChannelId: Accessor<string | undefined>;isGroupOpen: (group: ChannelsRailSection) => boolean;toggleGroup: (group: ChannelsRailSection) => void;/** Whether channel labels and smart tags are enabled for this user. */@@ -150,12 +163,12 @@ export type ChannelsRailContext = {activeDropTarget: Accessor<ChannelLabelDropTarget | undefined>;/** Mark every unread notification in the label's visible channels read. */markLabelRead: (label: ChannelLabel) => void;- sortBy: (group: ChannelsGroup) => ChannelListSort;- setSortBy: (group: ChannelsGroup, sort: ChannelListSort) => void;+ sortBy: (group: ChannelsSortGroup) => ChannelListSort;+ setSortBy: (group: ChannelsSortGroup, sort: ChannelListSort) => void;registerRootRef: (element: HTMLDivElement) => void;activateRow: (rowId: ChannelRailRow['id'], event?: MouseEvent) => void;registerScrollRef: (- group: ChannelsRailSection,+ group: ChannelsRailSection | 'threads',element: HTMLDivElement) => void;registerVirtualizer: (diff --git a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsxindex 2e53d05240..4987aa5fcb 100644--- a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx@@ -10,8 +10,12 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';import EmptyStateNoSearchMatchGraphic from '@design/empty-state-no-search-match.svg';import { type ChannelEntity, Entity } from '@entity';import CaretDownIcon from '@phosphor/caret-down.svg';+import ChatCircleIcon from '@phosphor/chat-circle.svg';+import ChatsCircleIcon from '@phosphor/chats-circle.svg';import CheckIcon from '@phosphor/check.svg';+import HashIcon from '@phosphor/hash.svg';import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';+import PlusIcon from '@phosphor/plus.svg';import SortIcon from '@phosphor/sort-ascending.svg';import XIcon from '@phosphor/x.svg';import type { Favorite } from '@service-storage/generated/schemas/favorite';@@ -35,7 +39,11 @@ import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';import { canLabelChannel } from '../../core/channel-label-eligibility';import { ChannelsLiveCallsSidebar } from '../../live-calls-sidebar';import { CHANNELS_TOUR } from '../../tour';-import type { ChannelListSort, ChannelsGroup } from '../../types';+import type {+ ChannelListSort,+ ChannelsGroup,+ ChannelsSortGroup,+} from '../../types';import { channelMentionsUser, formatDetailedTimestamp } from '../../utils';import { ChannelsEmptyState } from '../ChannelsEmptyState';import {@@ -53,6 +61,7 @@ import {isPrimaryMouseDown,} from './ChannelRailItems';import {+ ALL_THREADS_ROW_ID,type ChannelLabelDragData,type ChannelLabelDropData,type ChannelRailRow,@@ -82,6 +91,10 @@ const CHANNEL_TABS = [{ value: 'browse', label: 'All' },{ value: 'recents', label: 'Recent' },];+const CHANNEL_TABS_WITH_THREADS = [+ ...CHANNEL_TABS,+ { value: 'threads', label: 'Threads' },+];type ChannelRailSearch = {isOpen: Accessor<boolean>;@@ -130,7 +143,10 @@ const CHANNEL_SORT_OPTIONS: {{ value: 'created_at', label: 'Date created' },];-function ChannelSortDropdown(props: { group: ChannelsGroup; label: string }) {+function ChannelSortDropdown(props: {+ group: ChannelsSortGroup;+ label: string;+}) {const rail = useChannelsRail();const setSort = (value: string) => {const option = CHANNEL_SORT_OPTIONS.find((item) => item.value === value);@@ -446,7 +462,11 @@ function ExpandedFavoritesSection() {function ExpandedHeader(props: { search: ChannelRailSearch }) {const rail = useChannelsRail();const selectTab = (value: string) => {- if (value === 'browse' || value === 'recents') {+ if (+ value === 'browse' ||+ value === 'recents' ||+ (value === 'threads' && rail.threadsEnabled())+ ) {rail.selectTab(value);}};@@ -463,7 +483,9 @@ function ExpandedHeader(props: { search: ChannelRailSearch }) {<ViewSidebar.Toolbar><Tabsaria-label="Chat sidebar views"- list={CHANNEL_TABS}+ list={+ rail.threadsEnabled() ? CHANNEL_TABS_WITH_THREADS : CHANNEL_TABS+ }value={rail.tab()}onChange={selectTab}/>@@ -1026,6 +1048,134 @@ function ExpandedRecents() {);}+/** The Threads section's create action: a channel or a direct message. */+function ConversationsCreateMenu() {+ return (+ <Dropdown placement="bottom-end">+ <Dropdown.Trigger+ as={ViewSidebar.Control}+ variant="ghost"+ size="icon-sm"+ label="Create channel or direct message"+ >+ <PlusIcon class="size-3.5" />+ </Dropdown.Trigger>+ <Dropdown.Content class="min-w-44">+ <Dropdown.Group>+ <Dropdown.Item onSelect={openNewChannelModal}>+ <HashIcon class="size-3.5 shrink-0 text-ink-muted" />+ <span class="flex-1 truncate text-ink-muted">New channel</span>+ </Dropdown.Item>+ <Dropdown.Item onSelect={() => runCreateAction('channel')}>+ <ChatCircleIcon class="size-3.5 shrink-0 text-ink-muted" />+ <span class="flex-1 truncate text-ink-muted">+ New direct message+ </span>+ </Dropdown.Item>+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ );+}++function ExpandedThreads() {+ const rail = useChannelsRail();+ const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();+ const scope = useChannelRailScopeState(() => 'threads');+ const pagination = useChannelRailVirtualizer(() => 'threads');+ const allThreadsDomId = () => domIdForRow(rail.railId, ALL_THREADS_ROW_ID);+ const allThreadsSelected = () => rail.threadsChannelId() === undefined;+ const allThreadsFocused = () => rail.list.focus.key() === ALL_THREADS_ROW_ID;+ const registerScrollRef = (element: HTMLDivElement) => {+ setScrollRoot(element);+ rail.registerScrollRef('threads', element);+ };++ return (+ <ViewSidebar.Content class="h-full overflow-hidden">+ <ViewSidebar.Nav aria-label="Thread filters" class="shrink-0">+ <ViewSidebar.Item+ as="div"+ id={allThreadsDomId()}+ role="treeitem"+ tabIndex={-1}+ class={cn(+ !allThreadsSelected() && allThreadsFocused() && 'bg-hover text-ink'+ )}+ active={allThreadsSelected()}+ aria-current={allThreadsSelected() ? 'page' : undefined}+ onClick={(event) => {+ if (!isPrimaryMouseDown(event)) return;+ rail.activateRow(ALL_THREADS_ROW_ID, event);+ }}+ >+ <ViewSidebar.Icon>+ <ChatsCircleIcon class="size-4" />+ </ViewSidebar.Icon>+ <span class="min-w-0 flex-1 truncate">All threads</span>+ </ViewSidebar.Item>+ </ViewSidebar.Nav>+ <CollapsibleSection.Root open sizing="fill">+ <CollapsibleSection.Header focused={false} focusWithin={false}>+ <span class="flex h-full min-w-0 flex-1 items-center px-2">+ <span class="min-w-0 truncate">Conversations</span>+ </span>+ <div data-section-action="" class="flex items-center gap-0.5">+ <ChannelSortDropdown group="threads" label="Conversations" />+ <ConversationsCreateMenu />+ </div>+ </CollapsibleSection.Header>+ <CollapsibleSection.Content+ open+ contentRef={registerScrollRef}+ class="flex min-h-0 flex-col gap-0.5"+ >+ <Switch>+ <Match+ when={scope().source.isLoading() && scope().items.length === 0}+ >+ <RailListLoading />+ </Match>+ <Match when={scope().source.error() && scope().items.length === 0}>+ <RailListError retry={scope().source.refresh} />+ </Match>+ <Match when={scope().items.length > 0}>+ <Virtualizer+ ref={pagination.registerVirtualizer}+ data={scope().items}+ scrollRef={scrollRoot()}+ itemSize={34}+ bufferSize={240}+ keepMounted={scope().keepMounted}+ onScroll={pagination.loadMoreNearEnd}+ >+ {(channel) => (+ <div class="pb-0.5">+ <ChannelOption channel={channel} />+ </div>+ )}+ </Virtualizer>+ <Show when={scope().source.isLoadingMore()}>+ <RailListLoadingMore variant="channel" />+ </Show>+ <Show+ when={scope().source.error() && !scope().source.isLoadingMore()}+ >+ <RailListError retry={scope().source.refresh} compact />+ </Show>+ </Match>+ <Match when={true}>+ <div class="px-2 py-2 text-xs text-ink-extra-muted">+ No conversations+ </div>+ </Match>+ </Switch>+ </CollapsibleSection.Content>+ </CollapsibleSection.Root>+ </ViewSidebar.Content>+ );+}+export function ExpandedChannelsRail(props: { search: ChannelRailSearch }) {const listTarget = tourTarget(CHANNELS_TOUR.list);const rail = useChannelsRail();@@ -1059,6 +1209,9 @@ export function ExpandedChannelsRail(props: { search: ChannelRailSearch }) {<Match when={rail.tab() === 'recents'}><ExpandedRecents /></Match>+ <Match when={rail.tab() === 'threads'}>+ <ExpandedThreads />+ </Match></Switch></div><Show when={!props.search.isOpen() && rail.tab() === 'browse'}>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 a5a2b0c402..1d9885f81f 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@@ -185,6 +185,7 @@ describe('buildChannelRailRows', () => {channels: [acme, zeta],direct_messages: [],recents: [],+ threads: [],},buildChannelSectionRows({labels: [],@@ -217,6 +218,7 @@ describe('buildChannelRailRows', () => {channels: [deals],direct_messages: [],recents: [],+ threads: [],},sectionRows);@@ -248,11 +250,34 @@ describe('buildChannelRailRows', () => {channels: [acme],direct_messages: [],recents: [zeta, acme],+ threads: [],},[]);expect(rows.map((row) => row.id)).toEqual(['channel:zeta', 'channel:acme']);});++ it('puts All threads above one mixed list of channels and DMs', () => {+ const dm = channel('dm', 'Bob', 'direct_message');+ const rows = buildChannelRailRows(+ 'threads',+ expanded,+ {+ favorites: [],+ channels: [acme],+ direct_messages: [],+ recents: [],+ threads: [dm, acme],+ },+ []+ );+ expect(rows.map((row) => row.id)).toEqual([+ 'all-threads',+ 'channel:dm',+ 'channel:acme',+ ]);+ expect(rows[1]).toMatchObject({ scope: 'threads', localIndex: 0 });+ });});it('renders a channel in every matching smart tag with unique navigation IDs, excluding it from ungrouped even when collapsed', () => {@@ -291,6 +316,7 @@ it('renders a channel in every matching smart tag with unique navigation IDs, exchannels: [acme, zeta, deals],direct_messages: [],recents: [],+ threads: [],},sections);diff --git a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.ts b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.tsindex 61c2010576..8c136992f9 100644--- a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.ts+++ b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.ts@@ -8,6 +8,7 @@ import type {ChannelsTab,} from '../../types';import {+ ALL_THREADS_ROW_ID,type ChannelRailRow,type ChannelSectionRow,rowKeyForChannel,@@ -16,7 +17,7 @@ import {} from './ChannelsRailContext';export type ChannelRailItemsByScope = Record<- ChannelsQueryScope,+ ChannelsQueryScope | 'threads',readonly ChannelEntity[]> & {favorites: readonly Favorite[];@@ -79,6 +80,21 @@ export function buildChannelRailRows(items: ChannelRailItemsByScope,channelSectionRows: readonly ChannelSectionRow[]): ChannelRailRow[] {+ if (tab === 'threads') {+ return [+ { kind: 'all-threads', id: ALL_THREADS_ROW_ID },+ ...items.threads.map(+ (channel, localIndex): ChannelRailRow => ({+ kind: 'conversation',+ id: rowKeyForChannel(channel.id),+ scope: 'threads',+ localIndex,+ channel,+ })+ ),+ ];+ }+if (tab === 'recents') {return items.recents.map((channel, localIndex) => ({kind: 'conversation',diff --git a/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts b/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.tsindex 5423ad3761..680cad1850 100644--- a/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts+++ b/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts@@ -32,7 +32,10 @@ export function useChannelRailItemState(return {domId: domIdForRow(rail.railId, rowId),- selected: rail.selectedChannel()?.id === id,+ selected:+ rail.tab() === 'threads'+ ? rail.threadsChannelId() === id+ : rail.selectedChannel()?.id === id,focused: rail.list.focus.key() === rowId,muted: isMutedItem(notificationSource.mutedEntities(), {item_id: id,@@ -86,7 +89,9 @@ export function useChannelRailFavoritesState() {});}-export function useChannelRailScopeState(scope: Accessor<ChannelsQueryScope>) {+export function useChannelRailScopeState(+ scope: Accessor<ChannelsQueryScope | 'threads'>+) {const rail = useChannelsRail();return createMemo(() => {@@ -105,7 +110,7 @@ export function useChannelRailScopeState(scope: Accessor<ChannelsQueryScope>) {? focusedRow.localIndex: -1;const targetChannelId =- currentScope === 'recents'+ currentScope === 'recents' || currentScope === 'threads'? undefined: rail.channelActivity.targetChannelId(currentScope);const activityIndex =diff --git a/apps/web/src/features/channels-view/constants.ts b/apps/web/src/features/channels-view/constants.tsindex 4a1023d7a3..34a3926c5e 100644--- a/apps/web/src/features/channels-view/constants.ts+++ b/apps/web/src/features/channels-view/constants.ts@@ -1,5 +1,5 @@import { DEFAULT_ASIDE_LAYOUT } from '@app/components/view-shell/view-shell-layout';-import type { ChannelListSort, ChannelsGroup } from './types';+import type { ChannelListSort, ChannelsSortGroup } from './types';export const CHANNELS_DEFAULT_RAIL_WIDTH = DEFAULT_ASIDE_LAYOUT.width;export const CHANNELS_MIN_RAIL_WIDTH = DEFAULT_ASIDE_LAYOUT.min;@@ -8,7 +8,8 @@ export const CHANNELS_MAX_RAIL_WIDTH = DEFAULT_ASIDE_LAYOUT.max;export const CHANNELS_DEFAULT_SORT_BY = {channels: 'updated_at',direct_messages: 'updated_at',-} satisfies Record<ChannelsGroup, ChannelListSort>;+ threads: 'updated_at',+} satisfies Record<ChannelsSortGroup, ChannelListSort>;export function clampChannelsRailWidth(width: number): number {if (!Number.isFinite(width)) return CHANNELS_DEFAULT_RAIL_WIDTH;diff --git a/apps/web/src/features/channels-view/core/channel-threads-query.test.ts b/apps/web/src/features/channels-view/core/channel-threads-query.test.tsnew file mode 100644index 0000000000..9eacd2c4c4--- /dev/null+++ b/apps/web/src/features/channels-view/core/channel-threads-query.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';+import { channelThreadsQueryArgs } from './channel-threads-query';++// Threads user-1 takes part in, minus their roots nobody has replied to.+const INVOLVED = {+ '&': [+ { l: { Participant: 'user-1' } },+ {+ '!': {+ '&': [{ l: { RootSender: 'user-1' } }, { l: { HasReplies: false } }],+ },+ },+ ],+};++describe('channelThreadsQueryArgs', () => {+ it('scopes threads to the selected conversation and the user', () => {+ const { body, params } = channelThreadsQueryArgs('user-1', 'channel-1');+ expect(params.sort_method).toBe('updated_at');+ // The backend takes one UUID per ChannelId literal, not a list.+ expect(body.cthf).toEqual({+ '&': [{ l: { ChannelId: 'channel-1' } }, INVOLVED],+ });+ });++ it('drops only unanswered roots from the user’s threads when unfiltered', () => {+ const { body } = channelThreadsQueryArgs('user-1', undefined);+ expect(body.cthf).toEqual(INVOLVED);+ // Every other entity type is excluded.+ expect(body.chanf).toBeDefined();+ expect(body.df).toBeDefined();+ });+});diff --git a/apps/web/src/features/channels-view/core/channel-threads-query.ts b/apps/web/src/features/channels-view/core/channel-threads-query.tsnew file mode 100644index 0000000000..c74b47394b--- /dev/null+++ b/apps/web/src/features/channels-view/core/channel-threads-query.ts@@ -0,0 +1,37 @@+import { clause, compileClause, confine } from '@app/features/soup/filters';+import type { SoupAstItemsQueryArgs } from '@queries/soup/items';++const CHANNEL_THREADS_PAGE_SIZE = 20;++/**+ * Threads the user takes part in, most recent reply first, except messages+ * they sent that nobody has answered. With a channel id, only that+ * conversation's threads; without one, across every conversation.+ */+export function channelThreadsQueryArgs(+ userId: string,+ channelId: string | undefined+): SoupAstItemsQueryArgs {+ const involved = clause.and(+ clause.eq('channelThreadParticipantId', userId),+ clause.not(+ clause.and(+ clause.eq('channelThreadRootSenderId', userId),+ clause.eq('channelThreadHasReplies', false)+ )+ )+ );+ return {+ params: {+ limit: CHANNEL_THREADS_PAGE_SIZE,+ sort_method: 'updated_at',+ },+ body: compileClause(+ confine({+ cthf: channelId+ ? clause.and(clause.eq('channelThreadChannelId', channelId), involved)+ : involved,+ })+ ),+ };+}diff --git a/apps/web/src/features/channels-view/persistence.ts b/apps/web/src/features/channels-view/persistence.tsindex 6cca5c1bad..a6d10fb9d3 100644--- a/apps/web/src/features/channels-view/persistence.ts+++ b/apps/web/src/features/channels-view/persistence.ts@@ -45,7 +45,7 @@ const channelsExpandedGroupsSchema = z.preprocess(const channelsEntryStateSchemaWithDefaults = z.object({version: z.literal(1).default(1),- tab: z.enum(['browse', 'recents']).default('browse'),+ tab: z.enum(['browse', 'recents', 'threads']).default('browse'),mobileTab: z.enum(['channels', 'direct_messages', 'recents']).default('channels'),@@ -55,6 +55,7 @@ const channelsEntryStateSchemaWithDefaults = z.object({direct_messages: true,}),collapsedLabels: z.array(z.string()).default([]),+ threadsChannelId: z.string().optional(),});type ChannelsEntryState = z.infer<typeof channelsEntryStateSchemaWithDefaults>;@@ -69,6 +70,7 @@ const DEFAULT_CHANNELS_ENTRY_STATE = {direct_messages: true,},collapsedLabels: [],+ threadsChannelId: undefined,} satisfies ChannelsEntryState;const channelsPreferencesSchema = z.object({@@ -86,6 +88,9 @@ const channelsPreferencesSchema = z.object({direct_messages: z.enum(['viewed_at', 'updated_at', 'created_at']).default(CHANNELS_DEFAULT_SORT_BY.direct_messages),+ threads: z+ .enum(['viewed_at', 'updated_at', 'created_at'])+ .default(CHANNELS_DEFAULT_SORT_BY.threads),}).default(CHANNELS_DEFAULT_SORT_BY),});@@ -105,6 +110,7 @@ function selectEntryState(state: ChannelsViewState): ChannelsEntryState {mobileTab: state.mobileTab,expandedGroups: state.expandedGroups,collapsedLabels: state.collapsedLabels,+ threadsChannelId: state.threadsChannelId,};}@@ -121,6 +127,7 @@ function restoreChannelsEntryState(mobileTab: restored.mobileTab,expandedGroups: restored.expandedGroups,collapsedLabels: restored.collapsedLabels,+ threadsChannelId: restored.threadsChannelId,};}diff --git a/apps/web/src/features/channels-view/queries.test.ts b/apps/web/src/features/channels-view/queries.test.tsindex 687d130535..3b2fc97d5f 100644--- a/apps/web/src/features/channels-view/queries.test.ts+++ b/apps/web/src/features/channels-view/queries.test.ts@@ -19,7 +19,10 @@ const useSoupAstItemsQuery = vi.hoisted(() =>vi.mock('@queries/soup/items', () => ({ useSoupAstItemsQuery }));vi.mock('@entity', () => ({isChannelEntity: (entity: { type: string }) => entity.type === 'channel',+ isChannelThreadEntity: (entity: { type: string }) =>+ entity.type === 'channel_thread',}));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user-1' }));import { useChannelByIdQuery, useChannelsSources } from './queries';@@ -68,12 +71,17 @@ describe('channel list query selection', () => {return dispose;});try {- expect(useSoupAstItemsQuery).toHaveBeenCalledTimes(5);+ // Four channel lists, the Threads rail's threads and their channels,+ // then the selected conversation.+ expect(useSoupAstItemsQuery).toHaveBeenCalledTimes(7);for (const [, options] of useSoupAstItemsQuery.mock.calls.slice(0, 4)) {expect(options?.().graphqlProjection).toBe('channel-list');expect(options?.().staleTime).toBe(30_000);}- const [, selectionOptions] = useSoupAstItemsQuery.mock.calls[4];+ for (const [, options] of useSoupAstItemsQuery.mock.calls.slice(4, 6)) {+ expect(options?.().staleTime).toBe(30_000);+ }+ const [, selectionOptions] = useSoupAstItemsQuery.mock.calls[6];expect(selectionOptions?.().graphqlProjection).toBeUndefined();expect(selectionOptions?.().staleTime).toBe(0);} finally {@@ -81,3 +89,90 @@ describe('channel list query selection', () => {}});});++describe('Threads rail source', () => {+ it('lists only channels holding the user’s threads', () => {+ const thread = (+ id: string,+ channelId: string,+ senderId: string,+ replyCount: number+ ) => ({+ type: 'channel_thread',+ id,+ channelId,+ senderId,+ thread: { replyCount, preview: [] },+ });+ const channel = (id: string, updatedAt: string) => ({+ type: 'channel',+ id,+ name: id,+ updatedAt,+ });+ const threadFilters: string[] = [];+ useSoupAstItemsQuery.mockImplementation((args) => {+ const { body } = args();+ const isThreadQuery = JSON.stringify(body.cthf).includes('Participant');+ if (isThreadQuery) threadFilters.push(JSON.stringify(body.cthf));+ return {+ isEnabled: true,+ isLoading: false,+ data: {+ entities: isThreadQuery+ ? [+ thread('t1', 'dm', 'someone', 2),+ thread('t2', 'eng', 'user-1', 1),+ thread('t3', 'eng', 'someone', 4),+ ]+ : [+ channel('eng', '2026-09-02'),+ channel('dm', '2026-09-01'),+ channel('general', '2026-09-03'),+ ],+ },+ } as never;+ });+ const dispose = createRoot((dispose) => {+ const sources = useChannelsSources(+ (scope) => scope === 'threads',+ () => 'updated_at'+ );+ // Distinct channels in the channel sort; `general` holds no threads.+ expect(sources.threads.items().map((c) => c.id)).toEqual(['eng', 'dm']);+ // The server drops the user's unanswered roots, so pages stay full.+ expect(threadFilters[0]).toContain('HasReplies');+ return dispose;+ });+ dispose();+ useSoupAstItemsQuery.mockReset();+ });+});++describe('Threads rail paging', () => {+ it('keeps paging on its own while the list may be too short to scroll', () => {+ const fetchNextPage = vi.fn(async () => {});+ useSoupAstItemsQuery.mockImplementation(+ () =>+ ({+ isEnabled: true,+ isLoading: false,+ isFetching: false,+ error: null,+ hasNextPage: true,+ fetchNextPage,+ data: { entities: [] },+ }) as never+ );+ const dispose = createRoot((dispose) => {+ useChannelsSources(+ (scope) => scope === 'threads',+ () => 'updated_at'+ );+ return dispose;+ });+ expect(fetchNextPage).toHaveBeenCalled();+ dispose();+ useSoupAstItemsQuery.mockReset();+ });+});diff --git a/apps/web/src/features/channels-view/queries.ts b/apps/web/src/features/channels-view/queries.tsindex 5e3af8e0a9..af24292369 100644--- a/apps/web/src/features/channels-view/queries.ts+++ b/apps/web/src/features/channels-view/queries.ts@@ -4,21 +4,37 @@ import {defineQueryFilters,queryStateFrom,} from '@app/features/next-soup/filters/filter-store';+import { useUserId } from '@core/context/user';import { compareDateDesc } from '@core/util/date';-import { type ChannelEntity, type EntityData, isChannelEntity } from '@entity';+import {+ type ChannelEntity,+ type EntityData,+ isChannelEntity,+ isChannelThreadEntity,+} from '@entity';import {type SoupAstItemsQueryArgs,type SoupAstParams,useSoupAstItemsQuery,} from '@queries/soup/items';import { type Accessor, createEffect, createMemo } from 'solid-js';+import { channelThreadsQueryArgs } from './core/channel-threads-query';import type {ChannelListSort,- ChannelsGroup,ChannelsQueryScope,+ ChannelsSortGroup,} from './types';import { channelHasMessages, isDirectMessage } from './utils';+/** Threads per page the Threads rail reads to find their channels. */+const THREAD_CHANNELS_PAGE_SIZE = 100;+/**+ * Pages the rail loads on its own. A few busy channels can fill the first+ * page, leaving a list too short to scroll, so it keeps paging up to this cap;+ * scrolling the rail loads the rest.+ */+const THREAD_CHANNELS_AUTO_PAGES = 5;+const CHANNELS_QUERY_PARAMS = {limit: 100,} satisfies SoupAstParams;@@ -31,7 +47,10 @@ type ChannelsQueryDefinition = {export type ChannelsDataSource = ListDataSource<ChannelEntity>;-export type ChannelsSourceScope = ChannelsQueryScope | 'search';+/** Scopes backed by a channel list query. */+type ChannelsListScope = ChannelsQueryScope | 'search';++export type ChannelsSourceScope = ChannelsListScope | 'threads';export type ChannelsSources = Record<ChannelsSourceScope, ChannelsDataSource>;@@ -71,10 +90,10 @@ export const CHANNELS_QUERY_DEFINITIONS = {}),matches: () => true,},-} satisfies Record<ChannelsSourceScope, ChannelsQueryDefinition>;+} satisfies Record<ChannelsListScope, ChannelsQueryDefinition>;export function channelsQueryArgs(- scope: ChannelsSourceScope,+ scope: ChannelsListScope,sortMethod?: ChannelListSort): SoupAstItemsQueryArgs {const definition = CHANNELS_QUERY_DEFINITIONS[scope];@@ -89,7 +108,7 @@ export function channelsQueryArgs(}export function filterChannelsForScope(- scope: ChannelsSourceScope,+ scope: ChannelsListScope,channels: readonly ChannelEntity[]): ChannelEntity[] {return channels.filter(CHANNELS_QUERY_DEFINITIONS[scope].matches);@@ -188,8 +207,115 @@ export function resolveSelectedChannel();}+function sortChannels(+ channels: readonly ChannelEntity[],+ sort: ChannelListSort+): ChannelEntity[] {+ const sortDate = (channel: ChannelEntity) =>+ sort === 'created_at'+ ? channel.createdAt+ : sort === 'viewed_at'+ ? channel.viewedAt+ : channel.updatedAt;++ return channels+ .slice()+ .sort((left, right) => compareDateDesc(sortDate(left), sortDate(right)));+}++/**+ * The Threads rail: channels and DMs holding threads the user takes part in.+ * Channels have no thread filter, so the rail pages through the user's+ * threads and loads the distinct channels they belong to.+ */+function useThreadChannelsDataSource(+ enabled: Accessor<boolean>,+ sortMethod: Accessor<ChannelListSort>+): ChannelsDataSource {+ const userId = useUserId();+ const threadsQuery = useSoupAstItemsQuery(+ () => {+ const args = channelThreadsQueryArgs(userId() ?? '', undefined);+ return {+ ...args,+ params: { ...args.params, limit: THREAD_CHANNELS_PAGE_SIZE },+ };+ },+ () => ({ enabled: enabled() && Boolean(userId()), staleTime: 30_000 })+ );+ // Drive the paginated query on its own until the cap, like+ // `useChannelsByIdsQuery`, so later-page conversations appear without scroll.+ createEffect(() => {+ if (+ !threadsQuery.isEnabled ||+ threadsQuery.isLoading ||+ threadsQuery.isFetching ||+ threadsQuery.error ||+ !threadsQuery.hasNextPage ||+ (threadsQuery.data?.entities.length ?? 0) >=+ THREAD_CHANNELS_PAGE_SIZE * THREAD_CHANNELS_AUTO_PAGES+ )+ return;+ void threadsQuery.fetchNextPage();+ });+ const channelIds = createMemo<string[]>((previous) => {+ if (!threadsQuery.isEnabled || threadsQuery.isLoading) return previous;+ const ids = new Set<string>();+ for (const entity of threadsQuery.data?.entities ?? []) {+ if (isChannelThreadEntity(entity) && !entity.deletedAt)+ ids.add(entity.channelId);+ }+ return [...ids];+ }, []);+ const channelsQuery = useChannelsByIdsQuery(channelIds);+ const items = createMemo<ChannelEntity[]>((previous) => {+ if (channelIds().length === 0) return [];+ if (!channelsQuery.isEnabled || channelsQuery.isLoading) return previous;+ const byId = new Map(+ (channelsQuery.data?.entities ?? [])+ .filter(isChannelEntity)+ .map((channel) => [channel.id, channel])+ );+ return sortChannels(+ channelIds().flatMap((id) => byId.get(id) ?? []),+ sortMethod()+ );+ }, []);++ return {+ items,+ isLoading: () =>+ items().length === 0 &&+ ((threadsQuery.isEnabled && threadsQuery.isLoading) ||+ (channelsQuery.isEnabled && channelsQuery.isLoading)),+ isFetching: () =>+ (threadsQuery.isEnabled && threadsQuery.isFetching) ||+ (channelsQuery.isEnabled && channelsQuery.isFetching),+ error: () =>+ (threadsQuery.isEnabled ? threadsQuery.error : null) ??+ (channelsQuery.isEnabled ? channelsQuery.error : null) ??+ undefined,+ hasMore: () => threadsQuery.isEnabled && threadsQuery.hasNextPage,+ isLoadingMore: () =>+ threadsQuery.isEnabled && threadsQuery.isFetchingNextPage,+ loadMore: async () => {+ if (+ !threadsQuery.isEnabled ||+ threadsQuery.isFetchingNextPage ||+ !threadsQuery.hasNextPage+ )+ return;+ await threadsQuery.fetchNextPage();+ },+ refresh: async () => {+ if (!threadsQuery.isEnabled) return;+ await threadsQuery.refresh();+ },+ };+}+function useChannelsDataSource(- scope: ChannelsSourceScope,+ scope: ChannelsListScope,enabled: Accessor<boolean>,sortMethod: Accessor<ChannelListSort | undefined>): ChannelsDataSource {@@ -211,18 +337,10 @@ function useChannelsDataSource(if (scope === 'recents') return channels;- const activeSort =- sortMethod() ?? CHANNELS_QUERY_DEFINITIONS[scope].params.sort_method;- const sortDate = (channel: ChannelEntity) =>- activeSort === 'created_at'- ? channel.createdAt- : activeSort === 'viewed_at'- ? channel.viewedAt- : channel.updatedAt;-- return channels- .slice()- .sort((left, right) => compareDateDesc(sortDate(left), sortDate(right)));+ return sortChannels(+ channels,+ sortMethod() ?? CHANNELS_QUERY_DEFINITIONS[scope].params.sort_method+ );}, []);return {@@ -248,7 +366,7 @@ function useChannelsDataSource(export function useChannelsSources(enabled: (scope: ChannelsSourceScope) => boolean,- sortBy: (group: ChannelsGroup) => ChannelListSort+ sortBy: (group: ChannelsSortGroup) => ChannelListSort): ChannelsSources {return {channels: useChannelsDataSource(@@ -271,6 +389,10 @@ export function useChannelsSources(() => enabled('search'),() => undefined),+ threads: useThreadChannelsDataSource(+ () => enabled('threads'),+ () => sortBy('threads')+ ),};}diff --git a/apps/web/src/features/channels-view/queries/channel-search-source.ts b/apps/web/src/features/channels-view/queries/channel-search-source.tsindex a0e0bbbdfe..9a3e834d87 100644--- a/apps/web/src/features/channels-view/queries/channel-search-source.ts+++ b/apps/web/src/features/channels-view/queries/channel-search-source.ts@@ -38,7 +38,7 @@ export function createChannelSearchSource(options: {channel_types: match(options.scope()).with('direct_messages', () => ['direct_message']).with('channels', () => ['public', 'private', 'team'])- .with('recents', 'search', () => undefined)+ .with('recents', 'search', 'threads', () => undefined).exhaustive(),},},@@ -63,9 +63,11 @@ export function createChannelSearchSource(options: {...channel,...loadedById.get(channel.id),}));- // Recent search includes both channels and DMs, even without message metadata.+ // Recent and Threads search include both channels and DMs, even without+ // message metadata.+ const scope = options.scope();return filterChannelsForScope(- options.scope() === 'recents' ? 'search' : options.scope(),+ scope === 'recents' || scope === 'threads' ? 'search' : scope,matches);});diff --git a/apps/web/src/features/channels-view/queries/channel-threads.test.ts b/apps/web/src/features/channels-view/queries/channel-threads.test.tsnew file mode 100644index 0000000000..5c075efeea--- /dev/null+++ b/apps/web/src/features/channels-view/queries/channel-threads.test.ts@@ -0,0 +1,44 @@+import { createRoot } from 'solid-js';+import { createStore } from 'solid-js/store';+import { describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({ query: undefined as unknown }));++// Keep the Soup client (and its socket) out of jsdom; the test drives the query.+vi.mock('@queries/soup/items', () => ({+ useSoupAstItemsQuery: () => state.query,+}));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user-1' }));+vi.mock('@entity', () => ({+ isChannelThreadEntity: (entity: { type: string }) =>+ entity.type === 'channel_thread',+}));++import { useChannelThreadsQuery } from './channel-threads';++describe('useChannelThreadsQuery', () => {+ it('never shows placeholder threads from the previous conversation', () => {+ const [query, setQuery] = createStore({+ isEnabled: true,+ isLoading: false,+ isPlaceholderData: false,+ data: {+ entities: [{ type: 'channel_thread', id: 'a1', channelId: 'a' }],+ },+ });+ state.query = query;+ createRoot((dispose) => {+ const hook = useChannelThreadsQuery(+ () => 'a',+ () => true+ );+ expect(hook.threads().map((thread) => thread.id)).toEqual(['a1']);++ // Switching keeps the old rows as placeholder data on the REST path.+ setQuery({ isPlaceholderData: true });+ expect(hook.isPending()).toBe(true);+ expect(hook.threads()).toEqual([]);+ dispose();+ });+ });+});diff --git a/apps/web/src/features/channels-view/queries/channel-threads.ts b/apps/web/src/features/channels-view/queries/channel-threads.tsnew file mode 100644index 0000000000..6f87bf64f9--- /dev/null+++ b/apps/web/src/features/channels-view/queries/channel-threads.ts@@ -0,0 +1,31 @@+import { useUserId } from '@core/context/user';+import { type ChannelThreadEntity, isChannelThreadEntity } from '@entity';+import { useSoupAstItemsQuery } from '@queries/soup/items';+import { type Accessor, createMemo } from 'solid-js';+import { channelThreadsQueryArgs } from '../core/channel-threads-query';++export function useChannelThreadsQuery(+ channelId: Accessor<string | undefined>,+ enabled: Accessor<boolean>+) {+ const userId = useUserId();+ const query = useSoupAstItemsQuery(+ () => channelThreadsQueryArgs(userId() ?? '', channelId()),+ () => ({ enabled: enabled() && Boolean(userId()), staleTime: 30_000 })+ );+ // Soup's REST path keeps the previous filter's rows as placeholder data+ // while a new filter loads. Another conversation's threads must never show+ // under this one, so placeholder data counts as still loading.+ const isPending = () => query.isLoading || query.isPlaceholderData;+ // Gate the data read on loading so a pending query never suspends the list.+ const threads = createMemo<ChannelThreadEntity[]>(() =>+ query.isEnabled && !isPending()+ ? (query.data?.entities ?? []).filter(+ (entity): entity is ChannelThreadEntity =>+ isChannelThreadEntity(entity) && !entity.deletedAt+ )+ : []+ );++ return { query, threads, isPending };+}diff --git a/apps/web/src/features/channels-view/types.ts b/apps/web/src/features/channels-view/types.tsindex 7903eb4c06..4579bf7057 100644--- a/apps/web/src/features/channels-view/types.ts+++ b/apps/web/src/features/channels-view/types.ts@@ -1,9 +1,12 @@-export type ChannelsTab = 'browse' | 'recents';+export type ChannelsTab = 'browse' | 'recents' | 'threads';export type ChannelsGroup = 'channels' | 'direct_messages';export type ChannelListSort = 'viewed_at' | 'updated_at' | 'created_at';+/** Lists with their own sort preference: the All tab groups and the Threads rail. */+export type ChannelsSortGroup = ChannelsGroup | 'threads';+/** Collapsible sections of the All tab. */export type ChannelsRailSection = 'favorites' | ChannelsGroup;@@ -18,7 +21,13 @@ export type ChannelsViewState = {* only the open/closed state is personal, so it is stored by label id.*/collapsedLabels: string[];- sortBy: Record<ChannelsGroup, ChannelListSort>;+ /**+ * Threads tab filter: the conversation whose threads are shown, or all.+ * Kept in view state rather than the URL: a search-param change replaces the+ * split's history entry, which is too costly for a per-click filter.+ */+ threadsChannelId: string | undefined;+ sortBy: Record<ChannelsSortGroup, ChannelListSort>;asideWidth: number;};diff --git a/apps/web/src/features/channels-view/utils.test.ts b/apps/web/src/features/channels-view/utils.test.tsnew file mode 100644index 0000000000..726923f9ab--- /dev/null+++ b/apps/web/src/features/channels-view/utils.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';+import { activeChannelsTab } from './utils';++describe('activeChannelsTab', () => {+ it('shows All for a stored Threads tab while the flag is off or loading', () => {+ expect(activeChannelsTab('threads', false)).toBe('browse');+ });++ it('shows Threads once the flag is on', () => {+ expect(activeChannelsTab('threads', true)).toBe('threads');+ });++ it('leaves the other tabs alone', () => {+ expect(activeChannelsTab('recents', false)).toBe('recents');+ expect(activeChannelsTab('browse', false)).toBe('browse');+ });+});diff --git a/apps/web/src/features/channels-view/utils.ts b/apps/web/src/features/channels-view/utils.tsindex 13581d214e..35922b702c 100644--- a/apps/web/src/features/channels-view/utils.ts+++ b/apps/web/src/features/channels-view/utils.ts@@ -1,6 +1,6 @@import type { DateValue } from '@core/util/date';import type { ChannelEntity } from '@entity';-import type { ChannelsGroup } from './types';+import type { ChannelsGroup, ChannelsTab } from './types';export function isDirectMessage(channel: ChannelEntity) {return channel.channelType === 'direct_message';@@ -49,3 +49,14 @@ export function formatDetailedTimestamp(timestamp: DateValue) {timeStyle: 'short',});}++/**+ * The tab to render for a stored choice. Threads falls back to All while its+ * flag is off or still loading, without rewriting the stored choice.+ */+export function activeChannelsTab(+ tab: ChannelsTab,+ threadsEnabled: boolean+): ChannelsTab {+ return tab === 'threads' && !threadsEnabled ? 'browse' : tab;+}diff --git a/apps/web/src/features/soup/filters/facets/constants.ts b/apps/web/src/features/soup/filters/facets/constants.tsindex 341f70b9d3..b806d27c1a 100644--- a/apps/web/src/features/soup/filters/facets/constants.ts+++ b/apps/web/src/features/soup/filters/facets/constants.ts@@ -130,6 +130,7 @@ export const FILTER_TARGETS = {notification: 'done',domain: [true, false],},+ channelThreadHasReplies: { backend: 'HasReplies', domain: [true, false] },},// cf — chats / agents@@ -263,6 +264,7 @@ type FilterTargetsMeta = {channelThreadParticipantId: string[];channelThreadSeen: boolean;channelThreadDone: boolean;+ channelThreadHasReplies: boolean;};// cf — chats / agentsdiff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 4c47f0f32c..32cfe298cc 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -625,6 +625,15 @@ export const enableChannelTags = defineFlag({env: 'ENABLE_CHANNEL_TAGS',});+// The Chat view's Threads tab: channel threads filtered by conversation.+// On in development; PostHog decides elsewhere. Override with+// VITE_ENABLE_CHANNEL_THREADS_PREVIEW.+export const enableChannelThreadsPreview = defineFlag({+ key: 'enable-channel-threads-preview',+ env: 'ENABLE_CHANNEL_THREADS_PREVIEW',+ default: onInDev,+});+// The "Activity" section in the entity side panel: the entity's recent// activity timeline from the GraphQL activity log (who did what, when).// Purely additive — when off, the section never mounts and no activitydiff --git a/apps/web/src/lib/queries/soup/graphql/ast.ts b/apps/web/src/lib/queries/soup/graphql/ast.tsindex 7a5d4ca57d..55fa024a69 100644--- a/apps/web/src/lib/queries/soup/graphql/ast.ts+++ b/apps/web/src/lib/queries/soup/graphql/ast.ts@@ -416,7 +416,8 @@ type ChannelThreadLiteralField =| 'RootSender'| 'Sender'| 'Participant'- | 'NotificationState';+ | 'NotificationState'+ | 'HasReplies';const CHANNEL_THREAD_LITERAL_FIELDS = ['ThreadId',@@ -425,6 +426,7 @@ const CHANNEL_THREAD_LITERAL_FIELDS = ['Sender','Participant','NotificationState',+ 'HasReplies',] as const satisfies readonly ChannelThreadLiteralField[];function isChannelThreadLiteralField(@@ -452,6 +454,9 @@ function mapChannelThreadLiteral(.with('Participant', () => ({participant: mapString(value, 'participant'),}))+ .with('HasReplies', () => ({+ hasReplies: mapBoolean(value, 'hasReplies'),+ })).with('NotificationState', () => ({notificationState: mapNotificationState(value),}))diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.tsindex 2a87b1e1eb..71b4a2552f 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts@@ -312,14 +312,16 @@ export type GraphqlChannelThreadExpr =/** GraphQL input representing the channel thread literal. */export type GraphqlChannelThreadLiteral ={ /** The channel id option. */- channelId: string | number; notificationState?: never; participant?: never; rootSender?: never; threadId?: never; }- | { channelId?: never; /** Exact notification state for the requester. */+ channelId: string | number; hasReplies?: never; notificationState?: never; participant?: never; rootSender?: never; threadId?: never; }+ | { channelId?: never; /** Whether the thread has at least one undeleted reply. */+ hasReplies: boolean; notificationState?: never; participant?: never; rootSender?: never; threadId?: never; }+ | { channelId?: never; hasReplies?: never; /** Exact notification state for the requester. */notificationState: NotificationState; participant?: never; rootSender?: never; threadId?: never; }- | { channelId?: never; notificationState?: never; /** The participant option. */+ | { channelId?: never; hasReplies?: never; notificationState?: never; /** The participant option. */participant: string; rootSender?: never; threadId?: never; }- | { channelId?: never; notificationState?: never; participant?: never; /** The root sender option. */+ | { channelId?: never; hasReplies?: never; notificationState?: never; participant?: never; /** The root sender option. */rootSender: string; threadId?: never; }- | { channelId?: never; notificationState?: never; participant?: never; rootSender?: never; /** The thread id option. */+ | { channelId?: never; hasReplies?: never; notificationState?: never; participant?: never; rootSender?: never; /** The thread id option. */threadId: string | number; };/** GraphQL input representing the channel type filter. */diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rsindex 3c0da14da0..4418c8f11b 100644--- a/crates/channels/src/outbound/pg_channels_repo.rs+++ b/crates/channels/src/outbound/pg_channels_repo.rs@@ -1065,6 +1065,19 @@ fn push_channel_thread_filter_expr(Expr::Literal(ChannelThreadLiteral::Participant(participant)) => {push_channel_thread_participant_filter_expr(builder, participant);}+ Expr::Literal(ChannelThreadLiteral::HasReplies(has_replies)) => {+ // Counts replies the same way as `thread_stats` in the rows query.+ builder.push(+ r#"(EXISTS (+ SELECT 1+ FROM comms_messages reply+ WHERE reply.thread_id = m.id+ AND reply.deleted_at IS NULL+ ) = "#,+ );+ builder.push_bind(*has_replies);+ builder.push(")");+ }Expr::Literal(ChannelThreadLiteral::NotificationState(state)) => {push_channel_thread_notification_filter_expr(builder,diff --git a/crates/channels/src/outbound/pg_channels_repo/tests.rs b/crates/channels/src/outbound/pg_channels_repo/tests.rsindex 1632980b3d..261fe2547e 100644--- a/crates/channels/src/outbound/pg_channels_repo/tests.rs+++ b/crates/channels/src/outbound/pg_channels_repo/tests.rs@@ -1387,6 +1387,90 @@ async fn channel_thread_rows_filter_by_root_sender(pool: Pool<Postgres>) -> anyhOk(())}+async fn thread_ids_matching(+ pool: Pool<Postgres>,+ querying_user: &str,+ filter: Expr<ChannelThreadLiteral>,+) -> anyhow::Result<Vec<Uuid>> {+ let rows = repo(pool)+ .get_thread_messages(+ thread_rows_request(+ querying_user,+ Some(Arc::new(filter)),+ SimpleSortMethod::UpdatedAt,+ 50,+ )+ .into_params(),+ )+ .await+ .map_err(report_err)?;+ Ok(rows.iter().map(|row| row.id).collect())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn channel_thread_rows_filter_by_has_replies(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // user-a rooted msg1 (four replies), msg31 (one reply) and msg3 (none).+ let root_sender = || Expr::val(ChannelThreadLiteral::RootSender(macro_user_id(USER_A)));+ let with_replies = thread_ids_matching(+ pool.clone(),+ USER_A,+ Expr::and(+ root_sender(),+ Expr::val(ChannelThreadLiteral::HasReplies(true)),+ ),+ )+ .await?;+ assert_eq!(with_replies, vec![MSG1, MSG31]);++ let without_replies = thread_ids_matching(+ pool,+ USER_A,+ Expr::and(+ root_sender(),+ Expr::val(ChannelThreadLiteral::HasReplies(false)),+ ),+ )+ .await?;+ assert_eq!(without_replies, vec![MSG3]);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn channel_thread_rows_filter_hides_unanswered_own_roots(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // The web Threads tab: threads user-a takes part in, minus roots they sent+ // that nobody answered. msg3 is user-a's unanswered root.+ let participant = Expr::val(ChannelThreadLiteral::Participant(macro_user_id(USER_A)));+ let unanswered_own_root = Expr::and(+ Expr::val(ChannelThreadLiteral::RootSender(macro_user_id(USER_A))),+ Expr::val(ChannelThreadLiteral::HasReplies(false)),+ );+ let parent_ids = thread_ids_matching(+ pool.clone(),+ USER_A,+ Expr::and(participant.clone(), Expr::is_not(unanswered_own_root)),+ )+ .await?;+ let all_participating = thread_ids_matching(pool, USER_A, participant).await?;++ assert!(all_participating.contains(&MSG3));+ assert_eq!(+ parent_ids,+ all_participating+ .into_iter()+ .filter(|id| *id != MSG3)+ .collect::<Vec<_>>()+ );+ Ok(())+}+async fn threads_matching_participant(pool: Pool<Postgres>,querying_user: &str,diff --git a/crates/graphql_soup_filter_input/src/lib.rs b/crates/graphql_soup_filter_input/src/lib.rsindex ecc52d36ed..847910f8a1 100644--- a/crates/graphql_soup_filter_input/src/lib.rs+++ b/crates/graphql_soup_filter_input/src/lib.rs@@ -1022,6 +1022,8 @@ enum GraphqlChannelThreadLiteral {Participant(String),/// Exact notification state for the requester.NotificationState(GraphqlNotificationState),+ /// Whether the thread has at least one undeleted reply.+ HasReplies(bool),}impl IntoFilterExpr<ChannelThreadLiteral> for GraphqlChannelThreadLiteral {@@ -1037,6 +1039,7 @@ impl IntoFilterExpr<ChannelThreadLiteral> for GraphqlChannelThreadLiteral {ChannelThreadLiteral::Participant(parse_macro_user_id(participant, "participant")?)}Self::NotificationState(state) => ChannelThreadLiteral::NotificationState(state.into()),+ Self::HasReplies(has_replies) => ChannelThreadLiteral::HasReplies(has_replies),};Ok(Expr::val(literal))}diff --git a/crates/graphql_soup_filter_input/src/test.rs b/crates/graphql_soup_filter_input/src/test.rsindex 43e3db137e..93ae4feb32 100644--- a/crates/graphql_soup_filter_input/src/test.rs+++ b/crates/graphql_soup_filter_input/src/test.rs@@ -1,5 +1,7 @@use filter_ast::Expr;-use item_filters::ast::{chat::ChatLiteral, document::DocumentLiteral};+use item_filters::ast::{+ channel::ChannelThreadLiteral, chat::ChatLiteral, document::DocumentLiteral,+};use serde_json::{Value, json};use super::*;@@ -186,3 +188,22 @@ fn initiative_property_filters_preserve_entity_scope() {}))));}++#[test]+fn channel_thread_has_replies_materializes_for_browser_and_server() {+ for has_replies in [true, false] {+ let value = json!({+ "channelThreadFilter": {"literal": {"hasReplies": has_replies}}+ });+ let ast = materialize_graphql_filter(value.clone()).unwrap();+ assert!(matches!(+ ast.channel_thread_filter.as_deref(),+ Some(Expr::Literal(ChannelThreadLiteral::HasReplies(v))) if *v == has_replies+ ));+ let input: GraphqlEntityFilterAst = serde_json::from_value(value).unwrap();+ assert_eq!(+ serde_json::to_value(ast).unwrap(),+ serde_json::to_value(input.into_ast().unwrap()).unwrap()+ );+ }+}diff --git a/crates/item_filters/src/ast/channel.rs b/crates/item_filters/src/ast/channel.rsindex 71376a8f49..68b9e04e51 100644--- a/crates/item_filters/src/ast/channel.rs+++ b/crates/item_filters/src/ast/channel.rs@@ -160,6 +160,8 @@ pub enum ChannelThreadLiteral {Participant(MacroUserIdStr<'static>),/// An entity has a non-deleted notification in this exact state.NotificationState(crate::NotificationState),+ /// Whether the thread has at least one undeleted reply.+ HasReplies(bool),}impl ExpandFrame<ChannelThreadLiteral> for ChannelThreadFilters {diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 8d64d2d5ab..cc5baf5ca4 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -423,6 +423,30 @@ Deferred navigation waits until the destination is applied; an unavailable splitmust leave unread state unchanged. Join-only channels remainblocked after hydration, including on mobile.+### Threads tab++The `enable-channel-threads-preview` feature flag adds a third `Threads` tab.+It is on in development; `VITE_ENABLE_CHANNEL_THREADS_PREVIEW` overrides it+locally. The rail shows an `All threads` row above a `Conversations` section+with the same sort and `+` controls as the All tab's sections. Conversations+lists only channels and DMs that hold threads the user takes part in; it pages+through the user's threads and loads their channels, so scrolling the section+reveals more. Selecting a row filters the main pane instead of opening the+conversation. `All threads` clears the filter.++The main pane is a virtualized list of channel threads the user takes part in,+newest reply first. It loads more as it nears the end and returns to the top+when the selected conversation changes. Messages the user sent that have no+replies are hidden. Each card shows the root message with its replies collapsed+the same way as a channel timeline: the first reply groups, then a+`N more replies` control that expands the rest in place. In `All threads`, each+card is labelled with its conversation. An icon button (`View in channel`)+appears at a card's top right on hover or focus, and always on touch; it+switches back to `All` and opens the channel at that thread. Shift-clicking a+conversation row opens it in a new split. The filter lives in the view's state,+not the URL: it survives back/forward within the split and reloads, but a+copied link opens the Threads tab on `All threads`.+### Channel labelsChannel labels require the `enable-channel-tags` feature flag. The flag is offdiff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex c3dc883e3d..a728183dc1 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -1458,6 +1458,10 @@ input GraphqlChannelThreadLiteral @oneOf {Exact notification state for the requester."""notificationState: NotificationState+ """+ Whether the thread has at least one undeleted reply.+ """+ hasReplies: Boolean}"""