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.

Seanaye/fix/create tags (#7137)

Sean Ayec97b420c1b49
diff --git a/apps/web/src/features/property/tags/useDocTags.test.ts b/apps/web/src/features/property/tags/useDocTags.test.ts
new file mode 100644
index 0000000000..7a15203184
--- /dev/null
+++ b/apps/web/src/features/property/tags/useDocTags.test.ts
@@ -0,0 +1,158 @@
+import type { Property } from '@property/types';
+import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';
+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';
+import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ mutateAsync: vi.fn(),
+ properties: vi.fn<() => Property[]>(),
+ tagSets: vi.fn<() => TagSetResponse[]>(),
+}));
+
+vi.mock('@queries/properties/entity', () => ({
+ useBulkUpdateEntityPropertyOptionsMutation: () => ({
+ mutateAsync: mocks.mutateAsync,
+ }),
+}));
+vi.mock('@queries/properties/in-flight-options', () => ({
+ useInFlightEntityPropertyOptions: () => () => undefined,
+}));
+vi.mock('@queries/properties/tags', () => ({
+ useTagsQuery: () => ({
+ get data() {
+ return mocks.tagSets();
+ },
+ }),
+ useEnsureTagSetMutation: () => ({}),
+}));
+vi.mock('../hooks', () => ({
+ useEntityProperties: () => ({ properties: mocks.properties }),
+}));
+vi.mock('./tag-sets-context', () => ({
+ useTagSets: () => mocks.tagSets,
+}));
+
+import { useDocTags, useSoupDocTags } from './useDocTags';
+
+const definition: PropertyDefinitionDetailResponse = {
+ id: 'tag-def',
+ displayName: 'Tags',
+ dataType: 'TAG',
+ isMultiSelect: true,
+ isMetadata: false,
+ isSystem: false,
+ scope: 'system',
+};
+const property: Property = {
+ propertyId: 'assignment-1',
+ propertyDefinitionId: definition.id,
+ displayName: definition.displayName,
+ isMultiSelect: true,
+ owner: { scope: 'system' },
+ createdAt: '',
+ updatedAt: '',
+ valueType: 'SELECT_STRING',
+ value: ['cool'],
+};
+const soupProperty: SoupProperty = {
+ id: property.propertyId,
+ definition: {
+ id: definition.id,
+ display_name: definition.displayName,
+ data_type: 'TAG',
+ is_multi_select: true,
+ is_metadata: false,
+ is_system: false,
+ owner: { scope: 'system' },
+ created_at: '',
+ updated_at: '',
+ },
+ value: { type: 'SelectOption', value: ['cool'] },
+};
+
+let dispose: (() => void) | undefined;
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.mutateAsync.mockResolvedValue([]);
+ mocks.properties.mockReturnValue([property]);
+ mocks.tagSets.mockReturnValue([
+ {
+ scope: 'user',
+ definition,
+ options: [
+ {
+ id: 'cool',
+ propertyDefinitionId: definition.id,
+ displayOrder: 0,
+ value: { type: 'string', value: 'cool' },
+ },
+ ],
+ },
+ ]);
+});
+afterEach(() => dispose?.());
+
+describe('tag assignment identity', () => {
+ it.each(['detail', 'soup'] as const)(
+ 'preserves the %s assignment when removing a tag',
+ async (source) => {
+ const tags = createRoot((cleanup) => {
+ dispose = cleanup;
+ return source === 'detail'
+ ? useDocTags('doc-1', 'DOCUMENT')
+ : useSoupDocTags('doc-1', 'DOCUMENT', () => [soupProperty]);
+ });
+
+ expect(tags.isApplied('cool')).toBe(true);
+ await tags.removeTag('user', 'cool');
+ expect(mocks.mutateAsync).toHaveBeenCalledWith({
+ entityId: 'doc-1',
+ entityType: 'DOCUMENT',
+ properties: [
+ {
+ property: expect.objectContaining({
+ id: 'tag-def',
+ valueType: 'TAG',
+ }),
+ assignmentId: 'assignment-1',
+ currentOptionIds: ['cool'],
+ nextOptionIds: [],
+ },
+ ],
+ });
+ }
+ );
+
+ it.each(['detail', 'soup'] as const)(
+ 'reads the latest %s assignment after the first tag is saved',
+ async (source) => {
+ const [assigned, setAssigned] = createSignal(false);
+ mocks.properties.mockImplementation(() => (assigned() ? [property] : []));
+ const tags = createRoot((cleanup) => {
+ dispose = cleanup;
+ return source === 'detail'
+ ? useDocTags('doc-1', 'DOCUMENT')
+ : useSoupDocTags('doc-1', 'DOCUMENT', () =>
+ assigned() ? [soupProperty] : []
+ );
+ });
+
+ await tags.applyTag('user', 'cool');
+ expect(mocks.mutateAsync.mock.calls[0][0].properties[0]).toMatchObject({
+ assignmentId: undefined,
+ currentOptionIds: [],
+ nextOptionIds: ['cool'],
+ });
+
+ setAssigned(true);
+ await tags.removeTag('user', 'cool');
+ expect(mocks.mutateAsync.mock.calls[1][0].properties[0]).toMatchObject({
+ assignmentId: 'assignment-1',
+ currentOptionIds: ['cool'],
+ nextOptionIds: [],
+ });
+ }
+ );
+});
diff --git a/apps/web/src/features/property/tags/useDocTags.ts b/apps/web/src/features/property/tags/useDocTags.ts
index 00406d0e3e..b75fbe4aed 100644
--- a/apps/web/src/features/property/tags/useDocTags.ts
+++ b/apps/web/src/features/property/tags/useDocTags.ts
@@ -61,7 +61,8 @@ type SetTagOptionIdsForDefinition = (
function usePersistTagSelection(
entityId: string,
- entityType: EntityType
+ entityType: EntityType,
+ assignmentIdForDefinition: (definitionId: string) => string | undefined
): PersistTagSelection {
const mutation = useBulkUpdateEntityPropertyOptionsMutation(entityId);
@@ -71,6 +72,7 @@ function usePersistTagSelection(
entityType,
properties: updates.map((update) => ({
property: definitionDomain(update.definition),
+ assignmentId: assignmentIdForDefinition(update.definition.id),
currentOptionIds: update.currentOptionIds,
nextOptionIds: update.nextOptionIds,
})),
@@ -275,11 +277,17 @@ export function useDocTags(entityId: string, entityType: EntityType) {
? property.value
: [];
};
- const persistTagSelection = usePersistTagSelection(entityId, entityType);
+ const persistTagSelection = usePersistTagSelection(
+ entityId,
+ entityType,
+ (definitionId) =>
+ properties().find((prop) => prop.propertyDefinitionId === definitionId)
+ ?.propertyId
+ );
const tagsQuery = useTagsQuery();
const tagSets = (): TagSetResponse[] => tagsQuery.data ?? [];
- // The properties query isn't optimistically written, so surface in-flight
- // bulk updates as the optimistic value until the refetch lands.
+ // Cover new assignments (and the REST query) until persistence reconciles
+ // the source. Existing GraphQL assignments also update in the normalized cache.
const inFlightOptionIdsForDefinition =
useInFlightEntityPropertyOptions(entityId);
@@ -313,7 +321,12 @@ export function useSoupDocTags(
const value = property?.value;
return value?.type === 'SelectOption' ? value.value : [];
};
- const persistTagSelection = usePersistTagSelection(entityId, entityType);
+ const persistTagSelection = usePersistTagSelection(
+ entityId,
+ entityType,
+ (definitionId) =>
+ properties()?.find((prop) => prop.definition.id === definitionId)?.id
+ );
const tagSets = useTagSets();
const inFlightOptionIdsForDefinition =
useInFlightEntityPropertyOptions(entityId);
diff --git a/apps/web/src/lib/queries/properties/graphql-optimistic.test.ts b/apps/web/src/lib/queries/properties/graphql-optimistic.test.ts
index b9e2dbd00f..c4bbedcacd 100644
--- a/apps/web/src/lib/queries/properties/graphql-optimistic.test.ts
+++ b/apps/web/src/lib/queries/properties/graphql-optimistic.test.ts
@@ -6,6 +6,7 @@ import type {
import { describe, expect, it } from 'vitest';
import {
apiValuesToGraphqlPropertyValue,
+ buildOptimisticEntityPropertyOptions,
buildOptimisticSetEntityProperty,
} from './graphql-optimistic';
@@ -119,6 +120,46 @@ describe('apiValuesToGraphqlPropertyValue', () => {
});
});
+describe('buildOptimisticEntityPropertyOptions', () => {
+ const definition: PropertyDefinitionDomain = {
+ id: 'tag-def',
+ displayName: 'Tags',
+ valueType: 'TAG',
+ isMultiSelect: true,
+ isMetadata: false,
+ isSystem: false,
+ owner: { scope: 'system' },
+ createdAt: '',
+ updatedAt: '',
+ };
+
+ it('uses a known assignment with the original tag definition metadata', () => {
+ expect(
+ buildOptimisticEntityPropertyOptions(definition, ['cool'], 'assignment-1')
+ ).toMatchObject({
+ id: 'assignment-1',
+ propertyDefinitionId: 'tag-def',
+ dataType: 'TAG',
+ value: {
+ __typename: 'GraphqlSelectOptionPropertyValue',
+ optionIds: ['cool'],
+ },
+ });
+ });
+
+ it.each([
+ undefined,
+ '',
+ 'tag-def',
+ 'pending:tag-def',
+ 'optimistic-property:DOCUMENT:doc:tag-def',
+ ])('does not treat %s as a persisted assignment', (assignmentId) => {
+ expect(
+ buildOptimisticEntityPropertyOptions(definition, ['cool'], assignmentId)
+ ).toBeUndefined();
+ });
+});
+
describe('buildOptimisticSetEntityProperty', () => {
const instantiated: Property = {
propertyId: 'prop-1',
diff --git a/apps/web/src/lib/queries/properties/graphql-optimistic.ts b/apps/web/src/lib/queries/properties/graphql-optimistic.ts
index a84602aa74..c6207b596e 100644
--- a/apps/web/src/lib/queries/properties/graphql-optimistic.ts
+++ b/apps/web/src/lib/queries/properties/graphql-optimistic.ts
@@ -127,9 +127,15 @@ function hasPersistedAssignment(
): property is Property {
return (
isInstantiatedProperty(property) &&
- property.propertyId !== property.propertyDefinitionId &&
- !property.propertyId.startsWith('pending:') &&
- !isTemporaryGraphqlProperty(property.propertyId)
+ isPersistedAssignmentId(property.propertyId, property.propertyDefinitionId)
+ );
+}
+
+function isPersistedAssignmentId(id: string, definitionId: string): boolean {
+ return (
+ id !== definitionId &&
+ !id.startsWith('pending:') &&
+ !isTemporaryGraphqlProperty(id)
);
}
@@ -167,9 +173,16 @@ export function buildOptimisticSetEntityProperty(
*/
export function buildOptimisticEntityPropertyOptions(
property: Property | PropertyDefinitionDomain,
- optionIds: readonly string[]
+ optionIds: readonly string[],
+ assignmentId?: string
): SoupPropertyFieldsFragment | undefined {
- if (!hasPersistedAssignment(property)) return undefined;
+ const definitionId = isInstantiatedProperty(property)
+ ? property.propertyDefinitionId
+ : property.id;
+ const id =
+ assignmentId ??
+ (isInstantiatedProperty(property) ? property.propertyId : undefined);
+ if (!id || !isPersistedAssignmentId(id, definitionId)) return undefined;
return optimisticPropertyRecord(
property,
optionIds.length > 0
@@ -178,6 +191,6 @@ export function buildOptimisticEntityPropertyOptions(
optionIds: [...optionIds],
}
: null,
- property.propertyId
+ id
);
}
diff --git a/apps/web/src/lib/queries/properties/graphql/entity-options.test.ts b/apps/web/src/lib/queries/properties/graphql/entity-options.test.ts
index e914eb0ac3..b99f5b71fe 100644
--- a/apps/web/src/lib/queries/properties/graphql/entity-options.test.ts
+++ b/apps/web/src/lib/queries/properties/graphql/entity-options.test.ts
@@ -1,6 +1,8 @@
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';
+import { buildGraphqlEntitySoupInput } from '../../soup/graphql/entity-input';
const executeOptimisticMutationMock = vi.hoisted(() => vi.fn());
const optimisticMutationDispositionOfMock = vi.hoisted(() => vi.fn());
@@ -76,6 +78,9 @@ 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 }),
});
@@ -154,30 +159,7 @@ describe('updateGraphqlEntityPropertyOptions', () => {
expect(new Set(uuids).size).toBe(2);
});
- it('revalidates only the cached queries holding the entity when it has no record for the definition', async () => {
- inspectMock
- .mockResolvedValueOnce([
- {
- variables: { input: 'soup-with' },
- value: { items: [{ id: 'doc-1' }] },
- },
- {
- variables: { input: 'soup-without' },
- value: { items: [{ id: 'other' }] },
- },
- { variables: { input: 'soup-unreadable' }, value: undefined },
- ])
- .mockResolvedValueOnce([
- {
- variables: { input: 'grouped-with' },
- value: { bins: [{ items: [{ id: 'doc-1' }] }] },
- },
- {
- variables: { input: 'grouped-without' },
- value: { bins: [{ items: [] }] },
- },
- ]);
-
+ it('saves a first tag without inspection when the cache exceeds the variant budget', async () => {
await updateGraphqlEntityPropertyOptions({
entityType: 'DOCUMENT',
entityId: 'doc-1',
@@ -200,12 +182,13 @@ describe('updateGraphqlEntityPropertyOptions', () => {
]);
// No assignment id exists yet, so nothing can be patched before the commit.
expect(optimisticData.updateEntityPropertyOptions).toEqual([]);
- expect(
- options.revalidations.map(
- (revalidation: { variables: { input: string } }) =>
- revalidation.variables.input
- )
- ).toEqual(['soup-with', 'grouped-with']);
+ expect(options.revalidations).toEqual([
+ {
+ document: EntityPropertiesDocument,
+ variables: { input: buildGraphqlEntitySoupInput('DOCUMENT', 'doc-1') },
+ },
+ ]);
+ expect(inspectMock).not.toHaveBeenCalled();
});
it('skips revalidation discovery when the normalized cache is unavailable', async () => {
@@ -227,6 +210,66 @@ describe('updateGraphqlEntityPropertyOptions', () => {
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([]);
+ expect(inspectMock).not.toHaveBeenCalled();
+ });
+
+ it.each(['TASK', 'THREAD', 'INITIATIVE', 'CALL_RECORD'] as const)(
+ 'durably revalidates only the %s target after a queued first-tag commit',
+ async (entityType) => {
+ 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.revalidations).toEqual([
+ {
+ document: EntityPropertiesDocument,
+ variables: {
+ input: buildGraphqlEntitySoupInput(entityType, 'target-1'),
+ },
+ },
+ ]);
+ expect(inspectMock).not.toHaveBeenCalled();
+ }
+ );
+
it('resolves a queued commit with the requested selection', async () => {
optimisticMutationDispositionOfMock.mockReturnValue({
kind: 'queued',
diff --git a/apps/web/src/lib/queries/properties/graphql/entity-options.ts b/apps/web/src/lib/queries/properties/graphql/entity-options.ts
index 61ce596209..446294c7ef 100644
--- a/apps/web/src/lib/queries/properties/graphql/entity-options.ts
+++ b/apps/web/src/lib/queries/properties/graphql/entity-options.ts
@@ -9,20 +9,15 @@
import {
executeOptimisticMutation,
- inspect,
optimisticMutationDispositionOf,
type QueryRevalidation,
- selectAll,
} from '@graphql-cache/index';
import type { Property, PropertyDefinitionDomain } from '@property/types';
import { isInstantiatedProperty } from '@property/utils/typeGuards';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import type { PropertyTargetEntityType } from '@service-properties/generated/schemas/propertyTargetEntityType';
import {
- GroupSoupDocument,
- GroupSoupMembershipDocument,
- SoupDocument,
- SoupMembershipDocument,
+ EntityPropertiesDocument,
UpdateEntityPropertyOptionsDocument,
type UpdateEntityPropertyOptionsMutation,
type UpdateEntityPropertyOptionsMutationVariables,
@@ -31,6 +26,7 @@ import {
getGraphqlCacheHost,
getGraphqlSoupClient,
} from '@service-storage/graphql-soup';
+import { buildGraphqlEntitySoupInput } from '../../soup/graphql/entity-input';
import { buildOptimisticEntityPropertyOptions } from '../graphql-optimistic';
import {
type EntityPropertyOptionSelection,
@@ -43,6 +39,8 @@ export type GraphqlEntityPropertyOptionsInput = {
entityId: string;
properties: Array<{
property: Property | PropertyDefinitionDomain;
+ /** Existing assignment identity when the picker supplies a tag definition. */
+ assignmentId?: string;
currentOptionIds: string[];
nextOptionIds: string[];
}>;
@@ -57,51 +55,21 @@ function getPropertyDefinitionId(
}
/**
- * Queries that must re-read the entity after commit because a property record
- * the entity had never carried cannot be linked optimistically: the assignment
- * id arrives with the response, while `properties` is a link list on the entity
- * record that a bare record write does not extend.
- *
- * Only cached instances already holding the entity are revalidated, so an
- * unrelated loaded list is never refetched.
- *
- * Discovery reads through the id-only membership documents: a denormalized read
- * misses whenever ANY selected field was never written for ANY item in the
- * variant (a channel row carries no `properties`, so a full-item selection can
- * miss a variant that does hold the entity). Membership selects `__typename` and
- * `id` only, which every cached item has. Both membership documents select the
- * same cached fields as their list counterparts, so one inspection per field
- * finds every variant — including the single-entity ones the properties query
- * loads, which the list document then refetches as a superset.
+ * A new assignment must be linked into its entity's properties list. Re-reading
+ * that one entity updates the normalized parent for every list/detail consumer.
+ * Never inspect all cached Soup variants here: backfills can exceed the cache's
+ * inspection budget, and cache bookkeeping must not prevent the mutation.
+ * The descriptor is durable, so an offline commit also reconciles on replay.
*/
-async function newPropertyLinkRevalidations(
+function newPropertyLinkRevalidations(
+ entityType: EntityType | PropertyTargetEntityType,
entityId: string
-): Promise<QueryRevalidation[]> {
- const host = getGraphqlCacheHost();
- if (!host) return [];
-
- const [flatPages, groupedPages] = await Promise.all([
- inspect(
- host,
- selectAll(SoupMembershipDocument).field('user').field('soup')
- ),
- inspect(
- host,
- selectAll(GroupSoupMembershipDocument).field('user').field('groupSoup')
- ),
- ]);
-
- const holdsEntity = (items: readonly { id: string }[] | undefined) =>
- items?.some((item) => item.id === entityId) ?? false;
-
- return [
- ...flatPages
- .filter(({ value }) => holdsEntity(value?.items))
- .map(({ variables }) => ({ document: SoupDocument, variables })),
- ...groupedPages
- .filter(({ value }) => value?.bins.some((bin) => holdsEntity(bin.items)))
- .map(({ variables }) => ({ document: GroupSoupDocument, variables })),
- ];
+): QueryRevalidation[] {
+ if (!getGraphqlCacheHost()) return [];
+ const input = buildGraphqlEntitySoupInput(entityType, entityId);
+ return input
+ ? [{ document: EntityPropertiesDocument, variables: { input } }]
+ : [];
}
/**
@@ -140,13 +108,14 @@ export async function updateGraphqlEntityPropertyOptions(
const optimisticProperties = input.properties.flatMap((update) => {
const record = buildOptimisticEntityPropertyOptions(
update.property,
- update.nextOptionIds
+ update.nextOptionIds,
+ update.assignmentId
);
return record ? [record] : [];
});
const revalidations =
optimisticProperties.length < input.properties.length
- ? await newPropertyLinkRevalidations(input.entityId)
+ ? newPropertyLinkRevalidations(input.entityType, input.entityId)
: [];
const result = await executeOptimisticMutation(
diff --git a/apps/web/src/lib/queries/properties/in-flight-options.ts b/apps/web/src/lib/queries/properties/in-flight-options.ts
index 1af6b2eb60..41e89cd1ae 100644
--- a/apps/web/src/lib/queries/properties/in-flight-options.ts
+++ b/apps/web/src/lib/queries/properties/in-flight-options.ts
@@ -18,6 +18,8 @@ export type BulkUpdateEntityPropertyOptionsParams = {
entityType: EntityType;
properties: Array<{
property: Property | PropertyDefinitionDomain;
+ /** Preserve assignment identity without losing the definition's TAG data type. */
+ assignmentId?: string;
currentOptionIds: string[];
nextOptionIds: string[];
}>;
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 9e90663382..ef95048b00 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -587,7 +587,14 @@ Right side of a doc (toggle with `Hide/Show Side Panel`):
- `Actions` → `Ask Macro` (opens a doc-scoped AI chat, see ai-chat.md).
- `Details` → Owner, Created, Last updated.
-- `Tags` → `Add tags` (dialog). `Properties` → `Add property`.
+- `Tags` → `Add tags` (dialog). Click a tag's label to toggle and save; Shift-click
+ keeps the picker open for multiple selections. Reopen it to remove a tag.
+ With GraphQL Soup enabled, applying the first tag refetches only that entity's
+ properties; later edits update the existing assignment optimistically. Verify
+ both the side panel and list-row chip, then reload to confirm persistence.
+ This must also work after background backfills populate more than 128 cached
+ Soup variants—tag saves must not scan all cached pages.
+ `Properties` → `Add property`.
- Collapsed sections: `Stats`, `History` (version time-travel), `Activity`.
- `Activity` lists the same glyph-rail lines as `/app/component/activity` (plain glyphs on a
thin connector, one line each with long names truncated, compact `17h` / `8d` / `1mo`