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(quick-access): use graphql cache instead of history (#4982)
dev-rb200307504a9d
diff --git a/Cargo.lock b/Cargo.lockindex 33836d655e..9a3f2af2a1 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2291,7 +2291,7 @@ dependencies = [[[package]]name = "cache-wasm"-version = "0.2.0"+version = "0.3.0"dependencies = ["async-lock","cache-core",diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.mdindex 65fddc06b7..3a96588687 100644--- a/apps/web/docs/graphql-normalized-cache-plan.md+++ b/apps/web/docs/graphql-normalized-cache-plan.md@@ -192,10 +192,14 @@ Topology:| SQLite | Tauri native | records, mutation queue, optimistic layers, and meta; WAL mode || IndexedDB | browser | via the `idb` crate; stable per-scope DB with object stores for records, mutation queue, optimistic layers, and meta |-`Storage` trait (async): `get_batch`, `put_batch`, `delete_batch`,-`scan_prefix`, `approx_size`. Records serialized with `postcard` (stored as-`Uint8Array` values in IDB / blobs in SQLite). Note: wasm futures are not-`Send`, so the trait's futures are bound by `MaybeSend` (`crates/maybe_send`):+Normalized records are serialized with `postcard`. SQLite stores the bytes in+`records.value`; IndexedDB stores the bytes directly in the records object+store. Both backends implement schema-neutral, entity-key-ordered record scans.+`Storage::scan_records` selects concrete normalized types by their key ranges;+`Engine::read_records` applies a validated named fragment, loads linked records+in batches, includes optimistic layers, and omits incomplete projections.+Note: wasm futures are not `Send`, so the `Storage` trait's futures+are bound by `MaybeSend` (`crates/maybe_send`):`Send` on native targets — the Tauri host drives the engine directly from itsmulti-threaded runtime — and unbounded on wasm, implementable by `idb`.diff --git a/apps/web/src/features/command/CommandMenu.tsx b/apps/web/src/features/command/CommandMenu.tsxindex 7b4cfd748e..3cc544a023 100644--- a/apps/web/src/features/command/CommandMenu.tsx+++ b/apps/web/src/features/command/CommandMenu.tsx@@ -57,6 +57,7 @@ import {isCommandItem,isEntityItem,isSearchItem,+ type PaginationControls,useCommandItems,} from './useCommandItems';@@ -73,6 +74,7 @@ const CATEGORIES: { id: CategoryFilter; label: string }[] = [const VIRTUAL_ITEM_HEIGHT = 40; // tailwind h-10const LIST_PADDING = 16; // p-2 = 8px top + 8px bottomconst MAX_LIST_HEIGHT = VIRTUAL_ITEM_HEIGHT * 8 + LIST_PADDING;+const LOAD_MORE_THRESHOLD = VIRTUAL_ITEM_HEIGHT * 3;const EMPTY_STATE_HEIGHT = VIRTUAL_ITEM_HEIGHT * 1.5 + LIST_PADDING;export function CommandMenu() {@@ -145,10 +147,13 @@ export function CommandMenuInner(props: {const query = debouncedDependent(CommandState.query, 60);- const defaultFilteredItems = props.items+ const defaultCommandItems = props.items? undefined- : useCommandItems(query, CommandState.categoryFilter);- const filteredItems = props.items ?? defaultFilteredItems!;+ : useCommandItems(query, CommandState.categoryFilter, {+ searchActive: CommandState.isOpen,+ });+ const filteredItems = props.items ?? defaultCommandItems!.items;+ const pagination = defaultCommandItems?.pagination;const listController = createCommandListController({items: filteredItems,selectedIndex: CommandState.selectedIndex,@@ -377,6 +382,13 @@ export function CommandMenuInner(props: {keyDownHandler: () => {const items = filteredItems();if (items.length === 0) return false;+ if (+ CommandState.selectedIndex() >= items.length - 1 &&+ (pagination?.hasMore() || pagination?.isLoadingMore())+ ) {+ if (!pagination?.isLoadingMore()) void pagination?.loadMore();+ return true;+ }return listController.selectNext();},runWithInputFocused: true,@@ -627,6 +639,7 @@ export function CommandMenuInner(props: {}onItemMouseMove={listController.setSelectedIndexFromPointer}scrollSelectedIntoView={listController.shouldScrollSelectedIntoView()}+ pagination={pagination}/></Show></div>@@ -729,9 +742,25 @@ function VirtualizedCommandList(props: {onSelect: (item: CommandMenuItem, openInNewSplit: boolean) => void;onItemMouseMove: (index: number) => void;scrollSelectedIntoView: boolean;+ pagination?: PaginationControls;}) {let virtualizerHandle: VirtualizerHandle | undefined;+ const loadMoreNearEnd = () => {+ const pagination = props.pagination;+ if (+ !virtualizerHandle ||+ !pagination?.hasMore() ||+ pagination.isLoadingMore()+ )+ return;+ const remaining =+ virtualizerHandle.scrollSize -+ virtualizerHandle.scrollOffset -+ virtualizerHandle.viewportSize;+ if (remaining <= LOAD_MORE_THRESHOLD) void pagination.loadMore();+ };+createEffect(() => {const index = props.selectedIndex;if (@@ -765,6 +794,7 @@ function VirtualizedCommandList(props: {data={props.items}style={{ height: '100%' }}class="scrollbar-hidden"+ onScroll={loadMoreNearEnd}>{(item, index) => (<CommandItemdiff --git a/apps/web/src/features/command/mobile/MobileSearch.tsx b/apps/web/src/features/command/mobile/MobileSearch.tsxindex a5e0b23212..bacf214139 100644--- a/apps/web/src/features/command/mobile/MobileSearch.tsx+++ b/apps/web/src/features/command/mobile/MobileSearch.tsx@@ -8,6 +8,7 @@ import {isAskAiItem,isCommandItem,isEntityItem,+ type PaginationControls,useCommandItems,} from '@app/features/command/useCommandItems';import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';@@ -41,9 +42,11 @@ import {Show,Switch,} from 'solid-js';-import { VList } from 'virtua/solid';+import { type VirtualizerHandle, VList } from 'virtua/solid';import { SearchState } from './mobileSearchState';+const LOAD_MORE_THRESHOLD = 120;+const CATEGORIES: PillTabItem<CategoryFilter>[] = [{ value: 'all', label: 'All' },{ value: 'commands', label: 'Command' },@@ -67,9 +70,10 @@ function MobileSearchInner() {const query = debouncedDependent(SearchState.query, 60);- const filteredItems = useCommandItems(query, SearchState.categoryFilter, {+ const commandItems = useCommandItems(query, SearchState.categoryFilter, {showSearchRow: false,commandScopeCommands: SearchState.commandScopeCommands,+ searchActive: SearchState.isOpen,});const { results: fullTextResults, isLoading: isFullTextLoading } =useFullTextSearch(SearchState.query);@@ -185,7 +189,8 @@ function MobileSearchInner() {<Layer depth={0}><div class="fixed inset-0 z-mobile-search flex flex-col bg-surface pt-(--safe-top) pr-(--safe-right) pb-[calc(var(--virtual-keyboard-height)+var(--mobile-content-inset-bottom))] pl-(--safe-left)"><ResultsContainer- nameMatchItems={filteredItems()}+ nameMatchItems={commandItems.items()}+ pagination={commandItems.pagination}fullTextItems={fullTextResults()}onSelectNameMatch={(item, openInNewSplit) =>handleItemAction(item, openInNewSplit)@@ -267,6 +272,7 @@ function SearchInputBar(props: { onBack: () => void }) {function ResultsContainer(props: {nameMatchItems: CommandMenuItem[];+ pagination: PaginationControls;fullTextItems: WithSearch<EntityData>[];onSelectNameMatch: (item: CommandMenuItem, openInNewSplit: boolean) => void;onSelectFullText: (entity: WithSearch<EntityData>) => void;@@ -362,6 +368,7 @@ function ResultsContainer(props: {items={props.nameMatchItems}onSelect={props.onSelectNameMatch}onRowHeightMeasured={setRowHeight}+ pagination={props.pagination}/></div></Match>@@ -402,12 +409,32 @@ function VirtualizedCommandList(props: {items: CommandMenuItem[];onSelect: (item: CommandMenuItem, openInNewSplit: boolean) => void;onRowHeightMeasured?: (height: number) => void;+ pagination: PaginationControls;}) {+ let virtualizerHandle: VirtualizerHandle | undefined;+ const loadMoreNearEnd = () => {+ if (+ !virtualizerHandle ||+ !props.pagination.hasMore() ||+ props.pagination.isLoadingMore()+ )+ return;+ const remaining =+ virtualizerHandle.scrollSize -+ virtualizerHandle.scrollOffset -+ virtualizerHandle.viewportSize;+ if (remaining <= LOAD_MORE_THRESHOLD) void props.pagination.loadMore();+ };+return (<VList+ ref={(handle) => {+ virtualizerHandle = handle;+ }}data={props.items}style={{ height: '100%' }}class="scrollbar-hidden overscroll-none"+ onScroll={loadMoreNearEnd}>{(item, index) => (<divdiff --git a/apps/web/src/features/command/useCommandItems.ts b/apps/web/src/features/command/useCommandItems.tsindex bce9e76ab0..bddf334665 100644--- a/apps/web/src/features/command/useCommandItems.ts+++ b/apps/web/src/features/command/useCommandItems.ts@@ -1,5 +1,6 @@import { GO_TO_COMMAND_SCOPE, GO_TO_LEADER_KEY } from '@app/constants/hotkeys';import {+ type Bucket,type EntityItem,exclude,type QuickAccessItem,@@ -63,6 +64,12 @@ type AskAiItem = {/** Combined item type for command menu (quickAccess items + commands) */type CommandMenuItem = QuickAccessItem | CommandItem | SearchItem | AskAiItem;+export type PaginationControls = {+ hasMore: Accessor<boolean>;+ isLoadingMore: Accessor<boolean>;+ loadMore: () => Promise<void>;+};+function isCommandItem(item: CommandMenuItem): item is CommandItem {return item.kind === 'command';}@@ -318,35 +325,67 @@ function useCommandsList(});}-/**- * Hook to get items from QuickAccess organized by category.- * Items are already sorted by recency from QuickAccess.- */-function useQuickAccessBuckets(- commandScopeCommands: Accessor<CommandWithInfo[]>-): Record<CategoryFilter, () => CommandMenuItem[]> {+const QUICK_ACCESS_BUCKETS_BY_CATEGORY: Partial<+ Record<CategoryFilter, Bucket[]>+> = {+ all: exclude('person'),+ channels: ['channel'],+ dms: ['dm'],+ documents: ['note', 'document', 'snippet', 'project'],+ tasks: ['task'],+ chats: ['chat'],+ projects: ['project'],+ people: ['person'],+};++/** Creates only the Quick Access list needed by the active category. */+function useQuickAccessCategory(+ categoryFilter: Accessor<CategoryFilter>,+ commandScopeCommands: Accessor<CommandWithInfo[]>,+ searchTerm: Accessor<string>,+ enabled: Accessor<boolean>+) {const quickAccess = useQuickAccess();- const commandsList = useCommandsList(commandScopeCommands);- const entitiesList = quickAccess.useList(...exclude('person'));+ const commands = useCommandsList(commandScopeCommands);+ const activeList = createMemo(() => {+ if (+ commandScopeCommands().length > 0 ||+ CommandState.isEntityActionMode()+ ) {+ return undefined;+ }+ const buckets = QUICK_ACCESS_BUCKETS_BY_CATEGORY[categoryFilter()];+ return buckets+ ? quickAccess.useList({ buckets, searchTerm, enabled })+ : undefined;+ });+ const items = createMemo((): CommandMenuItem[] => {+ if (+ commandScopeCommands().length > 0 ||+ CommandState.isEntityActionMode() ||+ categoryFilter() === 'commands'+ ) {+ return commands();+ }- const allWithCommands = createMemo((): CommandMenuItem[] =>- mergeSortedArrays(- entitiesList(),- commandsList(),+ const entities: CommandMenuItem[] = activeList()?.items() ?? [];+ if (categoryFilter() !== 'all') return entities;+ return mergeSortedArrays(+ entities,+ commands(),(a, b) => b.sortTimestamp - a.sortTimestamp- )- );+ );+ });return {- all: allWithCommands,- channels: quickAccess.useList('channel'),- dms: quickAccess.useList('dm'),- documents: quickAccess.useList('note', 'document', 'snippet', 'project'),- tasks: quickAccess.useList('task'),- chats: quickAccess.useList('chat'),- projects: quickAccess.useList('project'),- people: quickAccess.useList('person'),- commands: commandsList,+ items,+ pagination: {+ hasMore: () => activeList()?.hasMore() ?? false,+ isLoadingMore: () => activeList()?.isLoadingMore() ?? false,+ loadMore: async () => {+ await activeList()?.loadMore();+ },+ } satisfies PaginationControls,};}@@ -360,24 +399,23 @@ export function useCommandItems(* command menu state; mobile search passes its own scope state.*/commandScopeCommands?: Accessor<CommandWithInfo[]>;+ /** Whether this menu should drive cache-backed Quick Access search. */+ searchActive?: Accessor<boolean>;}) {const showSearchRow = options?.showSearchRow ?? true;const commandScopeCommands =options?.commandScopeCommands ?? CommandState.commandScopeCommands;-- const buckets = useQuickAccessBuckets(commandScopeCommands);-- // When in command scope or entity action mode, always show commands regardless of category filter- const categoryItems = () => {- if (commandScopeCommands().length > 0) {- return buckets.commands();- }- if (CommandState.isEntityActionMode()) {- return buckets.commands();- }- return buckets[categoryFilter()]();- };+ const quickAccess = useQuickAccess();+ const searchActive = () => options?.searchActive?.() === true;+ const scopedSearchTerm = () => (searchActive() ? query() : '');+ const category = useQuickAccessCategory(+ categoryFilter,+ commandScopeCommands,+ scopedSearchTerm,+ searchActive+ );+ const categoryItems = category.items;const search = createMemo(() => {const q = query();@@ -390,6 +428,31 @@ export function useCommandItems(});});+ const rankItems = (+ items: CommandMenuItem[],+ queryText: string+ ): CommandMenuItem[] => {+ if (!queryText.trim()) return items.filter(showInRecencyList);+ if (!quickAccess.usesRecordSelection()) {+ return search()(items, queryText).map((result) => result.item);+ }++ const entities = items.filter(isEntityItem);+ const localItems = items.filter((item) => !isEntityItem(item));+ const rankedLocalItems = search()(localItems, queryText).map(+ (result) => result.item+ );+ if (entities.length === 0) return rankedLocalItems;++ const topCommands = rankedLocalItems.filter(isCommandItem).slice(0, 3);+ const topCommandIds = new Set(topCommands.map((item) => item.id));+ return [+ ...topCommands,+ ...entities,+ ...rankedLocalItems.filter((item) => !topCommandIds.has(item.id)),+ ];+ };+const shouldShowSearchRow = (q: string) => {if (!showSearchRow) return false;if (!q.trim()) return false;@@ -409,9 +472,7 @@ export function useCommandItems(!CommandState.isEntityActionMode()) {const trimmedQuery = q.trim();- const ranked = trimmedQuery- ? search()(items, q).map((result) => result.item)- : items.filter(showInRecencyList);+ const ranked = rankItems(items, q);const topCommands = ranked.filter(isCommandItem).slice(0, 3);if (!trimmedQuery || topCommands.length > 0) {@@ -428,9 +489,7 @@ export function useCommandItems(}}- const ranked = q- ? search()(items, q).map((result) => result.item)- : items.filter(showInRecencyList);+ const ranked = rankItems(items, q);if (shouldShowSearchRow(q)) {// With no direct results the menu would only offer search, so also@@ -444,7 +503,10 @@ export function useCommandItems(return ranked;});- return filteredItems;+ return {+ items: filteredItems,+ pagination: category.pagination,+ };}export type { AskAiItem, CommandMenuItem, SearchItem, UserItem };diff --git a/apps/web/src/features/next-soup/soup-view/filters-bar/search/search-facets.tsx b/apps/web/src/features/next-soup/soup-view/filters-bar/search/search-facets.tsxindex 74ff9645c1..9302c0314e 100644--- a/apps/web/src/features/next-soup/soup-view/filters-bar/search/search-facets.tsx+++ b/apps/web/src/features/next-soup/soup-view/filters-bar/search/search-facets.tsx@@ -178,7 +178,7 @@ export type SearchFacetVM = FacetBase &*/function useChannelPicker(): Accessor<SearchableOption[]> {const { useList } = useQuickAccess();- const channels = useList('channel', 'dm');+ const channels = useList('channel', 'dm').items;return createMemo(() =>channels()@@ -206,7 +206,7 @@ function useChannelPicker(): Accessor<SearchableOption[]> {function usePersonPicker(): Accessor<SearchableOption[]> {const { useList } = useQuickAccess();const currentUserId = useUserId();- const people = useList('person');+ const people = useList('person').items;return createMemo(() => {const uid = currentUserId();diff --git a/apps/web/src/features/property/editors/selectors/entityUtils.ts b/apps/web/src/features/property/editors/selectors/entityUtils.tsindex ff3301616b..c7db627927 100644--- a/apps/web/src/features/property/editors/selectors/entityUtils.ts+++ b/apps/web/src/features/property/editors/selectors/entityUtils.ts@@ -70,12 +70,12 @@ export function useQuickAccessEntities<T extends EntityType>(const items = (): EntityTypeItemMap[T][] => {const b = buckets();if (b === null) {- return quickAccess.useList()() as EntityTypeItemMap[T][];+ return quickAccess.useList().items() as EntityTypeItemMap[T][];}if (b.length === 0) {return [];}- return quickAccess.useList(...b)() as EntityTypeItemMap[T][];+ return quickAccess.useList(...b).items() as EntityTypeItemMap[T][];};return { items, isLoading: quickAccess.isLoading };}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex feee5df858..a50c64f7d5 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -21,6 +21,7 @@ import type { LexicalEditor } from 'lexical';import {type Accessor,createEffect,+ createMemo,createSignal,For,onCleanup,@@ -91,12 +92,12 @@ function MentionsMenuInner(props: MentionsMenuProps) {const analytics = useAnalytics();const searchTerm = debouncedDependent(props.menu.searchTerm, 60);+ const activeSearchTerm = () => (props.menu.isOpen() ? searchTerm() : '');const hasCustomEntities = () => !!props.entities;const quickAccess = hasCustomEntities() ? undefined : useQuickAccess();-- const allItems = props.entities ?? quickAccess!.useList();+ const allItems = props.entities ?? quickAccess!.useList().items;const { isKeypressActive } = useIsKeyPressActive();@@ -120,7 +121,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {const customChannels = props.entities? useEntityMentionFromList({items: props.entities,- buckets: ['channel'],+ buckets: ['channel', 'dm'],searchTerm,}): undefined;@@ -134,19 +135,21 @@ function MentionsMenuInner(props: MentionsMenuProps) {}): undefined;- const { searchedEntities: docs } =+ const docsMention =customDocs ??useEntityMention({buckets: ['note', 'task', 'snippet', 'document', 'project', 'chat'],- searchTerm,+ searchTerm: activeSearchTerm,});+ const docs = docsMention.entities;- const { searchedEntities: channels } =+ const channelsMention =customChannels ??useEntityMention({- buckets: ['channel'],- searchTerm,+ buckets: ['channel', 'dm'],+ searchTerm: activeSearchTerm,});+ const channels = channelsMention.entities;// CRM companies only surface in mentions when the feature is enabled —// the mention hook isn't even wired up otherwise.@@ -154,25 +157,29 @@ function MentionsMenuInner(props: MentionsMenuProps) {? (customCompanies ??useEntityMention({buckets: ['crm_company'],- searchTerm,+ searchTerm: activeSearchTerm,})): undefined;- const companies = () => companyMention?.searchedEntities() ?? [];-- const { emails, emailSearchQuery: emailUnifiedSearchInfiniteQuery } =- hasCustomEntities()- ? {- emails: () => [],- emailSearchQuery: {- hasNextPage: false,- isFetching: false,- fetchNextPage: () => {},- } as any,- }- : useEmailSearchMention({- searchTerm,- enabled: () => !props.sources || props.sources.includes('emails'),- });+ const companies = () => companyMention?.entities() ?? [];++ const {+ emails,+ totalCount: totalEmailCount,+ hasMore: hasMoreEmails,+ isLoadingMore: isLoadingMoreEmails,+ loadMore: loadMoreEmails,+ } = hasCustomEntities()+ ? {+ emails: () => [],+ totalCount: () => 0,+ hasMore: () => false,+ isLoadingMore: () => false,+ loadMore: async () => {},+ }+ : useEmailSearchMention({+ searchTerm: activeSearchTerm,+ enabled: () => !props.sources || props.sources.includes('emails'),+ });const dateOptions = useDateSearch({ query: searchTerm });const dates = createLazyMemo((): DateMentionItem[] => {@@ -250,7 +257,31 @@ function MentionsMenuInner(props: MentionsMenuProps) {id: 'all',label: 'All',getData: mobileAllItems,- getFullCount: () => mobileAllItems().length,+ getFullCount: () =>+ (usersAndGroups()?.length ?? 0) ++ docsMention.totalCount() ++ channelsMention.totalCount() ++ (companyMention?.totalCount() ?? 0) ++ totalEmailCount() ++ (dates()?.length ?? 0),+ hasMore: () =>+ docsMention.hasMore() ||+ channelsMention.hasMore() ||+ (companyMention?.hasMore() ?? false) ||+ hasMoreEmails(),+ isLoadingMore: () =>+ docsMention.isLoadingMore() ||+ channelsMention.isLoadingMore() ||+ (companyMention?.isLoadingMore() ?? false) ||+ isLoadingMoreEmails(),+ loadMore: async () => {+ await Promise.all([+ docsMention.loadMore(),+ channelsMention.loadMore(),+ companyMention?.loadMore(),+ loadMoreEmails(),+ ]);+ },},];}@@ -266,25 +297,37 @@ function MentionsMenuInner(props: MentionsMenuProps) {id: 'documents',label: 'Documents, Agents, & Tasks',getData: () => docs() ?? [],- getFullCount: () => docs()?.length ?? 0,+ getFullCount: docsMention.totalCount,+ hasMore: docsMention.hasMore,+ isLoadingMore: docsMention.isLoadingMore,+ loadMore: docsMention.loadMore,},{id: 'channels',label: 'Channels',getData: () => channels() ?? [],- getFullCount: () => channels()?.length ?? 0,+ getFullCount: channelsMention.totalCount,+ hasMore: channelsMention.hasMore,+ isLoadingMore: channelsMention.isLoadingMore,+ loadMore: channelsMention.loadMore,},{id: 'companies',label: 'Companies',getData: () => companies() ?? [],- getFullCount: () => companies()?.length ?? 0,+ getFullCount: () => companyMention?.totalCount() ?? 0,+ hasMore: () => companyMention?.hasMore() ?? false,+ isLoadingMore: () => companyMention?.isLoadingMore() ?? false,+ loadMore: async () => companyMention?.loadMore(),},{id: 'emails',label: 'Emails',getData: () => emails() ?? [],- getFullCount: () => emails()?.length ?? 0,+ getFullCount: totalEmailCount,+ hasMore: hasMoreEmails,+ isLoadingMore: isLoadingMoreEmails,+ loadMore: loadMoreEmails,},{id: 'dates',@@ -377,10 +420,10 @@ function MentionsMenuInner(props: MentionsMenuProps) {if (!controller.isViewAllMode()) {const currentCategory = controller.selectedCategory();if (currentCategory) {+ const category = controller.getBucket(currentCategory);if (controller.canViewAllForCategory(currentCategory) ||- (emailUnifiedSearchInfiniteQuery.hasNextPage &&- currentCategory === 'emails')+ category?.hasMore?.()) {controller.viewAll(currentCategory);}@@ -436,13 +479,16 @@ function MentionsMenuInner(props: MentionsMenuProps) {const items = controller.combinedItems();if (!items) return;+ const viewAllMode = controller.viewAllMode();+ const activeBucket = viewAllMode+ ? controller.getBucket(viewAllMode)+ : undefined;if (controller.selectedIndex() >= items.length - 5 &&- controller.viewAllMode() === 'emails' &&- emailUnifiedSearchInfiniteQuery.hasNextPage &&- !emailUnifiedSearchInfiniteQuery.isFetching+ activeBucket?.hasMore?.() &&+ !activeBucket.isLoadingMore?.()) {- emailUnifiedSearchInfiniteQuery.fetchNextPage();+ void activeBucket.loadMore?.();}if (controller.selectedIndex() >= items.length) {controller.selectItem(items.length - 1);@@ -461,10 +507,16 @@ function MentionsMenuInner(props: MentionsMenuProps) {const mode = controller.viewAllMode();if (!mode) return 'Items';const bucket = bucketConfigs().find((b) => b.id === mode);- return bucket?.label || 'Items';+ if (!bucket) return 'Items';+ return `${bucket.label} (${bucket.getFullCount()})`;+ };++ const activeViewAllBucket = () => {+ const mode = controller.viewAllMode();+ return mode ? controller.getBucket(mode) : undefined;};- const visibleBuckets = () => {+ const visibleBuckets = createMemo(() => {const currentBins = controller.bins();const seenIds = new Set<string>(blockId ? [blockId] : []);let cumulativeIndex = 0;@@ -486,7 +538,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {cumulativeIndex += bucketItems.length;return { config, bucketItems, startIndex };});- };+ });const clickOutsideHandler = (e: MouseEvent) => {e.stopPropagation();@@ -626,6 +678,13 @@ function MentionsMenuInner(props: MentionsMenuProps) {setIndex={setSelectedIndexFromMouse}setOpen={setMenuOpen}maxHeight={contentMaxHeight()}+ hasMore={activeViewAllBucket()?.hasMore?.() ?? false}+ isLoadingMore={+ activeViewAllBucket()?.isLoadingMore?.() ?? false+ }+ onEndReached={() => {+ void activeViewAllBucket()?.loadMore?.();+ }}/></Show></Surface>@@ -642,6 +701,9 @@ function VirtualizedItemList(props: {setIndex: (index: number) => void;setOpen: (open: boolean) => void;maxHeight?: number;+ hasMore: boolean;+ isLoadingMore: boolean;+ onEndReached: () => void;}) {let scrollContainerRef: HTMLDivElement | undefined;@@ -657,7 +719,8 @@ function VirtualizedItemList(props: {// Scroll selected item into viewcreateEffect(() => {const index = props.selectedIndex;- if (index >= 0 && index < props.items.length) {+ const itemCount = untrack(() => props.items.length);+ if (index >= 0 && index < itemCount) {virtualizer.scrollToIndex(index, { align: 'auto' });}});@@ -665,6 +728,13 @@ function VirtualizedItemList(props: {return (<divref={scrollContainerRef}+ onScroll={(event) => {+ if (!props.hasMore || props.isLoadingMore) return;+ const target = event.currentTarget;+ const remaining =+ target.scrollHeight - target.scrollTop - target.clientHeight;+ if (remaining <= VIRTUAL_ITEM_HEIGHT * 5) props.onEndReached();+ }}class="overflow-y-auto scrollbar-hidden"style={{'max-height':diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.tsindex e30914b1e6..0e9aa6bf2b 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts@@ -18,6 +18,9 @@ export interface BucketConfig<T extends MentionItem = MentionItem> {label: string;getData: () => T[];getFullCount: () => number;+ hasMore?: () => boolean;+ isLoadingMore?: () => boolean;+ loadMore?: () => Promise<void> | void;}/**@@ -329,10 +332,9 @@ class MentionsMenuController {canViewAllForCategory(categoryId: string): boolean {const currentBins = this.bins();- const rawBins = this.rawBins();+ const config = this.buckets().find((bucket) => bucket.id === categoryId);const abbreviatedCount = currentBins[categoryId] || 0;- const fullCount = rawBins[categoryId] || 0;- return fullCount > abbreviatedCount;+ return (config?.getFullCount() ?? 0) > abbreviatedCount;}private computeBins(rawBins: MentionBins, maxItems: number): MentionBins {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsxindex 3848bc4a0f..18e8c6596e 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/components/ItemBin.tsx@@ -24,8 +24,8 @@ export function ItemBin(const viewAllText = () => {if (- props.totalCount &&- props.showingCount &&+ props.totalCount !== undefined &&+ props.showingCount !== undefined &&props.totalCount > props.showingCount) {return `View all (${props.totalCount})`;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.tsindex 2800682e3d..748b8a86b7 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEmailSearchMention.ts@@ -1,5 +1,5 @@import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';-import type { EntityItem } from '@core/context/quickAccess';+import { type EntityItem, useQuickAccess } from '@core/context/quickAccess';import { createFreshSearch } from '@core/util/freshSort';import {type SearchSoupQueryArgs,@@ -8,6 +8,8 @@ import {import { createLazyMemo } from '@solid-primitives/memo';import type { Accessor } from 'solid-js';+const USE_QUICK_ACCESS_FOR_EMAIL_MENTIONS: boolean = false;+type UseEmailSearchMentionOptions = {searchTerm: Accessor<string>;enabled?: Accessor<boolean | undefined>;@@ -15,18 +17,30 @@ type UseEmailSearchMentionOptions = {type UseEmailSearchMentionResult = {emails: Accessor<EntityItem[]>;- emailSearchQuery: ReturnType<typeof useSearchSoupQuery>;+ totalCount: Accessor<number>;+ hasMore: Accessor<boolean>;+ isLoadingMore: Accessor<boolean>;+ loadMore: () => Promise<void>;};/**- * Hook for managing email mentions in the mentions menu with query-based search.+ * Provides email mentions through unified search by default. The Quick Access+ * path remains available behind USE_QUICK_ACCESS_FOR_EMAIL_MENTIONS.*/export function useEmailSearchMention(options: UseEmailSearchMentionOptions): UseEmailSearchMentionResult {const { searchTerm, enabled } = options;+ const listEnabled = () => enabled?.() !== false;+ const quickAccess = useQuickAccess();+ const usesQuickAccess = () =>+ USE_QUICK_ACCESS_FOR_EMAIL_MENTIONS && quickAccess.usesRecordSelection();+ const cachedEmails = quickAccess.useList({+ buckets: ['email'],+ searchTerm,+ enabled: () => usesQuickAccess() && listEnabled(),+ });- // Build search query args for remote email searchconst args = createLazyMemo((): SearchSoupQueryArgs => {return {params: {@@ -46,10 +60,10 @@ export function useEmailSearchMention(});const emailSearchQuery = useSearchSoupQuery(args, () => ({- enabled: enabled?.(),+ enabled: !usesQuickAccess() && listEnabled(),}));- const emailList = createLazyMemo((): EntityItem[] => {+ const remoteEmailList = createLazyMemo((): EntityItem[] => {if (emailSearchQuery.status !== 'success') return [];return emailSearchQuery.data.filter((e) => e.type === 'email')@@ -76,13 +90,32 @@ export function useEmailSearchMention(});const emails = createLazyMemo((): EntityItem[] => {+ if (usesQuickAccess()) return cachedEmails.items();+const term = searchTerm();- if (!term) return emailList();- return emailSearch(emailList(), term).map(({ item }) => item);+ const remoteEmails = remoteEmailList();+ if (!term) return remoteEmails;+ return emailSearch(remoteEmails, term).map(({ item }) => item);});return {emails,- emailSearchQuery,+ totalCount: () =>+ usesQuickAccess() ? cachedEmails.totalCount() : emails().length,+ hasMore: () =>+ usesQuickAccess()+ ? cachedEmails.hasMore()+ : Boolean(emailSearchQuery.hasNextPage),+ isLoadingMore: () =>+ usesQuickAccess()+ ? cachedEmails.isLoadingMore()+ : emailSearchQuery.isFetching,+ loadMore: async () => {+ if (usesQuickAccess()) {+ await cachedEmails.loadMore();+ } else if (emailSearchQuery.hasNextPage) {+ await emailSearchQuery.fetchNextPage();+ }+ },};}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.tsindex 9712145dbb..f03995ff73 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts@@ -1,20 +1,25 @@import {type EntityBucket,type EntityItem,+ type QuickAccessList,useQuickAccess,} from '@core/context/quickAccess';-import { createFreshSearch } from '@core/util/freshSort';+import { searchQuickAccessEntities } from '@core/context/quickAccess/entity-search';import { createLazyMemo } from '@solid-primitives/memo';import type { Accessor } from 'solid-js';type UseEntityMentionOptions = {- searchTerm: Accessor<string>;buckets: EntityBucket[];+ searchTerm: Accessor<string>;};type UseEntityMentionResult = {- searchedEntities: Accessor<EntityItem[]>;- allEntities: Accessor<EntityItem[]>;+ entities: Accessor<EntityItem[]>;+ totalCount: Accessor<number>;+ hasMore: Accessor<boolean>;+ isLoading: Accessor<boolean>;+ isLoadingMore: Accessor<boolean>;+ loadMore: () => Promise<void>;};/**@@ -24,29 +29,32 @@ type UseEntityMentionResult = {export function useEntityMention(options: UseEntityMentionOptions): UseEntityMentionResult {- const { searchTerm, buckets } = options;const quickAccess = useQuickAccess();-- const entitiesList = quickAccess.useList(- ...(buckets as [EntityBucket, ...EntityBucket[]])- );-- const entitySearch = createFreshSearch<EntityItem>({- config: { useViewedAt: true },- getName: (item) => item.searchText,- isChannelItem: (item) => item.bucket === 'channel',- getTimestamp: (item) => item.timestamps,- });-+ const entityList = quickAccess.useList({+ buckets: options.buckets,+ searchTerm: options.searchTerm,+ }) as QuickAccessList<EntityItem>;const entities = createLazyMemo(() => {- const term = searchTerm();- if (!term) return entitiesList();- return entitySearch(entitiesList(), term).map(({ item }) => item);+ if (quickAccess.usesRecordSelection()) return entityList.items();+ return searchQuickAccessEntities(entityList.items(), options.searchTerm());});return {- searchedEntities: entities,- allEntities: entitiesList,+ entities,+ totalCount: () =>+ quickAccess.usesRecordSelection()+ ? entityList.totalCount()+ : entities().length,+ hasMore: () => quickAccess.usesRecordSelection() && entityList.hasMore(),+ isLoading: () =>+ quickAccess.usesRecordSelection()+ ? entityList.isLoading()+ : quickAccess.isLoading(),+ isLoadingMore: () =>+ quickAccess.usesRecordSelection() && entityList.isLoadingMore(),+ loadMore: async () => {+ if (quickAccess.usesRecordSelection()) await entityList.loadMore();+ },};}@@ -70,21 +78,16 @@ export function useEntityMentionFromList(items().filter((item) => bucketSet.has(item.bucket)));- const entitySearch = createFreshSearch<EntityItem>({- config: { useViewedAt: true },- getName: (item) => item.searchText,- isChannelItem: (item) => item.bucket === 'channel',- getTimestamp: (item) => item.timestamps,- });-- const entities = createLazyMemo(() => {- const term = searchTerm();- if (!term) return entitiesList();- return entitySearch(entitiesList(), term).map(({ item }) => item);- });+ const entities = createLazyMemo(() =>+ searchQuickAccessEntities(entitiesList(), searchTerm())+ );return {- searchedEntities: entities,- allEntities: entitiesList,+ entities,+ totalCount: () => entities().length,+ hasMore: () => false,+ isLoading: () => false,+ isLoadingMore: () => false,+ loadMore: async () => undefined,};}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.tsindex 94dbd49ad5..a82ef75501 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts@@ -67,7 +67,7 @@ export function useUsersMention(}) as UserItem);}- return quickAccess.useList('person');+ return quickAccess.useList('person').items;});const userSearch = () => {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsxindex c871f8595f..3abe97a7e1 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx@@ -59,10 +59,11 @@ function SnippetsMenuInner(props: SnippetsMenuProps) {const analytics = useAnalytics();const searchTerm = debouncedDependent(props.menu.searchTerm, 60);+ const activeSearchTerm = () => (props.menu.isOpen() ? searchTerm() : '');- const { searchedEntities: snippets } = useEntityMention({+ const { entities: snippets } = useEntityMention({buckets: ['snippet'],- searchTerm,+ searchTerm: activeSearchTerm,});const filteredSnippets = () =>snippets().filter((snippet) => snippet.id !== props.sourceDocumentId);diff --git a/apps/web/src/lib/core/context/quickAccess/GraphqlQuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/GraphqlQuickAccessSource.tsxnew file mode 100644index 0000000000..e1f5f8981d--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/GraphqlQuickAccessSource.tsx@@ -0,0 +1,326 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import {+ ENABLE_CRM_FLAG,+ ENABLE_CRM_OVERRIDE,+ ENABLE_SNIPPETS_FLAG,+ ENABLE_SNIPPETS_OVERRIDE,+} from '@core/constant/featureFlags';+import {+ useAugmentUserWithDmActivity,+ useContacts,+ useIsConnectedSecondaryInbox,+} from '@core/user';+import { createQuerySignal } from '@graphql-cache/solid/create-query-signal';+import { useQuickAccessCrmCompaniesQuery } from '@queries/soup/quick-access-crm-companies';+import { useQuickAccessSnippetsQuery } from '@queries/soup/quick-access-snippets';+import { mapSoupPageToEntityList } from '@queries/soup/transform-utils';+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';+import type { SoupPage } from '@service-storage/generated/schemas';+import {+ SoupDocument,+ type SoupInput,+ type SoupQuery,+ type SoupQueryVariables,+} from '@service-storage/graphql/generated/graphql';+import {+ getGraphqlSoupCacheHost,+ getGraphqlSoupClient,+ mapGraphqlSoupItem,+ mapGraphqlSoupPage,+} from '@service-storage/graphql-soup';+import { createLazyMemo } from '@solid-primitives/memo';+import { debounce } from '@solid-primitives/scheduled';+import { useQueryClient } from '@tanstack/solid-query';+import { createMemo, createSignal, onCleanup, untrack } from 'solid-js';+import {+ graphqlEntityToQuickAccessItem,+ userToQuickAccessItem,+} from './graphql-items';+import {+ createQuickAccessRecordSelectionQuery,+ QUICK_ACCESS_RECORD_SELECTION_QUERY_KEY,+} from './record-selection-items';+import { createRecordSelectionQuickAccessItems } from './record-selection-list';+import type {+ Bucket,+ EntityItem,+ QuickAccessContextValue,+ QuickAccessItem,+ QuickAccessList,+ QuickAccessListOptions,+} from './types';++const QUICK_ACCESS_LIMIT = 500;+const DEFAULT_SEARCH_PAGE_SIZE = 50;+const CACHE_REFRESH_DEBOUNCE_MS = 250;+const NIL_UUID = '00000000-0000-0000-0000-000000000000';++function makeQuickAccessInput(snippetsEnabled: boolean): SoupInput {+ return {+ initial: {+ limit: QUICK_ACCESS_LIMIT,+ expand: true,+ sortMethod: 'VIEWED_UPDATED',+ emailView: 'ALL',+ filters: {+ emailFilter: { tree: { literal: { threadId: NIL_UUID } } },+ callFilter: { literal: { callId: NIL_UUID } },+ channelThreadFilter: { literal: { threadId: NIL_UUID } },+ foreignEntityFilter: { literal: { id: NIL_UUID } },+ // CRM comes from its dedicated team-aware query below. The GraphQL+ // resolver cannot return the broad company list without a team receipt.+ crmCompanyFilter: { literal: { id: NIL_UUID } },+ documentFilter: snippetsEnabled+ ? undefined+ : { not: { literal: { subType: 'SNIPPET' } } },+ },+ },+ };+}++function isTombstonedGraphqlItem(item: SoupPage['items'][number]): boolean {+ if (!item) return false;+ switch (item.tag) {+ case 'document':+ case 'chat':+ case 'project':+ return Boolean(item.data.deletedAt);+ default:+ return false;+ }+}++function mapGraphqlQuickAccessEntities(+ page: SoupPage,+ instructionsIdQuery: ReturnType<typeof useInstructionsMdIdQuery>+) {+ const visiblePage: SoupPage = {+ ...page,+ items: page.items.filter((item) => !isTombstonedGraphqlItem(item)),+ };+ const channelViewedAt = new Map<string, string | undefined>();+ for (const item of visiblePage.items) {+ if (item?.tag === 'channel') {+ channelViewedAt.set(+ item.data.channel.id,+ item.data.viewed_at ?? undefined+ );+ }+ }++ return mapSoupPageToEntityList(visiblePage, {+ instructionsIdQuery,+ }).map((entity) => {+ if (entity.type !== 'channel') return entity;+ return {+ ...entity,+ // `mapApiSoupItemToEntity` normally falls back to interacted_at. Quick+ // Access sorting must preserve the GraphQL viewedAt value itself.+ viewedAt: channelViewedAt.get(entity.id),+ };+ });+}++export function createGraphqlQuickAccessValue(): QuickAccessContextValue {+ const contacts = useContacts();+ const augmentUserWithDmActivity = useAugmentUserWithDmActivity();+ const isConnectedSecondaryInbox = useIsConnectedSecondaryInbox();+ const instructionsIdQuery = useInstructionsMdIdQuery();+ const crmFlag = useFeatureFlag(ENABLE_CRM_FLAG, {+ enabledOverride: ENABLE_CRM_OVERRIDE,+ });+ const snippetsFlag = useFeatureFlag(ENABLE_SNIPPETS_FLAG, {+ enabledOverride: ENABLE_SNIPPETS_OVERRIDE,+ });+ const { query: crmCompaniesQuery, companies: crmCompanies } =+ useQuickAccessCrmCompaniesQuery();+ const { query: snippetsQuery, snippets } = useQuickAccessSnippetsQuery();++ const cacheHost = getGraphqlSoupCacheHost();++ const queryClient = useQueryClient();+ const invalidateRecordSelection = () =>+ queryClient.invalidateQueries({+ queryKey: QUICK_ACCESS_RECORD_SELECTION_QUERY_KEY,+ });+ const scheduleCacheRefresh = debounce(() => {+ void invalidateRecordSelection();+ }, CACHE_REFRESH_DEBOUNCE_MS);++ const unsubscribeCacheChanges =+ cacheHost?.onCacheChanged(scheduleCacheRefresh);+ onCleanup(() => {+ unsubscribeCacheChanges?.();+ scheduleCacheRefresh.clear();+ });++ const input = createMemo(() => makeQuickAccessInput(snippetsFlag().enabled));+ const [refreshVersion, setRefreshVersion] = createSignal(0);+ const query = createQuerySignal<SoupQuery, SoupQueryVariables>({+ client: getGraphqlSoupClient,+ document: SoupDocument,+ variables: () => {+ refreshVersion();+ return { input: input() };+ },+ requestPolicy: 'cache-and-network',+ });+ // A network error can emit an undefined result after a stale cache hit.+ // Keep the last page so offline/revalidation failures do not empty the menu.+ const retainedQueryData = createMemo<SoupQuery | undefined>(+ (previous) => query.data() ?? previous+ );+ const graphqlEntities = createLazyMemo(() => {+ const data = retainedQueryData();+ if (!data) return [];+ return mapGraphqlQuickAccessEntities(+ mapGraphqlSoupPage(data),+ instructionsIdQuery+ );+ });++ const recordSelectionQuery = createQuickAccessRecordSelectionQuery({+ cacheHost: () => cacheHost,+ });+ const selectedEntities = createMemo(() => {+ const records = recordSelectionQuery.data;+ if (!records) return [];+ return mapGraphqlQuickAccessEntities(+ {+ items: records.map(mapGraphqlSoupItem),+ next_cursor: undefined,+ },+ instructionsIdQuery+ );+ });+ const itemsById = new Map<string, QuickAccessItem>();+ const selectedItemsById = new Map<string, QuickAccessItem>();+ const selectedItems = createMemo<EntityItem[]>(() => {+ const items = selectedEntities().flatMap((entity) => {+ const item = graphqlEntityToQuickAccessItem(entity);+ return item ? [item] : [];+ });+ selectedItemsById.clear();+ for (const item of items) selectedItemsById.set(item.id, item);+ return items;+ });++ const localItems = createMemo<QuickAccessItem[]>(() => {+ const nextItemsById = new Map<string, QuickAccessItem>();+ const addItem = (item: QuickAccessItem, replaceOnTie = false) => {+ const current = nextItemsById.get(item.id);+ if (+ !current ||+ item.sortTimestamp > current.sortTimestamp ||+ (replaceOnTie && item.sortTimestamp === current.sortTimestamp)+ ) {+ nextItemsById.set(item.id, item);+ }+ };+ const addEntity = (item: QuickAccessItem | undefined) => {+ if (!item || item.kind !== 'entity') return;+ if (item.bucket === 'note' && item.id === instructionsIdQuery.data)+ return;+ if (item.bucket === 'crm_company' && !crmFlag().enabled) return;+ if (item.bucket === 'snippet' && !snippetsFlag().enabled) return;+ addItem(item, true);+ };++ if (crmFlag().enabled) {+ for (const company of crmCompanies()) {+ addEntity(graphqlEntityToQuickAccessItem(company));+ }+ }+ if (snippetsFlag().enabled) {+ for (const snippet of snippets()) {+ addEntity(graphqlEntityToQuickAccessItem(snippet));+ }+ }+ for (const entity of graphqlEntities()) {+ addEntity(graphqlEntityToQuickAccessItem(entity));+ }+ for (const contact of contacts()) {+ if (isConnectedSecondaryInbox(contact.id)) continue;+ addItem(userToQuickAccessItem(augmentUserWithDmActivity(contact)));+ }++ const items = [...nextItemsById.values()].sort(+ (a, b) => b.sortTimestamp - a.sortTimestamp || a.id.localeCompare(b.id)+ );+ itemsById.clear();+ for (const item of items) itemsById.set(item.id, item);+ return items;+ });++ const useList = ((+ ...args: Bucket[] | [QuickAccessListOptions]+ ): QuickAccessList => {+ const first = args[0];+ const options =+ typeof first === 'object'+ ? first+ : {+ buckets: args as Bucket[],+ searchTerm: undefined,+ enabled: undefined,+ };++ const buckets = [...options.buckets];++ const listEnabled = () => options.enabled?.() ?? true;++ const activeSearchTerm = createMemo(+ () => options.searchTerm?.().trim() ?? ''+ );++ // Prevent reactive reads inside the hook from rerunning `useList`.+ const selected = untrack(() =>+ createRecordSelectionQuickAccessItems({+ buckets,+ searchTerm: activeSearchTerm,+ enabled: listEnabled,+ pageSize: DEFAULT_SEARCH_PAGE_SIZE,+ selectedItems,+ localItems,+ instructionsId: () => instructionsIdQuery.data ?? undefined,+ snippetsEnabled: () => snippetsFlag().enabled,+ crmEnabled: () => crmFlag().enabled,+ onItems: () => undefined,+ })+ );++ return {+ items: selected.items,+ totalCount: selected.totalCount,+ hasMore: () => listEnabled() && selected.hasMore(),+ isLoading: () =>+ listEnabled() &&+ cacheHost !== undefined &&+ recordSelectionQuery.isPending &&+ recordSelectionQuery.data === undefined,+ isLoadingMore: selected.isLoadingMore,+ loadMore: selected.loadMore,+ };+ }) as QuickAccessContextValue['useList'];++ const getById = (id: string): QuickAccessItem | undefined => {+ localItems();+ selectedItems();+ return itemsById.get(id) ?? selectedItemsById.get(id);+ };++ const refresh = () => {+ setRefreshVersion((version) => version + 1);+ void invalidateRecordSelection();+ void crmCompaniesQuery.refetch();+ void snippetsQuery.refetch();+ };++ return {+ useList,+ usesRecordSelection: () => true,+ isLoading: () => retainedQueryData() === undefined && query.fetching(),+ refresh,+ getById,+ };+}diff --git a/apps/web/src/lib/core/context/quickAccess/LegacyQuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/LegacyQuickAccessSource.tsxnew file mode 100644index 0000000000..ccf5ad4d25--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/LegacyQuickAccessSource.tsx@@ -0,0 +1,736 @@+import { itemToSafeName } from '@core/constant/allBlocks';+import { useChannelsContext } from '@core/context/channels';+import {+ type IUser,+ useAugmentUserWithDmActivity,+ useContacts,+ useIsConnectedSecondaryInbox,+} from '@core/user';+import type { DateValue } from '@core/util/date';+import type { ChannelEntity, CrmCompanyEntity, SnippetEntity } from '@entity';+import { queryReadyGate } from '@queries/gate';+import { type HistoryItem, useHistoryQuery } from '@queries/history/history';+import { useQuickAccessCrmCompaniesQuery } from '@queries/soup/quick-access-crm-companies';+import { useQuickAccessSnippetsQuery } from '@queries/soup/quick-access-snippets';+import { useRecentlyViewedSoupQuery } from '@queries/soup/recently-viewed';+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';+import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';+import { formatDocumentName } from '@service-storage/util/filename';+import { createLazyMemo } from '@solid-primitives/memo';+import { toDate } from 'date-fns';+import { createEffect, createSignal } from 'solid-js';+import type {+ Bucket,+ BucketCombination,+ EntityBucket,+ QuickAccessContextValue,+ QuickAccessEntity,+ QuickAccessItem,+ QuickAccessList,+ QuickAccessListOptions,+} from './types';+import { BUCKET_COMBINATIONS } from './types';++/**+ * index entry for sorted lists.+ */+type IndexEntry = {+ id: string;+ bucket: Bucket;+ sortTimestamp: number;+};++/**+ * full item and version hash.+ */+type CacheEntry = {+ item: QuickAccessItem;+ version: string;+};++function historyItemToEntity(item: HistoryItem): QuickAccessEntity {+ const base = {+ id: item.id,+ name: item.name,+ createdAt: item.createdAt,+ updatedAt: item.updatedAt,+ ownerId: item.ownerId,+ };++ switch (item.type) {+ case 'chat':+ return {+ ...base,+ type: 'chat',+ } as QuickAccessEntity;++ case 'project':+ return {+ ...base,+ type: 'project',+ } as QuickAccessEntity;++ case 'document': {+ const fileType = item.fileType ?? undefined;+ const subType = item.subType ?? undefined;+ const name = formatDocumentName(+ itemToSafeName({+ name: item.rawName ?? item.name,+ type: item.type,+ fileType,+ subType,+ }),+ fileType,+ {+ fullyQualifiedBlockName: true,+ }+ );+ return {+ ...base,+ name,+ type: 'document',+ fileType,+ subType: item.subType,+ } as QuickAccessEntity;+ }++ default:+ return {+ ...base,+ type: 'document',+ } as QuickAccessEntity;+ }+}++function channelToEntity(channel: ApiChannelWithLatest): ChannelEntity {+ return {+ type: 'channel',+ id: channel.id,+ name: channel.name ?? '',+ ownerId: channel.owner_id ?? '',+ channelType: channel.channel_type ?? 'public',+ participantIds: channel.participants?.map((p) => p.user_id),+ createdAt: channel.created_at,+ updatedAt: channel.updated_at,+ viewedAt: channel.viewed_at,+ interactedAt: channel.interacted_at,+ };+}++/**+ * Determines the bucket for a history item.+ */+function getBucketForHistoryItem(item: HistoryItem): EntityBucket {+ switch (item.type) {+ case 'chat':+ return 'chat';+ case 'project':+ return 'project';+ case 'document': {+ if (item.subType?.type === 'task') return 'task';+ if (item.subType?.type === 'snippet') return 'snippet';+ if (item.fileType === 'md') return 'note';+ return 'document';+ }+ default:+ return 'document';+ }+}++function getUserSearchText(user: IUser): string {+ const { email, name } = user;+ if (name === email) return `${email} | ${email}`;+ return `${name} | ${email}`;+}++function getEntitySearchText(entity: QuickAccessEntity): string {+ return entity.name;+}++function toTimestamp(value: DateValue | null | undefined): number {+ if (value == null) return 0;+ return toDate(value).getTime();+}++function getHistoryItemVersion(item: HistoryItem, viewedAt?: string): string {+ return `${item.name}|${item.updatedAt}|${viewedAt}|${item.deletedAt}`;+}++function getChannelVersion(+ channel: ApiChannelWithLatest,+ viewedAt?: string+): string {+ return `${channel.name}|${channel.updated_at}|${viewedAt}`;+}++function getUserVersion(user: IUser): string {+ return `${user.name}|${user.email}|${user.lastInteraction}`;+}++function getCrmCompanySearchText(company: CrmCompanyEntity): string {+ const domains = company.domains.map((d) => d.domain).join(' ');+ return domains ? `${company.name} | ${domains}` : company.name;+}++function getCrmCompanyVersion(+ company: CrmCompanyEntity,+ viewedAt?: string+): string {+ const domains = company.domains.map((d) => d.domain).join(',');+ return `${company.name}|${domains}|${company.updatedAt}|${viewedAt}`;+}++function getSnippetVersion(snippet: SnippetEntity, viewedAt?: string): string {+ return `${snippet.name}|${snippet.updatedAt}|${viewedAt}`;+}++/**+ * Merge two *already* sorted index arrays into a single sorted array.+ */+function mergeSortedIndices(a: IndexEntry[], b: IndexEntry[]): IndexEntry[] {+ const result: IndexEntry[] = [];+ let i = 0;+ let j = 0;++ while (i < a.length && j < b.length) {+ if (a[i].sortTimestamp >= b[j].sortTimestamp) {+ result.push(a[i]);+ i++;+ } else {+ result.push(b[j]);+ j++;+ }+ }++ while (i < a.length) {+ result.push(a[i]);+ i++;+ }+ while (j < b.length) {+ result.push(b[j]);+ j++;+ }++ return result;+}++/**+ * Merge multiple *already* sorted index arrays into a single sorted array.+ */+function mergeMultipleSortedIndices(arrays: IndexEntry[][]): IndexEntry[] {+ if (arrays.length === 0) return [];+ if (arrays.length === 1) return arrays[0];+ return arrays.reduce((acc, arr) => mergeSortedIndices(acc, arr));+}++export function createLegacyQuickAccessValue(): QuickAccessContextValue {+ // queries+ const historyQuery = useHistoryQuery();+ const { channels, isLoading: channelsLoading } = useChannelsContext();+ const contacts = useContacts();+ const augmentUserWithDmActivity = useAugmentUserWithDmActivity();+ const isConnectedSecondaryInbox = useIsConnectedSecondaryInbox();+ const instructionsIdQuery = useInstructionsMdIdQuery();+ const { query: crmCompaniesQuery, companies: crmCompaniesAccessor } =+ useQuickAccessCrmCompaniesQuery();+ const { query: snippetsQuery, snippets: snippetsAccessor } =+ useQuickAccessSnippetsQuery();++ // globally hidden ids+ const [hiddenIds, setHiddenIds] = createSignal<Set<string>>(new Set());++ const hideId = (id: string) => {+ setHiddenIds((prev) => {+ const next = new Set(prev);+ next.add(id);+ return next;+ });+ };++ // instructions.md effect+ createEffect(() => {+ const instructionsReady = queryReadyGate(instructionsIdQuery);+ if (!instructionsReady) return;+ const instructionsId = instructionsIdQuery.data;+ if (!instructionsId) return;+ hideId(instructionsId);+ });++ // stable cache for transformed items+ const itemCache = new Map<string, CacheEntry>();++ const recentlyViewedQuery = useRecentlyViewedSoupQuery();++ const soupViewedAtMap = createLazyMemo(() => {+ const map = new Map<string, string>();+ const data = recentlyViewedQuery.data;+ if (!data) return map;+ for (const item of data) {+ if (item.viewedAt) map.set(item.id, item.viewedAt);+ }+ return map;+ });++ const processedData = createLazyMemo(() => {+ const viewedAtMap = soupViewedAtMap();+ const seenIds = new Set<string>();+ const allEntries: IndexEntry[] = [];++ const transformedItems: Array<{+ id: string;+ name: string;+ type: string;+ reason: string;+ }> = [];++ // Process history items+ const historyData = historyQuery.data ?? [];+ const hidden = hiddenIds();+ for (const item of historyData) {+ if (item.deletedAt) continue;+ if (hidden.has(item.id)) continue;+ seenIds.add(item.id);++ const viewedAt = viewedAtMap.get(item.id);++ const version = getHistoryItemVersion(item, viewedAt);+ const cached = itemCache.get(item.id);++ if (!cached || cached.version !== version) {+ const reason = !cached+ ? 'new'+ : `changed (${cached.version} -> ${version})`;+ transformedItems.push({+ id: item.id,+ name: item.name,+ type: `history:${item.type}`,+ reason,+ });+ const bucket = getBucketForHistoryItem(item);+ const entity = {+ ...historyItemToEntity(item),+ viewedAt,+ };+ const viewedAtMs = toTimestamp(viewedAt);+ const updatedAtMs = toTimestamp(item.updatedAt);+ const sortTimestamp = viewedAtMs || updatedAtMs;++ const quickAccessItem: QuickAccessItem = {+ kind: 'entity',+ id: item.id,+ bucket,+ searchText: getEntitySearchText(entity),+ sortTimestamp,+ timestamps: {+ viewedAt,+ updatedAt: item.updatedAt,+ createdAt: item.createdAt,+ },+ data: entity,+ };++ itemCache.set(item.id, { item: quickAccessItem, version });+ allEntries.push({ id: item.id, bucket, sortTimestamp });+ } else {+ allEntries.push({+ id: item.id,+ bucket: cached.item.bucket,+ sortTimestamp: cached.item.sortTimestamp,+ });+ }+ }++ // Process channels+ const channelData = channels();+ for (const channel of channelData) {+ seenIds.add(channel.id);++ const viewedAt =+ viewedAtMap.get(channel.id) ?? channel.viewed_at ?? undefined;++ const version = getChannelVersion(channel, viewedAt);+ const cached = itemCache.get(channel.id);++ if (!cached || cached.version !== version) {+ const reason = !cached+ ? 'new'+ : `changed (${cached.version} -> ${version})`;+ transformedItems.push({+ id: channel.id,+ name: channel.name ?? '',+ type: `channel:${channel.channel_type}`,+ reason,+ });+ const isDm = channel.channel_type === 'direct_message';+ const bucket: Bucket = isDm ? 'dm' : 'channel';+ const entity = {+ ...channelToEntity(channel),+ viewedAt,+ };+ const viewedAtMs = toTimestamp(viewedAt);+ const updatedAtMs = toTimestamp(channel.updated_at);+ const sortTimestamp = viewedAtMs || updatedAtMs;++ const quickAccessItem: QuickAccessItem = {+ kind: 'entity',+ id: channel.id,+ bucket,+ searchText: channel.name ?? '',+ sortTimestamp,+ timestamps: {+ viewedAt,+ updatedAt: channel.updated_at,+ createdAt: channel.created_at,+ },+ data: entity,+ };++ itemCache.set(channel.id, { item: quickAccessItem, version });+ allEntries.push({ id: channel.id, bucket, sortTimestamp });+ } else {+ allEntries.push({+ id: channel.id,+ bucket: cached.item.bucket,+ sortTimestamp: cached.item.sortTimestamp,+ });+ }+ }++ // Process contacts (users)+ const contactData = contacts();+ for (const contact of contactData) {+ if (isConnectedSecondaryInbox(contact.id)) continue;+ const augmentedUser = augmentUserWithDmActivity(contact);+ seenIds.add(augmentedUser.id);++ const version = getUserVersion(augmentedUser);+ const cached = itemCache.get(augmentedUser.id);++ if (!cached || cached.version !== version) {+ const reason = !cached+ ? 'new'+ : `changed (${cached.version} -> ${version})`;+ transformedItems.push({+ id: augmentedUser.id,+ name: augmentedUser.name,+ type: 'user',+ reason,+ });+ const sortTimestamp = toTimestamp(augmentedUser.lastInteraction);++ const quickAccessItem: QuickAccessItem = {+ kind: 'user',+ id: augmentedUser.id,+ bucket: 'person',+ searchText: getUserSearchText(augmentedUser),+ sortTimestamp,+ timestamps: {+ lastInteraction: augmentedUser.lastInteraction,+ },+ data: augmentedUser,+ };++ itemCache.set(augmentedUser.id, { item: quickAccessItem, version });+ allEntries.push({+ id: augmentedUser.id,+ bucket: 'person',+ sortTimestamp,+ });+ } else {+ allEntries.push({+ id: augmentedUser.id,+ bucket: cached.item.bucket,+ sortTimestamp: cached.item.sortTimestamp,+ });+ }+ }++ // Process CRM companies (live soup list, complements the+ // recently-viewed feed which only has companies the user has+ // opened). Sort timestamp prefers viewed_at; falls back to+ // updated_at for unviewed companies — same shape as channels.+ const crmCompanyData = crmCompaniesAccessor();+ for (const company of crmCompanyData) {+ if (hidden.has(company.id)) continue;+ seenIds.add(company.id);++ const viewedAt =+ viewedAtMap.get(company.id) ?? company.viewedAt ?? undefined;++ const version = getCrmCompanyVersion(+ company,+ viewedAt as string | undefined+ );+ const cached = itemCache.get(company.id);++ if (!cached || cached.version !== version) {+ const reason = !cached+ ? 'new'+ : `changed (${cached.version} -> ${version})`;+ transformedItems.push({+ id: company.id,+ name: company.name,+ type: 'crm_company',+ reason,+ });+ const entity: CrmCompanyEntity = {+ ...company,+ viewedAt: (viewedAt ?? company.viewedAt) as DateValue | null,+ };+ const viewedAtMs = toTimestamp(viewedAt);+ const updatedAtMs = toTimestamp(company.updatedAt);+ const sortTimestamp = viewedAtMs || updatedAtMs;++ const quickAccessItem: QuickAccessItem = {+ kind: 'entity',+ id: company.id,+ bucket: 'crm_company',+ searchText: getCrmCompanySearchText(entity),+ sortTimestamp,+ timestamps: {+ viewedAt,+ updatedAt: company.updatedAt,+ createdAt: company.createdAt,+ },+ data: entity,+ };++ itemCache.set(company.id, { item: quickAccessItem, version });+ allEntries.push({+ id: company.id,+ bucket: 'crm_company',+ sortTimestamp,+ });+ } else {+ allEntries.push({+ id: company.id,+ bucket: cached.item.bucket,+ sortTimestamp: cached.item.sortTimestamp,+ });+ }+ }++ // Process snippets (live soup list, complements the history feed+ // which only has snippets the user has opened). Widens the pool to+ // team-shared snippets so the `;` menu lists snippets the user has+ // never opened. History-fed entries win for snippets the user has+ // already opened.+ const snippetData = snippetsAccessor();+ for (const snippet of snippetData) {+ if (hidden.has(snippet.id)) continue;+ if (seenIds.has(snippet.id)) continue;+ seenIds.add(snippet.id);++ const viewedAt =+ viewedAtMap.get(snippet.id) ?? snippet.viewedAt ?? undefined;++ const version = getSnippetVersion(+ snippet,+ viewedAt as string | undefined+ );+ const cached = itemCache.get(snippet.id);++ if (!cached || cached.version !== version) {+ const reason = !cached+ ? 'new'+ : `changed (${cached.version} -> ${version})`;+ transformedItems.push({+ id: snippet.id,+ name: snippet.name,+ type: 'snippet',+ reason,+ });+ const entity: SnippetEntity = {+ ...snippet,+ viewedAt: (viewedAt ?? snippet.viewedAt) as DateValue | null,+ };+ const viewedAtMs = toTimestamp(viewedAt);+ const updatedAtMs = toTimestamp(snippet.updatedAt);+ const sortTimestamp = viewedAtMs || updatedAtMs;++ const quickAccessItem: QuickAccessItem = {+ kind: 'entity',+ id: snippet.id,+ bucket: 'snippet',+ searchText: getEntitySearchText(entity),+ sortTimestamp,+ timestamps: {+ viewedAt,+ updatedAt: snippet.updatedAt,+ createdAt: snippet.createdAt,+ },+ data: entity,+ };++ itemCache.set(snippet.id, { item: quickAccessItem, version });+ allEntries.push({+ id: snippet.id,+ bucket: 'snippet',+ sortTimestamp,+ });+ } else {+ allEntries.push({+ id: snippet.id,+ bucket: cached.item.bucket,+ sortTimestamp: cached.item.sortTimestamp,+ });+ }+ }++ // Clean up stale cache entries (items that no longer exist)+ for (const id of itemCache.keys()) {+ if (!seenIds.has(id)) {+ itemCache.delete(id);+ }+ }++ // Sort all entries by timestamp descending+ allEntries.sort((a, b) => b.sortTimestamp - a.sortTimestamp);++ // Deduplicate by id - keep the first occurrence (most recent timestamp)+ const deduplicatedEntries: IndexEntry[] = [];+ const dedupeSet = new Set<string>();+ for (const entry of allEntries) {+ if (!dedupeSet.has(entry.id)) {+ dedupeSet.add(entry.id);+ deduplicatedEntries.push(entry);+ }+ }++ return deduplicatedEntries;+ });++ const getById = (id: string): QuickAccessItem | undefined => {+ return itemCache.get(id)?.item;+ };++ const resolveEntries = (entries: IndexEntry[]): QuickAccessItem[] => {+ const result: QuickAccessItem[] = [];+ for (const entry of entries) {+ const cached = itemCache.get(entry.id);+ if (cached) {+ result.push(cached.item);+ }+ }+ return result;+ };++ // Pre-compute individual bucket index lists (each already sorted)+ const bucketIndices = createLazyMemo<Map<Bucket, IndexEntry[]>>(() => {+ const map = new Map<Bucket, IndexEntry[]>();+ for (const entry of processedData()) {+ const list = map.get(entry.bucket);+ if (list) {+ list.push(entry);+ } else {+ map.set(entry.bucket, [entry]);+ }+ }+ return map;+ });++ const preBakedIndices = createLazyMemo<+ Record<BucketCombination, IndexEntry[]>+ >(() => {+ const indices = bucketIndices();+ return {+ all: processedData(),+ channels: mergeMultipleSortedIndices([+ indices.get('dm') ?? [],+ indices.get('channel') ?? [],+ ]),+ documents: mergeMultipleSortedIndices([+ indices.get('document') ?? [],+ indices.get('note') ?? [],+ indices.get('task') ?? [],+ indices.get('snippet') ?? [],+ indices.get('chat') ?? [],+ indices.get('project') ?? [],+ ]),+ };+ });++ // helper to get a pre-baked index list if the bucket combination matches+ const getPreBakedIndices = (buckets: Bucket[]): IndexEntry[] | undefined => {+ const baked = preBakedIndices();+ const bucketSet = new Set(buckets);++ for (const [name, combo] of Object.entries(BUCKET_COMBINATIONS)) {+ if (+ combo.length === buckets.length &&+ combo.every((b) => bucketSet.has(b))+ ) {+ return baked[name as BucketCombination];+ }+ }+ return undefined;+ };++ // API: useList+ // Optimized for common cases:+ // 1. No buckets = return pre-sorted all items list+ // 2. Single bucket = return pre-computed bucket list+ // 3. Pre-baked combination = return pre-merged list+ // 4. Other combinations = merge-sort bucket lists+ //+ // Items are resolved lazily+ const useList = ((+ ...args: Bucket[] | [QuickAccessListOptions]+ ): QuickAccessList => {+ const first = args[0];+ const options = typeof first === 'object' ? first : undefined;+ const buckets = options ? [...options.buckets] : (args as Bucket[]);+ const list = createLazyMemo(() => {+ if (options?.enabled?.() === false) return [];+ let indices: IndexEntry[];++ if (buckets.length === 0) {+ indices = preBakedIndices().all;+ } else if (buckets.length === 1) {+ // Single bucket = return pre-computed bucket list+ indices = bucketIndices().get(buckets[0]) ?? [];+ } else {+ // Check for pre-baked combination+ const preBaked = getPreBakedIndices(buckets);+ if (preBaked) {+ indices = preBaked;+ } else {+ // Fallback: merge-sort the requested bucket index lists+ const allIndices = bucketIndices();+ const indicesToMerge = buckets+ .map((b) => allIndices.get(b) ?? [])+ .filter((arr) => arr.length > 0);+ indices = mergeMultipleSortedIndices(indicesToMerge);+ }+ }++ return resolveEntries(indices);+ });+ return {+ items: list,+ totalCount: () => list().length,+ hasMore: () => false,+ isLoading: () => false,+ isLoadingMore: () => false,+ loadMore: async () => undefined,+ };+ }) as QuickAccessContextValue['useList'];++ // CRM companies are additive — they fold into the list when their query+ // resolves rather than gating quick access on a slower/failing CRM fetch.+ const isLoading = () => historyQuery.isLoading || channelsLoading();++ const refresh = () => {+ historyQuery.refetch();+ crmCompaniesQuery.refetch();+ snippetsQuery.refetch();+ };++ return {+ useList,+ usesRecordSelection: () => false,+ isLoading,+ refresh,+ getById,+ };+}diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsxindex 5be530371f..c38900764a 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessProvider.tsx@@ -1,727 +1,62 @@-import { itemToSafeName } from '@core/constant/allBlocks';-import { useChannelsContext } from '@core/context/channels';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import {- type IUser,- useAugmentUserWithDmActivity,- useContacts,- useIsConnectedSecondaryInbox,-} from '@core/user';-import type { DateValue } from '@core/util/date';-import type { ChannelEntity, CrmCompanyEntity, SnippetEntity } from '@entity';-import { queryReadyGate } from '@queries/gate';-import { type HistoryItem, useHistoryQuery } from '@queries/history/history';-import { useQuickAccessCrmCompaniesQuery } from '@queries/soup/quick-access-crm-companies';-import { useQuickAccessSnippetsQuery } from '@queries/soup/quick-access-snippets';-import { useRecentlyViewedSoupQuery } from '@queries/soup/recently-viewed';-import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';-import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';-import { formatDocumentName } from '@service-storage/util/filename';-import { createLazyMemo } from '@solid-primitives/memo';-import { toDate } from 'date-fns';-import type { Accessor } from 'solid-js';-import { createEffect, createSignal } from 'solid-js';-import { createAssertedContextProvider } from '../createContext';+ ENABLE_GRAPHQL_SOUP_FLAG,+ ENABLE_GRAPHQL_SOUP_OVERRIDE,+} from '@core/constant/featureFlags';+import { createMemo, type FlowComponent } from 'solid-js';+import { QuickAccessContextProvider } from './context';+import { createGraphqlQuickAccessValue } from './GraphqlQuickAccessSource';+import { createLegacyQuickAccessValue } from './LegacyQuickAccessSource';import type {Bucket,- BucketCombination,- EntityBucket,QuickAccessContextValue,- QuickAccessEntity,- QuickAccessItem,+ QuickAccessList,+ QuickAccessListOptions,} from './types';-import { BUCKET_COMBINATIONS } from './types';-/**- * index entry for sorted lists.- */-type IndexEntry = {- id: string;- bucket: Bucket;- sortTimestamp: number;-};--/**- * full item and version hash.- */-type CacheEntry = {- item: QuickAccessItem;- version: string;-};--function historyItemToEntity(item: HistoryItem): QuickAccessEntity {- const base = {- id: item.id,- name: item.name,- createdAt: item.createdAt,- updatedAt: item.updatedAt,- ownerId: item.ownerId,- };+export const QuickAccessProvider: FlowComponent = (props) => {+ const graphqlSoupFlag = useFeatureFlag(ENABLE_GRAPHQL_SOUP_FLAG, {+ enabledOverride: ENABLE_GRAPHQL_SOUP_OVERRIDE,+ });- switch (item.type) {- case 'chat':- return {- ...base,- type: 'chat',- } as QuickAccessEntity;-- case 'project':- return {- ...base,- type: 'project',- } as QuickAccessEntity;-- case 'document': {- const fileType = item.fileType ?? undefined;- const subType = item.subType ?? undefined;- const name = formatDocumentName(- itemToSafeName({- name: item.rawName ?? item.name,- type: item.type,- fileType,- subType,- }),- fileType,- {- fullyQualifiedBlockName: true,- }- );- return {- ...base,- name,- type: 'document',- fileType,- subType: item.subType,- } as QuickAccessEntity;- }-- default:- return {- ...base,- type: 'document',- } as QuickAccessEntity;- }-}+ const source = createMemo(() =>+ graphqlSoupFlag().enabled+ ? createGraphqlQuickAccessValue()+ : createLegacyQuickAccessValue()+ );-function channelToEntity(channel: ApiChannelWithLatest): ChannelEntity {- return {- type: 'channel',- id: channel.id,- name: channel.name ?? '',- ownerId: channel.owner_id ?? '',- channelType: channel.channel_type ?? 'public',- participantIds: channel.participants?.map((p) => p.user_id),- createdAt: channel.created_at,- updatedAt: channel.updated_at,- viewedAt: channel.viewed_at,- interactedAt: channel.interacted_at,+ const useList = ((+ ...args: Bucket[] | [QuickAccessListOptions]+ ): QuickAccessList => {+ const sourceList = createMemo(() => {+ const first = args[0];+ return typeof first === 'object'+ ? source().useList(first)+ : source().useList(...(args as Bucket[]));+ });+ return {+ items: () => sourceList().items(),+ totalCount: () => sourceList().totalCount(),+ hasMore: () => sourceList().hasMore(),+ isLoading: () => sourceList().isLoading(),+ isLoadingMore: () => sourceList().isLoadingMore(),+ loadMore: async () => {+ await sourceList().loadMore();+ },+ };+ }) as QuickAccessContextValue['useList'];++ const quickAccess: QuickAccessContextValue = {+ useList,+ usesRecordSelection: () => source().usesRecordSelection(),+ isLoading: () => source().isLoading(),+ refresh: () => source().refresh(),+ getById: (id) => source().getById(id),};-}--/**- * Determines the bucket for a history item.- */-function getBucketForHistoryItem(item: HistoryItem): EntityBucket {- switch (item.type) {- case 'chat':- return 'chat';- case 'project':- return 'project';- case 'document': {- if (item.subType?.type === 'task') return 'task';- if (item.subType?.type === 'snippet') return 'snippet';- if (item.fileType === 'md') return 'note';- return 'document';- }- default:- return 'document';- }-}--function getUserSearchText(user: IUser): string {- const { email, name } = user;- if (name === email) return `${email} | ${email}`;- return `${name} | ${email}`;-}--function getEntitySearchText(entity: QuickAccessEntity): string {- return entity.name;-}--function toTimestamp(value: DateValue | null | undefined): number {- if (value == null) return 0;- return toDate(value).getTime();-}--function getHistoryItemVersion(item: HistoryItem, viewedAt?: string): string {- return `${item.name}|${item.updatedAt}|${viewedAt}|${item.deletedAt}`;-}--function getChannelVersion(- channel: ApiChannelWithLatest,- viewedAt?: string-): string {- return `${channel.name}|${channel.updated_at}|${viewedAt}`;-}--function getUserVersion(user: IUser): string {- return `${user.name}|${user.email}|${user.lastInteraction}`;-}--function getCrmCompanySearchText(company: CrmCompanyEntity): string {- const domains = company.domains.map((d) => d.domain).join(' ');- return domains ? `${company.name} | ${domains}` : company.name;-}--function getCrmCompanyVersion(- company: CrmCompanyEntity,- viewedAt?: string-): string {- const domains = company.domains.map((d) => d.domain).join(',');- return `${company.name}|${domains}|${company.updatedAt}|${viewedAt}`;-}--function getSnippetVersion(snippet: SnippetEntity, viewedAt?: string): string {- return `${snippet.name}|${snippet.updatedAt}|${viewedAt}`;-}--/**- * Merge two *already* sorted index arrays into a single sorted array.- */-function mergeSortedIndices(a: IndexEntry[], b: IndexEntry[]): IndexEntry[] {- const result: IndexEntry[] = [];- let i = 0;- let j = 0;-- while (i < a.length && j < b.length) {- if (a[i].sortTimestamp >= b[j].sortTimestamp) {- result.push(a[i]);- i++;- } else {- result.push(b[j]);- j++;- }- }-- while (i < a.length) {- result.push(a[i]);- i++;- }- while (j < b.length) {- result.push(b[j]);- j++;- }-- return result;-}--/**- * Merge multiple *already* sorted index arrays into a single sorted array.- */-function mergeMultipleSortedIndices(arrays: IndexEntry[][]): IndexEntry[] {- if (arrays.length === 0) return [];- if (arrays.length === 1) return arrays[0];- return arrays.reduce((acc, arr) => mergeSortedIndices(acc, arr));-}--export const [QuickAccessProvider, useQuickAccess] =- createAssertedContextProvider(- 'QuickAccessContext',- (): QuickAccessContextValue => {- // queries- const historyQuery = useHistoryQuery();- const { channels, isLoading: channelsLoading } = useChannelsContext();- const contacts = useContacts();- const augmentUserWithDmActivity = useAugmentUserWithDmActivity();- const isConnectedSecondaryInbox = useIsConnectedSecondaryInbox();- const instructionsIdQuery = useInstructionsMdIdQuery();- const { query: crmCompaniesQuery, companies: crmCompaniesAccessor } =- useQuickAccessCrmCompaniesQuery();- const { query: snippetsQuery, snippets: snippetsAccessor } =- useQuickAccessSnippetsQuery();-- // globally hidden ids- const [hiddenIds, setHiddenIds] = createSignal<Set<string>>(new Set());-- const hideId = (id: string) => {- setHiddenIds((prev) => {- const next = new Set(prev);- next.add(id);- return next;- });- };-- // instructions.md effect- createEffect(() => {- const instructionsReady = queryReadyGate(instructionsIdQuery);- if (!instructionsReady) return;- const instructionsId = instructionsIdQuery.data;- if (!instructionsId) return;- hideId(instructionsId);- });-- // stable cache for transformed items- const itemCache = new Map<string, CacheEntry>();-- const recentlyViewedQuery = useRecentlyViewedSoupQuery();-- const soupViewedAtMap = createLazyMemo(() => {- const map = new Map<string, string>();- const data = recentlyViewedQuery.data;- if (!data) return map;- for (const item of data) {- if (item.viewedAt) map.set(item.id, item.viewedAt);- }- return map;- });-- const processedData = createLazyMemo(() => {- const viewedAtMap = soupViewedAtMap();- const seenIds = new Set<string>();- const allEntries: IndexEntry[] = [];-- const transformedItems: Array<{- id: string;- name: string;- type: string;- reason: string;- }> = [];-- // Process history items- const historyData = historyQuery.data ?? [];- const hidden = hiddenIds();- for (const item of historyData) {- if (item.deletedAt) continue;- if (hidden.has(item.id)) continue;- seenIds.add(item.id);-- const viewedAt = viewedAtMap.get(item.id);-- const version = getHistoryItemVersion(item, viewedAt);- const cached = itemCache.get(item.id);-- if (!cached || cached.version !== version) {- const reason = !cached- ? 'new'- : `changed (${cached.version} -> ${version})`;- transformedItems.push({- id: item.id,- name: item.name,- type: `history:${item.type}`,- reason,- });- const bucket = getBucketForHistoryItem(item);- const entity = {- ...historyItemToEntity(item),- viewedAt,- };- const viewedAtMs = toTimestamp(viewedAt);- const updatedAtMs = toTimestamp(item.updatedAt);- const sortTimestamp = viewedAtMs || updatedAtMs;-- const quickAccessItem: QuickAccessItem = {- kind: 'entity',- id: item.id,- bucket,- searchText: getEntitySearchText(entity),- sortTimestamp,- timestamps: {- viewedAt,- updatedAt: item.updatedAt,- createdAt: item.createdAt,- },- data: entity,- };-- itemCache.set(item.id, { item: quickAccessItem, version });- allEntries.push({ id: item.id, bucket, sortTimestamp });- } else {- allEntries.push({- id: item.id,- bucket: cached.item.bucket,- sortTimestamp: cached.item.sortTimestamp,- });- }- }- // Process channels- const channelData = channels();- for (const channel of channelData) {- seenIds.add(channel.id);-- const viewedAt =- viewedAtMap.get(channel.id) ?? channel.viewed_at ?? undefined;-- const version = getChannelVersion(channel, viewedAt);- const cached = itemCache.get(channel.id);-- if (!cached || cached.version !== version) {- const reason = !cached- ? 'new'- : `changed (${cached.version} -> ${version})`;- transformedItems.push({- id: channel.id,- name: channel.name ?? '',- type: `channel:${channel.channel_type}`,- reason,- });- const isDm = channel.channel_type === 'direct_message';- const bucket: Bucket = isDm ? 'dm' : 'channel';- const entity = {- ...channelToEntity(channel),- viewedAt,- };- const viewedAtMs = toTimestamp(viewedAt);- const updatedAtMs = toTimestamp(channel.updated_at);- const sortTimestamp = viewedAtMs || updatedAtMs;-- const quickAccessItem: QuickAccessItem = {- kind: 'entity',- id: channel.id,- bucket,- searchText: channel.name ?? '',- sortTimestamp,- timestamps: {- viewedAt,- updatedAt: channel.updated_at,- createdAt: channel.created_at,- },- data: entity,- };-- itemCache.set(channel.id, { item: quickAccessItem, version });- allEntries.push({ id: channel.id, bucket, sortTimestamp });- } else {- allEntries.push({- id: channel.id,- bucket: cached.item.bucket,- sortTimestamp: cached.item.sortTimestamp,- });- }- }-- // Process contacts (users)- const contactData = contacts();- for (const contact of contactData) {- if (isConnectedSecondaryInbox(contact.id)) continue;- const augmentedUser = augmentUserWithDmActivity(contact);- seenIds.add(augmentedUser.id);-- const version = getUserVersion(augmentedUser);- const cached = itemCache.get(augmentedUser.id);-- if (!cached || cached.version !== version) {- const reason = !cached- ? 'new'- : `changed (${cached.version} -> ${version})`;- transformedItems.push({- id: augmentedUser.id,- name: augmentedUser.name,- type: 'user',- reason,- });- const sortTimestamp = toTimestamp(augmentedUser.lastInteraction);-- const quickAccessItem: QuickAccessItem = {- kind: 'user',- id: augmentedUser.id,- bucket: 'person',- searchText: getUserSearchText(augmentedUser),- sortTimestamp,- timestamps: {- lastInteraction: augmentedUser.lastInteraction,- },- data: augmentedUser,- };-- itemCache.set(augmentedUser.id, { item: quickAccessItem, version });- allEntries.push({- id: augmentedUser.id,- bucket: 'person',- sortTimestamp,- });- } else {- allEntries.push({- id: augmentedUser.id,- bucket: cached.item.bucket,- sortTimestamp: cached.item.sortTimestamp,- });- }- }-- // Process CRM companies (live soup list, complements the- // recently-viewed feed which only has companies the user has- // opened). Sort timestamp prefers viewed_at; falls back to- // updated_at for unviewed companies — same shape as channels.- const crmCompanyData = crmCompaniesAccessor();- for (const company of crmCompanyData) {- if (hidden.has(company.id)) continue;- seenIds.add(company.id);-- const viewedAt =- viewedAtMap.get(company.id) ?? company.viewedAt ?? undefined;-- const version = getCrmCompanyVersion(- company,- viewedAt as string | undefined- );- const cached = itemCache.get(company.id);-- if (!cached || cached.version !== version) {- const reason = !cached- ? 'new'- : `changed (${cached.version} -> ${version})`;- transformedItems.push({- id: company.id,- name: company.name,- type: 'crm_company',- reason,- });- const entity: CrmCompanyEntity = {- ...company,- viewedAt: (viewedAt ?? company.viewedAt) as DateValue | null,- };- const viewedAtMs = toTimestamp(viewedAt);- const updatedAtMs = toTimestamp(company.updatedAt);- const sortTimestamp = viewedAtMs || updatedAtMs;-- const quickAccessItem: QuickAccessItem = {- kind: 'entity',- id: company.id,- bucket: 'crm_company',- searchText: getCrmCompanySearchText(entity),- sortTimestamp,- timestamps: {- viewedAt,- updatedAt: company.updatedAt,- createdAt: company.createdAt,- },- data: entity,- };-- itemCache.set(company.id, { item: quickAccessItem, version });- allEntries.push({- id: company.id,- bucket: 'crm_company',- sortTimestamp,- });- } else {- allEntries.push({- id: company.id,- bucket: cached.item.bucket,- sortTimestamp: cached.item.sortTimestamp,- });- }- }-- // Process snippets (live soup list, complements the history feed- // which only has snippets the user has opened). Widens the pool to- // team-shared snippets so the `;` menu lists snippets the user has- // never opened. History-fed entries win for snippets the user has- // already opened.- const snippetData = snippetsAccessor();- for (const snippet of snippetData) {- if (hidden.has(snippet.id)) continue;- if (seenIds.has(snippet.id)) continue;- seenIds.add(snippet.id);-- const viewedAt =- viewedAtMap.get(snippet.id) ?? snippet.viewedAt ?? undefined;-- const version = getSnippetVersion(- snippet,- viewedAt as string | undefined- );- const cached = itemCache.get(snippet.id);-- if (!cached || cached.version !== version) {- const reason = !cached- ? 'new'- : `changed (${cached.version} -> ${version})`;- transformedItems.push({- id: snippet.id,- name: snippet.name,- type: 'snippet',- reason,- });- const entity: SnippetEntity = {- ...snippet,- viewedAt: (viewedAt ?? snippet.viewedAt) as DateValue | null,- };- const viewedAtMs = toTimestamp(viewedAt);- const updatedAtMs = toTimestamp(snippet.updatedAt);- const sortTimestamp = viewedAtMs || updatedAtMs;-- const quickAccessItem: QuickAccessItem = {- kind: 'entity',- id: snippet.id,- bucket: 'snippet',- searchText: getEntitySearchText(entity),- sortTimestamp,- timestamps: {- viewedAt,- updatedAt: snippet.updatedAt,- createdAt: snippet.createdAt,- },- data: entity,- };-- itemCache.set(snippet.id, { item: quickAccessItem, version });- allEntries.push({- id: snippet.id,- bucket: 'snippet',- sortTimestamp,- });- } else {- allEntries.push({- id: snippet.id,- bucket: cached.item.bucket,- sortTimestamp: cached.item.sortTimestamp,- });- }- }-- // Clean up stale cache entries (items that no longer exist)- for (const id of itemCache.keys()) {- if (!seenIds.has(id)) {- itemCache.delete(id);- }- }-- // Sort all entries by timestamp descending- allEntries.sort((a, b) => b.sortTimestamp - a.sortTimestamp);-- // Deduplicate by id - keep the first occurrence (most recent timestamp)- const deduplicatedEntries: IndexEntry[] = [];- const dedupeSet = new Set<string>();- for (const entry of allEntries) {- if (!dedupeSet.has(entry.id)) {- dedupeSet.add(entry.id);- deduplicatedEntries.push(entry);- }- }-- return deduplicatedEntries;- });-- const getById = (id: string): QuickAccessItem | undefined => {- return itemCache.get(id)?.item;- };-- const resolveEntries = (entries: IndexEntry[]): QuickAccessItem[] => {- const result: QuickAccessItem[] = [];- for (const entry of entries) {- const cached = itemCache.get(entry.id);- if (cached) {- result.push(cached.item);- }- }- return result;- };-- // Pre-compute individual bucket index lists (each already sorted)- const bucketIndices = createLazyMemo<Map<Bucket, IndexEntry[]>>(() => {- const map = new Map<Bucket, IndexEntry[]>();- for (const entry of processedData()) {- const list = map.get(entry.bucket);- if (list) {- list.push(entry);- } else {- map.set(entry.bucket, [entry]);- }- }- return map;- });-- const preBakedIndices = createLazyMemo<- Record<BucketCombination, IndexEntry[]>- >(() => {- const indices = bucketIndices();- return {- all: processedData(),- channels: mergeMultipleSortedIndices([- indices.get('dm') ?? [],- indices.get('channel') ?? [],- ]),- documents: mergeMultipleSortedIndices([- indices.get('document') ?? [],- indices.get('note') ?? [],- indices.get('task') ?? [],- indices.get('snippet') ?? [],- indices.get('chat') ?? [],- indices.get('project') ?? [],- ]),- };- });-- // helper to get a pre-baked index list if the bucket combination matches- const getPreBakedIndices = (- buckets: Bucket[]- ): IndexEntry[] | undefined => {- const baked = preBakedIndices();- const bucketSet = new Set(buckets);-- for (const [name, combo] of Object.entries(BUCKET_COMBINATIONS)) {- if (- combo.length === buckets.length &&- combo.every((b) => bucketSet.has(b))- ) {- return baked[name as BucketCombination];- }- }- return undefined;- };-- // API: useList- // Optimized for common cases:- // 1. No buckets = return pre-sorted all items list- // 2. Single bucket = return pre-computed bucket list- // 3. Pre-baked combination = return pre-merged list- // 4. Other combinations = merge-sort bucket lists- //- // Items are resolved lazily- const useList = <B extends Bucket>(...buckets: B[]): Accessor<any> => {- return createLazyMemo(() => {- let indices: IndexEntry[];-- if (buckets.length === 0) {- indices = preBakedIndices().all;- } else if (buckets.length === 1) {- // Single bucket = return pre-computed bucket list- indices = bucketIndices().get(buckets[0]) ?? [];- } else {- // Check for pre-baked combination- const preBaked = getPreBakedIndices(buckets);- if (preBaked) {- indices = preBaked;- } else {- // Fallback: merge-sort the requested bucket index lists- const allIndices = bucketIndices();- const indicesToMerge = buckets- .map((b) => allIndices.get(b) ?? [])- .filter((arr) => arr.length > 0);- indices = mergeMultipleSortedIndices(indicesToMerge);- }- }-- return resolveEntries(indices);- });- };-- // CRM companies are additive — they fold into the list when their query- // resolves rather than gating quick access on a slower/failing CRM fetch.- const isLoading = () => historyQuery.isLoading || channelsLoading();-- const refresh = () => {- historyQuery.refetch();- crmCompaniesQuery.refetch();- snippetsQuery.refetch();- };-- return {- useList,- isLoading,- refresh,- getById,- };- }+ return (+ <QuickAccessContextProvider value={quickAccess}>+ {props.children}+ </QuickAccessContextProvider>);+};diff --git a/apps/web/src/lib/core/context/quickAccess/context.ts b/apps/web/src/lib/core/context/quickAccess/context.tsnew file mode 100644index 0000000000..8edf5a9422--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/context.ts@@ -0,0 +1,16 @@+import { createContext, useContext } from 'solid-js';+import type { QuickAccessContextValue } from './types';++const QuickAccessContext = createContext<QuickAccessContextValue>();++export const QuickAccessContextProvider = QuickAccessContext.Provider;++export function useQuickAccess(): QuickAccessContextValue {+ const value = useContext(QuickAccessContext);+ if (!value) {+ throw new Error(+ 'QuickAccessContext must be used within <QuickAccessContextProvider />'+ );+ }+ return value;+}diff --git a/apps/web/src/lib/core/context/quickAccess/debug/QuickAccessAll.tsx b/apps/web/src/lib/core/context/quickAccess/debug/QuickAccessAll.tsxindex 8516cb7284..6edb7f064e 100644--- a/apps/web/src/lib/core/context/quickAccess/debug/QuickAccessAll.tsx+++ b/apps/web/src/lib/core/context/quickAccess/debug/QuickAccessAll.tsx@@ -2,13 +2,13 @@ import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeimport { StaticSplitLabel } from '@components/app/split-layout/components/SplitLabel';import { InlineEntity } from '@entity';import { For, Match, Switch } from 'solid-js';-import { useQuickAccess } from '../QuickAccessProvider';+import { useQuickAccess } from '../context';export default function QuickAccessAll() {const { useList } = useQuickAccess();// @example const entities = useList('task', 'note', 'document', 'project');- const entities = useList();+ const entities = useList().items;return (<>diff --git a/apps/web/src/lib/core/context/quickAccess/entity-search.ts b/apps/web/src/lib/core/context/quickAccess/entity-search.tsnew file mode 100644index 0000000000..f12249142e--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/entity-search.ts@@ -0,0 +1,18 @@+import { createFreshSearch } from '@core/util/freshSort';+import type { EntityItem } from './types';++const entitySearch = createFreshSearch<EntityItem>({+ config: { useViewedAt: true },+ getName: (item) => item.searchText,+ isChannelItem: (item) => item.bucket === 'channel',+ getTimestamp: (item) => item.timestamps,+});++/** Fuzzy-ranks entity candidates using the existing mentions semantics. */+export function searchQuickAccessEntities(+ items: EntityItem[],+ query: string+): EntityItem[] {+ if (!query.trim()) return items;+ return entitySearch(items, query).map(({ item }) => item);+}diff --git a/apps/web/src/lib/core/context/quickAccess/graphql-items.ts b/apps/web/src/lib/core/context/quickAccess/graphql-items.tsnew file mode 100644index 0000000000..a8dce44426--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/graphql-items.ts@@ -0,0 +1,97 @@+import type { IUser } from '@core/user';+import type { DateValue } from '@core/util/date';+import type { CrmCompanyEntity, EntityData } from '@entity';+import { formatDocumentName } from '@service-storage/util/filename';+import { toDate } from 'date-fns';+import type { EntityBucket, EntityItem, UserItem } from './types';++export function getGraphqlEntityBucket(+ entity: EntityData+): EntityBucket | undefined {+ switch (entity.type) {+ case 'document':+ if (entity.subType?.type === 'task') return 'task';+ if (entity.subType?.type === 'snippet') return 'snippet';+ return entity.fileType === 'md' ? 'note' : 'document';+ case 'channel':+ return entity.channelType === 'direct_message' ? 'dm' : 'channel';+ case 'chat':+ return 'chat';+ case 'project':+ return 'project';+ case 'email':+ return 'email';+ case 'crm_company':+ return 'crm_company';+ default:+ return undefined;+ }+}++function toTimestamp(value: DateValue | null | undefined): number {+ if (value == null) return 0;+ return toDate(value).getTime();+}++function getCrmCompanySearchText(company: CrmCompanyEntity): string {+ const domains = company.domains.map((domain) => domain.domain).join(' ');+ return domains ? `${company.name} | ${domains}` : company.name;+}++function getEntitySearchText(entity: EntityData): string {+ return entity.type === 'crm_company'+ ? getCrmCompanySearchText(entity)+ : entity.name;+}++export function graphqlEntityToQuickAccessItem(+ entity: EntityData+): EntityItem | undefined {+ if ('deletedAt' in entity && entity.deletedAt) return undefined;++ const bucket = getGraphqlEntityBucket(entity);+ if (!bucket) return undefined;++ const data: EntityData =+ entity.type === 'document'+ ? {+ ...entity,+ name: formatDocumentName(entity.name, entity.fileType, {+ fullyQualifiedBlockName: true,+ }),+ }+ : entity;+ const sortValue =+ data.viewedAt ?? data.sortTs ?? data.updatedAt ?? data.createdAt;++ return {+ kind: 'entity',+ id: data.id,+ bucket,+ searchText: getEntitySearchText(data),+ sortTimestamp: toTimestamp(sortValue),+ timestamps: {+ viewedAt: data.viewedAt,+ updatedAt: data.updatedAt,+ createdAt: data.createdAt,+ },+ data,+ };+}++export function userToQuickAccessItem(user: IUser): UserItem {+ const searchText =+ user.name === user.email+ ? `${user.email} | ${user.email}`+ : `${user.name} | ${user.email}`;++ return {+ kind: 'user',+ id: user.id,+ bucket: 'person',+ searchText,+ sortTimestamp: toTimestamp(user.lastInteraction),+ timestamps: { lastInteraction: user.lastInteraction },+ data: user,+ };+}diff --git a/apps/web/src/lib/core/context/quickAccess/index.ts b/apps/web/src/lib/core/context/quickAccess/index.tsindex 319d4ba96c..5af601b868 100644--- a/apps/web/src/lib/core/context/quickAccess/index.ts+++ b/apps/web/src/lib/core/context/quickAccess/index.ts@@ -1,9 +1,11 @@-export { QuickAccessProvider, useQuickAccess } from './QuickAccessProvider';+export { useQuickAccess } from './context';+export { QuickAccessProvider } from './QuickAccessProvider';export type {Bucket,EntityBucket,EntityItem,QuickAccessItem,+ QuickAccessList,UserItem,} from './types';export { exclude } from './types';diff --git a/apps/web/src/lib/core/context/quickAccess/record-selection-items.test.ts b/apps/web/src/lib/core/context/quickAccess/record-selection-items.test.tsnew file mode 100644index 0000000000..94dfb93ae8--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/record-selection-items.test.ts@@ -0,0 +1,58 @@+import type { CacheHost } from '@graphql-cache/index';+import type { SoupItemFieldsFragment } from '@service-storage/graphql/generated/graphql';+import { describe, expect, it, vi } from 'vitest';+import { readCachedQuickAccessRecords } from './record-selection-items';++const item = (id: string) => ({ id }) as SoupItemFieldsFragment;++describe('readCachedQuickAccessRecords', () => {+ it('loads every record page with exclusive cursors', async () => {+ const readRecords = vi+ .fn()+ .mockResolvedValueOnce({+ records: [item('a'), item('b')],+ nextCursor: 'cursor-b',+ })+ .mockResolvedValueOnce({ records: [item('c')], nextCursor: null });++ await expect(+ readCachedQuickAccessRecords({ readRecords } as Pick<+ CacheHost,+ 'readRecords'+ >)+ ).resolves.toEqual([item('a'), item('b'), item('c')]);+ expect(readRecords).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ document: expect.stringContaining('fragment QuickAccessSoupItemFields'),+ fragmentName: 'QuickAccessSoupItemFields',+ })+ );+ expect(readRecords.mock.calls[0]?.[0].document).toContain(+ 'GraphqlSoupEmailThread'+ );+ expect(readRecords.mock.calls[0]?.[0].document).toContain(+ 'attachmentCount'+ );+ expect(readRecords.mock.calls[0]?.[0].document).toContain(+ 'participantCount'+ );+ expect(readRecords).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ cursor: 'cursor-b', limit: 500 })+ );+ });++ it('rejects a repeated host cursor', async () => {+ const readRecords = vi.fn().mockResolvedValue({+ records: [],+ nextCursor: 'same-cursor',+ });+ await expect(+ readCachedQuickAccessRecords({ readRecords } as Pick<+ CacheHost,+ 'readRecords'+ >)+ ).rejects.toThrow('repeated cursor');+ });+});diff --git a/apps/web/src/lib/core/context/quickAccess/record-selection-items.ts b/apps/web/src/lib/core/context/quickAccess/record-selection-items.tsnew file mode 100644index 0000000000..0fa8093f3f--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/record-selection-items.ts@@ -0,0 +1,66 @@+import {+ type CacheHost,+ MAX_RECORD_SELECTION_PAGE_SIZE,+ type RecordSelection,+ readRecords,+ selectRecords,+} from '@graphql-cache/index';+import {+ QuickAccessSoupItemFieldsFragmentDoc,+ type SoupItemFieldsFragment,+} from '@service-storage/graphql/generated/graphql';+import { createQuery, keepPreviousData } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';++const soupItemSelection = selectRecords(+ QuickAccessSoupItemFieldsFragmentDoc+) as RecordSelection<SoupItemFieldsFragment>;++/** Shared prefix for cache-backed Quick Access record reads. */+export const QUICK_ACCESS_RECORD_SELECTION_QUERY_KEY = [+ 'quick-access',+ 'record-selection',+] as const;++/** Loads complete cached non-email Soup item records. */+export async function readCachedQuickAccessRecords(+ cacheHost: Pick<CacheHost, 'readRecords'>+): Promise<SoupItemFieldsFragment[]> {+ const records: SoupItemFieldsFragment[] = [];+ let cursor: string | undefined;+ const seenCursors = new Set<string>();+ do {+ const page = await readRecords(cacheHost, soupItemSelection, {+ cursor,+ limit: MAX_RECORD_SELECTION_PAGE_SIZE,+ });+ records.push(...page.records);+ cursor = page.nextCursor ?? undefined;+ if (cursor) {+ if (seenCursors.has(cursor)) {+ throw new Error('cache record selection returned a repeated cursor');+ }+ seenCursors.add(cursor);+ }+ } while (cursor);+ return records;+}++/** Creates the shared query that materializes cached Soup item records. */+export function createQuickAccessRecordSelectionQuery(options: {+ cacheHost: Accessor<CacheHost | undefined>;+}) {+ return createQuery<SoupItemFieldsFragment[]>(() => {+ const cacheHost = options.cacheHost();+ return {+ queryKey: QUICK_ACCESS_RECORD_SELECTION_QUERY_KEY,+ queryFn: () =>+ cacheHost+ ? readCachedQuickAccessRecords(cacheHost)+ : Promise.resolve([]),+ enabled: cacheHost !== undefined,+ placeholderData: keepPreviousData,+ staleTime: Infinity,+ };+ });+}diff --git a/apps/web/src/lib/core/context/quickAccess/record-selection-list.test.ts b/apps/web/src/lib/core/context/quickAccess/record-selection-list.test.tsnew file mode 100644index 0000000000..119ad174c4--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/record-selection-list.test.ts@@ -0,0 +1,131 @@+import type { EntityData } from '@entity';+import { createRoot, createSignal } from 'solid-js';+import { describe, expect, it } from 'vitest';+import { createRecordSelectionQuickAccessItems } from './record-selection-list';+import type { EntityBucket, EntityItem, QuickAccessItem } from './types';++function entity(+ id: string,+ bucket: EntityBucket,+ searchText: string,+ sortTimestamp: number+): EntityItem {+ return {+ kind: 'entity',+ id,+ bucket,+ searchText,+ sortTimestamp,+ timestamps: {},+ data: {+ id,+ name: searchText,+ ownerId: 'user-1',+ type: bucket === 'email' ? 'email' : 'document',+ } as EntityData,+ };+}++function runInRoot(run: () => Promise<void>): Promise<void> {+ return new Promise((resolve, reject) => {+ createRoot((dispose) => {+ void run().then(+ () => {+ dispose();+ resolve();+ },+ (error) => {+ dispose();+ reject(error);+ }+ );+ });+ });+}++describe('createRecordSelectionQuickAccessItems', () => {+ it('filters, sorts, searches, counts, and paginates locally', async () => {+ await runInRoot(async () => {+ const [searchTerm, setSearchTerm] = createSignal('');+ const selected = [+ entity('a', 'document', 'Alpha', 20),+ entity('b', 'email', 'Bravo', 30),+ entity('c', 'document', 'Charlie', 10),+ entity('snippet', 'snippet', 'Snippet', 40),+ ];+ const local: QuickAccessItem[] = [+ entity('a', 'document', 'Alpha local', 25),+ {+ kind: 'user',+ id: 'person',+ bucket: 'person',+ searchText: 'Taylor | [email protected]',+ sortTimestamp: 5,+ timestamps: {},+ data: {+ id: 'person',+ name: 'Taylor',+ email: '[email protected]',+ },+ },+ ];+ const list = createRecordSelectionQuickAccessItems({+ buckets: [],+ searchTerm,+ enabled: () => true,+ pageSize: 2,+ selectedItems: () => selected,+ localItems: () => local,+ instructionsId: () => undefined,+ snippetsEnabled: () => false,+ crmEnabled: () => true,+ onItems: () => undefined,+ });++ expect(list.items().map((item) => item.id)).toEqual(['b', 'a']);+ expect(list.totalCount()).toBe(4);+ expect(list.hasMore()).toBe(true);+ await list.loadMore();+ expect(list.items().map((item) => item.id)).toEqual([+ 'b',+ 'a',+ 'c',+ 'person',+ ]);+ expect(list.hasMore()).toBe(false);++ setSearchTerm('charlie');+ await Promise.resolve();+ expect(list.items()[0]?.id).toBe('c');+ expect(list.totalCount()).toBe(2); // matching entity plus local user+ expect(list.hasMore()).toBe(false);+ });+ });++ it('applies bucket filtering before counts and visible slicing', async () => {+ await runInRoot(async () => {+ const list = createRecordSelectionQuickAccessItems({+ buckets: ['document'],+ searchTerm: () => '',+ enabled: () => true,+ pageSize: 1,+ selectedItems: () => [+ entity('doc-a', 'document', 'A', 1),+ entity('email-a', 'email', 'Email', 2),+ entity('doc-b', 'document', 'B', 3),+ ],+ localItems: () => [],+ instructionsId: () => undefined,+ snippetsEnabled: () => true,+ crmEnabled: () => true,+ onItems: () => undefined,+ });++ expect(list.items().map((item) => item.id)).toEqual(['doc-b']);+ expect(list.totalCount()).toBe(2);+ expect(list.hasMore()).toBe(true);+ await list.loadMore();+ expect(list.items().map((item) => item.id)).toEqual(['doc-b', 'doc-a']);+ });+ });+});diff --git a/apps/web/src/lib/core/context/quickAccess/record-selection-list.ts b/apps/web/src/lib/core/context/quickAccess/record-selection-list.tsnew file mode 100644index 0000000000..eceafb10b5--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/record-selection-list.ts@@ -0,0 +1,133 @@+import {+ type Accessor,+ createComputed,+ createMemo,+ createSignal,+} from 'solid-js';+import { searchQuickAccessEntities } from './entity-search';+import type {+ Bucket,+ EntityBucket,+ EntityItem,+ QuickAccessItem,+} from './types';++const ALL_ENTITY_BUCKETS: EntityBucket[] = [+ 'channel',+ 'dm',+ 'document',+ 'note',+ 'task',+ 'snippet',+ 'chat',+ 'project',+ 'email',+ 'crm_company',+];++function addItem(+ items: Map<string, QuickAccessItem>,+ item: QuickAccessItem,+ replaceOnTie = false+) {+ const current = items.get(item.id);+ if (+ !current ||+ item.sortTimestamp > current.sortTimestamp ||+ (replaceOnTie && item.sortTimestamp === current.sortTimestamp)+ ) {+ items.set(item.id, item);+ }+}++/** Creates a locally filtered and paginated Quick Access record list. */+export function createRecordSelectionQuickAccessItems(options: {+ buckets: Bucket[];+ searchTerm: Accessor<string>;+ enabled: Accessor<boolean>;+ pageSize: number;+ selectedItems: Accessor<EntityItem[]>;+ localItems: Accessor<QuickAccessItem[]>;+ instructionsId: Accessor<string | undefined>;+ snippetsEnabled: Accessor<boolean>;+ crmEnabled: Accessor<boolean>;+ onItems: (items: QuickAccessItem[]) => void;+}) {+ const entityBuckets = createMemo(() =>+ (options.buckets.length > 0 ? options.buckets : ALL_ENTITY_BUCKETS).filter(+ (bucket): bucket is EntityBucket =>+ bucket !== 'person' &&+ (bucket !== 'snippet' || options.snippetsEnabled()) &&+ (bucket !== 'crm_company' || options.crmEnabled())+ )+ );+ const [visibleLimit, setVisibleLimit] = createSignal(options.pageSize);++ createComputed(() => {+ options.searchTerm();+ options.enabled();+ entityBuckets();+ setVisibleLimit(options.pageSize);+ });++ const allItems = createMemo<QuickAccessItem[]>(() => {+ if (!options.enabled()) return [];+ const requested =+ options.buckets.length > 0 ? new Set(options.buckets) : undefined;+ const itemsById = new Map<string, QuickAccessItem>();+ const addVisibleItem = (item: QuickAccessItem, replaceOnTie = false) => {+ if (requested && !requested.has(item.bucket)) return;+ if (item.bucket === 'note' && item.id === options.instructionsId())+ return;+ if (item.bucket === 'snippet' && !options.snippetsEnabled()) return;+ if (item.bucket === 'crm_company' && !options.crmEnabled()) return;+ addItem(itemsById, item, replaceOnTie);+ };++ for (const item of options.selectedItems()) addVisibleItem(item);+ for (const item of options.localItems()) {+ addVisibleItem(item, item.kind === 'entity');+ }++ const values = [...itemsById.values()];+ const term = options.searchTerm();+ const result = term+ ? [+ ...searchQuickAccessEntities(+ values.filter((item): item is EntityItem => item.kind === 'entity'),+ term+ ),+ ...values+ .filter((item) => item.kind === 'user')+ .sort(+ (left, right) =>+ right.sortTimestamp - left.sortTimestamp ||+ left.id.localeCompare(right.id)+ ),+ ]+ : values.sort(+ (left, right) =>+ right.sortTimestamp - left.sortTimestamp ||+ left.id.localeCompare(right.id)+ );++ options.onItems(result);+ return result;+ });++ const items = createMemo(() => allItems().slice(0, visibleLimit()));+ const hasMore = createMemo(() => visibleLimit() < allItems().length);++ return {+ items,+ totalCount: () => allItems().length,+ hasMore,+ isLoadingMore: () => false,+ loadMore: async () => {+ setVisibleLimit((limit) =>+ Math.min(limit + options.pageSize, allItems().length)+ );+ },+ entityBuckets,+ };+}diff --git a/apps/web/src/lib/core/context/quickAccess/types.ts b/apps/web/src/lib/core/context/quickAccess/types.tsindex ca2c5e3fbf..74c140f93c 100644--- a/apps/web/src/lib/core/context/quickAccess/types.ts+++ b/apps/web/src/lib/core/context/quickAccess/types.ts@@ -131,22 +131,52 @@ export type ItemsForBuckets<Buckets extends Bucket[]> = Buckets extends [? ItemForBucket<First> | ItemsForBuckets<Rest>: never;+export type QuickAccessList<T extends QuickAccessItem = QuickAccessItem> = {+ items: Accessor<T[]>;+ /** Total matching items, including pages not loaded yet. */+ totalCount: Accessor<number>;+ hasMore: Accessor<boolean>;+ isLoading: Accessor<boolean>;+ isLoadingMore: Accessor<boolean>;+ loadMore: () => Promise<void>;+};++export type QuickAccessListOptions<+ B extends readonly Bucket[] = readonly Bucket[],+> = {+ buckets: B;+ /** Search only this list; omitted values retain ordinary browse ordering. */+ searchTerm?: Accessor<string>;+ /** Disable this list without affecting other Quick Access consumers. */+ enabled?: Accessor<boolean>;+};+export type QuickAccessContextValue = {/*** Get items from specific buckets, cached and reactive.- * Returns all items if no buckets specified.+ * Returns all items if no buckets specified. Passing options scopes search+ * to that list without affecting other Quick Access consumers.** @example- * const channels = quickAccess.useList('channel', 'dm');- * const people = quickAccess.useList('person');- * const everything = quickAccess.useList();+ * const channels = quickAccess.useList('channel', 'dm').items;+ * const people = quickAccess.useList('person').items;+ * const results = quickAccess.useList({+ * buckets: ['document'],+ * searchTerm,+ * }).items;*/useList: {- (): Accessor<QuickAccessItem[]>;- <B extends Bucket>(...buckets: [B]): Accessor<ItemForBucket<B>[]>;- <B extends Bucket[]>(...buckets: B): Accessor<ItemsForBuckets<B>[]>;+ (): QuickAccessList;+ <B extends Bucket>(...buckets: [B]): QuickAccessList<ItemForBucket<B>>;+ <B extends Bucket[]>(...buckets: B): QuickAccessList<ItemsForBuckets<B>>;+ <const B extends readonly Bucket[]>(+ options: QuickAccessListOptions<B>+ ): QuickAccessList<ItemForBucket<B[number]>>;};+ /** Whether this source reads normalized records through cache fragments. */+ usesRecordSelection: Accessor<boolean>;+/*** Whether any data sources are still loading.*/diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.tsindex 04ae3375b6..98c858dc7f 100644--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts@@ -99,6 +99,9 @@ function makeFakeHost(): FakeHost {});return readResult;},+ async readRecords() {+ return { records: [], nextCursor: null };+ },async writeQuery(args): Promise<WriteResult> {host.writes.push({opKey: args.opKey,@@ -175,6 +178,9 @@ function makeFakeHost(): FakeHost {subscribers.add(cb);return () => subscribers.delete(cb);},+ onCacheChanged() {+ return () => undefined;+ },dispose() {},};return host;diff --git a/apps/web/src/lib/graphql-cache/exchange/record-selection.test.ts b/apps/web/src/lib/graphql-cache/exchange/record-selection.test.tsnew file mode 100644index 0000000000..b2cf207c32--- /dev/null+++ b/apps/web/src/lib/graphql-cache/exchange/record-selection.test.ts@@ -0,0 +1,52 @@+import {+ SoupDocument,+ type SoupItemFieldsFragment,+ SoupItemFieldsFragmentDoc,+} from '@service-storage/graphql/generated/graphql';+import { describe, expect, expectTypeOf, it, vi } from 'vitest';+import type { CacheHost } from '../host/types';+import { readRecords, selectRecords } from './record-selection';++describe('typed record selection', () => {+ it('extracts the root fragment and infers generated result types', async () => {+ const readRecordsHost = vi.fn().mockResolvedValue({+ records: [{ id: 'item-1' }],+ nextCursor: 'cursor-1',+ });+ const host = { readRecords: readRecordsHost } as unknown as CacheHost;+ const selection = selectRecords(SoupItemFieldsFragmentDoc);+ const page = await readRecords(host, selection, { limit: 25 });++ expect(readRecordsHost).toHaveBeenCalledWith({+ document: expect.stringContaining('fragment SoupItemFields'),+ fragmentName: 'SoupItemFields',+ cursor: undefined,+ limit: 25,+ });+ expect(page.nextCursor).toBe('cursor-1');+ expectTypeOf(page.records).toEqualTypeOf<SoupItemFieldsFragment[]>();+ // @ts-expect-error Generated fragment records have no arbitrary field.+ page.records[0]?.missing;+ });++ it('rejects operation documents and malformed host pages', async () => {+ expect(() => selectRecords(SoupDocument)).toThrow(+ 'requires a fragment-only document'+ );++ const selection = selectRecords(SoupItemFieldsFragmentDoc);+ for (const result of [+ null,+ { records: null, nextCursor: null },+ { records: [null], nextCursor: null },+ { records: [], nextCursor: 42 },+ ]) {+ const host = {+ readRecords: async () => result,+ } as unknown as CacheHost;+ await expect(readRecords(host, selection, { limit: 1 })).rejects.toThrow(+ 'invalid cache'+ );+ }+ });+});diff --git a/apps/web/src/lib/graphql-cache/exchange/record-selection.ts b/apps/web/src/lib/graphql-cache/exchange/record-selection.tsnew file mode 100644index 0000000000..638306b7d4--- /dev/null+++ b/apps/web/src/lib/graphql-cache/exchange/record-selection.ts@@ -0,0 +1,83 @@+import type { TypedDocumentNode } from '@graphql-typed-document-node/core';+import { stringifyDocument } from '@urql/core';+import { type FragmentDefinitionNode, Kind } from 'graphql';+import type { CacheHost } from '../host/types';+import type { RecordCursor } from '../protocol';++const recordResultType: unique symbol = Symbol('recordResultType');++type RecordSelectionState = {+ readonly document: string;+ readonly fragmentName: string;+};++/** A generated fragment prepared for normalized-record selection. */+export type RecordSelection<TResult> = RecordSelectionState & {+ /** Phantom generated fragment result type. */+ readonly [recordResultType]: TResult;+};++/** One typed page of complete selected records. */+export type SelectedRecordPage<TResult> = {+ records: TResult[];+ nextCursor: RecordCursor | null;+};++/** Prepares a generated, fragment-only document for record selection. */+export function selectRecords<TResult, TVariables>(+ document: TypedDocumentNode<TResult, TVariables>+): RecordSelection<TResult> {+ if (+ document.definitions.some(+ (definition) => definition.kind === Kind.OPERATION_DEFINITION+ )+ ) {+ throw new Error('cache record selection requires a fragment-only document');+ }+ const fragment = document.definitions.find(+ (definition): definition is FragmentDefinitionNode =>+ definition.kind === Kind.FRAGMENT_DEFINITION+ );+ if (!fragment?.name?.value) {+ throw new Error('cache record selection requires a named fragment');+ }+ return {+ document: stringifyDocument(document),+ fragmentName: fragment.name.value,+ } as RecordSelection<TResult>;+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function validatePage(value: unknown): SelectedRecordPage<unknown> {+ if (!isRecord(value) || !Array.isArray(value.records)) {+ throw new Error('invalid cache record-selection page');+ }+ if (value.nextCursor !== null && typeof value.nextCursor !== 'string') {+ throw new Error('invalid cache record-selection cursor');+ }+ if (value.records.some((record) => !isRecord(record))) {+ throw new Error('invalid cache selected record');+ }+ return {+ records: value.records,+ nextCursor: value.nextCursor,+ };+}++/** Reads one typed page from a cache host using a prepared fragment. */+export async function readRecords<TResult>(+ host: Pick<CacheHost, 'readRecords'>,+ selection: RecordSelection<TResult>,+ options: { cursor?: RecordCursor; limit: number }+): Promise<SelectedRecordPage<TResult>> {+ const page: unknown = await host.readRecords({+ document: selection.document,+ fragmentName: selection.fragmentName,+ cursor: options.cursor,+ limit: options.limit,+ });+ return validatePage(page) as SelectedRecordPage<TResult>;+}diff --git a/apps/web/src/lib/graphql-cache/host/noop-host.ts b/apps/web/src/lib/graphql-cache/host/noop-host.tsindex 12797c0a14..c39d8a90f5 100644--- a/apps/web/src/lib/graphql-cache/host/noop-host.ts+++ b/apps/web/src/lib/graphql-cache/host/noop-host.ts@@ -1,7 +1,9 @@-import type {- OptimisticWriteResult,- ReadResult,- WriteResult,+import {+ type OptimisticWriteResult,+ type ReadRecordsArgs,+ type ReadResult,+ validateRecordSelectionLimit,+ type WriteResult,} from '../protocol';import type { CacheHost } from './types';@@ -25,6 +27,10 @@ export function createNoopCacheHost(reason: string): CacheHost {async readQuery(): Promise<ReadResult> {return { kind: 'miss' };},+ async readRecords(args: ReadRecordsArgs) {+ validateRecordSelectionLimit(args.limit);+ return { records: [], nextCursor: null };+ },async writeQuery(): Promise<WriteResult> {return emptyWriteResult();},@@ -52,6 +58,9 @@ export function createNoopCacheHost(reason: string): CacheHost {onOpsAffected() {return () => undefined;},+ onCacheChanged() {+ return () => undefined;+ },dispose() {},};}diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.tsindex 9f930c2705..44c1085931 100644--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts@@ -8,19 +8,18 @@ vi.mock('@tauri-apps/api/event', () => ({ listen: listenMock }));import { createTauriCacheHost } from './tauri-host';-type OpsAffectedPayload = { opIds: string[]; keys: string[] };-type EventCallback = (event: { payload: OpsAffectedPayload }) => void;+type EventCallback = (event: { payload: Record<string, unknown> }) => void;describe('createTauriCacheHost', () => {- let eventCallback: EventCallback | undefined;+ let eventCallbacks: Map<string, EventCallback>;const unlisten = vi.fn();beforeEach(() => {vi.clearAllMocks();- eventCallback = undefined;+ eventCallbacks = new Map();invokeMock.mockResolvedValue(null);- listenMock.mockImplementation((_event: string, cb: EventCallback) => {- eventCallback = cb;+ listenMock.mockImplementation((event: string, cb: EventCallback) => {+ eventCallbacks.set(event, cb);return Promise.resolve(unlisten);});});@@ -48,6 +47,52 @@ describe('createTauriCacheHost', () => {});});+ it('reports asynchronous native initialization failures', async () => {+ const onInitializationError = vi.fn();+ invokeMock.mockImplementation((command: string) =>+ command === 'graphql_cache_init'+ ? Promise.reject(new Error('init failed'))+ : Promise.resolve(null)+ );++ const host = createTauriCacheHost({+ scope: 'scope-1',+ onInitializationError,+ });++ await vi.waitFor(() =>+ expect(onInitializationError).toHaveBeenCalledOnce()+ );+ expect(onInitializationError).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'init failed' })+ );+ host.dispose();+ });++ it('reads selected records with fragment and cursor arguments', async () => {+ const page = { records: [], nextCursor: null };+ invokeMock.mockImplementation((command: string) =>+ Promise.resolve(command === 'graphql_cache_read_records' ? page : null)+ );+ const host = createTauriCacheHost({ scope: 'scope-1' });+ const cursor = 'cursor-1';++ await expect(+ host.readRecords({+ document: 'fragment Item on GraphqlSoupItem { id }',+ fragmentName: 'Item',+ cursor,+ limit: 25,+ })+ ).resolves.toEqual(page);+ expect(invokeMock).toHaveBeenCalledWith('graphql_cache_read_records', {+ document: 'fragment Item on GraphqlSoupItem { id }',+ fragmentName: 'Item',+ cursor,+ limit: 25,+ });+ });+it('sends writes with origin op id and identity', async () => {const host = createTauriCacheHost({ scope: 'scope-1' });const writeResult = { changed: ['A:1'], affectedOps: [], reset: false };@@ -179,7 +224,7 @@ describe('createTauriCacheHost', () => {expect.any(Function));- eventCallback?.({+ eventCallbacks.get('graphql-cache://ops-affected')?.({payload: {opIds: [`${host.clientId}:5`, 'other-client:9', `${host.clientId}:8`],keys: ['A:1'],@@ -188,12 +233,22 @@ describe('createTauriCacheHost', () => {expect(seen).toEqual([[5, 8]]);// No delivery when nothing matches this client.- eventCallback?.({+ eventCallbacks.get('graphql-cache://ops-affected')?.({payload: { opIds: ['other-client:9'], keys: ['A:1'] },});expect(seen).toEqual([[5, 8]]);});+ it('delivers cache change notifications', async () => {+ const host = createTauriCacheHost({ scope: 'scope-1' });+ let calls = 0;+ host.onCacheChanged(() => calls++);+ await Promise.resolve();++ eventCallbacks.get('graphql-cache://cache-changed')?.({ payload: {} });+ expect(calls).toBe(1);+ });+it('normalizes string command errors to Error rejections', async () => {const host = createTauriCacheHost({ scope: 'scope-1' });invokeMock.mockImplementation((command: string) =>diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.tsindex 64849381d5..c655b3f135 100644--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts@@ -9,13 +9,16 @@import { invoke } from '@tauri-apps/api/core';import { listen, type UnlistenFn } from '@tauri-apps/api/event';-import type {- CachedQueryInstanceWire,- ClaimedMutation,- MutationClaim,- OptimisticWriteResult,- ReadResult,- WriteResult,+import {+ type CachedQueryInstanceWire,+ type ClaimedMutation,+ type MutationClaim,+ type OptimisticWriteResult,+ type ReadRecordsArgs,+ type ReadResult,+ type SelectedRecordPageWire,+ validateRecordSelectionLimit,+ type WriteResult,} from '../protocol';import type {BeginOptimisticWriteArgs,@@ -27,6 +30,8 @@ import type {/** Keep in sync with `OPS_AFFECTED_EVENT` in graphql_cache_plugin. */const OPS_AFFECTED_EVENT = 'graphql-cache://ops-affected';+/** Keep in sync with `CACHE_CHANGED_EVENT` in the native plugin. */+const CACHE_CHANGED_EVENT = 'graphql-cache://cache-changed';/** Payload of the ops-affected event (graphql_cache_plugin `OpsAffectedEvent`). */type OpsAffectedPayload = {@@ -34,6 +39,8 @@ type OpsAffectedPayload = {keys: string[];};+type CacheChangedPayload = Record<string, never>;+export interface TauriHostOptions {scope: string;hotCapacity?: number;@@ -42,6 +49,8 @@ export interface TauriHostOptions {* IPC call rejects; the exchange degrades rejected reads to the network.*/requestTimeoutMs?: number;+ /** Reports an asynchronous durable-storage initialization failure. */+ onInitializationError?: (error: Error) => void;}const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;@@ -49,6 +58,7 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;export function createTauriCacheHost(options: TauriHostOptions): CacheHost {const clientId = crypto.randomUUID();const affectedSubscribers = new Set<(opKeys: number[]) => void>();+ const cacheChangeSubscribers = new Set<() => void>();const requestTimeoutMs =options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;@@ -94,10 +104,27 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {return undefined;});- const ready = request('graphql_cache_init', {+ const unlistenCacheChanges: Promise<UnlistenFn | undefined> =+ listen<CacheChangedPayload>(CACHE_CHANGED_EVENT, () => {+ for (const cb of cacheChangeSubscribers) cb();+ }).catch((error) => {+ console.warn('graphql cache change listener failed', error);+ return undefined;+ });++ const ready = request<void>('graphql_cache_init', {scope: options.scope,hotCapacity: options.hotCapacity,});+ void (async () => {+ try {+ await ready;+ } catch (error) {+ options.onInitializationError?.(+ error instanceof Error ? error : new Error(String(error))+ );+ }+ })();const opId = (opKey: number) => `${clientId}:${opKey}`;@@ -114,6 +141,20 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {});},+ async readRecords(args: ReadRecordsArgs): Promise<SelectedRecordPageWire> {+ const limit = validateRecordSelectionLimit(args.limit);+ await ready;+ return await request<SelectedRecordPageWire>(+ 'graphql_cache_read_records',+ {+ document: args.document,+ fragmentName: args.fragmentName,+ cursor: args.cursor,+ limit,+ }+ );+ },+async writeQuery(args: CacheWriteArgs): Promise<WriteResult> {await ready;return await request<WriteResult>('graphql_cache_write', {@@ -242,9 +283,16 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {return () => affectedSubscribers.delete(cb);},+ onCacheChanged(cb: () => void): () => void {+ cacheChangeSubscribers.add(cb);+ return () => cacheChangeSubscribers.delete(cb);+ },+dispose() {affectedSubscribers.clear();+ cacheChangeSubscribers.clear();void unlisten.then((fn) => fn?.());+ void unlistenCacheChanges.then((fn) => fn?.());},};}diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.tsindex 4d838b4e08..9bfb80f1bf 100644--- a/apps/web/src/lib/graphql-cache/host/types.ts+++ b/apps/web/src/lib/graphql-cache/host/types.ts@@ -12,7 +12,9 @@ import type {OptimisticLinkPatchWire,OptimisticWriteResult,QueryRevalidationWire,+ ReadRecordsArgs,ReadResult,+ SelectedRecordPageWire,WriteResult,} from '../protocol';@@ -50,6 +52,8 @@ export interface CacheHost {readonly disabled?: boolean;readQuery(args: CacheReadArgs): Promise<ReadResult>;+ /** Projects normalized records through a named GraphQL fragment. */+ readRecords(args: ReadRecordsArgs): Promise<SelectedRecordPageWire>;writeQuery(args: CacheWriteArgs): Promise<WriteResult>;/** Durably queues a mutation and its optimistic response. */beginOptimisticWrite(@@ -95,5 +99,8 @@ export interface CacheHost {*/onOpsAffected(cb: (opKeys: number[]) => void): () => void;+ /** Subscribes whenever the effective normalized-cache view changes. */+ onCacheChanged(cb: () => void): () => void;+dispose(): void;}diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts b/apps/web/src/lib/graphql-cache/host/worker-host.test.tsindex 23b08e6b5f..5cfbb66545 100644--- a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts+++ b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts@@ -27,6 +27,13 @@ describe('createWorkerCacheHost', () => {await expect(host.writeQuery({ query: '{ x }', data: { x: 1 } })).resolves.toEqual({ changed: [], affectedOps: [], reset: false });+ await expect(+ host.readRecords({+ document: 'fragment Item on GraphqlSoupItem { id }',+ fragmentName: 'Item',+ limit: 20,+ })+ ).resolves.toEqual({ records: [], nextCursor: null });});it('round-trips generated query inspection through the worker protocol', async () => {diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.tsindex f6c1495ef9..98b556fe78 100644--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts@@ -11,7 +11,10 @@ import {isCachePush,type MutationClaim,type OptimisticWriteResult,+ type ReadRecordsArgs,type ReadResult,+ type SelectedRecordPageWire,+ validateRecordSelectionLimit,type WorkerMessage,type WriteResult,} from '../protocol';@@ -44,6 +47,8 @@ export interface WorkerHostOptions {* operation that may already have completed durably.*/requestTimeoutMs?: number;+ /** Reports an asynchronous durable-storage initialization failure. */+ onInitializationError?: (error: Error) => void;}const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;@@ -56,6 +61,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {const clientId = crypto.randomUUID();const pending = new Map<number, Pending>();const affectedSubscribers = new Set<(opKeys: number[]) => void>();+ const cacheChangeSubscribers = new Set<() => void>();const requestTimeoutMs =options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;let nextRequestId = 1;@@ -66,6 +72,10 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {const onMessage = (event: MessageEvent<WorkerMessage>) => {const msg = event.data;if (isCachePush(msg)) {+ if (msg.kind === 'cache-changed') {+ for (const cb of cacheChangeSubscribers) cb();+ return;+ }const prefix = `${clientId}:`;const opKeys = msg.opIds.filter((id) => id.startsWith(prefix))@@ -119,7 +129,11 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {const id = nextRequestId++;return new Promise((resolve, reject) => {const entry: Pending = { resolve, reject };- if (msg.kind === 'read' || msg.kind === 'inspect-query') {+ if (+ msg.kind === 'read' ||+ msg.kind === 'read-records' ||+ msg.kind === 'inspect-query'+ ) {entry.timer = setTimeout(() => {if (pending.delete(id)) {reject(new Error(`cache worker timeout: ${msg.kind}`));@@ -136,6 +150,15 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {scope: options.scope,hotCapacity: options.hotCapacity,});+ void (async () => {+ try {+ await ready;+ } catch (error) {+ options.onInitializationError?.(+ error instanceof Error ? error : new Error(String(error))+ );+ }+ })();const opId = (opKey: number) => `${clientId}:${opKey}`;@@ -153,6 +176,18 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {})) as ReadResult;},+ async readRecords(args: ReadRecordsArgs): Promise<SelectedRecordPageWire> {+ const limit = validateRecordSelectionLimit(args.limit);+ await ready;+ return (await request({+ kind: 'read-records',+ document: args.document,+ fragmentName: args.fragmentName,+ cursor: args.cursor,+ limit,+ })) as SelectedRecordPageWire;+ },+async writeQuery(args: CacheWriteArgs): Promise<WriteResult> {await ready;return (await request({@@ -277,6 +312,15 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {return () => affectedSubscribers.delete(cb);},- dispose,+ onCacheChanged(cb: () => void): () => void {+ cacheChangeSubscribers.add(cb);+ return () => cacheChangeSubscribers.delete(cb);+ },++ dispose() {+ affectedSubscribers.clear();+ cacheChangeSubscribers.clear();+ dispose();+ },};}diff --git a/apps/web/src/lib/graphql-cache/index.ts b/apps/web/src/lib/graphql-cache/index.tsindex f89629752e..370e28ad7b 100644--- a/apps/web/src/lib/graphql-cache/index.ts+++ b/apps/web/src/lib/graphql-cache/index.ts@@ -22,6 +22,12 @@ export {select,update,} from './exchange/optimistic';+export {+ type RecordSelection,+ readRecords,+ type SelectedRecordPage,+ selectRecords,+} from './exchange/record-selection';export { createTauriCacheHost } from './host/tauri-host';export type {CacheHost,@@ -36,6 +42,13 @@ export type {CacheRequest,CacheResponse,OptimisticWriteResult,+ ReadRecordsArgs,ReadResult,+ RecordCursor,+ SelectedRecordPageWire,WriteResult,} from './protocol';+export {+ MAX_RECORD_SELECTION_PAGE_SIZE,+ validateRecordSelectionLimit,+} from './protocol';diff --git a/apps/web/src/lib/graphql-cache/lifecycle.ts b/apps/web/src/lib/graphql-cache/lifecycle.tsindex 7cdca28f53..30cbe78196 100644--- a/apps/web/src/lib/graphql-cache/lifecycle.ts+++ b/apps/web/src/lib/graphql-cache/lifecycle.ts@@ -4,8 +4,9 @@ import { rotateCacheScope } from './scope';const hosts = new Set<CacheHost>();/** Registers a cache host for account-lifecycle clearing. */-export function registerCacheHost(host: CacheHost): void {+export function registerCacheHost(host: CacheHost): () => void {hosts.add(host);+ return () => hosts.delete(host);}/** Best-effort wipe of records and queued user intent during logout. */diff --git a/apps/web/src/lib/graphql-cache/protocol.test.ts b/apps/web/src/lib/graphql-cache/protocol.test.tsnew file mode 100644index 0000000000..e974760404--- /dev/null+++ b/apps/web/src/lib/graphql-cache/protocol.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';+import {+ MAX_RECORD_SELECTION_PAGE_SIZE,+ validateRecordSelectionLimit,+} from './protocol';++describe('validateRecordSelectionLimit', () => {+ it('accepts bounded positive integers', () => {+ expect(validateRecordSelectionLimit(1)).toBe(1);+ expect(validateRecordSelectionLimit(MAX_RECORD_SELECTION_PAGE_SIZE)).toBe(+ MAX_RECORD_SELECTION_PAGE_SIZE+ );+ });++ it.each([+ 0,+ -1,+ 1.5,+ MAX_RECORD_SELECTION_PAGE_SIZE + 1,+ Number.NaN,+ Number.POSITIVE_INFINITY,+ ])('rejects invalid limit %s', (limit) => {+ expect(() => validateRecordSelectionLimit(limit)).toThrow(+ 'record selection limit must be an integer between 1 and 500'+ );+ });+});diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.tsindex fca0e6e492..4b2ff8885d 100644--- a/apps/web/src/lib/graphql-cache/protocol.ts+++ b/apps/web/src/lib/graphql-cache/protocol.ts@@ -11,6 +11,40 @@export type ReadResult = { kind: 'hit'; data: unknown } | { kind: 'miss' };+/** Opaque exclusive cursor for deterministic normalized-record scans. */+export type RecordCursor = string;++/** Untyped wire page returned by cache hosts. */+export type SelectedRecordPageWire = {+ records: unknown[];+ nextCursor: RecordCursor | null;+};++export type ReadRecordsArgs = {+ /** Serialized generated fragment document. */+ document: string;+ /** Root fragment to apply to matching normalized records. */+ fragmentName: string;+ cursor?: RecordCursor;+ limit: number;+};++export const MAX_RECORD_SELECTION_PAGE_SIZE = 500;++/** Validates a record-selection page size before crossing a host boundary. */+export function validateRecordSelectionLimit(limit: number): number {+ if (+ !Number.isSafeInteger(limit) ||+ limit < 1 ||+ limit > MAX_RECORD_SELECTION_PAGE_SIZE+ ) {+ throw new RangeError(+ `record selection limit must be an integer between 1 and ${MAX_RECORD_SELECTION_PAGE_SIZE}`+ );+ }+ return limit;+}+export type QueryRevalidationWire = {query: string;operationName?: string;@@ -156,6 +190,13 @@ export type CacheRequest = { id: number } & (leaseOwner: string;leaseGeneration: string;}+ | {+ kind: 'read-records';+ document: string;+ fragmentName: string;+ cursor?: RecordCursor;+ limit: number;+ }| {kind: 'inspect-query';query: string;@@ -192,15 +233,22 @@ export function isCacheNotice(* operations whose underlying records changed. The host filters by its own* clientId prefix and re-executes.*/-export type CachePush = {- kind: 'ops-affected';- opIds: string[];- /** Changed entity keys, for diagnostics/advanced consumers. */- keys: string[];-};+export type CachePush =+ | {+ kind: 'ops-affected';+ opIds: string[];+ /** Changed entity keys, for diagnostics/advanced consumers. */+ keys: string[];+ }+ | {+ kind: 'cache-changed';+ };export type WorkerMessage = CacheResponse | CachePush;export function isCachePush(msg: WorkerMessage): msg is CachePush {- return 'kind' in msg && msg.kind === 'ops-affected';+ return (+ 'kind' in msg &&+ (msg.kind === 'ops-affected' || msg.kind === 'cache-changed')+ );}diff --git a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts b/apps/web/src/lib/graphql-cache/worker/wasm-module.tsindex 3faf21b927..07d9c1d9c4 100644--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts@@ -15,6 +15,8 @@ import type {OptimisticWriteResult,QueryRevalidationWire,ReadResult,+ RecordCursor,+ SelectedRecordPageWire,WriteResult,} from '../protocol';@@ -25,6 +27,12 @@ export interface CacheEngine {operationName: string | undefined,variables: Record<string, unknown> | undefined): Promise<ReadResult>;+ readRecords(+ document: string,+ fragmentName: string,+ cursor: RecordCursor | undefined,+ limit: number+ ): Promise<SelectedRecordPageWire>;writeQuery(originOpId: string | undefined,query: string,diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.test.tsnew file mode 100644index 0000000000..09cbfda42e--- /dev/null+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts@@ -0,0 +1,81 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const loadCacheWasmMock = vi.hoisted(() => vi.fn());++vi.mock('./wasm-module', () => ({ loadCacheWasm: loadCacheWasmMock }));++import type { SelectedRecordPageWire } from '../protocol';+import { CacheWorkerCore } from './worker-core';++describe('CacheWorkerCore record selection', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('dispatches read-records to the wasm engine', async () => {+ const page: SelectedRecordPageWire = {+ records: [{ id: 'item-1' }],+ nextCursor: null,+ };+ const readRecords = vi.fn().mockResolvedValue(page);+ loadCacheWasmMock.mockResolvedValue({+ openCache: vi.fn().mockResolvedValue({ readRecords }),+ });+ const messages: unknown[] = [];+ const port = { postMessage: (message: unknown) => messages.push(message) };+ const core = new CacheWorkerCore();++ await core.handleRequest(port, {+ id: 1,+ kind: 'init',+ scope: 'scope-1',+ });+ await core.handleRequest(port, {+ id: 2,+ kind: 'read-records',+ document: 'fragment Item on GraphqlSoupItem { id }',+ fragmentName: 'Item',+ cursor: 'cursor-1',+ limit: 25,+ });++ expect(readRecords).toHaveBeenCalledWith(+ 'fragment Item on GraphqlSoupItem { id }',+ 'Item',+ 'cursor-1',+ 25+ );+ expect(messages.at(-1)).toEqual({ id: 2, ok: true, result: page });+ });++ it('pushes cache changes even without affected operations', async () => {+ const writeResult = {+ changed: ['GraphqlSoupDocument:doc-1'],+ affectedOps: [],+ reset: false,+ };+ loadCacheWasmMock.mockResolvedValue({+ openCache: vi.fn().mockResolvedValue({+ writeQuery: vi.fn().mockResolvedValue(writeResult),+ }),+ });+ const messages: unknown[] = [];+ const port = { postMessage: (message: unknown) => messages.push(message) };+ const core = new CacheWorkerCore();+ core.addPort(port);++ await core.handleRequest(port, {+ id: 1,+ kind: 'init',+ scope: 'scope-1',+ });+ await core.handleRequest(port, {+ id: 2,+ kind: 'write',+ query: 'query { user { id } }',+ data: { user: { id: 'user-1' } },+ });++ expect(messages).toContainEqual({ kind: 'cache-changed' });+ });+});diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.tsindex a07cace5ee..8820da2718 100644--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts@@ -10,6 +10,7 @@ import type {CacheResponse,OptimisticWriteResult,ReadResult,+ SelectedRecordPageWire,WriteResult,} from '../protocol';import { type CacheEngine, loadCacheWasm } from './wasm-module';@@ -70,6 +71,16 @@ export class CacheWorkerCore {);return result;})+ .with({ kind: 'read-records' }, async (request) => {+ const engine = this.requireEngine();+ const result: SelectedRecordPageWire = await engine.readRecords(+ request.document,+ request.fragmentName,+ request.cursor,+ request.limit+ );+ return result;+ }).with({ kind: 'write' }, async (request) => {const engine = this.requireEngine();const result = await engine.writeQuery(@@ -80,7 +91,7 @@ export class CacheWorkerCore {request.data,request.identity);- this.fanOut(result);+ this.fanOut(result, true);return result;}).with({ kind: 'begin-optimistic-write' }, async (request) => {@@ -95,7 +106,7 @@ export class CacheWorkerCore {request.revalidations,request.createdAtMs);- this.fanOut(result);+ this.fanOut(result, true);return result;}).with({ kind: 'inspect-query' }, async (request) => {@@ -136,7 +147,7 @@ export class CacheWorkerCore {request.variables,request.data);- this.fanOut(result);+ this.fanOut(result, true);return result;}).with({ kind: 'rollback-optimistic-write' }, async (request) => {@@ -146,18 +157,21 @@ export class CacheWorkerCore {request.leaseOwner,request.leaseGeneration);- this.fanOut(result);+ this.fanOut(result, true);return result;}).with({ kind: 'invalidate' }, async (request) => {const engine = this.requireEngine();const affectedOps = await engine.invalidateKeys(request.keys);- this.fanOut({- changed: request.keys,- affectedOps,- reset: false,- revalidations: [],- });+ this.fanOut(+ {+ changed: request.keys,+ affectedOps,+ reset: false,+ revalidations: [],+ },+ true+ );return affectedOps;}).with({ kind: 'teardown' }, async (request) => {@@ -166,6 +180,7 @@ export class CacheWorkerCore {}).with({ kind: 'clear' }, async () => {await this.requireEngine().clear();+ this.push({ kind: 'cache-changed' });return null;}).exhaustive();@@ -191,7 +206,7 @@ export class CacheWorkerCore {}/** Notifies every page connected to this shared engine. */- private fanOut(result: WriteResult): void {+ private fanOut(result: WriteResult, cacheChanged: boolean): void {if (result.affectedOps.length > 0) {this.push({kind: 'ops-affected',@@ -199,10 +214,12 @@ export class CacheWorkerCore {keys: result.changed,});}+ if (cacheChanged) {+ this.push({ kind: 'cache-changed' });+ }}private push(msg: CachePush): void {- if (msg.opIds.length === 0) return;for (const port of this.ports) {port.postMessage(msg);}diff --git a/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts b/apps/web/src/lib/queries/soup/quick-access-crm-companies.tsindex d71647c396..7ed8cbb7b0 100644--- a/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts+++ b/apps/web/src/lib/queries/soup/quick-access-crm-companies.ts@@ -1,5 +1,9 @@import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';-import { ENABLE_CRM } from '@core/constant/featureFlags';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import {+ ENABLE_CRM_FLAG,+ ENABLE_CRM_OVERRIDE,+} from '@core/constant/featureFlags';import { type CrmCompanyEntity, isCrmCompanyEntity } from '@entity';import { useSoupItemsQuery } from '@queries/soup/items';import { createMemo } from 'solid-js';@@ -20,6 +24,10 @@ const STALE_TIME = 5 * 60 * 1000;* Every other entity type is filtered out by extending `QUERY_FILTERS_BASE`.*/export function useQuickAccessCrmCompaniesQuery() {+ const crmFlag = useFeatureFlag(ENABLE_CRM_FLAG, {+ enabledOverride: ENABLE_CRM_OVERRIDE,+ });+const query = useSoupItemsQuery(() => ({params: {@@ -32,7 +40,7 @@ export function useQuickAccessCrmCompaniesQuery() {crm_company_filters: undefined,},}),- () => ({ staleTime: STALE_TIME, enabled: ENABLE_CRM() })+ () => ({ staleTime: STALE_TIME, enabled: crmFlag().enabled }));const companies = createMemo<CrmCompanyEntity[]>(diff --git a/apps/web/src/lib/queries/soup/transform-utils.ts b/apps/web/src/lib/queries/soup/transform-utils.tsindex a5909475f3..7f103cf9e4 100644--- a/apps/web/src/lib/queries/soup/transform-utils.ts+++ b/apps/web/src/lib/queries/soup/transform-utils.ts@@ -829,6 +829,7 @@ export const mapApiSoupItemToEntity = (hidden: item.data.hidden,createdAt: item.data.createdAt,updatedAt: item.data.updatedAt,+ viewedAt: item.data.viewedAt,sortTs: item.data.updatedAt,frecencyScore: item.frecency_score,domains: item.data.domains.map((d) => ({diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.tsindex 5ecf35e512..a629e22bd1 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts@@ -84,11 +84,11 @@ export function graphqlCacheEnabled(): boolean {}let cachedClient: Client | undefined;-let cacheHost: CacheHost | undefined;+let cachedCacheHost: CacheHost | undefined;/** Returns the persistent normalized-cache host after client initialization. */export function getGraphqlCacheHost(): CacheHost | undefined {- return cacheHost?.disabled ? undefined : cacheHost;+ return cachedCacheHost?.disabled ? undefined : cachedCacheHost;}/**@@ -102,14 +102,25 @@ export function getGraphqlCacheHost(): CacheHost | undefined {export function getGraphqlSoupClient(): Client {if (!graphqlCacheEnabled()) return graphqlSoupClient;cachedClient ??= (() => {+ let host: CacheHost | undefined;+ let unregisterHost: () => void = () => undefined;+ const onInitializationError = (error: Error) => {+ if (!host || cachedCacheHost !== host) return;+ unregisterHost();+ host.dispose();+ cachedCacheHost = undefined;+ cachedClient = graphqlSoupClient;+ console.warn(+ 'graphql cache async init failed; using uncached client',+ error+ );+ };try {const scope = getOrCreateCacheScope();- const host = isTauri()- ? createTauriCacheHost({ scope })- : createWorkerCacheHost({ scope });- cacheHost = host;- registerCacheHost(host);- return createClient({+ host = isTauri()+ ? createTauriCacheHost({ scope, onInitializationError })+ : createWorkerCacheHost({ scope, onInitializationError });+ const client = createClient({url: `${dssHost}/items/soup/graphql`,exchanges: [normalizedCacheExchange(host, {@@ -127,7 +138,12 @@ export function getGraphqlSoupClient(): Client {],fetch: dssGraphqlFetch,});+ cachedCacheHost = host;+ unregisterHost = registerCacheHost(host);+ return client;} catch (error) {+ host?.dispose();+ cachedCacheHost = undefined;console.warn('graphql cache init failed; using uncached client', error);return graphqlSoupClient;}@@ -135,6 +151,13 @@ export function getGraphqlSoupClient(): Client {return cachedClient;}+/** Returns the cache host backing the flagged GraphQL Soup client. */+export function getGraphqlSoupCacheHost(): CacheHost | undefined {+ if (!graphqlCacheEnabled()) return undefined;+ getGraphqlSoupClient();+ return cachedCacheHost;+}+export type GraphqlSoupInput = SoupInput;export type GraphqlSoupInitialInput = SoupInitialInput;export type GraphqlGroupedSoupInput = GroupedSoupInput;@@ -149,7 +172,7 @@ export type GraphqlGroupedSoupPage = {}>;};-type GraphqlSoupItem = SoupQuery['user']['soup']['items'][number];+export type GraphqlSoupItem = SoupQuery['user']['soup']['items'][number];type GraphqlSoupEntity = GraphqlSoupItem['entity'];type GraphqlProperty = Extract<GraphqlSoupEntity,@@ -293,7 +316,7 @@ function mapGraphqlNotifications(notifications: GraphqlSoupNotification[]) {}));}-function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {+export function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {const frecency = item.frecencyScore;// `is_favorited: false` below: the GraphQL soup surface has no favorites// data; the REST `SoupApiItem` shape requires the flag, and nothingdiff --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 92f347c894..e5532a96a8 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@@ -806,6 +806,58 @@ export type GroupSoupQuery = { user: { id: string, groupSoup: { bins: Array<{ ke| null }>, notifications: Array<{ id: string, eventType: string, entityType: GraphqlSoupEntityType, entityId: string, sent: boolean, done: boolean, seen: boolean, createdAt: string, viewedAt: string | null, updatedAt: string, senderId: string | null, metadata: unknown }> }}> }> } } };+export type QuickAccessSoupItemFieldsFragment = { id: string, entityType: GraphqlSoupEntityType, frecencyScore: number, entity:+ | { __typename: 'GraphqlSoupCall', id: string, channelId: string, channelName: string | null, createdBy: string, customName: string | null, summary: string | null, startedAt: string, endedAt: string | null, durationMs: number | null, isActive: boolean, status: string, attended: boolean, participants: Array<{ userId: string, joinedAt: string, leftAt: string | null }>, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlPropertyDataType, isMultiSelect: boolean, specificEntityType: GraphqlPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value:+ | { __typename: 'GraphqlBooleanPropertyValue', boolValue: boolean }+ | { __typename: 'GraphqlDatePropertyValue', dateValue: string }+ | { __typename: 'GraphqlEntityReferencePropertyValue', references: Array<{ entityId: string, entityType: GraphqlPropertyEntityType, specificMessageId: string | null }> }+ | { __typename: 'GraphqlLinkPropertyValue', urls: Array<string> }+ | { __typename: 'GraphqlNumberPropertyValue', numberValue: number }+ | { __typename: 'GraphqlSelectOptionPropertyValue', optionIds: Array<string> }+ | { __typename: 'GraphqlStringPropertyValue', stringValue: string }+ | null }>, notifications: Array<{ id: string, eventType: string, entityType: GraphqlSoupEntityType, entityId: string, sent: boolean, done: boolean, seen: boolean, createdAt: string, viewedAt: string | null, updatedAt: string, senderId: string | null, metadata: unknown }> }+ | { __typename: 'GraphqlSoupChannel', id: string, channelType: string, ownerId: string, organizationId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, interactedAt: string | null, channelName: string | null, channelTeamId: string | null, participants: Array<{ channelId: string, userId: string, role: string, joinedAt: string, leftAt: string | null }>, latestMessage: { id: string, threadId: string | null, senderId: string, content: string, createdAt: string, updatedAt: string, deletedAt: string | null, mentions: Array<string> } | null, latestNonThreadMessage: { id: string, threadId: string | null, senderId: string, content: string, createdAt: string, updatedAt: string, deletedAt: string | null, mentions: Array<string> } | null, notifications: Array<{ id: string, eventType: string, entityType: GraphqlSoupEntityType, entityId: string, sent: boolean, done: boolean, seen: boolean, createdAt: string, viewedAt: string | null, updatedAt: string, senderId: string | null, metadata: unknown }> }+ | { __typename: 'GraphqlSoupChannelThread', id: string, channelId: string, senderId: string, content: string, createdAt: string, updatedAt: string, effectiveUpdatedAt: string, replyCount: number, notifications: Array<{ id: string, eventType: string, entityType: GraphqlSoupEntityType, entityId: string, sent: boolean, done: boolean, seen: boolean, createdAt: string, viewedAt: string | null, updatedAt: string, senderId: string | null, metadata: unknown }> }+ | { __typename: 'GraphqlSoupChat', id: string, ownerId: string, projectId: string | null, isPersistent: boolean, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, chatName: string, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlPropertyDataType, isMultiSelect: boolean, specificEntityType: GraphqlPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value:+ | { __typename: 'GraphqlBooleanPropertyValue', boolValue: boolean }+ | { __typename: 'GraphqlDatePropertyValue', dateValue: string }+ | { __typename: 'GraphqlEntityReferencePropertyValue', references: Array<{ entityId: string, entityType: GraphqlPropertyEntityType, specificMessageId: string | null }> }+ | { __typename: 'GraphqlLinkPropertyValue', urls: Array<string> }+ | { __typename: 'GraphqlNumberPropertyValue', numberValue: number }+ | { __typename: 'GraphqlSelectOptionPropertyValue', optionIds: Array<string> }+ | { __typename: 'GraphqlStringPropertyValue', stringValue: string }+ | null }>, notifications: Array<{ id: string, eventType: string, entityType: GraphqlSoupEntityType, entityId: string, sent: boolean, done: boolean, seen: boolean, createdAt: string, viewedAt: string | null, updatedAt: string, senderId: string | null, metadata: unknown }> }+ | { __typename: 'GraphqlSoupCrmCompany', id: string, description: string | null, emailSync: boolean, hidden: boolean, createdAt: string, updatedAt: string, viewedAt: string | null, domains: Array<string>, crmTeamId: string, crmCompanyName: string | null, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlPropertyDataType, isMultiSelect: boolean, specificEntityType: GraphqlPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value:+ | { __typename: 'GraphqlBooleanPropertyValue', boolValue: boolean }+ | { __typename: 'GraphqlDatePropertyValue', dateValue: string }+ | { __typename: 'GraphqlEntityReferencePropertyValue', references: Array<{ entityId: string, entityType: GraphqlPropertyEntityType, specificMessageId: string | null }> }+ | { __typename: 'GraphqlLinkPropertyValue', urls: Array<string> }+ | { __typename: 'GraphqlNumberPropertyValue', numberValue: number }+ | { __typename: 'GraphqlSelectOptionPropertyValue', optionIds: Array<string> }+ | { __typename: 'GraphqlStringPropertyValue', stringValue: string }+ | null }>, notifications: Array<{ id: string, eventType: string, entityType: GraphqlSoupEntityType, entityId: string, sent: boolean, done: boolean, seen: boolean, createdAt: string, viewedAt: string | null, updatedAt: string, senderId: string | null, metadata: unknown }> }+ | { __typename: 'GraphqlSoupDocument', id: string, ownerId: string, fileType: string | null, projectId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, documentName: string, subType: { kind: string, isCompleted: boolean | null } | null, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlPropertyDataType, isMultiSelect: boolean, specificEntityType: GraphqlPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value:+ | { __typename: 'GraphqlBooleanPropertyValue', boolValue: boolean }+ | { __typename: 'GraphqlDatePropertyValue', dateValue: string }+ | { __typename: 'GraphqlEntityReferencePropertyValue', references: Array<{ entityId: string, entityType: GraphqlPropertyEntityType, specificMessageId: string | null }> }+ | { __typename: 'GraphqlLinkPropertyValue', urls: Array<string> }+ | { __typename: 'GraphqlNumberPropertyValue', numberValue: number }+ | { __typename: 'GraphqlSelectOptionPropertyValue', optionIds: Array<string> }+ | { __typename: 'GraphqlStringPropertyValue', stringValue: string }+ | null }>, notifications: Array<{ id: string, eventType: string, entityType: GraphqlSoupEntityType, entityId: string, sent: boolean, done: boolean, seen: boolean, createdAt: string, viewedAt: string | null, updatedAt: string, senderId: string | null, metadata: unknown }> }+ | { __typename: 'GraphqlSoupEmailThread', attachmentCount: number, participantCount: number }+ | { __typename: 'GraphqlSoupForeignEntity', id: string, foreignEntityId: string, foreignEntitySource: string, storedForId: string, storedForAuthEntity: string, metadata: unknown, createdAt: string, updatedAt: string, notifications: Array<{ id: string, eventType: string, entityType: GraphqlSoupEntityType, entityId: string, sent: boolean, done: boolean, seen: boolean, createdAt: string, viewedAt: string | null, updatedAt: string, senderId: string | null, metadata: unknown }> }+ | { __typename: 'GraphqlSoupProject', id: string, ownerId: string, parentId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, projectName: string, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlPropertyDataType, isMultiSelect: boolean, specificEntityType: GraphqlPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value:+ | { __typename: 'GraphqlBooleanPropertyValue', boolValue: boolean }+ | { __typename: 'GraphqlDatePropertyValue', dateValue: string }+ | { __typename: 'GraphqlEntityReferencePropertyValue', references: Array<{ entityId: string, entityType: GraphqlPropertyEntityType, specificMessageId: string | null }> }+ | { __typename: 'GraphqlLinkPropertyValue', urls: Array<string> }+ | { __typename: 'GraphqlNumberPropertyValue', numberValue: number }+ | { __typename: 'GraphqlSelectOptionPropertyValue', optionIds: Array<string> }+ | { __typename: 'GraphqlStringPropertyValue', stringValue: string }+ | null }>, notifications: Array<{ id: string, eventType: string, entityType: GraphqlSoupEntityType, entityId: string, sent: boolean, done: boolean, seen: boolean, createdAt: string, viewedAt: string | null, updatedAt: string, senderId: string | null, metadata: unknown }> }+ };+export type SetEntityPropertyMutationVariables = Exact<{input: SetEntityPropertyInput;}>;@@ -963,6 +1015,7 @@ export type SoupNotificationFieldsFragment = { id: string, eventType: string, enexport const SoupPropertyFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}}]}}]} as unknown as DocumentNode<SoupPropertyFieldsFragment, unknown>;export const SoupNotificationFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"done"}},{"kind":"Field","name":{"kind":"Name","value":"seen"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}}]} as unknown as DocumentNode<SoupNotificationFieldsFragment, unknown>;export const SoupChannelMessageFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<SoupChannelMessageFieldsFragment, unknown>;+export const QuickAccessSoupItemFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"QuickAccessSoupItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"Field","name":{"kind":"Name","value":"entity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"attachmentCount"}},{"kind":"Field","name":{"kind":"Name","value":"participantCount"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"done"}},{"kind":"Field","name":{"kind":"Name","value":"seen"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<QuickAccessSoupItemFieldsFragment, unknown>;export const SoupItemFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"Field","name":{"kind":"Name","value":"entity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"isImportant"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"sortTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"sfsPhotoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestContentMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"internalDateTs"}},{"kind":"Field","name":{"kind":"Name","value":"sentAt"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isStarred"}},{"kind":"Field","name":{"kind":"Name","value":"isSent"}},{"kind":"Field","name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","name":{"kind":"Name","value":"from"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"to"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bcc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bodyParsed"}},{"kind":"Field","name":{"kind":"Name","value":"bodyText"}},{"kind":"Field","name":{"kind":"Name","value":"bodyHtmlSanitized"}},{"kind":"Field","name":{"kind":"Name","value":"bodyMacro"}},{"kind":"Field","name":{"kind":"Name","value":"bodyReplyless"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"done"}},{"kind":"Field","name":{"kind":"Name","value":"seen"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<SoupItemFieldsFragment, unknown>;export const GroupSoupMembershipDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GroupSoupMembership"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"GroupedSoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"groupSoup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"bins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<GroupSoupMembershipQuery, GroupSoupMembershipQueryVariables>;export const GroupSoupDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GroupSoup"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"GroupedSoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"groupSoup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"bins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupItemFields"}}]}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"done"}},{"kind":"Field","name":{"kind":"Name","value":"seen"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"Field","name":{"kind":"Name","value":"entity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"isImportant"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"sortTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"sfsPhotoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestContentMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"internalDateTs"}},{"kind":"Field","name":{"kind":"Name","value":"sentAt"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isStarred"}},{"kind":"Field","name":{"kind":"Name","value":"isSent"}},{"kind":"Field","name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","name":{"kind":"Name","value":"from"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"to"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bcc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bodyParsed"}},{"kind":"Field","name":{"kind":"Name","value":"bodyText"}},{"kind":"Field","name":{"kind":"Name","value":"bodyHtmlSanitized"}},{"kind":"Field","name":{"kind":"Name","value":"bodyMacro"}},{"kind":"Field","name":{"kind":"Name","value":"bodyReplyless"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GroupSoupQuery, GroupSoupQueryVariables>;diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/quick-access.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/quick-access.graphqlnew file mode 100644index 0000000000..3a6a5d4619--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/graphql/quick-access.graphql@@ -0,0 +1,166 @@+fragment QuickAccessSoupItemFields on GraphqlSoupItem {+ id+ entityType+ frecencyScore+ entity {+ __typename+ ... on GraphqlSoupDocument {+ id+ documentName: name+ ownerId+ fileType+ projectId+ createdAt+ updatedAt+ viewedAt+ deletedAt+ subType {+ kind+ isCompleted+ }+ properties {+ ...SoupPropertyFields+ }+ notifications {+ ...SoupNotificationFields+ }+ }+ ... on GraphqlSoupChat {+ id+ chatName: name+ ownerId+ projectId+ isPersistent+ createdAt+ updatedAt+ viewedAt+ deletedAt+ properties {+ ...SoupPropertyFields+ }+ notifications {+ ...SoupNotificationFields+ }+ }+ ... on GraphqlSoupProject {+ id+ projectName: name+ ownerId+ parentId+ createdAt+ updatedAt+ viewedAt+ deletedAt+ properties {+ ...SoupPropertyFields+ }+ notifications {+ ...SoupNotificationFields+ }+ }+ # These fields are intentionally absent from cached Soup email records.+ # Their absence makes email projections incomplete, so record selection+ # omits email wrappers instead of returning typename-only shells.+ ... on GraphqlSoupEmailThread {+ attachmentCount+ participantCount+ }+ ... on GraphqlSoupChannel {+ id+ channelName: name+ channelType+ ownerId+ organizationId+ channelTeamId: teamId+ createdAt+ updatedAt+ viewedAt+ interactedAt+ participants {+ channelId+ userId+ role+ joinedAt+ leftAt+ }+ latestMessage {+ ...SoupChannelMessageFields+ }+ latestNonThreadMessage {+ ...SoupChannelMessageFields+ }+ notifications {+ ...SoupNotificationFields+ }+ }+ ... on GraphqlSoupChannelThread {+ id+ channelId+ senderId+ content+ createdAt+ updatedAt+ effectiveUpdatedAt+ replyCount+ notifications {+ ...SoupNotificationFields+ }+ }+ ... on GraphqlSoupCall {+ id+ channelId+ channelName+ createdBy+ customName+ summary+ startedAt+ endedAt+ durationMs+ isActive+ status+ attended+ participants {+ userId+ joinedAt+ leftAt+ }+ properties {+ ...SoupPropertyFields+ }+ notifications {+ ...SoupNotificationFields+ }+ }+ ... on GraphqlSoupCrmCompany {+ id+ crmTeamId: teamId+ crmCompanyName: name+ description+ emailSync+ hidden+ createdAt+ updatedAt+ viewedAt+ domains+ properties {+ ...SoupPropertyFields+ }+ notifications {+ ...SoupNotificationFields+ }+ }+ ... on GraphqlSoupForeignEntity {+ id+ foreignEntityId+ foreignEntitySource+ storedForId+ storedForAuthEntity+ metadata+ createdAt+ updatedAt+ notifications {+ ...SoupNotificationFields+ }+ }+ }+}diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsxindex f37802053c..9c2580c40b 100644--- a/apps/web/src/routes/Root.tsx+++ b/apps/web/src/routes/Root.tsx@@ -77,7 +77,6 @@ import {useUserInfoQuery,} from '@queries/auth/user-info';import { useChatRenameWebsocketSync } from '@queries/chat';-import { prefetchHistory } from '@queries/history/history';import { QuerySyncProvider } from '@queries/sync/SyncProvider';import { MutationUndoProvider } from '@queries/undo';import { useReopenTrackedEntitiesOnReconnect } from '@service-connection/client';@@ -129,7 +128,6 @@ function useSyncLoginCookie() {const rootPreload: RoutePreloadFunc = async (args) => {await prefetchUserInfo();- prefetchHistory();// even though we are using the transformUrl prop, we may still need to replace the url in the historyconst url = new URL(window.location.href);diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rsindex 00483158b2..b3207f7ee9 100644--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs@@ -12,15 +12,23 @@use crate::engine::{ClaimedMutationWire, EngineHandle, OptimisticWriteResultWire, ReadResultWire, WriteResultWire,};-use crate::{CacheState, InitializedCache, emit_ops_affected};+use crate::{CacheState, InitializedCache, emit_cache_changed, emit_ops_affected};use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};use cache_core::query_inspection::CachedQueryInstance;+use cache_core::record_selection::{RecordCursor, SelectedRecordPage};use cache_sqlite::SqliteStorage;use serde::Deserialize;use tauri::{AppHandle, Manager, Runtime, State};type Variables = serde_json::Map<String, serde_json::Value>;+fn parse_record_cursor(cursor: Option<String>) -> Result<Option<RecordCursor>, String> {+ cursor+ .map(|value| serde_json::from_value(serde_json::Value::String(value)))+ .transpose()+ .map_err(|error| error.to_string())+}+fn engine_handle(state: &State<'_, CacheState>) -> Result<EngineHandle, String> {state.0@@ -83,6 +91,20 @@ pub async fn graphql_cache_read(.await}+/// Projects normalized records through a named GraphQL fragment.+#[tauri::command]+pub async fn graphql_cache_read_records(+ state: State<'_, CacheState>,+ document: String,+ fragment_name: String,+ cursor: Option<String>,+ limit: u32,+) -> Result<SelectedRecordPage, String> {+ engine_handle(&state)?+ .read_records(document, fragment_name, parse_record_cursor(cursor)?, limit)+ .await+}+/// Normalizes and stores a network response; broadcasts affected operations/// to every webview.#[tauri::command]@@ -107,6 +129,7 @@ pub async fn graphql_cache_write<R: Runtime>().await?;emit_ops_affected(&app, &result.affected_ops, &result.changed);+ emit_cache_changed(&app);Ok(result)}@@ -138,6 +161,7 @@ pub async fn graphql_cache_begin_optimistic_write<R: Runtime>().await?;emit_ops_affected(&app, &result.result.affected_ops, &result.result.changed);+ emit_cache_changed(&app);Ok(result)}@@ -224,6 +248,7 @@ pub async fn graphql_cache_commit_optimistic_write<R: Runtime>().await?;emit_ops_affected(&app, &result.affected_ops, &result.changed);+ emit_cache_changed(&app);Ok(result)}@@ -240,6 +265,7 @@ pub async fn graphql_cache_rollback_optimistic_write<R: Runtime>(.rollback_optimistic_write(transaction_id, lease_owner, lease_generation).await?;emit_ops_affected(&app, &result.affected_ops, &result.changed);+ emit_cache_changed(&app);Ok(result)}@@ -253,6 +279,7 @@ pub async fn graphql_cache_invalidate<R: Runtime>() -> Result<Vec<String>, String> {let affected = engine_handle(&state)?.invalidate(keys.clone()).await?;emit_ops_affected(&app, &affected, &keys);+ emit_cache_changed(&app);Ok(affected)}@@ -267,6 +294,11 @@ pub async fn graphql_cache_teardown(/// Wipes all cached state (logout).#[tauri::command]-pub async fn graphql_cache_clear(state: State<'_, CacheState>) -> Result<(), String> {- engine_handle(&state)?.clear().await+pub async fn graphql_cache_clear<R: Runtime>(+ app: AppHandle<R>,+ state: State<'_, CacheState>,+) -> Result<(), String> {+ engine_handle(&state)?.clear().await?;+ emit_cache_changed(&app);+ Ok(())}diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rsindex a53c676afe..fd48390d29 100644--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs@@ -16,6 +16,7 @@ use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult, WriteResult};use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};use cache_core::query_inspection::{CachedQueryInstance, QueryInspection};use cache_core::queue::{ClaimedMutation, MutationClaimRequest, MutationClaimToken};+use cache_core::record_selection::{RecordCursor, RecordSelection, SelectedRecordPage};use cache_core::value::EntityKey;use cache_sqlite::SqliteStorage;use serde::Serialize;@@ -206,6 +207,25 @@ impl EngineHandle {.map_err(|e| e.to_string())}+ /// Projects normalized records through a named GraphQL fragment.+ pub async fn read_records(+ &self,+ document: String,+ fragment_name: String,+ cursor: Option<RecordCursor>,+ limit: u32,+ ) -> Result<SelectedRecordPage, String> {+ let selection = RecordSelection::parse(&document, &fragment_name)+ .map_err(|error| error.to_string())?;+ self.inner+ .lock()+ .await+ .engine+ .read_records(&selection, cursor.as_ref(), limit as usize)+ .await+ .map_err(|error| error.to_string())+ }+/// Enumerates cached variants of one generated query field.pub async fn inspect_query(&self,diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rsindex 648ffd1c97..702498faec 100644--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs@@ -78,6 +78,72 @@ fn write_then_read_round_trips() {assert_eq!(data, soup_data(false));}+#[test]+fn record_selection_returns_native_cache_entities() {+ let handle = spawn_handle();+ let query = r#"query Soup($input: SoupInput!) {+ user {+ id+ soup(input: $input) {+ items {+ id+ entity {+ __typename+ ... on GraphqlSoupDocument {+ id name fileType createdAt updatedAt viewedAt deletedAt+ subType { kind isCompleted }+ }+ }+ }+ nextCursor+ hasMore+ }+ }+ }"#;+ let data = serde_json::json!({+ "user": {+ "id": "user-1",+ "soup": {+ "items": [{+ "id": "item-1",+ "entity": {+ "__typename": "GraphqlSoupDocument",+ "id": "doc-1",+ "name": "A note",+ "fileType": "md",+ "createdAt": "1970-01-01T00:00:01Z",+ "updatedAt": "1970-01-01T00:00:02Z",+ "viewedAt": "1970-01-01T00:00:03Z",+ "deletedAt": null,+ "subType": null+ }+ }],+ "nextCursor": null,+ "hasMore": false+ }+ }+ });+ block_on(handle.write(+ None,+ query.to_string(),+ Some("Soup".to_string()),+ variables(),+ data,+ None,+ ))+ .unwrap();++ let page = block_on(handle.read_records(+ "fragment Document on GraphqlSoupDocument { id name }".to_string(),+ "Document".to_string(),+ None,+ 10,+ ))+ .unwrap();+ assert_eq!(page.records, vec![serde_json::json!({"id": "doc-1", "name": "A note"})]);+ assert!(page.next_cursor.is_none());+}+#[test]fn query_inspection_serializes_generated_variables_and_value() {let handle = spawn_handle();diff --git a/apps/web/tauri/graphql_cache_plugin/src/lib.rs b/apps/web/tauri/graphql_cache_plugin/src/lib.rsindex 8e719d34e3..dbc23d0b17 100644--- a/apps/web/tauri/graphql_cache_plugin/src/lib.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/lib.rs@@ -7,9 +7,9 @@//! instance across all webviews/windows, never webview storage.//! Webviews talk to it through the commands in [`commands`] (registered//! app-level in `src-tauri`, like the bundle updater plugin) and receive-//! change notifications via the [`OPS_AFFECTED_EVENT`] broadcast event,-//! mirroring the worker `ops-affected` push: each webview's `CacheHost`-//! filters op ids by its own client prefix.+//! operation and cache change notifications via broadcast events.+//! These mirror worker pushes; each webview's `CacheHost` filters operation+//! ids by its own client prefix.//!//! Design doc: `apps/web/docs/graphql-normalized-cache-plan.md`.@@ -32,6 +32,9 @@ pub use engine::{/// the engine).pub const OPS_AFFECTED_EVENT: &str = "graphql-cache://ops-affected";+/// Broadcast event emitted whenever the effective cache view changes.+pub const CACHE_CHANGED_EVENT: &str = "graphql-cache://cache-changed";+/// Payload of [`OPS_AFFECTED_EVENT`] — mirrors the worker `CachePush`/// message in `apps/web/src/lib/graphql-cache/protocol.ts`.#[derive(Clone, Debug, Serialize)]@@ -43,6 +46,11 @@ pub struct OpsAffectedEvent {pub keys: Vec<String>,}+/// Payload of [`CACHE_CHANGED_EVENT`].+#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CacheChangedEvent {}+struct InitializedCache {scope: String,handle: EngineHandle,@@ -67,3 +75,9 @@ fn emit_ops_affected<R: Runtime>(app: &AppHandle<R>, op_ids: &[String], keys: &[.inspect_err(|e| tracing::error!(error=?e, "failed to emit graphql cache change event")).ok();}++fn emit_cache_changed<R: Runtime>(app: &AppHandle<R>) {+ app.emit(CACHE_CHANGED_EVENT, CacheChangedEvent {})+ .inspect_err(|e| tracing::error!(error=?e, "failed to emit graphql cache change event"))+ .ok();+}diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex 596114447f..a1cc9f4045 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -228,6 +228,7 @@ pub fn run() {.invoke_handler(tauri::generate_handler![graphql_cache_plugin::commands::graphql_cache_init,graphql_cache_plugin::commands::graphql_cache_read,+ graphql_cache_plugin::commands::graphql_cache_read_records,graphql_cache_plugin::commands::graphql_cache_write,graphql_cache_plugin::commands::graphql_cache_begin_optimistic_write,graphql_cache_plugin::commands::graphql_cache_inspect_query,diff --git a/crates/client/cache-core/src/denormalize.rs b/crates/client/cache-core/src/denormalize.rsindex 8544d4f09a..746ee5bce1 100644--- a/crates/client/cache-core/src/denormalize.rs+++ b/crates/client/cache-core/src/denormalize.rs@@ -60,6 +60,25 @@ pub fn denormalize(variables: &serde_json::Map<String, Json>,source: &impl RecordSource,deps: &mut BTreeSet<EntityKey>,+) -> Result<ReadOutcome, DenormalizeError> {+ denormalize_record(+ &EntityKey::root(),+ meta::QUERY_ROOT_TYPE,+ &op.selection_set,+ variables,+ source,+ deps,+ )+}++/// Projects one normalized record through a fragment selection.+pub fn denormalize_record(+ key: &EntityKey,+ type_name: &str,+ selections: &[Selection],+ variables: &serde_json::Map<String, Json>,+ source: &impl RecordSource,+ deps: &mut BTreeSet<EntityKey>,) -> Result<ReadOutcome, DenormalizeError> {let mut walk = Walk {variables,@@ -68,8 +87,7 @@ pub fn denormalize(missing_records: BTreeSet::new(),miss: None,};- let root_key = EntityKey::root();- let data = walk.read_record(&root_key, meta::QUERY_ROOT_TYPE, &op.selection_set)?;+ let data = walk.read_record(key, type_name, selections)?;if !walk.missing_records.is_empty() {return Ok(ReadOutcome::NeedRecords(walk.missing_records));@@ -79,10 +97,9 @@ pub fn denormalize(}match data {Some(json) => Ok(ReadOutcome::Complete(json)),- // Root record itself absent → nothing cached for this operation yet.None => Ok(ReadOutcome::Miss {- entity: root_key,- field: "(root)".to_string(),+ entity: key.clone(),+ field: "(record)".to_string(),}),}}diff --git a/crates/client/cache-core/src/document.rs b/crates/client/cache-core/src/document.rsindex 9547774709..04ba4fbe72 100644--- a/crates/client/cache-core/src/document.rs+++ b/crates/client/cache-core/src/document.rs@@ -73,9 +73,18 @@ pub struct Operation {pub selection_set: Vec<Selection>,}+/// Named fragment definition retained for fragment-rooted record reads.+#[derive(Debug, Clone)]+pub struct Fragment {+ pub name: String,+ pub type_condition: String,+ pub selection_set: Vec<Selection>,+}+#[derive(Debug, Clone)]pub struct Document {pub operations: Vec<Operation>,+ pub fragments: Vec<Fragment>,}impl Document {@@ -115,7 +124,7 @@ impl Document {}}}- if operations_cst.is_empty() {+ if operations_cst.is_empty() && fragments.is_empty() {return Err(DocumentError::NoOperation);}@@ -144,12 +153,43 @@ impl Document {selection_set,});}- Ok(Document { operations })++ let mut fragment_names: Vec<_> = fragments.keys().cloned().collect();+ fragment_names.sort();+ let mut converted_fragments = Vec::with_capacity(fragment_names.len());+ for name in fragment_names {+ let definition = &fragments[&name];+ let type_condition = definition+ .type_condition()+ .and_then(|condition| condition.named_type())+ .and_then(|named| named.name())+ .ok_or(DocumentError::Malformed("fragment without type condition"))?+ .text()+ .to_string();+ let selection_set = convert_selection_set(+ definition+ .selection_set()+ .ok_or(DocumentError::Malformed("fragment without selections"))?,+ &fragments,+ 0,+ )?;+ converted_fragments.push(Fragment {+ name,+ type_condition,+ selection_set,+ });+ }++ Ok(Document {+ operations,+ fragments: converted_fragments,+ })}/// Selects an operation by name (or the only one when unnamed).pub fn operation(&self, name: Option<&str>) -> Result<&Operation, DocumentError> {match name {+ None if self.operations.is_empty() => Err(DocumentError::NoOperation),None => {if self.operations.len() == 1 {Ok(&self.operations[0])@@ -166,6 +206,14 @@ impl Document {.ok_or_else(|| DocumentError::UnknownOperation(n.to_string())),}}++ /// Selects a named fragment from this document.+ pub fn fragment(&self, name: &str) -> Result<&Fragment, DocumentError> {+ self.fragments+ .iter()+ .find(|fragment| fragment.name == name)+ .ok_or_else(|| DocumentError::UnknownFragment(name.to_string()))+ }}const MAX_FRAGMENT_DEPTH: usize = 32;diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rsindex 1d07c1f626..42a756692a 100644--- a/crates/client/cache-core/src/engine.rs+++ b/crates/client/cache-core/src/engine.rs@@ -2,7 +2,9 @@//! and dependency tracking together behind the API the hosts (wasm worker ///! Tauri) expose over RPC.-use crate::denormalize::{DenormalizeError, ReadOutcome, RecordSource, denormalize};+use crate::denormalize::{+ DenormalizeError, ReadOutcome, RecordSource, denormalize, denormalize_record,+};use crate::deps::{DepIndex, OpId};use crate::document::{Document, DocumentError, OperationKind};use crate::link_patch::{@@ -19,6 +21,9 @@ use crate::queue::{NewQueuedMutation, OptimisticSource, PersistedOptimisticLayer, QueuedMutation, StoredMutation,decode_optimistic_source, encode_optimistic_source,};+use crate::record_selection::{+ RecordCursor, RecordSelection, RecordSelectionError, SelectedRecordPage, validate_limit,+};use crate::store::Storage;use crate::value::{EntityKey, Record, canonical_json};use lru::LruCache;@@ -39,6 +44,8 @@ pub enum EngineError<S: std::error::Error + 'static> {LinkPatch(#[from] LinkPatchError),#[error(transparent)]QueryInspection(#[from] QueryInspectionError),+ #[error(transparent)]+ RecordSelection(#[from] RecordSelectionError),#[error("unknown or already-settled optimistic transaction {0}")]UnknownTransaction(OptimisticTransactionId),#[error("stale claim for optimistic transaction {0}")]@@ -416,6 +423,206 @@ impl<S: Storage> Engine<S> {Ok(outcome)}+ /// Reads complete cached records selected by a named fragment.+ ///+ /// Durable and optimistic-only records are merged in ascending entity-key+ /// order. Incomplete projections are omitted, and one complete record is+ /// read ahead before a continuation cursor is returned.+ pub async fn read_records(+ &mut self,+ selection: &RecordSelection,+ cursor: Option<&RecordCursor>,+ limit: usize,+ ) -> Result<SelectedRecordPage, EngineError<S::Error>> {+ validate_limit(limit)?;+ self.hydrate_optimistic().await?;++ const SCAN_BATCH_SIZE: usize = 128;+ let after = cursor.map(RecordCursor::entity_key).cloned();+ let type_names: BTreeSet<_> = selection.type_names().iter().map(String::as_str).collect();+ let optimistic = merged_optimistic(&self.optimistic);+ let mut optimistic_candidates: BTreeSet<_> = optimistic+ .keys()+ .filter(|key| {+ after.as_ref().is_none_or(|after| *key > after)+ && record_key_type(key).is_some_and(|name| type_names.contains(name))+ })+ .cloned()+ .collect();+ let mut storage_after = after;+ let mut selected = Vec::new();+ let target = limit.saturating_add(1);++ loop {+ let rows = self+ .storage+ .scan_records(+ selection.type_names(),+ storage_after.as_ref(),+ SCAN_BATCH_SIZE,+ )+ .await+ .map_err(EngineError::Storage)?;+ let storage_exhausted = rows.len() < SCAN_BATCH_SIZE;+ let high_key = rows.last().map(|(key, _)| key.clone());+ if let Some(high_key) = &high_key {+ storage_after = Some(high_key.clone());+ }++ let mut candidates: BTreeMap<EntityKey, Option<Record>> = rows+ .into_iter()+ .map(|(key, record)| (key, Some(record)))+ .collect();+ let optimistic_in_batch: Vec<_> = if storage_exhausted {+ optimistic_candidates.iter().cloned().collect()+ } else {+ optimistic_candidates+ .iter()+ .take_while(|key| high_key.as_ref().is_some_and(|high| *key <= high))+ .cloned()+ .collect()+ };+ for key in optimistic_in_batch {+ optimistic_candidates.remove(&key);+ candidates.entry(key).or_insert(None);+ }++ let projected = self+ .project_record_batch(selection, candidates, &optimistic)+ .await?;+ selected.extend(projected);+ if selected.len() >= target || storage_exhausted {+ break;+ }+ }++ let has_more = selected.len() > limit;+ selected.truncate(limit);+ let next_cursor = has_more.then(|| {+ RecordCursor::new(+ selected+ .last()+ .expect("a page with lookahead contains a record")+ .0+ .clone(),+ )+ });+ Ok(SelectedRecordPage {+ records: selected.into_iter().map(|(_, record)| record).collect(),+ next_cursor,+ })+ }++ async fn project_record_batch(+ &mut self,+ selection: &RecordSelection,+ candidates: BTreeMap<EntityKey, Option<Record>>,+ optimistic: &BTreeMap<EntityKey, Record>,+ ) -> Result<Vec<(EntityKey, Json)>, EngineError<S::Error>> {+ let candidate_keys: Vec<_> = candidates.keys().cloned().collect();+ let optimistic_only_candidates: BTreeSet<_> = candidates+ .iter()+ .filter_map(|(key, record)| record.is_none().then_some(key.clone()))+ .collect();+ let mut fetched_base: HashMap<_, _> = candidates+ .into_iter()+ .filter_map(|(key, record)| record.map(|record| (key, record)))+ .collect();+ let mut composed = HashMap::new();+ for (key, update) in optimistic {+ let base = fetched_base.get(key).or_else(|| self.hot.peek(key));+ if let Some(base) = base {+ let mut effective = base.clone();+ effective.merge(update.clone());+ composed.insert(key.clone(), effective);+ } else if optimistic_only_candidates.contains(key) {+ composed.insert(key.clone(), update.clone());+ }+ }++ let variables = serde_json::Map::new();+ let mut pending: BTreeSet<_> = candidate_keys.iter().cloned().collect();+ let mut completed = BTreeMap::new();+ let mut known_absent = BTreeSet::new();+ while !pending.is_empty() {+ let mut missing = BTreeSet::new();+ let source = EngineSource {+ hot: &self.hot,+ fetched: &fetched_base,+ composed: &composed,+ };+ let current: Vec<_> = pending.iter().cloned().collect();+ for key in current {+ let type_name = record_key_type(&key).unwrap_or_default();+ let mut dependencies = BTreeSet::new();+ match denormalize_record(+ &key,+ type_name,+ selection.selection_set(),+ &variables,+ &source,+ &mut dependencies,+ )? {+ ReadOutcome::Complete(record) => {+ pending.remove(&key);+ completed.insert(key, record);+ }+ ReadOutcome::Miss { .. } => {+ pending.remove(&key);+ }+ ReadOutcome::NeedRecords(keys) => missing.extend(keys),+ }+ }+ if pending.is_empty() {+ break;+ }++ let to_fetch: Vec<_> = missing+ .into_iter()+ .filter(|key| {+ !known_absent.contains(key)+ && !fetched_base.contains_key(key)+ && !composed.contains_key(key)+ })+ .collect();+ if to_fetch.is_empty() {+ break;+ }+ let fetched = self+ .storage+ .get_batch(&to_fetch)+ .await+ .map_err(EngineError::Storage)?;+ for (key, record) in to_fetch.into_iter().zip(fetched) {+ match record {+ Some(record) => {+ if let Some(update) = optimistic.get(&key) {+ let mut effective = record.clone();+ effective.merge(update.clone());+ composed.insert(key.clone(), effective);+ }+ fetched_base.insert(key, record);+ }+ None => {+ if let Some(update) = optimistic.get(&key) {+ composed.insert(key, update.clone());+ } else {+ known_absent.insert(key);+ }+ }+ }+ }+ }++ for (key, record) in fetched_base {+ self.hot.put(key, record);+ }+ Ok(candidate_keys+ .into_iter()+ .filter_map(|key| completed.remove(&key).map(|record| (key, record)))+ .collect())+ }+/// Normalizes and stores a network response. Returns changed records and/// the affected active operations (excluding `origin_op`).///@@ -1100,6 +1307,10 @@ fn layer_keys(layers: &[OptimisticLayer]) -> BTreeSet<EntityKey> {.collect()}+fn record_key_type(key: &EntityKey) -> Option<&str> {+ key.0.split_once(':').map(|(type_name, _)| type_name)+}+fn deduplicate_revalidations(revalidations: impl IntoIterator<Item = QueryRevalidation>,) -> Vec<QueryRevalidation> {diff --git a/crates/client/cache-core/src/lib.rs b/crates/client/cache-core/src/lib.rsindex e60678578f..0735c73ffe 100644--- a/crates/client/cache-core/src/lib.rs+++ b/crates/client/cache-core/src/lib.rs@@ -13,5 +13,6 @@ pub mod normalize;pub mod query_inspection;mod query_path;pub mod queue;+pub mod record_selection;pub mod store;pub mod value;diff --git a/crates/client/cache-core/src/record_selection.rs b/crates/client/cache-core/src/record_selection.rsnew file mode 100644index 0000000000..557118aea4--- /dev/null+++ b/crates/client/cache-core/src/record_selection.rs@@ -0,0 +1,281 @@+//! Fragment-rooted selection over normalized cache records.+//!+//! A selection is a named GraphQL fragment whose type condition resolves+//! only to normalized entity objects. Records are returned in stable entity+//! key order and projected with the ordinary denormalizer.++use crate::document::{ArgValue, Document, DocumentError, FieldNode, Selection};+use crate::meta::{self, FieldKind, TypeKind};+use crate::value::EntityKey;+use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};+use serde_json::Value as Json;+use std::collections::BTreeSet;+use thiserror::Error;++/// Largest record-selection page accepted by the engine.+pub const MAX_RECORD_SELECTION_PAGE_SIZE: usize = 500;++/// A validated named fragment that can be applied to normalized records.+#[derive(Debug, Clone)]+pub struct RecordSelection {+ type_names: Vec<String>,+ selection_set: Vec<Selection>,+}++impl RecordSelection {+ /// Parses and validates a named fragment document.+ pub fn parse(document: &str, fragment_name: &str) -> Result<Self, RecordSelectionError> {+ let document = Document::parse(document)?;+ for fragment in &document.fragments {+ concrete_type_names(&fragment.type_condition)?;+ validate_selections(&fragment.selection_set, &fragment.type_condition)?;+ }+ let fragment = document.fragment(fragment_name)?;+ let type_names = concrete_type_names(&fragment.type_condition)?;+ if type_names.is_empty() {+ return Err(RecordSelectionError::NoConcreteTypes(+ fragment.type_condition.clone(),+ ));+ }+ for type_name in &type_names {+ let metadata = meta::type_meta(type_name)+ .ok_or_else(|| RecordSelectionError::UnknownType(type_name.clone()))?;+ if metadata.kind != TypeKind::Object || metadata.key_fields.is_none() {+ return Err(RecordSelectionError::NotNormalized(type_name.clone()));+ }+ }+ Ok(Self {+ type_names,+ selection_set: fragment.selection_set.clone(),+ })+ }++ /// Concrete normalized object type names selected by this fragment.+ pub fn type_names(&self) -> &[String] {+ &self.type_names+ }++ pub(crate) fn selection_set(&self) -> &[Selection] {+ &self.selection_set+ }+}++/// Opaque exclusive cursor into entity-key record ordering.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct RecordCursor(EntityKey);++impl RecordCursor {+ pub(crate) fn new(entity_key: EntityKey) -> Self {+ Self(entity_key)+ }++ pub(crate) fn entity_key(&self) -> &EntityKey {+ &self.0+ }+}++impl Serialize for RecordCursor {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: Serializer,+ {+ serializer.serialize_str(&encode_cursor(&self.0))+ }+}++impl<'de> Deserialize<'de> for RecordCursor {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: Deserializer<'de>,+ {+ let value = String::deserialize(deserializer)?;+ decode_cursor(&value).map(Self).map_err(D::Error::custom)+ }+}++/// One page of projected normalized records.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SelectedRecordPage {+ /// Complete fragment projections in deterministic entity-key order.+ pub records: Vec<Json>,+ /// Exclusive cursor for the next page, present only when another complete+ /// matching record exists.+ pub next_cursor: Option<RecordCursor>,+}++/// Invalid fragment selection, cursor, or page request.+#[derive(Debug, Error)]+pub enum RecordSelectionError {+ /// The GraphQL document is malformed or the requested fragment is absent.+ #[error(transparent)]+ Document(#[from] DocumentError),+ /// A type condition references a type not in the compiled schema.+ #[error("unknown schema type `{0}`")]+ UnknownType(String),+ /// An abstract type has no concrete object implementations.+ #[error("type condition `{0}` has no concrete object types")]+ NoConcreteTypes(String),+ /// A selected concrete object is embedded rather than independently keyed.+ #[error("type condition resolves to non-normalized type `{0}`")]+ NotNormalized(String),+ /// A selected field does not exist on its containing schema type.+ #[error("unknown field `{type_name}.{field}`")]+ UnknownField { type_name: String, field: String },+ /// A nested fragment can never apply within its containing type.+ #[error("type condition `{condition}` cannot apply within `{parent}`")]+ ImpossibleTypeCondition { condition: String, parent: String },+ /// Fragment record reads have no variable bindings.+ #[error("record-selection fragment references unbound variable `${0}`")]+ UnboundVariable(String),+ /// A leaf field has sub-selections or a composite field has none.+ #[error("field `{type_name}.{field}` has an invalid selection shape")]+ InvalidFieldShape { type_name: String, field: String },+ /// Page limits must be nonzero and no larger than the safety bound.+ #[error("record-selection limit must be between 1 and {max}, got {limit}")]+ InvalidLimit { limit: usize, max: usize },+}++/// Validates a requested page size.+pub fn validate_limit(limit: usize) -> Result<(), RecordSelectionError> {+ if !(1..=MAX_RECORD_SELECTION_PAGE_SIZE).contains(&limit) {+ return Err(RecordSelectionError::InvalidLimit {+ limit,+ max: MAX_RECORD_SELECTION_PAGE_SIZE,+ });+ }+ Ok(())+}++fn concrete_type_names(type_name: &str) -> Result<Vec<String>, RecordSelectionError> {+ let metadata = meta::type_meta(type_name)+ .ok_or_else(|| RecordSelectionError::UnknownType(type_name.to_string()))?;+ let mut names = match metadata.kind {+ TypeKind::Object => vec![type_name.to_string()],+ TypeKind::Interface | TypeKind::Union => metadata+ .possible_types+ .iter()+ .map(|name| (*name).to_string())+ .collect(),+ };+ names.sort();+ names.dedup();+ Ok(names)+}++fn validate_selections(+ selections: &[Selection],+ parent_type: &str,+) -> Result<(), RecordSelectionError> {+ for selection in selections {+ match selection {+ Selection::Field(field) => validate_field(field, parent_type)?,+ Selection::Fragment {+ type_condition,+ selection_set,+ } => match type_condition {+ None => validate_selections(selection_set, parent_type)?,+ Some(condition) => {+ let parent_types: BTreeSet<_> =+ concrete_type_names(parent_type)?.into_iter().collect();+ let condition_types = concrete_type_names(condition)?;+ if !condition_types+ .iter()+ .any(|type_name| parent_types.contains(type_name))+ {+ return Err(RecordSelectionError::ImpossibleTypeCondition {+ condition: condition.clone(),+ parent: parent_type.to_string(),+ });+ }+ validate_selections(selection_set, condition)?;+ }+ },+ }+ }+ Ok(())+}++fn validate_field(field: &FieldNode, parent_type: &str) -> Result<(), RecordSelectionError> {+ for (_, value) in &field.arguments {+ if let Some(variable) = referenced_variable(value) {+ return Err(RecordSelectionError::UnboundVariable(variable.to_string()));+ }+ }+ if field.name == "__typename" {+ if field.selection_set.is_empty() {+ return Ok(());+ }+ return Err(RecordSelectionError::InvalidFieldShape {+ type_name: parent_type.to_string(),+ field: field.name.clone(),+ });+ }++ let metadata = meta::field_meta(parent_type, &field.name).ok_or_else(|| {+ RecordSelectionError::UnknownField {+ type_name: parent_type.to_string(),+ field: field.name.clone(),+ }+ })?;+ match metadata.ty.kind {+ FieldKind::Composite if field.selection_set.is_empty() => {+ Err(RecordSelectionError::InvalidFieldShape {+ type_name: parent_type.to_string(),+ field: field.name.clone(),+ })+ }+ FieldKind::Composite => validate_selections(&field.selection_set, metadata.ty.name),+ FieldKind::Leaf | FieldKind::OpaqueScalar if !field.selection_set.is_empty() => {+ Err(RecordSelectionError::InvalidFieldShape {+ type_name: parent_type.to_string(),+ field: field.name.clone(),+ })+ }+ FieldKind::Leaf | FieldKind::OpaqueScalar => Ok(()),+ }+}++fn referenced_variable(value: &ArgValue) -> Option<&str> {+ match value {+ ArgValue::Variable(name) => Some(name),+ ArgValue::List(items) => items.iter().find_map(referenced_variable),+ ArgValue::Object(fields) => fields+ .iter()+ .find_map(|(_, value)| referenced_variable(value)),+ ArgValue::Const(_) => None,+ }+}++fn encode_cursor(entity_key: &EntityKey) -> String {+ let encoded: String = entity_key+ .0+ .as_bytes()+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect();+ format!("r1.{encoded}")+}++fn decode_cursor(value: &str) -> Result<EntityKey, &'static str> {+ let encoded = value+ .strip_prefix("r1.")+ .ok_or("invalid record-selection cursor")?;+ if encoded.is_empty() || !encoded.len().is_multiple_of(2) {+ return Err("invalid record-selection cursor");+ }+ let bytes = encoded+ .as_bytes()+ .chunks_exact(2)+ .map(|pair| {+ let pair = std::str::from_utf8(pair).map_err(|_| "invalid record-selection cursor")?;+ u8::from_str_radix(pair, 16).map_err(|_| "invalid record-selection cursor")+ })+ .collect::<Result<Vec<_>, _>>()?;+ String::from_utf8(bytes)+ .map(EntityKey)+ .map_err(|_| "invalid record-selection cursor")+}++#[cfg(test)]+mod test;diff --git a/crates/client/cache-core/src/record_selection/test.rs b/crates/client/cache-core/src/record_selection/test.rsnew file mode 100644index 0000000000..5620549045--- /dev/null+++ b/crates/client/cache-core/src/record_selection/test.rs@@ -0,0 +1,114 @@+use super::*;++#[test]+fn accepts_fragment_only_object_document() {+ let selection = RecordSelection::parse(+ r#"+ fragment SoupItemFields on GraphqlSoupItem {+ itemId: id+ entityType+ entity {+ __typename+ ... on GraphqlSoupDocument { id name }+ ... on GraphqlSoupChat { id name }+ }+ }+ "#,+ "SoupItemFields",+ )+ .unwrap();++ assert_eq!(selection.type_names(), &["GraphqlSoupItem"]);+}++#[test]+fn accepts_normalized_union_selection() {+ let selection = RecordSelection::parse(+ r#"+ fragment SoupEntities on GraphqlSoupEntity {+ __typename+ ... on GraphqlSoupDocument { id name }+ ... on GraphqlSoupChat { id name }+ }+ "#,+ "SoupEntities",+ )+ .unwrap();++ assert!(+ selection+ .type_names()+ .contains(&"GraphqlSoupDocument".to_string())+ );+ assert!(+ selection+ .type_names()+ .contains(&"GraphqlSoupChat".to_string())+ );+}++#[test]+fn rejects_embedded_root_and_unbound_variables() {+ let embedded =+ RecordSelection::parse("fragment Page on SoupPage { nextCursor }", "Page").unwrap_err();+ assert!(matches!(+ embedded,+ RecordSelectionError::NotNormalized(ref name) if name == "SoupPage"+ ));++ let variable = RecordSelection::parse(+ r#"fragment UserSoup on GraphqlUser {+ soup(input: $input) { nextCursor }+ }"#,+ "UserSoup",+ )+ .unwrap_err();+ assert!(matches!(+ variable,+ RecordSelectionError::UnboundVariable(ref name) if name == "input"+ ));+}++#[test]+fn rejects_unknown_fragment_and_type() {+ assert!(matches!(+ RecordSelection::parse("fragment Item on GraphqlSoupItem { id }", "Missing"),+ Err(RecordSelectionError::Document(+ DocumentError::UnknownFragment(_)+ ))+ ));+ assert!(matches!(+ RecordSelection::parse("fragment Item on MissingType { id }", "Item"),+ Err(RecordSelectionError::UnknownType(_))+ ));+ assert!(matches!(+ RecordSelection::parse(+ "fragment Item on GraphqlSoupItem { id } fragment Unused on MissingType { id }",+ "Item",+ ),+ Err(RecordSelectionError::UnknownType(_))+ ));+}++#[test]+fn validates_page_limits() {+ assert!(matches!(+ validate_limit(0),+ Err(RecordSelectionError::InvalidLimit { .. })+ ));+ validate_limit(MAX_RECORD_SELECTION_PAGE_SIZE).unwrap();+ assert!(matches!(+ validate_limit(MAX_RECORD_SELECTION_PAGE_SIZE + 1),+ Err(RecordSelectionError::InvalidLimit { .. })+ ));+}++#[test]+fn cursor_has_opaque_roundtrip() {+ let cursor = RecordCursor::new(EntityKey("GraphqlSoupItem:item-1".to_string()));+ let encoded = serde_json::to_value(&cursor).unwrap();+ assert_eq!(+ serde_json::from_value::<RecordCursor>(encoded).unwrap(),+ cursor+ );+}diff --git a/crates/client/cache-core/src/store.rs b/crates/client/cache-core/src/store.rsindex 2374680f86..c079b2d87a 100644--- a/crates/client/cache-core/src/store.rs+++ b/crates/client/cache-core/src/store.rs@@ -38,6 +38,15 @@ pub trait Storage: MaybeSend {keys: &[EntityKey],) -> impl Future<Output = Result<(), Self::Error>> + MaybeSend;+ /// Scans normalized records of the requested concrete types in ascending+ /// entity-key order. `after` is exclusive.+ fn scan_records(+ &self,+ type_names: &[String],+ after: Option<&EntityKey>,+ limit: usize,+ ) -> impl Future<Output = Result<Vec<(EntityKey, Record)>, Self::Error>> + MaybeSend;+/// Atomically appends a mutation and its optimistic layer to the queue.fn enqueue_mutation(&mut self,@@ -138,6 +147,33 @@ impl Storage for InMemoryStorage {Ok(())}+ async fn scan_records(+ &self,+ type_names: &[String],+ after: Option<&EntityKey>,+ limit: usize,+ ) -> Result<Vec<(EntityKey, Record)>, Self::Error> {+ if limit == 0 || type_names.is_empty() {+ return Ok(Vec::new());+ }+ let type_names: std::collections::HashSet<_> =+ type_names.iter().map(String::as_str).collect();+ let mut records: Vec<_> = self+ .records+ .iter()+ .filter(|(key, _)| after.is_none_or(|after| *key > after))+ .filter(|(key, _)| {+ key.0+ .split_once(':')+ .is_some_and(|(type_name, _)| type_names.contains(type_name))+ })+ .map(|(key, record)| (key.clone(), record.clone()))+ .collect();+ records.sort_by(|(left, _), (right, _)| left.cmp(right));+ records.truncate(limit);+ Ok(records)+ }+async fn enqueue_mutation(&mut self,entry: NewQueuedMutation,diff --git a/crates/client/cache-core/tests/record_selection.rs b/crates/client/cache-core/tests/record_selection.rsnew file mode 100644index 0000000000..9508b061d6--- /dev/null+++ b/crates/client/cache-core/tests/record_selection.rs@@ -0,0 +1,298 @@+use cache_core::engine::{BeginOptimisticWrite, Engine};+use cache_core::record_selection::RecordSelection;+use cache_core::store::{InMemoryStorage, Storage};+use cache_core::value::{CacheValue, EntityKey, Record};+use pollster::block_on;+use serde_json::{Value as Json, json};+use std::collections::BTreeMap;++fn record(type_name: &str, fields: impl IntoIterator<Item = (&'static str, CacheValue)>) -> Record {+ let mut values = BTreeMap::from([(+ "__typename".to_string(),+ CacheValue::String(type_name.to_string()),+ )]);+ values.extend(+ fields+ .into_iter()+ .map(|(name, value)| (name.to_string(), value)),+ );+ Record { fields: values }+}++fn key(value: &str) -> EntityKey {+ EntityKey(value.to_string())+}++fn item(id: &str, entity: Option<EntityKey>) -> (EntityKey, Record) {+ let mut fields = vec![("id", CacheValue::String(id.to_string()))];+ if let Some(entity) = entity {+ fields.push(("entity", CacheValue::Ref(entity)));+ }+ (+ key(&format!("GraphqlSoupItem:{id}")),+ record("GraphqlSoupItem", fields),+ )+}++fn document(id: &str, name: &str) -> (EntityKey, Record) {+ (+ key(&format!("GraphqlSoupDocument:{id}")),+ record(+ "GraphqlSoupDocument",+ [+ ("id", CacheValue::String(id.to_string())),+ ("name", CacheValue::String(name.to_string())),+ ],+ ),+ )+}++const ITEM_FRAGMENT: &str = r#"+fragment SoupItemFields on GraphqlSoupItem {+ itemId: id+ entity {+ __typename+ ... on GraphqlSoupDocument {+ id+ documentName: name+ }+ }+}+"#;++#[test]+fn projects_cold_links_skips_incomplete_and_paginates_exclusively() {+ block_on(async {+ let mut storage = InMemoryStorage::new();+ storage+ .put_batch(vec![+ item("a", Some(key("GraphqlSoupDocument:a"))),+ item("b", None),+ item("c", Some(key("GraphqlSoupDocument:c"))),+ document("a", "Alpha"),+ document("c", "Charlie"),+ ])+ .await+ .unwrap();+ let mut engine = Engine::with_capacity(storage, 1);+ let selection = RecordSelection::parse(ITEM_FRAGMENT, "SoupItemFields").unwrap();++ let first = engine.read_records(&selection, None, 1).await.unwrap();+ assert_eq!(+ first.records,+ vec![json!({+ "itemId": "a",+ "entity": {+ "__typename": "GraphqlSoupDocument",+ "id": "a",+ "documentName": "Alpha"+ }+ })]+ );+ assert!(first.next_cursor.is_some());++ let second = engine+ .read_records(&selection, first.next_cursor.as_ref(), 1)+ .await+ .unwrap();+ assert_eq!(second.records[0]["itemId"], json!("c"));+ assert_eq!(+ second.records[0]["entity"]["documentName"],+ json!("Charlie")+ );+ assert!(second.next_cursor.is_none());+ });+}++#[test]+fn reads_object_and_union_fragments_in_entity_key_order() {+ block_on(async {+ let mut storage = InMemoryStorage::new();+ storage+ .put_batch(vec![+ document("b", "Beta"),+ document("a", "Alpha"),+ (+ key("GraphqlSoupChat:c"),+ record(+ "GraphqlSoupChat",+ [+ ("id", CacheValue::String("c".to_string())),+ ("name", CacheValue::String("Chat".to_string())),+ ],+ ),+ ),+ ])+ .await+ .unwrap();+ let mut engine = Engine::new(storage);+ let selection = RecordSelection::parse(+ r#"fragment Entity on GraphqlSoupEntity {+ __typename+ ... on GraphqlSoupDocument { id name }+ ... on GraphqlSoupChat { id name }+ }"#,+ "Entity",+ )+ .unwrap();++ let page = engine.read_records(&selection, None, 10).await.unwrap();+ assert_eq!(+ page.records+ .iter()+ .map(|record| record["id"].as_str().unwrap())+ .collect::<Vec<_>>(),+ vec!["c", "a", "b"]+ );+ assert!(page.next_cursor.is_none());+ });+}++#[test]+fn merges_optimistic_updates_with_cold_linked_bases() {+ block_on(async {+ let property_key = key("GraphqlProperty:property-1");+ let document_key = key("GraphqlSoupDocument:doc-1");+ let mut storage = InMemoryStorage::new();+ storage+ .put_batch(vec![+ item("item-1", Some(document_key.clone())),+ (+ document_key,+ record(+ "GraphqlSoupDocument",+ [+ ("id", CacheValue::String("doc-1".to_string())),+ (+ "properties",+ CacheValue::List(vec![CacheValue::Ref(property_key.clone())]),+ ),+ ],+ ),+ ),+ (+ property_key,+ record(+ "GraphqlProperty",+ [+ ("id", CacheValue::String("property-1".to_string())),+ (+ "propertyDefinitionId",+ CacheValue::String("definition-1".to_string()),+ ),+ ("displayName", CacheValue::String("Old".to_string())),+ ],+ ),+ ),+ ])+ .await+ .unwrap();+ let mut engine = Engine::with_capacity(storage, 1);+ let selection = RecordSelection::parse(+ r#"fragment Item on GraphqlSoupItem {+ id+ entity {+ ... on GraphqlSoupDocument {+ properties { id propertyDefinitionId displayName }+ }+ }+ }"#,+ "Item",+ )+ .unwrap();+ let mutation = r#"mutation SetProperty($input: SetEntityPropertyInput!) {+ setEntityProperty(input: $input) { id displayName }+ }"#;+ let Json::Object(variables) = json!({+ "input": {+ "entityType": "DOCUMENT",+ "entityId": "doc-1",+ "propertyDefinitionId": "definition-1"+ }+ }) else {+ unreachable!()+ };+ engine+ .begin_optimistic_write(+ None,+ BeginOptimisticWrite {+ query: mutation,+ operation_name: Some("SetProperty"),+ variables: &variables,+ data: &json!({+ "setEntityProperty": {+ "id": "property-1",+ "displayName": "Optimistic"+ }+ }),+ link_patches: &[],+ revalidations: &[],+ created_at_ms: 1,+ },+ )+ .await+ .unwrap();++ let page = engine.read_records(&selection, None, 10).await.unwrap();+ assert_eq!(page.records.len(), 1);+ assert_eq!(+ page.records[0]["entity"]["properties"][0],+ json!({+ "id": "property-1",+ "propertyDefinitionId": "definition-1",+ "displayName": "Optimistic"+ })+ );+ });+}++#[test]+fn includes_optimistic_only_records() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ let selection = RecordSelection::parse(+ "fragment Property on GraphqlProperty { id displayName }",+ "Property",+ )+ .unwrap();+ let mutation = r#"mutation SetProperty($input: SetEntityPropertyInput!) {+ setEntityProperty(input: $input) { id displayName }+ }"#;+ let Json::Object(variables) = json!({+ "input": {+ "entityType": "DOCUMENT",+ "entityId": "doc-1",+ "propertyDefinitionId": "definition-1",+ "value": { "string": "todo" }+ }+ }) else {+ unreachable!()+ };+ engine+ .begin_optimistic_write(+ None,+ BeginOptimisticWrite {+ query: mutation,+ operation_name: Some("SetProperty"),+ variables: &variables,+ data: &json!({+ "setEntityProperty": {+ "id": "property-1",+ "displayName": "Status"+ }+ }),+ link_patches: &[],+ revalidations: &[],+ created_at_ms: 1,+ },+ )+ .await+ .unwrap();++ let page = engine.read_records(&selection, None, 10).await.unwrap();+ assert_eq!(+ page.records,+ vec![json!({"id": "property-1", "displayName": "Status"})]+ );+ });+}diff --git a/crates/client/cache-idb/src/idb_storage.rs b/crates/client/cache-idb/src/idb_storage.rsindex de712bc44e..3c26815189 100644--- a/crates/client/cache-idb/src/idb_storage.rs+++ b/crates/client/cache-idb/src/idb_storage.rs@@ -8,7 +8,10 @@ use cache_core::queue::{};use cache_core::store::Storage;use cache_core::value::{EntityKey, Record};-use idb::{Database, DatabaseEvent, Factory, ObjectStoreParams, TransactionMode};+use idb::{+ CursorDirection, Database, DatabaseEvent, Factory, KeyRange, ObjectStoreParams, Query,+ TransactionMode,+};use thiserror::Error;use wasm_bindgen::{JsCast, JsValue};@@ -236,6 +239,65 @@ impl Storage for IdbStorage {Ok(())}+ async fn scan_records(+ &self,+ type_names: &[String],+ after: Option<&EntityKey>,+ limit: usize,+ ) -> Result<Vec<(EntityKey, Record)>, Self::Error> {+ if type_names.is_empty() || limit == 0 {+ return Ok(Vec::new());+ }++ let mut type_names = type_names.to_vec();+ type_names.sort();+ type_names.dedup();+ let mut records = Vec::with_capacity(limit);+ for type_name in type_names {+ if records.len() == limit {+ break;+ }+ let prefix = format!("{type_name}:");+ let upper = format!("{type_name};");+ if after.is_some_and(|after| after.0.as_str() >= upper.as_str()) {+ continue;+ }+ let (lower, lower_open) = match after {+ Some(after) if after.0.as_str() >= prefix.as_str() => (after.0.as_str(), true),+ _ => (prefix.as_str(), false),+ };+ let range = KeyRange::bound(+ &JsValue::from_str(lower),+ &JsValue::from_str(&upper),+ Some(lower_open),+ Some(true),+ )?;+ let tx = self+ .db+ .transaction(&[RECORDS_STORE], TransactionMode::ReadOnly)?;+ let store = tx.object_store(RECORDS_STORE)?;+ let Some(cursor) = store+ .open_cursor(Some(Query::from(range)), Some(CursorDirection::Next))?+ .await?+ else {+ continue;+ };+ let mut cursor = cursor.into_managed();+ while records.len() < limit {+ let Some(key) = cursor.key()? else {+ break;+ };+ let Some(value) = cursor.value()? else {+ break;+ };+ let key = key.as_string().ok_or(IdbStorageError::NotString)?;+ records.push((EntityKey(key), decode_record(&bytes_from_js(value)?)?));+ cursor.next(None).await?;+ }+ }+ Ok(records)+ }+async fn enqueue_mutation(&mut self,entry: NewQueuedMutation,diff --git a/crates/client/cache-idb/src/lib.rs b/crates/client/cache-idb/src/lib.rsindex 38c595e083..cd087dc67c 100644--- a/crates/client/cache-idb/src/lib.rs+++ b/crates/client/cache-idb/src/lib.rs@@ -4,7 +4,8 @@//! One stable IndexedDB database per cache scope. Disposable normalized//! records are versioned through metadata, while queued mutations and their//! optimistic layers remain discoverable across record-schema changes.-//! Postcard payloads are stored as `Uint8Array` values.+//! Postcard payloads are stored in indexable record envelopes whose `value`+//! property is a `Uint8Array`.//!//! wasm32-only; on other targets this crate is an empty shell so workspace//! `cargo test` stays green.diff --git a/crates/client/cache-idb/tests/web.rs b/crates/client/cache-idb/tests/web.rsindex 150d948db0..0f2a532eba 100644--- a/crates/client/cache-idb/tests/web.rs+++ b/crates/client/cache-idb/tests/web.rs@@ -9,6 +9,7 @@ use cache_core::queue::{MutationClaimRequest, MutationClaimToken, MutationRequest, NewQueuedMutation,PersistedOptimisticLayer, StoredMutation,};+use cache_core::record_selection::RecordSelection;use cache_core::store::Storage;use cache_core::value::{CacheValue, EntityKey, Record};use cache_idb::IdbStorage;@@ -73,6 +74,45 @@ async fn put_get_delete_roundtrip() {assert!(s.get_batch(&[key("B:2")]).await.unwrap()[0].is_none());}+#[wasm_bindgen_test]+async fn scans_selected_record_types_in_key_order() {+ let scope = "test-record-scan";+ IdbStorage::destroy(scope).await.unwrap();+ let mut storage = IdbStorage::open(scope).await.unwrap();+ storage+ .put_batch(vec![+ (key("TypeB:2"), record("b2")),+ (key("Other:1"), record("other")),+ (key("TypeA:2"), record("a2")),+ (key("TypeA:1"), record("a1")),+ ])+ .await+ .unwrap();++ let first = storage+ .scan_records(&["TypeB".into(), "TypeA".into()], None, 2)+ .await+ .unwrap();+ assert_eq!(+ first+ .iter()+ .map(|(key, _)| key.0.as_str())+ .collect::<Vec<_>>(),+ vec!["TypeA:1", "TypeA:2"]+ );+ let second = storage+ .scan_records(&["TypeA".into(), "TypeB".into()], Some(&first[1].0), 2)+ .await+ .unwrap();+ assert_eq!(+ second+ .iter()+ .map(|(key, _)| key.0.as_str())+ .collect::<Vec<_>>(),+ vec!["TypeB:2"]+ );+}+#[wasm_bindgen_test]async fn persists_across_reopen() {IdbStorage::destroy("test-persist").await.unwrap();@@ -156,4 +196,10 @@ async fn engine_over_idb() {panic!("expected hit");};assert_eq!(cached, data);++ let selection =+ RecordSelection::parse("fragment Item on GraphqlSoupItem { id }", "Item").unwrap();+ let page = engine.read_records(&selection, None, 10).await.unwrap();+ assert_eq!(page.records, vec![serde_json::json!({"id": "doc-1"})]);+ assert!(page.next_cursor.is_none());}diff --git a/crates/client/cache-sqlite/src/lib.rs b/crates/client/cache-sqlite/src/lib.rsindex 9e26dbbdec..83df316cab 100644--- a/crates/client/cache-sqlite/src/lib.rs+++ b/crates/client/cache-sqlite/src/lib.rs@@ -22,7 +22,7 @@ use cache_core::queue::{};use cache_core::store::Storage;use cache_core::value::{EntityKey, Record};-use rusqlite::{Connection, OptionalExtension, Transaction, params};+use rusqlite::{Connection, OptionalExtension, Transaction, params, params_from_iter};use std::path::Path;use std::sync::{Mutex, MutexGuard};use thiserror::Error;@@ -268,6 +268,47 @@ impl Storage for SqliteStorage {Ok(())}+ async fn scan_records(+ &self,+ type_names: &[String],+ after: Option<&EntityKey>,+ limit: usize,+ ) -> Result<Vec<(EntityKey, Record)>, Self::Error> {+ if type_names.is_empty() || limit == 0 {+ return Ok(Vec::new());+ }++ let mut sql = String::from("SELECT key, value FROM records WHERE ");+ let mut values = Vec::<rusqlite::types::Value>::new();+ if let Some(after) = after {+ sql.push_str("key > ? AND ");+ values.push(after.0.clone().into());+ }+ sql.push('(');+ for (index, type_name) in type_names.iter().enumerate() {+ if index > 0 {+ sql.push_str(" OR ");+ }+ sql.push_str("(key >= ? AND key < ?)");+ values.push(format!("{type_name}:").into());+ values.push(format!("{type_name};").into());+ }+ sql.push_str(") ORDER BY key ASC LIMIT ?");+ values.push(i64::try_from(limit).unwrap_or(i64::MAX).into());++ let conn = self.conn();+ let mut statement = conn.prepare(&sql)?;+ let rows = statement.query_map(params_from_iter(values.iter()), |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?))+ })?;+ let mut records = Vec::new();+ for row in rows {+ let (key, value) = row?;+ records.push((EntityKey(key), decode_record(&value)?));+ }+ Ok(records)+ }+async fn enqueue_mutation(&mut self,entry: NewQueuedMutation,@@ -553,6 +594,45 @@ mod tests {});}+ #[test]+ fn scans_selected_record_types_in_key_order() {+ block_on(async {+ let mut storage = SqliteStorage::open_in_memory("user-1").unwrap();+ storage+ .put_batch(vec![+ (key("TypeB:2"), record("b2")),+ (key("Other:1"), record("other")),+ (key("TypeA:2"), record("a2")),+ (key("TypeA:1"), record("a1")),+ ])+ .await+ .unwrap();++ let first = storage+ .scan_records(&["TypeB".into(), "TypeA".into()], None, 2)+ .await+ .unwrap();+ assert_eq!(+ first+ .iter()+ .map(|(key, _)| key.0.as_str())+ .collect::<Vec<_>>(),+ vec!["TypeA:1", "TypeA:2"]+ );+ let second = storage+ .scan_records(&["TypeA".into(), "TypeB".into()], Some(&first[1].0), 2)+ .await+ .unwrap();+ assert_eq!(+ second+ .iter()+ .map(|(key, _)| key.0.as_str())+ .collect::<Vec<_>>(),+ vec!["TypeB:2"]+ );+ });+ }+#[test]fn persists_across_reopen_same_namespace() {block_on(async {diff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.tomlindex cf51443089..bde03fce07 100644--- a/crates/client/cache-wasm/Cargo.toml+++ b/crates/client/cache-wasm/Cargo.toml@@ -2,7 +2,7 @@edition = "2024"name = "cache-wasm"publish = false-version = "0.2.0"+version = "0.3.0"[lib]crate-type = ["cdylib", "rlib"]diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rsindex 08f4398023..66704e75c8 100644--- a/crates/client/cache-wasm/src/shell.rs+++ b/crates/client/cache-wasm/src/shell.rs@@ -4,6 +4,7 @@ use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult};use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};use cache_core::query_inspection::QueryInspection;use cache_core::queue::{ClaimedMutation, MutationClaimRequest, MutationClaimToken};+use cache_core::record_selection::{RecordCursor, RecordSelection};use cache_core::value::EntityKey;use cache_idb::IdbStorage;use serde::{Deserialize, Serialize};@@ -189,6 +190,16 @@ fn parse_variables(serde_wasm_bindgen::from_value(variables).map_err(err_js)}+fn parse_record_cursor(cursor: JsValue) -> Result<Option<RecordCursor>, JsValue> {+ if cursor.is_undefined() || cursor.is_null() {+ Ok(None)+ } else {+ serde_wasm_bindgen::from_value(cursor)+ .map(Some)+ .map_err(err_js)+ }+}+fn parse_vec<T: serde::de::DeserializeOwned>(value: JsValue) -> Result<Vec<T>, JsValue> {if value.is_undefined() || value.is_null() {return Ok(Vec::new());@@ -226,6 +237,29 @@ impl CacheEngine {})}+ /// Projects normalized records through a named GraphQL fragment.+ #[wasm_bindgen(js_name = readRecords)]+ pub fn read_records(+ &self,+ document: String,+ fragment_name: String,+ cursor: JsValue,+ limit: u32,+ ) -> js_sys::Promise {+ let engine = self.engine.clone();+ future_to_promise(async move {+ let selection = RecordSelection::parse(&document, &fragment_name).map_err(err_js)?;+ let cursor = parse_record_cursor(cursor)?;+ let page = engine+ .lock()+ .await+ .read_records(&selection, cursor.as_ref(), limit as usize)+ .await+ .map_err(err_js)?;+ to_js(&page)+ })+ }+/// Normalizes and stores a network response. Resolves to/// `{changed: string[], affectedOps: string[], reset: boolean}` —/// `affectedOps` are the registered operation ids (excludingdiff --git a/docs/cache-record-selection-plan.md b/docs/cache-record-selection-plan.mdnew file mode 100644index 0000000000..b74444f44e--- /dev/null+++ b/docs/cache-record-selection-plan.md@@ -0,0 +1,173 @@+# Cache Record Selection Implementation Plan++## Proposed API++```ts+const selection = selectRecords(SoupItemFieldsFragmentDoc);++const page = await readRecords(cacheHost, selection, {+ cursor,+ limit: 500,+});+```++```ts+type SelectedRecordPage<T> = {+ records: T[];+ nextCursor: string | null;+};+```++`nextCursor` is present only when another complete matching record exists.++## Implementation plan++### 1. Remove the schema-specific entity index++- Delete `cache-core::entity_index` and its tests.+- Remove bucket, timestamp, search-text, scoring, counting, and snapshot APIs.+- Restore ordinary record persistence in:+ - `cache-idb`+ - `cache-sqlite`+ - `cache-wasm`+- Remove `queryIndexedItems` from WASM, Tauri, worker, host, and protocol layers.+- Remove projected SQLite columns and IndexedDB envelopes/indexes.+- Restore the unreleased feature-branch storage versions rather than supporting migration from them; normalized records are disposable.++### 2. Add generic fragment-based record selection++In `cache-core`:++- Extend document parsing to support named, fragment-only documents.+- Add a `record_selection` module containing:+ - Fragment validation.+ - Object/interface/union type-condition resolution.+ - Validation that selected concrete types are normalized entities.+ - Cursor and page models.+- Reject:+ - Unknown fragments or schema types.+ - Embedded/non-normalized type conditions.+ - Unbound variables in fragment fields.+ - Invalid or excessive page limits.++Add:++```rust+Engine::read_records(selection, cursor, limit)+```++The engine will:++1. Derive concrete type names from the fragment condition.+2. Iterate matching records in deterministic entity-key order.+3. Apply the fragment projection using normal denormalization.+4. Load linked cold records in batches.+5. Read the effective view, including optimistic layers.+6. Skip records that cannot satisfy the complete fragment.+7. Use one-record lookahead to decide whether to return `nextCursor`.++### 3. Add schema-neutral storage iteration++Replace the specialized index methods with one generic storage capability:++```rust+scan_records(type_names, after, limit)+```++Implement it for:++- `InMemoryStorage`+- SQLite, using ordered primary-key ranges+- IndexedDB, using object-store key cursors++No schema field names or application-level ordering metadata will be persisted.++### 4. Surface the API through every host++Add `readRecords` across:++- `cache-wasm`+- SharedWorker protocol and worker core+- Tauri commands/plugin+- `CacheHost`+- No-op host++Wire input contains only:++- Serialized fragment document+- Fragment name+- Opaque cursor+- Limit++Wire output contains only selected JSON records and `nextCursor`.++### 5. Add the typed frontend selection API++Create `exchange/record-selection.ts` with:++- `selectRecords(fragmentDocument)`+- `readRecords(host, selection, options)`+- Generated result-type inference+- Fragment-name extraction+- Defensive wire-result validation++Export it from `@graphql-cache/index`.++### 6. Replace index notifications++Replace `onEntityIndexChanged` with schema-neutral `onCacheChanged`.++Emit it for:++- Normal writes+- Optimistic writes and settlements+- External invalidations+- Queue refreshes that change the effective view+- Cache clears/resets++Record-selection consumers can invalidate and rerun without cache-core knowing their schema.++### 7. Adapt Quick Access++- Select cached `GraphqlSoupItem` records using the existing generated `SoupItemFieldsFragmentDoc`.+- Export/reuse the existing GraphQL Soup item mapper.+- Load record pages and map them into `QuickAccessItem`s.+- Perform bucket filtering, timestamp sorting, fuzzy search, counts, and visible-page slicing entirely in TypeScript.+- Make `loadMore` increase the locally visible slice after records have been loaded.+- Rename index-specific files, query keys, and flags to record-selection terminology.+- Remove indexed-snapshot mapping and tests.++### 8. Tests and verification++Add coverage for:++- Object and union fragment selection.+- Aliases and nested linked records.+- Cold storage reads.+- Optimistic records and updates.+- Incomplete-record omission.+- Stable, exclusive cursor pagination.+- `nextCursor` lookahead semantics.+- SQLite and IndexedDB parity.+- WASM, worker, Tauri, and no-op host transport.+- TypeScript result inference and malformed responses.+- Quick Access filtering, sorting, searching, counting, and pagination.++Verification:++```bash+cargo fmt+cargo test -p cache-core+cargo test -p cache-sqlite+cargo test -p graphql_cache_plugin+cargo check --target wasm32-unknown-unknown -p cache-idb -p cache-wasm --all-targets+wasm-pack test --headless --chrome crates/client/cache-idb+```++Then run focused web tests and `bun check` from `apps/web`.++Implementation will proceed incrementally: verify the generic Rust API first, then wire and consume it in Quick Access. After successful verification, create the required `jj` revision.++## Architecture check++Hexagonal boundaries were checked: these are client cache/transport adapters with no server-domain authorization or business-policy movement.