Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(tasks): update front end signal filter with task logic (#1138)

Seamusf6e95d3d793c
diff --git a/js/app/packages/app/component/Soup/utils/filterHelpers.ts b/js/app/packages/app/component/Soup/utils/filterHelpers.ts
index fa75828c5a..b32e9a6e15 100644
--- a/js/app/packages/app/component/Soup/utils/filterHelpers.ts
+++ b/js/app/packages/app/component/Soup/utils/filterHelpers.ts
@@ -1,3 +1,8 @@
+import {
+ PROPERTY_OPTION_IDS,
+ SYSTEM_PROPERTY_IDS,
+} from '@core/component/Properties/constants';
+import type { TaskEntityWithProperties } from '@macro-entity';
import type { ExpandedEntityType } from '@macro-entity';
import type { DocumentTypeFilter } from '../../ViewConfig';
@@ -63,3 +68,98 @@ export const isFocusFilterActive = (
const hasOpposite = focusFilters.includes(opposite);
return hasTarget && !hasOpposite;
};
+
+/**
+ * extracts assignee user ids from task properties.
+ */
+export const getTaskAssigneeIds = (
+ entity: TaskEntityWithProperties
+): string[] => {
+ const properties = entity.properties;
+ if (!properties) return [];
+ const assigneesProperty = properties.find(
+ (p) => p.definition.id === SYSTEM_PROPERTY_IDS.ASSIGNEES
+ );
+ if (!assigneesProperty?.value) return [];
+
+ const value = assigneesProperty.value;
+ if (value.type === 'EntityReference' && Array.isArray(value.value)) {
+ return value.value
+ .filter((ref) => ref.entity_type === 'USER')
+ .map((ref) => ref.entity_id);
+ }
+
+ return [];
+};
+
+/**
+ * gets the status option id from task properties.
+ */
+export const getTaskStatusOptionId = (
+ entity: TaskEntityWithProperties
+): string | undefined => {
+ const properties = entity.properties;
+ if (!properties) return undefined;
+
+ const statusProperty = properties.find(
+ (p) => p.definition.id === SYSTEM_PROPERTY_IDS.STATUS
+ );
+ if (!statusProperty?.value) return undefined;
+
+ const value = statusProperty.value;
+ if (
+ value.type === 'SelectOption' &&
+ 'value' in value &&
+ Array.isArray(value.value)
+ ) {
+ return value.value[0];
+ }
+
+ return undefined;
+};
+
+/**
+ * checks if a task is in a "closed" state (completed or canceled).
+ */
+export const isTaskClosed = (entity: TaskEntityWithProperties): boolean => {
+ if (entity.subType?.is_completed === true) {
+ return true;
+ }
+ const statusOptionId = getTaskStatusOptionId(entity);
+ if (
+ statusOptionId === PROPERTY_OPTION_IDS.STATUS.COMPLETED ||
+ statusOptionId === PROPERTY_OPTION_IDS.STATUS.CANCELED
+ ) {
+ return true;
+ }
+ return false;
+};
+
+/**
+ * checks if the current user is assigned to the task.
+ */
+export const isCurrentUserAssigned = (
+ entity: TaskEntityWithProperties,
+ currentUserId: string | undefined
+): boolean => {
+ if (!currentUserId) return false;
+ const assigneeIds = getTaskAssigneeIds(entity);
+ if (assigneeIds.length === 0) return true;
+ return assigneeIds.includes(currentUserId);
+};
+
+/**
+ * determines if a task should appear in the signal tab.
+ * tasks appear in signal if:
+ * - they are not completed or canceled
+ * - the current user is an assignee (or the task has no assignees)
+ */
+export const isSignalTask = (
+ entity: TaskEntityWithProperties,
+ currentUserId: string | undefined
+): boolean => {
+ if (isTaskClosed(entity)) {
+ return false;
+ }
+ return isCurrentUserAssigned(entity, currentUserId);
+};
diff --git a/js/app/packages/app/component/SoupContext.tsx b/js/app/packages/app/component/SoupContext.tsx
index 6d4f681a9a..c4f9a60190 100644
--- a/js/app/packages/app/component/SoupContext.tsx
+++ b/js/app/packages/app/component/SoupContext.tsx
@@ -15,7 +15,12 @@ import { isErr } from '@core/util/maybeResult';
import { getScrollParent } from '@core/util/scrollParent';
import { scrollToKeepGap } from '@core/util/scrollToKeepGap';
import { waitForFrames } from '@core/util/sleep';
-import { type EntityData, isSearchEntity, isTaskEntity } from '@macro-entity';
+import {
+ type EntityData,
+ isSearchEntity,
+ isTaskEntity,
+ type TaskEntityWithProperties,
+} from '@macro-entity';
import { entityHasUnreadNotifications } from '@notifications';
import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';
import type { PropertiesEntityType } from '@service-properties/client';
@@ -62,6 +67,10 @@ import {
} from './command/state';
import { useGlobalNotificationSource } from './GlobalAppState';
import { openEntityInSplitFromUnifiedList } from './soupContextHelpers';
+import {
+ isCurrentUserAssigned,
+ isTaskClosed,
+} from './Soup/utils/filterHelpers';
import type { SplitHandle } from './split-layout/layoutManager';
import { globalRemoveFromSplitHistory } from './split-layout/layoutUtils';
import {
@@ -525,7 +534,23 @@ export function createNavigationEntityListShortcut({
if (entity.type === 'email' || entity.type === 'channel') return true;
// property status complete (tasks have type 'document' with subType 'task')
- if (isTaskEntity(entity)) return true;
+ if (isTaskEntity(entity)) {
+ // Check if current user is assigned to the task
+ const currentUserId = userId();
+ if (
+ !isCurrentUserAssigned(
+ entity as TaskEntityWithProperties,
+ currentUserId
+ )
+ ) {
+ return false;
+ }
+ // Check if task is not already closed
+ if (isTaskClosed(entity as TaskEntityWithProperties)) {
+ return false;
+ }
+ return true;
+ }
if (['document', 'project'].includes(entity.type)) return true;
if (entityHasUnreadNotifications(notificationSource, entity)) {
@@ -554,9 +579,13 @@ export function createNavigationEntityListShortcut({
return true;
},
- canExecuteKeyDownHandler: () =>
- canAccessEntityList() &&
- actionRegistry.isActionEnabled('mark_as_done', plainSelectedEntities()),
+ canExecuteKeyDownHandler: () => {
+ if (!canAccessEntityList()) return false;
+ return actionRegistry.isActionEnabled(
+ 'mark_as_done',
+ plainSelectedEntities()
+ );
+ },
displayPriority: 10,
tags: [HotkeyTags.SelectionModification],
});
diff --git a/js/app/packages/app/component/ViewConfig.tsx b/js/app/packages/app/component/ViewConfig.tsx
index 8f4789c081..c871800f13 100644
--- a/js/app/packages/app/component/ViewConfig.tsx
+++ b/js/app/packages/app/component/ViewConfig.tsx
@@ -13,6 +13,7 @@ import type { DeepPartial } from '@core/util/withRequired';
import {
type EntityData,
type ExpandedEntityType,
+ isTaskEntity,
queryKeys,
type WithNotification,
} from '@macro-entity';
@@ -212,6 +213,9 @@ const ALL_VIEWCONFIG_DEFAULTS = {
optimisticallyExclude: true,
});
}
+ if (isTaskEntity(entity)) {
+ optimisticallyRemoveTaskFromSignal(entity.id);
+ }
if (extra?.notificationSource) {
console.log('marking notification as done');
markNotificationsForEntityAsDone(extra.notificationSource, entity);
@@ -454,6 +458,45 @@ export async function archiveEmail(
}
}
+/**
+ * Optimistically removes a task from the DSS queries (signal view).
+ * This is used when marking a task as done in the signal view to immediately
+ * remove it from the list before the query refetches.
+ */
+export async function optimisticallyRemoveTaskFromSignal(id: string) {
+ await queryClient.cancelQueries({ queryKey: queryKeys.all.dss });
+
+ const previousDss = queryClient.getQueriesData<{
+ pages: { items: (EntityData | { data: EntityData })[] }[];
+ }>({
+ queryKey: queryKeys.all.dss,
+ });
+
+ // Filter out the task with the given ID
+ for (const [key, data] of previousDss) {
+ if (!data) continue;
+
+ const updatedData = {
+ ...data,
+ pages: data.pages.map((page) => ({
+ ...page,
+ items: page.items.filter((item) => {
+ if ('data' in item) {
+ return item.data.id !== id;
+ }
+ return item.id !== id;
+ }),
+ })),
+ };
+
+ queryClient.setQueryData(key, updatedData);
+ }
+
+ // Note: We don't rollback on error since the mutation happens separately
+ // via setPropertyStatusCompleteMutation. The query invalidation will
+ // sync the state after the mutation completes.
+}
+
/**
* Normalizes an object by treating [], undefined, null, or missing properties as equivalent.
* Removes properties that are empty arrays, undefined, or null, and recursively processes nested objects.
diff --git a/js/app/packages/app/component/soupFilters.ts b/js/app/packages/app/component/soupFilters.ts
index 74cebfcf24..1e2fb7d33a 100644
--- a/js/app/packages/app/component/soupFilters.ts
+++ b/js/app/packages/app/component/soupFilters.ts
@@ -1,8 +1,14 @@
-import { type EntityData, isTaskEntity } from '@macro-entity';
+import { useUserId } from '@core/context/user';
+import {
+ type EntityData,
+ isTaskEntity,
+ type TaskEntityWithProperties,
+} from '@macro-entity';
import type { APIEmailThreadPreviewMetadata } from '@service-email/generated/schemas';
import type { SoupEmailThreadPreviewMetadata } from '@service-storage/generated/schemas';
import { makePersisted } from '@solid-primitives/storage';
import { createMemo, createSignal } from 'solid-js';
+import { isSignalTask } from './Soup/utils/filterHelpers';
import type { ClientFilter } from './ViewConfig';
type SignalConfig<T extends string> = {
@@ -253,6 +259,14 @@ const hasRecentlyViewed = (entity: EntityData) => {
return seconds < oneDayOfSeconds;
};
+const getCurrentUserId = () => {
+ try {
+ return useUserId()();
+ } catch {
+ return undefined;
+ }
+};
+
export const signalFilter: ClientFilter = {
id: 'signal',
predicate: (entity, _ctx) => {
@@ -265,8 +279,11 @@ export const signalFilter: ClientFilter = {
}
case 'document': {
if (isTaskEntity(entity)) {
- // TODO (seamus) : filter on isCompleted
- return true;
+ const currentUserId = getCurrentUserId();
+ return isSignalTask(
+ entity as TaskEntityWithProperties,
+ currentUserId
+ );
}
return hasRecentlyViewed(entity);
}
diff --git a/js/app/packages/macro-entity/src/types/entity.ts b/js/app/packages/macro-entity/src/types/entity.ts
index 3dad8e5bfe..993c7f2a73 100644
--- a/js/app/packages/macro-entity/src/types/entity.ts
+++ b/js/app/packages/macro-entity/src/types/entity.ts
@@ -6,6 +6,7 @@ import type {
import type {
SoupEmailThreadPreviewMetadata,
SoupLabel,
+ SoupProperty,
} from '@service-storage/generated/schemas';
import type { JSX } from 'solid-js';
@@ -133,6 +134,12 @@ export type EntityType = EntityData['type'];
export type ExpandedEntityType = EntityType | 'task';
+export type EntityWithProperties<T extends EntityData> = T & {
+ properties?: SoupProperty[];
+};
+
+export type TaskEntityWithProperties = EntityWithProperties<TaskEntity>;
+
export type EntityOf<K extends EntityType> = Extract<EntityData, { type: K }>;
export type EntityMapper<T extends EntityData> = (entity: EntityData) => T;
diff --git a/js/app/packages/macro-entity/src/utils/filter.ts b/js/app/packages/macro-entity/src/utils/filter.ts
index be15116180..2c0bbec692 100644
--- a/js/app/packages/macro-entity/src/utils/filter.ts
+++ b/js/app/packages/macro-entity/src/utils/filter.ts
@@ -3,6 +3,7 @@ import {
type EntityData,
type EntityFilter,
getEntityProjectId,
+ isTaskEntity,
} from '../types/entity';
import type { WithNotification } from '../types/notification';
@@ -43,6 +44,8 @@ export function importantFilterFn(entity: WithNotification<EntityData>) {
export function notDoneFilterFn(entity: WithNotification<EntityData>) {
if (entity.type === 'email') return !entity.done;
+ // Tasks are handled by signalFilter based on assignee/status, not notifications
+ if (isTaskEntity(entity)) return true;
return (
!!entity.notifications && entity.notifications().some(({ done }) => !done)
);
diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.ts
index 8448b7a5bd..fd521ca74a 100644
--- a/js/app/packages/queries/properties/entity.ts
+++ b/js/app/packages/queries/properties/entity.ts
@@ -1,6 +1,15 @@
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 InfiniteData,
+ type QueryKey,
+ useMutation,
+ useQuery,
+} from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import {
entityPropertyFromApi,
@@ -15,9 +24,13 @@ import {
propertiesServiceClient,
} from '../../service-clients/service-properties/client';
import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';
+import type { SoupPage } from '../../service-clients/service-storage/generated/schemas/soupPage';
+import type { SoupProperty } from '../../service-clients/service-storage/generated/schemas/soupProperty';
import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { propertiesKeys } from './keys';
+import { queryKeys } from '../../macro-entity/src/queries/key';
+import type { BulkEntityPropertiesData } from './bulk';
export function useEntityPropertiesQuery(
entityType: Accessor<EntityType>,
@@ -116,6 +129,15 @@ export function useSaveEntityPropertyMutation(
variables.entityType,
variables.entityId
);
+
+ // If the status property was changed, also invalidate DSS
+ // so that tasks can reappear in Signal when marked un-done
+ if (
+ variables.property.propertyDefinitionId ===
+ SYSTEM_PROPERTY_IDS.STATUS
+ ) {
+ queryClient.invalidateQueries({ queryKey: queryKeys.all.dss });
+ }
},
},
callbacks
@@ -206,9 +228,95 @@ export type SetPropertyStatusCompleteParams = {
entityId: string;
};
+type SetPropertyStatusCompleteContext = {
+ previousEntityProperties: [QueryKey, Property[] | undefined][];
+ previousBulkProperties: [QueryKey, BulkEntityPropertiesData | undefined][];
+ previousDss: [QueryKey, InfiniteData<SoupPage, unknown> | undefined][];
+};
+
+/**
+ * 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;
+ });
+}
+
+/**
+ * Updates DSS query data to set the status property to COMPLETED for a given entity.
+ */
+function updateDssStatusToCompleted(
+ data: InfiniteData<SoupPage, unknown> | undefined,
+ entityId: string
+): InfiniteData<SoupPage, unknown> | undefined {
+ if (!data) return data;
+
+ return {
+ ...data,
+ pages: data.pages.map((page) => ({
+ ...page,
+ items: page.items.map((item) => {
+ // SoupApiItem has { tag, data } structure where data contains the entity
+ if ('data' in item && item.data && 'id' in item.data) {
+ const itemData = item.data as {
+ id: string;
+ properties?: SoupProperty[];
+ };
+ if (itemData.id === entityId && itemData.properties) {
+ // Use Object.assign to preserve the original type while updating properties
+ const updatedData = {
+ ...item.data,
+ properties: updateStatusPropertyToCompleted(itemData.properties),
+ };
+ return {
+ ...item,
+ data: updatedData,
+ } as typeof item;
+ }
+ }
+ return item;
+ }),
+ })),
+ pageParams: data.pageParams,
+ };
+}
+
/** Sets the status property to complete for an entity (mark as done) */
export function useSetPropertyStatusCompleteMutation(
- callbacks?: MutationCallbacks<void, Error, SetPropertyStatusCompleteParams>
+ callbacks?: MutationCallbacks<
+ void,
+ Error,
+ SetPropertyStatusCompleteParams,
+ SetPropertyStatusCompleteContext
+ >
) {
return useMutation(() => ({
mutationFn: async (vars: SetPropertyStatusCompleteParams) => {
@@ -220,19 +328,116 @@ export function useSetPropertyStatusCompleteMutation(
})
);
},
- ...withCallbacks<void, Error, SetPropertyStatusCompleteParams>(
- {
- onError(error) {
- console.error('Failed to set status complete', error);
+ onMutate: async (
+ vars: SetPropertyStatusCompleteParams
+ ): Promise<SetPropertyStatusCompleteContext> => {
+ // Cancel any in-flight queries that might overwrite our optimistic update
+ await Promise.all([
+ queryClient.cancelQueries({
+ queryKey: propertiesKeys.entity({
+ entityType: vars.entityType,
+ entityId: vars.entityId,
+ }).queryKey,
+ }),
+ queryClient.cancelQueries({
+ predicate: ({ queryKey }) =>
+ bulkIncludesEntityPredicate(queryKey, vars.entityId),
+ }),
+ queryClient.cancelQueries({ queryKey: queryKeys.all.dss }),
+ ]);
+
+ // Snapshot previous data for rollback
+ const previousEntityProperties = queryClient.getQueriesData<Property[]>({
+ queryKey: propertiesKeys.entity({
+ entityType: vars.entityType,
+ entityId: vars.entityId,
+ }).queryKey,
+ });
+
+ const previousBulkProperties =
+ queryClient.getQueriesData<BulkEntityPropertiesData>({
+ predicate: ({ queryKey }) =>
+ bulkIncludesEntityPredicate(queryKey, vars.entityId),
+ });
+
+ const previousDss = queryClient.getQueriesData<
+ InfiniteData<SoupPage, unknown>
+ >({
+ queryKey: queryKeys.all.dss,
+ });
+
+ // Optimistically update entity properties query
+ queryClient.setQueriesData<Property[]>(
+ {
+ queryKey: propertiesKeys.entity({
+ entityType: vars.entityType,
+ entityId: vars.entityId,
+ }).queryKey,
},
- onSettled: (_data, _error, variables) => {
- invalidatePropertiesForEntity(
- variables.entityType,
- variables.entityId
- );
+ (old) => (old ? updateStatusPropertyToCompleted(old) : old)
+ );
+
+ // Optimistically update bulk properties queries
+ queryClient.setQueriesData<BulkEntityPropertiesData>(
+ {
+ predicate: ({ queryKey }) =>
+ bulkIncludesEntityPredicate(queryKey, vars.entityId),
},
- },
- callbacks
- ),
+ (old) => {
+ if (!old || !old[vars.entityId]) return old;
+ return {
+ ...old,
+ [vars.entityId]: updateStatusPropertyToCompleted(
+ old[vars.entityId]
+ ),
+ };
+ }
+ );
+
+ // Optimistically update DSS queries (embedded properties on entities)
+ queryClient.setQueriesData<InfiniteData<SoupPage, unknown>>(
+ { queryKey: queryKeys.all.dss },
+ (old) => updateDssStatusToCompleted(old, vars.entityId)
+ );
+
+ return {
+ previousEntityProperties,
+ previousBulkProperties,
+ previousDss,
+ };
+ },
+ onError: (
+ error: Error,
+ _vars: SetPropertyStatusCompleteParams,
+ context: SetPropertyStatusCompleteContext | undefined
+ ) => {
+ console.error('Failed to set status complete', error);
+
+ // Rollback optimistic updates
+ if (context) {
+ for (const [key, data] of context.previousEntityProperties) {
+ queryClient.setQueryData(key, data);
+ }
+ for (const [key, data] of context.previousBulkProperties) {
+ queryClient.setQueryData(key, data);
+ }
+ for (const [key, data] of context.previousDss) {
+ queryClient.setQueryData(key, data);
+ }
+ }
+ },
+ onSettled: (_data, _error, variables) => {
+ invalidatePropertiesForEntity(variables.entityType, variables.entityId);
+ // Also invalidate DSS to ensure consistency
+ queryClient.invalidateQueries({ queryKey: queryKeys.all.dss });
+ },
+ ...(callbacks
+ ? withCallbacks<
+ void,
+ Error,
+ SetPropertyStatusCompleteParams,
+ SetPropertyStatusCompleteContext
+ >({}, callbacks)
+ : {}),
}));
}