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(slack): keep internal run artifacts out of slack delivery (#70927)

Chris Volzer8b4e624737c7
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index e1c221a9b57d..639cb7d98b94 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -9,6 +9,7 @@ from django.db import models
import structlog
from temporalio import activity
+from posthog.models.integration import Integration, SlackIntegration
from posthog.temporal.ai.slack_app.attachments import (
PreparedSlackAttachments,
build_slack_attachment_prompt_text,
@@ -34,22 +35,45 @@ _INITIATOR_PLACEHOLDER = "<original user message was here>"
_SLACK_DELIVERY_CONSTRAINTS = """Slack delivery constraints:
- Local sandbox paths such as /tmp/workspace/... are not visible to Slack users.
- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.
-- For Slack deliverables, create a living artifact before claiming delivery. POST to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/` with `$POSTHOG_PERSONAL_API_KEY`; choose adapter `slack_canvas`, `slack_message`, `slack_file`, or `document_connector`. Use `adapter=slack_file` with `content_base64` for binary deliverables such as .xlsx/.pdf/.docx, or `source_artifact_id` / `source_storage_path` for a file already uploaded as a run artifact. To update a prior deliverable, GET the returned artifact id or POST new `content`, `content_base64`, or source artifact fields to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/<artifact_id>/edit/`.
+- For Slack deliverables, create a living artifact before claiming delivery. POST to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/` with `$POSTHOG_PERSONAL_API_KEY`; choose adapter `slack_canvas`, `slack_message`, `slack_file`, or `document_connector`. Use `adapter=slack_file` with `content_base64` for binary deliverables such as .xlsx/.pdf/.docx, or `source_artifact_id` / `source_storage_path` for a file you already uploaded as a `type=output` run artifact.
+- Run artifacts that are not your uploaded outputs (plans, context, tree snapshots, checkpoints, user uploads) are internal: never deliver them to Slack or mention them in your reply.
+- To update a prior deliverable, GET the returned artifact id or POST new `content`, `content_base64`, or source artifact fields to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/<artifact_id>/edit/`.
- Do not paste living-artifact Slack file links or permalinks into your final Slack answer unless the user explicitly asks for the URL. The Slack relay attaches pending file artifacts to your final answer automatically, so mention the artifact by name only if useful.
- If you created a local file but no upload or delivery tool is available, say that plainly and summarize the result in Slack instead."""
-# Variant used while the slack-app-canvas-file-artifacts flag is off for the workspace: the
-# slack_canvas / slack_file adapters need Slack scopes that are still in review, so the agent
-# must not be offered them (the adapters reject the request server-side regardless).
+# Variant used when the workspace cannot deliver canvases or files — the
+# slack-app-canvas-file-artifacts flag is off, or the Slack install is missing the
+# canvases:write / files:write scopes the adapters need. The agent must not be offered
+# capabilities it doesn't have (the adapters reject the request server-side regardless).
_SLACK_DELIVERY_CONSTRAINTS_MESSAGE_ONLY = """Slack delivery constraints:
- Local sandbox paths such as /tmp/workspace/... are not visible to Slack users.
- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.
-- Canvas and file uploads to Slack are not available in this workspace: do not use the `slack_canvas` or `slack_file` adapters, and do not promise a canvas, uploaded spreadsheet, or downloadable file.
+- You do not have canvas or file delivery in this workspace: do not use the `slack_canvas` or `slack_file` adapters, and do not promise a canvas, uploaded spreadsheet, or downloadable file.
- For Slack deliverables, create a living artifact before claiming delivery. POST to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/` with `$POSTHOG_PERSONAL_API_KEY` using adapter `slack_message`. To update a prior deliverable, GET the returned artifact id or POST new `content` to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/<artifact_id>/edit/`.
+- Run artifacts that are not your uploaded outputs (plans, context, tree snapshots, checkpoints, user uploads) are internal: never deliver them to Slack or mention them in your reply.
- If a deliverable cannot be expressed as a Slack message (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead."""
_SLACK_DELIVERY_CONSTRAINTS_TEXT_ONLY = """Slack delivery constraints:
-- Slack artifact delivery is disabled. Do not attach, upload, link to, or expose run artifacts or local working files, including /tmp/workspace paths."""
+- You do not have artifact delivery in this workspace: you cannot create or share artifacts (files, canvases, documents) from this run, so do not attempt to. Deliver results as plain text in your reply.
+- Do not attach, upload, link to, or expose run artifacts or local working files, including /tmp/workspace paths."""
+
+# Slack scopes the canvas/file living-artifact adapters check at delivery time.
+_SLACK_CANVAS_FILE_ADAPTER_SCOPES = frozenset({"canvases:write", "files:write"})
+
+
+def _canvas_file_delivery_available(integration: Integration) -> bool:
+ """Whether the workspace can actually deliver canvas/file artifacts.
+
+ The prompt offer must match delivery capability — the rollout flag AND the Slack
+ scopes the adapters check at delivery time — so the agent is never invited to
+ create an artifact that delivery will reject.
+ """
+ from products.slack_app.backend.feature_flags import is_slack_app_canvas_file_artifacts_enabled # noqa: PLC0415
+
+ if not is_slack_app_canvas_file_artifacts_enabled(integration):
+ return False
+ return not SlackIntegration(integration).missing_scopes(_SLACK_CANVAS_FILE_ADAPTER_SCOPES)
+
# Cap on how many messages a single follow-up update block can carry. Threads with
# hundreds of intervening messages between interactions are an edge case (a chatty
@@ -640,10 +664,7 @@ def create_posthog_code_task_for_repo_activity(
thread_ts=thread_ts,
)
- from products.slack_app.backend.feature_flags import ( # noqa: PLC0415
- is_slack_app_canvas_file_artifacts_enabled,
- is_slack_app_living_artifacts_enabled,
- )
+ from products.slack_app.backend.feature_flags import is_slack_app_living_artifacts_enabled # noqa: PLC0415
living_artifacts_enabled = is_slack_app_living_artifacts_enabled(integration)
@@ -653,8 +674,7 @@ def create_posthog_code_task_for_repo_activity(
user_message_ts,
mentioner_slack_user_id=slack_user_id,
mentioner_display_name=mentioner_display_name,
- canvas_file_artifacts_enabled=living_artifacts_enabled
- and is_slack_app_canvas_file_artifacts_enabled(integration),
+ canvas_file_artifacts_enabled=living_artifacts_enabled and _canvas_file_delivery_available(integration),
living_artifacts_enabled=living_artifacts_enabled,
)
diff --git a/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_task_creation.ambr b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_task_creation.ambr
index 44867585500c..9a15fbf0cafb 100644
--- a/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_task_creation.ambr
+++ b/posthog/temporal/tests/ai/slack_app/activities/__snapshots__/test_task_creation.ambr
@@ -35,7 +35,9 @@
Slack delivery constraints:
- Local sandbox paths such as /tmp/workspace/... are not visible to Slack users.
- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.
- - For Slack deliverables, create a living artifact before claiming delivery. POST to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/` with `$POSTHOG_PERSONAL_API_KEY`; choose adapter `slack_canvas`, `slack_message`, `slack_file`, or `document_connector`. Use `adapter=slack_file` with `content_base64` for binary deliverables such as .xlsx/.pdf/.docx, or `source_artifact_id` / `source_storage_path` for a file already uploaded as a run artifact. To update a prior deliverable, GET the returned artifact id or POST new `content`, `content_base64`, or source artifact fields to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/<artifact_id>/edit/`.
+ - For Slack deliverables, create a living artifact before claiming delivery. POST to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/` with `$POSTHOG_PERSONAL_API_KEY`; choose adapter `slack_canvas`, `slack_message`, `slack_file`, or `document_connector`. Use `adapter=slack_file` with `content_base64` for binary deliverables such as .xlsx/.pdf/.docx, or `source_artifact_id` / `source_storage_path` for a file you already uploaded as a `type=output` run artifact.
+ - Run artifacts that are not your uploaded outputs (plans, context, tree snapshots, checkpoints, user uploads) are internal: never deliver them to Slack or mention them in your reply.
+ - To update a prior deliverable, GET the returned artifact id or POST new `content`, `content_base64`, or source artifact fields to `$POSTHOG_API_URL/api/projects/$POSTHOG_PROJECT_ID/tasks/$POSTHOG_TASK_ID/runs/$POSTHOG_TASK_RUN_ID/living_artifacts/<artifact_id>/edit/`.
- Do not paste living-artifact Slack file links or permalinks into your final Slack answer unless the user explicitly asks for the URL. The Slack relay attaches pending file artifacts to your final answer automatically, so mention the artifact by name only if useful.
- If you created a local file but no upload or delivery tool is available, say that plainly and summarize the result in Slack instead.
can you take a look
diff --git a/posthog/temporal/tests/ai/slack_app/activities/test_task_creation.py b/posthog/temporal/tests/ai/slack_app/activities/test_task_creation.py
index 62d4e6bae8a0..47782ea1dc4e 100644
--- a/posthog/temporal/tests/ai/slack_app/activities/test_task_creation.py
+++ b/posthog/temporal/tests/ai/slack_app/activities/test_task_creation.py
@@ -11,6 +11,10 @@ to wording in the wrapper text show up as a diff in
``__snapshots__/test_task_creation.ambr`` rather than as a silent regression.
"""
+import pytest
+from unittest.mock import patch
+
+from posthog.models.integration import Integration
from posthog.temporal.ai.slack_app.activities.task_creation import (
_INITIATOR_PLACEHOLDER,
_SLACK_DELIVERY_CONSTRAINTS,
@@ -19,6 +23,7 @@ from posthog.temporal.ai.slack_app.activities.task_creation import (
_THREAD_CONTEXT_TAG,
_THREAD_CONTEXT_UPDATE_TAG,
_build_posthog_code_task_description,
+ _canvas_file_delivery_available,
_format_author_token,
_indent_body,
build_thread_context_update_block,
@@ -112,6 +117,28 @@ def test_build_description_limits_delivery_to_text_when_artifact_flag_off():
assert "slack_message" not in out
+ "flag_enabled,granted_scopes,expected",
+ [
+ (True, "chat:write,canvases:write,files:write", True),
+ (True, "chat:write,canvases:write", False),
+ (True, "chat:write", False),
+ (False, "chat:write,canvases:write,files:write", False),
+ ],
+)
+def test_canvas_file_delivery_requires_flag_and_scopes(flag_enabled, granted_scopes, expected):
+ # A flag-on workspace whose Slack install lacks the adapter scopes must not be
+ # offered canvas/file delivery in the prompt — the agent would create artifacts
+ # that delivery then rejects. Capability = rollout flag AND granted scopes.
+ integration = Integration(kind="slack", config={"scope": granted_scopes})
+
+ with patch(
+ "products.slack_app.backend.feature_flags.is_slack_app_canvas_file_artifacts_enabled",
+ return_value=flag_enabled,
+ ):
+ assert _canvas_file_delivery_available(integration) is expected
+
+
def test_build_description_renders_labeled_mention_for_each_author():
# Add a follow-up message after the mentioner so the placeholder isn't the trailing
# entry (the trailing-placeholder pop would otherwise drop the mentioner's row).
diff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.py
index 02a4b5c985a0..114d7d1c494e 100644
--- a/products/tasks/backend/logic/services/living_artifacts.py
+++ b/products/tasks/backend/logic/services/living_artifacts.py
@@ -354,19 +354,6 @@ def open_task_artifact(artifact: TaskArtifact) -> str | None:
return _adapter_for_existing_artifact(artifact).open(artifact)
-def _artifact_type_from_manifest(manifest_entry: dict[str, Any]) -> str:
- raw_type = str(manifest_entry.get("type") or "")
- content_type = str(manifest_entry.get("content_type") or "").lower()
- name = str(manifest_entry.get("name") or "").lower()
- if raw_type in {choice for choice, _label in TaskArtifact.ArtifactType.choices}:
- return raw_type
- if _is_spreadsheet_name_or_type(name, content_type):
- return TaskArtifact.ArtifactType.SPREADSHEET
- if content_type.startswith("text/") or name.endswith((".md", ".txt", ".html")):
- return TaskArtifact.ArtifactType.DOCUMENT
- return TaskArtifact.ArtifactType.FILE
-
-
def _find_source_artifact(
run: TaskRun,
*,
@@ -376,12 +363,24 @@ def _find_source_artifact(
for candidate_run in reversed(run.get_resume_chain()):
for artifact in candidate_run.artifacts or []:
if source_artifact_id and str(artifact.get("id")) == str(source_artifact_id):
- return artifact
+ return _require_shareable_source_artifact(artifact)
if source_storage_path and artifact.get("storage_path") == source_storage_path:
- return artifact
+ return _require_shareable_source_artifact(artifact)
return None
+def _require_shareable_source_artifact(artifact: dict[str, Any]) -> dict[str, Any]:
+ # Run manifests also carry internal state (plans, context, tree snapshots, user
+ # uploads). Living artifacts are deliverables that leave PostHog, so only files
+ # the agent explicitly uploaded as run outputs may be used as a content source.
+ if artifact.get("type") != "output" or artifact.get("source") != "agent_output":
+ raise ValueError(
+ "Source artifact is not a shareable run output: only files uploaded as type=output run artifacts "
+ "can be delivered. Upload the file as an output artifact first, or pass content or content_base64."
+ )
+ return artifact
+
+
def _is_textual_content(source_artifact: dict[str, Any]) -> bool:
content_type = str(source_artifact.get("content_type") or "").split(";")[0].strip().lower()
name = str(source_artifact.get("name") or "").lower()
@@ -398,16 +397,6 @@ def _is_textual_name_and_type(name: str, content_type: str) -> bool:
)
-def _is_spreadsheet_name_or_type(name: str, content_type: str) -> bool:
- normalized_content_type = str(content_type or "").split(";")[0].strip().lower()
- normalized_name = name.lower()
- return normalized_content_type in {
- "application/vnd.ms-excel",
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- "text/csv",
- } or normalized_name.endswith((".csv", ".xls", ".xlsx"))
-
-
def _guess_content_type(name: str) -> str:
guessed, _encoding = mimetypes.guess_type(name)
return guessed or DEFAULT_BINARY_CONTENT_TYPE
@@ -635,11 +624,17 @@ class SlackCanvasArtifactAdapter(LivingArtifactAdapter):
) -> ArtifactCommit:
mapping = _get_slack_mapping(run)
if not _canvas_file_artifacts_enabled(mapping):
- raise ValueError("Slack canvas delivery is not enabled for this workspace")
+ raise ValueError(
+ "Slack canvas delivery is not enabled for this workspace: you do not have this capability. "
+ "Use adapter=slack_message and deliver the content as text instead."
+ )
slack_integration = _slack_integration_for_mapping(mapping)
missing_scopes = slack_integration.missing_scopes(frozenset({SLACK_CANVAS_SCOPE}))
if missing_scopes:
- raise ValueError("Slack canvas delivery requires the canvases:write Slack scope")
+ raise ValueError(
+ "Slack canvas delivery is unavailable: the Slack integration is missing the canvases:write scope, "
+ "so you do not have this capability. Use adapter=slack_message and deliver the content as text instead."
+ )
slack = slack_integration.client
markdown = content.strip() or name
if artifact is None:
@@ -725,11 +720,17 @@ class SlackFileArtifactAdapter(LivingArtifactAdapter):
) -> ArtifactCommit:
mapping = _get_slack_mapping(run)
if not _canvas_file_artifacts_enabled(mapping):
- raise ValueError("Slack file delivery is not enabled for this workspace")
+ raise ValueError(
+ "Slack file delivery is not enabled for this workspace: you do not have this capability. "
+ "Use adapter=slack_message and summarize the result as text instead."
+ )
slack_integration = _slack_integration_for_mapping(mapping)
missing_scopes = slack_integration.missing_scopes(frozenset({SLACK_FILE_SCOPE}))
if missing_scopes:
- raise ValueError("Slack file delivery requires the files:write Slack scope")
+ raise ValueError(
+ "Slack file delivery is unavailable: the Slack integration is missing the files:write scope, "
+ "so you do not have this capability. Use adapter=slack_message and summarize the result as text instead."
+ )
resolved_content_type = content_type or _guess_content_type(name)
payload = content_bytes if content_bytes is not None else content.encode("utf-8")
@@ -1012,7 +1013,10 @@ def _living_artifacts_enabled_for_mapping(mapping: Any) -> bool:
def _require_living_artifacts_enabled(run: TaskRun) -> None:
if not _living_artifacts_enabled_for_run(run):
- raise ValueError("Living artifacts are not enabled for this Slack workspace")
+ raise ValueError(
+ "Living artifacts are not enabled for this Slack workspace: you cannot create or deliver "
+ "artifacts on this run. Deliver results as plain text in your reply instead."
+ )
def _canvas_file_artifacts_enabled(mapping: Any) -> bool:
diff --git a/products/tasks/backend/logic/services/tests/test_living_artifacts.py b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
index 6f3943386224..9fc0d6c2eefb 100644
--- a/products/tasks/backend/logic/services/tests/test_living_artifacts.py
+++ b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
@@ -428,6 +428,7 @@ class TestLivingArtifacts(TestCase):
{
"id": "artifact-1",
"name": "report.zip",
+ "type": "output",
"source": "agent_output",
"size": len(workbook_bytes),
"content_type": "application/zip",
@@ -461,6 +462,45 @@ class TestLivingArtifacts(TestCase):
)
slack.api_call.assert_not_called()
+ @parameterized.expand(
+ [
+ ("internal_type_by_id", "tree_snapshot", "agent_output", "id"),
+ ("user_attachment_by_id", "user_attachment", "user_attachment", "id"),
+ ("unlabeled_source_by_id", "output", "", "id"),
+ ("internal_type_by_storage_path", "tree_snapshot", "agent_output", "storage_path"),
+ ]
+ )
+ def test_internal_run_artifacts_rejected_as_living_artifact_sources(
+ self, _name: str, entry_type: str, entry_source: str, reference_by: str
+ ) -> None:
+ storage_path = f"tasks/artifacts/team_{self.team.id}/task_{self.task.id}/run_{self.task_run.id}/state.bin"
+ self.task_run.artifacts = [
+ {
+ "id": "artifact-1",
+ "name": "state.bin",
+ "type": entry_type,
+ "source": entry_source,
+ "size": 4,
+ "content_type": "application/octet-stream",
+ "storage_path": storage_path,
+ }
+ ]
+ self.task_run.save(update_fields=["artifacts", "updated_at"])
+ source_artifact_id = "artifact-1" if reference_by == "id" else None
+ source_storage_path = storage_path if reference_by == "storage_path" else None
+
+ with self.assertRaisesRegex(ValueError, "not a shareable run output"):
+ create_living_artifact(
+ run=self.task_run,
+ name="state.bin",
+ artifact_type=TaskArtifact.ArtifactType.FILE,
+ adapter=TaskArtifact.Adapter.SLACK_FILE,
+ source_artifact_id=source_artifact_id,
+ source_storage_path=source_storage_path,
+ )
+
+ self.assertFalse(TaskArtifact.objects.for_team(self.team.id).exists())
+
@patch("products.tasks.backend.logic.services.living_artifacts._canvas_file_artifacts_enabled", return_value=True)
@patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")
def test_slack_file_adapter_requires_file_scope(self, mock_integration_for_mapping, _mock_flag):
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index c4e97bbefee6..bd992b56cf0d 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -796,7 +796,7 @@ class TaskRunLivingArtifactCreateRequestSerializer(serializers.Serializer):
content_base64 = serializers.CharField(
required=False,
allow_blank=False,
- help_text="Base64-encoded binary content for Slack file uploads or other external adapters. Prefer source_artifact_id or source_storage_path for large files that were already uploaded as run artifacts.",
+ help_text="Base64-encoded binary content for Slack file uploads or other external adapters. Prefer source_artifact_id or source_storage_path for large files that were already uploaded as run output artifacts.",
)
content_type = serializers.CharField(
max_length=255,
@@ -807,12 +807,12 @@ class TaskRunLivingArtifactCreateRequestSerializer(serializers.Serializer):
source_artifact_id = serializers.CharField(
required=False,
allow_blank=True,
- help_text="Existing run artifact id to use as the initial content source.",
+ help_text="Existing run artifact id to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.",
)
source_storage_path = serializers.CharField(
required=False,
allow_blank=True,
- help_text="Existing run artifact storage_path to use as the initial content source.",
+ help_text="Existing run artifact storage_path to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.",
)
metadata = serializers.DictField(
child=serializers.JSONField(),
@@ -877,12 +877,12 @@ class TaskRunLivingArtifactEditRequestSerializer(serializers.Serializer):
source_artifact_id = serializers.CharField(
required=False,
allow_blank=True,
- help_text="Existing run artifact id to use as the next version content source.",
+ help_text="Existing run artifact id to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.",
)
source_storage_path = serializers.CharField(
required=False,
allow_blank=True,
- help_text="Existing run artifact storage_path to use as the next version content source.",
+ help_text="Existing run artifact storage_path to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.",
)
metadata = serializers.DictField(
child=serializers.JSONField(),
diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.py
index 87c7d6b2a04b..dbba1966aa93 100644
--- a/products/tasks/backend/temporal/slack_relay/activities.py
+++ b/products/tasks/backend/temporal/slack_relay/activities.py
@@ -5,7 +5,6 @@ from typing import Any
from markdown_to_mrkdwn import SlackMarkdownConverter
from temporalio import activity
-from posthog.storage import object_storage
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import close_db_connections
@@ -34,7 +33,6 @@ _RE_LOCAL_DELIVERABLE_REFERENCE = re.compile(
re.IGNORECASE,
)
_UNCONFIRMED_ATTACHMENT_NOTICE = "\n\n_Note: I can relay text here, but no file was attached to Slack for this run._"
-_ARTIFACT_LINKS_HEADER = "\n\n*Artifacts available in Slack:*"
# Repair pattern: bold/italic markers placed *inside* the close of a Slack-style
# angle-bracket link, e.g. ``**<https://example.com**>`` instead of
@@ -118,45 +116,6 @@ def _append_unconfirmed_attachment_notice(
return f"{text.rstrip()}{_UNCONFIRMED_ATTACHMENT_NOTICE}"
-def _append_artifact_links(
- text: str,
- *,
- artifacts: list[Any] | None,
- origin_product: str | None,
- enabled: bool = False,
-) -> str:
- if not enabled or origin_product != "slack" or not artifacts:
- return text
-
- normalized = " ".join(text.split())
- if not _RE_DELIVERY_CLAIM.search(normalized) and not _RE_LOCAL_DELIVERABLE_REFERENCE.search(normalized):
- return text
-
- lines: list[str] = []
- for artifact in artifacts[:5]:
- if not isinstance(artifact, dict):
- continue
- # Run manifests also contain checkpoints and user inputs; only explicit agent outputs are shareable.
- if artifact.get("type") != "output" or artifact.get("source") != "agent_output":
- continue
- name = str(artifact.get("name") or "Artifact")
- storage_path = artifact.get("storage_path")
- if not storage_path:
- continue
- try:
- url = object_storage.get_presigned_url(storage_path)
- except Exception:
- logger.warning("slack_relay_artifact_presign_failed", storage_path=storage_path, exc_info=True)
- continue
- if not url:
- continue
- lines.append(f"- <{url}|{name}>")
-
- if not lines:
- return text
- return f"{text.rstrip()}{_ARTIFACT_LINKS_HEADER}\n" + "\n".join(lines)
-
-
def _repair_link_trailing_markers(text: str) -> str:
"""Move emphasis markers from inside a Slack-style link close to outside.
@@ -397,7 +356,6 @@ class RelaySlackMessageInput:
@activity.defn
@close_db_connections
def relay_slack_message(input: RelaySlackMessageInput) -> None:
- from products.slack_app.backend.feature_flags import is_slack_app_living_artifacts_enabled
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
from products.tasks.backend.models import TaskRun
@@ -424,22 +382,16 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
logger.info("slack_relay_empty_text", run_id=input.run_id, relay_id=input.relay_id)
return
- living_artifacts_enabled = is_slack_app_living_artifacts_enabled(mapping.integration)
- has_pending_slack_files = living_artifacts_enabled and has_pending_slack_file_artifacts(task_run)
+ # Living-artifacts gating lives in the service: has_pending_slack_file_artifacts
+ # (and deliver_pending_slack_file_artifacts below) return falsy when the
+ # workspace's living-artifacts flag is off. Run-manifest artifacts are internal
+ # and must never surface here — Slack delivery goes through living artifacts only.
+ has_pending_slack_files = has_pending_slack_file_artifacts(task_run)
if not has_pending_slack_files:
- text_with_artifact_links = _append_artifact_links(
+ text = _append_unconfirmed_attachment_notice(
text,
- artifacts=task_run.artifacts,
origin_product=mapping.task.origin_product,
- enabled=living_artifacts_enabled,
)
- if text_with_artifact_links == text:
- text = _append_unconfirmed_attachment_notice(
- text,
- origin_product=mapping.task.origin_product,
- )
- else:
- text = text_with_artifact_links
# Split the raw markdown first, then convert each chunk independently. Converting
# per-chunk means an inline span broken by a hard char split (e.g. ``**bold**``
diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
index db389f95d609..8c310198beaf 100644
--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
@@ -17,7 +17,6 @@ from products.tasks.backend.models import Task, TaskArtifact, TaskRun
from products.tasks.backend.temporal.slack_relay.activities import (
SLACK_MESSAGE_TEXT_LIMIT,
RelaySlackMessageInput,
- _append_artifact_links,
_append_unconfirmed_attachment_notice,
_markdown_to_slack_mrkdwn,
_neutralize_approx_tildes,
@@ -178,19 +177,20 @@ class TestRelaySlackMessage(TestCase):
assert "user_activity_report.pdf" in posted
assert "no file was attached to Slack for this run" in posted
- @patch("products.slack_app.backend.feature_flags.is_slack_app_living_artifacts_enabled", return_value=False)
- @patch("products.tasks.backend.temporal.slack_relay.activities.object_storage.get_presigned_url")
+ @patch("products.slack_app.backend.feature_flags.is_slack_app_living_artifacts_enabled", return_value=True)
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
- def test_artifact_links_are_not_added_when_flag_is_off(
+ def test_run_manifest_artifacts_never_surface_in_slack(
self,
_mock_delete_progress,
mock_post,
_mock_update,
- mock_presign,
_mock_flag,
):
+ # Run-manifest artifacts are internal (checkpoints, inputs, raw agent outputs).
+ # Even with living artifacts enabled they must not leak into the posted text,
+ # and their presence must not suppress the unconfirmed-attachment notice.
self.task_run.artifacts = [
{
"id": "artifact-1",
@@ -207,7 +207,7 @@ class TestRelaySlackMessage(TestCase):
relay_slack_message(
RelaySlackMessageInput(
run_id=str(self.task_run.id),
- relay_id="relay-artifact-flag-off",
+ relay_id="relay-manifest-artifacts",
text=text,
)
)
@@ -215,10 +215,9 @@ class TestRelaySlackMessage(TestCase):
mock_post.assert_called_once()
posted = mock_post.call_args.args[0]
assert "Artifacts available in Slack" not in posted
+ assert "tasks/artifacts/report.pdf" not in posted
assert "no file was attached to Slack for this run" in posted
- mock_presign.assert_not_called()
- @patch("products.slack_app.backend.feature_flags.is_slack_app_living_artifacts_enabled", return_value=True)
@patch(
"products.tasks.backend.logic.services.living_artifacts._living_artifacts_enabled_for_mapping",
return_value=True,
@@ -240,7 +239,6 @@ class TestRelaySlackMessage(TestCase):
mock_requests_post,
_mock_canvas_file_flag,
_mock_living_artifacts_flag,
- _mock_slack_artifacts_flag,
):
storage_path = f"tasks/artifacts/team_{self.team.id}/task_{self.task.id}/run_{self.task_run.id}/report.v1.xlsx"
location = {
@@ -532,56 +530,6 @@ class TestAppendUnconfirmedAttachmentNotice(unittest.TestCase):
assert result == text
-class TestAppendArtifactLinks(unittest.TestCase):
- @parameterized.expand(
- [
- (
- "disabled_by_default",
- None,
- {"name": "report.pdf", "type": "output", "source": "agent_output", "storage_path": "report"},
- False,
- ),
- (
- "enabled_internal_artifact",
- True,
- {"name": "handoff.index", "type": "artifact", "source": "agent_output", "storage_path": "index"},
- False,
- ),
- (
- "enabled_agent_output",
- True,
- {"name": "report.pdf", "type": "output", "source": "agent_output", "storage_path": "report"},
- True,
- ),
- ]
- )
- @patch(
- "products.tasks.backend.temporal.slack_relay.activities.object_storage.get_presigned_url",
- return_value="https://example.com/report.pdf",
- )
- def test_only_enabled_agent_outputs_receive_links(
- self, _name, enabled, artifact, expected_link, mock_presign
- ) -> None:
- text = "Done. The file is attached."
-
- if enabled is None:
- result = _append_artifact_links(text, artifacts=[artifact], origin_product="slack")
- else:
- result = _append_artifact_links(
- text,
- artifacts=[artifact],
- origin_product="slack",
- enabled=enabled,
- )
-
- if expected_link:
- assert "<https://example.com/report.pdf|report.pdf>" in result
- mock_presign.assert_called_once_with("report")
- else:
- assert result == text
- mock_presign.assert_not_called()
-
-
class TestSplitTextForSlack(TestCase):
def test_short_text_returns_single_chunk(self):
assert _split_markdown_for_slack("hello world") == ["hello world"]
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index fefdabcd4daf..92ae4fff64a7 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -2140,16 +2140,16 @@ export interface TaskRunLivingArtifactCreateRequestApi {
* @maxLength 500000
*/
content?: string
- /** Base64-encoded binary content for Slack file uploads or other external adapters. Prefer source_artifact_id or source_storage_path for large files that were already uploaded as run artifacts. */
+ /** Base64-encoded binary content for Slack file uploads or other external adapters. Prefer source_artifact_id or source_storage_path for large files that were already uploaded as run output artifacts. */
content_base64?: string
/**
* MIME type for content_base64 or source-backed artifacts, such as application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
* @maxLength 255
*/
content_type?: string
- /** Existing run artifact id to use as the initial content source. */
+ /** Existing run artifact id to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected. */
source_artifact_id?: string
- /** Existing run artifact storage_path to use as the initial content source. */
+ /** Existing run artifact storage_path to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected. */
source_storage_path?: string
/** Optional metadata to persist with the living artifact. */
metadata?: TaskRunLivingArtifactCreateRequestApiMetadata
@@ -2239,9 +2239,9 @@ export interface TaskRunLivingArtifactEditRequestApi {
* @maxLength 255
*/
content_type?: string
- /** Existing run artifact id to use as the next version content source. */
+ /** Existing run artifact id to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected. */
source_artifact_id?: string
- /** Existing run artifact storage_path to use as the next version content source. */
+ /** Existing run artifact storage_path to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected. */
source_storage_path?: string
/** Optional metadata to merge into the artifact registry record. */
metadata?: TaskRunLivingArtifactEditRequestApiMetadata
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 0c5282765d17..13b30c0b8a9a 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -1799,7 +1799,7 @@ export const TasksRunsLivingArtifactsCreateBody = /* @__PURE__ */ zod.object({
.string()
.optional()
.describe(
- 'Base64-encoded binary content for Slack file uploads or other external adapters. Prefer source_artifact_id or source_storage_path for large files that were already uploaded as run artifacts.'
+ 'Base64-encoded binary content for Slack file uploads or other external adapters. Prefer source_artifact_id or source_storage_path for large files that were already uploaded as run output artifacts.'
),
content_type: zod
.string()
@@ -1811,11 +1811,15 @@ export const TasksRunsLivingArtifactsCreateBody = /* @__PURE__ */ zod.object({
source_artifact_id: zod
.string()
.optional()
- .describe('Existing run artifact id to use as the initial content source.'),
+ .describe(
+ 'Existing run artifact id to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.'
+ ),
source_storage_path: zod
.string()
.optional()
- .describe('Existing run artifact storage_path to use as the initial content source.'),
+ .describe(
+ 'Existing run artifact storage_path to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.'
+ ),
metadata: zod
.record(zod.string(), zod.unknown())
.optional()
@@ -1855,11 +1859,15 @@ export const TasksRunsLivingArtifactsEditBody = /* @__PURE__ */ zod.object({
source_artifact_id: zod
.string()
.optional()
- .describe('Existing run artifact id to use as the next version content source.'),
+ .describe(
+ 'Existing run artifact id to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.'
+ ),
source_storage_path: zod
.string()
.optional()
- .describe('Existing run artifact storage_path to use as the next version content source.'),
+ .describe(
+ 'Existing run artifact storage_path to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected.'
+ ),
metadata: zod
.record(zod.string(), zod.unknown())
.optional()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 06e0ba8a63b2..49e3e0c18587 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -58741,16 +58741,16 @@ export namespace Schemas {
* @maxLength 500000
*/
content?: string;
- /** Base64-encoded binary content for Slack file uploads or other external adapters. Prefer source_artifact_id or source_storage_path for large files that were already uploaded as run artifacts. */
+ /** Base64-encoded binary content for Slack file uploads or other external adapters. Prefer source_artifact_id or source_storage_path for large files that were already uploaded as run output artifacts. */
content_base64?: string;
/**
* MIME type for content_base64 or source-backed artifacts, such as application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.
* @maxLength 255
*/
content_type?: string;
- /** Existing run artifact id to use as the initial content source. */
+ /** Existing run artifact id to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected. */
source_artifact_id?: string;
- /** Existing run artifact storage_path to use as the initial content source. */
+ /** Existing run artifact storage_path to use as the initial content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected. */
source_storage_path?: string;
/** Optional metadata to persist with the living artifact. */
metadata?: TaskRunLivingArtifactCreateRequestMetadata;
@@ -58779,9 +58779,9 @@ export namespace Schemas {
* @maxLength 255
*/
content_type?: string;
- /** Existing run artifact id to use as the next version content source. */
+ /** Existing run artifact id to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected. */
source_artifact_id?: string;
- /** Existing run artifact storage_path to use as the next version content source. */
+ /** Existing run artifact storage_path to use as the next version content source. Only agent-uploaded output artifacts are accepted; internal run artifacts are rejected. */
source_storage_path?: string;
/** Optional metadata to merge into the artifact registry record. */
metadata?: TaskRunLivingArtifactEditRequestMetadata;