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(mobile): search across views (#7120)
Peter Chinmana9b9d37d9a47
diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsxindex 328b833051..a501117fca 100644--- a/apps/web/src/features/channels-view/channels-view.test.tsx+++ b/apps/web/src/features/channels-view/channels-view.test.tsx@@ -93,7 +93,10 @@ vi.mock('@core/component/LexicalMarkdown/component/core/StaticMarkdown',() => ({ StaticMarkdownContext: mocks.pass }));-vi.mock('@entity', () => ({ ListEntityMetadataQueryProvider: mocks.pass }));+vi.mock('@entity', async () => ({+ ...(await import('@entity/types/entity')),+ ListEntityMetadataQueryProvider: mocks.pass,+}));vi.mock('./components/ChannelDetailView', () => ({ChannelDetailView: (props: { channel: ChannelEntity }) => (<div data-testid="channel-detail">@@ -105,9 +108,9 @@ vi.mock('./components/ChannelDetailView', () => ({vi.mock('./components/ChannelsMobileView', () => ({ChannelsMobileView: (props: {source: ChannelsDataSource;- searchText: string;+ searchQuery: string;}) => (- <div data-testid="mobile-channels" data-query={props.searchText}>+ <div data-testid="mobile-channels" data-query={props.searchQuery}><For each={props.source.items()}>{(channel) => <div>{channel.name}</div>}</For>@@ -115,6 +118,12 @@ vi.mock('./components/ChannelsMobileView', () => ({),}));vi.mock('./components/rail/ChannelsRail', () => ({ ChannelsRail: () => null }));+vi.mock('@core/mobile/isTouchDevice', () => ({+ isTouchDevice: () => mocks.mobileLayout(),+}));+vi.mock('@app/features/soup/search/context', () => ({+ useOptionalSearchContext: () => undefined,+}));vi.mock('./channels-view-context', () => ({ChannelsViewProvider: mocks.pass,useChannelsView: () => ({@@ -136,6 +145,8 @@ vi.mock('./channels-view-context', () => ({}),}));vi.mock('./queries', () => ({+ filterChannelsForScope: (_scope: string, channels: ChannelEntity[]) =>+ channels,deduplicateChannels: (collections: ChannelEntity[][]) => [...new Map(collections.flat().map((channel) => [channel.id, channel])@@ -235,7 +246,7 @@ beforeEach(() => {afterEach(cleanup);describe('mobile dock search wiring', () => {- it('filters DMs from the active dock session and restores rows on close or navigation', () => {+ it('filters DMs from the active dock session and restores rows on close or navigation', async () => {mocks.mobileLayout = () => true;mocks.mobileTab = () => 'direct_messages';const [open, setOpen] = createSignal(true);@@ -255,12 +266,14 @@ describe('mobile dock search wiring', () => {render(() => <ChannelsView />);expect(screen.getByText('hutch')).toBeTruthy();setText('Julia');- expect(screen.getByText('Julia Westphal')).toBeTruthy();- expect(screen.queryByText('hutch')).toBeNull();+ await waitFor(() =>+ expect(screen.getByText('Julia Westphal')).toBeTruthy()+ );+ await waitFor(() => expect(screen.queryByText('hutch')).toBeNull());setActive(false);expect(screen.getByText('hutch')).toBeTruthy();setActive(true);- expect(screen.queryByText('hutch')).toBeNull();+ await waitFor(() => expect(screen.queryByText('hutch')).toBeNull());setOpen(false);expect(screen.getByText('hutch')).toBeTruthy();expect(screen.getByTestId('mobile-channels').dataset.query).toBe('');diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsxindex 4432567335..fb3eb1a6d4 100644--- a/apps/web/src/features/channels-view/channels-view.tsx+++ b/apps/web/src/features/channels-view/channels-view.tsx@@ -1,5 +1,6 @@import { ViewShell } from '@app/components/view-shell';import { SearchState } from '@app/features/command/mobile/mobileSearchState';+import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';import { markChannelNotificationsSeenOnOpen } from '@app/features/next-soup/utils';import { MaybeSoupEntityActionDrawerManager } from '@app/features/soup';import { withEntityNotifications } from '@app/features/soup/entity-notifications';@@ -32,49 +33,65 @@ import {useChannelByIdQuery,useChannelsSources,} from './queries';-import { useMobileChannelSearch } from './queries/mobile-channel-search';+import { createChannelSearchSource } from './queries/channel-search-source';const ChannelSourcesContext =createContext<ReturnType<typeof useChannelsSources>>();-import type { ChannelsQueryScope, ChannelsViewStateOptions } from './types';+import type { ChannelsViewStateOptions } from './types';export type ChannelsViewProps = {/** Explicit navigation state. When present, it wins over entry restoration. */initialState?: ChannelsViewStateOptions;};-function MobileChannels(props: {- sources: ChannelsSources;- tab: ChannelsQueryScope;- onTabChange: (tab: ChannelsQueryScope) => void;-}) {+// Mounted inside the mobile list's Suspense boundary.+function MobileChannelsList(props: { sources: ChannelsSources }) {const panel = useSplitPanelOrThrow();- // The dock lives outside the split. Derive its query only for the active- // mobile list so closing search or navigating away restores ordinary rows.- const searchText = () =>- SearchState.isOpen() && panel.handle.isActive()- ? SearchState.query().trim()- : '';- const source = useMobileChannelSearch({- text: searchText,- scope: () => props.tab,- source: () => props.sources[props.tab],+ const { state, setMobileTab } = useChannelsView();+ const mobileSearchText = useMobileSearchText(() => '', panel.handle.isActive);+ const mobileSearchSource = createChannelSearchSource({+ text: mobileSearchText,+ scope: () => state.mobileTab,+ source: () => props.sources[state.mobileTab],});-return (<ChannelsMobileView- source={source}- tab={props.tab}- onTabChange={props.onTabChange}- searchText={searchText()}+ source={mobileSearchSource}+ searchQuery={mobileSearchText()}+ onClearSearch={() => SearchState.setQuery('')}+ tab={state.mobileTab}+ onTabChange={setMobileTab}+ />+ );+}++function DesktopChannelsRail(props: {+ sources: ChannelsSources;+ searchOpen: boolean;+ onSearchOpenChange: (open: boolean) => void;+}) {+ const [searchQuery, setSearchQuery] = createSignal('');+ const searchSource = createChannelSearchSource({+ text: searchQuery,+ enabled: () => props.searchOpen,+ scope: () => 'search',+ source: () => props.sources.search,+ });+ return (+ <ChannelsRail+ sources={{ ...props.sources, search: searchSource }}+ searchQuery={searchQuery()}+ onSearchQueryChange={setSearchQuery}+ searchOpen={props.searchOpen}+ onSearchOpenChange={props.onSearchOpenChange}/>);}function ChannelsViewRoot() {const panel = useSplitPanelOrThrow();- const { state, mobileLayout, selectedChannel, setAsideWidth, setMobileTab } =+ const { state, mobileLayout, selectedChannel, setAsideWidth } =useChannelsView();const [railSearchOpen, setRailSearchOpen] = createSignal(false);@@ -112,8 +129,16 @@ function ChannelsViewRoot() {resizable><ViewShell.Aside onWidthChangeEnd={setAsideWidth}>- <DebugSuspense name="ChannelsView.rail">- <ChannelsRail+ <DebugSuspense+ name="ChannelsView.rail"+ fallback={+ <SpinnerIcon+ aria-label="Loading channels"+ class="size-5 animate-spin"+ />+ }+ >+ <DesktopChannelsRailsources={sources}searchOpen={railSearchOpen()}onSearchOpenChange={setRailSearchOpen}@@ -164,11 +189,7 @@ function ChannelsViewRoot() {</div>}>- <MobileChannels- sources={sources}- tab={state.mobileTab}- onTabChange={setMobileTab}- />+ <MobileChannelsList sources={sources} /></DebugSuspense></MaybeSoupEntityActionDrawerManager></Show>diff --git a/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx b/apps/web/src/features/channels-view/components/ChannelsMobileView.tsxindex 2464dec47d..d4bd48cd7c 100644--- a/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx+++ b/apps/web/src/features/channels-view/components/ChannelsMobileView.tsx@@ -14,6 +14,7 @@ import EmptyStateNoSearchMatchGraphic from '@design/empty-state-no-search-match.import type { ChannelEntity } from '@entity';import { isMutedItem } from '@entity/utils/notification';import SpinnerIcon from '@phosphor/spinner.svg';+import XIcon from '@phosphor/x.svg';import { hydrateChannelNotificationSelection } from '@queries/channel/notification-selection';import { createElementSize } from '@solid-primitives/resize-observer';import { Button, EmptyStatePanel } from '@ui';@@ -54,9 +55,10 @@ const LOAD_MORE_THRESHOLD = 300;export function ChannelsMobileView(props: {source: ChannelsDataSource;+ searchQuery: string;+ onClearSearch: () => void;tab: ChannelsQueryScope;onTabChange: (tab: ChannelsQueryScope) => void;- searchText?: string;}) {const panel = useSplitPanelOrThrow();const notificationSource = useGlobalNotificationSource();@@ -89,7 +91,7 @@ export function ChannelsMobileView(props: {createEffect(on(- () => props.searchText,+ () => props.searchQuery,() => viewport()?.scrollTo({ top: 0 })));@@ -207,22 +209,30 @@ export function ChannelsMobileView(props: {</Match><Match when={forceEmptyState() || visibleChannels().length === 0}><Show- when={props.searchText}+ when={props.searchQuery.trim()}fallback={<ChannelsEmptyState scope={props.tab} />}>- <EmptyStatePanel- centered- graphic={EmptyStateNoSearchMatchGraphic}- title="No results"- description={- <span>- No conversations match{' '}- <span class="[overflow-wrap:anywhere]">- “{props.searchText}”+ {(query) => (+ <EmptyStatePanel+ centered+ graphic={EmptyStateNoSearchMatchGraphic}+ title="No results"+ description={+ <span>+ No conversations match{' '}+ <span class="[overflow-wrap:anywhere]">+ “{query()}”+ </span></span>- </span>- }- />+ }+ primaryAction={{+ label: 'Clear search',+ icon: XIcon,+ onClick: props.onClearSearch,+ }}+ class="h-auto touch:pt-0 touch:pb-(--mobile-content-inset-bottom)"+ />+ )}</Show></Match><Match when={true}>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 6497237a51..cebc77fa5f 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@@ -192,6 +192,8 @@ const mount = () =>render(() => (<ChannelsRailsources={sources}+ searchQuery=""+ onSearchQueryChange={() => {}}searchOpen={false}onSearchOpenChange={() => {}}/>diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsxindex bd1ecd130c..289c02ce55 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx@@ -8,7 +8,6 @@ import {useViewControlHotkeys,useViewTabHotkeys,} from '@app/components/view-shell';-import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';import {type ChannelPreviewSelection,channelPreviewSelection,@@ -32,13 +31,11 @@ import {import { toast } from '@core/component/Toast/Toast';import { enableChannelTags } from '@core/constant/featureFlags';import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';-import { debouncedDependent } from '@core/util/debounce';import { thrownResultErrorHasCode } from '@core/util/result';import {type ChannelEntity,isChannelEntity,type WithNotification,- type WithSearch,} from '@entity';import { notificationIsRead } from '@entity/utils/notification';import { ensureNotificationSourceLoaded } from '@notifications/notification-helpers';@@ -51,8 +48,6 @@ import {useSetChannelLabelMutation,} from '@queries/channel-labels/channel-labels';import { useFavoritesData } from '@queries/favorites/favorites';-import { useSearchSoupQuery } from '@queries/soup/search';-import type { EntityFilters } from '@service-search/generated/models';import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';import { debounce } from '@solid-primitives/scheduled';import { useDragDropContext } from '@thisbeyond/solid-dnd';@@ -120,14 +115,12 @@ const LABEL_KEY_PREFIX = 'label:';const BROWSE_QUERY_SCOPES = ['channels', 'direct_messages'] as const;const CHANNEL_TAB_IDS: ChannelsTab[] = ['browse', 'recents'];const DM_LOADING_PREVIEW_OFFSET = 80;-const CHANNEL_SEARCH_FILTERS = {- ...QUERY_FILTERS_BASE,- channel_filters: { is_participant: true },-} satisfies EntityFilters;export type ChannelsRailProps = {sources: ChannelsSources;searchOpen: boolean;+ searchQuery: string;+ onSearchQueryChange: (query: string) => void;onSearchOpenChange: (open: boolean) => void;};@@ -259,14 +252,11 @@ export function ChannelsRail(props: ChannelsRailProps) {Partial<Record<ChannelsSourceScope, VirtualizerHandle>>>({});- const [searchQuery, setSearchQuery] = createSignal('');+ const searchQuery = () => props.searchQuery;+ const setSearchQuery = (query: string) => props.onSearchQueryChange(query);const [restoreListScroll, setRestoreListScroll] = createSignal(false);- const normalizedSearchQuery = () => searchQuery().trim();-- const serviceSearchQuery = debouncedDependent(normalizedSearchQuery, 300);-let searchInput: HTMLInputElement | undefined;const previewAfterNavigation = debounce(@@ -303,73 +293,10 @@ export function ChannelsRail(props: ChannelsRailProps) {]));- const channelSearchQuery = useSearchSoupQuery(- () => ({- params: { page_size: 100 },- body: {- query: serviceSearchQuery(),- match_type: 'partial',- search_on: 'name',- filters: CHANNEL_SEARCH_FILTERS,- },- }),- () => ({- enabled:- props.searchOpen && normalizedSearchQuery() === serviceSearchQuery(),- })- );-- const localSearchResults = createMemo(() => {- const query = normalizedSearchQuery().toLocaleLowerCase();- const items = props.sources.search.items();- if (!query) return items;-- return items.filter((channel) =>- channel.name.toLocaleLowerCase().includes(query)- );- });-- const serviceSearchResults = createMemo(() => {- if (- normalizedSearchQuery() !== serviceSearchQuery() ||- channelSearchQuery.isFetching ||- !channelSearchQuery.isSuccess- ) {- return [];- }-- return channelSearchQuery.data.filter(- (entity): entity is WithSearch<ChannelEntity> => isChannelEntity(entity)- );- });-- const searchResults = createMemo(() =>- deduplicateChannels([localSearchResults(), serviceSearchResults()])- );-- const searchLoading = () =>- props.sources.search.isLoading() ||- (normalizedSearchQuery().length >= 3 &&- (normalizedSearchQuery() !== serviceSearchQuery() ||- channelSearchQuery.isFetching));-- const searchError = () => {- if (- normalizedSearchQuery() === serviceSearchQuery() &&- channelSearchQuery.error instanceof Error- ) {- return channelSearchQuery.error;- }-- return props.sources.search.error() ?? undefined;- };-- const retrySearch = async () => {- await props.sources.search.refresh();- if (normalizedSearchQuery().length >= 3) {- await channelSearchQuery.refetch();- }- };+ const searchResults = () => props.sources.search.items();+ const searchLoading = () => props.sources.search.isFetching();+ const searchError = () => props.sources.search.error();+ const retrySearch = () => props.sources.search.refresh();// Shared or private labels; channel membership is always viewer-relative.const labelsQuery = useChannelLabelsQuery();@@ -858,7 +785,7 @@ export function ChannelsRail(props: ChannelsRailProps) {};const labelChannelById = (channelId: string) =>channelsById().get(channelId) ??- serviceSearchResults().find((channel) => channel.id === channelId);+ searchResults().find((channel) => channel.id === channelId);const channelName = (channelId: string) => {const name = labelChannelById(channelId)?.name;return name ? `#${name}` : 'the channel';diff --git a/apps/web/src/features/channels-view/queries/channel-search-source.test.ts b/apps/web/src/features/channels-view/queries/channel-search-source.test.tsnew file mode 100644index 0000000000..c3383e7ede--- /dev/null+++ b/apps/web/src/features/channels-view/queries/channel-search-source.test.ts@@ -0,0 +1,367 @@+import type { ChannelEntity } from '@entity/types/entity';+import type { useSearchSoupQuery } from '@queries/soup/search';+import { createRoot, createSignal } from 'solid-js';+import { createStore } from 'solid-js/store';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { ChannelsDataSource, ChannelsSourceScope } from '../queries';+import { createChannelSearchSource } from './channel-search-source';++const queryMock = vi.hoisted(() => vi.fn());+vi.mock('@queries/soup/search', () => ({+ useSearchSoupQuery: queryMock,+ validateSearchServiceText: (text: string) => text.length >= 3,+}));+vi.mock('@queries/soup/items', () => ({ useSoupAstItemsQuery: vi.fn() }));+vi.mock('@app/features/soup/search/context', () => ({+ useOptionalSearchContext: () => undefined,+}));+vi.mock('@entity', async () => await import('@entity/types/entity'));++const channel = (id: string, name: string, direct = false): ChannelEntity => ({+ id,+ name,+ type: 'channel',+ ownerId: 'viewer',+ isParticipant: true,+ channelType: direct ? 'direct_message' : 'private',+});+const localChannel = channel('channel', 'Alpha channel');+const localDm = channel('dm', 'Alpha person', true);+let dispose: (() => void) | undefined;++function setup(initialText = '', initialScope: ChannelsSourceScope = 'search') {+ return createRoot((cleanup) => {+ dispose = cleanup;+ const [text, setText] = createSignal(initialText);+ const [scope, setScope] = createSignal(initialScope);+ const [enabled, setEnabled] = createSignal(true);+ const [rows, setRows] = createSignal([localChannel, localDm]);+ const [remote, setRemote] = createStore<{+ data: ChannelEntity[];+ isFetching: boolean;+ isFetchingNextPage: boolean;+ hasNextPage: boolean;+ isSuccess: boolean;+ isPlaceholderData: boolean;+ error: Error | null;+ }>({+ data: [],+ isFetching: false,+ isFetchingNextPage: false,+ hasNextPage: true,+ isSuccess: true,+ isPlaceholderData: false,+ error: null,+ });+ const serverNextPage = vi.fn(async () => {});+ const serverRefresh = vi.fn(async () => {});+ let request!: Parameters<typeof useSearchSoupQuery>[0];+ let queryEnabled!: () => boolean;+ queryMock.mockImplementation(+ (+ args: typeof request,+ options: Parameters<typeof useSearchSoupQuery>[1]+ ) => {+ request = args;+ queryEnabled = () => options?.().enabled ?? true;+ return {+ get data() {+ if (!remote.isSuccess)+ throw new Error('Pending data read would suspend');+ return remote.data;+ },+ get isSuccess() {+ return remote.isSuccess;+ },+ get isPlaceholderData() {+ return remote.isPlaceholderData;+ },+ get isEnabled() {+ return queryEnabled();+ },+ get isFetching() {+ return remote.isFetching;+ },+ get isFetchingNextPage() {+ return remote.isFetchingNextPage;+ },+ get error() {+ return remote.error;+ },+ get hasNextPage() {+ return remote.hasNextPage;+ },+ fetchNextPage: serverNextPage,+ refetch: serverRefresh,+ };+ }+ );+ const local: ChannelsDataSource = {+ items: rows,+ isLoading: vi.fn(() => false),+ isFetching: vi.fn(() => false),+ error: () => undefined,+ hasMore: () => true,+ isLoadingMore: () => false,+ loadMore: vi.fn(async () => {}),+ refresh: vi.fn(async () => {}),+ };+ const source = createChannelSearchSource({+ text,+ scope,+ enabled,+ source: () => local,+ });+ return {+ source,+ local,+ request,+ queryEnabled,+ setText,+ setScope,+ setEnabled,+ setRows,+ setRemote,+ serverNextPage,+ serverRefresh,+ };+ });+}++const ids = (source: ChannelsDataSource) =>+ source.items().map((item) => item.id);++describe('shared channel search source', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ });+ afterEach(() => {+ dispose?.();+ vi.useRealTimers();+ });++ it('shows the ordinary list for an empty query and restores it on clear', async () => {+ const s = setup();+ expect(ids(s.source)).toEqual(['channel', 'dm']);+ expect(s.queryEnabled()).toBe(false);+ s.setText('nonexistent');+ await vi.advanceTimersByTimeAsync(300);+ expect(ids(s.source)).toEqual([]);+ expect(s.queryEnabled()).toBe(true);+ s.setText('');+ expect(ids(s.source)).toEqual(['channel', 'dm']);+ expect(s.queryEnabled()).toBe(false);+ });++ it('merges local and remote matches once, retaining loaded conversation metadata', () => {+ const s = setup('alpha');+ s.setRemote('data', [+ channel('channel', 'Alpha updated'),+ channel('remote', 'Alpha remote'),+ ]);+ expect(new Set(ids(s.source))).toEqual(+ new Set(['channel', 'dm', 'remote'])+ );+ expect(s.source.items().filter((row) => row.id === 'channel')).toHaveLength(+ 1+ );+ expect(s.source.items().find((row) => row.id === 'channel')?.name).toBe(+ 'Alpha channel'+ );+ });++ it('shares the request while enforcing desktop All and mobile tab scopes', () => {+ const s = setup('alpha');+ expect(s.request().body).toMatchObject({+ query: 'alpha',+ search_on: 'name',+ match_type: 'partial',+ filters: { channel_filters: { is_participant: true } },+ });+ expect(ids(s.source)).toHaveLength(2);+ s.setScope('direct_messages');+ expect(s.request().body.filters?.channel_filters?.channel_types).toEqual([+ 'direct_message',+ ]);+ expect(ids(s.source)).toEqual(['dm']);+ s.setScope('channels');+ expect(s.request().body.filters?.channel_filters?.channel_types).toEqual([+ 'public',+ 'private',+ 'team',+ ]);+ expect(ids(s.source)).toEqual(['channel']);+ s.setScope('recents');+ expect(ids(s.source)).toEqual(['channel', 'dm']); // Search includes conversations without message metadata.+ });++ it('paginates and refreshes search results instead of the unfiltered list', async () => {+ const s = setup();+ await s.source.loadMore();+ expect(s.local.loadMore).toHaveBeenCalledOnce();+ s.setText('alpha');+ await vi.advanceTimersByTimeAsync(300);+ await s.source.loadMore();+ expect(s.serverNextPage).toHaveBeenCalledOnce();+ expect(s.local.loadMore).toHaveBeenCalledOnce();+ s.setRemote({ isFetching: true, isFetchingNextPage: true });+ await s.source.loadMore();+ expect(s.serverNextPage).toHaveBeenCalledOnce();+ s.setRemote({ isFetching: false, isFetchingNextPage: false });+ await s.source.refresh();+ expect(s.local.refresh).toHaveBeenCalledOnce();+ expect(s.serverRefresh).toHaveBeenCalledOnce();+ });++ it('finishes an empty search while the ordinary list is still loading', async () => {+ const s = setup('nonexistent');+ vi.mocked(s.local.isLoading).mockReturnValue(true);+ vi.mocked(s.local.isFetching).mockReturnValue(true);+ s.setRemote({ isFetching: true });+ expect(s.source.isLoading()).toBe(true);+ expect(s.source.isFetching()).toBe(true);++ s.setRemote({ isFetching: false });+ expect(ids(s.source)).toEqual([]);+ expect(s.source.isLoading()).toBe(false);+ expect(s.source.isFetching()).toBe(false);+ await s.source.loadMore();+ expect(s.serverNextPage).toHaveBeenCalledOnce();+ expect(s.local.loadMore).not.toHaveBeenCalled();++ s.setText('');+ expect(s.source.isFetching()).toBe(true);+ await s.source.loadMore();+ expect(s.local.loadMore).not.toHaveBeenCalled();+ vi.mocked(s.local.isFetching).mockReturnValue(false);+ await s.source.loadMore();+ expect(s.local.loadMore).toHaveBeenCalledOnce();+ });++ it('uses ordinary loading state only when the query is empty', async () => {+ const s = setup('nonexistent');+ s.setRows([]);+ vi.mocked(s.local.isLoading).mockReturnValue(true);+ vi.mocked(s.local.isFetching).mockReturnValue(true);+ s.setText('');+ expect(s.source.isLoading()).toBe(true);+ s.setText('zz');+ await vi.advanceTimersByTimeAsync(300);+ expect(s.queryEnabled()).toBe(false);+ expect(s.source.isLoading()).toBe(false);+ expect(s.source.isFetching()).toBe(false);+ s.setEnabled(false);+ expect(s.source.isLoading()).toBe(false);+ expect(s.source.isFetching()).toBe(false);+ });++ it('hides stale service matches during debounce and stops work when closed', async () => {+ const s = setup('alpha');+ s.setRemote('data', [channel('remote', 'Alpha remote')]);+ s.setText('bravo');+ expect(s.queryEnabled()).toBe(false);+ await vi.advanceTimersByTimeAsync(20);+ expect(ids(s.source)).toEqual([]);+ s.setRemote({ isFetching: true });+ await vi.advanceTimersByTimeAsync(280);+ expect(s.source.isLoading()).toBe(true);+ s.setRemote({ isFetching: false, error: new Error('offline'), data: [] });+ expect(s.source.error()).toEqual(new Error('offline'));+ s.setEnabled(false);+ expect(s.queryEnabled()).toBe(false);+ expect(ids(s.source)).toEqual([]);+ expect(s.source.error()).toBeUndefined();+ expect(s.source.hasMore()).toBe(false);+ await s.source.loadMore();+ await s.source.refresh();+ expect(s.serverNextPage).not.toHaveBeenCalled();+ expect(s.local.refresh).not.toHaveBeenCalled();+ });++ it('includes remote-only Recent hits without message metadata and preserves loaded previews', () => {+ const s = setup('alpha');+ const local = {+ ...localChannel,+ participantIds: ['viewer'],+ latestRootMessage: {+ messageId: 'message',+ senderId: 'viewer',+ content: 'Hello',+ mentions: [],+ createdAt: '2026-09-28T12:00:00Z',+ },+ };+ s.setRows([local]);+ s.setScope('recents');+ s.setRemote('data', [+ channel('channel', 'Alpha remote copy'),+ channel('remote', 'Alpha remote', true),+ ]);+ expect(ids(s.source)).toEqual(['channel', 'remote']);+ expect(s.source.items()[0]).toMatchObject(local);+ expect(s.source.items()[1].latestRootMessage).toBeUndefined();+ expect(s.serverNextPage).not.toHaveBeenCalled();+ expect(s.request().body.filters?.channel_filters).toEqual({+ is_participant: true,+ channel_types: undefined,+ });+ });++ it('never reads pending data or exposes placeholder hits and pagination', async () => {+ const s = setup('alpha');+ s.setRemote({ isSuccess: false });+ expect(ids(s.source)).toEqual(['channel', 'dm']);+ s.setRemote({+ isSuccess: true,+ data: [channel('remote', 'Alpha remote')],+ isPlaceholderData: true,+ });+ expect(ids(s.source)).toEqual(['channel', 'dm']);+ expect(s.source.hasMore()).toBe(false);+ await s.source.loadMore();+ expect(s.serverNextPage).not.toHaveBeenCalled();+ s.setRemote('isPlaceholderData', false);+ expect(ids(s.source)).toContain('remote');+ s.setScope('direct_messages');+ s.setRemote('isPlaceholderData', true);+ expect(ids(s.source)).toEqual(['dm']);+ expect(s.source.hasMore()).toBe(false);+ });++ it('ignores an old service fetch for short queries and refreshes search even when browse fails', async () => {+ const s = setup('alpha');+ s.local.refresh = vi.fn(async () => {+ throw new Error('Browse failed');+ });+ await expect(s.source.refresh()).rejects.toThrow('Browse failed');+ expect(s.serverRefresh).toHaveBeenCalledOnce();+ s.setRemote({ isFetching: true, isFetchingNextPage: true });+ s.setText('zz');+ await vi.advanceTimersByTimeAsync(300);+ expect(s.source.isFetching()).toBe(false);+ expect(s.source.isLoadingMore()).toBe(false);+ expect(s.source.hasMore()).toBe(false);+ });++ it('reports only errors from the active source', async () => {+ const s = setup();+ const listError = new Error('List failed');+ const searchError = new Error('Search failed');+ s.local.error = () => listError;+ expect(s.source.error()).toBe(listError);+ s.setText('alpha');+ expect(s.source.error()).toBeUndefined();+ await vi.advanceTimersByTimeAsync(300);+ expect(s.source.error()).toBeUndefined();+ s.setRemote('error', searchError);+ expect(s.source.error()).toBe(searchError);+ s.setText('zz');+ await vi.advanceTimersByTimeAsync(300);+ expect(s.source.error()).toBeUndefined();+ s.setText('');+ expect(s.source.error()).toBe(listError);+ s.setEnabled(false);+ expect(s.source.error()).toBeUndefined();+ });+});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.tsnew file mode 100644index 0000000000..a0e0bbbdfe--- /dev/null+++ b/apps/web/src/features/channels-view/queries/channel-search-source.ts@@ -0,0 +1,112 @@+import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';+import { createSearchState } from '@app/features/soup/search/create-search-state';+import { isChannelEntity } from '@entity';+import { type Accessor, createMemo } from 'solid-js';+import { match } from 'ts-pattern';+import {+ type ChannelsDataSource,+ type ChannelsSourceScope,+ filterChannelsForScope,+} from '../queries';++export function createChannelSearchSource(options: {+ text: Accessor<string>;+ enabled?: Accessor<boolean>;+ scope: Accessor<ChannelsSourceScope>;+ source: Accessor<ChannelsDataSource>;+}): ChannelsDataSource {+ const enabled = () => options.enabled?.() ?? true;+ const searching = () => options.text().trim().length > 0;+ const search = createSearchState({+ enabled,+ text: options.text,+ localPool: () =>+ options+ .source()+ .items()+ .map((data) => ({ data })),+ buildRequest: ({ query, matchType }) => ({+ params: { page_size: 100 },+ body: {+ query,+ match_type: matchType,+ search_on: 'name',+ filters: {+ ...QUERY_FILTERS_BASE,+ channel_filters: {+ is_participant: true,+ channel_types: match(options.scope())+ .with('direct_messages', () => ['direct_message'])+ .with('channels', () => ['public', 'private', 'team'])+ .with('recents', 'search', () => undefined)+ .exhaustive(),+ },+ },+ },+ }),+ });+ const items = createMemo(() => {+ if (!enabled()) return [];+ if (!searching()) return [...options.source().items()];++ // Search records lack loaded conversation metadata, including message previews.+ const loadedById = new Map(+ options+ .source()+ .items()+ .map((channel) => [channel.id, channel])+ );+ const matches = search+ .data()+ .filter(isChannelEntity)+ .map((channel) => ({+ ...channel,+ ...loadedById.get(channel.id),+ }));+ // Recent search includes both channels and DMs, even without message metadata.+ return filterChannelsForScope(+ options.scope() === 'recents' ? 'search' : options.scope(),+ matches+ );+ });+ const isFetching = () =>+ enabled() &&+ (searching() ? search.isFetching() : options.source().isFetching());+ const hasMore = () =>+ enabled() &&+ (searching() ? search.hasNextPage() : options.source().hasMore());+ const isLoadingMore = () =>+ enabled() &&+ (searching()+ ? search.isFetchingNextPage()+ : options.source().isLoadingMore());+ const error = () => {+ if (!enabled()) return;+ if (!searching()) return options.source().error();+ return search.usesServiceSearch() ? search.error() : undefined;+ };++ return {+ items,+ isLoading: () =>+ enabled() &&+ items().length === 0 &&+ (searching() ? search.isLoading() : options.source().isLoading()),+ isFetching,+ error,+ hasMore,+ isLoadingMore,+ loadMore: async () => {+ if (!hasMore() || isFetching()) return;+ if (searching()) await search.fetchNextPage();+ else await options.source().loadMore();+ },+ refresh: async () => {+ if (!enabled()) return;+ await Promise.all([+ options.source().refresh(),+ ...(searching() ? [search.refresh()] : []),+ ]);+ },+ };+}diff --git a/apps/web/src/features/channels-view/queries/mobile-channel-search.test.ts b/apps/web/src/features/channels-view/queries/mobile-channel-search.test.tsdeleted file mode 100644index 4c43c3b331..0000000000--- a/apps/web/src/features/channels-view/queries/mobile-channel-search.test.ts+++ /dev/null@@ -1,379 +0,0 @@-import type { ChannelEntity } from '@entity/types/entity';-import type { SearchSoupQueryArgs } from '@queries/soup/search';-import { createRoot, createSignal } from 'solid-js';-import { createStore } from 'solid-js/store';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import type { ChannelsQueryScope } from '../types';--const mocks = vi.hoisted(() => ({ search: vi.fn() }));-vi.mock('@queries/soup/search', () => ({- useSearchSoupQuery: mocks.search,- validateSearchServiceText: (text: string) => text.length >= 3,-}));-vi.mock('@queries/soup/items', () => ({ useSoupAstItemsQuery: vi.fn() }));-vi.mock('@entity', () => ({- isChannelEntity: (entity: { type: string }) => entity.type === 'channel',-}));--import { useMobileChannelSearch } from './mobile-channel-search';--const channel = (- id: string,- name: string,- channelType: ChannelEntity['channelType'] = 'direct_message'-): ChannelEntity => ({- id,- name,- channelType,- type: 'channel',- ownerId: 'viewer',-});--const julia = channel('julia', 'Julia Westphal');-const hutch = channel('hutch', 'hutch');-let dispose: () => void;--beforeEach(() => {- vi.useFakeTimers();- vi.clearAllMocks();-});-afterEach(() => {- dispose?.();- vi.useRealTimers();-});--function setup(initialText = '') {- return createRoot((rootDispose) => {- dispose = rootDispose;- const [text, setText] = createSignal(initialText);- const [scope, setScope] =- createSignal<ChannelsQueryScope>('direct_messages');- const [rows, setRows] = createSignal<ChannelEntity[]>([julia, hutch]);- const [sourceFetching, setSourceFetching] = createSignal(false);- const [sourceError, setSourceError] = createSignal<Error>();- const [state, setState] = createStore({- isSuccess: false,- isLoading: false,- isFetching: false,- isFetchingNextPage: false,- isPlaceholderData: false,- hasNextPage: false,- error: null as Error | null,- data: [] as ChannelEntity[],- });- const fetchNextPage = vi.fn(async () => {});- const refetch = vi.fn(async () => {});- let args: () => SearchSoupQueryArgs;- let enabled: () => { enabled: boolean };- mocks.search.mockImplementation((getArgs, getOptions) => {- args = getArgs;- enabled = getOptions;- return {- get isSuccess() {- return state.isSuccess;- },- get isLoading() {- return state.isLoading;- },- get isFetching() {- return state.isFetching;- },- get isFetchingNextPage() {- return state.isFetchingNextPage;- },- get isPlaceholderData() {- return state.isPlaceholderData;- },- get hasNextPage() {- return state.hasNextPage;- },- get error() {- return state.error;- },- get isEnabled() {- return enabled().enabled;- },- get data() {- if (!state.isSuccess)- throw new Error('Pending data read would suspend');- return state.data;- },- fetchNextPage,- refetch,- };- });- const source = {- items: rows,- isLoading: () => false,- isFetching: sourceFetching,- isLoadingMore: () => false,- hasMore: () => true,- error: sourceError,- loadMore: vi.fn(async () => {}),- refresh: vi.fn(async () => {}),- };- const result = useMobileChannelSearch({- text,- scope,- source: () => source,- });- return {- result,- source,- setText,- setScope,- setRows,- setSourceFetching,- setSourceError,- setState,- fetchNextPage,- refetch,- args: () => args(),- enabled: () => enabled().enabled,- };- });-}--describe('mobile channel search', () => {- it('filters loaded DMs immediately and never reads disabled/pending data', () => {- const test = setup();- expect(test.result.items()).toEqual([julia, hutch]);- test.setText(' JU ');- expect(test.result.items()).toEqual([julia]);- expect(test.enabled()).toBe(false);- expect(test.result.isLoading()).toBe(false);- test.setText('Julia');- expect(test.result.items()).toEqual([julia]);- expect(test.enabled()).toBe(false);- });-- it('searches beyond the loaded page with a debounced participant-only name query', async () => {- const test = setup();- test.setRows([hutch]);- test.setText(' Julia ');- expect(test.result.items()).toEqual([]);- expect(test.result.isLoading()).toBe(true);- await vi.advanceTimersByTimeAsync(300);- expect(test.enabled()).toBe(true);- expect(test.args().body).toMatchObject({- query: 'Julia',- search_on: 'name',- match_type: 'partial',- filters: {- channel_filters: {- is_participant: true,- channel_types: ['direct_message'],- },- document_filters: {- document_ids: ['00000000-0000-0000-0000-000000000000'],- },- },- });- test.setState({ isSuccess: true, data: [julia] });- expect(test.result.items()).toEqual([julia]);- expect(test.result.isLoading()).toBe(false);- });-- it('deduplicates remote hits while retaining the loaded row metadata', () => {- const test = setup('Julia');- test.setRows([{ ...julia, participantIds: ['viewer', 'julia-user'] }]);- test.setState({- isSuccess: true,- data: [julia, channel('julian', 'Julian')],- });- expect(test.result.items().map((row) => row.id)).toEqual([- 'julia',- 'julian',- ]);- expect(test.result.items()[0].participantIds).toEqual([- 'viewer',- 'julia-user',- ]);- });-- it('changes tab filters and excludes placeholder results from the previous tab', () => {- const test = setup('Julia');- test.setState({ isSuccess: true, data: [julia] });- test.setRows([]);- test.setScope('channels');- test.setState('isPlaceholderData', true);- expect(test.result.items()).toEqual([]);- expect(test.args().body.filters?.channel_filters?.channel_types).toEqual([- 'public',- 'private',- 'team',- ]);- const team = channel('team', 'Julia project', 'team');- test.setState({ isPlaceholderData: false, data: [team, julia] });- expect(test.result.items()).toEqual([team]);- test.setScope('recents');- expect(- test.args().body.filters?.channel_filters?.channel_types- ).toBeUndefined();- expect(test.result.items()).toEqual([team, julia]);- });-- it('shows loading instead of an empty state while replacing placeholder results', () => {- const test = setup('Julia');- test.setRows([]);- test.setState({- isSuccess: true,- isFetching: true,- isPlaceholderData: true,- data: [hutch],- });- expect(test.result.items()).toEqual([]);- expect(test.result.isLoading()).toBe(true);- test.setState({- isFetching: false,- isPlaceholderData: false,- data: [],- });- expect(test.result.isLoading()).toBe(false);- });-- it('hides stale hits during debounce and placeholder data after changing the text', async () => {- const test = setup('Julia');- test.setState({ isSuccess: true, data: [julia], hasNextPage: true });- test.setText('hutch');- expect(test.result.items()).toEqual([hutch]);- expect(test.result.hasMore()).toBe(false);- test.setState('isPlaceholderData', true);- await vi.advanceTimersByTimeAsync(300);- expect(test.result.items()).toEqual([hutch]);- expect(test.result.hasMore()).toBe(false);- test.setText('zzzzzz');- test.setState({ isSuccess: false, isPlaceholderData: false });- await vi.advanceTimersByTimeAsync(300);- expect(test.result.items()).toEqual([]);- });-- it('paginates search results without discarding hits and restores browse pagination on clear', async () => {- const test = setup('Julia');- test.setState({ isSuccess: true, data: [julia], hasNextPage: true });- await test.result.loadMore();- expect(test.fetchNextPage).toHaveBeenCalledOnce();- expect(test.source.loadMore).not.toHaveBeenCalled();- test.setState({ isFetching: true, isFetchingNextPage: true });- expect(test.result.items()).toEqual([julia]);- expect(test.result.isLoadingMore()).toBe(true);- await test.result.loadMore();- expect(test.fetchNextPage).toHaveBeenCalledOnce();- test.setText('');- expect(test.result.items()).toEqual([julia, hutch]);- await test.result.loadMore();- expect(test.source.loadMore).toHaveBeenCalledOnce();- });-- it('keeps search pagination available during a browse refetch and restores browse fetching on clear', async () => {- const test = setup('Julia');- test.setState({ isSuccess: true, data: [julia], hasNextPage: true });- test.setSourceFetching(true);- expect(test.source.isFetching()).toBe(true);- expect(test.result.isFetching()).toBe(false);- expect(test.result.hasMore()).toBe(true);- await test.result.loadMore();- expect(test.fetchNextPage).toHaveBeenCalledOnce();- expect(test.source.loadMore).not.toHaveBeenCalled();-- test.setState({ isFetching: true, isFetchingNextPage: true });- expect(test.result.isFetching()).toBe(true);- expect(test.result.isLoadingMore()).toBe(true);- await test.result.loadMore();- expect(test.fetchNextPage).toHaveBeenCalledOnce();- test.setState({ isFetching: false, isFetchingNextPage: false });- expect(test.result.isFetching()).toBe(false);-- test.setText('');- expect(test.result.isFetching()).toBe(true);- test.setSourceFetching(false);- expect(test.result.isFetching()).toBe(false);- });-- it('reports search debounce and refetch activity but not browse activity for short queries', async () => {- const test = setup();- test.setText('Julia');- expect(test.result.isFetching()).toBe(true);- await vi.advanceTimersByTimeAsync(300);- test.setState({ isSuccess: true, data: [julia], isFetching: true });- expect(test.result.isFetching()).toBe(true);- test.setState('isFetching', false);- expect(test.result.isFetching()).toBe(false);-- test.setSourceFetching(true);- test.setText('Ju');- expect(test.result.isFetching()).toBe(false);- expect(test.result.hasMore()).toBe(false);- test.setText(' ');- expect(test.result.isFetching()).toBe(true);- });-- it.each([- { name: 'no hits', hits: [] },- { name: 'remote hits', hits: [julia] },- ])(- 'does not report a browse failure after a successful search with $name',- ({ hits }) => {- const test = setup('Julia');- test.setRows([]);- test.setSourceError(new Error('browse failed'));- test.setState({ isSuccess: true, data: hits });-- expect(test.result.items()).toEqual(hits);- expect(test.result.error()).toBeNull();- }- );-- it('hides browse errors during debounce and pending search, restoring them on clear', async () => {- const test = setup();- const browseError = new Error('browse failed');- test.setSourceError(browseError);- expect(test.result.error()).toBe(browseError);-- test.setText('Julia');- expect(test.enabled()).toBe(false);- expect(test.result.error()).toBeUndefined();- await vi.advanceTimersByTimeAsync(300);- test.setState('isFetching', true);- expect(test.enabled()).toBe(true);- expect(test.result.error()).toBeNull();-- test.setText('');- expect(test.result.error()).toBe(browseError);- });-- it('reports only the active source error and suppresses errors for local-only queries', () => {- const test = setup('Julia');- const browseError = new Error('browse failed');- const searchError = new Error('search failed');- test.setSourceError(browseError);- test.setState('error', searchError);- expect(test.result.error()).toBe(searchError);-- test.setText('Ju');- expect(test.result.items()).toEqual([julia]);- expect(test.result.error()).toBeUndefined();- test.setText('Other query');- expect(test.enabled()).toBe(false);- expect(test.result.error()).toBeUndefined();- test.setText(' ');- expect(test.result.error()).toBe(browseError);- test.setSourceError(undefined);- expect(test.result.error()).toBeUndefined();- });-- it('reports search failures without losing local hits and retries only valid searches', async () => {- const test = setup('Julia');- const error = new Error('offline');- test.setState('error', error);- expect(test.result.items()).toEqual([julia]);- expect(test.result.error()).toBe(error);- await test.result.refresh();- expect(test.refetch).toHaveBeenCalledWith({ throwOnError: true });- test.setText('Ju');- expect(test.result.error()).toBeUndefined();- await test.result.refresh();- expect(test.refetch).toHaveBeenCalledOnce();- expect(test.source.refresh).toHaveBeenCalledTimes(2);- });-});diff --git a/apps/web/src/features/channels-view/queries/mobile-channel-search.ts b/apps/web/src/features/channels-view/queries/mobile-channel-search.tsdeleted file mode 100644index d44dafc2e6..0000000000--- a/apps/web/src/features/channels-view/queries/mobile-channel-search.ts+++ /dev/null@@ -1,126 +0,0 @@-import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';-import { debouncedDependent } from '@core/util/debounce';-import { type ChannelEntity, isChannelEntity } from '@entity/types/entity';-import type { WithSearch } from '@entity/types/search';-import {- useSearchSoupQuery,- validateSearchServiceText,-} from '@queries/soup/search';-import { type Accessor, createMemo } from 'solid-js';-import { match } from 'ts-pattern';-import { type ChannelsDataSource, deduplicateChannels } from '../queries';-import type { ChannelsQueryScope } from '../types';--/** Name search supplements the active tab's loaded rows, not just its first page. */-export function useMobileChannelSearch(options: {- text: Accessor<string>;- scope: Accessor<ChannelsQueryScope>;- source: Accessor<ChannelsDataSource>;-}): ChannelsDataSource {- const text = createMemo(() => options.text().trim());- const serviceText = debouncedDependent(text, 300);- const channelTypes = createMemo(() =>- match(options.scope())- .with('direct_messages', () => ['direct_message'])- .with('channels', () => ['public', 'private', 'team'])- .with('recents', () => undefined)- .exhaustive()- );- const serviceEnabled = () =>- validateSearchServiceText(text()) && text() === serviceText();- const query = useSearchSoupQuery(- () => ({- params: { page_size: 100 },- body: {- query: serviceText(),- match_type: 'partial',- search_on: 'name',- filters: {- ...QUERY_FILTERS_BASE,- channel_filters: {- is_participant: true,- channel_types: channelTypes(),- },- },- },- }),- () => ({ enabled: serviceEnabled() })- );-- const items = createMemo(() => {- const source = options.source();- if (!text()) return source.items();-- const local = source- .items()- .filter((channel) =>- channel.name.toLocaleLowerCase().includes(text().toLocaleLowerCase())- );- // Disabled/pending reads must not suspend the mobile list. Placeholder data- // belongs to the previous query or tab and must never appear as a new hit.- const remote =- serviceEnabled() && query.isSuccess && !query.isPlaceholderData- ? query.data- .filter((entity): entity is WithSearch<ChannelEntity> =>- isChannelEntity(entity)- )- .filter((channel) => {- const types = channelTypes();- return !types || types.includes(channel.channelType);- })- : [];- return deduplicateChannels([local, remote]);- });- const searching = () => text().length > 0;- const serviceLoading = () =>- validateSearchServiceText(text()) &&- (text() !== serviceText() ||- (query.isFetching && !query.isFetchingNextPage));-- return {- items,- isLoading: () =>- searching()- ? items().length === 0 &&- (options.source().isLoading() || serviceLoading())- : options.source().isLoading(),- // Match the pagination source so browse refetches cannot block search pages.- isFetching: () =>- searching()- ? serviceLoading() || (serviceEnabled() && query.isFetching)- : options.source().isFetching(),- error: () =>- searching()- ? serviceEnabled()- ? query.error- : undefined- : options.source().error(),- hasMore: () =>- searching()- ? serviceEnabled() && !query.isPlaceholderData && query.hasNextPage- : options.source().hasMore(),- isLoadingMore: () =>- searching()- ? serviceEnabled() && query.isFetchingNextPage- : options.source().isLoadingMore(),- loadMore: async () => {- if (!searching()) return options.source().loadMore();- if (- !serviceEnabled() ||- query.isPlaceholderData ||- query.isFetching ||- !query.hasNextPage- )- return;- await query.fetchNextPage();- },- refresh: async () => {- await Promise.all([- options.source().refresh(),- ...(serviceEnabled() && query.isEnabled- ? [query.refetch({ throwOnError: true })]- : []),- ]);- },- };-}diff --git a/apps/web/src/features/command/mobile/MobileSearchInput.tsx b/apps/web/src/features/command/mobile/MobileSearchInput.tsxindex 83ebf687fa..b2f72503d8 100644--- a/apps/web/src/features/command/mobile/MobileSearchInput.tsx+++ b/apps/web/src/features/command/mobile/MobileSearchInput.tsx@@ -11,7 +11,7 @@ import { SearchState } from './mobileSearchState';import { openMobileAskAi } from './open-mobile-ask-ai';// This component only writes the global session state. The active split's-// bridge effect (see soup-view-context) mirrors the session into its own+// search accessor (useMobileSearchText) overlays the session on its own// search text — the input lives in the app chrome outside every split and// stays mounted for the whole session, so switching scope views never// remounts (and thereby blurs) it. It mounts and unmounts only with thediff --git a/apps/web/src/features/command/mobile/use-mobile-search-text.test.ts b/apps/web/src/features/command/mobile/use-mobile-search-text.test.tsnew file mode 100644index 0000000000..ef5a8fb1ed--- /dev/null+++ b/apps/web/src/features/command/mobile/use-mobile-search-text.test.ts@@ -0,0 +1,70 @@+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { createRoot, createSignal } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { SearchState } from './mobileSearchState';+import { useMobileSearchText } from './use-mobile-search-text';++vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: vi.fn() }));+vi.mock('./mobileSearchState', async () => {+ const { createSignal } = await import('solid-js');+ const [isOpen, setOpen] = createSignal(false);+ const [query, setQuery] = createSignal('');+ return {+ SearchState: {+ isOpen,+ query,+ setQuery,+ open: () => setOpen(true),+ close: () => {+ setOpen(false);+ setQuery('');+ },+ },+ };+});++describe('mobile view search text', () => {+ beforeEach(() => {+ SearchState.close();+ vi.mocked(isTouchDevice).mockReturnValue(true);+ });++ it('carries the query between scopes and restores each view on close', () => {+ createRoot((dispose) => {+ const [scope, setScope] = createSignal('tasks');+ const [savedTasks, setSavedTasks] = createSignal('saved task search');+ const tasks = useMobileSearchText(savedTasks, () => scope() === 'tasks');+ const email = useMobileSearchText(+ () => 'saved email search',+ () => scope() === 'mail'+ );+ SearchState.open();+ SearchState.setQuery('project');+ expect(tasks()).toBe('project');+ expect(email()).toBe('saved email search');+ setScope('mail');+ expect(email()).toBe('project');+ expect(tasks()).toBe('saved task search');+ SearchState.setQuery('');+ expect(email()).toBe('');+ SearchState.close();+ expect(email()).toBe('saved email search');+ expect(savedTasks()).toBe('saved task search');+ setSavedTasks('updated desktop search');+ expect(tasks()).toBe('updated desktop search');+ dispose();+ });+ });++ it('keeps desktop search independent of an open dock session', () => {+ vi.mocked(isTouchDevice).mockReturnValue(false);+ SearchState.open();+ SearchState.setQuery('mobile query');+ expect(+ useMobileSearchText(+ () => 'desktop query',+ () => true+ )()+ ).toBe('desktop query');+ });+});diff --git a/apps/web/src/features/command/mobile/use-mobile-search-text.ts b/apps/web/src/features/command/mobile/use-mobile-search-text.tsnew file mode 100644index 0000000000..0c6e2ee00d--- /dev/null+++ b/apps/web/src/features/command/mobile/use-mobile-search-text.ts@@ -0,0 +1,14 @@+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import type { Accessor } from 'solid-js';+import { SearchState } from './mobileSearchState';++/** Overlay the dock query without persisting it into the view's own state. */+export function useMobileSearchText(+ localText: Accessor<string>,+ isActive: Accessor<boolean>+): Accessor<string> {+ return () =>+ isTouchDevice() && SearchState.isOpen() && isActive()+ ? SearchState.query()+ : localText();+}diff --git a/apps/web/src/features/drive-view/drive-view.tsx b/apps/web/src/features/drive-view/drive-view.tsxindex ed76b894c3..7b9458c338 100644--- a/apps/web/src/features/drive-view/drive-view.tsx+++ b/apps/web/src/features/drive-view/drive-view.tsx@@ -1,4 +1,5 @@import { listOwnedSlotName } from '@app/components/list';+import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';import {type FacetSelection,@@ -46,10 +47,15 @@ function DriveComposition(props: { route: DriveRouteState }) {const tagSets = useTagSets();const tagSetsReady = useTagSetsReady();const view = createDriveViewState(props.route, () => list.reset());+ const searchText = useMobileSearchText(+ () => view.value().search,+ panel.handle.isActive+ );+ const selection = () => ({ ...view.value(), search: searchText() });const sidebar = createDriveSidebarSource();const source = withSplitPanelOwner(listOwnedSlotName('data-source'), () =>createDriveDataSource({- selection: view.value,+ selection,userId,tagSets,tagSetsReady,@@ -146,7 +152,15 @@ function DriveComposition(props: { route: DriveRouteState }) {onMount(() => panel.handle.setDisplayName('Drive'));return (- <DriveProvider value={{ state, source, list, sidebar, actions }}>+ <DriveProvider+ value={{+ state: { ...state, value: selection },+ source,+ list,+ sidebar,+ actions,+ }}+ ><DriveWorkspace /></DriveProvider>);diff --git a/apps/web/src/features/email-view/email-view-context.tsx b/apps/web/src/features/email-view/email-view-context.tsxindex 13a4c29e62..759db0a03f 100644--- a/apps/web/src/features/email-view/email-view-context.tsx+++ b/apps/web/src/features/email-view/email-view-context.tsx@@ -6,6 +6,7 @@ import {listOwnedSlotName,} from '@app/components/list';import { setSidebarSectionCollapsed } from '@app/components/view-shell';+import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';import { registerInboxFilterSplit } from '@app/features/next-soup/soup-view/inbox-filter-controllers';import { normalizeFacetSelection } from '@app/features/soup';import { registerListNavigationSource } from '@app/features/soup/collection/list-navigation-source';@@ -30,6 +31,7 @@ import {type Accessor,createEffect,createMemo,+ mergeProps,on,onCleanup,} from 'solid-js';@@ -122,7 +124,7 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<const tagSetsReady = useTagSetsReady();const initial = props.initialState ?? {};- const [state, setState] = makePersistedState(+ const [persistedState, setState] = makePersistedState(createStore<EmailViewState>({tab: initial.tab ?? DEFAULT_EMAIL_TAB,search: initial.search ?? '',@@ -140,6 +142,15 @@ export const [EmailViewProvider, useEmailView] = createAssertedContextProvider<restorePreferences: initial.collapsedSidebarSectionIds === undefined,}));+ const searchText = useMobileSearchText(+ () => persistedState.search,+ panel.handle.isActive+ );+ const state = mergeProps(persistedState, {+ get search() {+ return searchText();+ },+ });createEffect(on(diff --git a/apps/web/src/features/home/home-view-context.tsx b/apps/web/src/features/home/home-view-context.tsxindex 356fa274b1..569fe75286 100644--- a/apps/web/src/features/home/home-view-context.tsx+++ b/apps/web/src/features/home/home-view-context.tsx@@ -1,4 +1,5 @@import { channelsSearch } from '@app/features/channels-view/channels-route';+import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';import { driveSearch } from '@app/features/drive-view/primitives/drive-search';import type { FacetSelection } from '@app/features/soup/filters/facets/types';import { makePersistedState } from '@app/lib/persistence';@@ -24,6 +25,7 @@ import {createEffect,createMemo,createSignal,+ mergeProps,on,} from 'solid-js';import {@@ -96,7 +98,7 @@ export const [HomeViewProvider, useHomeView] = createAssertedContextProvider<const selectPreview = createPreviewSelectionGuard();const initial = props.initialState ?? {};const initialTab = initial.tab ?? 'signal';- const [state, setState] = makePersistedState(+ const [persistedState, setState] = makePersistedState(createStore<HomeViewState>({tab: initialTab,search: initial.search ?? '',@@ -111,6 +113,16 @@ export const [HomeViewProvider, useHomeView] = createAssertedContextProvider<}));+ const searchText = useMobileSearchText(+ () => persistedState.search,+ panel.handle.isActive+ );+ const state = mergeProps(persistedState, {+ get search() {+ return searchText();+ },+ });+createEffect(on(() => tabSearch.tab,diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsxindex 6b54720478..3a77446db1 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx@@ -5,7 +5,7 @@ import {soupItemMatchesListView,soupItemMatchesTagFilter,} from '@app/constants/list-views';-import { SearchState } from '@app/features/command/mobile/mobileSearchState';+import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';import {createSoupState,type GroupMeta,@@ -879,10 +879,9 @@ export const SoupViewContextProvider: FlowComponent<// per-split state: nothing to clear on close, nothing to reapply on pill// navigation). Otherwise it is the split's own persisted text, which only// the desktop search bar writes.- const effectiveSearchText = createMemo(() =>- isTouchDevice() && SearchState.isOpen() && panel.handle.isActive()- ? SearchState.query()- : searchText()+ const effectiveSearchText = useMobileSearchText(+ searchText,+ panel.handle.isActive);const search = createSearchState({diff --git a/apps/web/src/features/soup/search/create-search-state.ts b/apps/web/src/features/soup/search/create-search-state.tsindex ae45862192..609b988f02 100644--- a/apps/web/src/features/soup/search/create-search-state.ts+++ b/apps/web/src/features/soup/search/create-search-state.ts@@ -105,7 +105,13 @@ export function createSearchState(options: CreateSearchStateOptions) {});const serviceSearchResults = createMemo<EntityData[]>(() => {- if (isServiceDisabled() || !isServiceDebounceSettled()) return [];+ if (+ isServiceDisabled() ||+ !isServiceDebounceSettled() ||+ !searchQuery.isSuccess ||+ searchQuery.isPlaceholderData+ )+ return [];if (searchQuery.isFetching && !searchQuery.isFetchingNextPage) return [];@@ -171,11 +177,15 @@ export function createSearchState(options: CreateSearchStateOptions) {isSettling: () => isLocalSearchSettling() || isSearchServiceLoading(),usesServiceSearch: queryEnabled,isLoading: () => isSearchServiceLoading() && data().length === 0,- isFetching: () => isSearchServiceLoading() || searchQuery.isFetching,+ isFetching: () =>+ isSearchServiceLoading() || (queryEnabled() && searchQuery.isFetching),error: () =>searchQuery.error instanceof Error ? searchQuery.error : undefined,- hasNextPage: () => queryEnabled() && (searchQuery.hasNextPage ?? false),- isFetchingNextPage: () => searchQuery.isFetchingNextPage,+ hasNextPage: () =>+ queryEnabled() &&+ !searchQuery.isPlaceholderData &&+ (searchQuery.hasNextPage ?? false),+ isFetchingNextPage: () => queryEnabled() && searchQuery.isFetchingNextPage,fetchNextPage: () => searchQuery.fetchNextPage(),refetch: () => searchQuery.refetch(),/** Refetches the service results, throwing on failure so a caller (mobilediff --git a/apps/web/src/features/tasks-view/tasks-view-context.test.tsx b/apps/web/src/features/tasks-view/tasks-view-context.test.tsxindex 528efa9cc0..fde2c6f675 100644--- a/apps/web/src/features/tasks-view/tasks-view-context.test.tsx+++ b/apps/web/src/features/tasks-view/tasks-view-context.test.tsx@@ -17,6 +17,9 @@ const mocks = vi.hoisted(() => ({captured: {} as Record<string, unknown>,captors: new Map<string, () => unknown>(),projectsEnabled: (() => true) as () => boolean,+ touch: false,+ dockOpen: (): boolean => false,+ dockText: (): string => '',}));vi.mock('@app/lib/split-router', () => ({useNavigate: () => vi.fn(),@@ -58,6 +61,7 @@ vi.mock('@ui', () => ({vi.mock('@components/app/split-layout/layoutUtils', () => {const panel = {handle: {+ isActive: () => true,currentEntryState: () => mocks.captured,registerEntryStateCaptor: (key: string, getter: () => unknown) => {mocks.captors.set(key, getter);@@ -82,7 +86,15 @@ vi.mock('@components/app/createPreviewSelectionGuard', () => ({createPreviewSelectionGuard: () =>Object.assign(() => true, { canSelect: () => true }),}));-vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));+vi.mock('@core/mobile/isTouchDevice', () => ({+ isTouchDevice: () => mocks.touch,+}));+vi.mock('@app/features/command/mobile/mobileSearchState', () => ({+ SearchState: {+ isOpen: () => mocks.dockOpen(),+ query: () => mocks.dockText(),+ },+}));vi.mock('@app/components/view-shell', () => ({setSidebarSectionCollapsed: () => [],createCollapsedSidebarSectionsStorage: () => ({@@ -119,6 +131,9 @@ vi.mock('./queries/use-tasks-query', () => ({let disposeSlots: () => void;beforeEach(() => {mocks.routeTab = 'my-tasks';+ mocks.touch = false;+ mocks.dockOpen = () => false;+ mocks.dockText = () => '';mocks.captured = {};mocks.captors.clear();mocks.projectsEnabled = () => true;@@ -274,3 +289,45 @@ it('hides project tabs and columns while disabled without overwriting a restoredexpect(current.state.tab).toBe('my-tasks');expect(mocks.captors.get('tasks.view')!()).toMatchObject({ tab: 'my-tasks' });});++it.each([undefined, 'initiative:one:tasks'])(+ 'isolates dock search from saved and embedded task search (scope %s)',+ (scopeKey) => {+ mocks.touch = true;+ const [open, setOpen] = createSignal(true);+ mocks.dockOpen = open;+ mocks.dockText = () => 'dock query';+ let current!: TasksViewContext;+ const sourceFactory = (): TasksDataSource => ({+ items: () => [],+ isLoading: () => false,+ isFetching: () => false,+ error: () => undefined,+ hasMore: () => false,+ isLoadingMore: () => false,+ loadMore: async () => {},+ loadMoreGroup: async () => {},+ refresh: async () => {},+ });+ const Probe = () => {+ current = useTasksView();+ return null;+ };+ render(() => (+ <TasksViewProvider+ scopeKey={scopeKey}+ initialState={{ search: 'saved query' }}+ sourceFactory={sourceFactory}+ >+ <Probe />+ </TasksViewProvider>+ ));+ expect(current.state.search).toBe(scopeKey ? 'saved query' : 'dock query');+ current.setState('search', 'updated saved query');+ expect(current.state.search).toBe(+ scopeKey ? 'updated saved query' : 'dock query'+ );+ setOpen(false);+ expect(current.state.search).toBe('updated saved query');+ }+);diff --git a/apps/web/src/features/tasks-view/tasks-view-context.tsx b/apps/web/src/features/tasks-view/tasks-view-context.tsxindex 43e3d27b32..2281a8baa0 100644--- a/apps/web/src/features/tasks-view/tasks-view-context.tsx+++ b/apps/web/src/features/tasks-view/tasks-view-context.tsx@@ -6,6 +6,7 @@ import {listOwnedSlotName,} from '@app/components/list';import { setSidebarSectionCollapsed } from '@app/components/view-shell';+import { useMobileSearchText } from '@app/features/command/mobile/use-mobile-search-text';import { normalizeFacetSelection } from '@app/features/soup';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableProjects } from '@app/lib/core/constant/featureFlags';@@ -166,8 +167,15 @@ export const [TasksViewProvider, useTasksView] = createAssertedContextProvider<const [persistedState, setState] = props.scopeKey? withSplitPanelOwner(ownedSlot('view-state'), createState): createState();+ const searchText = useMobileSearchText(+ () => persistedState.search,+ () => !props.scopeKey && panel.handle.isActive()+ );// A pending or disabled rollout must not overwrite the saved Projects tab.const state = mergeProps(persistedState, {+ get search() {+ return searchText();+ },get tab(): TasksTab {return persistedState.tab === 'projects' && !projectsEnabled()? 'my-tasks'diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 0575536d4b..7e0b397756 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -492,7 +492,23 @@ conversation cards on `Recent`. Switching tabs preserves the active search andquery, then scrolls the results to the selected channel when present or to thestart. Closing search restores the active tab and applies the same scrollbehavior to its lists. An empty result uses the standard search empty state-artwork and wraps long queries.+artwork and wraps long queries. Desktop and the mobile dock use the same channel+name search: local fuzzy matches plus service results, deduplicated by channel+ID. Desktop searches across channels and DMs; mobile retains its Recent,+Channels, or DMs scope. An empty query shows the ordinary list. Scrolling search+results loads the next search page; clearing the query restores ordinary list+pagination. Check both surfaces with a matching query, a query with no matches,+and a clear/reopen cycle.+On mobile, a nonempty query with no matches shows **No results**, echoes the+query, and offers **Clear search**. Clearing restores the selected tab's list+and keeps the dock search session open. The tab's usual empty state and create+actions appear only when no search text is entered; loading and request errors+keep their own states.+Recent search includes both channels and DMs, including service hits without+message previews. It does not require message metadata or an importance filter.+Loaded conversation metadata is preserved when a service hit has the same ID.+Pending and placeholder service results never appear as current hits. Ordinary+list errors do not affect an active search.Collapsing a section does not discard its loaded pages. Recent has its ownpagination cursor. Each list is virtualized, so offscreen conversations may notexist in the DOM.diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex a555bd1131..39c02b7302 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -153,7 +153,7 @@ labels the top left of the block, matching the **Email**, **Tasks**, **Chat**, astarting pane; it does not create a chat. Email and Tasks have matching top pillsfor **New email** and **New task**.-The Inbox provider honors an explicit initial tab, search, grouping, and facet+The Home provider honors an explicit initial tab, search, grouping, and facetselection. Filters persist per user across reloads and fresh Home navigation;split history restores that entry's filter selection. An explicit facet selectionoverrides saved filters. Returning through split history resets navigation to Signal.@@ -673,6 +673,17 @@ Sidebar `Search` button → `/app/.../component/search` with a focused query box(including a `Featured Results` group) filter live as you type; no Enter needed. `Ctrl+K` isusually faster for jump-to-entity; `/` opens workspace search when no editor is focused.+On touch devices, the dock's **Search** button opens a persistent input. Type a+query, then switch the scope pills between **All**, **Notifications**, **Email**,+**Channels**, **Files**, **Agents**, and **Tasks**. The selected view searches with+the same query and retains its tab/facet restrictions. Channels searches+conversation names. Clearing the+input restores the current scope's unsearched list; **Close search** ends the+session. Switching scopes keeps the input mounted and focused. The dock query is+not saved into the view's desktop search or restored entry state. Home and+top-level Tasks use this same overlay; embedded project task lists retain their+own search while the dock is open.+Agent-session results use the robot icon and show a highlighted transcript snippet.`Show more [N]` expands additional matches, labeled **User / Agent · Turn N**.Click a snippet to open `/app/agent/<uuid>` at that folded message; a plain row click