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
refactor(soup): rework group by to better support optimistic updates (#3565)
dev-rb3bcd9c910cd1
diff --git a/js/app/packages/app/component/next-soup/create-soup-state.ts b/js/app/packages/app/component/next-soup/create-soup-state.tsindex 8f16aae2e7..79f7711d53 100644--- a/js/app/packages/app/component/next-soup/create-soup-state.ts+++ b/js/app/packages/app/component/next-soup/create-soup-state.ts@@ -28,9 +28,6 @@ export type GroupMeta = {count: number;isExpanded: () => boolean;toggle: () => void;- hasMore: () => boolean;- loadMore: () => Promise<void>;- isLoading: () => boolean;renderHeader?: (props: GroupHeaderProps) => JSX.Element;};diff --git a/js/app/packages/app/component/next-soup/soup-view/create-grouped-soup-queries.ts b/js/app/packages/app/component/next-soup/soup-view/create-grouped-soup-queries.tsnew file mode 100644index 0000000000..207cd17c6a--- /dev/null+++ b/js/app/packages/app/component/next-soup/soup-view/create-grouped-soup-queries.ts@@ -0,0 +1,162 @@+import { createInfiniteQueries } from '@app/component/next-soup/soup-view/create-infinite-queries';+import { throwOnErr } from '@core/util/result';+import type { EntityData } from '@entity';+import {+ parseGroupMeta,+ serializeGroupByField,+} from '@queries/soup/grouped/api';+import type { GroupByField, GroupMeta } from '@queries/soup/grouped/types';+import type {+ SoupApiItemFilter,+ SoupAstBody,+ SoupAstItemsGroupedPage,+ SoupParams,+} from '@queries/soup/items';+import { soupKeys } from '@queries/soup/keys';+import {+ isDisplayableSoupItem,+ isInstructionsMdDoc,+ mapApiSoupItemToEntity,+} from '@queries/soup/transform-utils';+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';+import { storageServiceClient } from '@service-storage/client';+import type { SoupApiItem } from '@service-storage/generated/schemas';+import type { Accessor } from 'solid-js';++type InitialGroupPage = {+ items: SoupAstItemsGroupedPage['items'];+ groups: GroupMeta[];+};++export type GroupQueryPage = {+ items: InitialGroupPage['items'];+ group: GroupMeta;+};++type GroupQueryData = {+ group: GroupMeta;+ entities: EntityData[];+};++type CreateGroupedSoupQueriesArgs = {+ initialPage: Accessor<InitialGroupPage | undefined>;+ groupByField: Accessor<GroupByField | undefined>;+ soupParams: Accessor<SoupParams>;+ soupBody: Accessor<SoupAstBody>;+ queryOptions: Accessor<{+ enabled?: boolean;+ meta?: {+ groupBy?: GroupByField;+ groupKey?: string;+ itemFilter?: SoupApiItemFilter;+ };+ }>;+};++export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {+ const instructionsIdQuery = useInstructionsMdIdQuery();++ const mapItemToEntity = (item: SoupApiItem) => {+ if (!isDisplayableSoupItem(item)) return;+ if (isInstructionsMdDoc(item, instructionsIdQuery)) return;++ return mapApiSoupItemToEntity(item);+ };++ const combineGroupPages = (+ pages: GroupQueryPage[],+ itemFilter: SoupApiItemFilter | undefined+ ): GroupQueryData | undefined => {+ let group: GroupMeta | undefined;+ let items: Record<string, SoupApiItem> = {};++ for (const page of pages) {+ group = group+ ? {+ ...page.group,+ itemIds: [...group.itemIds, ...page.group.itemIds],+ }+ : page.group;+ items = { ...items, ...page.items };+ }++ if (!group) return;++ const entities: EntityData[] = [];+ for (const id of group.itemIds) {+ const item = items[id];+ if (!item) continue;+ if (itemFilter && !itemFilter(item)) continue;++ const entity = mapItemToEntity(item);+ if (entity) entities.push(entity);+ }++ return { group, entities };+ };++ return createInfiniteQueries<GroupQueryPage, GroupQueryData | undefined>(+ () => {+ const field = args.groupByField();+ const initialGroupedPage = args.initialPage();++ if (!field || !initialGroupedPage) {+ return [];+ }++ const options = args.queryOptions();++ return initialGroupedPage.groups.map((group) => {+ const initialPage = { items: initialGroupedPage.items, group };++ return {+ key: group.key,+ queryKey: soupKeys.groupedGroup({+ params: args.soupParams(),+ body: args.soupBody(),+ groupBy: field,+ groupKey: group.key,+ }).queryKey,+ queryFn: async (ctx: { pageParam: string | null }) => {+ if (ctx.pageParam == null) {+ return initialPage;+ }++ const response = await throwOnErr(async () =>+ storageServiceClient.getGroupedSoupAstGroupPage({+ params: {+ cursor: ctx.pageParam ?? undefined,+ group_by: serializeGroupByField(field),+ group_key: group.key,+ limit: args.soupParams().limit,+ },+ body: args.soupBody(),+ })+ );++ return {+ items: response.items,+ group: parseGroupMeta(response.group),+ };+ },+ getNextPageParam: (lastPage: GroupQueryPage): string | null => {+ return lastPage.group.nextCursor;+ },+ placeholderData: {+ pages: [initialPage],+ pageParams: [null],+ },+ select: (pages) => combineGroupPages(pages, options.meta?.itemFilter),+ enabled: options.enabled,+ meta: {+ ...options.meta,+ groupBy: field,+ groupKey: group.key,+ normalize: true,+ },+ staleTime: Infinity,+ };+ });+ }+ );+}diff --git a/js/app/packages/app/component/next-soup/soup-view/create-infinite-queries.ts b/js/app/packages/app/component/next-soup/soup-view/create-infinite-queries.tsindex 037d647e2e..2112f7b1e4 100644--- a/js/app/packages/app/component/next-soup/soup-view/create-infinite-queries.ts+++ b/js/app/packages/app/component/next-soup/soup-view/create-infinite-queries.ts@@ -11,9 +11,11 @@ type InfiniteQueryConfig<TData, TSelect = TData[]> = {queryFn: (ctx: { pageParam: string | null }) => Promise<TData>;getNextPageParam: (lastPage: TData) => string | null;initialData?: InfiniteData<TData, string | null>;+ placeholderData?: InfiniteData<TData, string | null>;select?: (pages: TData[]) => TSelect;enabled?: boolean;staleTime?: number;+ meta?: Record<string, unknown>;};type InfiniteQueryResult<TData, TSelect> = {@@ -29,9 +31,14 @@ type InfiniteQueryResult<TData, TSelect> = {>;};+type InfiniteQueriesResult<TData, TSelect> = {+ list: Accessor<InfiniteQueryResult<TData, TSelect>[]>;+ map: Accessor<Map<string, InfiniteQueryResult<TData, TSelect>>>;+};+export function createInfiniteQueries<TData, TSelect = TData[]>(getConfigs: Accessor<InfiniteQueryConfig<TData, TSelect>[]>-): Accessor<InfiniteQueryResult<TData, TSelect>[]> {+): InfiniteQueriesResult<TData, TSelect> {const queries = mapArray(() => getConfigs().map((c) => c.key),(key): InfiniteQueryResult<TData, TSelect> => {@@ -65,6 +72,11 @@ export function createInfiniteQueries<TData, TSelect = TData[]>(TData | null,string | null>,+ placeholderData: config?.placeholderData as InfiniteData<+ TData | null,+ string | null+ >,+ meta: config?.meta,};});@@ -88,5 +100,13 @@ export function createInfiniteQueries<TData, TSelect = TData[]>(});- return queries;+ const queriesByKey = createMemo(() => {+ const map = new Map<string, InfiniteQueryResult<TData, TSelect>>();+ for (const query of queries()) {+ map.set(query.key, query);+ }+ return map;+ });++ return { list: queries, map: queriesByKey };}diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsxindex eef83e3dd8..456a4340dd 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx@@ -18,11 +18,16 @@ import {type Query,type QueryStore,} from '@app/component/next-soup/filters/filter-store/query-store';-import { createInfiniteQueries } from '@app/component/next-soup/soup-view/create-infinite-queries';+import { createGroupedSoupQueries } from '@app/component/next-soup/soup-view/create-grouped-soup-queries';import { createSearchState } from '@app/component/next-soup/soup-view/create-search-state';import { deduplicateEntities } from '@app/component/next-soup/utils';import { useEntryState } from '@app/component/split-layout/entry-state';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';+import {+ isListViewID,+ type ListView,+ soupItemMatchesListView,+} from '@app/constants/list-views';import { useFeatureFlag } from '@app/lib/analytics/posthog';import {ENABLE_FEATURED_SEARCH_RESULTS,@@ -30,7 +35,6 @@ import {ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE,} from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';-import { throwOnErr } from '@core/util/result';import {type EntityData,getPropertyOptionLabel,@@ -39,20 +43,13 @@ import {} from '@entity';import { useNotificationsForEntity } from '@notifications';import { useQueryClient } from '@queries/client';-import {- parseGroupedSoupPage,- serializeGroupByField,-} from '@queries/soup/grouped/api';import type {GroupMeta as ApiGroupMeta,GroupByField,- GroupedSoupPage,} from '@queries/soup/grouped/types';-import { type SoupParams, useSoupAstItemsQuery } from '@queries/soup/items';+import type { SoupParams } from '@queries/soup/items';+import { useSoupAstItemsQuery } from '@queries/soup/items';import { soupKeys } from '@queries/soup/keys';-import { mapSoupPageToEntityList } from '@queries/soup/transform-utils';-import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';-import { storageServiceClient } from '@service-storage/client';import type { SoupPage } from '@service-storage/generated/schemas';import type { InfiniteData } from '@tanstack/solid-query';import {@@ -106,6 +103,9 @@ interface SoupViewContextValues {activeTab: Accessor<string | undefined>;setActiveTab: Setter<string | undefined>;groupByField: Accessor<GroupByField | undefined>;+ fetchNextGroupPage: (groupKey: string) => Promise<void>;+ isFetchingGroupPage: (groupKey: string) => boolean;+ hasNextGroupPage: (groupKey: string) => boolean;}const SoupViewContext = createContext<SoupViewContextValues>();@@ -329,16 +329,28 @@ export const SoupViewContextProvider: FlowComponent<};};+ const activeListView = createMemo<ListView | undefined>(() => {+ const content = panel.handle.content();+ if (content.type !== 'component') return;+ return isListViewID(content.id) ? content.id : undefined;+ });+const itemsQuery = useSoupAstItemsQuery(() => ({params: soupParams(),body: soupBody(),groupBy: groupByField(),}),- () => ({- enabled: !search.isSearching(),- showSupportedForeignEntities: showSupportedForeignEntitiesFF().enabled,- })+ () => {+ const view = activeListView();+ return {+ enabled: !search.isSearching(),+ showSupportedForeignEntities: showSupportedForeignEntitiesFF().enabled,+ meta: {+ itemFilter: (item) => soupItemMatchesListView(item, view),+ },+ };+ });const items = createMemo<SoupEntity[]>(@@ -441,98 +453,38 @@ export const SoupViewContextProvider: FlowComponent<return [...featured, ...rest];};- const instructionsIdQuery = useInstructionsMdIdQuery();-- const groupQueries = createInfiniteQueries<GroupedSoupPage, SoupEntity[]>(- () => {- const field = groupByField();+ const groupQueries = createGroupedSoupQueries({+ initialPage: () => {const groups = itemsQuery.data?.groups;- const items = itemsQuery.data?.items;- const dataVersion = itemsQuery.dataUpdatedAt;-- if (!field || !groups || !items) {- return [];- }-- return groups.map((group) => {- const initialGroupItems = items.slice(- group.startIndex,- group.startIndex + group.pageCount- );+ const items = itemsQuery.data?.itemsById;+ if (!groups || !items) return;+ return { groups, items };+ },+ groupByField,+ soupParams,+ soupBody,+ queryOptions: () => {+ const view = activeListView();+ return {+ enabled: !search.isSearching(),+ meta: {+ itemFilter: (item) => soupItemMatchesListView(item, view),+ },+ };+ },+ });- return {- key: group.key,- queryKey: [- ...soupKeys.groupedGroup({- params: soupParams(),- body: soupBody(),- groupBy: field,- groupKey: group.key,- }).queryKey,- dataVersion,- ] as readonly unknown[],- queryFn: async (ctx: { pageParam: string | null }) => {- const response = await throwOnErr(async () =>- storageServiceClient.getGroupedSoupAstItems({- params: {- cursor: ctx.pageParam ?? undefined,- group_by: serializeGroupByField(field),- group_key: group.key,- },- body: {- ...soupBody(),- ...soupParams(),- },- })- );- return parseGroupedSoupPage(response);- },- getNextPageParam: (lastPage: GroupedSoupPage): string | null => {- const meta = lastPage.groups.find((g) => g.key === group.key);- return meta?.nextCursor ?? null;- },- initialData: {- pages: [- {- items: initialGroupItems,- nextCursor: group.nextCursor,- groups: [group],- },- ],- pageParams: [null],- },- select: (pages: GroupedSoupPage[]): SoupEntity[] => {- const allItems = pages.flatMap((p) => p.items);- return mapSoupPageToEntityList(- { items: allItems, next_cursor: null },- {- instructionsIdQuery,- showSupportedForeignEntities:- showSupportedForeignEntitiesFF().enabled,- }- ).map((e) => attachNotifications(e)) as SoupEntity[];- },- enabled: true,- staleTime: Infinity,- };- });- }- );+ const groupQueryFor = (groupKey: string) => groupQueries.map().get(groupKey);- const loadMoreForGroup = async (groupKey: string): Promise<void> => {- const query = groupQueries().find((q) => q.key === groupKey);- await query?.fetchNextPage();+ const fetchNextGroupPage = async (groupKey: string) => {+ await groupQueryFor(groupKey)?.fetchNextPage();};- const isGroupLoadingMore = (groupKey: string) => {- const query = groupQueries().find((q) => q.key === groupKey);- return query?.isFetchingNextPage() ?? false;- };+ const isFetchingGroupPage = (groupKey: string) =>+ groupQueryFor(groupKey)?.isFetchingNextPage() ?? false;- const hasMoreForGroup = (groupKey: string) => {- const query = groupQueries().find((q) => q.key === groupKey);- return query?.hasNextPage() ?? false;- };+ const hasNextGroupPage = (groupKey: string) =>+ groupQueryFor(groupKey)?.hasNextPage() ?? false;const buildGroupMeta = (group: ApiGroupMeta): GroupMeta => {const resolvedLabel = getPropertyOptionLabel(group.key) ?? group.label;@@ -543,9 +495,6 @@ export const SoupViewContextProvider: FlowComponent<count: group.totalCount,isExpanded: () => soup.grouping.isExpanded(group.key),toggle: () => soup.grouping.toggle(group.key),- hasMore: () => hasMoreForGroup(group.key),- loadMore: () => loadMoreForGroup(group.key),- isLoading: () => isGroupLoadingMore(group.key),};};@@ -553,29 +502,29 @@ export const SoupViewContextProvider: FlowComponent<const field = groupByField();const groups = itemsQuery.data?.groups;- // Not grouped - build simple entity rowsif (!field || !groups || search.isSearching()) {return entities().map((entity, index) =>soup.buildRow({ id: entity.id, index, original: entity }));}- // Grouped - build header + entity + loadMore rows for each groupconst result: SoupRow[] = [];let globalIndex = 0;for (const apiGroup of groups) {const groupMeta = buildGroupMeta(apiGroup);- const query = groupQueries().find((q) => q.key === apiGroup.key);- const groupEntities = query?.data() ?? [];+ const groupData = groupQueryFor(apiGroup.key)?.data();+ const groupEntities =+ groupData?.entities.map(+ (entity) =>+ (isWithNotification(entity)+ ? entity+ : attachNotifications(entity)) as SoupEntity+ ) ?? [];- // Get first entity to use for header original- // If the group has no entities, we can skip itconst firstEntity = groupEntities[0];-if (!firstEntity) continue;- // Header rowresult.push(soup.buildRow({id: `header:${apiGroup.key}`,@@ -586,7 +535,6 @@ export const SoupViewContextProvider: FlowComponent<}));- // Entity rowsfor (const entity of groupEntities) {result.push(soup.buildRow({@@ -598,12 +546,9 @@ export const SoupViewContextProvider: FlowComponent<);}- // We can stop here if the group has no more data- // that needs to be fetched- if (!groupMeta.hasMore()) continue;+ if (!hasNextGroupPage(apiGroup.key)) continue;const lastEntity = groupEntities[groupEntities.length - 1];-result.push(soup.buildRow({id: `loadmore:${apiGroup.key}`,@@ -662,6 +607,9 @@ export const SoupViewContextProvider: FlowComponent<activeTab,setActiveTab,groupByField,+ fetchNextGroupPage,+ isFetchingGroupPage,+ hasNextGroupPage,};return (diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsxindex 1b4276971a..ed3d5ad1b5 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx@@ -112,7 +112,6 @@ import {batch,createEffect,createMemo,- createRenderEffect,createSignal,type JSX,Match,@@ -123,7 +122,6 @@ import {Suspense,Switch,} from 'solid-js';-import { createStore, reconcile } from 'solid-js/store';import { Dynamic } from 'solid-js/web';import { type VirtualizerHandle, VList } from 'virtua/solid';import type { CacheSnapshot } from 'virtua/unstable_core';@@ -608,6 +606,8 @@ export const SoupViewList = (props: SoupViewListProps) => {isLocalSearchSettling,activeTab,setActiveTab,+ fetchNextGroupPage,+ isFetchingGroupPage,} = useSoupView();const { hasActiveRefinements, hasHiddenItems, resetToTabDefaults } =useFilterRefinements();@@ -724,6 +724,7 @@ export const SoupViewList = (props: SoupViewListProps) => {currentView,activeTab,applyTabPreset,+ fetchNextGroupPage,});// Create markDone action for swipe/click handlers@@ -1217,7 +1218,9 @@ export const SoupViewList = (props: SoupViewListProps) => {)}><Show- when={!group().isLoading()}+ when={+ !isFetchingGroupPage(group().key)+ }fallback={<Buttonvariant="base"@@ -1244,7 +1247,9 @@ export const SoupViewList = (props: SoupViewListProps) => {'border-transparent':highlighted(),})}- onClick={() => group().loadMore()}+ onClick={() => {+ fetchNextGroupPage(group().key);+ }}><CaretDownIcon class="size-2.5" />Load More@@ -1431,12 +1436,6 @@ const SoupList = (props: SoupListProps) => {const itemSize = createMemo(() => props.itemSize ?? DEFAULT_ITEM_SIZE);const overscan = createMemo(() => props.overscan ?? DEFAULT_OVERSCAN);- const [stableRows, setStableRows] = createStore<SoupRow[]>([]);-- createRenderEffect(() => {- setStableRows(reconcile(props.rows, { key: 'id' }));- });-const handleScroll = (offset: number) => {const handle = virtualizerHandle();@@ -1472,7 +1471,7 @@ const SoupList = (props: SoupListProps) => {cache={props.cache}ref={registerVirtualizerHandler}class={cn('overscroll-none', props.virtualizerClass)}- data={stableRows}+ data={props.rows}itemSize={itemSize()}bufferSize={overscan() * itemSize()}onScroll={handleScroll}diff --git a/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts b/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.tsindex 2d866f34f1..c60ae7df8f 100644--- a/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts+++ b/js/app/packages/app/component/next-soup/soup-view/use-soup-view-hotkeys.ts@@ -36,7 +36,8 @@ type UseSoupViewHotkeysOptions = {previewState: Accessor<boolean>;currentView: Accessor<ListView | undefined>;activeTab: Accessor<string | undefined>;- applyTabPreset: (view: ListView, tabId: string) => boolean;+ applyTabPreset: (view: ListView, tabId: string) => void;+ fetchNextGroupPage: (groupKey: string) => Promise<void>;};export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {@@ -49,6 +50,7 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {currentView,activeTab,applyTabPreset,+ fetchNextGroupPage,} = options;const analytics = useAnalytics();@@ -155,7 +157,7 @@ export const useSoupViewHotkeys = (options: UseSoupViewHotkeysOptions) => {// If focused on a load more row, trigger load more and stay at same indexif (focusedRow.getIsLoadMore() && focusedRow.group) {const currentIndex = focusedRow.index;- focusedRow.group.loadMore().then(() => {+ fetchNextGroupPage(focusedRow.group.key).then(() => {soup.navigate.toIndex(currentIndex);virtualizerHandle()?.scrollToIndex(currentIndex, {align: 'nearest',diff --git a/js/app/packages/app/constants/list-views.ts b/js/app/packages/app/constants/list-views.tsindex 52e3d837fd..d009de43fc 100644--- a/js/app/packages/app/constants/list-views.ts+++ b/js/app/packages/app/constants/list-views.ts@@ -1,3 +1,6 @@+import type { SoupApiItem } from '@service-storage/generated/schemas';+import { match } from 'ts-pattern';+export const LIST_VIEWS = ['inbox','agents',@@ -44,3 +47,25 @@ export const isListViewID = (id: string | null | undefined): id is ListView => {return LIST_VIEWS.includes(id as 'inbox');};++export const soupItemMatchesListView = (+ item: SoupApiItem,+ view: ListView | undefined+): boolean =>+ match(view)+ .with('agents', () => item.tag === 'chat')+ .with('mail', () => item.tag === 'emailThread')+ .with(+ 'documents',+ () => item.tag === 'document' && item.data.subType?.type !== 'task'+ )+ .with(+ 'tasks',+ () => item.tag === 'document' && item.data.subType?.type === 'task'+ )+ .with('channels', () => item.tag === 'channel')+ .with('calls', () => item.tag === 'call')+ .with('folders', () => item.tag === 'project')+ .with('inbox', 'search', undefined, () => true)+ .with('companies', () => item.tag === 'crmCompany')+ .exhaustive();diff --git a/js/app/packages/queries/soup/grouped/api.ts b/js/app/packages/queries/soup/grouped/api.tsindex bd6fa8590e..9a4ceec3bd 100644--- a/js/app/packages/queries/soup/grouped/api.ts+++ b/js/app/packages/queries/soup/grouped/api.ts@@ -1,9 +1,50 @@-import type { GroupByField, GroupedSoupPage, GroupMeta } from './types';+import type { SoupProperty } from '@service-storage/generated/schemas';+import type { ApiGroupByField as ApiGroupedSoupField } from '@service-storage/generated/schemas/apiGroupByField';+import type { ApiGroupMeta } from '@service-storage/generated/schemas/apiGroupMeta';+import type { SoupApiItem } from '@service-storage/generated/schemas/soupApiItem';+import { match } from 'ts-pattern';+import { type GroupByField, type GroupMeta, NOT_SET_GROUP_KEY } from './types';-/**- * Serialize GroupByField to the API's expected JSON format.- */-export function serializeGroupByField(field: GroupByField): unknown {+function hasProperties<T extends SoupApiItem>(+ item: T+): item is T & {+ data: T['data'] & {+ properties?: SoupProperty[];+ };+} {+ if (+ item.tag === 'channel' ||+ item.tag === 'call' ||+ item.tag === 'crmCompany' ||+ item.tag === 'foreignEntity'+ )+ return false;++ return true;+}++function hasProjectId<T extends SoupApiItem>(+ item: T+): item is T & {+ data: T['data'] & {+ projectId?: string;+ };+} {+ if (+ item.tag === 'channel' ||+ item.tag === 'call' ||+ item.tag === 'crmCompany' ||+ item.tag === 'foreignEntity' ||+ item.tag === 'project'+ )+ return false;++ return true;+}++export function serializeGroupByField(+ field: GroupByField+): ApiGroupedSoupField {switch (field.type) {case 'date':return 'date';@@ -21,34 +62,150 @@ export function serializeGroupByField(field: GroupByField): unknown {}}-/**- * Parse raw API group metadata to typed GroupMeta.- */-export function parseGroupMeta(raw: Record<string, unknown>): GroupMeta {+export function parseGroupMeta(raw: ApiGroupMeta): GroupMeta {return {- key: raw.key as string,- label: raw.label as string,- displayOrder: (raw.display_order as number) ?? null,- totalCount: raw.total_count as number,- pageCount: raw.page_count as number,- startIndex: raw.start_index as number,- nextCursor: (raw.next_cursor as string) ?? null,+ key: raw.key,+ label: raw.label,+ displayOrder: raw.display_order ?? null,+ totalCount: raw.total_count,+ itemIds: raw.item_ids,+ nextCursor: raw.next_cursor ?? null,};}+const ENTITY_TYPE_META: Record<+ string,+ { label: string; displayOrder: number }+> = {+ document: { label: 'Documents', displayOrder: 0 },+ email: { label: 'Emails', displayOrder: 1 },+ channel: { label: 'Messages', displayOrder: 2 },+ chat: { label: 'Chats', displayOrder: 3 },+ project: { label: 'Projects', displayOrder: 4 },+ call: { label: 'Calls', displayOrder: 5 },+};++export type ResolvedGroupMeta = Pick<+ GroupMeta,+ 'key' | 'label' | 'displayOrder'+>;++export function resolveGroupMetaForKey(+ groupBy: GroupByField | undefined,+ key: string,+ item?: SoupApiItem+): ResolvedGroupMeta | undefined {+ if (!groupBy) return;++ return match(groupBy)+ .with({ type: 'entity_type' }, () => {+ const meta = ENTITY_TYPE_META[key] ?? { label: 'Other', displayOrder: 6 };++ return { key, label: meta.label, displayOrder: meta.displayOrder };+ })+ .with({ type: 'project' }, () => {+ if (key === NOT_SET_GROUP_KEY) {+ return {+ key,+ label: 'No Project',+ displayOrder: Number.MAX_SAFE_INTEGER,+ };+ }++ return;+ })+ .with({ type: 'property' }, (propertyGroupBy) => {+ if (key === NOT_SET_GROUP_KEY) {+ return { key, label: 'Not Set', displayOrder: Number.MAX_SAFE_INTEGER };+ }++ const propertyValueType = getGroupedPropertyValueType(+ item,+ propertyGroupBy+ );++ if (propertyValueType === 'SelectOption') {+ return {+ key,+ label: key,+ displayOrder: null,+ };+ }++ return;+ })+ .with({ type: 'date' }, () => undefined)+ .exhaustive();+}++function getGroupedPropertyValueType(+ item: SoupApiItem | undefined,+ groupBy: GroupByField+): string | undefined {+ if (!item || groupBy.type !== 'property') return;++ if (!hasProperties(item)) return;++ const properties = item.data.properties;++ const prop = properties?.find(+ (p) => p.definition?.id === groupBy.propertyDefinitionId+ );++ const value = prop?.value;++ return value?.type;+}+/**- * Parse the API response into our typed GroupedSoupPage.- * Handles snake_case to camelCase conversion.+ * Compute the group keys an item belongs to under the given grouping.+ * Returns `undefined` when bucketing can't be reproduced client-side+ * (date, non-categorical property) — caller should invalidate.*/-export function parseGroupedSoupPage(response: unknown): GroupedSoupPage {- const data = response as Record<string, unknown>;- const items = (data.items ?? []) as GroupedSoupPage['items'];- const nextCursor = (data.next_cursor as string) ?? null;- const rawGroups = (data.groups ?? []) as Array<Record<string, unknown>>;+export function computeGroupKeysForItem(+ item: SoupApiItem,+ groupBy: GroupByField | undefined+) {+ if (!groupBy) return;- return {- items,- nextCursor,- groups: rawGroups.map(parseGroupMeta),- };+ return match(groupBy)+ .with({ type: 'entity_type' }, () => [item.tag])+ .with({ type: 'project' }, () => {+ if (!hasProjectId(item)) return;++ const projectId = item.data.projectId;++ return [projectId ?? NOT_SET_GROUP_KEY];+ })+ .with({ type: 'property' }, (propertyGroupBy) => {+ if (!hasProperties(item)) return;++ const properties = item.data.properties;++ if (!properties) return [NOT_SET_GROUP_KEY];++ const prop = properties.find(+ (p) => p.definition?.id === propertyGroupBy.propertyDefinitionId+ );++ if (!prop) return [NOT_SET_GROUP_KEY];++ const value = prop.value;++ if (value == null) return [NOT_SET_GROUP_KEY];++ if (value.type === 'SelectOption' && Array.isArray(value.value)) {+ return value.value.length > 0 ? value.value : [NOT_SET_GROUP_KEY];+ }++ if (value.type === 'EntityReference' && Array.isArray(value.value)) {+ return value.value.length > 0+ ? value.value.map((r) => r.entity_id)+ : [NOT_SET_GROUP_KEY];+ }++ return;+ })+ .with({ type: 'date' }, () => undefined)+ .exhaustive();}diff --git a/js/app/packages/queries/soup/grouped/types.ts b/js/app/packages/queries/soup/grouped/types.tsindex d924b3da32..0243756b56 100644--- a/js/app/packages/queries/soup/grouped/types.ts+++ b/js/app/packages/queries/soup/grouped/types.ts@@ -1,5 +1,12 @@import type { SoupApiItem } from '@service-storage/generated/schemas';+/**+ * Empty group key emitted by the backend+ * (rust/cloud-storage/soup/src/domain/models/grouping.rs)+ * for items missing a value for the grouped property.+ */+export const NOT_SET_GROUP_KEY = '';+export type GroupByField =| { type: 'date' }| { type: 'entity_type' }@@ -10,6 +17,13 @@ export type GroupByField =entityType?: PropertyEntityType;};+export const GROUP_BY_TYPES: readonly GroupByField['type'][] = [+ 'date',+ 'entity_type',+ 'project',+ 'property',+];+export type PropertyEntityType =| 'CHANNEL'| 'CHAT'@@ -25,13 +39,14 @@ export interface GroupMeta {label: string;displayOrder: number | null;totalCount: number;- pageCount: number;- startIndex: number;+ /** Ordered ids of items in this group for the current page. */+ itemIds: string[];nextCursor: string | null;}export interface GroupedSoupPage {- items: SoupApiItem[];+ /** Items pool keyed by id. Per-group ordering lives in `groups[].itemIds`. */+ items: Record<string, SoupApiItem>;nextCursor: string | null;groups: GroupMeta[];}diff --git a/js/app/packages/queries/soup/items.ts b/js/app/packages/queries/soup/items.tsindex f403e63f89..7932bba4f6 100644--- a/js/app/packages/queries/soup/items.ts+++ b/js/app/packages/queries/soup/items.ts@@ -6,9 +6,18 @@ import {parseGroupMeta,serializeGroupByField,} from '@queries/soup/grouped/api';-import type { GroupByField, GroupMeta } from '@queries/soup/grouped/types';+import {+ type GroupByField,+ type GroupMeta,+ NOT_SET_GROUP_KEY,+} from '@queries/soup/grouped/types';import { soupKeys } from '@queries/soup/keys';-import { mapSoupPageToEntityList } from '@queries/soup/transform-utils';+import {+ isDisplayableSoupItem,+ isInstructionsMdDoc,+ mapApiSoupItemToEntity,+ mapSoupPageToEntityList,+} from '@queries/soup/transform-utils';import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';import { storageServiceClient } from '@service-storage/client';import type { SoupApiItem } from '@service-storage/generated/schemas';@@ -39,7 +48,6 @@ export type SoupAstItemsQueryArgs = {params: SoupAstParams;body: SoupAstBody;groupBy?: GroupByField;- groupKey?: string;};export type SoupApiItemFilter = (item: SoupApiItem) => boolean;@@ -47,19 +55,40 @@ export type SoupApiItemFilter = (item: SoupApiItem) => boolean;interface SoupItemsQueryOptions {enabled?: boolean;staleTime?: StaleTime;+ meta?: {+ groupBy?: GroupByField;+ groupKey?: string;+ itemFilter?: (item: SoupApiItem) => boolean;+ };showSupportedForeignEntities?: boolean;}-type SoupAstItemsPage = {+/**+ * Cached page for `useSoupAstItemsQuery`. Discriminated by `kind`:+ * - `grouped`: items pool keyed by id, `groups[].itemIds` describes order.+ * Parent never paginates when grouped — per-group queries handle load-more.+ * - `flat`: items array; standard infinite-query pagination.+ */+export type SoupAstItemsPage = SoupAstItemsGroupedPage | SoupAstItemsFlatPage;++export type SoupAstItemsGroupedPage = {+ kind: 'grouped';+ items: Record<string, SoupApiItem>;+ groups: GroupMeta[];+ nextCursor: null;+};++export type SoupAstItemsFlatPage = {+ kind: 'flat';items: SoupApiItem[];nextCursor: string | null;- groups?: GroupMeta[];};-type SoupAstItemsData = {+export type SoupAstItemsData = {entities: EntityData[];groups: GroupMeta[] | undefined;- items: SoupApiItem[];+ /** Raw API item pool. Only present when query is grouped. */+ itemsById?: SoupAstItemsGroupedPage['items'];};export const useSoupItemsQuery = (@@ -117,37 +146,28 @@ export const useSoupAstItemsQuery = (const instructionsIdQuery = useInstructionsMdIdQuery();return useInfiniteQuery(() => {- const { params, body, groupBy, groupKey } = args();+ const { params, body, groupBy } = args();return {- queryKey: soupKeys.astItems({ params, body, groupBy, groupKey }).queryKey,+ queryKey: soupKeys.astItems({ params, body, groupBy }).queryKey,queryFn: async (ctx): Promise<SoupAstItemsPage> => {if (groupBy) {const response = await throwOnErr(async () =>await storageServiceClient.getGroupedSoupAstItems({params: {- cursor: ctx.pageParam,group_by: serializeGroupByField(groupBy),- group_key: groupKey,- },- body: {- ...body,- ...params,+ per_group_limit: params.limit,},+ body,}));- const groups = response.groups- ? (response.groups as Array<Record<string, unknown>>).map(- parseGroupMeta- )- : undefined;-return {+ kind: 'grouped',items: response.items,- nextCursor: response.next_cursor ?? null,- groups,+ groups: response.groups.map(parseGroupMeta),+ nextCursor: null,};}@@ -165,42 +185,74 @@ export const useSoupAstItemsQuery = ();return {+ kind: 'flat',items: response.items,nextCursor: response.next_cursor ?? null,- groups: [],};},initialPageParam: null as string | null,getNextPageParam: (lastPage): string | null => {- if (groupBy) return null;+ if (lastPage.kind === 'grouped') return null;return lastPage.nextCursor;},select: (data): SoupAstItemsData => {- const items = data.pages.flatMap((page) => page.items);+ const firstPage = data.pages[0];++ if (firstPage?.kind === 'grouped') {+ const groups = firstPage.groups+ .slice()+ .sort(makeGroupComparator(groupBy));++ const itemsById = firstPage.items;+ const entities: EntityData[] = [];++ for (const g of groups) {+ for (const id of g.itemIds) {+ const item = itemsById[id];++ let displayable = false;++ if (item.tag === 'foreignEntity') {+ displayable =+ options?.().showSupportedForeignEntities === true &&+ item.data.foreignEntitySource === 'github_pull_request';+ } else {+ displayable =+ item && !isInstructionsMdDoc(item, instructionsIdQuery);+ }+ if (displayable && isDisplayableSoupItem(item)) {+ const mapped = mapApiSoupItemToEntity(item);+ entities.push(mapped);+ }+ }+ }++ return { entities, groups, itemsById };+ }+const entities = data.pages.flatMap((page) => {- return mapSoupPageToEntityList(page, {- instructionsIdQuery,- showSupportedForeignEntities:- options?.().showSupportedForeignEntities,- });+ if (page.kind !== 'flat') return [];++ return mapSoupPageToEntityList(+ { items: page.items, next_cursor: null },+ { instructionsIdQuery }+ );});- const rawGroups = data.pages[0]?.groups;- const groups = rawGroups?.slice().sort(makeGroupComparator(groupBy));- return { entities, groups, items };+ return { entities, groups: undefined };},enabled: options?.().enabled,staleTime: options?.().staleTime,placeholderData: (p) => p,- meta: { normalize: true },+ meta: {+ ...options?.().meta,+ groupBy,+ normalize: true,+ },};});};-// Empty group key from backend (rust/cloud-storage/soup/src/domain/models/grouping.rs)-// for items missing a value for the grouped property.-const NOT_SET_GROUP_KEY = '';-// Stable UUIDs from migrations/20251128000001_seed_system_properties.sql.// Custom (user-created) options fall through to displayOrder.const STATUS_OPTION_ORDER: readonly string[] = [diff --git a/js/app/packages/queries/soup/keys.ts b/js/app/packages/queries/soup/keys.tsindex 60c8c1db42..ea0629ff05 100644--- a/js/app/packages/queries/soup/keys.ts+++ b/js/app/packages/queries/soup/keys.ts@@ -8,7 +8,7 @@ export const soupKeys = createQueryKeys('soup', {queryKey: [args.params, args.body],}),astItems: (args: SoupAstItemsQueryArgs) => ({- queryKey: [args.params, args.body, args.groupBy, args.groupKey],+ queryKey: [args.params, args.body, args.groupBy],}),search: (args: SearchSoupQueryArgs) => ({queryKey: [args.params, args.body],diff --git a/js/app/packages/queries/soup/normalized-cache/grouped-operations.ts b/js/app/packages/queries/soup/normalized-cache/grouped-operations.tsnew file mode 100644index 0000000000..b7c9373b08--- /dev/null+++ b/js/app/packages/queries/soup/normalized-cache/grouped-operations.ts@@ -0,0 +1,434 @@+import type { SoupApiItem } from '@service-storage/generated/schemas';+import type { InfiniteData } from '@tanstack/solid-query';++import { queryClient } from '../../client';+import {+ computeGroupKeysForItem,+ type ResolvedGroupMeta,+ resolveGroupMetaForKey,+} from '../grouped/api';+import type { GroupByField, GroupMeta } from '../grouped/types';+import type { SoupAstItemsGroupedPage } from '../items';+import { soupKeys } from '../keys';+import { getSoupQueryMeta } from './utils';++type GroupedGroupPage = {+ items: Record<string, SoupApiItem>;+ group: GroupMeta;+};++type GroupedGroupInfiniteData = InfiniteData<GroupedGroupPage, unknown>;++/** Runtime guard for the normalized grouped parent page shape. */+function isGroupedPage(page: unknown): page is SoupAstItemsGroupedPage {+ if (!page || typeof page !== 'object') return false;+ const p = page as Record<string, unknown>;+ return (+ p.kind === 'grouped' &&+ Array.isArray(p.groups) &&+ p.items !== null &&+ typeof p.items === 'object' &&+ !Array.isArray(p.items)+ );+}++/** Builds a new optimistic group containing a single item. */+function makeGroup(meta: ResolvedGroupMeta, entityId: string): GroupMeta {+ return {+ ...meta,+ totalCount: 1,+ itemIds: [entityId],+ nextCursor: null,+ };+}++/** Moves an item id to the front of a group, incrementing count only if new. */+function prependId(group: GroupMeta, entityId: string): GroupMeta {+ const existing = group.itemIds.includes(entityId);++ return {+ ...group,+ itemIds: existing+ ? [entityId, ...group.itemIds.filter((id) => id !== entityId)]+ : [entityId, ...group.itemIds],+ totalCount: existing ? group.totalCount : group.totalCount + 1,+ };+}++/** Removes an item id from a group and decrements the total count safely. */+function removeId(group: GroupMeta, entityId: string): GroupMeta {+ if (!group.itemIds.includes(entityId)) return group;++ return {+ ...group,+ itemIds: group.itemIds.filter((id) => id !== entityId),+ totalCount: Math.max(0, group.totalCount - 1),+ };+}++/**+ * Recomputes an updated item's memberships across grouped parent AST queries.+ * Updates only resolvable grouped pages; unresolved grouping metadata is left+ * unchanged so callers can rely on later invalidation/refetch behavior.+ */+export function syncGroupedParents(entityId: string, entity: SoupApiItem) {+ const queries = queryClient.getQueryCache().findAll({+ queryKey: soupKeys.astItems._def,+ });++ for (const query of queries) {+ const prev = query.state.data as InfiniteData<unknown, unknown> | undefined;++ if (!prev || !Array.isArray(prev.pages) || prev.pages.length === 0) {+ continue;+ }++ const meta = getSoupQueryMeta(query.meta);++ if (!meta.groupBy) continue;++ const nextGroupKeys = computeGroupKeysForItem(entity, meta.groupBy);++ if (nextGroupKeys === undefined) {+ queryClient.invalidateQueries({ queryKey: query.queryKey });+ continue;+ }++ let changed = false;+ let needsInvalidation = false;++ const pages = [];+ for (const page of prev.pages) {+ if (!isGroupedPage(page)) {+ pages.push(page);+ continue;+ }++ const next = syncMembership(+ page,+ entityId,+ nextGroupKeys,+ entity,+ meta.groupBy+ );++ if (!next) {+ needsInvalidation = true;+ pages.push(page);+ continue;+ }++ if (next !== page) changed = true;+ pages.push(next);+ }++ if (needsInvalidation) {+ queryClient.invalidateQueries({ queryKey: query.queryKey });+ continue;+ }++ if (!changed) continue;++ query.setData({ ...prev, pages }, { manual: true });+ }+}++/**+ * Reconciles expanded single-group queries after an item changes.+ * Adds the item to matching first pages and removes it from groups it no+ * longer belongs to or no longer passes the query's item filter for.+ */+export function syncGroupQueries(entityId: string, entity: SoupApiItem) {+ const queries = queryClient.getQueryCache().findAll({+ queryKey: soupKeys.groupedGroup._def,+ });++ for (const query of queries) {+ const prev = query.state.data as GroupedGroupInfiniteData | undefined;+ if (!prev?.pages?.length) continue;++ const meta = getSoupQueryMeta(query.meta);+ if (!meta.groupBy || meta.groupKey == null) continue;++ const nextGroupKeys = computeGroupKeysForItem(entity, meta.groupBy);+ if (nextGroupKeys === undefined) {+ queryClient.invalidateQueries({ queryKey: query.queryKey });+ continue;+ }++ const filter = meta.itemFilter;+ let shouldHave = nextGroupKeys.includes(meta.groupKey);++ if (filter && !filter(entity)) {+ shouldHave = false;+ }++ let changed = false;++ const pages = [];+ let index = 0;+ for (const page of prev.pages) {+ const hasEntity = page.group.itemIds.includes(entityId);++ if (shouldHave && index === 0 && !hasEntity) {+ changed = true;+ pages.push({+ ...page,+ items: { ...page.items, [entityId]: entity },+ group: prependId(page.group, entityId),+ });+ index += 1;+ continue;+ }++ if (!shouldHave && hasEntity) {+ changed = true;+ const { [entityId]: _removed, ...items } = page.items;+ pages.push({+ ...page,+ items,+ group: removeId(page.group, entityId),+ });+ index += 1;+ continue;+ }++ pages.push(page);+ index += 1;+ }++ if (changed) {+ query.setData({ ...prev, pages }, { manual: true });+ }+ }+}++/**+ * Inserts an item into a grouped parent page, creating optimistic group metadata+ * for any target groups that can be resolved locally.+ */+export function insertGroupedPage(+ page: SoupAstItemsGroupedPage,+ item: SoupApiItem,+ itemId: string,+ groupBy: GroupByField | undefined+) {+ const newKeys = computeGroupKeysForItem(item, groupBy);+ if (newKeys === undefined || newKeys.length === 0) return;++ const targetKeys = new Set(newKeys);+ const existingKeys = new Set(page.groups.map((g) => g.key));+ const groups: GroupMeta[] = [];++ for (const targetKey of targetKeys) {+ if (existingKeys.has(targetKey)) continue;++ const meta = resolveGroupMetaForKey(groupBy, targetKey, item);+ if (!meta) return;++ groups.push(makeGroup(meta, itemId));+ }++ for (const group of page.groups) {+ groups.push(targetKeys.has(group.key) ? prependId(group, itemId) : group);+ }++ return {+ ...page,+ items: { ...page.items, [itemId]: item },+ groups,+ };+}++/** Inserts an item into the first page of any expanded group query it matches. */+export function insertGroupQueries(item: SoupApiItem, itemId: string) {+ const queries = queryClient.getQueryCache().findAll({+ queryKey: soupKeys.groupedGroup._def,+ });++ for (const query of queries) {+ const prev = query.state.data as GroupedGroupInfiniteData | undefined;+ if (!prev?.pages?.length) continue;++ const meta = getSoupQueryMeta(query.meta);+ const filter = meta.itemFilter;+ if (filter && !filter(item)) continue;++ if (!meta.groupBy || meta.groupKey == null) continue;++ const targetKeys = computeGroupKeysForItem(item, meta.groupBy);+ if (targetKeys === undefined) {+ queryClient.invalidateQueries({ queryKey: query.queryKey });+ continue;+ }+ if (!targetKeys.includes(meta.groupKey)) continue;++ const firstPage = prev.pages[0];+ if (firstPage.group.itemIds.includes(itemId)) continue;++ query.setData(+ {+ ...prev,+ pages: [+ {+ ...firstPage,+ items: { ...firstPage.items, [itemId]: item },+ group: prependId(firstPage.group, itemId),+ },+ ...prev.pages.slice(1),+ ],+ },+ { manual: true }+ );+ }+}++/** Removes items from a grouped parent page's item pool and group memberships. */+export function removeGroupedPage(+ page: SoupAstItemsGroupedPage,+ entityIds: Set<string>+) {+ const groups: GroupMeta[] = [];+ let changed = false;++ for (const group of page.groups) {+ const itemIds = group.itemIds.filter((id) => !entityIds.has(id));+ const removed = group.itemIds.length - itemIds.length;++ if (removed === 0) {+ groups.push(group);+ continue;+ }++ changed = true;+ groups.push({+ ...group,+ itemIds,+ totalCount: Math.max(0, group.totalCount - removed),+ });+ }++ const items: Record<string, SoupApiItem> = {};+ for (const [id, item] of Object.entries(page.items)) {+ if (entityIds.has(id)) {+ changed = true;+ continue;+ }++ items[id] = item;+ }++ return changed ? { ...page, items, groups } : page;+}++/** Removes items from all expanded group queries while preserving unaffected pages. */+export function removeGroupQueries(entityIds: Set<string>) {+ const queries = queryClient.getQueryCache().findAll({+ queryKey: soupKeys.groupedGroup._def,+ });++ for (const query of queries) {+ const prev = query.state.data as GroupedGroupInfiniteData | undefined;+ if (!prev?.pages?.length) continue;++ let changed = false;++ const pages = [];++ for (const page of prev.pages) {+ const itemIds = page.group.itemIds.filter((id) => !entityIds.has(id));+ const removed = page.group.itemIds.length - itemIds.length;+ let items = page.items;++ for (const id of entityIds) {+ if (id in items) {+ const { [id]: _, ...rest } = items;+ items = { ...rest };++ changed = true;+ }+ }++ if (removed === 0) {+ pages.push(items === page.items ? page : { ...page, items });+ continue;+ }++ changed = true;+ pages.push({+ ...page,+ items,+ group: {+ ...page.group,+ itemIds,+ totalCount: Math.max(0, page.group.totalCount - removed),+ },+ });+ }++ if (changed) {+ query.setData({ ...prev, pages }, { manual: true });+ }+ }+}++/** Reconcile group membership for an existing entity. Returns `undefined`+ * when a required new group cannot be created client-side and the caller should+ * invalidate instead of applying a partial optimistic move. */+function syncMembership(+ page: SoupAstItemsGroupedPage,+ entityId: string,+ nextGroupKeys: readonly string[],+ entity: SoupApiItem,+ groupBy: GroupByField | undefined+) {+ const nextGroups = new Set(nextGroupKeys);+ const currentGroups = new Set(page.groups.map((g) => g.key));++ let changed = false;++ const groups: GroupMeta[] = [];++ for (const group of nextGroups) {+ if (currentGroups.has(group)) continue;++ const meta = resolveGroupMetaForKey(groupBy, group, entity);++ if (!meta) return;++ changed = true;+ groups.push(makeGroup(meta, entityId));+ }++ for (const group of page.groups) {+ const hasEntity = group.itemIds.includes(entityId);+ const shouldInsert = nextGroups.has(group.key);++ if (hasEntity === shouldInsert) {+ groups.push(group);+ continue;+ }++ changed = true;+ groups.push(+ shouldInsert ? prependId(group, entityId) : removeId(group, entityId)+ );+ }++ if (!changed) return page;++ const newGroupsExist = nextGroups.size > 0;+ const nextItems: Record<string, SoupApiItem> = {};++ for (const [id, item] of Object.entries(page.items)) {+ if (id !== entityId || newGroupsExist) {+ nextItems[id] = item;+ }+ }++ if (newGroupsExist) {+ nextItems[entityId] = entity;+ }++ return { ...page, items: nextItems, groups };+}diff --git a/js/app/packages/queries/soup/normalized-cache/normalizer.ts b/js/app/packages/queries/soup/normalized-cache/normalizer.tsindex a2de6d3c0f..f21d9616f8 100644--- a/js/app/packages/queries/soup/normalized-cache/normalizer.ts+++ b/js/app/packages/queries/soup/normalized-cache/normalizer.ts@@ -5,6 +5,16 @@ export type NormalizerData = Parameters<ReturnType<typeof createQueryNormalizer>['setNormalizedData']>[0];+export const SOUP_NORM_PREFIX = 'soup:';++export function soupNormKey(id: string): string {+ return `${SOUP_NORM_PREFIX}${id}`;+}++export function stripSoupNormPrefix(normKey: string): string {+ return normKey.slice(SOUP_NORM_PREFIX.length);+}+/*** Extracts a normalization key from SoupApiItem wrappers.* Only objects with `tag + data + frecency_score` are normalized.@@ -16,9 +26,9 @@ export const getNormalizationObjectKey = (const data = obj.data as Record<string, unknown>;if (obj.tag === 'channel') {const channel = data?.channel as Record<string, unknown> | undefined;- return channel?.id ? `soup:${channel.id}` : undefined;+ return channel?.id ? soupNormKey(channel.id as string) : undefined;}- return data?.id ? `soup:${data.id}` : undefined;+ return data?.id ? soupNormKey(data.id as string) : undefined;}return undefined;};diff --git a/js/app/packages/queries/soup/normalized-cache/operations.test.ts b/js/app/packages/queries/soup/normalized-cache/operations.test.tsindex 9784848baf..4669a42486 100644--- a/js/app/packages/queries/soup/normalized-cache/operations.test.ts+++ b/js/app/packages/queries/soup/normalized-cache/operations.test.ts@@ -36,6 +36,9 @@ vi.mock('./normalizer', () => ({}return undefined;},+ SOUP_NORM_PREFIX: 'soup:',+ soupNormKey: (id: string) => `soup:${id}`,+ stripSoupNormPrefix: (normKey: string) => normKey.slice('soup:'.length),}));import { soupKeys } from '../keys';@@ -140,7 +143,9 @@ function mockSearchCache(};}-const soupSeedKey = [...soupKeys.astItems._def, 'seed'];+/** Legacy `items` query (flat SoupPage shape) — used by the bulk of the+ * pre-existing tests since they assert behavior agnostic of kind. */+const soupSeedKey = [...soupKeys.items._def, 'seed'];const searchSeedKey = [...soupKeys.search._def, 'seed'];function seedSoupQuery(data: InfiniteData<SoupPage, unknown>) {@@ -471,3 +476,257 @@ describe('optimisticUpdateSoupItemUpdatedAt', () => {expect(mockNormalizer.setNormalizedData).not.toHaveBeenCalled();});});++// -- Normalized grouped cache tests --++import type { GroupByField, GroupMeta } from '../grouped/types';+import type { SoupAstItemsGroupedPage } from '../items';++const STATUS_DEF = 'status-def-id';+const STATUS_GROUP_BY: GroupByField = {+ type: 'property',+ propertyDefinitionId: STATUS_DEF,+};++/** Build a task-like document item with a status property value. */+function mockTaskItem(id: string, statusOption: string): SoupApiItem {+ return {+ tag: 'document',+ data: {+ id,+ title: `task ${id}`,+ properties: [+ {+ definition: { id: STATUS_DEF },+ value: { type: 'SelectOption', value: [statusOption] },+ },+ ],+ },+ frecency_score: 1,+ } as unknown as SoupApiItem;+}++function buildGroup(+ key: string,+ itemIds: string[],+ totalCount?: number,+ displayOrder?: number+): GroupMeta {+ return {+ key,+ label: key,+ displayOrder: displayOrder ?? null,+ totalCount: totalCount ?? itemIds.length,+ itemIds,+ nextCursor: null,+ };+}++function mockGroupedParentCache(+ items: SoupApiItem[],+ groups: GroupMeta[]+): InfiniteData<SoupAstItemsGroupedPage, unknown> {+ const itemsById: Record<string, SoupApiItem> = {};+ for (const it of items) itemsById[getSoupItemId(it)] = it;+ return {+ pages: [+ {+ kind: 'grouped',+ items: itemsById,+ groups,+ nextCursor: null,+ },+ ],+ pageParams: [null],+ };+}++/** Seed a grouped astItems query with status property grouping metadata. */+function seedGroupedAstQuery(+ data: InfiniteData<SoupAstItemsGroupedPage, unknown>,+ suffix = 'grouped-seed'+) {+ const key = [...soupKeys.astItems._def, {}, {}, STATUS_GROUP_BY, suffix];+ testQueryClient.setQueryDefaults(key, { meta: { groupBy: STATUS_GROUP_BY } });+ testQueryClient.setQueryData(key, data);+ return key;+}++describe('insertSoupEntity — grouped cache', () => {+ it('adds item to items pool and prepends id to target group itemIds', () => {+ const items = [+ mockTaskItem('a-1', 'in_progress'),+ mockTaskItem('b-1', 'done'),+ ];+ const groups = [+ buildGroup('in_progress', ['a-1'], 3, 0),+ buildGroup('done', ['b-1'], 2, 1),+ ];+ const key = seedGroupedAstQuery(mockGroupedParentCache(items, groups));++ insertSoupEntity(mockTaskItem('a-new', 'in_progress'));++ const cached =+ testQueryClient.getQueryData<+ InfiniteData<SoupAstItemsGroupedPage, unknown>+ >(key)!;+ const page = cached.pages[0];++ // Pool gained the new item.+ expect(page.items['a-new']).toBeDefined();+ // in_progress gained the id at the top; totalCount bumped.+ const inProgress = page.groups.find((g) => g.key === 'in_progress')!;+ expect(inProgress.itemIds).toEqual(['a-new', 'a-1']);+ expect(inProgress.totalCount).toBe(4);+ // done untouched.+ const done = page.groups.find((g) => g.key === 'done')!;+ expect(done.itemIds).toEqual(['b-1']);+ expect(done.totalCount).toBe(2);+ });++ it('rollback restores grouped cache', () => {+ const items = [mockTaskItem('a-1', 'in_progress')];+ const groups = [buildGroup('in_progress', ['a-1'], 1, 0)];+ const key = seedGroupedAstQuery(mockGroupedParentCache(items, groups));++ const tx = insertSoupEntity(mockTaskItem('a-new', 'in_progress'));+ tx.rollback();++ const restored =+ testQueryClient.getQueryData<+ InfiniteData<SoupAstItemsGroupedPage, unknown>+ >(key)!;+ expect(restored.pages[0].items['a-new']).toBeUndefined();+ expect(restored.pages[0].groups[0].itemIds).toEqual(['a-1']);+ expect(restored.pages[0].groups[0].totalCount).toBe(1);+ });+});++describe('removeSoupEntities — grouped cache', () => {+ it('drops from pool, filters itemIds, decrements totalCount per affected group', () => {+ const items = [+ mockTaskItem('a-1', 'in_progress'),+ mockTaskItem('a-2', 'in_progress'),+ mockTaskItem('b-1', 'done'),+ ];+ const groups = [+ buildGroup('in_progress', ['a-1', 'a-2'], 5, 0),+ buildGroup('done', ['b-1'], 3, 1),+ ];+ const key = seedGroupedAstQuery(mockGroupedParentCache(items, groups));++ removeSoupEntities(new Set(['a-1']));++ const cached =+ testQueryClient.getQueryData<+ InfiniteData<SoupAstItemsGroupedPage, unknown>+ >(key)!;+ const page = cached.pages[0];+ expect(page.items['a-1']).toBeUndefined();+ expect(page.items['a-2']).toBeDefined();++ const inProgress = page.groups.find((g) => g.key === 'in_progress')!;+ expect(inProgress.itemIds).toEqual(['a-2']);+ expect(inProgress.totalCount).toBe(4);++ // done untouched.+ const done = page.groups.find((g) => g.key === 'done')!;+ expect(done.itemIds).toEqual(['b-1']);+ expect(done.totalCount).toBe(3);+ });++ it('rollback restores grouped cache', () => {+ const items = [mockTaskItem('a-1', 'in_progress')];+ const groups = [buildGroup('in_progress', ['a-1'], 1, 0)];+ const key = seedGroupedAstQuery(mockGroupedParentCache(items, groups));++ const tx = removeSoupEntities(new Set(['a-1']));+ tx.rollback();++ const restored =+ testQueryClient.getQueryData<+ InfiniteData<SoupAstItemsGroupedPage, unknown>+ >(key)!;+ expect(restored.pages[0].items['a-1']).toBeDefined();+ expect(restored.pages[0].groups[0].itemIds).toEqual(['a-1']);+ expect(restored.pages[0].groups[0].totalCount).toBe(1);+ });+});++describe('optimisticUpdateSoupEntity — cross-group move', () => {+ it('moves item id between groups via itemIds mutations only', () => {+ const items = [+ mockTaskItem('a-1', 'in_progress'),+ mockTaskItem('a-2', 'in_progress'),+ mockTaskItem('b-1', 'done'),+ ];+ const groups = [+ buildGroup('in_progress', ['a-1', 'a-2'], 5, 0),+ buildGroup('done', ['b-1'], 3, 1),+ ];+ const key = seedGroupedAstQuery(mockGroupedParentCache(items, groups));++ // Simulate what normy would do during the merge: the canonical entity+ // (status now `done`) is what reconcile reads from normy's store.+ const merged = mockTaskItem('a-1', 'done');+ mockNormalizer.getObjectById.mockReturnValue(merged);+ // The cache itself also reflects the merge — apply via setQueryData so+ // TanStack Query sees the new reference rather than mutating in place.+ const cached =+ testQueryClient.getQueryData<+ InfiniteData<SoupAstItemsGroupedPage, unknown>+ >(key)!;+ testQueryClient.setQueryData<+ InfiniteData<SoupAstItemsGroupedPage, unknown>+ >(key, {+ ...cached,+ pages: cached.pages.map((p, i) =>+ i === 0 ? { ...p, items: { ...p.items, 'a-1': merged } } : p+ ),+ });++ optimisticUpdateSoupEntity({+ tag: 'document',+ data: { id: 'a-1' },+ frecency_score: 1,+ } as unknown as Parameters<typeof optimisticUpdateSoupEntity>[0]);++ const after =+ testQueryClient.getQueryData<+ InfiniteData<SoupAstItemsGroupedPage, unknown>+ >(key)!;+ const page = after.pages[0];++ expect(page.items['a-1']).toBeDefined();++ const inProgress = page.groups.find((g) => g.key === 'in_progress')!;+ const done = page.groups.find((g) => g.key === 'done')!;+ expect(inProgress.itemIds).toEqual(['a-2']);+ expect(inProgress.totalCount).toBe(4);+ expect(done.itemIds).toEqual(['a-1', 'b-1']);+ expect(done.totalCount).toBe(4);+ });++ it('no-op when grouping membership did not change', () => {+ const items = [mockTaskItem('a-1', 'in_progress')];+ const groups = [buildGroup('in_progress', ['a-1'], 1, 0)];+ const key = seedGroupedAstQuery(mockGroupedParentCache(items, groups));++ mockNormalizer.getObjectById.mockReturnValue(+ mockTaskItem('a-1', 'in_progress')+ );++ optimisticUpdateSoupEntity({+ tag: 'document',+ data: { id: 'a-1' },+ frecency_score: 1,+ } as unknown as Parameters<typeof optimisticUpdateSoupEntity>[0]);++ const after =+ testQueryClient.getQueryData<+ InfiniteData<SoupAstItemsGroupedPage, unknown>+ >(key)!;+ expect(after.pages[0].groups[0].itemIds).toEqual(['a-1']);+ expect(after.pages[0].groups[0].totalCount).toBe(1);+ });+});diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.tsindex ba7dc5c83d..9fc6a53ade 100644--- a/js/app/packages/queries/soup/normalized-cache/operations.ts+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts@@ -14,59 +14,90 @@ import {import { isAfter } from 'date-fns';import { match } from 'ts-pattern';import { queryClient } from '../../client';-import type { SoupApiItemFilter } from '../items';+import type { SoupApiItemFilter, SoupAstItemsPage } from '../items';import { soupKeys } from '../keys';+import {+ insertGroupedPage,+ insertGroupQueries,+ removeGroupedPage,+ removeGroupQueries,+ syncGroupedParents,+ syncGroupQueries,+} from './grouped-operations';import {getNormalizationObjectKey,getSoupNormalizer,type NormalizerData,+ soupNormKey,+ stripSoupNormPrefix,} from './normalizer';import type {SoupEntityPartial,SoupEntityTag,SoupTransaction,} from './types';+import { getSoupQueryMeta } from './utils';++type SoupItemsInfiniteData = InfiniteData<SoupPage, unknown>;+type SoupAstItemsInfiniteData = InfiniteData<SoupAstItemsPage, unknown>;+type SoupSearchInfiniteData = InfiniteData<+ { results: UnifiedSearchResponseItem[] },+ unknown+>;/**- * Optimistically update a single soup entity across all queries that reference it.- * Returns a transaction whose `rollback()` restores only the affected queries- * Channels: `{ tag: 'channel', data: { channel: { id, ...fields } }, frecency_score }`- * Everything else: `{ tag, data: { id, ...fields }, frecency_score }`+ * Optimistically update a single soup entity across all queries that+ * reference it. After normy's field merge, reconciles group membership in+ * every grouped cache containing this entity (`itemIds`-only mutations;+ * the items pool itself isn't moved between groups). Date and+ * non-categorical groupings fall back to invalidation.+ *+ * Partial shape:+ * - Channels: `{ tag: 'channel', data: { channel: { id, ...fields } }, frecency_score }`+ * - Everything else: `{ tag, data: { id, ...fields }, frecency_score }`*/export function optimisticUpdateSoupEntity<T extends SoupEntityTag>(partial: SoupEntityPartial<T>): SoupTransaction {+ queryClient.cancelQueries({ queryKey: soupKeys.items._def });+ queryClient.cancelQueries({ queryKey: soupKeys.astItems._def });+const normalizer = getSoupNormalizer();const normKey = getNormalizationObjectKey(partial);const dependentKeys = normKey? normalizer.getDependentQueriesByIds([normKey]): [];-- const previous = dependentKeys.map(+ const previousDependents = dependentKeys.map((key: QueryKey) =>- [- key,- queryClient.getQueryData<InfiniteData<SoupPage, unknown>>(key),- ] as const+ [key, queryClient.getQueryData<SoupItemsInfiniteData>(key)] as const);+ const previousAllSoup = snapshotSoup();normalizer.setNormalizedData(partial as NormalizerData);+ if (normKey) {+ const entityId = stripSoupNormPrefix(normKey);+ const entity = getSoupEntityById(entityId);+ if (entity) {+ syncGroupedParents(entityId, entity);+ syncGroupQueries(entityId, entity);+ }+ }+return {rollback: () => {- for (const [key, data] of previous) {+ for (const [key, data] of previousDependents) {queryClient.setQueryData(key, data);}+ restoreSnapshot(previousAllSoup);},};}-/** Read an entity from normy's normalized store by ID. Returns `undefined` if not cached. */export function getSoupEntityById(entityId: string): SoupApiItem | undefined {- return (getSoupNormalizer().getObjectById(`soup:${entityId}`) ?? undefined) as- | SoupApiItem- | undefined;+ return (getSoupNormalizer().getObjectById(soupNormKey(entityId)) ??+ undefined) as SoupApiItem | undefined;}/**@@ -75,7 +106,7 @@ export function getSoupEntityById(entityId: string): SoupApiItem | undefined {*/export function invalidateSoupEntity(entityId: string): void {const normalizer = getSoupNormalizer();- const keys = normalizer.getDependentQueriesByIds([`soup:${entityId}`]);+ const keys = normalizer.getDependentQueriesByIds([soupNormKey(entityId)]);for (const queryKey of keys) {queryClient.invalidateQueries({ queryKey });}@@ -91,12 +122,11 @@ export function invalidateAllSoup(): void {});}-/** O(1) check whether an entity exists in normy's normalized store. */export function hasSoupEntity(entityId: string): boolean {- return getSoupNormalizer().getObjectById(`soup:${entityId}`) != null;+ return getSoupNormalizer().getObjectById(soupNormKey(entityId)) != null;}-/** Extract the canonical entity ID from a SoupApiItem (handles channel's nested `data.channel.id` and callRecord's `data.callId`). */+/** Channels nest the id under `data.channel.id`; call records under `data.callId`. */export function getSoupItemId(item: SoupApiItem): string {switch (item.tag) {case 'channel':@@ -110,106 +140,173 @@ export function getSoupItemId(item: SoupApiItem): string {/*** Insert a new entity into the first page of every active soup list query.- * Normy auto-normalizes the entry on insertion, making it available via `getSoupEntityById`.- * Use for entities that don't yet exist in the cache. For existing entities use- * `optimisticUpdateSoupEntity` (deep-merge) instead.+ * Grouped pages: derive the item's target groups via `computeGroupKeysForItem`+ * and upsert into each resolvable group. Date / unresolved labels invalidate.*/export function insertSoupEntity(item: SoupApiItem): SoupTransaction {- const previous = snapshotSoup();+ queryClient.cancelQueries({ queryKey: soupKeys.items._def });+ queryClient.cancelQueries({ queryKey: soupKeys.astItems._def });- queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(+ const previous = snapshotSoup();+ queryClient.setQueriesData<SoupItemsInfiniteData>({predicate: (query) => {- const matchingKey =- partialMatchKey(query.queryKey, soupKeys.astItems._def) ||- partialMatchKey(query.queryKey, soupKeys.items._def);-+ if (!partialMatchKey(query.queryKey, soupKeys.items._def)) return false;const filter = query.meta?.itemFilter as SoupApiItemFilter | undefined;- if (!filter) return matchingKey;- return filter(item) && matchingKey;+ return filter ? filter(item) : true;},},(prev) => {- if (!prev || !prev.pages) return prev;+ if (!prev?.pages) return prev;return {...prev,- pages: prev.pages.map((p, i) => {- if (i !== 0) return p;- return { ...p, items: [item, ...p.items] };- }),+ pages: prev.pages.map((p, i) =>+ i === 0 ? { ...p, items: [item, ...p.items] } : p+ ),};});+ const parents = queryClient.getQueriesData<SoupAstItemsInfiniteData>({+ queryKey: soupKeys.astItems._def,+ });++ for (const [key, prev] of parents) {+ if (!prev?.pages?.length) continue;++ const meta = getSoupQueryMeta(+ queryClient.getQueryCache().find({ queryKey: key })?.meta+ );+ const filter = meta.itemFilter;+ if (filter && !filter(item)) continue;++ const firstPage = prev.pages[0];++ if (firstPage.kind === 'flat') {+ queryClient.setQueryData<SoupAstItemsInfiniteData>(key, {+ ...prev,+ pages: prev.pages.map((p, i) =>+ i === 0 && p.kind === 'flat' ? { ...p, items: [item, ...p.items] } : p+ ),+ });++ continue;+ }++ const nextPage = insertGroupedPage(+ firstPage,+ item,+ getSoupItemId(item),+ meta.groupBy+ );++ if (!nextPage) {+ queryClient.invalidateQueries({ queryKey: key });+ continue;+ }++ queryClient.setQueryData<SoupAstItemsInfiniteData>(key, {+ ...prev,+ pages: [nextPage, ...prev.pages.slice(1)],+ });+ }++ insertGroupQueries(item, getSoupItemId(item));+return { rollback: () => restoreSnapshot(previous) };}-/**- * Optimistically remove entities from all soup list queries.- * Cancels in-flight fetches first to prevent them from re-adding removed items.- * Snapshots the full soup cache before mutating — rollback restores everything.- */export function removeSoupEntities(entityIds: Set<string>): SoupTransaction {queryClient.cancelQueries({ queryKey: soupKeys.items._def });queryClient.cancelQueries({ queryKey: soupKeys.astItems._def });const previous = snapshotSoup();- queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(+ queryClient.setQueriesData<SoupItemsInfiniteData>({- predicate(query) {- return (- partialMatchKey(query.queryKey, soupKeys.astItems._def) ||- partialMatchKey(query.queryKey, soupKeys.items._def)- );- },+ predicate: (q) => partialMatchKey(q.queryKey, soupKeys.items._def),},(prev) => {- if (!prev || !prev.pages) return prev;+ if (!prev?.pages) return prev;return {...prev,pages: prev.pages.map((page) => {const items = page.items.filter((item) => !entityIds.has(getSoupItemId(item)));- return items.length === page.items.length ? page : { ...page, items };+ if (items.length === page.items.length) return page;+ return { ...page, items };}),};});+ queryClient.setQueriesData<SoupAstItemsInfiniteData>(+ { queryKey: soupKeys.astItems._def },+ (prev) => {+ if (!prev?.pages?.length) return prev;++ const firstPage = prev.pages[0];++ if (firstPage.kind === 'flat') {+ // Flat AST queries can have multiple pages; remove the ids from every+ // page and preserve page references that were not affected.+ let changed = false;+ const pages = prev.pages.map((page) => {+ if (page.kind !== 'flat') return page;++ const items = page.items.filter(+ (item) => !entityIds.has(getSoupItemId(item))+ );++ if (items.length === page.items.length) return page;++ changed = true;+ return { ...page, items };+ });++ return changed ? { ...prev, pages } : prev;+ }++ // Grouped AST queries only use the first parent page. Group membership is+ // fully represented there by `groups[].itemIds`, so update that page once.+ const nextPage = removeGroupedPage(firstPage, entityIds);++ return nextPage === firstPage+ ? prev+ : { ...prev, pages: [nextPage, ...prev.pages.slice(1)] };+ }+ );++ removeGroupQueries(entityIds);+return { rollback: () => restoreSnapshot(previous) };}-/**- * Optimistically remove entities from all search result queries.- * Same cancel-snapshot-mutate pattern as `removeSoupEntities` but targets search queries.- */export function removeSearchEntities(entityIds: Set<string>): SoupTransaction {queryClient.cancelQueries({ queryKey: soupKeys.search._def });- const previous = queryClient.getQueriesData<- InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown>- >({+ const previous = queryClient.getQueriesData<SoupSearchInfiniteData>({queryKey: soupKeys.search._def,});- queryClient.setQueriesData<- InfiniteData<{ results: UnifiedSearchResponseItem[] }, unknown>- >({ queryKey: soupKeys.search._def }, (prev) => {- if (!prev) return prev;- return {- ...prev,- pages: prev.pages.map((page) => {- const results = page.results.filter(- (result) => !entityIds.has(getSearchResultId(result))- );- return results.length === page.results.length- ? page- : { ...page, results };- }),- };- });+ queryClient.setQueriesData<SoupSearchInfiniteData>(+ { queryKey: soupKeys.search._def },+ (prev) => {+ if (!prev) return prev;+ return {+ ...prev,+ pages: prev.pages.map((page) => {+ const results = page.results.filter(+ (result) => !entityIds.has(getSearchResultId(result))+ );+ return results.length === page.results.length+ ? page+ : { ...page, results };+ }),+ };+ }+ );return {rollback: () => {@@ -256,6 +353,7 @@ export async function refetchSoupEntity(optimisticUpdateSoupEntity(item);} else {insertSoupEntity(item);+ invalidateAllSoup();}}}@@ -403,20 +501,22 @@ function getSearchResultId(result: UnifiedSearchResponseItem): string {.exhaustive();}-/** @private */-function snapshotSoup(): [- QueryKey,- InfiniteData<SoupPage, unknown> | undefined,-][] {- return queryClient.getQueriesData<InfiniteData<SoupPage, unknown>>({- queryKey: soupKeys.astItems._def,- });+/** @private Captures every soup-list-shaped query (legacy items, parent+ * astItems, per-group caches) for full-range rollback. */+function snapshotSoup(): [QueryKey, unknown][] {+ return [+ ...queryClient.getQueriesData<unknown>({ queryKey: soupKeys.items._def }),+ ...queryClient.getQueriesData<unknown>({+ queryKey: soupKeys.astItems._def,+ }),+ ...queryClient.getQueriesData<unknown>({+ queryKey: soupKeys.groupedGroup._def,+ }),+ ];}/** @private */-function restoreSnapshot(- snapshot: [QueryKey, InfiniteData<SoupPage, unknown> | undefined][]-): void {+function restoreSnapshot(snapshot: [QueryKey, unknown][]): void {for (const [key, data] of snapshot) {queryClient.setQueryData(key, data);}diff --git a/js/app/packages/queries/soup/normalized-cache/utils.ts b/js/app/packages/queries/soup/normalized-cache/utils.tsnew file mode 100644index 0000000000..02e2a70997--- /dev/null+++ b/js/app/packages/queries/soup/normalized-cache/utils.ts@@ -0,0 +1,37 @@+import { GROUP_BY_TYPES, type GroupByField } from '../grouped/types';+import type { SoupApiItemFilter } from '../items';++export type SoupQueryMeta = {+ groupBy?: GroupByField;+ groupKey?: string;+ itemFilter?: SoupApiItemFilter;+};++export function getSoupQueryMeta(meta: unknown): SoupQueryMeta {+ if (!meta || typeof meta !== 'object') return {};++ const raw = meta as Record<string, unknown>;+ const soupMeta: SoupQueryMeta = {};++ if (isGroupByField(raw.groupBy)) soupMeta.groupBy = raw.groupBy;+ if (typeof raw.groupKey === 'string') soupMeta.groupKey = raw.groupKey;+ if (typeof raw.itemFilter === 'function') {+ soupMeta.itemFilter = raw.itemFilter as SoupApiItemFilter;+ }++ return soupMeta;+}++function isGroupByField(value: unknown): value is GroupByField {+ if (!value || typeof value !== 'object') return false;++ const groupBy = value as Record<string, unknown>;+ const type = groupBy.type;+ if (typeof type !== 'string') return false;++ if (!GROUP_BY_TYPES.some((groupByType) => groupByType === type)) return false;++ return (+ type !== 'property' || typeof groupBy.propertyDefinitionId === 'string'+ );+}diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex ee5ab1d70f..8fa4aafee0 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -36,12 +36,14 @@ import type {} from '@service-search/generated/models';import type {GithubPullRequest,+ SoupApiItem,SoupDocument,SoupPage,} from '@service-storage/generated/schemas';import type { ChannelType } from '@service-storage/generated/schemas/channelType';import type { UseQueryResult } from '@tanstack/solid-query';import { differenceInMilliseconds } from 'date-fns';+import { match } from 'ts-pattern';type InnerSearchResult =| DocumentSearchResult@@ -499,6 +501,10 @@ const resolveDocumentEntityName = (});};+export const isDisplayableSoupItem = (+ _: SoupPage['items'][number]+): _ is DisplayableSoupItem => true;+/*** The email soup query encodes "no sort timestamp" — e.g. a never-viewed thread* under the `viewed_at` sort — as the Unix epoch. Map it to `undefined` so each@@ -512,6 +518,217 @@ function normalizeSentinelTs(return Date.parse(ts) > 0 ? ts : undefined;}+export const mapApiSoupItemToEntity = (item: DisplayableSoupItem): SoupEntity =>+ match(item)+ .with({ tag: 'chat' }, (item) => ({+ ...item.data,+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ type: item.tag,+ name: item.data.name || 'New Chat',+ frecencyScore: item.frecency_score,+ viewedAt: item.data.viewedAt,+ projectId: item.data.projectId ?? undefined,+ }))+ .with({ tag: 'project' }, (item) => ({+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ id: item.data.id,+ ownerId: item.data.ownerId,+ frecencyScore: item.frecency_score,+ viewedAt: item.data.viewedAt,+ projectId: item.data.parentId ?? undefined,+ type: item.tag,+ name: item.data.name || 'New Project',+ }))+ .with({ tag: 'emailThread' }, (item) => {+ const participants = item.data.participants?.map((p) => ({+ email: p.emailAddress ?? '',+ name: p.name ?? '',+ }));++ const hasIcsAttachment = item.data.attachments?.some(+ (a) =>+ a.mimeType === 'text/calendar' ||+ a.filename?.toLowerCase().endsWith('.ics')+ );++ const attachments = item.data.attachments?.map((a) => ({+ id: a.id,+ filename: a.filename,+ mimeType: a.mimeType,+ sizeBytes: a.sizeBytes,+ }));++ // The thread preview has no link id of its own; its participants and+ // labels are scoped to the owning inbox, so they share its link id.+ const linkId =+ item.data.participants?.[0]?.linkId ?? item.data.labels?.[0]?.linkId;++ return {+ ...item.data,+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ sortTs: normalizeSentinelTs(item.data.sortTs),+ senderEmail: item.data.senderEmail ?? undefined,+ senderName: item.data.senderName ?? undefined,+ snippet: item.data.snippet ?? undefined,+ done: !item.data.inboxVisible,+ type: 'email',+ name: item.data.name || 'Email Thread',+ frecencyScore: item.frecency_score,+ viewedAt: item.data.viewedAt,+ projectId: item.data.projectId ?? undefined,+ linkId,+ participants,+ hasIcsAttachment,+ attachments,+ } satisfies EmailEntity;+ })+ .with({ tag: 'call' }, (item) => {+ const status = item.data.status;++ return {+ type: 'call',+ id: item.data.callId,+ name:+ item.data.customName ??+ item.data.channelName ??+ blockNameToDefaultFile('call'),+ channelId: item.data.channelId,+ channelName: item.data.channelName ?? undefined,+ ownerId: item.data.createdBy,+ createdAt: item.data.startedAt,+ updatedAt: item.data.endedAt ?? item.data.startedAt,+ sortTs: item.data.endedAt ?? item.data.startedAt,+ isActive: item.data.isActive,+ status,+ attended: status === 'ATTENDED',+ durationMs: item.data.durationMs ?? undefined,+ participantIds: item.data.participants.map((p) => p.userId),+ summary: item.data.summary ?? undefined,+ } satisfies CallEntity;+ })+ .with({ tag: 'channel' }, (item) => {+ const latestMessage =+ item.data.latest_message ?? item.data.latest_non_thread_message;++ const out: ChannelEntity = {+ type: 'channel',+ id: item.data.channel.id,+ name: item.data.channel.name || 'Unknown Channel',+ channelType: item.data.channel.channel_type,+ ownerId: item.data.channel.owner_id,+ frecencyScore: item.frecency_score ?? 0,+ updatedAt: item.data.channel.updated_at,+ createdAt: item.data.channel.created_at,+ participantIds: item.data.participants.map((p) => p.user_id),+ viewedAt: item.data.viewed_at ?? item.data.interacted_at,+ interactedAt: item.data.interacted_at,+ latestMessage: latestMessage+ ? {+ messageId: latestMessage.message_id,+ threadId: latestMessage.thread_id ?? undefined,+ content: latestMessage.content,+ senderId: latestMessage.sender_id,+ createdAt: latestMessage.created_at,+ }+ : undefined,+ };+ return out;+ })+ .with({ tag: 'foreignEntity' }, (item) => {+ const metadata = item.data.metadata as unknown as GithubPullRequest;++ let status: GithubPullRequestEntity['metadata']['status'] = 'open';++ if (metadata.status === 'merged') {+ status = 'merged';+ } else if (metadata.status === 'closed') {+ status = 'closed';+ }++ const out: GithubPullRequestEntity = {+ type: 'foreign',+ id: item.data.id,+ name: metadata.name ?? metadata.displayName,+ ownerId: item.data.storedForId,+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ foreignSource: 'github_pull_request',+ foreignId: item.data.foreignEntityId,+ storedForId: item.data.storedForId,+ storedForAuthEntity: item.data.storedForAuthEntity,+ metadata: {+ number: metadata.number,+ name: metadata.name ?? metadata.displayName,+ owner: metadata.owner,+ repo: metadata.repo,+ url: metadata.url,+ status: status,+ additions: metadata.additions ?? 0,+ deletions: metadata.deletions ?? 0,+ comments: metadata.comments ?? [],+ checks: metadata.checks?.filter(Boolean) ?? [],+ },+ };++ return out;+ })+ .with({ tag: 'document' }, (item) => ({+ ...item.data,+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ type: item.tag,+ frecencyScore: item.frecency_score,+ viewedAt: item.data.viewedAt,+ fileType: item.data.fileType ?? undefined,+ projectId: item.data.projectId ?? undefined,+ subType:+ item.data.subType === null || item.data.subType === undefined+ ? undefined+ : {+ type: item.data.subType.type as 'task',+ is_completed: item.data.subType.is_completed,+ },+ name: resolveDocumentEntityName(item.data),+ }))+ .with({ tag: 'crmCompany' }, (item) => {+ const primaryDomain = item.data.domains[0]?.domain;+ return {+ type: 'crm_company',+ id: item.data.id,+ teamId: item.data.teamId,+ name: item.data.name || primaryDomain || 'Unknown Company',+ ownerId: item.data.teamId,+ description: item.data.description ?? undefined,+ emailSync: item.data.emailSync,+ hidden: item.data.hidden,+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ sortTs: item.data.updatedAt,+ frecencyScore: item.frecency_score,+ domains: item.data.domains.map((d) => ({+ id: d.id,+ companyId: d.companyId,+ domain: d.domain,+ createdAt: d.createdAt,+ })),+ } satisfies CrmCompanyEntity;+ })+ .exhaustive();++export const isInstructionsMdDoc = (+ item: SoupApiItem,+ instructionsIdQuery: UseQueryResult<string | null | undefined, Error>+) => {+ if (item.tag !== 'document') return false;++ if (!instructionsIdQuery.isSuccess) return false;++ return item.data.id === instructionsIdQuery.data;+};+export const mapSoupPageToEntityList: (data: SoupPage,options: {@@ -530,217 +747,8 @@ export const mapSoupPageToEntityList: (return (item.tag !== 'document' ||- !options.instructionsIdQuery.isSuccess ||- item.data.id !== options.instructionsIdQuery.data+ !isInstructionsMdDoc(item, options.instructionsIdQuery));})- .map((item): SoupEntity => {- if (item.tag === 'chat') {- return {- ...item.data,- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- type: item.tag,- name: item.data.name || 'New Chat',- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt,- projectId: item.data.projectId ?? undefined,- };- }-- if (item.tag === 'project') {- return {- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- id: item.data.id,- ownerId: item.data.ownerId,- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt,- projectId: item.data.parentId ?? undefined,- type: item.tag,- name: item.data.name || 'New Project',- };- }-- if (item.tag === 'emailThread') {- const participants = item.data.participants?.map((p) => ({- email: p.emailAddress ?? '',- name: p.name ?? '',- }));-- const hasIcsAttachment = item.data.attachments?.some(- (a) =>- a.mimeType === 'text/calendar' ||- a.filename?.toLowerCase().endsWith('.ics')- );-- const attachments = item.data.attachments?.map((a) => ({- id: a.id,- filename: a.filename,- mimeType: a.mimeType,- sizeBytes: a.sizeBytes,- }));-- // The thread preview has no link id of its own; its participants and- // labels are scoped to the owning inbox, so they share its link id.- const linkId =- item.data.participants?.[0]?.linkId ?? item.data.labels?.[0]?.linkId;-- return {- ...item.data,- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- sortTs: normalizeSentinelTs(item.data.sortTs),- senderEmail: item.data.senderEmail ?? undefined,- senderName: item.data.senderName ?? undefined,- snippet: item.data.snippet ?? undefined,- done: !item.data.inboxVisible,- type: 'email',- name: item.data.name || 'Email Thread',- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt,- projectId: item.data.projectId ?? undefined,- linkId,- participants,- hasIcsAttachment,- attachments,- };- }-- if (item.tag === 'call') {- const status = item.data.status;-- return {- type: 'call',- id: item.data.callId,- name:- item.data.customName ??- item.data.channelName ??- blockNameToDefaultFile('call'),- channelId: item.data.channelId,- channelName: item.data.channelName ?? undefined,- ownerId: item.data.createdBy,- createdAt: item.data.startedAt,- updatedAt: item.data.endedAt ?? item.data.startedAt,- sortTs: item.data.endedAt ?? item.data.startedAt,- isActive: item.data.isActive,- status,- attended: status === 'ATTENDED',- durationMs: item.data.durationMs ?? undefined,- participantIds: item.data.participants.map((p) => p.userId),- summary: item.data.summary ?? undefined,- } satisfies CallEntity;- }-- if (item.tag === 'channel') {- const latestMessage =- item.data.latest_message ?? item.data.latest_non_thread_message;-- const out: ChannelEntity = {- type: 'channel',- id: item.data.channel.id,- name: item.data.channel.name || 'Unknown Channel',- channelType: item.data.channel.channel_type,- ownerId: item.data.channel.owner_id,- frecencyScore: item.frecency_score ?? 0,- updatedAt: item.data.channel.updated_at,- createdAt: item.data.channel.created_at,- participantIds: item.data.participants.map((p) => p.user_id),- viewedAt: item.data.viewed_at ?? item.data.interacted_at,- interactedAt: item.data.interacted_at,- latestMessage: latestMessage- ? {- messageId: latestMessage.message_id,- threadId: latestMessage.thread_id ?? undefined,- content: latestMessage.content,- senderId: latestMessage.sender_id,- createdAt: latestMessage.created_at,- }- : undefined,- };- return out;- }-- if (item.tag === 'foreignEntity') {- const metadata = item.data.metadata as unknown as GithubPullRequest;-- let status: GithubPullRequestEntity['metadata']['status'] = 'open';-- if (metadata.status === 'merged') {- status = 'merged';- } else if (metadata.status === 'closed') {- status = 'closed';- }-- const out: GithubPullRequestEntity = {- type: 'foreign',- id: item.data.id,- name: metadata.name ?? metadata.displayName,- ownerId: item.data.storedForId,- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- foreignSource: 'github_pull_request',- foreignId: item.data.foreignEntityId,- storedForId: item.data.storedForId,- storedForAuthEntity: item.data.storedForAuthEntity,- metadata: {- number: metadata.number,- name: metadata.name ?? metadata.displayName,- owner: metadata.owner,- repo: metadata.repo,- url: metadata.url,- status: status,- additions: metadata.additions ?? 0,- deletions: metadata.deletions ?? 0,- comments: metadata.comments ?? [],- checks: metadata.checks?.filter(Boolean) ?? [],- },- };-- return out;- }-- if (item.tag === 'crmCompany') {- const primaryDomain = item.data.domains[0]?.domain;- return {- type: 'crm_company',- id: item.data.id,- teamId: item.data.teamId,- name: item.data.name || primaryDomain || 'Unknown Company',- ownerId: item.data.teamId,- description: item.data.description ?? undefined,- emailSync: item.data.emailSync,- hidden: item.data.hidden,- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- sortTs: item.data.updatedAt,- frecencyScore: item.frecency_score,- domains: item.data.domains.map((d) => ({- id: d.id,- companyId: d.companyId,- domain: d.domain,- createdAt: d.createdAt,- })),- } satisfies CrmCompanyEntity;- }-- return {- ...item.data,- createdAt: item.data.createdAt,- updatedAt: item.data.updatedAt,- type: item.tag,- frecencyScore: item.frecency_score,- viewedAt: item.data.viewedAt,- fileType: item.data.fileType ?? undefined,- projectId: item.data.projectId ?? undefined,- subType:- item.data.subType === null || item.data.subType === undefined- ? undefined- : {- type: item.data.subType.type as 'task',- is_completed: item.data.subType.is_completed,- },- name: resolveDocumentEntityName(item.data),- };- });+ .map(mapApiSoupItemToEntity);};diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex 3ed471587a..08b15787ec 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -31,6 +31,11 @@ import type {AccessLevel,CallRecordPreview,GithubPullRequestsResponse,+ GroupedSoupGroupPage,+ GroupedSoupInitialPage,+ PostGroupedSoupAstGroupPageRequest,+ PostGroupedSoupAstInitialRequest,+ PostGroupedSoupAstRequest,PostSoupAstRequest,PostSoupRequest,SoupPage,@@ -360,10 +365,34 @@ export const storageServiceClient = {},async getGroupedSoupAstItems(args: {+ params: {+ group_by: PostGroupedSoupAstInitialRequest['group_by'];+ per_group_limit?: number | null;+ };+ body: PostSoupAstRequest;+ }) {+ const { limit: _limit, sort_method: _sortMethod, ...filters } = args.body;+ const body = {+ ...filters,+ mode: 'initial',+ group_by: args.params.group_by,+ ...(args.params.per_group_limit != null && {+ per_group_limit: args.params.per_group_limit,+ }),+ } satisfies PostGroupedSoupAstRequest;++ return await dssFetch<GroupedSoupInitialPage>(`/items/soup/ast/grouped`, {+ method: 'POST',+ body: JSON.stringify(body),+ });+ },++ async getGroupedSoupAstGroupPage(args: {params: {cursor?: string | null;- group_by: unknown;- group_key?: string | null;+ group_by: PostGroupedSoupAstGroupPageRequest['group_by'];+ group_key: string;+ limit?: number | null;};body: PostSoupAstRequest;}) {@@ -371,26 +400,22 @@ export const storageServiceClient = {if (args.params.cursor) params.set('cursor', args.params.cursor);const searchParams = params.toString() ? `?${params.toString()}` : '';- const body: Record<string, unknown> = { ...args.body };- if (args.params.group_by) body.group_by = args.params.group_by;- if (args.params.group_key != null) body.group_key = args.params.group_key;-- return await dssFetch<- SoupPage & {- groups?: {- key: string;- label: string;- display_order: number | null;- total_count: number;- page_count: number;- start_index: number;- next_cursor: string | null;- }[];+ const { limit: _limit, sort_method: _sortMethod, ...filters } = args.body;+ const body = {+ ...filters,+ mode: 'group_page',+ group_by: args.params.group_by,+ group_key: args.params.group_key,+ ...(args.params.limit != null && { limit: args.params.limit }),+ } satisfies PostGroupedSoupAstRequest;++ return await dssFetch<GroupedSoupGroupPage>(+ `/items/soup/ast/grouped${searchParams}`,+ {+ method: 'POST',+ body: JSON.stringify(body),}- >(`/items/soup/ast/grouped${searchParams}`, {- method: 'POST',- body: JSON.stringify(body),- });+ );},async createChannel(args: CreateChannelRequest) {diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByField.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByField.tsnew file mode 100644index 0000000000..08163df565--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByField.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiGroupByFieldOneOf } from './apiGroupByFieldOneOf';++/**+ * API representation of group-by field.+ */+export type ApiGroupByField =+ | 'date'+ | 'entity_type'+ | 'project'+ | ApiGroupByFieldOneOf;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByFieldOneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByFieldOneOf.tsnew file mode 100644index 0000000000..6ae05f77d8--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByFieldOneOf.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiGroupByFieldOneOfProperty } from './apiGroupByFieldOneOfProperty';++/**+ * Group by a property value (e.g., status, priority, or custom properties)+ */+export type ApiGroupByFieldOneOf = {+ /** Group by a property value (e.g., status, priority, or custom properties) */+ property: ApiGroupByFieldOneOfProperty;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByFieldOneOfProperty.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByFieldOneOfProperty.tsnew file mode 100644index 0000000000..598ad30070--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByFieldOneOfProperty.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiGroupByFieldOneOfPropertyEntityType } from './apiGroupByFieldOneOfPropertyEntityType';++/**+ * Group by a property value (e.g., status, priority, or custom properties)+ */+export type ApiGroupByFieldOneOfProperty = {+ entity_type?: ApiGroupByFieldOneOfPropertyEntityType;+ /** The property definition UUID to group by */+ property_definition_id: string;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByFieldOneOfPropertyEntityType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByFieldOneOfPropertyEntityType.tsnew file mode 100644index 0000000000..cfabee4ad3--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupByFieldOneOfPropertyEntityType.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiPropertyEntityType } from './apiPropertyEntityType';++export type ApiGroupByFieldOneOfPropertyEntityType =+ null | ApiPropertyEntityType;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupMeta.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupMeta.tsnew file mode 100644index 0000000000..3057000542--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupMeta.ts@@ -0,0 +1,33 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiGroupMetaDisplayOrder } from './apiGroupMetaDisplayOrder';+import type { ApiGroupMetaNextCursor } from './apiGroupMetaNextCursor';++/**+ * API representation of group metadata.++Items belonging to this group are referenced by `item_ids`, each of which+looks up an entry in `GroupedSoupPage.items` (a normalized pool).+ */+export interface ApiGroupMeta {+ /** Display order for sorting groups (lower = first) */+ display_order?: ApiGroupMetaDisplayOrder;+ /** Ordered ids of items in this group for the current page.+Each id keys into `GroupedSoupPage.items`. */+ item_ids: string[];+ /** Group key - format depends on group_by field */+ key: string;+ /** Human-readable label for the group */+ label: string;+ /** Cursor to load more items specifically from this group */+ next_cursor?: ApiGroupMetaNextCursor;+ /**+ * Total count of items in this group across all pages+ * @minimum 0+ */+ total_count: number;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupMetaDisplayOrder.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupMetaDisplayOrder.tsnew file mode 100644index 0000000000..c82a371853--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupMetaDisplayOrder.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Display order for sorting groups (lower = first)+ */+export type ApiGroupMetaDisplayOrder = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupMetaNextCursor.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupMetaNextCursor.tsnew file mode 100644index 0000000000..f906349a7c--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiGroupMetaNextCursor.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Cursor to load more items specifically from this group+ */+export type ApiGroupMetaNextCursor = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiPropertyEntityType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiPropertyEntityType.tsnew file mode 100644index 0000000000..d573ee1e4d--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiPropertyEntityType.ts@@ -0,0 +1,24 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Entity type for property lookups (API representation).+ */+export type ApiPropertyEntityType =+ (typeof ApiPropertyEntityType)[keyof typeof ApiPropertyEntityType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ApiPropertyEntityType = {+ CHANNEL: 'CHANNEL',+ CHAT: 'CHAT',+ COMPANY: 'COMPANY',+ DOCUMENT: 'DOCUMENT',+ PROJECT: 'PROJECT',+ TASK: 'TASK',+ THREAD: 'THREAD',+ USER: 'USER',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedInitialParams.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedInitialParams.tsnew file mode 100644index 0000000000..6af4364d51--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedInitialParams.ts@@ -0,0 +1,23 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiGroupByField } from './apiGroupByField';+import type { GroupedInitialParamsPerGroupLimit } from './groupedInitialParamsPerGroupLimit';+import type { GroupedInitialParamsSortMethod } from './groupedInitialParamsSortMethod';++/**+ * Parameters for the initial grouped soup query.+ */+export interface GroupedInitialParams {+ /** Field to group results by (required). */+ group_by: ApiGroupByField;+ /**+ * Limit the number of items returned per group. Defaults to 20. Max 500.+ * @minimum 0+ */+ per_group_limit?: GroupedInitialParamsPerGroupLimit;+ sort_method?: GroupedInitialParamsSortMethod;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedInitialParamsPerGroupLimit.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedInitialParamsPerGroupLimit.tsnew file mode 100644index 0000000000..095dcca97e--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedInitialParamsPerGroupLimit.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Limit the number of items returned per group. Defaults to 20. Max 500.+ * @minimum 0+ */+export type GroupedInitialParamsPerGroupLimit = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedInitialParamsSortMethod.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedInitialParamsSortMethod.tsnew file mode 100644index 0000000000..2bb906f6c2--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedInitialParamsSortMethod.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { GroupedSoupSort } from './groupedSoupSort';++export type GroupedInitialParamsSortMethod = null | GroupedSoupSort;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedPageParams.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedPageParams.tsnew file mode 100644index 0000000000..9461616e03--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedPageParams.ts@@ -0,0 +1,25 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiGroupByField } from './apiGroupByField';+import type { GroupedPageParamsLimit } from './groupedPageParamsLimit';+import type { GroupedPageParamsSortMethod } from './groupedPageParamsSortMethod';++/**+ * Parameters for fetching one page within a specific group.+ */+export interface GroupedPageParams {+ /** Field to group results by (required). */+ group_by: ApiGroupByField;+ /** Group key to fetch. */+ group_key: string;+ /**+ * Limit the number of items returned. Defaults to 20. Max 500.+ * @minimum 0+ */+ limit?: GroupedPageParamsLimit;+ sort_method?: GroupedPageParamsSortMethod;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedPageParamsLimit.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedPageParamsLimit.tsnew file mode 100644index 0000000000..7f0743160a--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedPageParamsLimit.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Limit the number of items returned. Defaults to 20. Max 500.+ * @minimum 0+ */+export type GroupedPageParamsLimit = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedPageParamsSortMethod.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedPageParamsSortMethod.tsnew file mode 100644index 0000000000..e3bb0b343b--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedPageParamsSortMethod.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { GroupedSoupSort } from './groupedSoupSort';++export type GroupedPageParamsSortMethod = null | GroupedSoupSort;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupGroupPage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupGroupPage.tsnew file mode 100644index 0000000000..85a5700aaa--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupGroupPage.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiGroupMeta } from './apiGroupMeta';+import type { GroupedSoupGroupPageItems } from './groupedSoupGroupPageItems';++/**+ * Response for fetching a page within one group.+ */+export interface GroupedSoupGroupPage {+ /** Metadata and item membership for the requested group page. */+ group: ApiGroupMeta;+ /** Items in this page, keyed by id. Ordering lives in `group.item_ids`. */+ items: GroupedSoupGroupPageItems;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupGroupPageItems.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupGroupPageItems.tsnew file mode 100644index 0000000000..c26910ff08--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupGroupPageItems.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { SoupApiItem } from './soupApiItem';++/**+ * Items in this page, keyed by id. Ordering lives in `group.item_ids`.+ */+export type GroupedSoupGroupPageItems = { [key: string]: SoupApiItem };diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupInitialPage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupInitialPage.tsnew file mode 100644index 0000000000..d762ff1117--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupInitialPage.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiGroupMeta } from './apiGroupMeta';+import type { GroupedSoupInitialPageItems } from './groupedSoupInitialPageItems';++/**+ * Response for the initial grouped soup query.++Items are returned as a pool keyed by id; each `ApiGroupMeta.item_ids`+describes the ordered membership of one group.+ */+export interface GroupedSoupInitialPage {+ /** Ordered group metadata for this grouped response. */+ groups: ApiGroupMeta[];+ /** Items in this page, keyed by id. Ordering lives in `groups[].item_ids`. */+ items: GroupedSoupInitialPageItems;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupInitialPageItems.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupInitialPageItems.tsnew file mode 100644index 0000000000..82758e8a18--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupInitialPageItems.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { SoupApiItem } from './soupApiItem';++/**+ * Items in this page, keyed by id. Ordering lives in `groups[].item_ids`.+ */+export type GroupedSoupInitialPageItems = { [key: string]: SoupApiItem };diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPage.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPage.tsnew file mode 100644index 0000000000..dd3ab17acf--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPage.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { GroupedSoupPageOneOf } from './groupedSoupPageOneOf';+import type { GroupedSoupPageOneOfFour } from './groupedSoupPageOneOfFour';++/**+ * Response for grouped soup queries.+ */+export type GroupedSoupPage = GroupedSoupPageOneOf | GroupedSoupPageOneOfFour;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOf.tsnew file mode 100644index 0000000000..5fa2b5fef7--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { GroupedSoupInitialPage } from './groupedSoupInitialPage';+import type { GroupedSoupPageOneOfAllOf } from './groupedSoupPageOneOfAllOf';++export type GroupedSoupPageOneOf = GroupedSoupInitialPage &+ GroupedSoupPageOneOfAllOf;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfAllOf.tsnew file mode 100644index 0000000000..312d16df74--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { GroupedSoupPageOneOfAllOfMode } from './groupedSoupPageOneOfAllOfMode';++export type GroupedSoupPageOneOfAllOf = {+ mode: GroupedSoupPageOneOfAllOfMode;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfAllOfMode.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfAllOfMode.tsnew file mode 100644index 0000000000..71101938c2--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfAllOfMode.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type GroupedSoupPageOneOfAllOfMode =+ (typeof GroupedSoupPageOneOfAllOfMode)[keyof typeof GroupedSoupPageOneOfAllOfMode];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const GroupedSoupPageOneOfAllOfMode = {+ initial: 'initial',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfFour.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfFour.tsnew file mode 100644index 0000000000..a6c058aed4--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfFour.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { GroupedSoupGroupPage } from './groupedSoupGroupPage';+import type { GroupedSoupPageOneOfFourAllOf } from './groupedSoupPageOneOfFourAllOf';++export type GroupedSoupPageOneOfFour = GroupedSoupGroupPage &+ GroupedSoupPageOneOfFourAllOf;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfFourAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfFourAllOf.tsnew file mode 100644index 0000000000..b0e805a1d9--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfFourAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { GroupedSoupPageOneOfFourAllOfMode } from './groupedSoupPageOneOfFourAllOfMode';++export type GroupedSoupPageOneOfFourAllOf = {+ mode: GroupedSoupPageOneOfFourAllOfMode;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfFourAllOfMode.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfFourAllOfMode.tsnew file mode 100644index 0000000000..815f65dd92--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupPageOneOfFourAllOfMode.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type GroupedSoupPageOneOfFourAllOfMode =+ (typeof GroupedSoupPageOneOfFourAllOfMode)[keyof typeof GroupedSoupPageOneOfFourAllOfMode];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const GroupedSoupPageOneOfFourAllOfMode = {+ group_page: 'group_page',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupSort.ts b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupSort.tsnew file mode 100644index 0000000000..570dfea019--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/groupedSoupSort.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Sort method for grouped queries (frecency not supported).+ */+export type GroupedSoupSort =+ (typeof GroupedSoupSort)[keyof typeof GroupedSoupSort];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const GroupedSoupSort = {+ viewed_at: 'viewed_at',+ created_at: 'created_at',+ updated_at: 'updated_at',+ viewed_updated: 'viewed_updated',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 9b7e1a2d1a..195dff343f 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -76,6 +76,13 @@ export * from './apiChannelMessagesPagePreviousCursor';export * from './apiChannelParticipant';export * from './apiCountedReaction';export * from './apiEntityFilterAst';+export * from './apiGroupByField';+export * from './apiGroupByFieldOneOf';+export * from './apiGroupByFieldOneOfProperty';+export * from './apiGroupByFieldOneOfPropertyEntityType';+export * from './apiGroupMeta';+export * from './apiGroupMetaDisplayOrder';+export * from './apiGroupMetaNextCursor';export * from './apiMessageAttachment';export * from './apiMessageAttachmentHeight';export * from './apiMessageAttachmentWidth';@@ -84,6 +91,7 @@ export * from './apiMessageSenderAvatarUrl';export * from './apiMessageSenderName';export * from './apiMessageSenderType';export * from './apiParticipantRole';+export * from './apiPropertyEntityType';export * from './apiResolvedChannelMessage';export * from './apiThreadInfo';export * from './apiThreadInfoLatestReplyAt';@@ -568,6 +576,24 @@ export * from './githubPullRequestForeignEntityId';export * from './githubPullRequestName';export * from './githubPullRequestStatus';export * from './githubPullRequestsResponse';+export * from './groupedInitialParams';+export * from './groupedInitialParamsPerGroupLimit';+export * from './groupedInitialParamsSortMethod';+export * from './groupedPageParams';+export * from './groupedPageParamsLimit';+export * from './groupedPageParamsSortMethod';+export * from './groupedSoupGroupPage';+export * from './groupedSoupGroupPageItems';+export * from './groupedSoupInitialPage';+export * from './groupedSoupInitialPageItems';+export * from './groupedSoupPage';+export * from './groupedSoupPageOneOf';+export * from './groupedSoupPageOneOfAllOf';+export * from './groupedSoupPageOneOfAllOfMode';+export * from './groupedSoupPageOneOfFour';+export * from './groupedSoupPageOneOfFourAllOf';+export * from './groupedSoupPageOneOfFourAllOfMode';+export * from './groupedSoupSort';export * from './hashMap';export * from './hashMapOneOf';export * from './hashMapOneOfAllOf';@@ -657,6 +683,16 @@ export * from './pinnedItem';export * from './pinRequest';export * from './postActivityRequest';export * from './postChannelMessagesParams';+export * from './postGroupedSoupAstGroupPageRequest';+export * from './postGroupedSoupAstInitialRequest';+export * from './postGroupedSoupAstRequest';+export * from './postGroupedSoupAstRequestOneOf';+export * from './postGroupedSoupAstRequestOneOfAllOf';+export * from './postGroupedSoupAstRequestOneOfAllOfMode';+export * from './postGroupedSoupAstRequestOneOfFour';+export * from './postGroupedSoupAstRequestOneOfFourAllOf';+export * from './postGroupedSoupAstRequestOneOfFourAllOfMode';+export * from './postItemsSoupAstGroupedParams';export * from './postItemsSoupAstParams';export * from './postItemsSoupParams';export * from './postMessageRequest';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstGroupPageRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstGroupPageRequest.tsnew file mode 100644index 0000000000..b955eb80d7--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstGroupPageRequest.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiEntityFilterAst } from './apiEntityFilterAst';+import type { GroupedPageParams } from './groupedPageParams';++/**+ * Request body for fetching one page within a specific group.+ */+export type PostGroupedSoupAstGroupPageRequest = ApiEntityFilterAst &+ GroupedPageParams;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstInitialRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstInitialRequest.tsnew file mode 100644index 0000000000..801471701b--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstInitialRequest.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiEntityFilterAst } from './apiEntityFilterAst';+import type { GroupedInitialParams } from './groupedInitialParams';++/**+ * Request body for the initial grouped soup query.+ */+export type PostGroupedSoupAstInitialRequest = ApiEntityFilterAst &+ GroupedInitialParams;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequest.tsnew file mode 100644index 0000000000..fb94ec9348--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequest.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { PostGroupedSoupAstRequestOneOf } from './postGroupedSoupAstRequestOneOf';+import type { PostGroupedSoupAstRequestOneOfFour } from './postGroupedSoupAstRequestOneOfFour';++/**+ * Request body for grouped soup queries with AST filters.+ */+export type PostGroupedSoupAstRequest =+ | PostGroupedSoupAstRequestOneOf+ | PostGroupedSoupAstRequestOneOfFour;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOf.tsnew file mode 100644index 0000000000..2283a1ee51--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { PostGroupedSoupAstInitialRequest } from './postGroupedSoupAstInitialRequest';+import type { PostGroupedSoupAstRequestOneOfAllOf } from './postGroupedSoupAstRequestOneOfAllOf';++export type PostGroupedSoupAstRequestOneOf = PostGroupedSoupAstInitialRequest &+ PostGroupedSoupAstRequestOneOfAllOf;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfAllOf.tsnew file mode 100644index 0000000000..c2a9b83f3c--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { PostGroupedSoupAstRequestOneOfAllOfMode } from './postGroupedSoupAstRequestOneOfAllOfMode';++export type PostGroupedSoupAstRequestOneOfAllOf = {+ mode: PostGroupedSoupAstRequestOneOfAllOfMode;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfAllOfMode.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfAllOfMode.tsnew file mode 100644index 0000000000..1718d53503--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfAllOfMode.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type PostGroupedSoupAstRequestOneOfAllOfMode =+ (typeof PostGroupedSoupAstRequestOneOfAllOfMode)[keyof typeof PostGroupedSoupAstRequestOneOfAllOfMode];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const PostGroupedSoupAstRequestOneOfAllOfMode = {+ initial: 'initial',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfFour.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfFour.tsnew file mode 100644index 0000000000..a5bbbee1a6--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfFour.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { PostGroupedSoupAstGroupPageRequest } from './postGroupedSoupAstGroupPageRequest';+import type { PostGroupedSoupAstRequestOneOfFourAllOf } from './postGroupedSoupAstRequestOneOfFourAllOf';++export type PostGroupedSoupAstRequestOneOfFour =+ PostGroupedSoupAstGroupPageRequest & PostGroupedSoupAstRequestOneOfFourAllOf;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfFourAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfFourAllOf.tsnew file mode 100644index 0000000000..7517df104f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfFourAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { PostGroupedSoupAstRequestOneOfFourAllOfMode } from './postGroupedSoupAstRequestOneOfFourAllOfMode';++export type PostGroupedSoupAstRequestOneOfFourAllOf = {+ mode: PostGroupedSoupAstRequestOneOfFourAllOfMode;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfFourAllOfMode.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfFourAllOfMode.tsnew file mode 100644index 0000000000..a764fdb07f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postGroupedSoupAstRequestOneOfFourAllOfMode.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type PostGroupedSoupAstRequestOneOfFourAllOfMode =+ (typeof PostGroupedSoupAstRequestOneOfFourAllOfMode)[keyof typeof PostGroupedSoupAstRequestOneOfFourAllOfMode];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const PostGroupedSoupAstRequestOneOfFourAllOfMode = {+ group_page: 'group_page',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postItemsSoupAstGroupedParams.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postItemsSoupAstGroupedParams.tsnew file mode 100644index 0000000000..8c4ccfbeaf--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postItemsSoupAstGroupedParams.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type PostItemsSoupAstGroupedParams = {+ /**+ * Base64 encoded cursor value.+ */+ cursor?: string;+};diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex b4268d14f3..cbc02a813d 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -10754,6 +10754,3220 @@ export const postItemsSoupAstResponse = zod.object({next_cursor: zod.string().nullish(),});+/**+ * @summary Gets the items grouped by the specified field using AST filters.+ */+export const postItemsSoupAstGroupedQueryParams = zod.object({+ cursor: zod.string().optional().describe('Base64 encoded cursor value.'),+});++export const postItemsSoupAstGroupedBodyPerGroupLimitMin = 0;++export const postItemsSoupAstGroupedBodyLimitMin = 0;++export const postItemsSoupAstGroupedBody = zod+ .union([+ zod+ .object({+ callf: zod+ .unknown()+ .optional()+ .describe('the filters that should be applied to the call entity'),+ ccf: zod+ .unknown()+ .optional()+ .describe(+ "Filters applied to the crm_company entity (wire key `ccf`).\nEmpty\/omitted = team's full visible list."+ ),+ cf: zod+ .unknown()+ .optional()+ .describe('the filters that should be applied to the chat entity'),+ chanf: zod+ .unknown()+ .optional()+ .describe('the filters that should be applied to the channel entity'),+ df: zod+ .unknown()+ .optional()+ .describe(+ 'the filters that should be applied to the document entity'+ ),+ eca: zod+ .array(zod.string())+ .optional()+ .describe(+ 'CRM-scoped address filter (wire key: `eca`). Symmetric counterpart\nto `ecd` for fully-qualified email addresses.'+ ),+ ecd: zod+ .array(zod.string())+ .optional()+ .describe(+ 'CRM-scoped domain filter (wire key: `ecd`). Parallel to the\nfreeform `ef` AST. Expanded by the router into an any-direction\nOR sub-tree AND-merged into `ef`, plus a `CrmScope` tag stamped\non the resulting [`item_filters::ast::EmailFilterAst::crm_scope`].\nDrives the per-team CRM authorization pre-check and candidate-set\nwidening downstream. Mutually exclusive with `eca`.'+ ),+ ef: zod+ .unknown()+ .optional()+ .describe(+ 'the filters that should be applied to the email entity (raw AST\ntree only; CRM scope is carried by the `ecd` \/ `eca` sibling\nfields). On this endpoint the email filter stays a bare tree,\nunlike the materialized [`EntityFilterAst`] used for cursors.'+ ),+ fef: zod+ .unknown()+ .optional()+ .describe(+ 'the filters that should be applied to foreign entity records'+ ),+ pf: zod+ .unknown()+ .optional()+ .describe('the filters that should be applied to the project entity'),+ propf: zod+ .unknown()+ .optional()+ .describe(+ 'the filters that should be applied based on entity properties'+ ),+ })+ .and(+ zod+ .object({+ group_by: zod+ .union([+ zod+ .enum(['date'])+ .describe(+ 'Smart date buckets: Today, Yesterday, This Week, Last Week, This Month, Last Month, Older'+ ),+ zod+ .enum(['entity_type'])+ .describe(+ 'Group by entity type (document, email, channel, etc.)'+ ),+ zod.enum(['project']).describe('Group by project'),+ zod+ .object({+ property: zod+ .object({+ entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Entity type for property lookups (API representation).'+ ),+ ])+ .optional(),+ property_definition_id: zod+ .uuid()+ .describe('The property definition UUID to group by'),+ })+ .describe(+ 'Group by a property value (e.g., status, priority, or custom properties)'+ ),+ })+ .describe(+ 'Group by a property value (e.g., status, priority, or custom properties)'+ ),+ ])+ .describe('API representation of group-by field.'),+ per_group_limit: zod+ .number()+ .min(postItemsSoupAstGroupedBodyPerGroupLimitMin)+ .nullish()+ .describe(+ 'Limit the number of items returned per group. Defaults to 20. Max 500.'+ ),+ sort_method: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'viewed_at',+ 'created_at',+ 'updated_at',+ 'viewed_updated',+ ])+ .describe(+ 'Sort method for grouped queries (frecency not supported).'+ ),+ ])+ .optional(),+ })+ .describe('Parameters for the initial grouped soup query.')+ )+ .describe('Request body for the initial grouped soup query.')+ .and(+ zod.object({+ mode: zod.enum(['initial']),+ })+ ),+ zod+ .object({+ callf: zod+ .unknown()+ .optional()+ .describe('the filters that should be applied to the call entity'),+ ccf: zod+ .unknown()+ .optional()+ .describe(+ "Filters applied to the crm_company entity (wire key `ccf`).\nEmpty\/omitted = team's full visible list."+ ),+ cf: zod+ .unknown()+ .optional()+ .describe('the filters that should be applied to the chat entity'),+ chanf: zod+ .unknown()+ .optional()+ .describe('the filters that should be applied to the channel entity'),+ df: zod+ .unknown()+ .optional()+ .describe(+ 'the filters that should be applied to the document entity'+ ),+ eca: zod+ .array(zod.string())+ .optional()+ .describe(+ 'CRM-scoped address filter (wire key: `eca`). Symmetric counterpart\nto `ecd` for fully-qualified email addresses.'+ ),+ ecd: zod+ .array(zod.string())+ .optional()+ .describe(+ 'CRM-scoped domain filter (wire key: `ecd`). Parallel to the\nfreeform `ef` AST. Expanded by the router into an any-direction\nOR sub-tree AND-merged into `ef`, plus a `CrmScope` tag stamped\non the resulting [`item_filters::ast::EmailFilterAst::crm_scope`].\nDrives the per-team CRM authorization pre-check and candidate-set\nwidening downstream. Mutually exclusive with `eca`.'+ ),+ ef: zod+ .unknown()+ .optional()+ .describe(+ 'the filters that should be applied to the email entity (raw AST\ntree only; CRM scope is carried by the `ecd` \/ `eca` sibling\nfields). On this endpoint the email filter stays a bare tree,\nunlike the materialized [`EntityFilterAst`] used for cursors.'+ ),+ fef: zod+ .unknown()+ .optional()+ .describe(+ 'the filters that should be applied to foreign entity records'+ ),+ pf: zod+ .unknown()+ .optional()+ .describe('the filters that should be applied to the project entity'),+ propf: zod+ .unknown()+ .optional()+ .describe(+ 'the filters that should be applied based on entity properties'+ ),+ })+ .and(+ zod+ .object({+ group_by: zod+ .union([+ zod+ .enum(['date'])+ .describe(+ 'Smart date buckets: Today, Yesterday, This Week, Last Week, This Month, Last Month, Older'+ ),+ zod+ .enum(['entity_type'])+ .describe(+ 'Group by entity type (document, email, channel, etc.)'+ ),+ zod.enum(['project']).describe('Group by project'),+ zod+ .object({+ property: zod+ .object({+ entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Entity type for property lookups (API representation).'+ ),+ ])+ .optional(),+ property_definition_id: zod+ .uuid()+ .describe('The property definition UUID to group by'),+ })+ .describe(+ 'Group by a property value (e.g., status, priority, or custom properties)'+ ),+ })+ .describe(+ 'Group by a property value (e.g., status, priority, or custom properties)'+ ),+ ])+ .describe('API representation of group-by field.'),+ group_key: zod.string().describe('Group key to fetch.'),+ limit: zod+ .number()+ .min(postItemsSoupAstGroupedBodyLimitMin)+ .nullish()+ .describe(+ 'Limit the number of items returned. Defaults to 20. Max 500.'+ ),+ sort_method: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'viewed_at',+ 'created_at',+ 'updated_at',+ 'viewed_updated',+ ])+ .describe(+ 'Sort method for grouped queries (frecency not supported).'+ ),+ ])+ .optional(),+ })+ .describe('Parameters for fetching one page within a specific group.')+ )+ .describe('Request body for fetching one page within a specific group.')+ .and(+ zod.object({+ mode: zod.enum(['group_page']),+ })+ ),+ ])+ .describe('Request body for grouped soup queries with AST filters.');++export const postItemsSoupAstGroupedResponseGroupsItemTotalCountMin = 0;++export const postItemsSoupAstGroupedResponseItemsDataChannelOrgIdMin = 0;++export const postItemsSoupAstGroupedResponseGroupTotalCountMin = 0;++export const postItemsSoupAstGroupedResponseItemsDataChannelOrgIdMinOne = 0;++export const postItemsSoupAstGroupedResponse = zod+ .union([+ zod+ .object({+ groups: zod+ .array(+ zod+ .object({+ display_order: zod+ .number()+ .nullish()+ .describe('Display order for sorting groups (lower = first)'),+ item_ids: zod+ .array(zod.uuid())+ .describe(+ 'Ordered ids of items in this group for the current page.\nEach id keys into `GroupedSoupPage.items`.'+ ),+ key: zod+ .string()+ .describe('Group key - format depends on group_by field'),+ label: zod+ .string()+ .describe('Human-readable label for the group'),+ next_cursor: zod+ .string()+ .nullish()+ .describe(+ 'Cursor to load more items specifically from this group'+ ),+ total_count: zod+ .number()+ .min(postItemsSoupAstGroupedResponseGroupsItemTotalCountMin)+ .describe(+ 'Total count of items in this group across all pages'+ ),+ })+ .describe(+ 'API representation of group metadata.\n\nItems belonging to this group are referenced by `item_ids`, each of which\nlooks up an entry in `GroupedSoupPage.items` (a normalized pool).'+ )+ )+ .describe('Ordered group metadata for this grouped response.'),+ items: zod+ .record(+ zod.string(),+ zod+ .union([+ zod.object({+ data: zod.object({+ branchedFromId: zod+ .uuid()+ .nullish()+ .describe(+ 'The id of the document this document branched from'+ ),+ branchedFromVersionId: zod+ .number()+ .nullish()+ .describe(+ 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on the file type'+ ),+ createdAt: zod.iso+ .datetime({})+ .describe('The time the document was created'),+ deletedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the document was deleted'),+ documentFamilyId: zod+ .number()+ .nullish()+ .describe(+ 'The id of the document family this document belongs to'+ ),+ documentVersionId: zod+ .number()+ .describe(+ 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on the file type'+ ),+ fileType: zod+ .string()+ .nullish()+ .describe(+ 'The file type of the document (e.g. pdf, docx)'+ ),+ id: zod.uuid().describe('The document id'),+ name: zod.string().describe('The name of the document'),+ ownerId: zod.string().describe('The owner of the document'),+ projectId: zod+ .uuid()+ .nullish()+ .describe(+ 'The id of the project that this document belongs to'+ ),+ properties: zod+ .array(+ zod+ .object({+ definition: zod+ .object({+ created_at: zod.iso.datetime({}),+ data_type: zod+ .enum([+ 'BOOLEAN',+ 'DATE',+ 'NUMBER',+ 'STRING',+ 'SELECT_NUMBER',+ 'SELECT_STRING',+ 'ENTITY',+ 'LINK',+ ])+ .describe(+ 'Data type for property values, determining storage and validation.'+ ),+ display_name: zod.string(),+ id: zod.uuid(),+ is_metadata: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'+ ),+ is_multi_select: zod.boolean(),+ is_system: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system property (stored in DB).'+ ),+ owner: zod+ .union([+ zod+ .object({+ scope: zod.enum(['user']),+ user_id: zod.string(),+ })+ .describe('User-scoped property only'),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum(['organization']),+ })+ .describe(+ 'Organization-scoped property only'+ ),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum([+ 'user_and_organization',+ ]),+ user_id: zod.string(),+ })+ .describe(+ 'Both user and organization-scoped'+ ),+ zod+ .object({+ scope: zod.enum(['system']),+ })+ .describe(+ 'System-owned property (no user or org owner)'+ ),+ ])+ .describe(+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'+ ),+ specific_entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}),+ })+ .describe(+ 'Property definition model (service representation).'+ ),+ value: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['Boolean']),+ value: zod+ .boolean()+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ })+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ zod+ .object({+ type: zod.enum(['Number']),+ value: zod+ .number()+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ })+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ zod+ .object({+ type: zod.enum(['String']),+ value: zod+ .string()+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ })+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ zod+ .object({+ type: zod.enum(['Date']),+ value: zod.iso+ .datetime({})+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ })+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ zod+ .object({+ type: zod.enum(['SelectOption']),+ value: zod+ .array(zod.uuid())+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ })+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['EntityReference']),+ value: zod+ .array(+ zod+ .object({+ entity_id: zod.string(),+ entity_type: zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ specific_message_id: zod+ .uuid()+ .nullish()+ .describe(+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'+ ),+ })+ .describe(+ 'Entity reference for entity-type property values.'+ )+ )+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ })+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['Link']),+ value: zod+ .array(zod.string())+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ })+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ ])+ .describe(+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'+ ),+ ])+ .optional(),+ })+ .describe(+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'+ )+ )+ .describe('Properties'),+ sha: zod+ .string()+ .nullish()+ .describe(+ 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'+ ),+ subType: zod+ .union([+ zod.null(),+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ })+ .describe(+ 'A task document with its associated properties'+ )+ .describe(+ 'Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'+ ),+ ])+ .optional(),+ updatedAt: zod.iso+ .datetime({})+ .describe(+ 'The time the document instance \/ document BOM was updated'+ ),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the document was last viewed'),+ }),+ tag: zod.enum(['document']),+ }),+ zod.object({+ data: zod.object({+ createdAt: zod.iso+ .datetime({})+ .describe('The time the chat was created'),+ deletedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the chat was deleted'),+ id: zod.uuid().describe('The chat uuid'),+ isPersistent: zod+ .boolean()+ .describe('Whether the chat is persistent or not'),+ name: zod.string().describe('The name of the chat'),+ ownerId: zod.string().describe('Who the chat belongs to'),+ projectId: zod+ .uuid()+ .nullish()+ .describe('The project id of the chat'),+ properties: zod+ .array(+ zod+ .object({+ definition: zod+ .object({+ created_at: zod.iso.datetime({}),+ data_type: zod+ .enum([+ 'BOOLEAN',+ 'DATE',+ 'NUMBER',+ 'STRING',+ 'SELECT_NUMBER',+ 'SELECT_STRING',+ 'ENTITY',+ 'LINK',+ ])+ .describe(+ 'Data type for property values, determining storage and validation.'+ ),+ display_name: zod.string(),+ id: zod.uuid(),+ is_metadata: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'+ ),+ is_multi_select: zod.boolean(),+ is_system: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system property (stored in DB).'+ ),+ owner: zod+ .union([+ zod+ .object({+ scope: zod.enum(['user']),+ user_id: zod.string(),+ })+ .describe('User-scoped property only'),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum(['organization']),+ })+ .describe(+ 'Organization-scoped property only'+ ),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum([+ 'user_and_organization',+ ]),+ user_id: zod.string(),+ })+ .describe(+ 'Both user and organization-scoped'+ ),+ zod+ .object({+ scope: zod.enum(['system']),+ })+ .describe(+ 'System-owned property (no user or org owner)'+ ),+ ])+ .describe(+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'+ ),+ specific_entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}),+ })+ .describe(+ 'Property definition model (service representation).'+ ),+ value: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['Boolean']),+ value: zod+ .boolean()+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ })+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ zod+ .object({+ type: zod.enum(['Number']),+ value: zod+ .number()+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ })+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ zod+ .object({+ type: zod.enum(['String']),+ value: zod+ .string()+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ })+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ zod+ .object({+ type: zod.enum(['Date']),+ value: zod.iso+ .datetime({})+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ })+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ zod+ .object({+ type: zod.enum(['SelectOption']),+ value: zod+ .array(zod.uuid())+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ })+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['EntityReference']),+ value: zod+ .array(+ zod+ .object({+ entity_id: zod.string(),+ entity_type: zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ specific_message_id: zod+ .uuid()+ .nullish()+ .describe(+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'+ ),+ })+ .describe(+ 'Entity reference for entity-type property values.'+ )+ )+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ })+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['Link']),+ value: zod+ .array(zod.string())+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ })+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ ])+ .describe(+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'+ ),+ ])+ .optional(),+ })+ .describe(+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'+ )+ )+ .describe('Properties'),+ updatedAt: zod.iso+ .datetime({})+ .describe('The time the chat was last updated'),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the chat was last viewed'),+ }),+ tag: zod.enum(['chat']),+ }),+ zod.object({+ data: zod.object({+ createdAt: zod.iso+ .datetime({})+ .describe('The time the project was created'),+ deletedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the project was deleted'),+ id: zod.uuid().describe('The id of the project'),+ name: zod.string().describe('The name of the project'),+ ownerId: zod+ .string()+ .describe('The user id of who created the project'),+ parentId: zod+ .uuid()+ .nullish()+ .describe('The parent project id'),+ properties: zod+ .array(+ zod+ .object({+ definition: zod+ .object({+ created_at: zod.iso.datetime({}),+ data_type: zod+ .enum([+ 'BOOLEAN',+ 'DATE',+ 'NUMBER',+ 'STRING',+ 'SELECT_NUMBER',+ 'SELECT_STRING',+ 'ENTITY',+ 'LINK',+ ])+ .describe(+ 'Data type for property values, determining storage and validation.'+ ),+ display_name: zod.string(),+ id: zod.uuid(),+ is_metadata: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'+ ),+ is_multi_select: zod.boolean(),+ is_system: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system property (stored in DB).'+ ),+ owner: zod+ .union([+ zod+ .object({+ scope: zod.enum(['user']),+ user_id: zod.string(),+ })+ .describe('User-scoped property only'),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum(['organization']),+ })+ .describe(+ 'Organization-scoped property only'+ ),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum([+ 'user_and_organization',+ ]),+ user_id: zod.string(),+ })+ .describe(+ 'Both user and organization-scoped'+ ),+ zod+ .object({+ scope: zod.enum(['system']),+ })+ .describe(+ 'System-owned property (no user or org owner)'+ ),+ ])+ .describe(+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'+ ),+ specific_entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}),+ })+ .describe(+ 'Property definition model (service representation).'+ ),+ value: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['Boolean']),+ value: zod+ .boolean()+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ })+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ zod+ .object({+ type: zod.enum(['Number']),+ value: zod+ .number()+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ })+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ zod+ .object({+ type: zod.enum(['String']),+ value: zod+ .string()+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ })+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ zod+ .object({+ type: zod.enum(['Date']),+ value: zod.iso+ .datetime({})+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ })+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ zod+ .object({+ type: zod.enum(['SelectOption']),+ value: zod+ .array(zod.uuid())+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ })+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['EntityReference']),+ value: zod+ .array(+ zod+ .object({+ entity_id: zod.string(),+ entity_type: zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ specific_message_id: zod+ .uuid()+ .nullish()+ .describe(+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'+ ),+ })+ .describe(+ 'Entity reference for entity-type property values.'+ )+ )+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ })+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['Link']),+ value: zod+ .array(zod.string())+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ })+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ ])+ .describe(+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'+ ),+ ])+ .optional(),+ })+ .describe(+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'+ )+ )+ .describe('Properties'),+ updatedAt: zod.iso+ .datetime({})+ .describe('The time the project was updated'),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the document was last viewed'),+ }),+ tag: zod.enum(['project']),+ }),+ zod.object({+ data: zod+ .object({+ createdAt: zod.iso.datetime({}),+ id: zod.uuid(),+ inboxVisible: zod.boolean(),+ isDraft: zod.boolean(),+ isImportant: zod.boolean(),+ isRead: zod.boolean(),+ name: zod.string().nullish(),+ ownerId: zod.string(),+ projectId: zod.string().nullish(),+ providerId: zod.string().nullish(),+ senderEmail: zod.string().nullish(),+ senderName: zod.string().nullish(),+ senderPhotoUrl: zod.string().nullish(),+ snippet: zod.string().nullish(),+ sortTs: zod.iso.datetime({}),+ updatedAt: zod.iso.datetime({}),+ viewedAt: zod.iso.datetime({}).nullish(),+ })+ .and(+ zod.object({+ attachments: zod.array(+ zod.object({+ contentId: zod.string().nullish(),+ createdAt: zod.iso.datetime({}),+ filename: zod.string().nullish(),+ id: zod.uuid(),+ messageId: zod.uuid(),+ mimeType: zod.string().nullish(),+ providerAttachmentId: zod.string().nullish(),+ sizeBytes: zod.number().nullish(),+ })+ ),+ labels: zod.array(+ zod.object({+ createdAt: zod.iso.datetime({}),+ id: zod.uuid(),+ labelListVisibility: zod.enum([+ 'labelShow',+ 'labelShowIfUnread',+ 'labelHide',+ ]),+ linkId: zod.uuid(),+ messageListVisibility: zod.enum(['show', 'hide']),+ name: zod.string(),+ providerLabelId: zod.string(),+ type: zod.enum(['system', 'user']),+ })+ ),+ participants: zod.array(+ zod.object({+ emailAddress: zod.string().nullish(),+ id: zod.uuid(),+ linkId: zod.uuid(),+ name: zod.string().nullish(),+ sfsPhotoUrl: zod.string().nullish(),+ })+ ),+ properties: zod.array(+ zod+ .object({+ definition: zod+ .object({+ created_at: zod.iso.datetime({}),+ data_type: zod+ .enum([+ 'BOOLEAN',+ 'DATE',+ 'NUMBER',+ 'STRING',+ 'SELECT_NUMBER',+ 'SELECT_STRING',+ 'ENTITY',+ 'LINK',+ ])+ .describe(+ 'Data type for property values, determining storage and validation.'+ ),+ display_name: zod.string(),+ id: zod.uuid(),+ is_metadata: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'+ ),+ is_multi_select: zod.boolean(),+ is_system: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system property (stored in DB).'+ ),+ owner: zod+ .union([+ zod+ .object({+ scope: zod.enum(['user']),+ user_id: zod.string(),+ })+ .describe('User-scoped property only'),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum(['organization']),+ })+ .describe(+ 'Organization-scoped property only'+ ),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum([+ 'user_and_organization',+ ]),+ user_id: zod.string(),+ })+ .describe(+ 'Both user and organization-scoped'+ ),+ zod+ .object({+ scope: zod.enum(['system']),+ })+ .describe(+ 'System-owned property (no user or org owner)'+ ),+ ])+ .describe(+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'+ ),+ specific_entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}),+ })+ .describe(+ 'Property definition model (service representation).'+ ),+ value: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['Boolean']),+ value: zod+ .boolean()+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ })+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ zod+ .object({+ type: zod.enum(['Number']),+ value: zod+ .number()+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ })+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ zod+ .object({+ type: zod.enum(['String']),+ value: zod+ .string()+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ })+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ zod+ .object({+ type: zod.enum(['Date']),+ value: zod.iso+ .datetime({})+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ })+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ zod+ .object({+ type: zod.enum(['SelectOption']),+ value: zod+ .array(zod.uuid())+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ })+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['EntityReference']),+ value: zod+ .array(+ zod+ .object({+ entity_id: zod.string(),+ entity_type: zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ specific_message_id: zod+ .uuid()+ .nullish()+ .describe(+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'+ ),+ })+ .describe(+ 'Entity reference for entity-type property values.'+ )+ )+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ })+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['Link']),+ value: zod+ .array(zod.string())+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ })+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ ])+ .describe(+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'+ ),+ ])+ .optional(),+ })+ .describe(+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'+ )+ ),+ })+ ),+ tag: zod.enum(['emailThread']),+ }),+ zod.object({+ data: zod+ .object({+ channel: zod.object({+ channel_type: zod+ .enum(['public', 'private', 'direct_message', 'team'])+ .describe('Type of channel.'),+ created_at: zod.iso.datetime({}),+ id: zod.uuid(),+ name: zod.string().nullish(),+ org_id: zod+ .number()+ .min(+ postItemsSoupAstGroupedResponseItemsDataChannelOrgIdMin+ )+ .nullish(),+ owner_id: zod.string(),+ team_id: zod.uuid().nullish(),+ updated_at: zod.iso.datetime({}),+ }),+ participants: zod.array(+ zod.object({+ channel_id: zod.uuid(),+ joined_at: zod.iso.datetime({}),+ left_at: zod.iso.datetime({}).nullish(),+ role: zod+ .enum(['owner', 'admin', 'member'])+ .describe('The role a user has within a channel.'),+ user_id: zod.string(),+ })+ ),+ })+ .and(+ zod.object({+ latest_message: zod+ .union([+ zod.null(),+ zod.object({+ content: zod.string(),+ created_at: zod.iso.datetime({}),+ deleted_at: zod.iso.datetime({}).nullish(),+ mentions: zod+ .array(zod.string())+ .describe(+ 'message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'+ ),+ message_id: zod.uuid(),+ sender_id: zod.string(),+ thread_id: zod.uuid().nullish(),+ updated_at: zod.iso.datetime({}),+ }),+ ])+ .optional(),+ latest_non_thread_message: zod+ .union([+ zod.null(),+ zod.object({+ content: zod.string(),+ created_at: zod.iso.datetime({}),+ deleted_at: zod.iso.datetime({}).nullish(),+ mentions: zod+ .array(zod.string())+ .describe(+ 'message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'+ ),+ message_id: zod.uuid(),+ sender_id: zod.string(),+ thread_id: zod.uuid().nullish(),+ updated_at: zod.iso.datetime({}),+ }),+ ])+ .optional(),+ })+ )+ .and(+ zod.object({+ interacted_at: zod.iso.datetime({}).nullish(),+ viewed_at: zod.iso.datetime({}).nullish(),+ })+ ),+ tag: zod.enum(['channel']),+ }),+ zod.object({+ data: zod+ .object({+ attended: zod+ .boolean()+ .describe(+ 'Whether the requesting user attended this call. Kept for compatibility\nand derived from `status == ATTENDED`.'+ ),+ callId: zod.uuid().describe('The call identifier.'),+ channelId: zod+ .uuid()+ .describe('The channel this call belongs to.'),+ channelName: zod+ .string()+ .nullish()+ .describe('Resolved display name for the channel.'),+ createdBy: zod+ .string()+ .describe('User who created the call.'),+ customName: zod+ .string()+ .nullish()+ .describe(+ 'User-supplied or AI-generated display name for the call.'+ ),+ durationMs: zod+ .number()+ .nullish()+ .describe(+ 'Call duration in milliseconds (None if still active).'+ ),+ endedAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ 'When the call ended (None if still active).'+ ),+ isActive: zod+ .boolean()+ .describe('Whether the call is currently active.'),+ participants: zod+ .array(+ zod+ .object({+ joinedAt: zod.iso+ .datetime({})+ .describe('When the user joined the call.'),+ leftAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ 'When the user left (None if still in an active call).'+ ),+ userId: zod.string().describe('The user id.'),+ })+ .describe(+ 'A participant in a call record, as displayed in Soup.'+ )+ )+ .describe('Participants in the call.'),+ startedAt: zod.iso+ .datetime({})+ .describe('When the call started.'),+ status: zod+ .enum(['ATTENDED', 'MISSED', 'UNATTENDED'])+ .describe(+ 'Viewer-relative attendance status for a call record.\nSerializes as `ATTENDED`, `MISSED`, or `UNATTENDED`.'+ ),+ summary: zod+ .string()+ .nullish()+ .describe(+ 'AI-generated summary of the call. Only set on archived\n`call_records` once summarization has run; active calls always\nreturn `None`.'+ ),+ })+ .describe(+ 'A call record as displayed in Soup. Excludes room_name, egress_id,\nand transcript — fields that are irrelevant for the soup feed.'+ ),+ tag: zod.enum(['call']),+ }),+ zod.object({+ data: zod+ .object({+ createdAt: zod.iso+ .datetime({})+ .describe('When the company was created.'),+ description: zod+ .string()+ .nullish()+ .describe(+ "Display description from the primary domain's directory entry."+ ),+ domains: zod+ .array(+ zod+ .object({+ companyId: zod+ .uuid()+ .describe(+ 'The id of the company the domain belongs to.'+ ),+ createdAt: zod.iso+ .datetime({})+ .describe(+ 'When the domain record was created.'+ ),+ domain: zod+ .string()+ .describe(+ 'The domain (lowercased, e.g. \"acme.com\").'+ ),+ id: zod+ .uuid()+ .describe('The id of the domain record.'),+ })+ .describe(+ "A CRM domain as displayed in Soup. Mirrors the crm crate's\n[`CrmDomain`] with a stable wire shape that the FE can rely on."+ )+ )+ .describe(+ 'Domains associated with this company, ordered by creation time\nascending (primary first).'+ ),+ emailSync: zod+ .boolean()+ .describe(+ 'Whether email sync is enabled for this company.'+ ),+ hidden: zod+ .boolean()+ .describe(+ 'Whether the company is hidden from CRM listings. Soup filters\nthese out by default.'+ ),+ id: zod.uuid().describe('The id of the company.'),+ name: zod+ .string()+ .nullish()+ .describe(+ "Display name from the primary domain's directory entry, or\n`None` when unresolved."+ ),+ teamId: zod+ .uuid()+ .describe(+ 'The id of the team that owns this company record.'+ ),+ updatedAt: zod.iso+ .datetime({})+ .describe('When the company was last updated.'),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ 'When the requesting user last viewed this company, or `None` if\nnever viewed. Mirrors the `viewed_at` other soup entities carry.'+ ),+ })+ .describe(+ 'A CRM company as displayed in Soup. Carries the core company\nfields plus display metadata resolved from `crm_domain_directory`\nagainst the primary (earliest-created) domain.'+ ),+ tag: zod.enum(['crmCompany']),+ }),+ zod.object({+ data: zod+ .object({+ createdAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was created.'),+ foreignEntityId: zod+ .string()+ .describe(+ 'Identifier assigned by the external system.'+ ),+ foreignEntitySource: zod+ .string()+ .describe(+ 'Source system that owns the external identifier.'+ ),+ id: zod+ .uuid()+ .describe(+ 'Internal primary key for this foreign entity record.'+ ),+ metadata: zod+ .object({})+ .describe(+ 'Arbitrary metadata stored with the mapping.'+ ),+ storedForAuthEntity: zod+ .string()+ .describe(+ 'Internal auth entity namespace this foreign entity is stored for.'+ ),+ storedForId: zod+ .string()+ .describe(+ 'Internal entity identifier this foreign entity is stored for.'+ ),+ updatedAt: zod.iso+ .datetime({})+ .describe(+ 'Timestamp when the record was last updated.'+ ),+ })+ .describe('A foreign entity record as displayed in Soup.'),+ tag: zod.enum(['foreignEntity']),+ }),+ ])+ .and(+ zod.object({+ frecency_score: zod.number(),+ })+ )+ )+ .describe(+ 'Items in this page, keyed by id. Ordering lives in `groups[].item_ids`.'+ ),+ })+ .describe(+ 'Response for the initial grouped soup query.\n\nItems are returned as a pool keyed by id; each `ApiGroupMeta.item_ids`\ndescribes the ordered membership of one group.'+ )+ .and(+ zod.object({+ mode: zod.enum(['initial']),+ })+ ),+ zod+ .object({+ group: zod+ .object({+ display_order: zod+ .number()+ .nullish()+ .describe('Display order for sorting groups (lower = first)'),+ item_ids: zod+ .array(zod.uuid())+ .describe(+ 'Ordered ids of items in this group for the current page.\nEach id keys into `GroupedSoupPage.items`.'+ ),+ key: zod+ .string()+ .describe('Group key - format depends on group_by field'),+ label: zod.string().describe('Human-readable label for the group'),+ next_cursor: zod+ .string()+ .nullish()+ .describe(+ 'Cursor to load more items specifically from this group'+ ),+ total_count: zod+ .number()+ .min(postItemsSoupAstGroupedResponseGroupTotalCountMin)+ .describe('Total count of items in this group across all pages'),+ })+ .describe(+ 'API representation of group metadata.\n\nItems belonging to this group are referenced by `item_ids`, each of which\nlooks up an entry in `GroupedSoupPage.items` (a normalized pool).'+ ),+ items: zod+ .record(+ zod.string(),+ zod+ .union([+ zod.object({+ data: zod.object({+ branchedFromId: zod+ .uuid()+ .nullish()+ .describe(+ 'The id of the document this document branched from'+ ),+ branchedFromVersionId: zod+ .number()+ .nullish()+ .describe(+ 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on the file type'+ ),+ createdAt: zod.iso+ .datetime({})+ .describe('The time the document was created'),+ deletedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the document was deleted'),+ documentFamilyId: zod+ .number()+ .nullish()+ .describe(+ 'The id of the document family this document belongs to'+ ),+ documentVersionId: zod+ .number()+ .describe(+ 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on the file type'+ ),+ fileType: zod+ .string()+ .nullish()+ .describe(+ 'The file type of the document (e.g. pdf, docx)'+ ),+ id: zod.uuid().describe('The document id'),+ name: zod.string().describe('The name of the document'),+ ownerId: zod.string().describe('The owner of the document'),+ projectId: zod+ .uuid()+ .nullish()+ .describe(+ 'The id of the project that this document belongs to'+ ),+ properties: zod+ .array(+ zod+ .object({+ definition: zod+ .object({+ created_at: zod.iso.datetime({}),+ data_type: zod+ .enum([+ 'BOOLEAN',+ 'DATE',+ 'NUMBER',+ 'STRING',+ 'SELECT_NUMBER',+ 'SELECT_STRING',+ 'ENTITY',+ 'LINK',+ ])+ .describe(+ 'Data type for property values, determining storage and validation.'+ ),+ display_name: zod.string(),+ id: zod.uuid(),+ is_metadata: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'+ ),+ is_multi_select: zod.boolean(),+ is_system: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system property (stored in DB).'+ ),+ owner: zod+ .union([+ zod+ .object({+ scope: zod.enum(['user']),+ user_id: zod.string(),+ })+ .describe('User-scoped property only'),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum(['organization']),+ })+ .describe(+ 'Organization-scoped property only'+ ),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum([+ 'user_and_organization',+ ]),+ user_id: zod.string(),+ })+ .describe(+ 'Both user and organization-scoped'+ ),+ zod+ .object({+ scope: zod.enum(['system']),+ })+ .describe(+ 'System-owned property (no user or org owner)'+ ),+ ])+ .describe(+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'+ ),+ specific_entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}),+ })+ .describe(+ 'Property definition model (service representation).'+ ),+ value: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['Boolean']),+ value: zod+ .boolean()+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ })+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ zod+ .object({+ type: zod.enum(['Number']),+ value: zod+ .number()+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ })+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ zod+ .object({+ type: zod.enum(['String']),+ value: zod+ .string()+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ })+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ zod+ .object({+ type: zod.enum(['Date']),+ value: zod.iso+ .datetime({})+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ })+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ zod+ .object({+ type: zod.enum(['SelectOption']),+ value: zod+ .array(zod.uuid())+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ })+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['EntityReference']),+ value: zod+ .array(+ zod+ .object({+ entity_id: zod.string(),+ entity_type: zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ specific_message_id: zod+ .uuid()+ .nullish()+ .describe(+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'+ ),+ })+ .describe(+ 'Entity reference for entity-type property values.'+ )+ )+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ })+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['Link']),+ value: zod+ .array(zod.string())+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ })+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ ])+ .describe(+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'+ ),+ ])+ .optional(),+ })+ .describe(+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'+ )+ )+ .describe('Properties'),+ sha: zod+ .string()+ .nullish()+ .describe(+ 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'+ ),+ subType: zod+ .union([+ zod.null(),+ zod+ .object({+ is_completed: zod+ .boolean()+ .describe(+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'+ ),+ type: zod.enum(['task']),+ })+ .describe(+ 'A task document with its associated properties'+ )+ .describe(+ 'Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'+ ),+ ])+ .optional(),+ updatedAt: zod.iso+ .datetime({})+ .describe(+ 'The time the document instance \/ document BOM was updated'+ ),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the document was last viewed'),+ }),+ tag: zod.enum(['document']),+ }),+ zod.object({+ data: zod.object({+ createdAt: zod.iso+ .datetime({})+ .describe('The time the chat was created'),+ deletedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the chat was deleted'),+ id: zod.uuid().describe('The chat uuid'),+ isPersistent: zod+ .boolean()+ .describe('Whether the chat is persistent or not'),+ name: zod.string().describe('The name of the chat'),+ ownerId: zod.string().describe('Who the chat belongs to'),+ projectId: zod+ .uuid()+ .nullish()+ .describe('The project id of the chat'),+ properties: zod+ .array(+ zod+ .object({+ definition: zod+ .object({+ created_at: zod.iso.datetime({}),+ data_type: zod+ .enum([+ 'BOOLEAN',+ 'DATE',+ 'NUMBER',+ 'STRING',+ 'SELECT_NUMBER',+ 'SELECT_STRING',+ 'ENTITY',+ 'LINK',+ ])+ .describe(+ 'Data type for property values, determining storage and validation.'+ ),+ display_name: zod.string(),+ id: zod.uuid(),+ is_metadata: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'+ ),+ is_multi_select: zod.boolean(),+ is_system: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system property (stored in DB).'+ ),+ owner: zod+ .union([+ zod+ .object({+ scope: zod.enum(['user']),+ user_id: zod.string(),+ })+ .describe('User-scoped property only'),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum(['organization']),+ })+ .describe(+ 'Organization-scoped property only'+ ),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum([+ 'user_and_organization',+ ]),+ user_id: zod.string(),+ })+ .describe(+ 'Both user and organization-scoped'+ ),+ zod+ .object({+ scope: zod.enum(['system']),+ })+ .describe(+ 'System-owned property (no user or org owner)'+ ),+ ])+ .describe(+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'+ ),+ specific_entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}),+ })+ .describe(+ 'Property definition model (service representation).'+ ),+ value: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['Boolean']),+ value: zod+ .boolean()+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ })+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ zod+ .object({+ type: zod.enum(['Number']),+ value: zod+ .number()+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ })+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ zod+ .object({+ type: zod.enum(['String']),+ value: zod+ .string()+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ })+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ zod+ .object({+ type: zod.enum(['Date']),+ value: zod.iso+ .datetime({})+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ })+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ zod+ .object({+ type: zod.enum(['SelectOption']),+ value: zod+ .array(zod.uuid())+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ })+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['EntityReference']),+ value: zod+ .array(+ zod+ .object({+ entity_id: zod.string(),+ entity_type: zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ specific_message_id: zod+ .uuid()+ .nullish()+ .describe(+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'+ ),+ })+ .describe(+ 'Entity reference for entity-type property values.'+ )+ )+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ })+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['Link']),+ value: zod+ .array(zod.string())+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ })+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ ])+ .describe(+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'+ ),+ ])+ .optional(),+ })+ .describe(+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'+ )+ )+ .describe('Properties'),+ updatedAt: zod.iso+ .datetime({})+ .describe('The time the chat was last updated'),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the chat was last viewed'),+ }),+ tag: zod.enum(['chat']),+ }),+ zod.object({+ data: zod.object({+ createdAt: zod.iso+ .datetime({})+ .describe('The time the project was created'),+ deletedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the project was deleted'),+ id: zod.uuid().describe('The id of the project'),+ name: zod.string().describe('The name of the project'),+ ownerId: zod+ .string()+ .describe('The user id of who created the project'),+ parentId: zod+ .uuid()+ .nullish()+ .describe('The parent project id'),+ properties: zod+ .array(+ zod+ .object({+ definition: zod+ .object({+ created_at: zod.iso.datetime({}),+ data_type: zod+ .enum([+ 'BOOLEAN',+ 'DATE',+ 'NUMBER',+ 'STRING',+ 'SELECT_NUMBER',+ 'SELECT_STRING',+ 'ENTITY',+ 'LINK',+ ])+ .describe(+ 'Data type for property values, determining storage and validation.'+ ),+ display_name: zod.string(),+ id: zod.uuid(),+ is_metadata: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'+ ),+ is_multi_select: zod.boolean(),+ is_system: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system property (stored in DB).'+ ),+ owner: zod+ .union([+ zod+ .object({+ scope: zod.enum(['user']),+ user_id: zod.string(),+ })+ .describe('User-scoped property only'),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum(['organization']),+ })+ .describe(+ 'Organization-scoped property only'+ ),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum([+ 'user_and_organization',+ ]),+ user_id: zod.string(),+ })+ .describe(+ 'Both user and organization-scoped'+ ),+ zod+ .object({+ scope: zod.enum(['system']),+ })+ .describe(+ 'System-owned property (no user or org owner)'+ ),+ ])+ .describe(+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'+ ),+ specific_entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}),+ })+ .describe(+ 'Property definition model (service representation).'+ ),+ value: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['Boolean']),+ value: zod+ .boolean()+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ })+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ zod+ .object({+ type: zod.enum(['Number']),+ value: zod+ .number()+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ })+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ zod+ .object({+ type: zod.enum(['String']),+ value: zod+ .string()+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ })+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ zod+ .object({+ type: zod.enum(['Date']),+ value: zod.iso+ .datetime({})+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ })+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ zod+ .object({+ type: zod.enum(['SelectOption']),+ value: zod+ .array(zod.uuid())+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ })+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['EntityReference']),+ value: zod+ .array(+ zod+ .object({+ entity_id: zod.string(),+ entity_type: zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ specific_message_id: zod+ .uuid()+ .nullish()+ .describe(+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'+ ),+ })+ .describe(+ 'Entity reference for entity-type property values.'+ )+ )+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ })+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['Link']),+ value: zod+ .array(zod.string())+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ })+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ ])+ .describe(+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'+ ),+ ])+ .optional(),+ })+ .describe(+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'+ )+ )+ .describe('Properties'),+ updatedAt: zod.iso+ .datetime({})+ .describe('The time the project was updated'),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe('The time the document was last viewed'),+ }),+ tag: zod.enum(['project']),+ }),+ zod.object({+ data: zod+ .object({+ createdAt: zod.iso.datetime({}),+ id: zod.uuid(),+ inboxVisible: zod.boolean(),+ isDraft: zod.boolean(),+ isImportant: zod.boolean(),+ isRead: zod.boolean(),+ name: zod.string().nullish(),+ ownerId: zod.string(),+ projectId: zod.string().nullish(),+ providerId: zod.string().nullish(),+ senderEmail: zod.string().nullish(),+ senderName: zod.string().nullish(),+ senderPhotoUrl: zod.string().nullish(),+ snippet: zod.string().nullish(),+ sortTs: zod.iso.datetime({}),+ updatedAt: zod.iso.datetime({}),+ viewedAt: zod.iso.datetime({}).nullish(),+ })+ .and(+ zod.object({+ attachments: zod.array(+ zod.object({+ contentId: zod.string().nullish(),+ createdAt: zod.iso.datetime({}),+ filename: zod.string().nullish(),+ id: zod.uuid(),+ messageId: zod.uuid(),+ mimeType: zod.string().nullish(),+ providerAttachmentId: zod.string().nullish(),+ sizeBytes: zod.number().nullish(),+ })+ ),+ labels: zod.array(+ zod.object({+ createdAt: zod.iso.datetime({}),+ id: zod.uuid(),+ labelListVisibility: zod.enum([+ 'labelShow',+ 'labelShowIfUnread',+ 'labelHide',+ ]),+ linkId: zod.uuid(),+ messageListVisibility: zod.enum(['show', 'hide']),+ name: zod.string(),+ providerLabelId: zod.string(),+ type: zod.enum(['system', 'user']),+ })+ ),+ participants: zod.array(+ zod.object({+ emailAddress: zod.string().nullish(),+ id: zod.uuid(),+ linkId: zod.uuid(),+ name: zod.string().nullish(),+ sfsPhotoUrl: zod.string().nullish(),+ })+ ),+ properties: zod.array(+ zod+ .object({+ definition: zod+ .object({+ created_at: zod.iso.datetime({}),+ data_type: zod+ .enum([+ 'BOOLEAN',+ 'DATE',+ 'NUMBER',+ 'STRING',+ 'SELECT_NUMBER',+ 'SELECT_STRING',+ 'ENTITY',+ 'LINK',+ ])+ .describe(+ 'Data type for property values, determining storage and validation.'+ ),+ display_name: zod.string(),+ id: zod.uuid(),+ is_metadata: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'+ ),+ is_multi_select: zod.boolean(),+ is_system: zod+ .boolean()+ .describe(+ 'Flag to indicate if this is a system property (stored in DB).'+ ),+ owner: zod+ .union([+ zod+ .object({+ scope: zod.enum(['user']),+ user_id: zod.string(),+ })+ .describe('User-scoped property only'),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum(['organization']),+ })+ .describe(+ 'Organization-scoped property only'+ ),+ zod+ .object({+ organization_id: zod.number(),+ scope: zod.enum([+ 'user_and_organization',+ ]),+ user_id: zod.string(),+ })+ .describe(+ 'Both user and organization-scoped'+ ),+ zod+ .object({+ scope: zod.enum(['system']),+ })+ .describe(+ 'System-owned property (no user or org owner)'+ ),+ ])+ .describe(+ 'Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'+ ),+ specific_entity_type: zod+ .union([+ zod.null(),+ zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ ])+ .optional(),+ updated_at: zod.iso.datetime({}),+ })+ .describe(+ 'Property definition model (service representation).'+ ),+ value: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ type: zod.enum(['Boolean']),+ value: zod+ .boolean()+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ })+ .describe(+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'+ ),+ zod+ .object({+ type: zod.enum(['Number']),+ value: zod+ .number()+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ })+ .describe(+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'+ ),+ zod+ .object({+ type: zod.enum(['String']),+ value: zod+ .string()+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ })+ .describe(+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'+ ),+ zod+ .object({+ type: zod.enum(['Date']),+ value: zod.iso+ .datetime({})+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ })+ .describe(+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'+ ),+ zod+ .object({+ type: zod.enum(['SelectOption']),+ value: zod+ .array(zod.uuid())+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ })+ .describe(+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['EntityReference']),+ value: zod+ .array(+ zod+ .object({+ entity_id: zod.string(),+ entity_type: zod+ .enum([+ 'CHANNEL',+ 'CHAT',+ 'COMPANY',+ 'DOCUMENT',+ 'PROJECT',+ 'TASK',+ 'THREAD',+ 'USER',+ ])+ .describe(+ 'Type of entity that can be referenced by entity properties.'+ ),+ specific_message_id: zod+ .uuid()+ .nullish()+ .describe(+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'+ ),+ })+ .describe(+ 'Entity reference for entity-type property values.'+ )+ )+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ })+ .describe(+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'+ ),+ zod+ .object({+ type: zod.enum(['Link']),+ value: zod+ .array(zod.string())+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ })+ .describe(+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'+ ),+ ])+ .describe(+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'+ ),+ ])+ .optional(),+ })+ .describe(+ 'A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.'+ )+ ),+ })+ ),+ tag: zod.enum(['emailThread']),+ }),+ zod.object({+ data: zod+ .object({+ channel: zod.object({+ channel_type: zod+ .enum(['public', 'private', 'direct_message', 'team'])+ .describe('Type of channel.'),+ created_at: zod.iso.datetime({}),+ id: zod.uuid(),+ name: zod.string().nullish(),+ org_id: zod+ .number()+ .min(+ postItemsSoupAstGroupedResponseItemsDataChannelOrgIdMinOne+ )+ .nullish(),+ owner_id: zod.string(),+ team_id: zod.uuid().nullish(),+ updated_at: zod.iso.datetime({}),+ }),+ participants: zod.array(+ zod.object({+ channel_id: zod.uuid(),+ joined_at: zod.iso.datetime({}),+ left_at: zod.iso.datetime({}).nullish(),+ role: zod+ .enum(['owner', 'admin', 'member'])+ .describe('The role a user has within a channel.'),+ user_id: zod.string(),+ })+ ),+ })+ .and(+ zod.object({+ latest_message: zod+ .union([+ zod.null(),+ zod.object({+ content: zod.string(),+ created_at: zod.iso.datetime({}),+ deleted_at: zod.iso.datetime({}).nullish(),+ mentions: zod+ .array(zod.string())+ .describe(+ 'message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'+ ),+ message_id: zod.uuid(),+ sender_id: zod.string(),+ thread_id: zod.uuid().nullish(),+ updated_at: zod.iso.datetime({}),+ }),+ ])+ .optional(),+ latest_non_thread_message: zod+ .union([+ zod.null(),+ zod.object({+ content: zod.string(),+ created_at: zod.iso.datetime({}),+ deleted_at: zod.iso.datetime({}).nullish(),+ mentions: zod+ .array(zod.string())+ .describe(+ 'message mentions formatted as `{ENTITY_TYPE}:{ENTITY_ID}`'+ ),+ message_id: zod.uuid(),+ sender_id: zod.string(),+ thread_id: zod.uuid().nullish(),+ updated_at: zod.iso.datetime({}),+ }),+ ])+ .optional(),+ })+ )+ .and(+ zod.object({+ interacted_at: zod.iso.datetime({}).nullish(),+ viewed_at: zod.iso.datetime({}).nullish(),+ })+ ),+ tag: zod.enum(['channel']),+ }),+ zod.object({+ data: zod+ .object({+ attended: zod+ .boolean()+ .describe(+ 'Whether the requesting user attended this call. Kept for compatibility\nand derived from `status == ATTENDED`.'+ ),+ callId: zod.uuid().describe('The call identifier.'),+ channelId: zod+ .uuid()+ .describe('The channel this call belongs to.'),+ channelName: zod+ .string()+ .nullish()+ .describe('Resolved display name for the channel.'),+ createdBy: zod+ .string()+ .describe('User who created the call.'),+ customName: zod+ .string()+ .nullish()+ .describe(+ 'User-supplied or AI-generated display name for the call.'+ ),+ durationMs: zod+ .number()+ .nullish()+ .describe(+ 'Call duration in milliseconds (None if still active).'+ ),+ endedAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ 'When the call ended (None if still active).'+ ),+ isActive: zod+ .boolean()+ .describe('Whether the call is currently active.'),+ participants: zod+ .array(+ zod+ .object({+ joinedAt: zod.iso+ .datetime({})+ .describe('When the user joined the call.'),+ leftAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ 'When the user left (None if still in an active call).'+ ),+ userId: zod.string().describe('The user id.'),+ })+ .describe(+ 'A participant in a call record, as displayed in Soup.'+ )+ )+ .describe('Participants in the call.'),+ startedAt: zod.iso+ .datetime({})+ .describe('When the call started.'),+ status: zod+ .enum(['ATTENDED', 'MISSED', 'UNATTENDED'])+ .describe(+ 'Viewer-relative attendance status for a call record.\nSerializes as `ATTENDED`, `MISSED`, or `UNATTENDED`.'+ ),+ summary: zod+ .string()+ .nullish()+ .describe(+ 'AI-generated summary of the call. Only set on archived\n`call_records` once summarization has run; active calls always\nreturn `None`.'+ ),+ })+ .describe(+ 'A call record as displayed in Soup. Excludes room_name, egress_id,\nand transcript — fields that are irrelevant for the soup feed.'+ ),+ tag: zod.enum(['call']),+ }),+ zod.object({+ data: zod+ .object({+ createdAt: zod.iso+ .datetime({})+ .describe('When the company was created.'),+ description: zod+ .string()+ .nullish()+ .describe(+ "Display description from the primary domain's directory entry."+ ),+ domains: zod+ .array(+ zod+ .object({+ companyId: zod+ .uuid()+ .describe(+ 'The id of the company the domain belongs to.'+ ),+ createdAt: zod.iso+ .datetime({})+ .describe(+ 'When the domain record was created.'+ ),+ domain: zod+ .string()+ .describe(+ 'The domain (lowercased, e.g. \"acme.com\").'+ ),+ id: zod+ .uuid()+ .describe('The id of the domain record.'),+ })+ .describe(+ "A CRM domain as displayed in Soup. Mirrors the crm crate's\n[`CrmDomain`] with a stable wire shape that the FE can rely on."+ )+ )+ .describe(+ 'Domains associated with this company, ordered by creation time\nascending (primary first).'+ ),+ emailSync: zod+ .boolean()+ .describe(+ 'Whether email sync is enabled for this company.'+ ),+ hidden: zod+ .boolean()+ .describe(+ 'Whether the company is hidden from CRM listings. Soup filters\nthese out by default.'+ ),+ id: zod.uuid().describe('The id of the company.'),+ name: zod+ .string()+ .nullish()+ .describe(+ "Display name from the primary domain's directory entry, or\n`None` when unresolved."+ ),+ teamId: zod+ .uuid()+ .describe(+ 'The id of the team that owns this company record.'+ ),+ updatedAt: zod.iso+ .datetime({})+ .describe('When the company was last updated.'),+ viewedAt: zod.iso+ .datetime({})+ .nullish()+ .describe(+ 'When the requesting user last viewed this company, or `None` if\nnever viewed. Mirrors the `viewed_at` other soup entities carry.'+ ),+ })+ .describe(+ 'A CRM company as displayed in Soup. Carries the core company\nfields plus display metadata resolved from `crm_domain_directory`\nagainst the primary (earliest-created) domain.'+ ),+ tag: zod.enum(['crmCompany']),+ }),+ zod.object({+ data: zod+ .object({+ createdAt: zod.iso+ .datetime({})+ .describe('Timestamp when the record was created.'),+ foreignEntityId: zod+ .string()+ .describe(+ 'Identifier assigned by the external system.'+ ),+ foreignEntitySource: zod+ .string()+ .describe(+ 'Source system that owns the external identifier.'+ ),+ id: zod+ .uuid()+ .describe(+ 'Internal primary key for this foreign entity record.'+ ),+ metadata: zod+ .object({})+ .describe(+ 'Arbitrary metadata stored with the mapping.'+ ),+ storedForAuthEntity: zod+ .string()+ .describe(+ 'Internal auth entity namespace this foreign entity is stored for.'+ ),+ storedForId: zod+ .string()+ .describe(+ 'Internal entity identifier this foreign entity is stored for.'+ ),+ updatedAt: zod.iso+ .datetime({})+ .describe(+ 'Timestamp when the record was last updated.'+ ),+ })+ .describe('A foreign entity record as displayed in Soup.'),+ tag: zod.enum(['foreignEntity']),+ }),+ ])+ .and(+ zod.object({+ frecency_score: zod.number(),+ })+ )+ )+ .describe(+ 'Items in this page, keyed by id. Ordering lives in `group.item_ids`.'+ ),+ })+ .describe('Response for fetching a page within one group.')+ .and(+ zod.object({+ mode: zod.enum(['group_page']),+ })+ ),+ ])+ .describe('Response for grouped soup queries.');+/*** @summary Gets the users pinned items*/diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 4a271f5fe3..4ad4aff587 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -6851,6 +6851,66 @@}}},+ "/items/soup/ast/grouped": {+ "post": {+ "tags": ["soup::inbound::axum_router"],+ "summary": "Gets the items grouped by the specified field using AST filters.",+ "operationId": "post_items_soup_ast_grouped",+ "parameters": [+ {+ "name": "cursor",+ "in": "query",+ "description": "Base64 encoded cursor value.",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PostGroupedSoupAstRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GroupedSoupPage"+ }+ }+ }+ },+ "403": {+ "description": "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/pins": {"get": {"tags": ["pins::get_pins"],@@ -9347,6 +9407,94 @@}}},+ "ApiGroupByField": {+ "oneOf": [+ {+ "type": "string",+ "description": "Smart date buckets: Today, Yesterday, This Week, Last Week, This Month, Last Month, Older",+ "enum": ["date"]+ },+ {+ "type": "string",+ "description": "Group by entity type (document, email, channel, etc.)",+ "enum": ["entity_type"]+ },+ {+ "type": "string",+ "description": "Group by project",+ "enum": ["project"]+ },+ {+ "type": "object",+ "description": "Group by a property value (e.g., status, priority, or custom properties)",+ "required": ["property"],+ "properties": {+ "property": {+ "type": "object",+ "description": "Group by a property value (e.g., status, priority, or custom properties)",+ "required": ["property_definition_id"],+ "properties": {+ "entity_type": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ApiPropertyEntityType",+ "description": "Optional entity type filter for the property lookup"+ }+ ]+ },+ "property_definition_id": {+ "type": "string",+ "format": "uuid",+ "description": "The property definition UUID to group by"+ }+ }+ }+ }+ }+ ],+ "description": "API representation of group-by field."+ },+ "ApiGroupMeta": {+ "type": "object",+ "description": "API representation of group metadata.\n\nItems belonging to this group are referenced by `item_ids`, each of which\nlooks up an entry in `GroupedSoupPage.items` (a normalized pool).",+ "required": ["key", "label", "total_count", "item_ids"],+ "properties": {+ "display_order": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "Display order for sorting groups (lower = first)"+ },+ "item_ids": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Ordered ids of items in this group for the current page.\nEach id keys into `GroupedSoupPage.items`."+ },+ "key": {+ "type": "string",+ "description": "Group key - format depends on group_by field"+ },+ "label": {+ "type": "string",+ "description": "Human-readable label for the group"+ },+ "next_cursor": {+ "type": ["string", "null"],+ "description": "Cursor to load more items specifically from this group"+ },+ "total_count": {+ "type": "integer",+ "format": "int32",+ "description": "Total count of items in this group across all pages",+ "minimum": 0+ }+ }+ },"ApiMessageAttachment": {"type": "object","description": "An attachment on a message.",@@ -9415,6 +9563,20 @@"description": "Participant role in a channel.","enum": ["owner", "admin", "member"]},+ "ApiPropertyEntityType": {+ "type": "string",+ "description": "Entity type for property lookups (API representation).",+ "enum": [+ "CHANNEL",+ "CHAT",+ "COMPANY",+ "DOCUMENT",+ "PROJECT",+ "TASK",+ "THREAD",+ "USER"+ ]+ },"ApiResolvedChannelMessage": {"type": "object","description": "Resolution metadata for any channel message id.",@@ -14294,6 +14456,157 @@}}},+ "GroupedInitialParams": {+ "type": "object",+ "description": "Parameters for the initial grouped soup query.",+ "required": ["group_by"],+ "properties": {+ "group_by": {+ "$ref": "#/components/schemas/ApiGroupByField",+ "description": "Field to group results by (required)."+ },+ "per_group_limit": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "Limit the number of items returned per group. Defaults to 20. Max 500.",+ "minimum": 0+ },+ "sort_method": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/GroupedSoupSort",+ "description": "Sort method. Defaults to viewed_updated."+ }+ ]+ }+ }+ },+ "GroupedPageParams": {+ "type": "object",+ "description": "Parameters for fetching one page within a specific group.",+ "required": ["group_by", "group_key"],+ "properties": {+ "group_by": {+ "$ref": "#/components/schemas/ApiGroupByField",+ "description": "Field to group results by (required)."+ },+ "group_key": {+ "type": "string",+ "description": "Group key to fetch."+ },+ "limit": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "Limit the number of items returned. Defaults to 20. Max 500.",+ "minimum": 0+ },+ "sort_method": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/GroupedSoupSort",+ "description": "Sort method. Defaults to viewed_updated."+ }+ ]+ }+ }+ },+ "GroupedSoupGroupPage": {+ "type": "object",+ "description": "Response for fetching a page within one group.",+ "required": ["items", "group"],+ "properties": {+ "group": {+ "$ref": "#/components/schemas/ApiGroupMeta",+ "description": "Metadata and item membership for the requested group page."+ },+ "items": {+ "type": "object",+ "description": "Items in this page, keyed by id. Ordering lives in `group.item_ids`.",+ "additionalProperties": {+ "$ref": "#/components/schemas/SoupApiItem"+ },+ "propertyNames": {+ "type": "string",+ "format": "uuid"+ }+ }+ }+ },+ "GroupedSoupInitialPage": {+ "type": "object",+ "description": "Response for the initial grouped soup query.\n\nItems are returned as a pool keyed by id; each `ApiGroupMeta.item_ids`\ndescribes the ordered membership of one group.",+ "required": ["items", "groups"],+ "properties": {+ "groups": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiGroupMeta"+ },+ "description": "Ordered group metadata for this grouped response."+ },+ "items": {+ "type": "object",+ "description": "Items in this page, keyed by id. Ordering lives in `groups[].item_ids`.",+ "additionalProperties": {+ "$ref": "#/components/schemas/SoupApiItem"+ },+ "propertyNames": {+ "type": "string",+ "format": "uuid"+ }+ }+ }+ },+ "GroupedSoupPage": {+ "oneOf": [+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/GroupedSoupInitialPage"+ },+ {+ "type": "object",+ "required": ["mode"],+ "properties": {+ "mode": {+ "type": "string",+ "enum": ["initial"]+ }+ }+ }+ ]+ },+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/GroupedSoupGroupPage"+ },+ {+ "type": "object",+ "required": ["mode"],+ "properties": {+ "mode": {+ "type": "string",+ "enum": ["group_page"]+ }+ }+ }+ ]+ }+ ],+ "description": "Response for grouped soup queries."+ },+ "GroupedSoupSort": {+ "type": "string",+ "description": "Sort method for grouped queries (frecency not supported).",+ "enum": ["viewed_at", "created_at", "updated_at", "viewed_updated"]+ },"HashMap": {"type": "object","additionalProperties": {@@ -15193,6 +15506,71 @@}}},+ "PostGroupedSoupAstGroupPageRequest": {+ "allOf": [+ {+ "$ref": "#/components/schemas/ApiEntityFilterAst",+ "description": "Filters to apply (AST format)"+ },+ {+ "$ref": "#/components/schemas/GroupedPageParams",+ "description": "Grouping parameters (required)"+ }+ ],+ "description": "Request body for fetching one page within a specific group."+ },+ "PostGroupedSoupAstInitialRequest": {+ "allOf": [+ {+ "$ref": "#/components/schemas/ApiEntityFilterAst",+ "description": "Filters to apply (AST format)"+ },+ {+ "$ref": "#/components/schemas/GroupedInitialParams",+ "description": "Grouping parameters (required)"+ }+ ],+ "description": "Request body for the initial grouped soup query."+ },+ "PostGroupedSoupAstRequest": {+ "oneOf": [+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/PostGroupedSoupAstInitialRequest"+ },+ {+ "type": "object",+ "required": ["mode"],+ "properties": {+ "mode": {+ "type": "string",+ "enum": ["initial"]+ }+ }+ }+ ]+ },+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/PostGroupedSoupAstGroupPageRequest"+ },+ {+ "type": "object",+ "required": ["mode"],+ "properties": {+ "mode": {+ "type": "string",+ "enum": ["group_page"]+ }+ }+ }+ ]+ }+ ],+ "description": "Request body for grouped soup queries with AST filters."+ },"PostMessageRequest": {"type": "object","description": "Request to send a channel message.",diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 5a1df390d1..377515956a 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -122,7 +122,12 @@ use models_soup::email_thread::{use models_soup::foreign_entity::SoupForeignEntity;use models_soup::item::SoupItem;use models_soup::project::SoupProject;-use soup::inbound::axum_router::{PostSoupRequest, SoupApiItem, SoupApiSort, SoupPage};+use soup::inbound::axum_router::{+ ApiGroupByField, ApiGroupMeta, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage,+ PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest,+ PostGroupedSoupAstRequest, PostSoupAstRequest, PostSoupRequest, SoupApiItem, SoupApiSort,+ SoupPage,+};use utoipa::OpenApi;#[derive(OpenApi)]@@ -197,6 +202,7 @@ use utoipa::OpenApi;soup::inbound::axum_router::get_soup_handler,soup::inbound::axum_router::post_soup_handler,soup::inbound::axum_router::post_soup_ast_handler,+ soup::inbound::axum_router::post_grouped_soup_ast_handler,// channelschannels::inbound::axum_router::create_channel_handler,@@ -391,6 +397,15 @@ use utoipa::OpenApi;SoupMessageListVisibility,SoupLabelType,PostSoupRequest,+ PostSoupAstRequest,+ PostGroupedSoupAstInitialRequest,+ PostGroupedSoupAstGroupPageRequest,+ PostGroupedSoupAstRequest,+ ApiGroupByField,+ ApiGroupMeta,+ GroupedSoupInitialPage,+ GroupedSoupGroupPage,+ GroupedSoupPage,// ChannelsApiChannelMessagesPage,diff --git a/rust/cloud-storage/soup/src/domain/models/grouping.rs b/rust/cloud-storage/soup/src/domain/models/grouping.rsindex 89d7d211c7..081a09b156 100644--- a/rust/cloud-storage/soup/src/domain/models/grouping.rs+++ b/rust/cloud-storage/soup/src/domain/models/grouping.rs@@ -40,10 +40,9 @@ pub struct GroupMeta {pub display_order: Option<i32>,/// Total count of items in this group across all pagespub total_count: u32,- /// Number of items from this group in the current page- pub page_count: u32,- /// Index in the items array where this group starts (current page)- pub start_index: u32,+ /// Ordered ids of items in this group for the current page.+ /// Each id keys into `GroupedResponse::items`.+ pub item_ids: Vec<Uuid>,/// Cursor to load more items specifically from this group#[serde(skip_serializing_if = "Option::is_none")]pub next_cursor: Option<String>,@@ -52,8 +51,8 @@ pub struct GroupMeta {/// Result of building a grouped response.#[derive(Debug)]pub struct GroupedResponse {- /// Items in this page with frecency scores.- pub items: Vec<FrecencySoupItem>,+ /// Items pool keyed by id. Ordering is described by `groups[].item_ids`.+ pub items: HashMap<Uuid, FrecencySoupItem>,/// Group metadata for each group.pub groups: Vec<GroupMeta>,/// Page-level cursor for loading more items.@@ -70,8 +69,7 @@ pub fn build_grouped_response() -> GroupedResponse {struct GroupData {total_count: u32,- page_count: u32,- start_index: u32,+ item_ids: Vec<Uuid>,last_item_id: Option<Uuid>,last_cursor_val: Option<CursorVal<SimpleSortMethod>>,label: Option<String>,@@ -79,10 +77,10 @@ pub fn build_grouped_response(}let mut group_stats: HashMap<String, GroupData> = HashMap::new();- let mut result_items = Vec::with_capacity(items.len());+ let mut items_pool: HashMap<Uuid, FrecencySoupItem> = HashMap::with_capacity(items.len());let mut get_cursor_val = SoupItem::sort_on(sort_method);- for (idx, grouped_item) in items.into_iter().enumerate() {+ for grouped_item in items.into_iter() {let key = grouped_item.group_key.clone();let item_id = grouped_item.item.id();let cursor_val = get_cursor_val(&grouped_item.item);@@ -95,28 +93,31 @@ pub fn build_grouped_response(};GroupData {total_count: grouped_item.group_total_count,- page_count: 0,- start_index: idx as u32,+ item_ids: Vec::new(),last_item_id: None,last_cursor_val: None,label: Some(label),display_order,}});- entry.page_count += 1;+ entry.item_ids.push(item_id);entry.last_item_id = Some(item_id);entry.last_cursor_val = Some(cursor_val);- result_items.push(FrecencySoupItem {- item: grouped_item.item,- frecency_score: grouped_item.frecency_score,- });+ // First occurrence wins; later duplicates are dropped instead of+ // overwriting an already-populated entry.+ items_pool+ .entry(item_id)+ .or_insert_with(|| FrecencySoupItem {+ item: grouped_item.item,+ frecency_score: grouped_item.frecency_score,+ });}let mut groups: Vec<GroupMeta> = group_stats.into_iter().map(|(key, data)| {- let has_more = data.page_count < data.total_count;+ let has_more = (data.item_ids.len() as u32) < data.total_count;let next_cursor = if has_more {data.last_item_id.zip(data.last_cursor_val)@@ -127,7 +128,7 @@ pub fn build_grouped_response(EntityFilterAst,> = CursorWithValAndFilter {id,- limit: data.page_count as usize,+ limit: data.item_ids.len(),val,filter: filters.clone(),};@@ -142,8 +143,7 @@ pub fn build_grouped_response(label: data.label.unwrap_or_default(),display_order: data.display_order,total_count: data.total_count,- page_count: data.page_count,- start_index: data.start_index,+ item_ids: data.item_ids,next_cursor,}})@@ -162,7 +162,7 @@ pub fn build_grouped_response(};GroupedResponse {- items: result_items,+ items: items_pool,groups,page_cursor,}diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rsindex 0b22d9ec95..46649d4f37 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs@@ -48,7 +48,7 @@ use model_error_response::ErrorResponse;use model_user::axum_extractor::MacroUserExtractor;use models_grouping::{GroupByField, GroupingConfig};use models_pagination::{- Cursor, CursorWithValAndFilter, Frecency, PaginatedOpaqueCursor, SimpleSortMethod, SortMethod,+ CursorWithValAndFilter, Frecency, PaginatedOpaqueCursor, SimpleSortMethod, SortMethod,TypeEraseCursor,};use models_soup::item::SoupItem;@@ -56,6 +56,7 @@ use non_empty::IsEmpty;use recursion::CollapsibleExt;use rootcause::{Report, report};use serde::{Deserialize, Serialize};+use std::collections::HashMap;use std::sync::Arc;use thiserror::Error;use utoipa::{IntoParams, ToSchema};@@ -137,6 +138,56 @@ pub struct GroupedParams {pub limit: Option<u16>,}+/// Parameters for the initial grouped soup query.+#[derive(Debug, Deserialize, ToSchema)]+pub struct GroupedInitialParams {+ /// Field to group results by (required).+ pub group_by: ApiGroupByField,+ /// Sort method. Defaults to viewed_updated.+ #[serde(default)]+ pub sort_method: Option<GroupedSoupSort>,+ /// Limit the number of items returned per group. Defaults to 20. Max 500.+ #[serde(default)]+ pub per_group_limit: Option<u16>,+}++/// Parameters for fetching one page within a specific group.+#[derive(Debug, Deserialize, ToSchema)]+pub struct GroupedPageParams {+ /// Field to group results by (required).+ pub group_by: ApiGroupByField,+ /// Group key to fetch.+ pub group_key: String,+ /// Sort method. Defaults to viewed_updated.+ #[serde(default)]+ pub sort_method: Option<GroupedSoupSort>,+ /// Limit the number of items returned. Defaults to 20. Max 500.+ #[serde(default)]+ pub limit: Option<u16>,+}++impl From<GroupedInitialParams> for GroupedParams {+ fn from(params: GroupedInitialParams) -> Self {+ Self {+ group_by: params.group_by,+ group_key: None,+ sort_method: params.sort_method,+ limit: params.per_group_limit,+ }+ }+}++impl From<GroupedPageParams> for GroupedParams {+ fn from(params: GroupedPageParams) -> Self {+ Self {+ group_by: params.group_by,+ group_key: Some(params.group_key),+ sort_method: params.sort_method,+ limit: params.limit,+ }+ }+}+/// Entity type for property lookups (API representation).#[derive(Debug, Clone, Copy, Deserialize, Serialize, ToSchema)]#[serde(rename_all = "SCREAMING_SNAKE_CASE")]@@ -213,6 +264,9 @@ impl From<ApiGroupByField> for GroupByField {}/// API representation of group metadata.+///+/// Items belonging to this group are referenced by `item_ids`, each of which+/// looks up an entry in `GroupedSoupPage.items` (a normalized pool).#[derive(Debug, Clone, Serialize, ToSchema)]pub struct ApiGroupMeta {/// Group key - format depends on group_by field@@ -224,10 +278,9 @@ pub struct ApiGroupMeta {pub display_order: Option<i32>,/// Total count of items in this group across all pagespub total_count: u32,- /// Number of items from this group in the current page- pub page_count: u32,- /// Index in the items array where this group starts (current page)- pub start_index: u32,+ /// Ordered ids of items in this group for the current page.+ /// Each id keys into `GroupedSoupPage.items`.+ pub item_ids: Vec<Uuid>,/// Cursor to load more items specifically from this group#[serde(skip_serializing_if = "Option::is_none")]pub next_cursor: Option<String>,@@ -240,8 +293,7 @@ impl From<GroupMeta> for ApiGroupMeta {label: meta.label,display_order: meta.display_order,total_count: meta.total_count,- page_count: meta.page_count,- start_index: meta.start_index,+ item_ids: meta.item_ids,next_cursor: meta.next_cursor,}}@@ -253,16 +305,38 @@ pub struct SoupPage {next_cursor: Option<String>,}+/// Response for the initial grouped soup query.+///+/// Items are returned as a pool keyed by id; each `ApiGroupMeta.item_ids`+/// describes the ordered membership of one group.+#[derive(Debug, Serialize, ToSchema)]+pub struct GroupedSoupInitialPage {+ /// Items in this page, keyed by id. Ordering lives in `groups[].item_ids`.+ pub items: HashMap<Uuid, SoupApiItem>,+ /// Ordered group metadata for this grouped response.+ pub groups: Vec<ApiGroupMeta>,+}++/// Response for fetching a page within one group.+#[derive(Debug, Serialize, ToSchema)]+pub struct GroupedSoupGroupPage {+ /// Items in this page, keyed by id. Ordering lives in `group.item_ids`.+ pub items: HashMap<Uuid, SoupApiItem>,+ /// Metadata and item membership for the requested group page.+ pub group: ApiGroupMeta,+}+/// Response for grouped soup queries.#[derive(Debug, Serialize, ToSchema)]-pub struct GroupedSoupPage {- /// Items in this page (flat list, ordered by group then sort)- pub items: Vec<SoupApiItem>,- /// Cursor to load the next page (global pagination)- pub next_cursor: Option<String>,- /// Group metadata - present when group_by is specified in the request- #[serde(skip_serializing_if = "Option::is_none")]- pub groups: Option<Vec<ApiGroupMeta>>,+#[serde(tag = "mode", rename_all = "snake_case")]+pub enum GroupedSoupPage {+ Initial(GroupedSoupInitialPage),+ GroupPage(GroupedSoupGroupPage),+}++struct ApiGroupedSoupParts {+ items: HashMap<Uuid, SoupApiItem>,+ groups: Vec<ApiGroupMeta>,}pub struct SoupRouterState<T, U, EAS> {@@ -383,7 +457,7 @@ wherefilters: EntityFilterAst,params: GroupedParams,cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, EntityFilterAst>>,- ) -> Result<Json<GroupedSoupPage>, SoupHandlerErr> {+ ) -> Result<ApiGroupedSoupParts, SoupHandlerErr> {let limit = params.limit.unwrap_or(20).clamp(20, 500);let sort_method = params.sort_method@@ -420,21 +494,18 @@ wherefilters,);- Ok(Json(GroupedSoupPage {+ Ok(ApiGroupedSoupParts {items: response.items.into_iter()- .map(SoupApiItem::from_frecency_soup_item)+ .map(|(id, item)| (id, SoupApiItem::from_frecency_soup_item(item))).collect(),- next_cursor: response.page_cursor,- groups: Some(- response- .groups- .into_iter()- .map(ApiGroupMeta::from)- .collect(),- ),- }))+ groups: response+ .groups+ .into_iter()+ .map(ApiGroupMeta::from)+ .collect(),+ })}}@@ -788,19 +859,44 @@ where.await}-/// Request body for grouped soup queries with AST filters.+/// Request body for the initial grouped soup query.+#[derive(Debug, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct PostGroupedSoupAstInitialRequest {+ /// Filters to apply (AST format)+ #[serde(default, flatten)]+ filters: ApiEntityFilterAst,+ /// Grouping parameters (required)+ #[serde(flatten)]+ params: GroupedInitialParams,+}++/// Request body for fetching one page within a specific group.#[derive(Debug, Deserialize, ToSchema)]#[serde(rename_all = "camelCase")]-pub struct PostGroupedSoupAstRequest {+pub struct PostGroupedSoupAstGroupPageRequest {/// Filters to apply (AST format)#[serde(default, flatten)]filters: ApiEntityFilterAst,/// Grouping parameters (required)#[serde(flatten)]- params: GroupedParams,+ params: GroupedPageParams,+}++/// Request body for grouped soup queries with AST filters.+#[derive(Debug, Deserialize, ToSchema)]+#[serde(tag = "mode", rename_all = "snake_case")]+pub enum PostGroupedSoupAstRequest {+ Initial(PostGroupedSoupAstInitialRequest),+ GroupPage(PostGroupedSoupAstGroupPageRequest),}-/// Gets the items grouped by the specified field using AST filters+enum GroupedSoupRequestMode {+ Initial,+ GroupPage,+}++/// Gets the items grouped by the specified field using AST filters.#[utoipa::path(post,operation_id = "post_items_soup_ast_grouped",@@ -819,41 +915,50 @@ pub struct PostGroupedSoupAstRequest {pub async fn post_grouped_soup_ast_handler<T, U, EAS>(State(service): State<SoupRouterState<T, U, EAS>>,Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,- cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, ApiEntityFilterAst>>,- Json(PostGroupedSoupAstRequest { filters, params }): Json<PostGroupedSoupAstRequest>,+ cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, EntityFilterAst>>,+ Json(request): Json<PostGroupedSoupAstRequest>,) -> Result<Json<GroupedSoupPage>, SoupHandlerErr>whereT: SoupService,U: EmailService,EAS: EntityAccessService,{+ let (filters, params, mode) = match request {+ PostGroupedSoupAstRequest::Initial(request) => (+ request.filters,+ request.params.into(),+ GroupedSoupRequestMode::Initial,+ ),+ PostGroupedSoupAstRequest::GroupPage(request) => (+ request.filters,+ request.params.into(),+ GroupedSoupRequestMode::GroupPage,+ ),+ };+let filters = filters.into_entity_ast().map_err(|_| SoupHandlerErr::Expand)?;- let simple_cursor = cursor- .map(- |Cursor {- id,- limit,- val,- filter,- }| {- Ok::<_, SoupHandlerErr>(Cursor {- id,- limit,- val,- filter: filter- .into_entity_ast()- .map_err(|_| SoupHandlerErr::Expand)?,- })- },- )- .transpose()?;+ let response = service+ .handle_grouped(macro_user_id, filters, params, cursor)+ .await?;- service- .handle_grouped(macro_user_id, filters, params, simple_cursor)- .await+ Ok(Json(match mode {+ GroupedSoupRequestMode::Initial => GroupedSoupPage::Initial(GroupedSoupInitialPage {+ items: response.items,+ groups: response.groups,+ }),+ GroupedSoupRequestMode::GroupPage => {+ let Some(group) = response.groups.into_iter().next() else {+ return Err(SoupHandlerErr::Expand);+ };+ GroupedSoupPage::GroupPage(GroupedSoupGroupPage {+ items: response.items,+ group,+ })+ }+ }))}/// Returns the team receipt to use when CRM-scoped visibility is required.