Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(soup): optimistic batch updating of properties (#2668)
teoee6fcf89d7eb
diff --git a/js/app/biome.jsonc b/js/app/biome.jsoncindex ba543a5d28..3eed8492dd 100644--- a/js/app/biome.jsonc+++ b/js/app/biome.jsonc@@ -1,5 +1,5 @@{- "$schema": "https://biomejs.dev/schemas/2.4.12/schema.json",+ "$schema": "https://biomejs.dev/schemas/2.4.7/schema.json","vcs": {"clientKind": "git","enabled": true,diff --git a/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsx b/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsxindex c3bb50f6b4..116c8c4581 100644--- a/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsx+++ b/js/app/packages/app/component/property-edit-modal/PropertyEditorModal.tsx@@ -107,15 +107,17 @@ export function PropertyEditorModal() {const handlePropertySave = (value: PropertyApiValues) => {const { selectedEntities, targetProperty } = propertyEditorState;if (!selectedEntities.length || !targetProperty) return;++ // Snapshot before closing — closing resets selectedEntities.+ const count = selectedEntities.length;+ const message = `Set ${targetProperty.displayName} for ${+ count === 1 ? selectedEntities[0].name : count + ' entities'+ }`;+saveProperties(selectedEntities, targetProperty, value).then((success) => {- if (success) {- const count = selectedEntities.length;- const message = `Set ${targetProperty.displayName} for ${count === 1 ? selectedEntities[0].name : count + ' entities'}`;- toast.success(message);- }- // failure toast handled by mutation- closePropertyEditor();+ if (success) toast.success(message);});+ closePropertyEditor();};const { dispose: disposeHotkey } = registerHotkey({diff --git a/js/app/packages/app/component/property-edit-modal/hooks/useSaveProperties.ts b/js/app/packages/app/component/property-edit-modal/hooks/useSaveProperties.tsindex 207bd6d54d..f4682d1811 100644--- a/js/app/packages/app/component/property-edit-modal/hooks/useSaveProperties.ts+++ b/js/app/packages/app/component/property-edit-modal/hooks/useSaveProperties.ts@@ -3,10 +3,7 @@ import type {PropertyApiValues,PropertyDefinitionDomain,} from '@core/component/Properties/types';-import {- isInstantiatedProperty,- macroEntityToPropertyEntityType,-} from '@core/component/Properties/utils';+import { macroEntityToPropertyEntityType } from '@core/component/Properties/utils';import type { EntityData } from '@entity';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';@@ -21,19 +18,15 @@ export function useSavePropertyForMultiEntitites() {console.error('saveProperties Error: no selected entities');}- const definitionId = isInstantiatedProperty(property)- ? property.propertyDefinitionId- : property.id;-- const propList = entities.map((e) => ({- entityId: e.id,- entityType: macroEntityToPropertyEntityType(e),- property: { id: definitionId, isMultiSelect: property.isMultiSelect },- apiValues: value,- }));-try {- await mutation.mutateAsync({ properties: propList });+ await mutation.mutateAsync({+ properties: entities.map((e) => ({+ entityId: e.id,+ entityType: macroEntityToPropertyEntityType(e),+ property,+ apiValues: value,+ })),+ });return true;} catch {return false;diff --git a/js/app/packages/block-md/component/FrontMatterProperties.tsx b/js/app/packages/block-md/component/FrontMatterProperties.tsxindex 06f95f9ce0..d6efb79d9f 100644--- a/js/app/packages/block-md/component/FrontMatterProperties.tsx+++ b/js/app/packages/block-md/component/FrontMatterProperties.tsx@@ -19,7 +19,7 @@ import type {Property,PropertyApiValues,} from '@core/component/Properties/types';-import { useSaveEntityPropertyMutation } from '@queries/properties/entity';+import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import { useDocumentMetadataQuery } from '@queries/storage/document-metadata';import CaretDown from '@icon/bold/caret-down-bold.svg';import CaretRight from '@icon/bold/caret-right-bold.svg';@@ -204,27 +204,18 @@ export function FrontMatterProperties(props: FrontMatterPropertiesProps) {const height = () => containerSize.height;createEffect(on(height, layoutShift));- const saveMutation = useSaveEntityPropertyMutation();+ const saveMutation = useBulkSaveEntityPropertiesMutation();++ const saveOne = (property: Property, apiValues: PropertyApiValues) =>+ saveMutation.mutateAsync({+ properties: [{ entityId: blockId, entityType, property, apiValues }],+ });// Network-based save handler for FrontMatter propertiesconst saveHandler: PropertySaveHandler = {- saveProperty: (property: Property, value: PropertyApiValues) =>- saveMutation.mutateAsync({- entityId: blockId,- entityType,- property,- apiValues: value,- }),- saveDate: (property: Property, date: Date) =>- saveMutation.mutateAsync({- entityId: blockId,- entityType,- property,- apiValues: {- valueType: 'DATE',- value: date,- },- }),+ saveProperty: (property, value) => saveOne(property, value),+ saveDate: (property, date) =>+ saveOne(property, { valueType: 'DATE', value: date }),};return (diff --git a/js/app/packages/core/component/Properties/PropertiesView.tsx b/js/app/packages/core/component/Properties/PropertiesView.tsxindex e29a0d8010..3bcf7ccf97 100644--- a/js/app/packages/core/component/Properties/PropertiesView.tsx+++ b/js/app/packages/core/component/Properties/PropertiesView.tsx@@ -1,6 +1,6 @@import { useBlockId } from '@core/block';import LoadingSpinner from '@icon/regular/spinner.svg';-import { useSaveEntityPropertyMutation } from '@queries/properties/entity';+import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import { type Accessor, Show } from 'solid-js';import { Modals } from './component/modal/Modals';import { AddPropertyButton } from './component/panel/AddPropertyButton';@@ -30,7 +30,7 @@ export function PropertiesView(props: PropertiesPanelProps) {false);- const saveMutation = useSaveEntityPropertyMutation();+ const saveMutation = useBulkSaveEntityPropertiesMutation();const handleRefresh = () => {refetch();@@ -49,24 +49,22 @@ export function PropertiesView(props: PropertiesPanelProps) {handleRefresh();};- const saveHandler: PropertySaveHandler = {- saveProperty: (property: Property, value: PropertyApiValues) =>- saveMutation.mutateAsync({- entityId: blockId,- entityType: props.entityType,- property,- apiValues: value,- }),- saveDate: (property: Property, date: Date) =>- saveMutation.mutateAsync({- entityId: blockId,- entityType: props.entityType,- property,- apiValues: {- valueType: 'DATE',- value: date,+ const saveOne = (property: Property, apiValues: PropertyApiValues) =>+ saveMutation.mutateAsync({+ properties: [+ {+ entityId: blockId,+ entityType: props.entityType,+ property,+ apiValues,},- }),+ ],+ });++ const saveHandler: PropertySaveHandler = {+ saveProperty: (property, value) => saveOne(property, value),+ saveDate: (property, date) =>+ saveOne(property, { valueType: 'DATE', value: date }),};return (diff --git a/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx b/js/app/packages/entity/src/extractors-property/entity-key-properties.tsxindex 1f2e827f40..925b2450a6 100644--- a/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx+++ b/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx@@ -10,7 +10,7 @@ import type {} from '@core/component/Properties/types';import { EntityType } from '@service-properties/generated/schemas/entityType';import { For, Show, Suspense, createMemo } from 'solid-js';-import { useSaveEntityPropertyMutation } from '@queries/properties/entity';+import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import { match } from 'ts-pattern';import {type EntityData,@@ -68,26 +68,24 @@ export function EntityKeyProperties(props: EntityKeyPropertiesProps) {return getSortedKeyProperties(soupProperties.map(soupPropertyToProperty));});- const saveMutation = useSaveEntityPropertyMutation();+ const saveMutation = useBulkSaveEntityPropertiesMutation();- const saveHandler: PropertySaveHandler = {- saveProperty: (property: Property, value: PropertyApiValues) =>- saveMutation.mutateAsync({- entityId: props.entity.id,- entityType: entityType(),- property,- apiValues: value,- }),- saveDate: (property: Property, date: Date) =>- saveMutation.mutateAsync({- entityId: props.entity.id,- entityType: entityType(),- property,- apiValues: {- valueType: 'DATE',- value: date,+ const saveOne = (property: Property, apiValues: PropertyApiValues) =>+ saveMutation.mutateAsync({+ properties: [+ {+ entityId: props.entity.id,+ entityType: entityType(),+ property,+ apiValues,},- }),+ ],+ });++ const saveHandler: PropertySaveHandler = {+ saveProperty: (property, value) => saveOne(property, value),+ saveDate: (property, date) =>+ saveOne(property, { valueType: 'DATE', value: date }),};return (diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.tsindex 0b6a7edf48..bd760b2fd2 100644--- a/js/app/packages/queries/properties/entity.ts+++ b/js/app/packages/queries/properties/entity.ts@@ -1,11 +1,7 @@import { toast } from '@core/component/Toast/Toast';-import {- PROPERTY_OPTION_IDS,- SYSTEM_PROPERTY_IDS,-} from '@core/component/Properties/constants';import { throwOnErr } from '@core/util/maybeResult';-import { type QueryKey, useMutation, useQuery } from '@tanstack/solid-query';-import type { Accessor } from 'solid-js';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { batch, type Accessor } from 'solid-js';import {entityPropertyFromApi,propertyValueToApi,@@ -13,12 +9,14 @@ import {import type {Property,PropertyApiValues,+ PropertyDefinitionDomain,} from '../../core/component/Properties/types';+import { isInstantiatedProperty } from '../../core/component/Properties/utils';import {type PropertiesEntityType,propertiesServiceClient,} from '../../service-clients/service-properties/client';-import { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';+import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';import type { SoupPropertyValue } from '../../service-clients/service-storage/generated/schemas/soupPropertyValue';import { queryClient } from '../client';import { type MutationCallbacks, withCallbacks } from '../utils';@@ -28,10 +26,7 @@ import {optimisticUpdateSoupEntity,invalidateSoupEntity,type SoupTransaction,- refetchSoupEntity,- type SoupEntityTag,} from '../soup/cache';-import { match, P } from 'ts-pattern';export function useEntityPropertiesQuery(entityType: Accessor<EntityType>,@@ -75,14 +70,40 @@ export function invalidatePropertiesForEntity(});}-export type SaveEntityPropertyParams = {- entityId: string;- entityType: EntityType;- property: Property;- apiValues: PropertyApiValues;-};+function getPropertyDefinitionId(+ property: Property | PropertyDefinitionDomain+): string {+ return isInstantiatedProperty(property)+ ? property.propertyDefinitionId+ : property.id;+}-type SaveEntityPropertyContext = SoupTransaction | undefined;+function optimisticUpdateSoupEntityProperty(+ entityId: string,+ propertyDefinitionId: string,+ value: SoupPropertyValue+): SoupTransaction | undefined {+ const current = getSoupEntityById(entityId);+ if (+ !current ||+ current.tag === 'channel' ||+ current.tag === 'callRecord' ||+ !current.data.properties+ ) {+ return undefined;+ }++ return optimisticUpdateSoupEntity({+ tag: current.tag,+ data: {+ ...current.data,+ properties: current.data.properties.map((prop) =>+ prop.definition.id === propertyDefinitionId ? { ...prop, value } : prop+ ),+ },+ frecency_score: current.frecency_score,+ });+}/*** Converts PropertyApiValues to the SoupProperty value format for optimistic updates.@@ -125,80 +146,6 @@ function apiValuesToSoupPropertyValue(}}-export function useSaveEntityPropertyMutation(- callbacks?: MutationCallbacks<- void,- Error,- SaveEntityPropertyParams,- SaveEntityPropertyContext- >-) {- return useMutation(() => ({- mutationFn: async (vars: SaveEntityPropertyParams) => {- const propertyValue = propertyValueToApi(- vars.apiValues,- vars.property.isMultiSelect- );-- await throwOnErr(- async () =>- await propertiesServiceClient.setEntityProperty({- entity_type: vars.entityType,- entity_id: vars.entityId,- property_id: vars.property.propertyDefinitionId,- body: {- value: propertyValue,- },- })- );- },- onMutate: async (- vars: SaveEntityPropertyParams- ): Promise<SaveEntityPropertyContext> => {- const current = getSoupEntityById(vars.entityId);- if (!current || current.tag === 'channel' || current.tag === 'callRecord')- return;-- const soupValue = apiValuesToSoupPropertyValue(vars.apiValues);- if (current.data.properties) {- return optimisticUpdateSoupEntity({- tag: current.tag,- data: {- ...current.data,- properties: current.data.properties.map((prop) =>- prop.definition.id === vars.property.propertyDefinitionId- ? { ...prop, value: soupValue }- : prop- ),- },- frecency_score: current.frecency_score,- });- }- },- onError: (- error: Error,- _vars: SaveEntityPropertyParams,- context: SaveEntityPropertyContext- ) => {- context?.rollback();- console.error('Failed to save property', error);- toast.failure('Failed to save property');- },- onSettled: (_data, _error, variables) => {- invalidatePropertiesForEntity(variables.entityType, variables.entityId);- invalidateSoupEntity(variables.entityId);- },- ...(callbacks- ? withCallbacks<- void,- Error,- SaveEntityPropertyParams,- SaveEntityPropertyContext- >({}, callbacks)- : {}),- }));-}-export type DeleteEntityPropertyParams = {entityPropertyId: string;entityType: EntityType;@@ -282,194 +229,27 @@ export type SetPropertyStatusCompleteParams = {entityId: string;};-type SetPropertyStatusCompleteContext = {- previousEntityProperties: [QueryKey, Property[] | undefined][];- soupTxn?: SoupTransaction;-};--/**- * Updates a property array to set the status property to COMPLETED.- * Works with both Property[] (from properties service) and SoupProperty[] (from DSS).- */-function updateStatusPropertyToCompleted<- T extends { propertyDefinitionId?: string; definition?: { id: string } },->(properties: T[]): T[] {- return properties.map((prop) => {- const propDefId =- 'propertyDefinitionId' in prop- ? prop.propertyDefinitionId- : prop.definition?.id;-- if (propDefId === SYSTEM_PROPERTY_IDS.STATUS) {- // Handle Property type (from properties service)- if ('valueType' in prop && prop.valueType === 'SELECT_STRING') {- return {- ...prop,- value: [PROPERTY_OPTION_IDS.STATUS.COMPLETED],- };- }- // Handle SoupProperty type (from DSS)- if ('value' in prop) {- return {- ...prop,- value: {- type: 'SelectOption' as const,- value: [PROPERTY_OPTION_IDS.STATUS.COMPLETED],- },- };- }- }- return prop;- });-}--function propertyEntityTypeToSoupTag(- entityType: EntityType-): SoupEntityTag | null {- return match(entityType)- .with(EntityType.CHANNEL, () => 'channel' as const)- .with(EntityType.THREAD, () => 'emailThread' as const)- .with(EntityType.CHAT, () => 'chat' as const)- .with(P.union(EntityType.COMPANY, EntityType.USER), () => null)- .with(- P.union(EntityType.DOCUMENT, EntityType.TASK),- () => 'document' as const- )- .with(EntityType.PROJECT, () => 'project' as const)- .exhaustive();-}--function withValidSoupTag(- entityType: EntityType,- callback: (tag: SoupEntityTag) => void-) {- const tag = propertyEntityTypeToSoupTag(entityType);- if (tag) {- callback(tag);- }-}--/** Sets the status property to complete for an entity (mark as done) */-export function useSetPropertyStatusCompleteMutation(- callbacks?: MutationCallbacks<- void,- Error,- SetPropertyStatusCompleteParams,- SetPropertyStatusCompleteContext- >-) {- return useMutation(() => ({- mutationFn: async (vars: SetPropertyStatusCompleteParams) => {- await throwOnErr(- async () =>- await propertiesServiceClient.setPropertyStatusComplete({- entity_type: vars.entityType,- entity_id: vars.entityId,- })- );- },- onMutate: async (- vars: SetPropertyStatusCompleteParams- ): Promise<SetPropertyStatusCompleteContext> => {- // Cancel any in-flight property queries- await Promise.all([- queryClient.cancelQueries({- queryKey: propertiesKeys.entity({- entityType: vars.entityType,- entityId: vars.entityId,- }).queryKey,- }),- ]);-- // Snapshot previous property data for rollback- const previousEntityProperties = queryClient.getQueriesData<Property[]>({- queryKey: propertiesKeys.entity({- entityType: vars.entityType,- entityId: vars.entityId,- }).queryKey,- });-- // Optimistically update entity properties query- queryClient.setQueriesData<Property[]>(- {- queryKey: propertiesKeys.entity({- entityType: vars.entityType,- entityId: vars.entityId,- }).queryKey,- },- (old) => (old ? updateStatusPropertyToCompleted(old) : old)- );-- // Optimistically update soup queries (embedded properties on entities)- const current = getSoupEntityById(vars.entityId);-- let soupTxn: SoupTransaction | undefined;- if (- current &&- current.tag !== 'channel' &&- current.tag !== 'callRecord' &&- current.data.properties- ) {- soupTxn = optimisticUpdateSoupEntity({- tag: current.tag,- data: {- ...current.data,- properties: updateStatusPropertyToCompleted(- current.data.properties- ),- },- frecency_score: current.frecency_score,- });- }-- return {- previousEntityProperties,- soupTxn,- };- },- onError: (- error: Error,- _vars: SetPropertyStatusCompleteParams,- context: SetPropertyStatusCompleteContext | undefined- ) => {- console.error('Failed to set status complete', error);-- if (context) {- context.soupTxn?.rollback();- for (const [key, data] of context.previousEntityProperties) {- queryClient.setQueryData(key, data);- }- }- },- onSettled: (_data, _error, variables) => {- invalidatePropertiesForEntity(variables.entityType, variables.entityId);- withValidSoupTag(variables.entityType, (tag) =>- refetchSoupEntity(variables.entityId, tag)- );- },- ...(callbacks- ? withCallbacks<- void,- Error,- SetPropertyStatusCompleteParams,- SetPropertyStatusCompleteContext- >({}, callbacks)- : {}),- }));-}-export type BulkSaveEntityPropertiesParams = {properties: Array<{entityId: string;entityType: EntityType;- property: { id: string; isMultiSelect: boolean };+ property: Property | PropertyDefinitionDomain;apiValues: PropertyApiValues;}>;};+type BulkSaveEntityPropertiesContext = {+ soupTxns: SoupTransaction[];+};+/** Saves multiple entity properties in bulk using parallel requests */export function useBulkSaveEntityPropertiesMutation(- callbacks?: MutationCallbacks<void, Error, BulkSaveEntityPropertiesParams>+ callbacks?: MutationCallbacks<+ void,+ Error,+ BulkSaveEntityPropertiesParams,+ BulkSaveEntityPropertiesContext+ >) {return useMutation(() => ({mutationFn: async (vars: BulkSaveEntityPropertiesParams) => {@@ -485,7 +265,7 @@ export function useBulkSaveEntityPropertiesMutation(await propertiesServiceClient.setEntityProperty({entity_type: item.entityType,entity_id: item.entityId,- property_id: item.property.id,+ property_id: getPropertyDefinitionId(item.property),body: {value: propertyValue,},@@ -494,9 +274,44 @@ export function useBulkSaveEntityPropertiesMutation(}));},- ...withCallbacks<void, Error, BulkSaveEntityPropertiesParams>(+ ...withCallbacks<+ void,+ Error,+ BulkSaveEntityPropertiesParams,+ BulkSaveEntityPropertiesContext+ >({- onError(error) {+ onMutate: (+ vars: BulkSaveEntityPropertiesParams+ ): BulkSaveEntityPropertiesContext => {+ const soupTxns = batch<SoupTransaction[]>(() => {+ const txns: SoupTransaction[] = [];+ for (const item of vars.properties) {+ const txn = optimisticUpdateSoupEntityProperty(+ item.entityId,+ getPropertyDefinitionId(item.property),+ apiValuesToSoupPropertyValue(item.apiValues)+ );+ if (txn) txns.push(txn);+ }+ return txns;+ });+ return { soupTxns };+ },+ onError(+ error: Error,+ _vars: BulkSaveEntityPropertiesParams,+ context: BulkSaveEntityPropertiesContext | undefined+ ) {+ // Reverse order: later transactions snapshotted state that already+ // included earlier updates, so they must unwind first.+ if (context?.soupTxns.length) {+ batch(() => {+ for (let i = context.soupTxns.length - 1; i >= 0; i--) {+ context.soupTxns[i].rollback();+ }+ });+ }console.error('Failed to bulk save properties', error);toast.failure('Failed to save properties');},@@ -505,24 +320,11 @@ export function useBulkSaveEntityPropertiesMutation(console.error('Failed bulk save properties', variables, error);toast.failure('Failed to save properties');}-- // Invalidate queries for all affected entities- const entityGroups = new Map<EntityType, Set<string>>();-- variables.properties.forEach((p) => {- if (!entityGroups.has(p.entityType)) {- entityGroups.set(p.entityType, new Set());+ batch(() => {+ for (const p of variables.properties) {+ invalidatePropertiesForEntity(p.entityType, p.entityId);+ invalidateSoupEntity(p.entityId);}- entityGroups.get(p.entityType)!.add(p.entityId);- });-- entityGroups.forEach((entityIds, entityType) => {- entityIds.forEach((entityId) => {- invalidatePropertiesForEntity(entityType, entityId);- withValidSoupTag(entityType, (tag) =>- refetchSoupEntity(entityId, tag)- );- });});},},