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(slack-app): offer chart delivery in task prompts (#75261)

Sam Penningtondc0d6e7a3327
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index beaf367e51e7..659aab82e863 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -38,6 +38,11 @@ _SLACK_ARTIFACT_DELIVERY_KEY = "slack_artifact_delivery"
_SLACK_ARTIFACT_DELIVERY_NONE = "none"
_SLACK_ARTIFACT_DELIVERY_MESSAGE = "message"
_SLACK_ARTIFACT_DELIVERY_CANVAS_FILE = "canvas_file"
+# Charts are a second key rather than a fourth mode: an agent build that predates them
+# ignores an unknown key and still renders the mode it knows, whereas an unknown *mode*
+# matches nothing and drops the delivery constraints entirely. The agent ships as a
+# published package baked into the sandbox image, so it can lag a backend deploy.
+_SLACK_CHART_DELIVERY_KEY = "slack_chart_delivery"
# Cap on how many messages a single follow-up update block can carry. Threads with
@@ -117,11 +122,14 @@ def _indent_body(text: str, indent: str = " ") -> str:
def _artifact_delivery_state_updates(integration: Integration) -> dict[str, Any]:
"""Run state telling the agent which Slack delivery routes this workspace has.
- The agent turns the mode into its delivery constraints, so the wording lives with the
+ The agent turns these into its delivery constraints, so the wording lives with the
agent and the gating stays here. Canvas and file delivery needs its own rollout flag
*and* the Slack scopes the adapters write with, so that the agent is never invited to
- create an artifact delivery would reject. Resolved when the run is created, before the
- sandbox boots and reads the state.
+ create an artifact delivery would reject. Charts are gated on the flag alone: they
+ post as an image block referencing a PostHog-hosted url, which needs no upload and so
+ no ``files:write``. That difference is the whole point of the separate key — a
+ workspace waiting on the in-review scopes can still deliver charts. Resolved when the
+ run is created, before the sandbox boots and reads the state.
"""
from products.slack_app.backend.feature_flags import ( # noqa: PLC0415
is_slack_app_canvas_file_artifacts_enabled,
@@ -129,14 +137,14 @@ def _artifact_delivery_state_updates(integration: Integration) -> dict[str, Any]
)
if not is_slack_app_living_artifacts_enabled(integration):
- mode = _SLACK_ARTIFACT_DELIVERY_NONE
- elif is_slack_app_canvas_file_artifacts_enabled(integration) and not SlackIntegration(integration).missing_scopes(
- _SLACK_CANVAS_FILE_ADAPTER_SCOPES
- ):
+ return {_SLACK_ARTIFACT_DELIVERY_KEY: _SLACK_ARTIFACT_DELIVERY_NONE, _SLACK_CHART_DELIVERY_KEY: False}
+
+ charts_enabled = is_slack_app_canvas_file_artifacts_enabled(integration)
+ if charts_enabled and not SlackIntegration(integration).missing_scopes(_SLACK_CANVAS_FILE_ADAPTER_SCOPES):
mode = _SLACK_ARTIFACT_DELIVERY_CANVAS_FILE
else:
mode = _SLACK_ARTIFACT_DELIVERY_MESSAGE
- return {_SLACK_ARTIFACT_DELIVERY_KEY: mode}
+ return {_SLACK_ARTIFACT_DELIVERY_KEY: mode, _SLACK_CHART_DELIVERY_KEY: charts_enabled}
def _uploaded_attachment_ids(uploaded_artifacts: list[dict[str, Any]]) -> list[str]:
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 79f12aee6dc9..c79a415cfb12 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
@@ -78,21 +78,23 @@ def test_build_description_keeps_the_prompt_bare_without_a_context_block(thread_
@pytest.mark.parametrize(
- "living_enabled,canvas_flag_enabled,granted_scopes,expected_mode",
+ "living_enabled,canvas_flag_enabled,granted_scopes,expected_mode,expected_charts",
[
- (True, True, "chat:write,canvases:write,files:write", "canvas_file"),
- (True, True, "chat:write,canvases:write", "message"),
- (True, True, "chat:write", "message"),
- (True, False, "chat:write,canvases:write,files:write", "message"),
- (False, True, "chat:write,canvases:write,files:write", "none"),
+ (True, True, "chat:write,canvases:write,files:write", "canvas_file", True),
+ (True, True, "chat:write,canvases:write", "message", True),
+ (True, True, "chat:write", "message", True),
+ (True, False, "chat:write,canvases:write,files:write", "message", False),
+ (False, True, "chat:write,canvases:write,files:write", "none", False),
],
)
def test_artifact_delivery_mode_offers_only_what_delivery_accepts(
- living_enabled, canvas_flag_enabled, granted_scopes, expected_mode
+ living_enabled, canvas_flag_enabled, granted_scopes, expected_mode, expected_charts
):
- # The agent offers whatever this mode says, so it must never claim more than the
+ # The agent offers whatever this state says, so it must never claim more than the
# workspace has: canvas/file needs its flag AND both scopes AND the umbrella gate,
- # or the agent promises an artifact the adapters then reject.
+ # or the agent promises an artifact the adapters then reject. Charts clear on the flag
+ # and the umbrella gate alone, which is why the two rows with the flag on but a scope
+ # missing still get charts while dropping to message mode.
integration = Integration(kind="slack", config={"scope": granted_scopes})
with (
@@ -105,7 +107,10 @@ def test_artifact_delivery_mode_offers_only_what_delivery_accepts(
return_value=canvas_flag_enabled,
),
):
- assert _artifact_delivery_state_updates(integration) == {"slack_artifact_delivery": expected_mode}
+ assert _artifact_delivery_state_updates(integration) == {
+ "slack_artifact_delivery": expected_mode,
+ "slack_chart_delivery": expected_charts,
+ }
def test_build_description_renders_labeled_mention_for_each_author():
diff --git a/products/desktop/packages/agent/src/server/agent-server.test.ts b/products/desktop/packages/agent/src/server/agent-server.test.ts
index 4c3dbb2851c9..b56be4e4f640 100644
--- a/products/desktop/packages/agent/src/server/agent-server.test.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.test.ts
@@ -229,6 +229,7 @@ interface TestableServer {
): Promise<void>;
detectedPrUrl: string | null;
slackArtifactDelivery: "none" | "message" | "canvas_file" | null;
+ slackChartDelivery: boolean;
buildCloudSystemPrompt(
prUrl?: string | null,
slackThreadUrl?: string | null,
@@ -4150,6 +4151,59 @@ describe("AgentServer HTTP Mode", () => {
);
});
+ // Charts need only the rollout flag, while canvas/file also needs Slack scopes still in
+ // review, so the chart offer has to be independent of the delivery mode in both
+ // directions: present on a message-only workspace, absent on a canvas_file one whose
+ // backend never sent the key.
+ it.each([
+ { delivery: "canvas_file" as const, charts: true },
+ { delivery: "message" as const, charts: true },
+ ])(
+ "offers the chart endpoint on a $delivery workspace when charts are on",
+ ({ delivery, charts }) => {
+ const s = createServer() as unknown as TestableServer;
+ s.slackArtifactDelivery = delivery;
+ s.slackChartDelivery = charts;
+
+ const prompt = s.buildCloudSystemPrompt();
+
+ expect(prompt).toContain("living_artifacts/chart/");
+ expect(prompt).toContain("deliver a chart image by default");
+ },
+ );
+
+ it.each([
+ { delivery: "canvas_file" as const },
+ { delivery: "message" as const },
+ { delivery: "none" as const },
+ ])(
+ "never mentions charts on a $delivery workspace when charts are off",
+ ({ delivery }) => {
+ const s = createServer() as unknown as TestableServer;
+ s.slackArtifactDelivery = delivery;
+ s.slackChartDelivery = false;
+
+ expect(s.buildCloudSystemPrompt()).not.toContain(
+ "living_artifacts/chart/",
+ );
+ },
+ );
+
+ it("tells a message-only workspace that charts are the exception to the no-file rule", () => {
+ // Without this the two bullets contradict each other: one forbids file delivery, the
+ // other tells the agent to deliver an image.
+ const s = createServer() as unknown as TestableServer;
+ s.slackArtifactDelivery = "message";
+ s.slackChartDelivery = true;
+
+ const prompt = s.buildCloudSystemPrompt();
+
+ expect(prompt).toContain("Chart images are the one exception");
+ expect(prompt).toContain(
+ "cannot be expressed as a Slack message or a chart image",
+ );
+ });
+
it("describes every repository in a shared multi-repository workspace", () => {
const s = createServer({
repositoryPath: undefined,
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index afa3230e4866..77bd549d9352 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -367,6 +367,22 @@ function readSlackArtifactDelivery(
return SLACK_ARTIFACT_DELIVERY_MODES.find((known) => known === mode) ?? null;
}
+/**
+ * Charts ride on their own key rather than a delivery mode: they need only the rollout
+ * flag, while canvas and file delivery also needs Slack scopes that are still in review,
+ * so a workspace can have charts and nothing else. Absent or non-boolean means a backend
+ * that predates charts, which is the same as off.
+ */
+function readSlackChartDelivery(taskRun: TaskRun | null): boolean {
+ const state = taskRun?.state;
+
+ if (!state || typeof state !== "object") {
+ return false;
+ }
+
+ return (state as Record<string, unknown>).slack_chart_delivery === true;
+}
+
// Prompt block we hand the agent when the user attached files but we could not
// load any of them into the session (missing from the run manifest, no storage
// path, etc.). Without this the caller falls back to the bare task description —
@@ -401,6 +417,7 @@ export class AgentServer {
private runUsage = new RunUsageAccumulator();
private detectedPrUrl: string | null = null;
private slackArtifactDelivery: SlackArtifactDelivery | null = null;
+ private slackChartDelivery = false;
private taskRepositories: string[] = [];
// Reset per session. `evaluatedPrUrls` dedupes per URL; `prAttributionChain` serializes
// attributions so the most recently created PR in a run wins.
@@ -1643,6 +1660,7 @@ export class AgentServer {
// Unconditional for the same reason as detectedPrUrl: a re-init on this
// instance must not keep the previous run's delivery capability.
this.slackArtifactDelivery = readSlackArtifactDelivery(preTaskRun);
+ this.slackChartDelivery = readSlackChartDelivery(preTaskRun);
// Web backlink to the inbox report that spawned this task, so the
// auto-generated PR can point back at it. Built from the same pieces as the
@@ -3674,16 +3692,33 @@ export class AgentServer {
- Do not say a file, report, PDF, spreadsheet, document, or other artifact is attached, uploaded, or shared unless a tool explicitly confirms that delivery.
- 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.`;
+ // Charts attach to both modes: they post as an image block referencing a PostHog-hosted
+ // url, so they work wherever the workspace can post at all.
+ const chartBullets = this.slackChartDelivery
+ ? `
+- When an analytics answer is naturally visual (a trend over time, funnel, breakdown comparison, retention curve), deliver a chart image by default alongside the summary. Do not wait for the user to say "chart". Skip the image only when the result is a single number, a short list, or the user asked for raw data.
+- To show a chart in Slack (a saved insight or an ad-hoc analytics query result), make a single call: POST to \`${endpoint}chart/\` with \`$POSTHOG_PERSONAL_API_KEY\` and body \`{"name": "<chart title>", "query": <query JSON, e.g. {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", ...}}>}\`, or \`{"name": "<chart title>", "insight_id": <numeric insight id>}\` for a saved insight. It renders the chart server-side and registers it for Slack delivery in one step, blocking until done (typically a few seconds).
+- The chart renders directly under your answer text with its name as the title, so do not restate the title or announce the chart ("Here's a chart of…"). Spend your answer text on the takeaway instead: the trend, inflection points, spikes, or drops a reader should notice, with numbers where they matter. Each chart is delivered with an "Open in PostHog" button, so do not paste the response \`url\` into your answer unless the user explicitly asks for a link. Do not download, view, or re-upload the image yourself.
+- Report a chart failure rather than retrying blindly: a 400 carries the reason in \`error\`, or in \`detail\` when the request body itself was rejected, and a 429 means the project's chart render limit is saturated, so answer without the chart.
+- SQL results cannot be charted yet, because the chart endpoint rejects SQL queries. Chart with an insight query (e.g. TrendsQuery) when the question can be expressed as one; otherwise summarize the SQL result in your answer text.`
+ : "";
+
if (this.slackArtifactDelivery === "message") {
+ const chartException = this.slackChartDelivery
+ ? " Chart images are the one exception: deliver them through the dedicated chart endpoint below, never through the generic living-artifacts endpoint."
+ : "";
+ const unsupportedDeliverable = this.slackChartDelivery
+ ? "- If a deliverable cannot be expressed as a Slack message or a chart image (for example .xlsx/.pdf/.docx), say that plainly and summarize the result in Slack instead."
+ : "- 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.";
return `${preamble}
-- 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 \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\` using adapter \`slack_message\`. To update a prior deliverable, GET the returned artifact id or POST new \`content\` to \`${endpoint}<artifact_id>/edit/\`.
-- 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.`;
+- 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.${chartException}
+- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` with \`$POSTHOG_PERSONAL_API_KEY\` using adapter \`slack_message\`. To update a prior deliverable, GET the returned artifact id or POST new \`content\` to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}
+${unsupportedDeliverable}`;
}
return `${preamble}
- For Slack deliverables, create a living artifact before claiming delivery. POST to \`${endpoint}\` 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.
-- To update a prior deliverable, GET the returned artifact id or POST new \`content\`, \`content_base64\`, or source artifact fields to \`${endpoint}<artifact_id>/edit/\`.
+- To update a prior deliverable, GET the returned artifact id or POST new \`content\`, \`content_base64\`, or source artifact fields to \`${endpoint}<artifact_id>/edit/\`.${chartBullets}
- 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.`;
}
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index 0e3b55d46a33..bc8337949d2c 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -170,7 +170,9 @@ def is_slack_app_canvas_file_artifacts_enabled(integration: Integration) -> bool
install authorized earlier won't have them until it reconnects.
The flag alone: the two adapters need one scope each, so they check theirs at point
- of use and can name the one to grant. Keyed on the Slack workspace + PostHog org."""
+ of use and can name the one to grant, and chart images post by public url on
+ ``chat:write`` alone, so this flag can roll charts out ahead of those grants. Keyed
+ on the Slack workspace + PostHog org."""
try:
return bool(
posthoganalytics.feature_enabled(