Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(properties): use task properties (#762)
teo744a618ed7c0
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsxindex 68f4552417..e1067d3051 100644--- a/js/app/packages/app/component/UnifiedListView.tsx+++ b/js/app/packages/app/component/UnifiedListView.tsx@@ -253,7 +253,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {} = unifiedListContext;// Properties for task entities- const [taskPropertiesStore] = useTaskProperties(entities_);+ const taskPropertiesStore = useTaskProperties(entities_);const view = createMemo(() => viewsData[selectedView()]);const selectedEntity = createMemo(() => view()?.selectedEntity);@@ -1694,6 +1694,14 @@ export function UnifiedListView(props: UnifiedListViewProps) {return innerProps.entity.updatedAt;}};++ const properties = () => {+ if (isTaskEntity(innerProps.entity)) {+ return taskPropertiesStore()[innerProps.entity.id] ?? [];+ }+ return undefined;+ };+return (<EntityRowentityId={innerProps.entity.id}@@ -1716,11 +1724,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {});}}entity={innerProps.entity}- properties={- isTaskEntity(innerProps.entity)- ? taskPropertiesStore[innerProps.entity.id]- : undefined- }+ properties={properties()}timestamp={timestamp()}onClick={entityClickHandler}onClickRowAction={diff --git a/js/app/packages/core/component/Properties/api/fetchProperties.ts b/js/app/packages/core/component/Properties/api/fetchProperties.tsindex 7e145476ae..efff3de331 100644--- a/js/app/packages/core/component/Properties/api/fetchProperties.ts+++ b/js/app/packages/core/component/Properties/api/fetchProperties.ts@@ -1,41 +1,10 @@import { isErr } from '@core/util/maybeResult';-import { queryClient } from '@queries/client';import { propertiesServiceClient } from '@service-properties/client';-import type { EntityReference } from '@service-properties/generated/schemas/entityReference';import type { EntityType } from '@service-properties/generated/schemas/entityType';import type { Property, Result } from '../types';import { ERROR_MESSAGES } from '../utils/errorHandling';import { entityPropertyFromApi } from './converters';-/**- * Query keys for properties cache.- *- * Cache is keyed by (entity + propertyDefinitionIds set) rather than per individual property.- * This is simpler and sufficient because:- * 1. Our main consumer (useTaskProperties) always requests the same fixed set of properties- * 2. Per-property caching wouldn't save API calls anyway - if any property is missing,- * we'd still need to fetch all requested properties for that entity- */-export const propertyQueryKeys = {- all: ['properties'] as const,- entity: (- entityType: EntityType,- entityId: string,- propertyDefinitionIds?: string[]- ) =>- [- ...propertyQueryKeys.all,- 'entity',- entityType,- entityId,- propertyDefinitionIds?.sort(),- ] as const,-};--/**- * Fetch all properties for an entity.- * Returns a Result type for backward compatibility with existing hooks.- */export async function fetchEntityProperties(entityId: string,entityType: EntityType,@@ -84,80 +53,3 @@ export async function fetchEntityProperties(};}}--/**- * Fetch properties for multiple entities in bulk.- * Uses TanStack Query cache - only fetches entities not already cached.- *- * Note: This is not standard TanStack Query usage (normally you'd use useQuery/useQueries).- * We use queryClient manually because we need bulk fetching (1 API call for N entities)- * rather than N individual queries. Using TanStack as a cache layer is fine for this use case.- *- * @param entities - Array of entity references to fetch properties for- * @param propertyDefinitionIds - Property definition IDs to fetch (required for cache correctness)- */-export async function fetchBulkEntityProperties(- entities: EntityReference[],- propertyDefinitionIds: string[]-): Promise<Map<string, Property[]>> {- if (entities.length === 0) {- return new Map();- }-- const result = new Map<string, Property[]>();- const entitiesToFetch: EntityReference[] = [];-- // Check cache for each entity- for (const entity of entities) {- const queryKey = propertyQueryKeys.entity(- entity.entity_type,- entity.entity_id,- propertyDefinitionIds- );- const cached = queryClient.getQueryData<Property[]>(queryKey);-- if (cached) {- result.set(entity.entity_id, cached);- } else {- entitiesToFetch.push(entity);- }- }-- // Fetch only uncached entities- if (entitiesToFetch.length > 0) {- const fetchResult = await propertiesServiceClient.getBulkEntityProperties({- body: { entities: entitiesToFetch, property_ids: propertyDefinitionIds },- });-- if (isErr(fetchResult)) {- console.error(- 'api.properties.fetchBulkEntityProperties:',- fetchResult,- ERROR_MESSAGES.PROPERTY_FETCH- );- // Return what we have from cache, don't throw- return result;- }-- const [, data] = fetchResult;-- // Update cache and result for each fetched entity- for (const [entityId, response] of Object.entries(data)) {- const properties = response.properties.map(entityPropertyFromApi);- const entity = entitiesToFetch.find((e) => e.entity_id === entityId);-- if (entity) {- const queryKey = propertyQueryKeys.entity(- entity.entity_type,- entity.entity_id,- propertyDefinitionIds- );- queryClient.setQueryData(queryKey, properties);- }-- result.set(entityId, properties);- }- }-- return result;-}diff --git a/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts b/js/app/packages/core/component/Properties/hooks/useTaskProperties.tsindex 54932e1d64..2232f3e65e 100644--- a/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts+++ b/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts@@ -1,6 +1,5 @@-import { createEffect } from 'solid-js';-import { createStore, type SetStoreFunction } from 'solid-js/store';-import { fetchBulkEntityProperties } from '../api/fetchProperties';+import { useBulkEntityPropertiesQuery } from '@queries/properties/bulk';+import { createMemo } from 'solid-js';import { SYSTEM_PROPERTY_IDS } from '../constants';import type { Property } from '../types';@@ -18,46 +17,28 @@ const TASK_PROPERTY_DEFINITION_IDS = [SYSTEM_PROPERTY_IDS.PRIORITY,];-function isTaskEntity(entity: Entity): boolean {+function isTaskEntity(+ entity: Entity+): entity is Entity & { type: 'document'; subType: 'task' } {return entity.type === 'document' && entity.subType === 'task';}-/**- * Hook to fetch and cache properties for task entities.- * Returns a store where keys are entity IDs and values are property arrays.- *- * Uses TanStack Query cache internally - properties are cached per entity- * and won't be refetched if already in cache.- *- * @param entities - Accessor for the list of entities to fetch properties for- */export function useTaskProperties(entities: () => Entity[] | undefined-): [TaskPropertiesStore, SetStoreFunction<TaskPropertiesStore>] {- const [store, setStore] = createStore<TaskPropertiesStore>({});-- createEffect(() => {- const allEntities = entities();- if (!allEntities?.length) return;-+): () => TaskPropertiesStore {+ const taskEntityRefs = createMemo(() => {+ const allEntities = entities() ?? [];const taskEntities = allEntities.filter(isTaskEntity);- if (taskEntities.length === 0) return;-- const entityRefs = taskEntities.map((e) => ({+ return taskEntities.map((e) => ({entity_id: e.id,entity_type: 'TASK' as const,}));-- fetchBulkEntityProperties(entityRefs, TASK_PROPERTY_DEFINITION_IDS).then(- (result) => {- for (const [id, props] of result) {- if (!(id in store)) {- setStore(id, props);- }- }- }- );});- return [store, setStore];+ const query = useBulkEntityPropertiesQuery(+ taskEntityRefs,+ TASK_PROPERTY_DEFINITION_IDS+ );++ return () => query.data ?? {};}diff --git a/js/app/packages/core/util/compareUtils.ts b/js/app/packages/core/util/compareUtils.tsindex ad4bb3ce4d..e1f1dbe529 100644--- a/js/app/packages/core/util/compareUtils.ts+++ b/js/app/packages/core/util/compareUtils.ts@@ -1,20 +1,16 @@export function setEquals<T>(a: Set<T>, b: Set<T>): boolean {if (a.size !== b.size) return false;-for (const item of a.values()) {if (!b.has(item)) return false;}-return true;}export function arrayEquals<T extends ArrayLike<any>>(a: T, b: T): boolean {if (a.length !== b.length) return false;-for (let i = 0; i < a.length; i++) {if (a[i] !== b[i]) return false;}-return true;}@@ -23,16 +19,12 @@ export function mergeByKey<T extends Record<string, any>, K extends keyof T>(...lists: T[][]): T[] {const map = new Map<T[K], T>();-for (const list of lists) {for (const item of list) {const id = item[key];- if (!map.has(id)) {- map.set(id, item);- }+ if (!map.has(id)) map.set(id, item);}}-return Array.from(map.values());}@@ -44,10 +36,29 @@ export function mapFromListsByKey<T extends Record<string, any>>(for (const list of lists) {for (const item of list) {const id = extractor(item);- if (!map.has(id)) {- map.set(id, item);- }+ if (!map.has(id)) map.set(id, item);}}return map;}++export function uniqueByKey<T>(+ items: readonly T[],+ keyOf: (item: T) => string+): T[] {+ const map = new Map<string, T>();+ for (const item of items) {+ const key = keyOf(item);+ if (!map.has(key)) map.set(key, item);+ }+ return [...map.values()];+}++export function uniqueByKeySorted<T>(+ items: readonly T[],+ keyOf: (item: T) => string+): T[] {+ return uniqueByKey(items, keyOf).toSorted((a, b) =>+ keyOf(a).localeCompare(keyOf(b))+ );+}diff --git a/js/app/packages/queries/cache.test.ts b/js/app/packages/queries/cache.test.tsnew file mode 100644index 0000000000..901bc4846a--- /dev/null+++ b/js/app/packages/queries/cache.test.ts@@ -0,0 +1,100 @@+import { QueryClient } from '@tanstack/solid-query';+import { describe, expect, it } from 'vitest';+import { partitionByQueryCache } from './cache';++type EntityRef = { entity_id: string; entity_type: string };++const entityQueryKey = (entity: EntityRef) =>+ ['properties', 'entity', entity.entity_type, entity.entity_id] as const;++describe('partitionByQueryCache', () => {+ it('returns all items as missing when cache is empty', () => {+ const queryClient = new QueryClient();+ const entities: EntityRef[] = [+ { entity_id: 'A', entity_type: 'TASK' },+ { entity_id: 'B', entity_type: 'TASK' },+ { entity_id: 'C', entity_type: 'TASK' },+ ];++ const { cached, missing } = partitionByQueryCache<EntityRef, string[]>({+ queryClient,+ items: entities,+ queryKeyOf: entityQueryKey,+ });++ expect(cached.size).toBe(0);+ expect(missing).toEqual(entities);+ });++ it('returns all items as cached when all are in cache', () => {+ const queryClient = new QueryClient();+ const entities: EntityRef[] = [+ { entity_id: 'A', entity_type: 'TASK' },+ { entity_id: 'B', entity_type: 'TASK' },+ { entity_id: 'C', entity_type: 'TASK' },+ ];++ for (const entity of entities) {+ queryClient.setQueryData(entityQueryKey(entity), [+ `data-${entity.entity_id}`,+ ]);+ }++ const { cached, missing } = partitionByQueryCache<EntityRef, string[]>({+ queryClient,+ items: entities,+ queryKeyOf: entityQueryKey,+ });++ expect(missing).toEqual([]);+ expect(cached.size).toBe(3);+ expect(cached.get(entities[0])).toEqual(['data-A']);+ expect(cached.get(entities[1])).toEqual(['data-B']);+ expect(cached.get(entities[2])).toEqual(['data-C']);+ });++ it('only returns uncached items as missing when some are cached', () => {+ const queryClient = new QueryClient();+ const entitiesABC: EntityRef[] = [+ { entity_id: 'A', entity_type: 'TASK' },+ { entity_id: 'B', entity_type: 'TASK' },+ { entity_id: 'C', entity_type: 'TASK' },+ ];++ // Cache A, B, C+ for (const entity of entitiesABC) {+ queryClient.setQueryData(entityQueryKey(entity), [+ `data-${entity.entity_id}`,+ ]);+ }++ // Now request A, B, C, D - only D should be missing+ const entityD: EntityRef = { entity_id: 'D', entity_type: 'TASK' };+ const entitiesABCD = [...entitiesABC, entityD];++ const { cached, missing } = partitionByQueryCache<EntityRef, string[]>({+ queryClient,+ items: entitiesABCD,+ queryKeyOf: entityQueryKey,+ });++ expect(missing).toEqual([entityD]);+ expect(cached.size).toBe(3);+ expect(cached.get(entitiesABC[0])).toEqual(['data-A']);+ expect(cached.get(entitiesABC[1])).toEqual(['data-B']);+ expect(cached.get(entitiesABC[2])).toEqual(['data-C']);+ });++ it('handles empty items array', () => {+ const queryClient = new QueryClient();++ const { cached, missing } = partitionByQueryCache<EntityRef, string[]>({+ queryClient,+ items: [],+ queryKeyOf: entityQueryKey,+ });++ expect(cached.size).toBe(0);+ expect(missing).toEqual([]);+ });+});diff --git a/js/app/packages/queries/cache.ts b/js/app/packages/queries/cache.tsnew file mode 100644index 0000000000..199a2a81bf--- /dev/null+++ b/js/app/packages/queries/cache.ts@@ -0,0 +1,24 @@+import type { QueryClient } from '@tanstack/solid-query';++export type CachePartition<Item, Data> = {+ readonly cached: ReadonlyMap<Item, Data>;+ readonly missing: readonly Item[];+};++export function partitionByQueryCache<Item, Data>(args: {+ readonly queryClient: QueryClient;+ readonly items: readonly Item[];+ readonly queryKeyOf: (item: Item) => readonly unknown[];+}): CachePartition<Item, Data> {+ const cached = new Map<Item, Data>();+ const missing: Item[] = [];++ for (const item of args.items) {+ const key = args.queryKeyOf(item);+ const data = args.queryClient.getQueryData<Data>(key);+ if (data !== undefined) cached.set(item, data);+ else missing.push(item);+ }++ return { cached, missing };+}diff --git a/js/app/packages/queries/properties/bulk.ts b/js/app/packages/queries/properties/bulk.tsnew file mode 100644index 0000000000..ca40760860--- /dev/null+++ b/js/app/packages/queries/properties/bulk.ts@@ -0,0 +1,132 @@+import type { UseBaseQueryOptions } from '@tanstack/solid-query';+import { useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { entityPropertyFromApi } from '../../core/component/Properties/api/converters';+import type { Property } from '../../core/component/Properties/types';+import { isErr } from '../../core/util/maybeResult';+import { propertiesServiceClient } from '../../service-clients/service-properties/client';+import type { EntityReference } from '../../service-clients/service-properties/generated/schemas/entityReference';+import { partitionByQueryCache } from '../cache';+import { queryClient } from '../client';+import { propertiesKeys } from './keys';++export type BulkEntityPropertiesData = Record<string, Property[]>;++type BulkEntityPropertiesQueryOptions = UseBaseQueryOptions<+ BulkEntityPropertiesData,+ Error+>;++type BulkEntityPropertiesParams = {+ readonly entities: readonly EntityReference[];+ readonly propertyDefinitionIds: readonly string[];+};++const entityPropertiesKey = (+ entity: EntityReference,+ propertyDefinitionIds: readonly string[]+) =>+ propertiesKeys.entity({+ entityType: entity.entity_type,+ entityId: entity.entity_id,+ propertyDefinitionIds,+ }).queryKey;++async function fetchBulkWithCachePartition(+ params: BulkEntityPropertiesParams+): Promise<BulkEntityPropertiesData> {+ if (params.entities.length === 0) return {};++ const { cached, missing } = partitionByQueryCache<+ EntityReference,+ Property[]+ >({+ queryClient,+ items: params.entities,+ queryKeyOf: (entity) =>+ entityPropertiesKey(entity, params.propertyDefinitionIds),+ });++ const out: BulkEntityPropertiesData = {};+ for (const [entity, properties] of cached.entries()) {+ out[entity.entity_id] = properties;+ }++ if (missing.length === 0) return out;++ const result = await propertiesServiceClient.getBulkEntityProperties({+ body: {+ entities: [...missing],+ property_ids: [...params.propertyDefinitionIds],+ },+ });++ if (isErr(result)) {+ throw new Error('Failed to fetch entity properties', { cause: result[0] });+ }++ const [, data] = result;+ for (const entity of missing) {+ const response = data[entity.entity_id];+ if (!response) {+ out[entity.entity_id] = [];+ continue;+ }++ const properties = response.properties.map(entityPropertyFromApi);+ queryClient.setQueryData(+ entityPropertiesKey(entity, params.propertyDefinitionIds),+ properties+ );+ out[entity.entity_id] = properties;+ }++ return out;+}++function bulkEntityPropertiesQueryOptions(+ params: BulkEntityPropertiesParams+): BulkEntityPropertiesQueryOptions {+ return {+ queryKey: propertiesKeys.bulk({+ entities: params.entities,+ propertyDefinitionIds: params.propertyDefinitionIds,+ }).queryKey,+ queryFn: () => fetchBulkWithCachePartition(params),+ };+}++export function useBulkEntityPropertiesQuery(+ entities: Accessor<readonly EntityReference[]>,+ propertyDefinitionIds: readonly string[],+ options?: Accessor<+ Omit<+ BulkEntityPropertiesQueryOptions,+ 'queryKey' | 'queryFn' | 'initialData'+ >+ >+) {+ return useQuery(+ () => {+ const currentEntities = entities();+ const placeholder: BulkEntityPropertiesData = {};+ for (const entity of currentEntities) {+ const cached = queryClient.getQueryData<Property[]>(+ entityPropertiesKey(entity, propertyDefinitionIds)+ );+ placeholder[entity.entity_id] = cached ?? [];+ }+ return {+ initialData: placeholder,+ staleTime: 0,+ enabled: currentEntities.length > 0,+ ...options?.(),+ ...bulkEntityPropertiesQueryOptions({+ entities: currentEntities,+ propertyDefinitionIds,+ }),+ };+ },+ () => queryClient+ );+}diff --git a/js/app/packages/queries/properties/keys.ts b/js/app/packages/queries/properties/keys.tsnew file mode 100644index 0000000000..c5e9e80272--- /dev/null+++ b/js/app/packages/queries/properties/keys.ts@@ -0,0 +1,43 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';+import { uniqueByKeySorted } from '../../core/util/compareUtils';+import type { EntityReference } from '../../service-clients/service-properties/generated/schemas/entityReference';+import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';++const normalizeStringIds = (ids: readonly string[]) => [...new Set(ids)].sort();++const entityRefKey = (e: EntityReference) => `${e.entity_type}:${e.entity_id}`;++const normalizeEntities = (entities: readonly EntityReference[]) =>+ uniqueByKeySorted(entities, entityRefKey);++export const propertiesKeys = createQueryKeys('properties', {+ all: null,++ entity: (params: {+ entityType: EntityType;+ entityId: string;+ propertyDefinitionIds?: readonly string[] | undefined;+ }) => ({+ queryKey: [+ 'entity',+ params.entityType,+ params.entityId,+ params.propertyDefinitionIds+ ? normalizeStringIds(params.propertyDefinitionIds)+ : undefined,+ ],+ }),++ bulk: (params: {+ entities: readonly EntityReference[];+ propertyDefinitionIds: readonly string[];+ }) => ({+ queryKey: [+ 'bulk',+ {+ entities: normalizeEntities(params.entities),+ propertyDefinitionIds: normalizeStringIds(params.propertyDefinitionIds),+ },+ ],+ }),+});diff --git a/js/app/packages/queries/tsconfig.json b/js/app/packages/queries/tsconfig.jsonnew file mode 100644index 0000000000..8c7c83e293--- /dev/null+++ b/js/app/packages/queries/tsconfig.json@@ -0,0 +1,11 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "jsx": "preserve",+ "jsxImportSource": "solid-js",+ "composite": true,+ "isolatedModules": true,+ "skipLibCheck": true,+ "moduleResolution": "bundler"+ }+}