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(command): keep matching channels visible and prioritized (#9029)
gbirman6f2cbd60b147
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex ed53bd518e..f735e06dee 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -253,6 +253,8 @@ the user's newest account for that app from the last fifteen minutes.- Keep mobile Search history lightweight: save query/category/mode, account-scoped item anchors, and at most 200 ordering IDs per mode; never save row objects or virtualizer caches. Restore from current sources with at most three additional pages, fall back when an anchor disappears, and stop restoration on user interaction or scope changes. Dock navigation starts a fresh search session; cached rows belong to the source, not history.- Release per-history-entry state when its router entry is replaced, pruned, or closed; retain only the latest per-view session snapshot and the latest split event outside reachable Back/Forward history.- Keep Quick Access cache availability reactive to the GraphQL rollout flag; it can arrive after the provider mounts, and email has no legacy source fallback.+- Merge the complete channel list into Quick Access even with the GraphQL cache enabled; preserve newer viewed timestamps and apply the channel boost before the extra DM boost in shared command/mobile name ranking.+- Include all channel metadata in Quick Access item versions; record complete, cached-recent, and merged channel counts plus the last index-build duration on cache-search traces.- Virtualize mobile name results like desktop Command Menu; local Quick Access sources are unbounded, and mounting them all stalls iOS keyboard focus during layout. Load additional search pages near the scroll end instead of reserving a paging bar.- Reconcile mobile full-text rows by entity ID so appending a page preserves DOM rows and scroll position; restore item anchors after responsive row measurement and disable browser scroll anchoring so layout changes cannot override restoration.- Reserve the safe area plus the category row above mobile Search, and only the safe area above Channels; their hidden split headers must not add another blank strip.diff --git a/apps/web/src/features/command/rank-command-search-items.test.ts b/apps/web/src/features/command/rank-command-search-items.test.tsindex ad04ab74d0..ebfe6b6ab0 100644--- a/apps/web/src/features/command/rank-command-search-items.test.ts+++ b/apps/web/src/features/command/rank-command-search-items.test.ts@@ -115,7 +115,7 @@ describe('command menu search ranking', () => {);it.each([false, true])(- 'ranks commands and entities by the same viewed recency with GraphQL %s',+ 'prioritizes channels over commands and keeps their viewed recency with GraphQL %s',(cacheEnabled) => {const items = [channel('old-channel', 'Planning', NOW - 20 * DAY),@@ -124,12 +124,25 @@ describe('command menu search ranking', () => {];expect(ids(items, 'Planning', cacheEnabled)).toEqual(['recent-channel',- 'command','old-channel',+ 'command',]);});+ it('keeps commands and other entities ordered by recency', () => {+ expect(+ ids(+ [+ project('old-project', 'Planning', NOW - 20 * DAY),+ command('command', 'Planning', NOW - DAY),+ project('recent-project', 'Planning', NOW),+ ],+ 'Planning'+ )+ ).toEqual(['recent-project', 'command', 'old-project']);+ });+it('keeps ranking independent of whether a match came from cached or local results', () => {const cached = channel('cached', 'Planning', NOW - DAY);const local = channel('local', 'Planning', NOW);@@ -137,6 +150,51 @@ describe('command menu search ranking', () => {expect(ids([local, cached], 'Planning')).toEqual(['local', 'cached']);});+ it.each([+ { cacheEnabled: false, query: 'planning' },+ { cacheEnabled: true, query: 'planning' },+ { cacheEnabled: false, query: 'planning notes' },+ { cacheEnabled: true, query: 'planning notes' },+ ])(+ 'keeps an old channel ahead of recent contacts and agents for $query with GraphQL $cacheEnabled',+ ({ cacheEnabled, query }) => {+ const session: EntityItem = {+ id: 'session',+ kind: 'entity',+ bucket: 'agent_session',+ searchText: 'Review planning notes Assistant',+ sortTimestamp: NOW,+ timestamps: { updatedAt: new Date(NOW) },+ data: {+ id: 'session',+ type: 'agent_session',+ name: 'Review planning notes',+ ownerId: 'owner',+ botId: 'assistant',+ status: 'completed',+ },+ };+ const items = [+ session,+ contact('crm', 'Planning notes coordinator'),+ channel('channel', 'Planning notes', NOW - 60 * DAY),+ ];+ expect(ids(items, query, cacheEnabled)[0]).toBe('channel');+ expect(ids([...items].reverse(), query, cacheEnabled)[0]).toBe('channel');+ }+ );++ it('keeps full-name DMs ahead of other results when aliases extend their search text', () => {+ const dm = {+ ...channel('dm', 'Avery Morgan', NOW - 60 * DAY, 'dm'),+ searchText:+ 'Avery Morgan | Avery Morgan | [email protected] | Avery Morgan | [email protected]',+ };+ expect(+ ids([project('project', 'Avery Morgan'), dm], 'avery morgan')+ ).toEqual(['dm', 'project']);+ });+it('breaks equal search scores by recency then id across refreshes', () => {const items = [channel('older', 'Planning', NOW - 50 * DAY),@@ -217,7 +275,7 @@ describe('command menu search ranking', () => {contact('recent-crm', 'Jack CRM', NOW),contact('older-crm', 'Jack CRM', NOW - 10 * DAY),command('command', 'Jack command', NOW - 5 * DAY),- channel('document-slot', 'Jack channel', NOW - 15 * DAY),+ channel('channel-slot', 'Jack channel', NOW - 15 * DAY),person('jack', 'Jack Smith'),channel('old-dm', 'Jack old', NOW - 60 * DAY, 'dm'),channel('recent-dm', 'Jack recent', NOW - DAY, 'dm'),@@ -226,10 +284,10 @@ describe('command menu search ranking', () => {expect(ids(items, 'jack')).toEqual(['recent-dm','old-dm',- 'command',+ 'channel-slot','jack',+ 'command','recent-crm',- 'document-slot','older-crm',]);});diff --git a/apps/web/src/features/command/rank-command-search-items.ts b/apps/web/src/features/command/rank-command-search-items.tsindex 44129a3a2a..ec10cde163 100644--- a/apps/web/src/features/command/rank-command-search-items.ts+++ b/apps/web/src/features/command/rank-command-search-items.ts@@ -44,13 +44,14 @@ export function rankCommandSearchItems<T extends CommandMenuItem>(const search = createFreshSearch<T>({config: {useViewedAt: true,+ channelBoost: 3,dmBoost: 1.8,fuzzyWeight: 0.7,timeWeight: 0.7,minFuzzyThreshold: 0.1,- commaSeparatedChannelMatch: true,},getName: (item) => item.searchText,+ isChannelItem: (item) => item.bucket === 'channel' || item.bucket === 'dm',isDmItem: (item) => item.bucket === 'dm',getTimestamp: (item) => item.timestamps,});diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.tsindex 466e58498f..fad1166a6c 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts@@ -17,6 +17,7 @@ import { INITIAL_CACHE_REVISION } from '@graphql-cache/index';import type { HydrationSearchChanges } from '@graphql-cache/protocol';import type { CachedGraphqlChannel } from '@queries/channel/graphql';import type { HistoryItem } from '@queries/history/types';+import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';import type { ListedDatabase } from '@service-storage/generated/schemas/listedDatabase';import { render } from '@solidjs/testing-library';import {@@ -56,7 +57,7 @@ vi.mock('@queries/email/local-draft-source', async () => ({const mocks = vi.hoisted(() => ({search: vi.fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>(),history: [] as HistoryItem[],- channels: vi.fn(() => []),+ channels: vi.fn<() => ApiChannelWithLatest[]>(() => []),cachedChannels: (): CachedGraphqlChannel[] => [],projectedChannels: [] as CachedGraphqlChannel[],changed: undefined as@@ -669,8 +670,79 @@ describe('Quick Access source integration', () => {}});- it('uses only GraphQL channels when the cache is enabled', async () => {+ it('keeps known channels searchable before the cache has hydrated them', async () => {+ mocks.channels.mockReturnValue([+ {+ id: 'uncached-channel',+ name: 'Planning',+ channel_type: 'public',+ owner_id: 'owner',+ participants: [],+ auto_join_team: false,+ is_participant: true,+ created_at: '2026-08-01T00:00:00.000Z',+ updated_at: '2026-08-02T00:00:00.000Z',+ },+ ]);+ const [cached, setCached] = createSignal<CachedGraphqlChannel[]>([]);+ mocks.cachedChannels = cached;+ const list = setup((source) =>+ source.useList({ buckets: ['channel'], searchTerm: () => 'planning' })+ );++ expect(list.items().map((item) => item.id)).toEqual(['uncached-channel']);+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));+ expect(list.items().map((item) => item.id)).toEqual(['uncached-channel']);++ setCached([+ cachedChannel('uncached-channel', {+ name: 'Planning',+ ownerId: 'cached-owner',+ participantIds: ['participant-1'],+ channelType: 'private',+ createdAt: '2026-07-01T00:00:00.000Z',+ interactedAt: '2026-08-03T00:00:00.000Z',+ }),+ ]);+ expect(list.items().map((item) => item.id)).toEqual(['uncached-channel']);+ expect(list.items()[0]).toMatchObject({+ data: {+ ownerId: 'cached-owner',+ participantIds: ['participant-1'],+ channelType: 'private',+ createdAt: '2026-07-01T00:00:00.000Z',+ interactedAt: '2026-08-03T00:00:00.000Z',+ },+ });+ });++ it('merges complete channels with cached channels and prefers cached metadata', async () => {const channel = cachedChannel('cached-channel');+ mocks.channels.mockReturnValue([+ {+ id: channel.id,+ name: 'Previous name',+ channel_type: 'public',+ owner_id: 'owner',+ participants: [],+ auto_join_team: false,+ is_participant: true,+ created_at: channel.createdAt,+ updated_at: channel.updatedAt,+ viewed_at: '2026-08-03T00:00:00.000Z',+ },+ {+ id: 'uncached-channel',+ name: 'Planning',+ channel_type: 'public',+ owner_id: 'owner',+ participants: [],+ auto_join_team: false,+ is_participant: true,+ created_at: channel.createdAt,+ updated_at: channel.updatedAt,+ },+ ]);mocks.cachedChannels = () => [channel];mocks.search.mockResolvedValue({documents: [channelHit(channel)],@@ -684,9 +756,15 @@ describe('Quick Access source integration', () => {expect(lists.every((list) => !list.isLoading())).toBe(true));for (const list of lists) {- expect(list.items().map((item) => item.id)).toEqual(['cached-channel']);+ expect(list.items().map((item) => item.id)).toEqual([+ 'cached-channel',+ 'uncached-channel',+ ]);+ expect(list.items()[0].searchText).toBe(channel.name);+ expect(list.items()[0].sortTimestamp).toBe(+ Date.parse('2026-08-03T00:00:00.000Z')+ );}- expect(mocks.channels).not.toHaveBeenCalled();});it('loads channels beyond the recent query through cache search', async () => {@@ -704,7 +782,57 @@ describe('Quick Access source integration', () => {expect(list.items()).toHaveLength(75);expect(new Set(list.items().map((item) => item.id)).size).toBe(75);expect(list.items().some((item) => item.id === 'channel-74')).toBe(true);- expect(mocks.channels).not.toHaveBeenCalled();+ });++ it('uses projected channel metadata beyond the recent cache page while preserving live viewed recency', async () => {+ const [knownChannels, setKnownChannels] = createSignal<+ ApiChannelWithLatest[]+ >([+ {+ id: 'renamed-channel',+ name: 'Old planning name',+ channel_type: 'public',+ owner_id: 'owner',+ participants: [],+ auto_join_team: false,+ is_participant: true,+ created_at: '2026-08-01T00:00:00.000Z',+ updated_at: '2026-08-02T00:00:00.000Z',+ viewed_at: '2026-08-03T00:00:00.000Z',+ },+ ]);+ mocks.channels.mockImplementation(knownChannels);+ const projectedChannel = cachedChannel('renamed-channel', {+ name: 'New planning name',+ });+ mocks.projectedChannels = [projectedChannel];+ mocks.search.mockResolvedValue({+ documents: [channelHit(projectedChannel)],+ nextCursor: null,+ });+ const list = setup((source) =>+ source.useList({ buckets: ['channel'], searchTerm: () => 'new planning' })+ );+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));+ expect(list.items().map((item) => item.searchText)).toEqual([+ 'New planning name',+ ]);+ expect(list.items()[0].sortTimestamp).toBe(+ Date.parse('2026-08-03T00:00:00.000Z')+ );++ setKnownChannels((channels) =>+ channels.map((channel) => ({+ ...channel,+ viewed_at: '2026-08-04T00:00:00.000Z',+ }))+ );+ expect(list.items().map((item) => item.searchText)).toEqual([+ 'New planning name',+ ]);+ expect(list.items()[0].sortTimestamp).toBe(+ Date.parse('2026-08-04T00:00:00.000Z')+ );});it('sorts projected and known browse rows together using viewed recency', async () => {diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsxindex 3b6adde14a..7a497377d7 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx@@ -264,13 +264,6 @@ function getHistoryItemVersion(return `${item.name}|${item.updatedAt}|${viewedAt}|${item.deletedAt}`;}-function getChannelVersion(- channel: CachedGraphqlChannel,- viewedAt?: string-): string {- return `${channel.name}|${channel.updatedAt}|${viewedAt}`;-}-function getUserVersion(user: IUser,lastInteraction: DateValue | undefined@@ -519,22 +512,37 @@ export function createQuickAccessValue(): QuickAccessContextValue {});const channelEntries = createLazyMemo(() => {+ const startedAt = performance.now();const viewedAtMap = soupViewedAtMap();const allEntries: IndexEntry[] = [];-- // The GraphQL cache is authoritative while enabled. Otherwise preserve the- // existing channel-list source unchanged.- const usesCache = cacheHost() !== undefined;- const channelData = usesCache- ? queryReadyGate(cachedChannelsQuery)+ const completeChannels = channels();+ const cachedChannels =+ cacheHost() && queryReadyGate(cachedChannelsQuery)? cachedChannelsQuery.data- : []- : channels().map(apiChannelToQuickAccessChannel);- for (const sourceChannel of channelData) {+ : [];++ // A partial cache must not hide channels already available in the complete+ // channel list. Cached metadata wins for duplicates, retaining newer views.+ const channelData = new Map(+ completeChannels.map((channel) => [+ channel.id,+ apiChannelToQuickAccessChannel(channel),+ ])+ );+ for (const channel of cachedChannels) {+ channelData.set(channel.id, {+ ...channel,+ viewedAt: latestDate(+ channelData.get(channel.id)?.viewedAt,+ channel.viewedAt+ ),+ });+ }+ for (const sourceChannel of channelData.values()) {const recentlyViewedAt = viewedAtMap.get(sourceChannel.id);const viewedAt = latestDate(recentlyViewedAt, sourceChannel.viewedAt);const channel = { ...sourceChannel, viewedAt };- const version = getChannelVersion(channel, viewedAt);+ const version = JSON.stringify(channel);const cached = itemCache.get(channel.id);if (!cached || cached.version !== version) {@@ -554,7 +562,13 @@ export function createQuickAccessValue(): QuickAccessContextValue {}}- return sortIndexEntries(allEntries);+ const entries = sortIndexEntries(allEntries);+ return {+ entries,+ completeCount: completeChannels.length,+ cachedCount: cachedChannels.length,+ buildDurationMs: performance.now() - startedAt,+ };});const contactEntries = createLazyMemo(() => {@@ -954,7 +968,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {const processedData = createLazyMemo(() => {const allEntries = mergeMultipleSortedIndices([historyEntries().entries,- channelEntries(),+ channelEntries().entries,contactEntries(),crmCompanyEntries(),crmContactEntries(),@@ -1144,6 +1158,19 @@ export function createQuickAccessValue(): QuickAccessContextValue {projectedBuckets().length > 0 && options.enabled?.() !== false,existingItems: localItems,filterPreviousItems: filterQuickAccessItems,+ sourceAttributes: () => {+ const channelIndex = channelEntries();+ return {+ 'search.channel_index.complete_count':+ channelIndex.completeCount,+ 'search.channel_index.cached_recent_count':+ channelIndex.cachedCount,+ 'search.channel_index.merged_count':+ channelIndex.entries.length,+ 'search.channel_index.last_build_ms':+ channelIndex.buildDurationMs,+ };+ },materialize: async (documents) => {const idOf = (recordKey: string) =>recordKey.slice(recordKey.indexOf(':') + 1);@@ -1158,7 +1185,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {cachedEmails,] = await Promise.all([materializeCachedGraphqlHistoryItems(projectionHost, missing),- materializeCachedGraphqlChannels(projectionHost, missing),+ materializeCachedGraphqlChannels(projectionHost, documents),materializeCachedGraphqlCrmCompanies(projectionHost, missing),materializeCachedGraphqlCrmContacts(projectionHost, missing),materializeCachedEmailItems(projectionHost, documents),@@ -1184,6 +1211,18 @@ export function createQuickAccessValue(): QuickAccessContextValue {const email = emailsById.get(id);return email ? [email] : [];}+ const channel = channelsById.get(id);+ if (channel) {+ return [+ channelToQuickAccessItem({+ ...channel,+ viewedAt: latestDate(+ soupViewedAtMap().get(id),+ channel.viewedAt+ ),+ }),+ ];+ }const cached = itemCache.get(id)?.item;if (cached) return [cached];const historyItem = historyById.get(id);@@ -1236,8 +1275,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {},];}- const channel = channelsById.get(id);- return channel ? [channelToQuickAccessItem(channel)] : [];+ return [];});},})@@ -1259,7 +1297,26 @@ export function createQuickAccessValue(): QuickAccessContextValue {const ranked = projected.items().filter((item) => !localDraftIds.has(item.id))- .map((item) => itemCache.get(item.id)?.item ?? item);+ .map((item) => {+ const cached = itemCache.get(item.id)?.item;+ if (!cached) return item;+ // Projected channels carry current cache metadata even when the+ // complete list still has an older name. Only overlay newer views.+ if (item.kind === 'entity' && item.data.type === 'channel') {+ const viewedAt = latestDate(+ item.timestamps.viewedAt,+ cached.timestamps.viewedAt+ );+ return {+ ...item,+ sortTimestamp:+ toTimestamp(viewedAt) || toTimestamp(item.timestamps.updatedAt),+ timestamps: { ...item.timestamps, viewedAt },+ data: { ...item.data, viewedAt },+ };+ }+ return cached;+ });const seen = new Set(ranked.map((item) => item.id));const combined = ranked.concat(local.filter((item) => !seen.has(item.id))diff --git a/apps/web/src/lib/core/context/quickAccess/projected-list.ts b/apps/web/src/lib/core/context/quickAccess/projected-list.tsindex c67945168c..721cea0d41 100644--- a/apps/web/src/lib/core/context/quickAccess/projected-list.ts+++ b/apps/web/src/lib/core/context/quickAccess/projected-list.ts@@ -55,6 +55,8 @@ export function createProjectedList<T extends { id: string }>(options: {enabled?: Accessor<boolean>;/** Visible fallback rows; duplicates do not grow the combined menu. */existingItems?: Accessor<readonly T[]>;+ /** Snapshot of source availability; reading it must not trigger a new request. */+ sourceAttributes?: Accessor<Record<string, number>>;/** Keep already-materialized matches visible while a new query is pending. */filterPreviousItems?: (items: T[], query: string) => T[];materialize: (documents: SearchDocumentWire[]) => Promise<T[]>;@@ -118,6 +120,11 @@ export function createProjectedList<T extends { id: string }>(options: {span.setAttr('search.query_length', request.query.length);span.setAttr('search.append', append);try {+ for (const [key, value] of Object.entries(+ untrack(() => options.sourceAttributes?.() ?? {})+ )) {+ span.setAttr(key, value);+ }do {const page = await span.span('quick_access.search_page',diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 09fe3118df..819e4bf0c2 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -1037,8 +1037,8 @@ Rows use the same touch highlight as Home and Email: taps retain feedback whileopening, holds stay highlighted for the action menu, and scrolling or cancellinga touch clears the press highlight.The mobile dock Search button opens the independent Search route. Its Channels-and People categories search cached channel names and people directly; the-conversation list does not constrain results. Full-text search is explicit,+and People categories search the complete channel list, cached channel names,+and people directly; the conversation list does not constrain results. Full-text search is explicit,and People uses the existing channel-content scope. Closing search resets itssession; the conversation list retains its browse pagination. See[Search](search.md) for mode, keyboard, and session-reset checks.diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex fbfaa86df9..41f7008128 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -1174,9 +1174,11 @@ Counts describe loaded results, not the full server corpus. Scans throughincomplete or already-visible cache hits are bounded per action; continuenavigating/scrolling, or narrow the query, to resume from the saved cursor.A failed local refresh keeps displayed rows and their continuation available for-another pagination attempt. Missing items may still be uncached, but should appear-after hydration without retyping, including channels outside the first cached-page. Cmd+K's+another pagination attempt. Quick Access merges the complete channel list with+cached channels, so known channels remain searchable before cache hydration and+outside its recent page. Cached metadata wins for duplicate channels while newer+viewed timestamps from either source are retained. Other uncached items should+appear after hydration without retyping. Cmd+K'slocal search explicitly excludes email hits before limiting entity results;email mentions keep their separate search-service path. Text search loads onlyits requested cache buckets, so a document-only category must not read the email@@ -1233,9 +1235,20 @@ contacts.Cmd+K merges cached and locally available items before applying recency order.An empty query prefers when an item was last viewed, falling back to its update-time; equal timestamps have a stable entity-type and ID order. Searching retains the menu's-relevance/recency ranking and DM boost with GraphQL enabled. Verify that refreshing-the cache or reopening the menu with unchanged data does not reorder the results.+time; equal timestamps have a stable entity-type and ID order. Typed searches give+channels (including DMs) the same 3x boost as the main search view, with the menu's+additional 1.8x DM boost; relevance and viewed recency still order those results.+This shared ranking also applies to mobile name search. Verify an older matching+channel stays above recent CRM contacts and agent sessions in All, and remains+findable in Channels while its cache entry is absent. Refreshing the cache or+reopening the menu with unchanged data must not reorder results or duplicate a+channel when its cache entry arrives. Hydration must also refresh ownership,+participants, and channel type when the name and timestamps are unchanged.++The `quick_access.search` trace includes `search.channel_index` attributes for+complete-list, cached-recent-page, and merged channel counts. `last_build_ms`+records the most recent shared channel-index build duration; that build can+precede the search and is not a child phase of the cache request.Pending or failed Quick Access history, recently-viewed, skills, and cached-channellookups must not hide the app shell. Verify a cold lookup with Cmd/Ctrl+K: navigation