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(tags): share a personal tag with the team from settings (#5438)
gbirman2f0a9aa1b211
diff --git a/apps/web/src/features/property/tags/use-tag-team-sharing-flag.ts b/apps/web/src/features/property/tags/use-tag-team-sharing-flag.tsnew file mode 100644index 0000000000..58fe3af463--- /dev/null+++ b/apps/web/src/features/property/tags/use-tag-team-sharing-flag.ts@@ -0,0 +1,18 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import {+ ENABLE_TAG_TEAM_SHARING_FLAG,+ ENABLE_TAG_TEAM_SHARING_OVERRIDE,+} from '@core/constant/featureFlags';+import type { Accessor } from 'solid-js';++/**+ * Whether a personal tag may be shared with the team. Gates only the entry+ * point — the backend endpoints are ungated, so anything already promoted+ * stays promoted when this is off.+ */+export function useTagTeamSharingFlag(): Accessor<boolean> {+ const flag = useFeatureFlag(ENABLE_TAG_TEAM_SHARING_FLAG, {+ enabledOverride: ENABLE_TAG_TEAM_SHARING_OVERRIDE,+ });+ return () => flag().enabled;+}diff --git a/apps/web/src/features/settings/Tags.tsx b/apps/web/src/features/settings/Tags.tsxindex bf974b4a5d..7a9e14fe4f 100644--- a/apps/web/src/features/settings/Tags.tsx+++ b/apps/web/src/features/settings/Tags.tsx@@ -1,26 +1,33 @@import PencilIcon from '@phosphor/pencil-simple.svg';import PlusIcon from '@phosphor/plus.svg';+import SpinnerIcon from '@phosphor/spinner.svg';import TrashIcon from '@phosphor/trash.svg';+import UsersIcon from '@phosphor/users-three.svg';+import XIcon from '@phosphor/x.svg';import { TagDot } from '@property/tags/TagDot';import {type EditableTag,TagEditorDialog,type TagEditorDialogMode,} from '@property/tags/TagEditorDialog';+import { useTagTeamSharingFlag } from '@property/tags/use-tag-team-sharing-flag';import {useDeletePropertyOptionMutation,+ useMergeTagMutation,+ usePromoteTagMutation,useTagsQuery,} from '@queries/properties/tags';import { useCurrentTeamQuery } from '@queries/team/teams';+import { parseTagNameConflict } from '@service-properties/client';import type { PropertyOptionResponse } from '@service-properties/generated/schemas/propertyOptionResponse';import type { TagScope } from '@service-properties/generated/schemas/tagScope';import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';-import { Button, Tooltip } from '@ui';-import { createMemo, createSignal, For, Show } from 'solid-js';+import { Button, Dialog, Panel, Tooltip } from '@ui';+import { createMemo, createSignal, For, type JSX, Show } from 'solid-js';import { SettingsCard, SettingsPage, SettingsSection } from './primitives';-function optionLabel(option: PropertyOptionResponse): string {- return option.value.type === 'string' ? option.value.value : '';+function optionLabel(option: PropertyOptionResponse | undefined): string {+ return option?.value.type === 'string' ? option.value.value : '';}function sortedOptions(set: TagSetResponse | undefined) {@@ -41,6 +48,12 @@ function tagForOption(};}+/** A pending share blocked by a same-named team label. */+type ShareConflict = {+ tag: EditableTag;+ conflictingOption: PropertyOptionResponse;+};+function EmptyTagRows(props: { scope: TagScope }) {return (<div class="px-6 py-8 text-center text-sm text-ink-extra-muted">@@ -57,7 +70,10 @@ function TagListSection(props: {onCreate: (scope: TagScope) => void;onEdit: (tag: EditableTag) => void;onDelete: (tag: EditableTag) => void;+ /** Omitted when the tag can't be shared (team scope, no team, flag off). */+ onShare?: (tag: EditableTag) => void;deleting?: boolean;+ sharingOptionId?: string;}) {const options = createMemo(() => sortedOptions(props.set));const editable = () => Boolean(props.set?.definition);@@ -97,6 +113,29 @@ function TagListSection(props: {const tag = () => tagForOption(props.scope, set(), option);return (<div class="flex shrink-0 items-center gap-1">+ <Show when={props.onShare}>+ {(onShare) => (+ <Tooltip label="Share with team">+ <button+ type="button"+ aria-label={`Share ${optionLabel(option)} with team`}+ class="flex size-7 shrink-0 items-center justify-center rounded-md text-ink-extra-muted outline-none hover:bg-hover hover:text-ink focus-visible:border focus-visible:border-accent disabled:opacity-30"+ disabled={+ props.deleting ||+ props.sharingOptionId !== undefined+ }+ onClick={() => onShare()(tag())}+ >+ <Show+ when={props.sharingOptionId === option.id}+ fallback={<UsersIcon class="size-4" />}+ >+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </button>+ </Tooltip>+ )}+ </Show><Tooltip label="Edit tag"><buttontype="button"@@ -132,13 +171,78 @@ function TagListSection(props: {);}+/** Panel-shaped confirm dialog, matching the Team tab's action dialogs. */+function ConfirmDialog(props: {+ open: boolean;+ title: string;+ confirmLabel: string;+ pending: boolean;+ onConfirm: () => void;+ onClose: () => void;+ children: JSX.Element;+}) {+ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => !open && !props.pending && props.onClose()}+ >+ <Panel depth={2} class="max-h-[75vh] rounded-xl text-ink">+ <Panel.Header class="gap-1 px-2">+ <Dialog.CloseButton+ as={Button}+ variant="ghost"+ size="icon-sm"+ disabled={props.pending}+ >+ <XIcon />+ </Dialog.CloseButton>+ <Dialog.Title as="span" class="m-0 p-0 text-sm font-medium">+ {props.title}+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="flex flex-col gap-3 p-3">+ <p class="text-sm text-ink-muted">{props.children}</p>+ <div class="flex justify-end gap-1 pt-2">+ <Button+ variant="ghost"+ class="rounded-xs"+ disabled={props.pending}+ onClick={props.onClose}+ >+ Cancel+ </Button>+ <Button+ variant="active"+ class="rounded-xs"+ disabled={props.pending}+ onClick={props.onConfirm}+ >+ <Show when={props.pending} fallback={props.confirmLabel}>+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ </div>+ </Panel.Body>+ </Panel>+ </Dialog>+ );+}+export function Tags() {const tagsQuery = useTagsQuery();const teamQuery = useCurrentTeamQuery();const deleteTag = useDeletePropertyOptionMutation();+ const promoteTag = usePromoteTagMutation();+ const mergeTag = useMergeTagMutation();+ const teamSharingEnabled = useTagTeamSharingFlag();const [editorMode, setEditorMode] = createSignal<TagEditorDialogMode | null>(null);+ const [sharingOptionId, setSharingOptionId] = createSignal<string>();+ const [pendingShare, setPendingShare] = createSignal<EditableTag | null>(+ null+ );+ const [conflict, setConflict] = createSignal<ShareConflict | null>(null);const tagSet = (scope: TagScope) =>tagsQuery.data?.find((set) => set.scope === scope);@@ -162,6 +266,54 @@ export function Tags() {});};+ // Promotion is one-way — there is no un-share endpoint — so it is confirmed+ // before anything moves.+ const shareTag = (tag: EditableTag) => setPendingShare(tag);++ const confirmShare = () => {+ const tag = pendingShare();+ if (!tag) return;++ setSharingOptionId(tag.option.id);+ promoteTag.mutate(+ { optionId: tag.option.id },+ {+ onSettled: () => setSharingOptionId(undefined),+ onSuccess: () => setPendingShare(null),+ onError: (error) => {+ // The mutation stays silent on a name collision so it can be turned+ // into a prompt here; every other failure already toasted.+ const detected = parseTagNameConflict(error);+ setPendingShare(null);+ if (detected) {+ setConflict({+ tag,+ conflictingOption: detected.conflicting_option,+ });+ }+ },+ }+ );+ };++ const confirmMerge = () => {+ const pending = conflict();+ if (!pending) return;++ mergeTag.mutate(+ {+ optionId: pending.tag.option.id,+ targetOptionId: pending.conflictingOption.id,+ },+ {+ onSuccess: () => setConflict(null),+ }+ );+ };++ // Sharing needs a team to share into, and only personal labels can move.+ const canShare = () => teamSharingEnabled() && hasTeam();+return (<SettingsPagetitle="Tags"@@ -185,6 +337,8 @@ export function Tags() {onCreate={openCreate}onEdit={openEdit}onDelete={removeTag}+ onShare={canShare() ? shareTag : undefined}+ sharingOptionId={sharingOptionId()}deleting={deleteTag.isPending}/><Show when={hasTeam()}>@@ -206,6 +360,38 @@ export function Tags() {teamAvailable={hasTeam()}onClose={() => setEditorMode(null)}/>++ <ConfirmDialog+ open={pendingShare() !== null}+ title="Share with team"+ confirmLabel="Share"+ pending={promoteTag.isPending}+ onConfirm={confirmShare}+ onClose={() => setPendingShare(null)}+ >+ <span class="font-medium text-ink">+ {optionLabel(pendingShare()?.option)}+ </span>{' '}+ moves into the {teamName()} team tag set. This action cannot be+ reversed.+ </ConfirmDialog>++ <ConfirmDialog+ open={conflict() !== null}+ title="Team label already exists"+ confirmLabel="Use team label"+ pending={mergeTag.isPending}+ onConfirm={confirmMerge}+ onClose={() => setConflict(null)}+ >+ Your team already has a label named{' '}+ <span class="font-medium text-ink">+ {optionLabel(conflict()?.conflictingOption)}+ </span>+ . Everything tagged with your personal label will be retagged with the+ team's, and your personal label will be removed. This action cannot be+ reversed.+ </ConfirmDialog></SettingsPage>);}diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex e55f6d6117..7dfe3e3884 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -586,3 +586,13 @@ export const ENABLE_CALENDAR_PROMPT_WEB_FLAG = 'enable-calendar-prompt-web';export const ENABLE_CALENDAR_PROMPT_WEB_OVERRIDE = getFeatureFlagOverride('ENABLE_CALENDAR_PROMPT_WEB');++// Sharing a personal tag with the team: the "Share with team" action on+// personal tags in Settings › Tags, and the prompt that merges into an+// existing team label when the names collide. The backend endpoints ship+// ungated, so flipping this off only hides the entry point. PostHog-gated+// with a dev-mode default; override with VITE_ENABLE_TAG_TEAM_SHARING.+export const ENABLE_TAG_TEAM_SHARING_FLAG = 'enable-tag-team-sharing';+export const ENABLE_TAG_TEAM_SHARING_OVERRIDE =+ getFeatureFlagOverride('ENABLE_TAG_TEAM_SHARING') ??+ (DEV_MODE_ENV ? true : undefined);diff --git a/apps/web/src/lib/queries/properties/tags.ts b/apps/web/src/lib/queries/properties/tags.tsindex 008370a40f..5b9fbefde7 100644--- a/apps/web/src/lib/queries/properties/tags.ts+++ b/apps/web/src/lib/queries/properties/tags.ts@@ -2,7 +2,10 @@ import { useIsAuthenticated } from '@core/auth';import { toast } from '@core/component/Toast/Toast';import { thrownResultErrorHasCode, throwOnErr } from '@core/util/result';import { useMutation, useQuery } from '@tanstack/solid-query';-import { propertiesServiceClient } from '../../service-clients/service-properties/client';+import {+ parseTagNameConflict,+ propertiesServiceClient,+} from '../../service-clients/service-properties/client';import type { AddPropertyOptionRequest } from '../../service-clients/service-properties/generated/schemas/addPropertyOptionRequest';import type { EnsureTagSetRequest } from '../../service-clients/service-properties/generated/schemas/ensureTagSetRequest';import type { PropertyOption } from '../../service-clients/service-properties/generated/schemas/propertyOption';@@ -429,3 +432,96 @@ export function useDeletePropertyOptionMutation(),}));}++type PromoteTagParams = {+ /** The personal label being shared with the team. */+ optionId: string;+};++/**+ * Share a personal label with the caller's team.+ *+ * The option id survives the move, so entities already carrying the label keep+ * it — only its owning definition changes. Rejects with a+ * `TAG_NAME_CONFLICT` error carrying the colliding team label when the team+ * already has one by that name; read it with `parseTagNameConflict` and offer+ * {@link useMergeTagMutation} instead.+ */+export function usePromoteTagMutation(+ callbacks?: MutationCallbacks<PropertyOptionResponse, Error, PromoteTagParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: PromoteTagParams) =>+ await throwOnErr(+ async () =>+ await propertiesServiceClient.promoteTag({+ body: { option_id: vars.optionId },+ })+ ),+ ...withCallbacks<PropertyOptionResponse, Error, PromoteTagParams>(+ {+ onError(error) {+ // A name collision is a prompt, not a failure — the caller turns it+ // into the "replace with the team label?" confirmation.+ if (parseTagNameConflict(error)) return;+ console.error('Failed to share label with team', error);+ toast.failure('Failed to share label with team');+ },+ onSuccess: (option) => onTagRemapped(option),+ },+ callbacks+ ),+ }));+}++type MergeTagParams = {+ /** The personal label being retired. */+ optionId: string;+ /** The team label its entities are retagged with. */+ targetOptionId: string;+};++/**+ * Replace a personal label with an existing team label, retagging everything+ * that carried the personal one. The team label's name and color win.+ */+export function useMergeTagMutation(+ callbacks?: MutationCallbacks<PropertyOptionResponse, Error, MergeTagParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: MergeTagParams) =>+ await throwOnErr(+ async () =>+ await propertiesServiceClient.mergeTag({+ body: {+ option_id: vars.optionId,+ target_option_id: vars.targetOptionId,+ },+ })+ ),+ ...withCallbacks<PropertyOptionResponse, Error, MergeTagParams>(+ {+ onError(error) {+ console.error('Failed to replace label with the team label', error);+ toast.failure('Failed to replace label');+ },+ onSuccess: (option) => onTagRemapped(option),+ },+ callbacks+ ),+ }));+}++/**+ * Refresh everything a promote or merge moved.+ *+ * Both rewrite which definition owns the label AND the values stored on every+ * entity that carried it (a merge also swaps the option id), so the cached+ * entity properties behind tag chips, filters and `TagsRow` are stale too —+ * not just the tag sets. There are no WS events for this, so the whole+ * properties namespace is refetched rather than reconciled by hand.+ */+function onTagRemapped(option: PropertyOptionResponse) {+ invalidatePropertyOptions(option.propertyDefinitionId);+ invalidateAllProperties();+}diff --git a/apps/web/src/lib/service-clients/service-properties/client.ts b/apps/web/src/lib/service-clients/service-properties/client.tsindex 08c132fa5b..fc5d530111 100644--- a/apps/web/src/lib/service-clients/service-properties/client.ts+++ b/apps/web/src/lib/service-clients/service-properties/client.ts@@ -5,6 +5,7 @@ import {} from '@core/util/fetchWithToken';import { registerClient } from '@core/util/mockClient';import type { ObjectLike, ResultError } from '@core/util/result';+import { ThrownResultError } from '@core/util/result';import type { SafeFetchInit } from '@core/util/safeFetch';import type { Result } from 'neverthrow';import type { AddPropertyOptionRequest } from './generated/schemas/addPropertyOptionRequest';@@ -17,16 +18,67 @@ import type { EntityPropertiesResponse } from './generated/schemas/entityPropertimport type { GetBulkEntityProperties200 } from './generated/schemas/getBulkEntityProperties200';import type { GetEntityPropertiesParams } from './generated/schemas/getEntityPropertiesParams';import type { ListPropertiesParams } from './generated/schemas/listPropertiesParams';+import type { MergeTagRequest } from './generated/schemas/mergeTagRequest';+import type { PromoteTagRequest } from './generated/schemas/promoteTagRequest';import type { PropertyDefinition } from './generated/schemas/propertyDefinition';import type { PropertyDefinitionResponse } from './generated/schemas/propertyDefinitionResponse';import type { PropertyOption } from './generated/schemas/propertyOption';+import type { PropertyOptionResponse } from './generated/schemas/propertyOptionResponse';import type { PropertyTargetEntityType } from './generated/schemas/propertyTargetEntityType';import type { SetEntityPropertyRequest } from './generated/schemas/setEntityPropertyRequest';+import type { TagPromotionConflictResponse } from './generated/schemas/tagPromotionConflictResponse';import type { TagSetResponse } from './generated/schemas/tagSetResponse';import type { UpdatePropertyOptionRequest } from './generated/schemas/updatePropertyOptionRequest';type PropertiesEntityType = PropertyTargetEntityType;+/**+ * A promote-tag call rejected because the team already owns a label with that+ * name. The colliding label rides along on the error so the caller can prompt+ * with it and then merge into it.+ */+export const TAG_NAME_CONFLICT_CODE = 'TAG_NAME_CONFLICT' as const;++type TagPromoteErrorCode = typeof TAG_NAME_CONFLICT_CODE;++/** safeFetch's default mapping for statuses the custom handler doesn't claim. */+function defaultFetchError(response: Response) {+ switch (response.status) {+ case 401:+ return { code: 'UNAUTHORIZED' as const, message: 'Unauthorized access' };+ case 403:+ return { code: 'FORBIDDEN' as const, message: 'Forbidden' };+ case 404:+ return { code: 'NOT_FOUND' as const, message: 'Resource not found' };+ default:+ return {+ code: 'HTTP_ERROR' as const,+ message: `HTTP error! status: ${response.status}`,+ };+ }+}++/**+ * Recover the colliding team label from a thrown promote error, or `null` when+ * the failure was something else.+ */+export function parseTagNameConflict(+ error: unknown+): TagPromotionConflictResponse | null {+ if (!(error instanceof ThrownResultError)) return null;+ const conflict = error.errors.find(+ (candidate) => candidate.code === TAG_NAME_CONFLICT_CODE+ );+ if (!conflict) return null;++ try {+ const parsed = JSON.parse(conflict.message) as TagPromotionConflictResponse;+ return parsed.conflicting_option ? parsed : null;+ } catch {+ return null;+ }+}+type ListPropertiesArgs = ListPropertiesParams;type CreatePropertyDefinitionArgs = {body: CreatePropertyDefinitionRequest;@@ -76,6 +128,12 @@ type GetBulkEntityPropertiesArgs = {type EnsureTagSetArgs = {body: EnsureTagSetRequest;};+type PromoteTagArgs = {+ body: PromoteTagRequest;+};+type MergeTagArgs = {+ body: MergeTagRequest;+};type UpdatePropertyOptionArgs = {definition_id: string;option_id: string;@@ -257,6 +315,50 @@ export const propertiesServiceClient = {});},+ /**+ * Share a personal label with the caller's team, keeping its option id so+ * everything already tagged stays tagged.+ *+ * A 409 means the team already has a label with that name. The default+ * safeFetch mapping would collapse that to a bare `CONFLICT` and drop the+ * body, so a custom handler carries the colliding label through as JSON for+ * the caller to prompt with (see `parseTagNameConflict`).+ */+ promoteTag: async (args: PromoteTagArgs) => {+ return await fetchWithToken<PropertyOptionResponse, TagPromoteErrorCode>(+ `${propertiesHost}/properties/tags/promote`,+ {+ method: 'POST',+ body: JSON.stringify(args.body),+ errorResponseHandler: async (response) => {+ if (response.status === 409) {+ const body = (await response+ .json()+ .catch(() => null)) as TagPromotionConflictResponse | null;+ if (body?.conflicting_option) {+ return {+ code: TAG_NAME_CONFLICT_CODE,+ message: JSON.stringify(body),+ };+ }+ }+ return defaultFetchError(response);+ },+ }+ );+ },++ /** Replace a personal label with an existing team label, retagging entities. */+ mergeTag: async (args: MergeTagArgs) => {+ return await propertiesFetch<PropertyOptionResponse>(+ `/properties/tags/merge`,+ {+ method: 'POST',+ body: JSON.stringify(args.body),+ }+ );+ },+updatePropertyOption: async (args: UpdatePropertyOptionArgs) => {return await propertiesFetch<PropertyOption>(`/properties/definitions/${args.definition_id}/options/${args.option_id}`,