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
import type { Property, PropertyDefinitionDomain } from '@property/types';
import { EntityPropertiesDocument } from '@service-storage/graphql/generated/graphql';
import { validate as validateUuid } from 'uuid';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const executeOptimisticMutationMock = vi.hoisted(() => vi.fn());
const optimisticMutationDispositionOfMock = vi.hoisted(() => vi.fn());
const inspectMock = vi.hoisted(() => vi.fn());
const cacheHostState = vi.hoisted(() => ({ current: {} as unknown }));
vi.mock('@graphql-cache/index', async (importOriginal) => {
const actual = await importOriginal<typeof import('@graphql-cache/index')>();
return {
...actual,
executeOptimisticMutation: executeOptimisticMutationMock,
optimisticMutationDispositionOf: optimisticMutationDispositionOfMock,
inspect: inspectMock,
};
});
vi.mock('@service-storage/graphql-soup', () => ({
getGraphqlSoupClient: () => ({}),
getGraphqlCacheHost: () => cacheHostState.current,
}));
vi.mock('./entity', async (importOriginal) => ({
buildEntityPropertiesInput: (
await importOriginal<typeof import('./entity')>()
).buildEntityPropertiesInput,
toGraphqlPropertyTargetEntityType: (entityType: string) =>
entityType === 'TASK' ? 'DOCUMENT' : entityType,
}));
import { updateGraphqlEntityPropertyOptions } from './entity-options';
const tagDefinition = {
id: 'tag-def',
displayName: 'Tags',
valueType: 'TAG',
isMultiSelect: true,
isSystem: false,
isMetadata: false,
} as unknown as PropertyDefinitionDomain;
const tagProperty = {
propertyId: 'assignment-1',
propertyDefinitionId: 'tag-def',
displayName: 'Tags',
valueType: 'TAG',
isMultiSelect: true,
isSystemProperty: false,
isMetadata: false,
} as unknown as Property;
function committedWith(optionIds: string[]) {
return {
kind: 'committed' as const,
data: {
updateEntityPropertyOptions: [
{
propertyDefinitionId: 'tag-def',
value: {
__typename: 'GraphqlSelectOptionPropertyValue',
optionIds,
},
},
],
},
};
}
function optimisticArgs() {
const call = executeOptimisticMutationMock.mock.calls[0];
if (!call) throw new Error('mutation was never executed');
return { variables: call[2], optimisticData: call[3], options: call[4] };
}
describe('updateGraphqlEntityPropertyOptions', () => {
beforeEach(() => {
vi.clearAllMocks();
cacheHostState.current = {};
inspectMock.mockRejectedValue(
new Error('query inspection variant count 129 exceeds limit 128')
);
executeOptimisticMutationMock.mockReturnValue({
toPromise: () => Promise.resolve({ data: undefined, error: undefined }),
});
optimisticMutationDispositionOfMock.mockReturnValue(
committedWith(['spotlight'])
);
});
it('sends option deltas and writes the property record optimistically', async () => {
await expect(
updateGraphqlEntityPropertyOptions({
entityType: 'DOCUMENT',
entityId: 'doc-1',
properties: [
{
property: tagProperty,
currentOptionIds: ['stale'],
nextOptionIds: ['spotlight'],
},
],
})
).resolves.toEqual([
{ propertyDefinitionId: 'tag-def', optionIds: ['spotlight'] },
]);
const { variables, optimisticData, options } = optimisticArgs();
expect(variables).toEqual({
input: {
entityType: 'DOCUMENT',
entityId: 'doc-1',
properties: [
{
propertyDefinitionId: 'tag-def',
addOptionIds: ['spotlight'],
removeOptionIds: ['stale'],
},
],
},
});
expect(optimisticData.updateEntityPropertyOptions).toMatchObject([
{
id: 'assignment-1',
propertyDefinitionId: 'tag-def',
value: {
__typename: 'GraphqlSelectOptionPropertyValue',
optionIds: ['spotlight'],
},
},
]);
// The response may replace an assignment that this client still has cached.
expect(options.updates).toMatchObject([
{
recordRoot: { entityKey: 'GraphqlSoupDocument:doc-1' },
operation: {
kind: 'upsertByField',
entityKey: 'GraphqlProperty:assignment-1',
whereField: 'propertyDefinitionId',
equals: 'tag-def',
},
},
]);
expect(options.revalidations).toEqual([
{
document: EntityPropertiesDocument,
variables: { input: { entityType: 'DOCUMENT', entityId: 'doc-1' } },
onlyOnLinkFailure: true,
},
]);
expect(validateUuid(options.uuid)).toBe(true);
expect(inspectMock).not.toHaveBeenCalled();
});
it('uses a fresh UUID for each non-coalescible delta batch', async () => {
const input = {
entityType: 'DOCUMENT' as const,
entityId: 'doc-1',
properties: [
{
property: tagProperty,
currentOptionIds: ['stale'],
nextOptionIds: ['spotlight'],
},
],
};
await updateGraphqlEntityPropertyOptions(input);
await updateGraphqlEntityPropertyOptions(input);
const uuids = executeOptimisticMutationMock.mock.calls.map(
(call) => call[4].uuid
);
expect(uuids.every(validateUuid)).toBe(true);
expect(new Set(uuids).size).toBe(2);
});
it('saves a first tag without inspection when the cache exceeds the variant budget', async () => {
await updateGraphqlEntityPropertyOptions({
entityType: 'DOCUMENT',
entityId: 'doc-1',
properties: [
{
property: tagDefinition,
currentOptionIds: [],
nextOptionIds: ['spotlight'],
},
],
});
const { variables, optimisticData, options } = optimisticArgs();
expect(variables.input.properties).toEqual([
{
propertyDefinitionId: 'tag-def',
addOptionIds: ['spotlight'],
removeOptionIds: [],
},
]);
const temporaryId = 'optimistic-property:DOCUMENT:doc-1:tag-def';
expect(optimisticData.updateEntityPropertyOptions).toMatchObject([
{
id: temporaryId,
propertyDefinitionId: 'tag-def',
dataType: 'TAG',
value: { optionIds: ['spotlight'] },
},
]);
// Every query reading the parent sees the new assignment immediately.
// Commit resolves its server ID from the matching response record.
expect(options.updates).toMatchObject([
{
recordRoot: {
fragmentName: 'PropertyAssignmentParent',
entityKey: 'GraphqlSoupDocument:doc-1',
},
path: [{ field: 'properties' }],
operation: {
kind: 'upsertByField',
entityKey: `GraphqlProperty:${temporaryId}`,
whereField: 'propertyDefinitionId',
equals: 'tag-def',
},
},
]);
expect(options.revalidations).toEqual([
{
document: EntityPropertiesDocument,
variables: { input: { entityType: 'DOCUMENT', entityId: 'doc-1' } },
onlyOnLinkFailure: true,
},
]);
expect(inspectMock).not.toHaveBeenCalled();
});
it('skips revalidation discovery when the normalized cache is unavailable', async () => {
cacheHostState.current = undefined;
await updateGraphqlEntityPropertyOptions({
entityType: 'DOCUMENT',
entityId: 'doc-1',
properties: [
{
property: tagDefinition,
currentOptionIds: [],
nextOptionIds: ['spotlight'],
},
],
});
expect(inspectMock).not.toHaveBeenCalled();
expect(optimisticArgs().options.revalidations).toEqual([]);
});
it('uses the supplied assignment identity and preserves TAG metadata', async () => {
await updateGraphqlEntityPropertyOptions({
entityType: 'DOCUMENT',
entityId: 'doc-1',
properties: [
{
property: tagDefinition,
assignmentId: 'assignment-1',
currentOptionIds: ['spotlight'],
nextOptionIds: [],
},
],
});
const { variables, optimisticData, options } = optimisticArgs();
expect(variables.input.properties[0].removeOptionIds).toEqual([
'spotlight',
]);
expect(optimisticData.updateEntityPropertyOptions).toMatchObject([
{ id: 'assignment-1', dataType: 'TAG', value: null },
]);
expect(options.revalidations).toEqual([
{
document: EntityPropertiesDocument,
variables: { input: { entityType: 'DOCUMENT', entityId: 'doc-1' } },
onlyOnLinkFailure: true,
},
]);
expect(inspectMock).not.toHaveBeenCalled();
});
it.each([
['TASK', 'GraphqlSoupDocument', 'DOCUMENT'],
['THREAD', 'GraphqlSoupEmailThread', 'EMAIL_THREAD'],
['INITIATIVE', 'GraphqlSoupInitiative', 'INITIATIVE'],
['CALL_RECORD', 'GraphqlSoupCall', 'CALL'],
] as const)(
'durably links and revalidates only the %s target after a queued first-tag commit',
async (entityType, typename, soupEntityType) => {
optimisticMutationDispositionOfMock.mockReturnValue({
kind: 'queued',
transactionId: 'txn-1',
});
await expect(
updateGraphqlEntityPropertyOptions({
entityType,
entityId: 'target-1',
properties: [
{
property: tagDefinition,
currentOptionIds: [],
nextOptionIds: ['spotlight'],
},
],
})
).resolves.toEqual([
{ propertyDefinitionId: 'tag-def', optionIds: ['spotlight'] },
]);
expect(optimisticArgs().options.updates).toMatchObject([
{
recordRoot: { entityKey: `${typename}:target-1` },
operation: {
kind: 'upsertByField',
whereField: 'propertyDefinitionId',
equals: 'tag-def',
},
},
]);
expect(optimisticArgs().options.revalidations).toEqual([
{
document: EntityPropertiesDocument,
variables: {
input: { entityType: soupEntityType, entityId: 'target-1' },
},
onlyOnLinkFailure: true,
},
]);
expect(inspectMock).not.toHaveBeenCalled();
}
);
it('links each new tag set independently in one mutation', async () => {
await updateGraphqlEntityPropertyOptions({
entityType: 'DOCUMENT',
entityId: 'doc-1',
properties: [
{
property: tagDefinition,
currentOptionIds: [],
nextOptionIds: ['spotlight'],
},
{
property: { ...tagDefinition, id: 'team-tag-def' },
currentOptionIds: [],
nextOptionIds: ['roadmap'],
},
],
});
const { optimisticData, options } = optimisticArgs();
expect(optimisticData.updateEntityPropertyOptions).toMatchObject([
{ propertyDefinitionId: 'tag-def', value: { optionIds: ['spotlight'] } },
{
propertyDefinitionId: 'team-tag-def',
value: { optionIds: ['roadmap'] },
},
]);
expect(options.updates).toMatchObject([
{ operation: { kind: 'upsertByField', equals: 'tag-def' } },
{ operation: { kind: 'upsertByField', equals: 'team-tag-def' } },
]);
expect(options.revalidations).toHaveLength(1);
});
it('resolves a queued commit with the requested selection', async () => {
optimisticMutationDispositionOfMock.mockReturnValue({
kind: 'queued',
transactionId: 'txn-1',
});
await expect(
updateGraphqlEntityPropertyOptions({
entityType: 'DOCUMENT',
entityId: 'doc-1',
properties: [
{
property: tagProperty,
currentOptionIds: [],
nextOptionIds: ['spotlight'],
},
],
})
).resolves.toEqual([
{ propertyDefinitionId: 'tag-def', optionIds: ['spotlight'] },
]);
});
it('throws a permanent failure so the caller can surface it', async () => {
const error = new Error('forbidden');
optimisticMutationDispositionOfMock.mockReturnValue({
kind: 'permanently-failed',
error,
});
await expect(
updateGraphqlEntityPropertyOptions({
entityType: 'DOCUMENT',
entityId: 'doc-1',
properties: [
{
property: tagProperty,
currentOptionIds: [],
nextOptionIds: ['spotlight'],
},
],
})
).rejects.toThrow('forbidden');
});
it('reconciles from the server when a concurrent edit merged in', async () => {
optimisticMutationDispositionOfMock.mockReturnValue(
committedWith(['spotlight', 'roadmap'])
);
await expect(
updateGraphqlEntityPropertyOptions({
entityType: 'DOCUMENT',
entityId: 'doc-1',
properties: [
{
property: tagProperty,
currentOptionIds: [],
nextOptionIds: ['spotlight'],
},
],
})
).resolves.toEqual([
{ propertyDefinitionId: 'tag-def', optionIds: ['spotlight', 'roadmap'] },
]);
});
});