Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(conversations): add personal reply macros (#127483)

Alex V9662e7504799
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f7c08a422c45..79d0dadcffe3 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -15899,9 +15899,9 @@ snapshots:
scenes-app-support-macros--picker--light:
hash: v1.k794b7964.725b4cd7997538c3cea8f55a8391596eef97beca53f2e5c2fa13bb6b7d7459b1.R20Qy3OtfqfUTqOwd1KMB5qm933nct90nWQql98zSyQ
scenes-app-support-macros--settings--dark:
- hash: v1.k794b7964.fadedf6e8964c23ab41e26181310fb76ca0b9efd151eadeb16734bca0e1ee34d.229Ec2grvKXd99nzmYiS8PU6B9yAA61n_6UKRHpW5L0
+ hash: v1.k794b7964.e17104ac486762148326640cffc7569aaedf783f3e92337052dd0206625e47fe.e8Cdx1c_ToYiu7nDNitnjZye0NbigN7bJ113v2adTL0
scenes-app-support-macros--settings--light:
- hash: v1.k794b7964.face70e5161efd8afc282e5b275484efec0edc6a753199d0e2d1639fa8a5f0ce.xwOoYkUaLh8zfbgob8gjybocWu2MPnoFGmmH7xhHatQ
+ hash: v1.k794b7964.b1ca07a8a3ed7d1a59cdd491cd5960cc240f3246fa94953ad378f04eea40ec8c.NF_7jv4VSIb1-ZfFNXu6mUxjOKN6V2gXlVEVxlVFI4s
scenes-app-support-supportplaybookeditor--customized--dark:
hash: v1.k794b7964.56dd8c26993da8181fb09aa4d9868be1f5925885f1f1854ca38100636acdaaec.yjA6yaERFMxD3ydwD-uPOPa4qSoIgBECHwHq3wOm_1E
scenes-app-support-supportplaybookeditor--customized--light:
diff --git a/products/conversations/backend/activity_logging.py b/products/conversations/backend/activity_logging.py
index 2c2a44683a4b..8b1fa64e424c 100644
--- a/products/conversations/backend/activity_logging.py
+++ b/products/conversations/backend/activity_logging.py
@@ -20,6 +20,14 @@ def handle_ticket_macro_change(
macro = after_update if after_update is not None else before_update
if macro is None:
return
+ # The team reads the activity log, so it never shows the personal side of a macro.
+ personal = TicketMacro.Visibility.PERSONAL
+ if all(m is None or m.visibility == personal for m in (before_update, after_update)):
+ return
+ changes = changes_between("TicketMacro", previous=before_update, current=after_update)
+ if before_update is not None and after_update is not None and before_update.visibility != after_update.visibility:
+ macro = after_update if after_update.visibility != personal else before_update
+ changes = [change for change in changes if change.field == "visibility"]
# Usage bumps go through QuerySet.update, which never reaches this receiver. usage_count and
# last_used_at are also in signal_exclusions, so a save that only touches them stays quiet.
log_activity(
@@ -30,8 +38,5 @@ def handle_ticket_macro_change(
item_id=macro.id,
scope=scope,
activity=activity,
- detail=Detail(
- changes=changes_between("TicketMacro", previous=before_update, current=after_update),
- name=macro.name,
- ),
+ detail=Detail(changes=changes, name=macro.name),
)
diff --git a/products/conversations/backend/api/tests/test_ticket_macros.py b/products/conversations/backend/api/tests/test_ticket_macros.py
index 3b42cb36346e..9799a623fb44 100644
--- a/products/conversations/backend/api/tests/test_ticket_macros.py
+++ b/products/conversations/backend/api/tests/test_ticket_macros.py
@@ -7,6 +7,7 @@ from rest_framework import status
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.team.team import Team
+from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, hash_key_value
from products.access_control.backend.models.access_control import AccessControl
@@ -175,6 +176,75 @@ class TestTicketMacroAPI(APIBaseTest):
assert not TicketMacro.objects.for_team(self.team.id).filter(pk=created["id"]).exists()
assert ActivityLog.objects.filter(scope="TicketMacro", item_id=created["id"], activity="deleted").exists()
+ def test_personal_macro_is_hidden_from_everyone_but_its_creator(self):
+ personal = self._create(name="Mine", shortcut="mine", visibility="personal")
+ shared = self._create(name="Team", shortcut="team")
+ assert personal["visibility"] == "personal"
+ assert shared["visibility"] == "shared"
+ assert not ActivityLog.objects.filter(scope="TicketMacro", item_id=personal["id"]).exists()
+
+ self.client.force_login(User.objects.create_and_join(self.organization, "[email protected]", None))
+ listed = self.client.get(self.base_url).json()["results"]
+ assert [row["name"] for row in listed] == ["Team"]
+ url = f"{self.base_url}{personal['id']}/"
+ assert self.client.get(url).status_code == status.HTTP_404_NOT_FOUND
+ assert self.client.patch(url, {"name": "Taken"}, format="json").status_code == status.HTTP_404_NOT_FOUND
+ assert self.client.post(f"{url}used/").status_code == status.HTTP_404_NOT_FOUND
+
+ @parameterized.expand(
+ [
+ ("teammate_reuses_my_personal_shortcut", "personal", "teammate", "personal", status.HTTP_201_CREATED),
+ ("teammate_shares_my_personal_shortcut", "personal", "teammate", "shared", status.HTTP_201_CREATED),
+ ("teammate_shadows_a_shared_shortcut", "shared", "teammate", "personal", status.HTTP_201_CREATED),
+ ("teammate_reuses_a_shared_shortcut", "shared", "teammate", "shared", status.HTTP_400_BAD_REQUEST),
+ ("i_share_my_personal_shortcut", "personal", "me", "shared", status.HTTP_201_CREATED),
+ ("i_reuse_my_personal_shortcut", "personal", "me", "personal", status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_shortcut_clashes(self, _name, existing_visibility, author, new_visibility, expected_status):
+ self._create(name="Existing", shortcut="hi", visibility=existing_visibility)
+ if author == "teammate":
+ self.client.force_login(User.objects.create_and_join(self.organization, "[email protected]", None))
+ response = self.client.post(
+ self.base_url,
+ {"name": "New", "body": "Hello", "shortcut": "hi", "visibility": new_visibility},
+ format="json",
+ )
+ assert response.status_code == expected_status, response.json()
+
+ def test_hidden_personal_shortcut_never_blocks_an_edit(self):
+ personal = self._create(name="Mine", shortcut="hi", visibility="personal")
+ shared = self._create(name="Shared", shortcut="other")
+
+ self.client.force_login(User.objects.create_and_join(self.organization, "[email protected]", None))
+ response = self.client.patch(f"{self.base_url}{shared['id']}/", {"shortcut": "hi"}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ self.client.force_login(self.user)
+ response = self.client.patch(f"{self.base_url}{personal['id']}/", {"body": "Hey"}, format="json")
+ assert response.status_code == status.HTTP_200_OK, response.json()
+
+ def test_only_the_creator_can_make_a_macro_personal(self):
+ teammate = User.objects.create_and_join(self.organization, "[email protected]", None)
+ theirs = TicketMacro.objects.for_team(self.team.id).create(
+ team=self.team, name="Theirs", body="Hi", created_by=teammate
+ )
+ response = self.client.patch(f"{self.base_url}{theirs.id}/", {"visibility": "personal"}, format="json")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ theirs.refresh_from_db()
+ assert theirs.visibility == "shared"
+
+ mine = self._create()
+ response = self.client.patch(
+ f"{self.base_url}{mine['id']}/", {"visibility": "personal", "name": "Private"}, format="json"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["visibility"] == "personal"
+ log = ActivityLog.objects.filter(scope="TicketMacro", item_id=mine["id"], activity="updated").get()
+ assert log.detail is not None
+ assert log.detail["name"] == "Cancellation"
+ assert [change["field"] for change in log.detail["changes"]] == ["visibility"]
+
def test_editor_grant_on_one_ticket_cannot_edit_macros(self):
created = self._create()
self.organization.available_product_features = [{"key": "access_control", "name": "Access control"}]
diff --git a/products/conversations/backend/api/ticket_macros.py b/products/conversations/backend/api/ticket_macros.py
index 500601f0b045..fbfc694743cb 100644
--- a/products/conversations/backend/api/ticket_macros.py
+++ b/products/conversations/backend/api/ticket_macros.py
@@ -1,7 +1,7 @@
import re
from typing import Any
-from django.db.models import F
+from django.db.models import F, Q
from django.utils import timezone
from drf_spectacular.utils import extend_schema, extend_schema_view
@@ -43,7 +43,8 @@ class TicketMacroSerializer(serializers.ModelSerializer):
allow_null=True,
allow_blank=True,
help_text="Slash command for this macro, without the leading slash. Lowercase letters, numbers, and "
- "hyphens. Unique within the project. Null when the macro has no shortcut.",
+ "hyphens. A shared shortcut is unique among the project's shared macros, and a personal one among "
+ "the creator's personal macros. Null when the macro has no shortcut.",
)
body = serializers.CharField(
max_length=MAX_BODY_LENGTH,
@@ -51,6 +52,12 @@ class TicketMacroSerializer(serializers.ModelSerializer):
"{{customer.email}}, {{agent.first_name}}, {{agent.name}}, and {{ticket.number}}. "
"Variables are filled in when an agent inserts the macro.",
)
+ visibility = serializers.ChoiceField(
+ choices=TicketMacro.Visibility.choices,
+ required=False,
+ help_text="Who can see and use the macro. 'shared' is everyone in the project, the default. "
+ "'personal' is only the person who created it.",
+ )
usage_count = serializers.IntegerField(
read_only=True,
help_text="How many times agents have inserted this macro.",
@@ -68,6 +75,7 @@ class TicketMacroSerializer(serializers.ModelSerializer):
"name",
"shortcut",
"body",
+ "visibility",
"usage_count",
"last_used_at",
"created_at",
@@ -118,13 +126,26 @@ class TicketMacroSerializer(serializers.ModelSerializer):
return data
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ user_id = self.context["request"].user.id
+ owner_id = self.instance.created_by_id if self.instance is not None else user_id
+ visibility = attrs.get("visibility", getattr(self.instance, "visibility", TicketMacro.Visibility.SHARED))
+ if visibility == TicketMacro.Visibility.PERSONAL and (user_id is None or owner_id != user_id):
+ # A personal macro belongs to its creator, so anyone else would make it vanish from the whole team.
+ raise serializers.ValidationError(
+ {"visibility": "Only the person who created this macro can make it personal."}
+ )
+
shortcut = attrs["shortcut"] if "shortcut" in attrs else getattr(self.instance, "shortcut", None)
if shortcut:
- team_id = self.context["team_id"]
- existing = TicketMacro.objects.for_team(team_id).filter(shortcut=shortcut)
+ # Each scope only clashes with itself, so the check never reads another person's personal
+ # macros and cannot reveal their shortcuts. A personal macro here always belongs to the caller.
+ same_scope = Q(visibility=visibility)
+ if visibility == TicketMacro.Visibility.PERSONAL:
+ same_scope &= Q(created_by_id=user_id)
+ clashes = TicketMacro.objects.for_team(self.context["team_id"]).filter(same_scope, shortcut=shortcut)
if self.instance is not None:
- existing = existing.exclude(pk=self.instance.pk)
- if existing.exists():
+ clashes = clashes.exclude(pk=self.instance.pk)
+ if clashes.exists():
raise serializers.ValidationError({"shortcut": "Another macro already uses this shortcut."})
return attrs
@@ -173,8 +194,12 @@ class TicketMacroViewSet(
return self.action in ("create", "partial_update", "destroy")
def safely_get_queryset(self, queryset: Any) -> Any:
+ visible = Q(visibility=TicketMacro.Visibility.SHARED)
+ # Guarded: created_by_id=None would match the personal macros of deleted users.
+ if self.request.user.id is not None:
+ visible |= Q(created_by_id=self.request.user.id)
return (
- queryset.filter(team_id=self.team_id)
+ queryset.filter(visible, team_id=self.team_id)
.select_related("created_by")
.order_by("-usage_count", "-created_at", "-id")
)
@@ -183,7 +208,12 @@ class TicketMacroViewSet(
report_user_action(
self.request.user,
event,
- {"id": str(instance.id), "name": instance.name, "has_shortcut": bool(instance.shortcut)},
+ {
+ "id": str(instance.id),
+ "name": instance.name,
+ "has_shortcut": bool(instance.shortcut),
+ "visibility": instance.visibility,
+ },
team=self.team,
request=self.request,
)
diff --git a/products/conversations/backend/migrations/0080_ticketmacro_visibility.py b/products/conversations/backend/migrations/0080_ticketmacro_visibility.py
new file mode 100644
index 000000000000..08aff9c8e048
--- /dev/null
+++ b/products/conversations/backend/migrations/0080_ticketmacro_visibility.py
@@ -0,0 +1,25 @@
+# Generated by Django 6.1.2 on 2026-11-02 14:11
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("conversations", "0079_ticketmacro"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="ticketmacro",
+ name="visibility",
+ field=models.CharField(
+ choices=[
+ ("shared", "Everyone in the project"),
+ ("personal", "Only the creator"),
+ ],
+ db_default="shared",
+ default="shared",
+ max_length=16,
+ ),
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/0081_ticketmacro_shortcut_per_visibility.py b/products/conversations/backend/migrations/0081_ticketmacro_shortcut_per_visibility.py
new file mode 100644
index 000000000000..373f2e789bc4
--- /dev/null
+++ b/products/conversations/backend/migrations/0081_ticketmacro_shortcut_per_visibility.py
@@ -0,0 +1,60 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import CreateIndexConcurrently, DropIndexConcurrently
+
+TABLE = "posthog_conversations_ticket_macro"
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("conversations", "0080_ticketmacro_visibility"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.RemoveConstraint(model_name="ticketmacro", name="conv_macro_team_shortcut_uniq"),
+ migrations.AddConstraint(
+ model_name="ticketmacro",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(shortcut__isnull=False, visibility="shared"),
+ fields=("team", "shortcut"),
+ name="conv_macro_shared_shortcut_uniq",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="ticketmacro",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(shortcut__isnull=False, visibility="personal"),
+ fields=("team", "created_by", "shortcut"),
+ name="conv_macro_personal_shortcut_uniq",
+ ),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="conv_macro_shared_shortcut_uniq",
+ table_name=TABLE,
+ columns='("team_id", "shortcut")',
+ unique=True,
+ where='WHERE ("shortcut" IS NOT NULL AND "visibility" = \'shared\')',
+ ),
+ CreateIndexConcurrently(
+ index_name="conv_macro_personal_shortcut_uniq",
+ table_name=TABLE,
+ columns='("team_id", "created_by_id", "shortcut")',
+ unique=True,
+ where='WHERE ("shortcut" IS NOT NULL AND "visibility" = \'personal\')',
+ ),
+ DropIndexConcurrently(
+ index_name="conv_macro_team_shortcut_uniq",
+ table_name=TABLE,
+ columns='("team_id", "shortcut")',
+ unique=True,
+ where='WHERE "shortcut" IS NOT NULL',
+ ),
+ ],
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txt
index 9a0054eb34ea..2323db500b49 100644
--- a/products/conversations/backend/migrations/max_migration.txt
+++ b/products/conversations/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0079_ticketmacro
+0081_ticketmacro_shortcut_per_visibility
diff --git a/products/conversations/backend/models/ticket_macro.py b/products/conversations/backend/models/ticket_macro.py
index 0c4f440ccd76..6916923c01d9 100644
--- a/products/conversations/backend/models/ticket_macro.py
+++ b/products/conversations/backend/models/ticket_macro.py
@@ -6,7 +6,11 @@ from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
class TicketMacro(ModelActivityMixin, TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):
- """A shared reply an agent can insert into the ticket composer."""
+ """A saved reply an agent can insert into the ticket composer."""
+
+ class Visibility(models.TextChoices):
+ SHARED = "shared", "Everyone in the project"
+ PERSONAL = "personal", "Only the creator"
activity_logging_on_delete = True
@@ -31,6 +35,12 @@ class TicketMacro(ModelActivityMixin, TeamScopedRootMixin, UUIDModel, CreatedMet
name = models.CharField(max_length=200)
shortcut = models.CharField(max_length=50, null=True, blank=True)
body = models.TextField()
+ visibility = models.CharField(
+ max_length=16,
+ choices=Visibility.choices,
+ default=Visibility.SHARED,
+ db_default=Visibility.SHARED,
+ )
usage_count = models.PositiveIntegerField(default=0, db_default=0)
last_used_at = models.DateTimeField(null=True, blank=True)
@@ -39,10 +49,16 @@ class TicketMacro(ModelActivityMixin, TeamScopedRootMixin, UUIDModel, CreatedMet
db_table = "posthog_conversations_ticket_macro"
constraints = [
# Null shortcuts are not unique: several macros can have no slash command.
+ # A personal shortcut only has to be unique for its creator, so it cannot block teammates.
models.UniqueConstraint(
fields=["team", "shortcut"],
- condition=models.Q(shortcut__isnull=False),
- name="conv_macro_team_shortcut_uniq",
+ condition=models.Q(shortcut__isnull=False, visibility="shared"),
+ name="conv_macro_shared_shortcut_uniq",
+ ),
+ models.UniqueConstraint(
+ fields=["team", "created_by", "shortcut"],
+ condition=models.Q(shortcut__isnull=False, visibility="personal"),
+ name="conv_macro_personal_shortcut_uniq",
),
]
indexes = [
diff --git a/products/conversations/frontend/components/Macros/MacroFormModal.tsx b/products/conversations/frontend/components/Macros/MacroFormModal.tsx
index 256196773f43..e52f59f91f11 100644
--- a/products/conversations/frontend/components/Macros/MacroFormModal.tsx
+++ b/products/conversations/frontend/components/Macros/MacroFormModal.tsx
@@ -1,10 +1,11 @@
import { useActions, useValues } from 'kea'
import { useRef, useState } from 'react'
-import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonModal, LemonSegmentedButton } from '@posthog/lemon-ui'
import { RichContentEditorType } from 'lib/components/RichContentEditor/types'
import { markdownToHtml } from 'lib/utils/markdown'
+import { userLogic } from 'scenes/userLogic'
import { serializeToMarkdown, SupportEditor } from '../Editor'
import { unescapeMacroTokens } from './renderMacro'
@@ -21,8 +22,15 @@ const VARIABLES: { label: string; token: string }[] = [
export function MacroFormModal(): JSX.Element | null {
const { macroDraft, macroSaving } = useValues(supportMacrosLogic)
- const { closeMacroDraft, setMacroDraftName, setMacroDraftShortcut, createMacro, updateMacro } =
- useActions(supportMacrosLogic)
+ const {
+ closeMacroDraft,
+ setMacroDraftName,
+ setMacroDraftShortcut,
+ setMacroDraftVisibility,
+ createMacro,
+ updateMacro,
+ } = useActions(supportMacrosLogic)
+ const { user } = useValues(userLogic)
const editorRef = useRef<RichContentEditorType | null>(null)
const draftKey = macroDraft ? (macroDraft.id ?? 'new') : ''
const bodyEmptyDefault = !(macroDraft?.body ?? '').trim()
@@ -38,6 +46,8 @@ export function MacroFormModal(): JSX.Element | null {
if (!macroDraft) {
return null
}
+ // An existing macro whose creator is deleted has no owner, so nobody can make it personal.
+ const isSomeoneElses = macroDraft.id !== null && macroDraft.createdById !== user?.id
const save = (): void => {
const editor = editorRef.current
@@ -52,7 +62,12 @@ export function MacroFormModal(): JSX.Element | null {
if (shortcutError(macroDraft.shortcut)) {
return
}
- const payload = { name: macroDraft.name, shortcut: macroDraft.shortcut, body }
+ const payload = {
+ name: macroDraft.name,
+ shortcut: macroDraft.shortcut,
+ body,
+ visibility: macroDraft.visibility,
+ }
if (macroDraft.id) {
updateMacro({ ...payload, id: macroDraft.id })
} else {
@@ -107,6 +122,25 @@ export function MacroFormModal(): JSX.Element | null {
Letters, numbers, and hyphens. Leave this blank to keep the macro in the menu only. Agents insert it
by typing / followed by the shortcut.
</p>
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-sm">Visible to</span>
+ <LemonSegmentedButton
+ size="small"
+ value={macroDraft.visibility}
+ onChange={setMacroDraftVisibility}
+ options={[
+ { value: 'shared', label: 'Everyone' },
+ {
+ value: 'personal',
+ label: 'Only me',
+ disabledReason: isSomeoneElses
+ ? 'Only the person who created this macro can make it personal'
+ : undefined,
+ },
+ ]}
+ data-attr="support-macro-visibility"
+ />
+ </div>
<SupportEditor
key={macroDraft.id ?? 'new'}
initialContent={null}
diff --git a/products/conversations/frontend/components/Macros/MacroPicker.tsx b/products/conversations/frontend/components/Macros/MacroPicker.tsx
index 0ee9a6c92a61..84a767496927 100644
--- a/products/conversations/frontend/components/Macros/MacroPicker.tsx
+++ b/products/conversations/frontend/components/Macros/MacroPicker.tsx
@@ -58,6 +58,9 @@ export function MacroPicker({
{macro.shortcut ? (
<span className="shrink-0 text-xs text-muted">/{macro.shortcut}</span>
) : null}
+ {macro.visibility === 'personal' ? (
+ <span className="shrink-0 text-xs text-muted">Only you</span>
+ ) : null}
</span>
<span className="max-w-full truncate text-xs text-muted">{macroPreview(macro.body)}</span>
</span>
diff --git a/products/conversations/frontend/components/Macros/MacroSuggestionExtension.tsx b/products/conversations/frontend/components/Macros/MacroSuggestionExtension.tsx
index 1bb54d8d7d2d..4ff0d16bee36 100644
--- a/products/conversations/frontend/components/Macros/MacroSuggestionExtension.tsx
+++ b/products/conversations/frontend/components/Macros/MacroSuggestionExtension.tsx
@@ -42,6 +42,9 @@ function MacroSuggestionPanel({ range, query, editor, onInsert, onClose }: Macro
<span className="truncate">
{macro.name}
{macro.shortcut ? <span className="text-muted"> /{macro.shortcut}</span> : null}
+ {macro.visibility === 'personal' ? (
+ <span className="text-muted"> · Only you</span>
+ ) : null}
</span>
<span className="max-w-full truncate text-xs text-muted">{macroPreview(macro.body)}</span>
</span>
diff --git a/products/conversations/frontend/components/Macros/renderMacro.test.ts b/products/conversations/frontend/components/Macros/renderMacro.test.ts
index d2c7f13ac32a..07ede8df500d 100644
--- a/products/conversations/frontend/components/Macros/renderMacro.test.ts
+++ b/products/conversations/frontend/components/Macros/renderMacro.test.ts
@@ -61,17 +61,19 @@ describe('support macros', () => {
})
test.each([
- ['refund', ['refund', 'refund-partial', 'Refund policy']],
- ['ref', ['refund-partial', 'refund', 'Refund policy']],
+ ['refund', ['My refund', 'Full refund', 'Partial refund', 'Refund policy']],
+ ['ref', ['Partial refund', 'Full refund', 'My refund', 'Refund policy']],
['policy', ['Refund policy']],
])('ranks matches for %s', (query, expected) => {
- // Input is most used first, so an exact shortcut must outrank a more used prefix match.
+ // Input is most used first, so an exact shortcut must outrank a more used prefix match,
+ // and your personal macro must outrank a teammate's shared one on the same shortcut.
const macros = [
- { id: '1', name: 'Partial refund', shortcut: 'refund-partial' },
- { id: '2', name: 'Refund policy', shortcut: null },
- { id: '3', name: 'Full refund', shortcut: 'refund' },
+ { id: '1', name: 'Partial refund', shortcut: 'refund-partial', visibility: 'shared' },
+ { id: '2', name: 'Refund policy', shortcut: null, visibility: 'shared' },
+ { id: '3', name: 'Full refund', shortcut: 'refund', visibility: 'shared' },
+ { id: '4', name: 'My refund', shortcut: 'refund', visibility: 'personal' },
] as unknown as TicketMacroApi[]
- expect(matchMacros(macros, query).map((macro) => macro.shortcut ?? macro.name)).toEqual(expected)
+ expect(matchMacros(macros, query).map((macro) => macro.name)).toEqual(expected)
})
it('does not treat an email address as a first name', () => {
diff --git a/products/conversations/frontend/components/Macros/renderMacro.ts b/products/conversations/frontend/components/Macros/renderMacro.ts
index 29013d1b9ae1..18041532c838 100644
--- a/products/conversations/frontend/components/Macros/renderMacro.ts
+++ b/products/conversations/frontend/components/Macros/renderMacro.ts
@@ -107,16 +107,17 @@ export function macroPreview(body: string): string {
function matchRank(macro: TicketMacroApi, needle: string): number | null {
const shortcut = macro.shortcut ?? ''
if (shortcut === needle) {
- return 0
+ // A teammate can share a shortcut you already use personally. Yours wins for you.
+ return macro.visibility === 'personal' ? 0 : 1
}
if (shortcut.startsWith(needle)) {
- return 1
+ return 2
}
if (macro.name.toLowerCase().includes(needle)) {
- return 2
+ return 3
}
if (shortcut.includes(needle)) {
- return 3
+ return 4
}
return null
}
diff --git a/products/conversations/frontend/components/Macros/supportMacrosLogic.ts b/products/conversations/frontend/components/Macros/supportMacrosLogic.ts
index 8cbe891b0ae6..94c3b533038d 100644
--- a/products/conversations/frontend/components/Macros/supportMacrosLogic.ts
+++ b/products/conversations/frontend/components/Macros/supportMacrosLogic.ts
@@ -18,17 +18,23 @@ import type { TicketMacroApi } from 'products/conversations/frontend/generated/a
const SHORTCUT_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
+export type MacroVisibility = NonNullable<TicketMacroApi['visibility']>
+
export interface MacroDraft {
id: string | null
name: string
shortcut: string
body: string
+ visibility: MacroVisibility
+ /** Null for a new macro. */
+ createdById: number | null
}
export interface MacroSavePayload {
name: string
shortcut: string
body: string
+ visibility: MacroVisibility
}
function normalizeShortcut(shortcut: string): string | null {
@@ -119,6 +125,9 @@ export interface supportMacrosLogicActions {
setMacroDraftShortcut: (shortcut: string) => {
shortcut: string
}
+ setMacroDraftVisibility: (visibility: MacroVisibility) => {
+ visibility: MacroVisibility
+ }
setMacroSaving: (saving: boolean) => {
saving: boolean
}
@@ -165,6 +174,7 @@ export const supportMacrosLogic = kea<supportMacrosLogicType>([
closeMacroDraft: true,
setMacroDraftName: (name: string) => ({ name }),
setMacroDraftShortcut: (shortcut: string) => ({ shortcut }),
+ setMacroDraftVisibility: (visibility: MacroVisibility) => ({ visibility }),
setMacroSaving: (saving: boolean) => ({ saving }),
ensureMacrosLoaded: true,
}),
@@ -216,10 +226,13 @@ export const supportMacrosLogic = kea<supportMacrosLogicType>([
name: macro?.name ?? '',
shortcut: macro?.shortcut ?? '',
body: macro?.body ?? '',
+ visibility: macro?.visibility ?? 'shared',
+ createdById: macro?.created_by?.id ?? null,
}),
closeMacroDraft: () => null,
setMacroDraftName: (state, { name }) => (state ? { ...state, name } : state),
setMacroDraftShortcut: (state, { shortcut }) => (state ? { ...state, shortcut } : state),
+ setMacroDraftVisibility: (state, { visibility }) => (state ? { ...state, visibility } : state),
},
],
macroSaving: [
@@ -261,7 +274,7 @@ export const supportMacrosLogic = kea<supportMacrosLogicType>([
[featureFlagLogic.actionTypes.setFeatureFlags]: () => {
actions.ensureMacrosLoaded()
},
- createMacro: async ({ name, shortcut, body }) => {
+ createMacro: async ({ name, shortcut, body, visibility }) => {
if (!values.currentTeamId) {
return
}
@@ -276,6 +289,7 @@ export const supportMacrosLogic = kea<supportMacrosLogicType>([
name: name.trim(),
shortcut: normalizeShortcut(shortcut),
body,
+ visibility,
})
actions.upsertMacro(created)
actions.closeMacroDraft()
@@ -286,7 +300,7 @@ export const supportMacrosLogic = kea<supportMacrosLogicType>([
actions.setMacroSaving(false)
}
},
- updateMacro: async ({ id, name, shortcut, body }) => {
+ updateMacro: async ({ id, name, shortcut, body, visibility }) => {
if (!values.currentTeamId) {
return
}
@@ -301,6 +315,7 @@ export const supportMacrosLogic = kea<supportMacrosLogicType>([
name: name.trim(),
shortcut: normalizeShortcut(shortcut),
body,
+ visibility,
})
actions.upsertMacro(updated)
actions.closeMacroDraft()
diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.ts
index afa188caee32..4060de9c3c69 100644
--- a/products/conversations/frontend/generated/api.schemas.ts
+++ b/products/conversations/frontend/generated/api.schemas.ts
@@ -40,6 +40,18 @@ export interface AIReplyPlaybookApi {
readonly max_chars: number
}
+/**
+ * * `shared` - Everyone in the project
+ * * `personal` - Only the creator
+ */
+export type TicketMacroVisibilityEnumApi =
+ (typeof TicketMacroVisibilityEnumApi)[keyof typeof TicketMacroVisibilityEnumApi]
+
+export const TicketMacroVisibilityEnumApi = {
+ Shared: 'shared',
+ Personal: 'personal',
+} as const
+
/**
* * `engineering` - Engineering
* * `data` - Data
@@ -106,7 +118,7 @@ export interface TicketMacroApi {
*/
name: string
/**
- * Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. Unique within the project. Null when the macro has no shortcut.
+ * Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. A shared shortcut is unique among the project's shared macros, and a personal one among the creator's personal macros. Null when the macro has no shortcut.
* @maxLength 50
* @nullable
*/
@@ -116,6 +128,11 @@ export interface TicketMacroApi {
* @maxLength 10000
*/
body: string
+ /** Who can see and use the macro. 'shared' is everyone in the project, the default. 'personal' is only the person who created it.
+ *
+ * * `shared` - Everyone in the project
+ * * `personal` - Only the creator */
+ visibility?: TicketMacroVisibilityEnumApi
/** How many times agents have inserted this macro. */
readonly usage_count: number
/**
@@ -152,7 +169,7 @@ export interface PatchedTicketMacroApi {
*/
name?: string
/**
- * Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. Unique within the project. Null when the macro has no shortcut.
+ * Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. A shared shortcut is unique among the project's shared macros, and a personal one among the creator's personal macros. Null when the macro has no shortcut.
* @maxLength 50
* @nullable
*/
@@ -162,6 +179,11 @@ export interface PatchedTicketMacroApi {
* @maxLength 10000
*/
body?: string
+ /** Who can see and use the macro. 'shared' is everyone in the project, the default. 'personal' is only the person who created it.
+ *
+ * * `shared` - Everyone in the project
+ * * `personal` - Only the creator */
+ visibility?: TicketMacroVisibilityEnumApi
/** How many times agents have inserted this macro. */
readonly usage_count?: number
/**
diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.ts
index fae75a95e0cf..493900695f9a 100644
--- a/products/conversations/frontend/generated/api.zod.ts
+++ b/products/conversations/frontend/generated/api.zod.ts
@@ -25,7 +25,7 @@ export const ConversationsMacrosCreateBody = /* @__PURE__ */ zod.object({
.max(conversationsMacrosCreateBodyShortcutMax)
.nullish()
.describe(
- 'Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. Unique within the project. Null when the macro has no shortcut.'
+ "Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. A shared shortcut is unique among the project's shared macros, and a personal one among the creator's personal macros. Null when the macro has no shortcut."
),
body: zod
.string()
@@ -33,6 +33,13 @@ export const ConversationsMacrosCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Reply text in markdown. May contain {{customer.first_name}}, {{customer.name}}, {{customer.email}}, {{agent.first_name}}, {{agent.name}}, and {{ticket.number}}. Variables are filled in when an agent inserts the macro.'
),
+ visibility: zod
+ .enum(['shared', 'personal'])
+ .describe('\* `shared` - Everyone in the project\n\* `personal` - Only the creator')
+ .optional()
+ .describe(
+ "Who can see and use the macro. 'shared' is everyone in the project, the default. 'personal' is only the person who created it.\n\n\* `shared` - Everyone in the project\n\* `personal` - Only the creator"
+ ),
})
export const conversationsMacrosPartialUpdateBodyNameMax = 200
@@ -52,7 +59,7 @@ export const ConversationsMacrosPartialUpdateBody = /* @__PURE__ */ zod.object({
.max(conversationsMacrosPartialUpdateBodyShortcutMax)
.nullish()
.describe(
- 'Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. Unique within the project. Null when the macro has no shortcut.'
+ "Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. A shared shortcut is unique among the project's shared macros, and a personal one among the creator's personal macros. Null when the macro has no shortcut."
),
body: zod
.string()
@@ -61,6 +68,13 @@ export const ConversationsMacrosPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'Reply text in markdown. May contain {{customer.first_name}}, {{customer.name}}, {{customer.email}}, {{agent.first_name}}, {{agent.name}}, and {{ticket.number}}. Variables are filled in when an agent inserts the macro.'
),
+ visibility: zod
+ .enum(['shared', 'personal'])
+ .describe('\* `shared` - Everyone in the project\n\* `personal` - Only the creator')
+ .optional()
+ .describe(
+ "Who can see and use the macro. 'shared' is everyone in the project, the default. 'personal' is only the person who created it.\n\n\* `shared` - Everyone in the project\n\* `personal` - Only the creator"
+ ),
})
/**
diff --git a/products/conversations/frontend/scenes/settings/MacrosSection.tsx b/products/conversations/frontend/scenes/settings/MacrosSection.tsx
index d898a35b9fc5..02cad095c06e 100644
--- a/products/conversations/frontend/scenes/settings/MacrosSection.tsx
+++ b/products/conversations/frontend/scenes/settings/MacrosSection.tsx
@@ -25,6 +25,11 @@ export function MacrosSection(): JSX.Element {
dataIndex: 'shortcut',
render: (_, macro) => (macro.shortcut ? `/${macro.shortcut}` : ''),
},
+ {
+ title: 'Visible to',
+ dataIndex: 'visibility',
+ render: (_, macro) => (macro.visibility === 'personal' ? 'Only you' : 'Everyone'),
+ },
{
title: 'Uses',
dataIndex: 'usage_count',
@@ -54,7 +59,10 @@ export function MacrosSection(): JSX.Element {
onClick={() =>
LemonDialog.open({
title: 'Delete this macro?',
- description: 'People on your team will no longer be able to insert it.',
+ description:
+ macro.visibility === 'personal'
+ ? "You won't be able to insert it anymore."
+ : 'People on your team will no longer be able to insert it.',
primaryButton: {
children: 'Delete',
status: 'danger',
@@ -73,7 +81,8 @@ export function MacrosSection(): JSX.Element {
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="mb-0 text-sm text-muted">
- Save replies you send often. Insert one from a ticket, or type / and its shortcut.
+ Save replies you send often. Share them with your team or keep them to yourself. Insert one from a
+ ticket, or type / and its shortcut.
</p>
<LemonButton
type="primary"
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
index 903b4461574a..93ce385ced3e 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
@@ -400,10 +400,10 @@ export interface supportTicketSceneLogicActions {
value: true
}
insertMacro: (
- macro: Pick<TicketMacroApi, 'body' | 'id'>,
+ macro: Pick<TicketMacroApi, 'body' | 'id' | 'visibility'>,
source: 'button' | 'slash'
) => {
- macro: Pick<TicketMacroApi, 'body' | 'id'>
+ macro: Pick<TicketMacroApi, 'body' | 'id' | 'visibility'>
source: 'button' | 'slash'
}
loadFullEmail: (messageId: string) => string
@@ -702,7 +702,10 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
applyAiDraft: (message: ChatMessage) => ({ message }),
setAiDraftApplying: (applying: boolean) => ({ applying }),
bumpComposerPrefill: true,
- insertMacro: (macro: Pick<TicketMacroApi, 'id' | 'body'>, source: 'button' | 'slash') => ({ macro, source }),
+ insertMacro: (macro: Pick<TicketMacroApi, 'id' | 'body' | 'visibility'>, source: 'button' | 'slash') => ({
+ macro,
+ source,
+ }),
setPendingComposerInsert: (content: string | null) => ({ content }),
bumpComposerInsert: true,
@@ -1741,7 +1744,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
renderMacro(macro.body, macroContextFromTicket(values.ticket, values.user))
)
actions.bumpComposerInsert()
- posthog.capture('support macro inserted', { macro_id: macro.id, source })
+ posthog.capture('support macro inserted', { macro_id: macro.id, source, visibility: macro.visibility })
const teamId = getCurrentTeamId()
if (!teamId) {
return
diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yaml
index 227b096e0f63..5a7bc746cafa 100644
--- a/products/conversations/mcp/tools.yaml
+++ b/products/conversations/mcp/tools.yaml
@@ -19,10 +19,11 @@ tools:
list: true
title: List support macros
description: >
- List the shared reply macros in the project, most used first. A macro is a saved reply an agent inserts into
- a ticket. The body is markdown and may contain customer, agent, and ticket variables in double braces. Fill
- those in for the current ticket before sending the reply. shortcut is the slash command without the leading
- slash, or null when the macro has none.
+ List the reply macros the caller can use, most used first: the macros shared with the project, plus the
+ caller's personal macros (visibility 'personal'). A macro is a saved reply an agent inserts into a ticket.
+ The body is markdown and may contain customer, agent, and ticket variables in double braces. Fill those in
+ for the current ticket before sending the reply. shortcut is the slash command without the leading slash, or
+ null when the macro has none.
feature_flag: support-macros
response:
include:
@@ -30,6 +31,7 @@ tools:
- name
- shortcut
- body
+ - visibility
- usage_count
informational_wrapper:
tag: support-macro-data
@@ -59,6 +61,7 @@ tools:
- name
- shortcut
- body
+ - visibility
- usage_count
- last_used_at
informational_wrapper:
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 34a443be341d..0d832b849da5 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3331,7 +3331,7 @@
}
},
"conversations-macros-list": {
- "description": "List the shared reply macros in the project, most used first. A macro is a saved reply an agent inserts into a ticket. The body is markdown and may contain customer, agent, and ticket variables in double braces. Fill those in for the current ticket before sending the reply. shortcut is the slash command without the leading slash, or null when the macro has none.",
+ "description": "List the reply macros the caller can use, most used first: the macros shared with the project, plus the caller's personal macros (visibility 'personal'). A macro is a saved reply an agent inserts into a ticket. The body is markdown and may contain customer, agent, and ticket variables in double braces. Fill those in for the current ticket before sending the reply. shortcut is the slash command without the leading slash, or null when the macro has none.",
"category": "Conversations",
"feature": "conversations",
"summary": "List support macros",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index a3598f273977..b5e1a2b5e12e 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3346,7 +3346,7 @@
}
},
"conversations-macros-list": {
- "description": "List the shared reply macros in the project, most used first. A macro is a saved reply an agent inserts into a ticket. The body is markdown and may contain customer, agent, and ticket variables in double braces. Fill those in for the current ticket before sending the reply. shortcut is the slash command without the leading slash, or null when the macro has none.",
+ "description": "List the reply macros the caller can use, most used first: the macros shared with the project, plus the caller's personal macros (visibility 'personal'). A macro is a saved reply an agent inserts into a ticket. The body is markdown and may contain customer, agent, and ticket variables in double braces. Fill those in for the current ticket before sending the reply. shortcut is the slash command without the leading slash, or null when the macro has none.",
"category": "Conversations",
"feature": "conversations",
"summary": "List support macros",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2e5176ff15ba..1c827e27fcdc 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -83756,6 +83756,18 @@ export namespace Schemas {
results: Ticket[];
}
+ /**
+ * * `shared` - Everyone in the project
+ * * `personal` - Only the creator
+ */
+ export type TicketMacroVisibilityEnum = typeof TicketMacroVisibilityEnum[keyof typeof TicketMacroVisibilityEnum];
+
+
+ export const TicketMacroVisibilityEnum = {
+ Shared: 'shared',
+ Personal: 'personal',
+ } as const;
+
export interface TicketMacro {
/** UUID of the macro. */
readonly id: string;
@@ -83765,7 +83777,7 @@ export namespace Schemas {
*/
name: string;
/**
- * Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. Unique within the project. Null when the macro has no shortcut.
+ * Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. A shared shortcut is unique among the project's shared macros, and a personal one among the creator's personal macros. Null when the macro has no shortcut.
* @maxLength 50
* @nullable
*/
@@ -83775,6 +83787,11 @@ export namespace Schemas {
* @maxLength 10000
*/
body: string;
+ /** Who can see and use the macro. 'shared' is everyone in the project, the default. 'personal' is only the person who created it.
+ *
+ * * `shared` - Everyone in the project
+ * * `personal` - Only the creator */
+ visibility?: TicketMacroVisibilityEnum;
/** How many times agents have inserted this macro. */
readonly usage_count: number;
/**
@@ -95301,7 +95318,7 @@ export namespace Schemas {
*/
name?: string;
/**
- * Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. Unique within the project. Null when the macro has no shortcut.
+ * Slash command for this macro, without the leading slash. Lowercase letters, numbers, and hyphens. A shared shortcut is unique among the project's shared macros, and a personal one among the creator's personal macros. Null when the macro has no shortcut.
* @maxLength 50
* @nullable
*/
@@ -95311,6 +95328,11 @@ export namespace Schemas {
* @maxLength 10000
*/
body?: string;
+ /** Who can see and use the macro. 'shared' is everyone in the project, the default. 'personal' is only the person who created it.
+ *
+ * * `shared` - Everyone in the project
+ * * `personal` - Only the creator */
+ visibility?: TicketMacroVisibilityEnum;
/** How many times agents have inserted this macro. */
readonly usage_count?: number;
/**
diff --git a/services/mcp/src/tools/generated/conversations.ts b/services/mcp/src/tools/generated/conversations.ts
index 99e76b7b9fda..8897f152a0a4 100644
--- a/services/mcp/src/tools/generated/conversations.ts
+++ b/services/mcp/src/tools/generated/conversations.ts
@@ -38,7 +38,7 @@ const conversationsMacrosList = (): ToolBase<
const filtered = {
...result,
results: (result.results ?? []).map((item: any) =>
- pickResponseFields(item, ['id', 'name', 'shortcut', 'body', 'usage_count'])
+ pickResponseFields(item, ['id', 'name', 'shortcut', 'body', 'visibility', 'usage_count'])
),
} as typeof result
return withInformationalResponse(
@@ -75,6 +75,7 @@ const conversationsMacrosRetrieve = (): ToolBase<
'name',
'shortcut',
'body',
+ 'visibility',
'usage_count',
'last_used_at',
]) as typeof result