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(tag): colored tag chips + item count for property-update ai tool cards (#5099)

gbirmand2f15231d2c3
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Properties.test.tsx b/apps/web/src/lib/core/component/AI/component/tool/Properties.test.tsx
new file mode 100644
index 0000000000..935b73d6cb
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/Properties.test.tsx
@@ -0,0 +1,244 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { propertiesKeys } from '@queries/properties/keys';
+import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import type { PropertyOption } from '@service-properties/generated/schemas/propertyOption';
+import type { PropertyOptionResponse } from '@service-properties/generated/schemas/propertyOptionResponse';
+import type { PropertyOptionValue } from '@service-properties/generated/schemas/propertyOptionValue';
+import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';
+import type { TagSetResponseDefinition } from '@service-properties/generated/schemas/tagSetResponseDefinition';
+import { cleanup, render } from '@solidjs/testing-library';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import type { Component } from 'solid-js';
+import { Dynamic } from 'solid-js/web';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ bulkSetEntityPropertyOptionsHandler,
+ setEntityPropertyHandler,
+} from './Properties';
+
+vi.mock('@core/auth', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@core/auth')>()),
+ useIsAuthenticated: () => () => true,
+}));
+
+const TAG_DEF = 'tag-def-1';
+const STATUS_DEF = 'status-def';
+
+function stringValue(value: string): PropertyOptionValue {
+ return { type: 'string', value } as PropertyOptionValue;
+}
+
+function tagOption(
+ id: string,
+ label: string,
+ color: string
+): PropertyOptionResponse {
+ return {
+ id,
+ propertyDefinitionId: TAG_DEF,
+ displayOrder: 0,
+ value: stringValue(label),
+ color,
+ };
+}
+
+const tagSets: TagSetResponse[] = [
+ {
+ scope: 'user',
+ definition: { id: TAG_DEF } as TagSetResponseDefinition,
+ options: [
+ tagOption('opt-follow', 'Follow-up', 'rgb(220, 38, 38)'),
+ tagOption('opt-urgent', 'Urgent', 'rgb(37, 99, 235)'),
+ ],
+ },
+];
+
+const statusOptions: PropertyOption[] = [
+ {
+ id: 'status-done',
+ property_definition_id: STATUS_DEF,
+ display_order: 0,
+ value: stringValue('Done'),
+ color: 'rgb(16, 185, 129)',
+ created_at: '',
+ updated_at: '',
+ },
+];
+
+function makeClient(): QueryClient {
+ const client = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, staleTime: Number.POSITIVE_INFINITY },
+ },
+ });
+ client.setQueryData(propertiesKeys.tags.queryKey, tagSets);
+ client.setQueryData(
+ propertiesKeys.options({ propertyDefinitionId: STATUS_DEF }).queryKey,
+ statusOptions
+ );
+ client.setQueryData(
+ propertiesKeys.options({ propertyDefinitionId: 'empty-def' }).queryKey,
+ []
+ );
+ return client;
+}
+
+function renderTool<
+ TName extends 'SetEntityProperty' | 'BulkSetEntityPropertyOptions',
+>(handler: { render: Component<never> }, tool: NamedTool<TName, 'call'>) {
+ const client = makeClient();
+ return render(() => (
+ <QueryClientProvider client={client}>
+ <Dynamic
+ component={handler.render as Component<Record<string, unknown>>}
+ tool={tool}
+ chat_id="chat-1"
+ message_id="message-1"
+ part_index={0}
+ isComplete={false}
+ renderContext={{ isStreaming: false, grouped: false }}
+ />
+ </QueryClientProvider>
+ ));
+}
+
+function bulkTool(
+ data: NamedTool<'BulkSetEntityPropertyOptions', 'call'>['data']
+): NamedTool<'BulkSetEntityPropertyOptions', 'call'> {
+ return { id: 'tool-1', name: 'BulkSetEntityPropertyOptions', data };
+}
+
+function setTool(
+ data: NamedTool<'SetEntityProperty', 'call'>['data']
+): NamedTool<'SetEntityProperty', 'call'> {
+ return { id: 'tool-1', name: 'SetEntityProperty', data };
+}
+
+afterEach(cleanup);
+
+describe('BulkSetEntityPropertyOptions renderer', () => {
+ it('renders the affected-item count and a colored tag chip', () => {
+ const { container } = renderTool(
+ bulkSetEntityPropertyOptionsHandler,
+ bulkTool({
+ property_definition_id: TAG_DEF,
+ add_option_ids: ['opt-follow'],
+ entities: Array.from({ length: 18 }, (_, i) => ({
+ entity_id: `doc-${i}`,
+ entity_type: 'document',
+ })),
+ })
+ );
+
+ expect(container.textContent).toContain('Tag');
+ expect(container.textContent).toContain('18 items');
+ expect(container.textContent).toContain('Follow-up');
+
+ const dot = container.querySelector('span[style*="background-color"]');
+ expect(dot).not.toBeNull();
+ expect((dot as HTMLElement).style.backgroundColor).toBe('rgb(220, 38, 38)');
+ });
+
+ it('singularizes the item count', () => {
+ const { container } = renderTool(
+ bulkSetEntityPropertyOptionsHandler,
+ bulkTool({
+ property_definition_id: TAG_DEF,
+ add_option_ids: ['opt-follow'],
+ entities: [{ entity_id: 'doc-0', entity_type: 'document' }],
+ })
+ );
+
+ expect(container.textContent).toContain('1 item');
+ expect(container.textContent).not.toContain('1 items');
+ });
+});
+
+describe('SetEntityProperty renderer', () => {
+ it('renders a tag add as a colored chip', () => {
+ const { container } = renderTool(
+ setEntityPropertyHandler,
+ setTool({
+ entity_type: 'document',
+ entity_id: 'entity-1',
+ property_definition_id: TAG_DEF,
+ add_option_ids: ['opt-follow'],
+ })
+ );
+
+ expect(container.textContent).toContain('Tag');
+ expect(container.textContent).toContain('document');
+ expect(container.textContent).toContain('Follow-up');
+ });
+
+ it('renders a tag removal as a struck-through chip labelled Untag', () => {
+ const { container } = renderTool(
+ setEntityPropertyHandler,
+ setTool({
+ entity_type: 'document',
+ entity_id: 'entity-1',
+ property_definition_id: TAG_DEF,
+ remove_option_ids: ['opt-urgent'],
+ })
+ );
+
+ expect(container.textContent).toContain('Untag');
+ const struck = container.querySelector('.line-through');
+ expect(struck).not.toBeNull();
+ expect(struck?.textContent).toContain('Urgent');
+ });
+
+ it('resolves a non-tag select value (Status) to a colored chip', () => {
+ const { container } = renderTool(
+ setEntityPropertyHandler,
+ setTool({
+ entity_type: 'document',
+ entity_id: 'entity-1',
+ property_definition_id: STATUS_DEF,
+ option_id: 'status-done',
+ })
+ );
+
+ expect(container.textContent).toContain('Set');
+ expect(container.textContent).toContain('document');
+ expect(container.textContent).toContain('Done');
+
+ const dot = container.querySelector('span[style*="background-color"]');
+ expect((dot as HTMLElement).style.backgroundColor).toBe(
+ 'rgb(16, 185, 129)'
+ );
+ });
+
+ it('renders a literal string value', () => {
+ const { container } = renderTool(
+ setEntityPropertyHandler,
+ setTool({
+ entity_type: 'document',
+ entity_id: 'entity-1',
+ property_definition_id: 'notes-def',
+ string_value: 'Draft copy',
+ })
+ );
+
+ expect(container.textContent).toContain('Set');
+ expect(container.textContent).toContain('Draft copy');
+ });
+
+ it('falls back to a bare label when no option resolves', () => {
+ const { container } = renderTool(
+ setEntityPropertyHandler,
+ setTool({
+ entity_type: 'company',
+ entity_id: 'entity-1',
+ property_definition_id: 'empty-def',
+ add_option_ids: ['ghost-option'],
+ })
+ );
+
+ expect(container.textContent).toContain('Update property on');
+ expect(container.textContent).toContain('company');
+ });
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Properties.tsx b/apps/web/src/lib/core/component/AI/component/tool/Properties.tsx
index c412beef4e..99a544dcae 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/Properties.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/Properties.tsx
@@ -1,8 +1,187 @@
import PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';
import Sliders from '@phosphor-icons/core/regular/sliders.svg';
+import { TagDot } from '@property/tags/TagDot';
+import { usePropertyOptionsQuery } from '@queries/properties/options';
+import { useTagsQuery } from '@queries/properties/tags';
+import type { NamedTool } from '@service-cognition/generated/tools/tool';
+import type { PropertyOptionValue } from '@service-properties/generated/schemas/propertyOptionValue';
+import { cn } from '@ui';
+import { type Accessor, createMemo, For, Show } from 'solid-js';
import { BaseTool } from './BaseTool';
import { createToolRenderer } from './ToolRenderer';
+type ResolvedOption = { id: string; label: string; color?: string };
+
+// Max chips shown per group before collapsing the rest into a "+N" counter.
+const CHIP_LIMIT = 5;
+
+function optionValueLabel(value: PropertyOptionValue): string {
+ return value.type === 'string' ? value.value : String(value.value);
+}
+
+/**
+ * Resolves option ids to labels + colors using the caller's tag sets, falling
+ * back to the target definition's own options for non-tag selects (e.g. Status).
+ * The definition options are only fetched when an id isn't already a known tag.
+ */
+function useOptionResolver(
+ propertyDefinitionId: Accessor<string>,
+ optionIds: Accessor<string[]>
+) {
+ const tagsQuery = useTagsQuery();
+
+ const tagOptions = createMemo(() => {
+ const map = new Map<string, ResolvedOption>();
+ for (const set of tagsQuery.data ?? []) {
+ for (const option of set.options) {
+ map.set(option.id, {
+ id: option.id,
+ label: optionValueLabel(option.value),
+ color: option.color ?? undefined,
+ });
+ }
+ }
+ return map;
+ });
+
+ const needsDefinitionOptions = createMemo(() =>
+ optionIds().some((id) => !tagOptions().has(id))
+ );
+
+ const optionsQuery = usePropertyOptionsQuery(
+ propertyDefinitionId,
+ needsDefinitionOptions
+ );
+
+ const byId = createMemo(() => {
+ const map = new Map(tagOptions());
+ for (const option of optionsQuery.data ?? []) {
+ if (!map.has(option.id)) {
+ map.set(option.id, {
+ id: option.id,
+ label: optionValueLabel(option.value),
+ color: option.color ?? undefined,
+ });
+ }
+ }
+ return map;
+ });
+
+ const isTagProperty = createMemo(() =>
+ (tagsQuery.data ?? []).some(
+ (set) => set.definition?.id === propertyDefinitionId()
+ )
+ );
+
+ return { byId, isTagProperty };
+}
+
+function resolveChips(
+ ids: string[],
+ byId: ReadonlyMap<string, ResolvedOption>
+): ResolvedOption[] {
+ const chips: ResolvedOption[] = [];
+ for (const id of ids) {
+ const chip = byId.get(id);
+ if (chip) chips.push(chip);
+ }
+ return chips;
+}
+
+function describeLiteralValue(
+ data: NamedTool<'SetEntityProperty', 'call'>['data']
+): string | undefined {
+ if (data.string_value != null) return data.string_value;
+ if (data.number_value != null) return String(data.number_value);
+ if (data.boolean_value != null) return data.boolean_value ? 'Yes' : 'No';
+ if (data.date_value != null) return data.date_value.slice(0, 10);
+ if (data.link_url != null) return data.link_url;
+ if (data.link_urls?.length) return data.link_urls.join(', ');
+ if (data.entity_ref) return data.entity_ref.entityId.replace(/^macro\|/, '');
+ if (data.entity_refs?.length) {
+ return data.entity_refs
+ .map((ref) => ref.entityId.replace(/^macro\|/, ''))
+ .join(', ');
+ }
+ return undefined;
+}
+
+function OptionChip(props: {
+ label: string;
+ color?: string;
+ removed?: boolean;
+}) {
+ return (
+ <span
+ class={cn(
+ 'inline-flex min-w-0 items-center gap-1',
+ props.removed && 'line-through opacity-60'
+ )}
+ >
+ <TagDot color={props.color} class="size-2" />
+ <span class="truncate text-ink">{props.label}</span>
+ </span>
+ );
+}
+
+function OptionChips(props: { options: ResolvedOption[]; removed?: boolean }) {
+ const visible = () => props.options.slice(0, CHIP_LIMIT);
+ const overflow = () => props.options.length - visible().length;
+ return (
+ <>
+ <For each={visible()}>
+ {(option) => (
+ <OptionChip
+ label={option.label}
+ color={option.color}
+ removed={props.removed}
+ />
+ )}
+ </For>
+ <Show when={overflow() > 0}>
+ <span class="shrink-0 text-2xs text-ink-muted">+{overflow()}</span>
+ </Show>
+ </>
+ );
+}
+
+function PropertyToolBody(props: {
+ scopeLabel: string;
+ isTag: boolean;
+ added: ResolvedOption[];
+ removed: ResolvedOption[];
+ literalValue?: string;
+}) {
+ const hasChips = () => props.added.length > 0 || props.removed.length > 0;
+ const verb = () => {
+ if (hasChips()) {
+ if (props.added.length === 0) return props.isTag ? 'Untag' : 'Update';
+ return props.isTag ? 'Tag' : 'Set';
+ }
+ return props.literalValue != null ? 'Set' : 'Update property on';
+ };
+
+ return (
+ <div class="flex min-w-0 flex-1 items-center gap-1.5">
+ <span class="shrink-0">
+ {verb()} <span class="text-ink">{props.scopeLabel}</span>
+ </span>
+ <Show when={hasChips()}>
+ <div class="flex min-w-0 items-center gap-1.5 overflow-hidden">
+ <OptionChips options={props.added} />
+ <Show when={props.added.length > 0 && props.removed.length > 0}>
+ <span class="shrink-0 text-ink-muted">·</span>
+ </Show>
+ <OptionChips options={props.removed} removed />
+ </div>
+ </Show>
+ <Show when={hasChips() ? undefined : props.literalValue}>
+ {(value) => <span class="min-w-0 truncate text-ink">{value()}</span>}
+ </Show>
+ </div>
+ );
+}
+
const getHandler = createToolRenderer({
name: 'GetEntityProperties',
render: (ctx) => (
@@ -15,28 +194,65 @@ const getHandler = createToolRenderer({
const setHandler = createToolRenderer({
name: 'SetEntityProperty',
- render: (ctx) => (
- <BaseTool icon={PencilSimple} renderContext={ctx.renderContext} type="call">
- Update property on{' '}
- <span class="text-ink">{ctx.tool.data.entity_type}</span>
- </BaseTool>
- ),
+ render: (ctx) => {
+ const addIds = () => [
+ ...(ctx.tool.data.add_option_ids ?? []),
+ ...(ctx.tool.data.option_ids ?? []),
+ ...(ctx.tool.data.option_id ? [ctx.tool.data.option_id] : []),
+ ];
+ const removeIds = () => ctx.tool.data.remove_option_ids ?? [];
+ const allIds = () => [...addIds(), ...removeIds()];
+
+ const { byId, isTagProperty } = useOptionResolver(
+ () => ctx.tool.data.property_definition_id,
+ allIds
+ );
+
+ return (
+ <BaseTool
+ icon={PencilSimple}
+ renderContext={ctx.renderContext}
+ type="call"
+ >
+ <PropertyToolBody
+ scopeLabel={ctx.tool.data.entity_type}
+ isTag={isTagProperty()}
+ added={resolveChips(addIds(), byId())}
+ removed={resolveChips(removeIds(), byId())}
+ literalValue={describeLiteralValue(ctx.tool.data)}
+ />
+ </BaseTool>
+ );
+ },
});
const bulkSetHandler = createToolRenderer({
name: 'BulkSetEntityPropertyOptions',
render: (ctx) => {
- const count = ctx.tool.data.entities.length;
+ const addIds = () => ctx.tool.data.add_option_ids ?? [];
+ const removeIds = () => ctx.tool.data.remove_option_ids ?? [];
+ const allIds = () => [...addIds(), ...removeIds()];
+
+ const { byId, isTagProperty } = useOptionResolver(
+ () => ctx.tool.data.property_definition_id,
+ allIds
+ );
+
+ const count = () => ctx.tool.data.entities.length;
+ const scopeLabel = () => `${count()} ${count() === 1 ? 'item' : 'items'}`;
+
return (
<BaseTool
icon={PencilSimple}
renderContext={ctx.renderContext}
type="call"
>
- Update a property on{' '}
- <span class="text-ink">
- {count} {count === 1 ? 'item' : 'items'}
- </span>
+ <PropertyToolBody
+ scopeLabel={scopeLabel()}
+ isTag={isTagProperty()}
+ added={resolveChips(addIds(), byId())}
+ removed={resolveChips(removeIds(), byId())}
+ />
</BaseTool>
);
},
diff --git a/apps/web/src/lib/queries/properties/options.ts b/apps/web/src/lib/queries/properties/options.ts
index fbb4fcf532..db90591558 100644
--- a/apps/web/src/lib/queries/properties/options.ts
+++ b/apps/web/src/lib/queries/properties/options.ts
@@ -10,6 +10,10 @@ import { queryClient } from '../client';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { propertiesKeys } from './keys';
+// Stable empty default so `data` is never undefined: a shared query that errors
+// with undefined data under an app-shell Suspense boundary would remount-loop.
+const EMPTY_OPTIONS: PropertyOption[] = [];
+
export function usePropertyOptionsQuery(
propertyDefinitionId: Accessor<string>,
enabled: Accessor<boolean> = () => true
@@ -30,6 +34,7 @@ export function usePropertyOptionsQuery(
},
enabled: enabled(),
staleTime: 1000 * 60 * 5, // 5 minutes
+ placeholderData: EMPTY_OPTIONS,
};
});
}