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.

fix(skills): gate the public skill share behind consent (#99231)

posthog[bot]1778f9a793a5
diff --git a/docs/internal/skills/community-skills-api.md b/docs/internal/skills/community-skills-api.md
index f0e8f79252bc..2040e9fc5ad5 100644
--- a/docs/internal/skills/community-skills-api.md
+++ b/docs/internal/skills/community-skills-api.md
@@ -79,6 +79,11 @@ Lives on `LLMSkillViewSet` (`products/skills/backend/api/skills.py`), not the co
because the subject is a team-owned skill.
Rendering and the GitHub calls are in `community_publish_services.py`.
+Callers must first retrieve the latest skill and show its version and file manifest to the publisher.
+The publish request must include the retrieved row's `id` as `expected_skill_id` and its numeric
+`version` as `expected_version`. The API returns `409` if either value differs from the latest row.
+After a conflict, retrieve the skill again and require new consent before another publish request.
+
- Gated by `CommunityPublishFeatureFlagPermission`, which applies the same
`llm-analytics-community-skills` check as the browse endpoints to this action alone. Skills is GA,
so the flag cannot sit on the viewset.
@@ -183,10 +188,10 @@ Adding an owner is the remedy. There is no exemption for project or organization
wants to publish adds themselves as an owner first.
Errors surface as `400` (invalid payload), `403` (the requester does not own the skill, or it has no
-owners), `404` (unknown skill), `502` (GitHub refused a step), or `503` when the instance has no
-publisher App configured. The 503 is the fail-safe that keeps publishing off until the GitHub App is
-installed. A private key that cannot sign is a 503 too: it is a deployment nobody can retry their way
-out of, so it must not read as GitHub being down.
+owners), `404` (unknown skill), `409` (the reviewed skill row is no longer latest), `502` (GitHub
+refused a step), or `503` when the instance has no publisher App configured. The 503 is the fail-safe
+that keeps publishing off until the GitHub App is installed. A private key that cannot sign is a 503
+too: it is a deployment nobody can retry their way out of, so it must not read as GitHub being down.
The three are kept apart on purpose, because each sends the publisher somewhere different. The skill
is rendered before GitHub is touched, so a skill that has to be edited answers `400` even while the
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index aa8c59184ca7..582a0cd62c8f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6721,9 +6721,9 @@ snapshots:
scenes-app-ai-observability-skills--skill-detail-stacked-below-2-xl-breakpoint--wide--light:
hash: v1.k794b7964.4ce94e0415732ee8ee483b5be5eeffeda8b33ca70444bebe8ccaaef858159540.9XEuH7i8VEm-twy2jenDX5dusdL7ZUbxFYyTSsU_LPM
scenes-app-ai-observability-skills--skills-list--dark:
- hash: v1.k794b7964.5f1884413c0c96dc63183fb7a32db8800aaff3919dc2df83fd80529a566cee8d.tvTf-dU6lFhAm8TR6j7CZKNqm-jcpBUgxey0PGK7nuI
+ hash: v1.k794b7964.ef922a0a06bf1db7141ffa5dda43e7106b3eec562f4dc4c0996b817b8e55b3be.Ij1-WjXoREtj3yIYkzbXuRg-ccNy-NPBUBW_31tlfRw
scenes-app-ai-observability-skills--skills-list--light:
- hash: v1.k794b7964.be983851dd216dffb0f8cdd9df2de912fa9d477a821e66eee7b1f82bd0000ca6.aiGZU3HoH-JsbDcEul_7etKK6iVsTktb0ZxZ2_vmfOk
+ hash: v1.k794b7964.d22fb946238114580130ed5d5978b187d6acd086868d1ebb8e326e02c65fc6f5.W7RfUzTvMqZEzuRPjF2h0XXTftd4X0bauTIRZAc48qk
scenes-app-ai-observability-trace--full--dark:
hash: v1.k794b7964.142fc550717f2be0bc0c72f8b670fb5b70f1be8cf26ae2805e4a6ae6937c06a5.ms9_vuzQ5yFxSSCaQtMJLVHBMBR0fIKrrKJhivb5Zfg
scenes-app-ai-observability-trace--full--light:
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 54b37b2a5278..26c8e7410f33 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4632,6 +4632,9 @@ importers:
'@storybook/react':
specifier: 'catalog:'
+ '@testing-library/react':
+ specifier: ^14.3.1
kea-test-utils:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
diff --git a/products/skills/backend/api/skill_serializers.py b/products/skills/backend/api/skill_serializers.py
index 936c2fb3aaf2..14d24386bc23 100644
--- a/products/skills/backend/api/skill_serializers.py
+++ b/products/skills/backend/api/skill_serializers.py
@@ -994,6 +994,13 @@ class LLMSkillMarketplaceCommandSerializer(serializers.Serializer):
class LLMSkillPublishToCommunitySerializer(serializers.Serializer):
+ expected_skill_id = serializers.UUIDField(
+ help_text="Immutable ID of the skill version that the publisher reviewed."
+ )
+ expected_version = serializers.IntegerField(
+ min_value=1,
+ help_text="Skill version that the publisher reviewed. The request returns 409 if the latest version changed.",
+ )
display_name = serializers.RegexField(
DISPLAY_NAME_PATTERN,
required=False,
@@ -1023,6 +1030,10 @@ class LLMSkillPublishToCommunitySerializer(serializers.Serializer):
)
+class LLMSkillPublishConflictSerializer(serializers.Serializer):
+ detail = serializers.CharField(help_text="Reason that the reviewed skill version can no longer be published.")
+
+
class CommunitySkillPublishResultSerializer(serializers.Serializer):
pr_url = serializers.URLField(
help_text="URL of the pull request opened in the community-skills repo for maintainer review."
diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.py
index 53d2a17e240b..4f402608e0fd 100644
--- a/products/skills/backend/api/skills.py
+++ b/products/skills/backend/api/skills.py
@@ -85,6 +85,7 @@ from .skill_serializers import (
LLMSkillListSerializer,
LLMSkillMarketplaceCommandSerializer,
LLMSkillMarketplaceIssueSerializer,
+ LLMSkillPublishConflictSerializer,
LLMSkillPublishSerializer,
LLMSkillPublishToCommunitySerializer,
LLMSkillRenameSerializer,
@@ -1476,7 +1477,10 @@ class LLMSkillViewSet(
)
return Response(self._serialize_skill(renamed_skill))
- @extend_schema(request=LLMSkillPublishToCommunitySerializer, responses={201: CommunitySkillPublishResultSerializer})
+ @extend_schema(
+ request=LLMSkillPublishToCommunitySerializer,
+ responses={201: CommunitySkillPublishResultSerializer, 409: LLMSkillPublishConflictSerializer},
+ )
@action(
methods=["POST"],
detail=False,
@@ -1497,6 +1501,17 @@ class LLMSkillViewSet(
payload = LLMSkillPublishToCommunitySerializer(data=request.data)
payload.is_valid(raise_exception=True)
+ if (
+ skill.id != payload.validated_data["expected_skill_id"]
+ or skill.version != payload.validated_data["expected_version"]
+ ):
+ return Response(
+ {
+ "detail": "This skill changed after you reviewed it. Reopen the dialog and review the latest version."
+ },
+ status=status.HTTP_409_CONFLICT,
+ )
+
files = [{"path": f.path, "content": f.content, "content_type": f.content_type} for f in skill.files.all()]
supplied_tags = payload.validated_data.get("tags")
# An explicit empty list means "publish with no tags", so fall back to the skill's own tags
diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.py
index ca33de761cca..4adba6c70bbe 100644
--- a/products/skills/backend/api/test/test_skills.py
+++ b/products/skills/backend/api/test/test_skills.py
@@ -1694,7 +1694,7 @@ class TestLLMSkillAPI(APIBaseTest):
response = self.client.post(
self._url("name/make-pr/publish-community"),
- data={"author_handle": "andymaguire"},
+ data={"expected_skill_id": str(skill.id), "expected_version": 1, "author_handle": "andymaguire"},
format="json",
)
@@ -1729,9 +1729,13 @@ class TestLLMSkillAPI(APIBaseTest):
self, _label: str, payload: dict, metadata_tags: list, expected: list, mock_publish, _mock_flag
):
mock_publish.return_value = {"pr_url": "https://github.com/x/y/pull/1", "pr_number": 1, "branch": "b"}
- self.create_skill(name="make-pr", metadata={"tags": metadata_tags})
+ skill = self.create_skill(name="make-pr", metadata={"tags": metadata_tags})
- response = self.client.post(self._url("name/make-pr/publish-community"), data=payload, format="json")
+ response = self.client.post(
+ self._url("name/make-pr/publish-community"),
+ data={"expected_skill_id": str(skill.id), "expected_version": 1, **payload},
+ format="json",
+ )
assert response.status_code == status.HTTP_201_CREATED
assert mock_publish.call_args.kwargs["tags"] == expected
@@ -1744,6 +1748,39 @@ class TestLLMSkillAPI(APIBaseTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
mock_publish.assert_not_called()
+ @patch(COMMUNITY_FLAG, return_value=True)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_rejects_a_version_that_the_publisher_did_not_review(self, mock_publish, _mock_flag):
+ skill = self.create_skill(name="make-pr")
+
+ response = self.client.post(
+ self._url("name/make-pr/publish-community"),
+ data={"expected_skill_id": str(skill.id), "expected_version": 2},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ assert response.json()["detail"] == (
+ "This skill changed after you reviewed it. Reopen the dialog and review the latest version."
+ )
+ mock_publish.assert_not_called()
+
+ @patch(COMMUNITY_FLAG, return_value=True)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_rejects_a_recreated_skill_with_the_same_version(self, mock_publish, _mock_flag):
+ reviewed_skill = self.create_skill(name="make-pr")
+ archive_skill(self.team, "make-pr")
+ replacement_skill = self.create_skill(name="make-pr")
+
+ response = self.client.post(
+ self._url("name/make-pr/publish-community"),
+ data={"expected_skill_id": str(reviewed_skill.id), "expected_version": replacement_skill.version},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_409_CONFLICT
+ mock_publish.assert_not_called()
+
@parameterized.expand(
[
# Longer than CommunitySkill.name: the PR merges and ingest then drops the entry.
@@ -1755,11 +1792,11 @@ class TestLLMSkillAPI(APIBaseTest):
@patch(COMMUNITY_FLAG, return_value=True)
@patch("products.skills.backend.api.skills.publish_skill_to_community")
def test_publish_to_community_rejects_display_name(self, _label: str, display_name: str, mock_publish, _mock_flag):
- self.create_skill(name="make-pr")
+ skill = self.create_skill(name="make-pr")
response = self.client.post(
self._url("name/make-pr/publish-community"),
- data={"display_name": display_name},
+ data={"expected_skill_id": str(skill.id), "expected_version": 1, "display_name": display_name},
format="json",
)
@@ -1769,9 +1806,13 @@ class TestLLMSkillAPI(APIBaseTest):
@patch(COMMUNITY_FLAG, return_value=False)
@patch("products.skills.backend.api.skills.publish_skill_to_community")
def test_publish_to_community_is_gated_on_the_community_flag(self, mock_publish, _mock_flag):
- self.create_skill(name="make-pr")
+ skill = self.create_skill(name="make-pr")
- response = self.client.post(self._url("name/make-pr/publish-community"), data={}, format="json")
+ response = self.client.post(
+ self._url("name/make-pr/publish-community"),
+ data={"expected_skill_id": str(skill.id), "expected_version": 1},
+ format="json",
+ )
assert response.status_code == status.HTTP_403_FORBIDDEN
mock_publish.assert_not_called()
@@ -1780,9 +1821,13 @@ class TestLLMSkillAPI(APIBaseTest):
@patch("products.skills.backend.api.skills.publish_skill_to_community")
def test_publish_to_community_not_configured_returns_503(self, mock_publish, _mock_flag):
mock_publish.side_effect = CommunitySkillPublishNotConfiguredError("nope")
- self.create_skill(name="make-pr")
+ skill = self.create_skill(name="make-pr")
- response = self.client.post(self._url("name/make-pr/publish-community"), data={}, format="json")
+ response = self.client.post(
+ self._url("name/make-pr/publish-community"),
+ data={"expected_skill_id": str(skill.id), "expected_version": 1},
+ format="json",
+ )
assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
@@ -1792,9 +1837,13 @@ class TestLLMSkillAPI(APIBaseTest):
# Nothing reached GitHub and republishing the same skill fails the same way, so a 502 would
# tell the publisher to retry an upstream request that was never the problem.
mock_publish.side_effect = CommunitySkillPublishValidationError("that slug is reserved")
- self.create_skill(name="make-pr")
+ skill = self.create_skill(name="make-pr")
- response = self.client.post(self._url("name/make-pr/publish-community"), data={}, format="json")
+ response = self.client.post(
+ self._url("name/make-pr/publish-community"),
+ data={"expected_skill_id": str(skill.id), "expected_version": 1},
+ format="json",
+ )
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["detail"] == "that slug is reserved"
@@ -1803,9 +1852,13 @@ class TestLLMSkillAPI(APIBaseTest):
@patch("products.skills.backend.api.skills.publish_skill_to_community")
def test_publish_to_community_github_error_returns_502(self, mock_publish, _mock_flag):
mock_publish.side_effect = CommunitySkillPublishError("github exploded")
- self.create_skill(name="make-pr")
+ skill = self.create_skill(name="make-pr")
- response = self.client.post(self._url("name/make-pr/publish-community"), data={}, format="json")
+ response = self.client.post(
+ self._url("name/make-pr/publish-community"),
+ data={"expected_skill_id": str(skill.id), "expected_version": 1},
+ format="json",
+ )
assert response.status_code == status.HTTP_502_BAD_GATEWAY
@@ -1999,7 +2052,11 @@ class TestSkillAccessControlRBAC(APIBaseTest):
response = self.client.post(
self._url(f"name/{self.skill.name}/publish-community"),
- data={"author_handle": "someone"},
+ data={
+ "expected_skill_id": str(self.skill.id),
+ "expected_version": self.skill.version,
+ "author_handle": "someone",
+ },
format="json",
)
@@ -2035,7 +2092,11 @@ class TestSkillAccessControlRBAC(APIBaseTest):
response = self.client.post(
self._url(f"name/{self.skill.name}/publish-community"),
- data={"author_handle": "someone"},
+ data={
+ "expected_skill_id": str(self.skill.id),
+ "expected_version": self.skill.version,
+ "author_handle": "someone",
+ },
format="json",
)
diff --git a/products/skills/frontend/LLMSkillScene.stories.tsx b/products/skills/frontend/LLMSkillScene.stories.tsx
index 666098cd7629..6ad4310a7446 100644
--- a/products/skills/frontend/LLMSkillScene.stories.tsx
+++ b/products/skills/frontend/LLMSkillScene.stories.tsx
@@ -2,6 +2,7 @@ import { MOCK_USER_UUID } from 'lib/api.mock'
import { Meta, StoryObj } from '@storybook/react'
+import { FEATURE_FLAGS } from 'lib/constants'
import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
@@ -160,6 +161,7 @@ const meta: Meta = {
layout: 'fullscreen',
viewMode: 'story',
mockDate: '2025-01-28',
+ featureFlags: [FEATURE_FLAGS.LLM_ANALYTICS_COMMUNITY_SKILLS],
pageUrl: urls.skill(SKILL_NAME),
testOptions: {
waitForLoadersToDisappear: true,
@@ -170,6 +172,8 @@ const meta: Meta = {
get: {
'/api/projects/:team_id/llm_skills/': toPaginatedResponse([SKILL_LIST_ENTRY, UNOWNED_SKILL_LIST_ENTRY]),
'/api/projects/:team_id/llm_skills/resolve/name/:name/': RESOLVE_RESPONSE,
+ // Backs the share dialog's file manifest.
+ '/api/projects/:team_id/llm_skills/name/:name/': SKILL,
},
}),
],
diff --git a/products/skills/frontend/LLMSkillScene.tsx b/products/skills/frontend/LLMSkillScene.tsx
index 2941400f7c95..7edbde856430 100644
--- a/products/skills/frontend/LLMSkillScene.tsx
+++ b/products/skills/frontend/LLMSkillScene.tsx
@@ -61,6 +61,7 @@ import {
openArchiveSkillDialog,
openPublishToCommunityDialog,
openRenameSkillDialog,
+ publishToCommunityDisabledReason,
} from './skillSceneComponents'
const MonacoDiffEditor = lazyWithRetry(() => import('lib/components/MonacoDiffEditor'))
@@ -184,22 +185,13 @@ export function LLMSkillScene(): JSX.Element {
const canEditSkill = userHasAccess(AccessControlResourceType.LlmSkill, AccessControlLevel.Editor)
const communitySkillsEnabled = !!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_COMMUNITY_SKILLS]
- const skillOwners = isSkill(skill) ? skill.owners : []
- const isOwner = !!user && skillOwners.some((owner) => owner.uuid === user.uuid)
- // Publishing is owner-only on the backend, so mirror that here instead of letting a non-owner's
- // click come back a 403. In-flight guard keyed on the skill name matches the list view.
- // The backend publishes the latest version by name, so block publishing from a historical
- // version to avoid pushing content the user is not viewing.
const publishDisabledReason = isSkill(skill)
- ? publishingSkills[skill.name]
- ? 'Publishing…'
- : skillOwners.length === 0
- ? 'Add an owner before publishing to the community'
- : !isOwner
- ? "Only the skill's owners can publish it"
- : isHistoricalVersion
- ? 'Switch to the latest version to publish'
- : undefined
+ ? publishToCommunityDisabledReason({
+ ownerUuids: skill.owners.map((owner) => owner.uuid),
+ currentUserUuid: user?.uuid,
+ publishing: !!publishingSkills[skill.name],
+ isHistoricalVersion,
+ })
: undefined
const renameDisabledReason = renameBlockedReason(isSkill(skill) ? skill.name : null)
@@ -279,7 +271,7 @@ export function LLMSkillScene(): JSX.Element {
data-attr="llma-skill-publish-community-button"
fullWidth
>
- Publish to community
+ Publish to PostHog community…
</LemonButton>
</AccessControlAction>
)}
diff --git a/products/skills/frontend/LLMSkillsScene.tsx b/products/skills/frontend/LLMSkillsScene.tsx
index 41fdd2efe8ce..e1ba50290352 100644
--- a/products/skills/frontend/LLMSkillsScene.tsx
+++ b/products/skills/frontend/LLMSkillsScene.tsx
@@ -33,6 +33,7 @@ import type { LLMSkillListApi } from 'products/skills/frontend/generated/api.sch
import { llmSkillsEmptyState } from './emptyState/llmSkillsEmptyState'
import { SKILLS_GROUP_LIMIT, SKILLS_PER_PAGE, SkillGroupNode, SkillGroupTree, llmSkillsLogic } from './llmSkillsLogic'
+import { ShareSkillMenuItem } from './ShareSkillMenuItem'
import { SKILL_NAME_MAX_LENGTH, validateSkillName } from './skillConstants'
import { openArchiveSkillDialog, openPublishToCommunityDialog } from './skillSceneComponents'
import { SkillsSceneShell } from './SkillsSceneShell'
@@ -204,18 +205,7 @@ function buildSkillColumns(
</LemonButton>
</AccessControlAction>
- <AccessControlAction
- resourceType={AccessControlResourceType.LlmSkill}
- minAccessLevel={AccessControlLevel.Editor}
- >
- <LemonButton
- onClick={() => publishToCommunity(skill)}
- data-attr="llma-skill-dropdown-publish-community"
- fullWidth
- >
- Publish to community
- </LemonButton>
- </AccessControlAction>
+ <ShareSkillMenuItem skill={skill} onShare={publishToCommunity} />
<AccessControlAction
resourceType={AccessControlResourceType.LlmSkill}
diff --git a/products/skills/frontend/PublishToCommunityContents.tsx b/products/skills/frontend/PublishToCommunityContents.tsx
new file mode 100644
index 000000000000..aeab093c38bd
--- /dev/null
+++ b/products/skills/frontend/PublishToCommunityContents.tsx
@@ -0,0 +1,85 @@
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { LemonButton, LemonCollapse, LemonTag } from '@posthog/lemon-ui'
+
+import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+
+import type { LLMSkillApi } from './generated/api.schemas'
+import { skillPublishPreviewLogic } from './skillPublishPreviewLogic'
+
+export function PublishToCommunityContents({
+ skillName,
+ onPreviewChange,
+}: {
+ skillName: string
+ onPreviewChange: (preview: LLMSkillApi | null) => void
+}): JSX.Element {
+ const { publishPreview, publishPreviewLoading } = useValues(skillPublishPreviewLogic({ skillName }))
+ const { loadPublishPreview } = useActions(skillPublishPreviewLogic({ skillName }))
+
+ useEffect(() => {
+ onPreviewChange(publishPreview)
+ }, [onPreviewChange, publishPreview])
+
+ return (
+ <>
+ <div className="flex flex-col gap-1 rounded border p-2 bg-primary-highlight">
+ <div className="flex items-center gap-2">
+ <span className="font-semibold">Visibility</span>
+ <span>Public on GitHub</span>
+ <LemonTag type="danger">Public</LemonTag>
+ </div>
+ {publishPreviewLoading ? (
+ <LemonSkeleton active className="h-4 w-3/5" />
+ ) : publishPreview ? (
+ <>
+ <div>
+ <span className="font-semibold">Version</span> v{publishPreview.version}
+ </div>
+ <LemonCollapse
+ embedded
+ size="small"
+ panels={[
+ {
+ key: 'files',
+ header: 'Review files',
+ content: (
+ <ul className="m-0 pl-4 list-disc font-mono text-xs max-h-40 overflow-y-auto break-all">
+ <li>SKILL.md</li>
+ {publishPreview.files.map((file) => (
+ <li key={file.path}>{file.path}</li>
+ ))}
+ </ul>
+ ),
+ },
+ ]}
+ />
+ </>
+ ) : (
+ <div className="flex items-center gap-2">
+ <span className="text-secondary">Could not load the version and file list.</span>
+ <LemonButton size="small" onClick={loadPublishPreview}>
+ Retry
+ </LemonButton>
+ </div>
+ )}
+ </div>
+ <LemonField name="consent">
+ {({ value, onChange }) => (
+ <LemonCheckbox
+ checked={!!value}
+ onChange={onChange}
+ disabledReason={
+ !publishPreview ? 'Wait for the version and file list before you publish' : undefined
+ }
+ data-attr="llma-publish-consent"
+ label="I reviewed this skill and can share it publicly"
+ />
+ )}
+ </LemonField>
+ </>
+ )
+}
diff --git a/products/skills/frontend/ShareSkillMenuItem.tsx b/products/skills/frontend/ShareSkillMenuItem.tsx
new file mode 100644
index 000000000000..bddc341db331
--- /dev/null
+++ b/products/skills/frontend/ShareSkillMenuItem.tsx
@@ -0,0 +1,50 @@
+import { useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { AccessControlAction } from 'lib/components/AccessControlAction'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import type { LLMSkillListApi } from './generated/api.schemas'
+import { llmSkillsLogic } from './llmSkillsLogic'
+import { publishToCommunityDisabledReason } from './skillSceneComponents'
+
+export function ShareSkillMenuItem({
+ skill,
+ onShare,
+}: {
+ skill: LLMSkillListApi
+ onShare: (skill: LLMSkillListApi) => void
+}): JSX.Element | null {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { publishingSkills } = useValues(llmSkillsLogic)
+ const { user } = useValues(userLogic)
+
+ if (!featureFlags[FEATURE_FLAGS.LLM_ANALYTICS_COMMUNITY_SKILLS]) {
+ return null
+ }
+
+ return (
+ <AccessControlAction
+ resourceType={AccessControlResourceType.LlmSkill}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ onClick={() => onShare(skill)}
+ disabledReason={publishToCommunityDisabledReason({
+ ownerUuids: skill.owners.map((owner) => owner.uuid),
+ currentUserUuid: user?.uuid,
+ publishing: !!publishingSkills[skill.name],
+ })}
+ data-attr="llma-skill-dropdown-publish-community"
+ fullWidth
+ >
+ Publish to PostHog community…
+ </LemonButton>
+ </AccessControlAction>
+ )
+}
diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.ts
index 5b2a0c7a6e8b..46764197bd8c 100644
--- a/products/skills/frontend/generated/api.schemas.ts
+++ b/products/skills/frontend/generated/api.schemas.ts
@@ -703,6 +703,13 @@ export interface LLMSkillFileApi {
}
export interface LLMSkillPublishToCommunityApi {
+ /** Immutable ID of the skill version that the publisher reviewed. */
+ expected_skill_id: string
+ /**
+ * Skill version that the publisher reviewed. The request returns 409 if the latest version changed.
+ * @minimum 1
+ */
+ expected_version: number
/** Human-friendly display name for the community listing. Defaults to a title-cased skill slug. Must be a single line: it is used as the pull request title and commit message. */
display_name?: string
/**
@@ -723,6 +730,11 @@ export interface CommunitySkillPublishResultApi {
branch: string
}
+export interface LLMSkillPublishConflictApi {
+ /** Reason that the reviewed skill version can no longer be published. */
+ detail: string
+}
+
export interface LLMSkillRenameApi {
/**
* New name for the skill. Must be unique in the project, and must not start with 'signals-scout-' or 'review-hog-'.
diff --git a/products/skills/frontend/generated/api.ts b/products/skills/frontend/generated/api.ts
index 10087fb8c701..00218a6cf758 100644
--- a/products/skills/frontend/generated/api.ts
+++ b/products/skills/frontend/generated/api.ts
@@ -493,7 +493,7 @@ export const getLlmSkillsNamePublishCommunityCreateUrl = (projectId: string, ski
export const llmSkillsNamePublishCommunityCreate = async (
projectId: string,
skillName: string,
- lLMSkillPublishToCommunityApi?: LLMSkillPublishToCommunityApi,
+ lLMSkillPublishToCommunityApi: LLMSkillPublishToCommunityApi,
options?: RequestInit
): Promise<CommunitySkillPublishResultApi> => {
return apiMutator<CommunitySkillPublishResultApi>(getLlmSkillsNamePublishCommunityCreateUrl(projectId, skillName), {
diff --git a/products/skills/frontend/generated/api.zod.ts b/products/skills/frontend/generated/api.zod.ts
index a5dff191ec5b..ba45b8bb3214 100644
--- a/products/skills/frontend/generated/api.zod.ts
+++ b/products/skills/frontend/generated/api.zod.ts
@@ -309,6 +309,11 @@ export const llmSkillsNamePublishCommunityCreateBodyAuthorHandleOneRegExp = new
export const llmSkillsNamePublishCommunityCreateBodyAuthorHandleTwoMax = 0
export const LlmSkillsNamePublishCommunityCreateBody = /* @__PURE__ */ zod.object({
+ expected_skill_id: zod.uuid().describe('Immutable ID of the skill version that the publisher reviewed.'),
+ expected_version: zod
+ .number()
+ .min(1)
+ .describe('Skill version that the publisher reviewed. The request returns 409 if the latest version changed.'),
display_name: zod
.union([
zod
diff --git a/products/skills/frontend/llmSkillsLogic.ts b/products/skills/frontend/llmSkillsLogic.ts
index 928df3432e5d..4292778dd538 100644
--- a/products/skills/frontend/llmSkillsLogic.ts
+++ b/products/skills/frontend/llmSkillsLogic.ts
@@ -285,12 +285,16 @@ export interface llmSkillsLogicActions {
options: {
author_handle?: string
display_name?: string
+ expected_skill_id: string
+ expected_version: number
tags?: string[]
}
) => {
options: {
author_handle?: string | undefined
display_name?: string | undefined
+ expected_skill_id: string
+ expected_version: number
tags?: string[] | undefined
}
skillName: string
@@ -369,7 +373,13 @@ export const llmSkillsLogic = kea<llmSkillsLogicType>([
duplicateSkill: (skillName: string, newName: string) => ({ skillName, newName }),
publishToCommunity: (
skillName: string,
- options: { display_name?: string; tags?: string[]; author_handle?: string }
+ options: {
+ expected_skill_id: string
+ expected_version: number
+ display_name?: string
+ tags?: string[]
+ author_handle?: string
+ }
) => ({ skillName, options }),
publishToCommunitySuccess: (skillName: string) => ({ skillName }),
publishToCommunityFailure: (skillName: string) => ({ skillName }),
@@ -494,7 +504,7 @@ export const llmSkillsLogic = kea<llmSkillsLogicType>([
},
},
],
- // Resolved GitHub handle for the current user — used to prefill the publish dialog's
+ // Resolved GitHub handle for the current user — used to prefill the share dialog's
// author_handle so the common case (GitHub-SSO'd users) is correct by default. Null when
// no GitHub identity is linked; the dialog field then falls back to free text.
githubLogin: [
@@ -644,6 +654,8 @@ export const llmSkillsLogic = kea<llmSkillsLogicType>([
String(ApiConfig.getCurrentTeamId()),
skillName,
{
+ expected_skill_id: options.expected_skill_id,
+ expected_version: options.expected_version,
display_name: options.display_name,
tags: options.tags,
author_handle: options.author_handle,
diff --git a/products/skills/frontend/skillPublishPreviewLogic.ts b/products/skills/frontend/skillPublishPreviewLogic.ts
new file mode 100644
index 000000000000..c34e495206be
--- /dev/null
+++ b/products/skills/frontend/skillPublishPreviewLogic.ts
@@ -0,0 +1,76 @@
+import { MakeLogicType, afterMount, kea, key, path, props } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { ApiConfig } from '~/lib/api'
+
+import { llmSkillsNameRetrieve } from 'products/skills/frontend/generated/api'
+import type { LLMSkillApi } from 'products/skills/frontend/generated/api.schemas'
+
+export interface SkillPublishPreviewLogicProps {
+ skillName: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface skillPublishPreviewLogicValues {
+ publishPreview: LLMSkillApi | null
+ publishPreviewLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface skillPublishPreviewLogicActions {
+ loadPublishPreview: () => any
+ loadPublishPreviewFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPublishPreviewSuccess: (
+ publishPreview: LLMSkillApi,
+ payload?: any
+ ) => {
+ publishPreview: LLMSkillApi
+ payload?: any
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface skillPublishPreviewLogicMeta {
+ key: string
+}
+
+export type skillPublishPreviewLogicType = MakeLogicType<
+ skillPublishPreviewLogicValues,
+ skillPublishPreviewLogicActions,
+ SkillPublishPreviewLogicProps,
+ skillPublishPreviewLogicMeta
+>
+
+/** What a public share would commit: the skill version the backend would take, and its files.
+ * Read from the server rather than from whichever scene opened the dialog, so the consent screen
+ * names what the share sends and not what the page happens to be rendering. */
+export const skillPublishPreviewLogic = kea<skillPublishPreviewLogicType>([
+ path(['scenes', 'skills', 'skillPublishPreviewLogic']),
+ props({} as SkillPublishPreviewLogicProps),
+ key((props) => props.skillName),
+
+ loaders(({ props }) => ({
+ publishPreview: [
+ null as LLMSkillApi | null,
+ {
+ loadPublishPreview: async () => {
+ // body_length sits at its minimum: the dialog needs the manifest and the
+ // version, never the body.
+ return await llmSkillsNameRetrieve(String(ApiConfig.getCurrentTeamId()), props.skillName, {
+ body_length: 1,
+ })
+ },
+ },
+ ],
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadPublishPreview()
+ }),
+])
diff --git a/products/skills/frontend/skillSceneComponents.test.tsx b/products/skills/frontend/skillSceneComponents.test.tsx
new file mode 100644
index 000000000000..92e9c2017a71
--- /dev/null
+++ b/products/skills/frontend/skillSceneComponents.test.tsx
@@ -0,0 +1,171 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { Provider } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { LemonFormDialog } from 'lib/lemon-ui/LemonDialog/LemonDialog'
+import { lemonDialogLogic } from 'lib/lemon-ui/LemonDialog/lemonDialogLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { llmSkillsNameRetrieve } from 'products/skills/frontend/generated/api'
+import type { LLMSkillApi } from 'products/skills/frontend/generated/api.schemas'
+
+import { openPublishToCommunityDialog, publishToCommunityDisabledReason } from './skillSceneComponents'
+
+jest.mock('products/skills/frontend/generated/api', () => ({
+ llmSkillsNameRetrieve: jest.fn(),
+}))
+
+const mockRetrieve = llmSkillsNameRetrieve as jest.MockedFunction<typeof llmSkillsNameRetrieve>
+
+type OpenFormConfig = Parameters<typeof LemonDialog.openForm>[0]
+
+const MOCK_PREVIEW = {
+ id: '123e4567-e89b-12d3-a456-426614174000',
+ name: 'my-skill',
+ version: 3,
+ files: [
+ { path: 'scripts/run.sh', content_type: 'text/x-shellscript', line_count: 1, char_count: 7 },
+ { path: 'references/guide.md', content_type: 'text/markdown', line_count: 1, char_count: 7 },
+ ],
+} as unknown as LLMSkillApi
+
+describe('skillSceneComponents', () => {
+ let openFormSpy: jest.SpyInstance<void, [OpenFormConfig]>
+ let dialogConfig: OpenFormConfig | undefined
+
+ beforeEach(() => {
+ initKeaTests()
+ dialogConfig = undefined
+ mockRetrieve.mockResolvedValue(MOCK_PREVIEW)
+ openFormSpy = jest.spyOn(LemonDialog, 'openForm').mockImplementation((config) => {
+ dialogConfig = config
+ })
+ })
+
+ afterEach(() => {
+ cleanup()
+ openFormSpy.mockRestore()
+ })
+
+ describe('publish to community dialog', () => {
+ it('blocks the rendered dialog until the preview loads and the consent box is checked', async () => {
+ const onPublish = jest.fn()
+ openPublishToCommunityDialog({ skillName: 'my-skill', githubLogin: null, onPublish })
+
+ expect(dialogConfig?.initialValues.consent).toBe(false)
+ expect(dialogConfig?.title).toBe('Publish to the PostHog community?')
+ expect(dialogConfig?.description).toBe(
+ 'If approved for the PostHog catalog, all PostHog users can find and use this skill. Its contents will be public on GitHub immediately.'
+ )
+ expect(dialogConfig?.errors?.consent(false, {})).toBe(
+ 'Review the skill and confirm that you can share it publicly'
+ )
+ expect(dialogConfig?.errors?.consent(true, {})).toBeUndefined()
+ expect(dialogConfig?.primaryButtonProps?.children).toBe('Publish to community')
+
+ render(
+ <Provider>
+ <LemonFormDialog {...dialogConfig!} dialogKey="publish-consent-test" inline />
+ </Provider>
+ )
+
+ const publishButton = screen.getByText('Publish to community').closest('button')!
+ expect(publishButton).toHaveAttribute('aria-disabled', 'true')
+ await waitFor(() => expect(screen.getByText('v3')).toBeInTheDocument())
+ expect(publishButton).toHaveAttribute('aria-disabled', 'true')
+
+ const consentCheckbox = screen.getByRole('checkbox')
+ expect(consentCheckbox).toBeEnabled()
+ fireEvent.click(consentCheckbox)
+ await waitFor(() =>
+ expect(screen.getByText('Publish to community').closest('button')).toHaveAttribute(
+ 'aria-disabled',
+ 'false'
+ )
+ )
+ fireEvent.click(screen.getByText('Publish to community').closest('button')!)
+
+ expect(onPublish).toHaveBeenCalledWith(
+ 'my-skill',
+ expect.objectContaining({
+ expected_skill_id: '123e4567-e89b-12d3-a456-426614174000',
+ expected_version: 3,
+ })
+ )
+ })
+
+ it('names the destination and version, with the file list behind Review files', async () => {
+ openPublishToCommunityDialog({ skillName: 'my-skill', githubLogin: null, onPublish: jest.fn() })
+
+ render(
+ <Provider>
+ <Form logic={lemonDialogLogic} props={{}} formKey="form">
+ {dialogConfig?.content as JSX.Element}
+ </Form>
+ </Provider>
+ )
+
+ expect(screen.getByText('Public on GitHub')).toBeInTheDocument()
+ await waitFor(() => expect(screen.getByText('v3')).toBeInTheDocument())
+ expect(screen.queryByText('SKILL.md')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByText('Review files'))
+ expect(screen.getByText('SKILL.md')).toBeInTheDocument()
+ expect(screen.getByText('scripts/run.sh')).toBeInTheDocument()
+ expect(screen.getByText('references/guide.md')).toBeInTheDocument()
+ })
+
+ it('blocks publishing and offers a retry when the preview fails', async () => {
+ mockRetrieve.mockRejectedValueOnce(new Error('Preview failed'))
+ openPublishToCommunityDialog({ skillName: 'my-skill', githubLogin: null, onPublish: jest.fn() })
+
+ render(
+ <Provider>
+ <LemonFormDialog {...dialogConfig!} dialogKey="publish-retry-test" inline />
+ </Provider>
+ )
+
+ const publishButton = screen.getByText('Publish to community').closest('button')!
+ await waitFor(() =>
+ expect(screen.getByText('Could not load the version and file list.')).toBeInTheDocument()
+ )
+ expect(publishButton).toHaveAttribute('aria-disabled', 'true')
+
+ mockRetrieve.mockResolvedValueOnce(MOCK_PREVIEW)
+ fireEvent.click(screen.getByText('Retry').closest('button')!)
+
+ await waitFor(() => expect(screen.getByText('v3')).toBeInTheDocument())
+ })
+ })
+
+ describe('publishToCommunityDisabledReason', () => {
+ it.each([
+ ['in flight', { publishing: true }, 'Publishing…'],
+ ['no owners', { ownerUuids: [] }, 'Add an owner before you publish this skill'],
+ ['not an owner', { currentUserUuid: 'other' }, "Only the skill's owners can publish it"],
+ ['historical version', { isHistoricalVersion: true }, 'Switch to the latest version to publish'],
+ ])('blocks publishing %s', (_label, overrides, expected) => {
+ expect(
+ publishToCommunityDisabledReason({
+ ownerUuids: ['me'],
+ currentUserUuid: 'me',
+ publishing: false,
+ ...overrides,
+ })
+ ).toBe(expected)
+ })
+
+ it('allows an owner to publish the latest version', () => {
+ expect(
+ publishToCommunityDisabledReason({
+ ownerUuids: ['me'],
+ currentUserUuid: 'me',
+ publishing: false,
+ })
+ ).toBeUndefined()
+ })
+ })
+})
diff --git a/products/skills/frontend/skillSceneComponents.tsx b/products/skills/frontend/skillSceneComponents.tsx
index 538a2902ccbe..9527df2e87cb 100644
--- a/products/skills/frontend/skillSceneComponents.tsx
+++ b/products/skills/frontend/skillSceneComponents.tsx
@@ -12,6 +12,7 @@ import { LemonDialog } from '~/lib/lemon-ui/LemonDialog'
import type { SkillFormFileValues } from './llmSkillLogic'
import { isSkill, llmSkillLogic } from './llmSkillLogic'
+import { PublishToCommunityContents } from './PublishToCommunityContents'
import { SKILL_NAME_MAX_LENGTH, validateSkillName } from './skillConstants'
export { LLMSkillsScene } from './LLMSkillsScene'
@@ -53,11 +54,43 @@ export function openRenameSkillDialog(skillName: string, onRename: (newName: str
}
interface PublishToCommunityOptions {
+ expected_skill_id: string
+ expected_version: number
display_name?: string
tags?: string[]
author_handle?: string
}
+/** Owner-only on the backend, so mirror that here instead of letting a click come back a 403.
+ * Shared so the list view and the single-skill view guard the trigger identically. */
+export function publishToCommunityDisabledReason({
+ ownerUuids,
+ currentUserUuid,
+ publishing,
+ isHistoricalVersion,
+}: {
+ ownerUuids: string[]
+ currentUserUuid: string | undefined
+ publishing: boolean
+ isHistoricalVersion?: boolean
+}): string | undefined {
+ if (publishing) {
+ return 'Publishing…'
+ }
+ if (ownerUuids.length === 0) {
+ return 'Add an owner before you publish this skill'
+ }
+ if (!currentUserUuid || !ownerUuids.includes(currentUserUuid)) {
+ return "Only the skill's owners can publish it"
+ }
+ // The backend shares the latest version by name, so block sharing from a historical version to
+ // avoid pushing content the user is not looking at.
+ if (isHistoricalVersion) {
+ return 'Switch to the latest version to publish'
+ }
+ return undefined
+}
+
/** Collect the publish fields, then hand them to `onPublish`. Shared so the list view and the
* single-skill view open the identical dialog. */
export function openPublishToCommunityDialog({
@@ -69,19 +102,28 @@ export function openPublishToCommunityDialog({
githubLogin: string | null
onPublish: (skillName: string, options: PublishToCommunityOptions) => void
}): void {
+ let expectedSkill: { id: string; version: number } | null = null
+
LemonDialog.openForm({
- title: 'Publish to community',
+ title: 'Publish to the PostHog community?',
description:
- "Publishing commits the skill's instructions, every bundled file, and any template variables (their prompts and defaults) to a public GitHub repo, then opens a pull request for a maintainer to review. The contents are public from the moment you submit, so don't include credentials or internal details.",
+ 'If approved for the PostHog catalog, all PostHog users can find and use this skill. Its contents will be public on GitHub immediately.',
initialValues: {
display_name: skillName.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),
tags: '',
// Prefill with the user's resolved GitHub handle when we have one; the field stays
// editable so users without a linked GitHub identity can still type one (free-text fallback).
author_handle: githubLogin ?? '',
+ consent: false,
},
content: (
<div className="flex flex-col gap-2">
+ <PublishToCommunityContents
+ skillName={skillName}
+ onPreviewChange={(preview) => {
+ expectedSkill = preview ? { id: preview.id, version: preview.version } : null
+ }}
+ />
<LemonField name="display_name" label="Display name">
<LemonInput data-attr="llma-publish-display-name" autoFocus />
</LemonField>
@@ -93,8 +135,18 @@ export function openPublishToCommunityDialog({
</LemonField>
</div>
),
- onSubmit: ({ display_name, tags, author_handle }) =>
+ errors: {
+ consent: (consent: boolean) =>
+ consent ? undefined : 'Review the skill and confirm that you can share it publicly',
+ },
+ primaryButtonProps: { children: 'Publish to community' },
+ onSubmit: ({ display_name, tags, author_handle }) => {
+ if (expectedSkill === null) {
+ return
+ }
onPublish(skillName, {
+ expected_skill_id: expectedSkill.id,
+ expected_version: expectedSkill.version,
display_name: display_name?.trim() || undefined,
tags: tags
? tags
@@ -103,7 +155,8 @@ export function openPublishToCommunityDialog({
.filter(Boolean)
: undefined,
author_handle: author_handle?.trim() || undefined,
- }),
+ })
+ },
})
}
diff --git a/products/skills/package.json b/products/skills/package.json
index 77b7b0239fce..d333e5c3ea2d 100644
--- a/products/skills/package.json
+++ b/products/skills/package.json
@@ -11,6 +11,7 @@
},
"devDependencies": {
"@storybook/react": "catalog:",
+ "@testing-library/react": "^14.3.1",
"kea-test-utils": "catalog:"
},
"peerDependencies": {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7c5187a3868e..8fcd6fcb9172 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -49744,7 +49744,19 @@ export namespace Schemas {
rotate?: boolean;
}
+ export interface LLMSkillPublishConflict {
+ /** Reason that the reviewed skill version can no longer be published. */
+ detail: string;
+ }
+
export interface LLMSkillPublishToCommunity {
+ /** Immutable ID of the skill version that the publisher reviewed. */
+ expected_skill_id: string;
+ /**
+ * Skill version that the publisher reviewed. The request returns 409 if the latest version changed.
+ * @minimum 1
+ */
+ expected_version: number;
/** Human-friendly display name for the community listing. Defaults to a title-cased skill slug. Must be a single line: it is used as the pull request title and commit message. */
display_name?: string;
/**