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): agent design (#64293)

Vojta Bartošdc48fc87541d
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index 6af616adb358..581186b60fae 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -18,6 +18,7 @@ logger = structlog.get_logger(__name__)
SLACK_APP_OAUTH_FLAG = "slack-app-oauth"
SLACK_APP_HOME_FLAG = "slack-app-home"
+SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"
def slack_oauth_link_enabled(integration: Integration, slack_team_id: str) -> bool:
@@ -58,6 +59,24 @@ def slack_oauth_link_enabled(integration: Integration, slack_team_id: str) -> bo
return False
+def is_slack_app_agent_design_enabled(integration_id: int) -> bool:
+ """Fail-closed agent-design gate. Per-integration key + region targeting.
+ Local-only eval — see ``slack_oauth_link_enabled``."""
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ SLACK_APP_AGENT_DESIGN_FLAG,
+ f"slack_integration:{integration_id}",
+ person_properties={"region": get_instance_region() or "unknown"},
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception("slack_app_agent_design_feature_flag_check_failed", integration_id=integration_id)
+ return False
+
+
def is_slack_app_home_enabled(integration: Integration, *, region: str | None = None) -> bool:
"""Return True when the ``slack-app-home`` flag is on for this workspace.
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index e3f5bc3bc652..46de89b971e8 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -16,6 +16,47 @@ UPSTREAM_PROVIDER_FAILURE_MESSAGE = (
UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN = re.compile(r"\bapi error:\s*(?:429|5\d\d)\b", re.IGNORECASE)
+_TASK_FIELD_LIMIT = 256
+_MARKDOWN_CHUNK_LIMIT = 12000
+
+
+def _split_markdown_text(text: str, limit: int = _MARKDOWN_CHUNK_LIMIT) -> list[str]:
+ """≤limit pieces at paragraph/line boundaries. Slack stitches chunks server-side."""
+ if len(text) <= limit:
+ return [text]
+ pieces: list[str] = []
+ remaining = text
+ while len(remaining) > limit:
+ cut = remaining.rfind("\n\n", 0, limit)
+ if cut <= 0:
+ cut = remaining.rfind("\n", 0, limit)
+ if cut <= 0:
+ cut = limit
+ pieces.append(remaining[:cut])
+ remaining = remaining[cut:].lstrip("\n")
+ if remaining:
+ pieces.append(remaining)
+ return pieces
+
+
+def _task_update_chunk(
+ task_id: str,
+ title: str,
+ status: str,
+ details: str | None,
+) -> dict[str, Any]:
+ """task_update chunk with title/details truncated to Slack's 256-char cap."""
+ chunk: dict[str, Any] = {
+ "type": "task_update",
+ "id": task_id,
+ "title": title[:_TASK_FIELD_LIMIT],
+ "status": status,
+ }
+ if details:
+ chunk["details"] = details[:_TASK_FIELD_LIMIT]
+ return chunk
+
+
def _format_task_error(error: str) -> str:
error = error.strip()
if not error:
@@ -129,6 +170,111 @@ class SlackThreadHandler:
except Exception as e:
logger.warning("slack_update_reaction_failed", error=str(e))
+ def start_status_stream(
+ self,
+ first_task_id: str | None = None,
+ first_task_title: str | None = None,
+ first_task_details: str | None = None,
+ first_markdown_text: str | None = None,
+ ) -> str | None:
+ """chat.startStream in plan-block mode. Seed with EITHER a task_update
+ (starts with a plan-block step) OR a markdown_text chunk (starts as
+ prose; a plan block appears later when a task_update arrives)."""
+ if not self.context.mentioning_slack_user_id:
+ return None
+ chunks: list[dict[str, Any]] = []
+ if first_task_id and first_task_title:
+ chunks.append(_task_update_chunk(first_task_id, first_task_title, "in_progress", first_task_details))
+ if first_markdown_text:
+ for piece in _split_markdown_text(first_markdown_text):
+ chunks.append({"type": "markdown_text", "text": piece})
+ if not chunks:
+ return None
+ try:
+ client = self._get_client()
+ integration = self._get_integration()
+ response = client.chat_startStream(
+ channel=self.context.channel,
+ thread_ts=self.context.thread_ts,
+ recipient_user_id=self.context.mentioning_slack_user_id,
+ recipient_team_id=integration.integration_id,
+ task_display_mode="plan",
+ chunks=chunks,
+ )
+ ts = response.get("ts") if isinstance(response, dict) else response["ts"]
+ return ts if isinstance(ts, str) else None
+ except Exception as e:
+ logger.warning("slack_app_status_stream_start_failed", error=str(e))
+ return None
+
+ def append_status_chunks(
+ self,
+ ts: str,
+ task_updates: list[dict[str, Any]] | None = None,
+ markdown_text: str | None = None,
+ ) -> None:
+ """Append plan-block step transitions and/or markdown_text chunks."""
+ chunks: list[dict[str, Any]] = []
+ for t in task_updates or []:
+ task_id = t.get("id")
+ title = t.get("title")
+ status = t.get("status")
+ if not task_id or not title or not status:
+ continue
+ chunks.append(_task_update_chunk(str(task_id), str(title), str(status), t.get("details")))
+ if markdown_text:
+ for piece in _split_markdown_text(markdown_text):
+ chunks.append({"type": "markdown_text", "text": piece})
+ if not chunks:
+ return
+ try:
+ self._get_client().chat_appendStream(
+ channel=self.context.channel,
+ ts=ts,
+ chunks=chunks,
+ )
+ except Exception as e:
+ logger.warning("slack_app_status_stream_append_failed", error=str(e))
+
+ def stop_status_stream(
+ self,
+ ts: str,
+ complete_task_id: str | None = None,
+ complete_task_title: str | None = None,
+ complete_task_details: str | None = None,
+ final_markdown: str | None = None,
+ ) -> None:
+ """Final flush: mark the last plan-block step complete, stream the final
+ answer as markdown_text chunks (this is what STAYS in the message body),
+ append a trailing @-mention for one notification, then chat.stopStream."""
+ final_chunks: list[dict[str, Any]] = []
+ if complete_task_id and complete_task_title:
+ final_chunks.append(
+ _task_update_chunk(complete_task_id, complete_task_title, "complete", complete_task_details)
+ )
+ if final_markdown:
+ for piece in _split_markdown_text(final_markdown):
+ final_chunks.append({"type": "markdown_text", "text": piece})
+ if self.context.mentioning_slack_user_id:
+ # Newlines keep the mention off the tail of the last streamed prose chunk.
+ final_chunks.append({"type": "markdown_text", "text": f"\n\n<@{self.context.mentioning_slack_user_id}>"})
+ if final_chunks:
+ try:
+ self._get_client().chat_appendStream(
+ channel=self.context.channel,
+ ts=ts,
+ chunks=final_chunks,
+ )
+ except Exception as e:
+ logger.warning("slack_app_status_stream_final_append_failed", error=str(e))
+ try:
+ self._get_client().chat_stopStream(
+ channel=self.context.channel,
+ ts=ts,
+ )
+ except Exception as e:
+ logger.warning("slack_app_status_stream_stop_failed", error=str(e))
+
def post_or_update_progress(
self,
stage: str,
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 3e8f0cf8933f..a57f377df9e7 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2042,10 +2042,12 @@ def relay_task_run_message(
text: str,
text_parts: list[str] | None = None,
) -> tuple[str, str | None]:
- """Queue a Slack relay workflow for a run message.
+ """Queue a Slack relay workflow for a run message, or under the agent-design
+ flag signal the running task workflow to stream the text inline.
Returns ``(status, relay_id)`` where status is ``"accepted"`` (relay_id set), ``"skipped"``
- (run not found / terminal / no Slack mapping / empty text), or ``"failed"``.
+ (run not found / terminal / no Slack mapping / empty text / streamed inline under the
+ agent-design flag), or ``"failed"``.
When ``text_parts`` is provided the last non-empty entry is used — it's the
post-last-tool-use answer, and posting only that keeps the interim narration
@@ -2055,8 +2057,13 @@ def relay_task_run_message(
from products.slack_app.backend.models import ( # noqa: PLC0415 — cross-product import kept off the api import path
SlackThreadTaskMapping,
)
+ from products.tasks.backend.models import TaskRun # noqa: PLC0415 — keep ORM off the api import path
from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path
execute_posthog_code_agent_relay_workflow,
+ signal_agent_text_delta,
+ )
+ from products.tasks.backend.temporal.process_task.activities.feature_flags import ( # noqa: PLC0415 — keep temporal off the api import path
+ AGENT_DESIGN_STATE_KEY,
)
run = _get_visible_run(run_id, task_id, team_id)
@@ -2070,6 +2077,13 @@ def relay_task_run_message(
if not trimmed:
return "skipped", None
+ if bool((run.state or {}).get(AGENT_DESIGN_STATE_KEY)):
+ try:
+ signal_agent_text_delta(TaskRun.get_workflow_id(str(run.task_id), str(run.id)), trimmed)
+ except Exception:
+ logger.exception("task_run_relay_text_signal_failed", extra={"run_id": str(run.id)})
+ return "skipped", None
+
try:
relay_id = execute_posthog_code_agent_relay_workflow(run_id=str(run.id), text=trimmed, delete_progress=True)
except Exception:
diff --git a/products/tasks/backend/temporal/__init__.py b/products/tasks/backend/temporal/__init__.py
index 69904bd70612..56cf04d02ad7 100644
--- a/products/tasks/backend/temporal/__init__.py
+++ b/products/tasks/backend/temporal/__init__.py
@@ -40,12 +40,20 @@ from .process_task.activities import (
track_workflow_event,
update_task_run_status,
)
+from .process_task.activities.feature_flags import is_slack_app_agent_design_enabled_for_task_activity
from .process_task.activities.get_pr_context import get_pr_context
+from .process_task.activities.slack_agent_design import (
+ append_slack_agent_design_steps,
+ start_slack_agent_design_stream,
+ stop_slack_agent_design_stream,
+)
+from .process_task.slack_agent_design_relay import SlackAgentDesignRelayWorkflow
from .process_task.workflow import ProcessTaskWorkflow
from .slack_relay import PostHogCodeAgentRelayWorkflow, relay_slack_message
WORKFLOWS = [
ProcessTaskWorkflow,
+ SlackAgentDesignRelayWorkflow,
CreateSnapshotForRepositoryWorkflow,
PostHogCodeAgentRelayWorkflow,
RunTaskAutomationWorkflow,
@@ -81,6 +89,10 @@ ACTIVITIES = [
update_task_run_status,
get_pr_context,
relay_slack_message,
+ is_slack_app_agent_design_enabled_for_task_activity,
+ start_slack_agent_design_stream,
+ append_slack_agent_design_steps,
+ stop_slack_agent_design_stream,
run_task_automation_activity,
# create_snapshot activities
get_snapshot_context,
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 3195aa09e3dc..0e2f73ecc49a 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -412,6 +412,13 @@ def signal_task_followup_message(workflow_id: str, message: str | None, artifact
asyncio.run(handle.signal("send_followup_message", args=[message, artifact_ids]))
+def signal_agent_text_delta(workflow_id: str, text: str) -> None:
+ """Push text into the live agent-design plan-block stream for a running task."""
+ client = sync_connect()
+ handle = client.get_workflow_handle(workflow_id)
+ asyncio.run(handle.signal("agent_text_delta", text))
+
+
def execute_posthog_code_agent_relay_workflow(
run_id: str,
text: str,
diff --git a/products/tasks/backend/temporal/process_task/activities/feature_flags.py b/products/tasks/backend/temporal/process_task/activities/feature_flags.py
new file mode 100644
index 000000000000..398014ff19df
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/activities/feature_flags.py
@@ -0,0 +1,40 @@
+from dataclasses import dataclass
+from typing import Any
+
+from temporalio import activity
+
+from posthog.temporal.common.logger import get_logger
+from posthog.temporal.common.utils import close_db_connections
+
+logger = get_logger(__name__)
+
+
+@dataclass
+class IsSlackAppAgentDesignEnabledForTaskActivityInput:
+ integration_id: int
+ run_id: str
+
+
+AGENT_DESIGN_STATE_KEY = "slack_app_agent_design_enabled"
+
+
+@close_db_connections
+def is_slack_app_agent_design_enabled_for_task_activity(
+ input: IsSlackAppAgentDesignEnabledForTaskActivityInput,
+) -> bool:
+ """Flag check + persist to TaskRun.state so out-of-workflow callers (e.g.
+ forward_pending_message) can read the decision without re-evaluating."""
+ from products.slack_app.backend.feature_flags import is_slack_app_agent_design_enabled
+ from products.tasks.backend.models import TaskRun
+
+ enabled = is_slack_app_agent_design_enabled(input.integration_id)
+
+ def _persist(state: dict[str, Any]) -> None:
+ state[AGENT_DESIGN_STATE_KEY] = enabled
+
+ try:
+ TaskRun.mutate_state_atomic(input.run_id, _persist)
+ except Exception:
+ logger.exception("slack_app_agent_design_state_persist_failed", run_id=input.run_id)
+ return enabled
diff --git a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
index e02cc9a562bd..487cdaa8c7ed 100644
--- a/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
+++ b/products/tasks/backend/temporal/process_task/activities/forward_pending_message.py
@@ -8,6 +8,7 @@ from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import close_db_connections
from products.tasks.backend.temporal.observability import log_activity_execution
+from products.tasks.backend.temporal.process_task.activities.feature_flags import AGENT_DESIGN_STATE_KEY
logger = get_logger(__name__)
@@ -169,6 +170,10 @@ def _enqueue_pending_delivery_failure_relay(task_run: Any, user_message_ts: str
def _enqueue_pending_reply_relay(task_run: Any, user_message_ts: str | None, command_result_data: Any) -> None:
+ # Agent-design already streamed the reply into the plan block — don't post it again.
+ if bool((task_run.state or {}).get(AGENT_DESIGN_STATE_KEY)):
+ return
+
from products.tasks.backend.temporal.client import execute_posthog_code_agent_relay_workflow
reply_text = _extract_assistant_text_from_command_result(
diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
index a383db039345..8f2798a0bc58 100644
--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
@@ -4,6 +4,7 @@ import json
import time
import asyncio
from dataclasses import dataclass
+from typing import Any
import httpx
import httpx_sse
@@ -49,6 +50,10 @@ class RelaySandboxEventsInput:
team_id: int
distinct_id: str
sandbox_id: str | None = None
+ # When True + slack_thread_context set, the relay forwards per-turn signals
+ # to the parent to drive SlackAgentDesignRelayWorkflow children.
+ slack_thread_context: dict[str, Any] | None = None
+ is_agent_design_enabled: bool = False
@activity.defn
@@ -118,6 +123,8 @@ async def relay_sandbox_events(input: RelaySandboxEventsInput) -> None:
background_logs_enabled=background_logs_enabled,
task_run=task_run,
inactivity_timeout_seconds=inactivity_timeout_seconds,
+ slack_thread_context=input.slack_thread_context,
+ is_agent_design_enabled=input.is_agent_design_enabled,
)
except asyncio.CancelledError:
logger.info("relay_sandbox_events_cancelled", run_id=input.run_id)
@@ -239,6 +246,8 @@ async def _relay_loop(
background_logs_enabled: bool = False,
task_run: TaskRunModel | None = None,
inactivity_timeout_seconds: float = INACTIVITY_TIMEOUT_DEFAULT_SECONDS,
+ slack_thread_context: dict[str, Any] | None = None,
+ is_agent_design_enabled: bool = False,
) -> None:
"""Connect to sandbox SSE and relay events to Redis. Reconnects on transient failures."""
reconnect_count = 0
@@ -264,6 +273,10 @@ async def _relay_loop(
# can't leave it stuck True and emit phantom heartbeats.
agent_active: list[bool] = [False]
last_audit_ts_ns: list[int] = [0] # track last agentsh audit timestamp
+ # Brackets turn_started / turn_completed signals to the parent.
+ slack_turn_active: list[bool] = [False]
+ # ACP emits one tool_call + N tool_call_update per id; only render the start.
+ emitted_tool_call_ids: set[str] = set()
stop_heartbeat = asyncio.Event()
heartbeat_task = asyncio.create_task(
@@ -329,9 +342,37 @@ async def _relay_loop(
# does sync Redis (cache.add) and a potential network call to
# the feature-flag service.
asyncio.create_task(asyncio.to_thread(_safe_dispatch_awaiting_input, task_run))
+ if is_agent_design_enabled and slack_turn_active[0] and workflow_handle is not None:
+ slack_turn_active[0] = False
+ asyncio.create_task(_signal_safely(workflow_handle, "turn_completed"))
elif not agent_active[0] and _is_active_agent_update(event_data):
agent_active[0] = True
+ # Agent-design signal fan-out: first session/update opens the
+ # child relay; tool_call → step, agent_message_chunk → markdown.
+ if is_agent_design_enabled and workflow_handle is not None:
+ if not slack_turn_active[0] and _is_session_update(event_data):
+ slack_turn_active[0] = True
+ asyncio.create_task(
+ _signal_safely(
+ workflow_handle,
+ "turn_started",
+ arg={"slack_thread_context": slack_thread_context or {}},
+ )
+ )
+ if slack_turn_active[0]:
+ step_payload = _extract_tool_call_step(event_data, emitted_tool_call_ids)
+ if step_payload is not None:
+ asyncio.create_task(
+ _signal_safely(workflow_handle, "agent_status_update", arg=step_payload)
+ )
+ if slack_turn_active[0] and _is_session_update(event_data):
+ text_delta = _extract_agent_message_text(event_data)
+ if text_delta:
+ asyncio.create_task(
+ _signal_safely(workflow_handle, "agent_text_delta", arg=text_delta)
+ )
+
now = time.monotonic()
if (
workflow_handle is not None
@@ -447,6 +488,113 @@ def _is_active_agent_update(event_data: dict) -> bool:
return update.get("sessionUpdate") in _GENERATION_SESSION_UPDATE_SUBTYPES
+# Priority order for picking the plan-block step's details line from rawInput.
+_TOOL_ARGS_PREVIEW_KEYS = (
+ "file_path",
+ "notebook_path",
+ "path",
+ "command", # Bash
+ "code", # MCP exec / hogql / sql payloads
+ "query",
+ "pattern",
+ "url",
+ "description",
+ "prompt", # Task / Agent sub-agent
+ "name",
+ "title",
+)
+_TOOL_ARGS_PREVIEW_LIMIT = 240
+
+
+def _extract_tool_call_step(event_data: dict, seen: set[str]) -> dict[str, Any] | None:
+ """Build {title, details} from an ACP tool_call/tool_call_update.
+
+ Streaming Claude tools arrive with empty rawInput first; we defer the
+ emit + seen-write until rawInput populates so the step gets a details line.
+ """
+ if not _is_session_update(event_data):
+ return None
+ update = (event_data.get("notification", {}).get("params") or {}).get("update") or {}
+ if update.get("sessionUpdate") not in ("tool_call", "tool_call_update"):
+ return None
+
+ tool_call_id = update.get("toolCallId")
+ if not isinstance(tool_call_id, str) or tool_call_id in seen:
+ return None
+
+ # Bare tool name ("Read", "Bash") from agent meta; fall back to rendered title.
+ meta = update.get("_meta") or {}
+ title = ((meta.get("claudeCode") or {}) if isinstance(meta, dict) else {}).get("toolName")
+ if not isinstance(title, str) or not title:
+ title = update.get("title")
+ if not isinstance(title, str) or not title:
+ return None
+
+ details = _tool_args_preview(update.get("rawInput"))
+ if not details:
+ # rawInput not assembled yet — next tool_call_update will retry here.
+ return None
+
+ seen.add(tool_call_id)
+ return {"title": title, "details": details}
+
+
+def _tool_args_preview(raw_input: Any) -> str | None:
+ """First non-empty string from _TOOL_ARGS_PREVIEW_KEYS, trimmed to one line."""
+ if not isinstance(raw_input, dict):
+ return None
+ pick: str | None = None
+ for key in _TOOL_ARGS_PREVIEW_KEYS:
+ value = raw_input.get(key)
+ if isinstance(value, str) and value:
+ pick = value
+ break
+ if pick is None:
+ for value in raw_input.values():
+ if isinstance(value, str) and value.strip():
+ pick = value
+ break
+ if not pick:
+ return None
+ one_line = " ".join(pick.split())
+ if len(one_line) > _TOOL_ARGS_PREVIEW_LIMIT:
+ return one_line[: _TOOL_ARGS_PREVIEW_LIMIT - 1] + "…"
+ return one_line
+
+
+def _extract_agent_message_text(event_data: dict) -> str | None:
+ """Text delta from an ACP agent_message_chunk session/update, else None."""
+ notification = event_data.get("notification", {})
+ if notification.get("method") != "session/update":
+ return None
+ params = notification.get("params") or {}
+ update = params.get("update") or {}
+ if update.get("sessionUpdate") != "agent_message_chunk":
+ return None
+ content = update.get("content")
+ if not isinstance(content, dict):
+ return None
+ if content.get("type") != "text":
+ return None
+ text = content.get("text")
+ return text if isinstance(text, str) and text else None
+
+
+async def _signal_safely(
+ workflow_handle: temporalio.client.WorkflowHandle,
+ signal_name: str,
+ arg: Any = None,
+) -> None:
+ """Fire-and-forget signal — failures must never break the relay loop."""
+ try:
+ if arg is None:
+ await workflow_handle.signal(signal_name)
+ else:
+ await workflow_handle.signal(signal_name, arg=arg)
+ except Exception as e:
+ logger.warning("slack_app_relay_signal_failed", signal=signal_name, error=str(e))
+
+
def _is_keepalive_event(event_data: dict) -> bool:
return event_data.get("type") == "keepalive"
diff --git a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py
new file mode 100644
index 000000000000..63118b5389bc
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py
@@ -0,0 +1,114 @@
+"""Agent-design activities: chat.startStream lifecycle (start / append / stop).
+
+Every turn shape rides the same three-activity lifecycle — plan-block steps,
+interim narrative between them, and the final answer all flow as chunks into
+one streamed message. Best-effort: a Slack outage must never escalate to a
+task failure.
+"""
+
+from dataclasses import dataclass, field
+from typing import Any, Optional
+
+from temporalio import activity
+
+from posthog.temporal.common.logger import get_logger
+from posthog.temporal.common.utils import close_db_connections
+
+logger = get_logger(__name__)
+
+
+@dataclass
+class TaskUpdateChunk:
+ """One plan-block step. Flat so Temporal can serialize it."""
+
+ id: str
+ title: str
+ status: str # "in_progress" | "complete"
+ details: Optional[str] = None
+
+
+@dataclass
+class StartSlackAgentDesignStreamInput:
+ slack_thread_context: dict[str, Any]
+ # Seed with EITHER a task_update step OR a markdown_text chunk.
+ first_task_id: Optional[str] = None
+ first_task_title: Optional[str] = None
+ first_task_details: Optional[str] = None
+ first_markdown_text: Optional[str] = None
+
+
+@dataclass
+class AppendSlackAgentDesignStepsInput:
+ slack_thread_context: dict[str, Any]
+ ts: str
+ task_updates: list[TaskUpdateChunk] = field(default_factory=list)
+ markdown_text: Optional[str] = None
+
+
+@dataclass
+class StopSlackAgentDesignStreamInput:
+ slack_thread_context: dict[str, Any]
+ ts: str
+ complete_task_id: Optional[str] = None
+ complete_task_title: Optional[str] = None
+ complete_task_details: Optional[str] = None
+ # Streamed as markdown_text chunks below the plan block right before stopStream.
+ final_markdown: Optional[str] = None
+
+
+@close_db_connections
+def start_slack_agent_design_stream(input: StartSlackAgentDesignStreamInput) -> Optional[str]:
+ """Open the stream, seeded with either a first tool-call step or a first
+ markdown_text chunk (pre-first-tool-call streaming). Returns ts or None."""
+ from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
+
+ try:
+ context = SlackThreadContext.from_dict(input.slack_thread_context)
+ return SlackThreadHandler(context).start_status_stream(
+ first_task_id=input.first_task_id,
+ first_task_title=input.first_task_title,
+ first_task_details=input.first_task_details,
+ first_markdown_text=input.first_markdown_text,
+ )
+ except Exception as e:
+ logger.warning("slack_app_start_agent_design_stream_failed", error=str(e))
+ return None
+
+
+@close_db_connections
+def append_slack_agent_design_steps(input: AppendSlackAgentDesignStepsInput) -> None:
+ """Append plan-block step transitions and/or a markdown_text chunk."""
+ from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
+
+ try:
+ context = SlackThreadContext.from_dict(input.slack_thread_context)
+ SlackThreadHandler(context).append_status_chunks(
+ ts=input.ts,
+ task_updates=[
+ {"id": t.id, "title": t.title, "status": t.status, "details": t.details} for t in input.task_updates
+ ],
+ markdown_text=input.markdown_text,
+ )
+ except Exception as e:
+ logger.warning("slack_app_append_agent_design_steps_failed", error=str(e))
+
+
+@close_db_connections
+def stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> None:
+ """Mark the last step complete, stream the final answer, append @-mention, close."""
+ from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
+
+ try:
+ context = SlackThreadContext.from_dict(input.slack_thread_context)
+ SlackThreadHandler(context).stop_status_stream(
+ ts=input.ts,
+ complete_task_id=input.complete_task_id,
+ complete_task_title=input.complete_task_title,
+ complete_task_details=input.complete_task_details,
+ final_markdown=input.final_markdown,
+ )
+ except Exception as e:
+ logger.warning("slack_app_stop_agent_design_stream_failed", error=str(e))
diff --git a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py
new file mode 100644
index 000000000000..a29e54257d13
--- /dev/null
+++ b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py
@@ -0,0 +1,294 @@
+"""Per-turn child of ProcessTaskWorkflow.
+
+Two phases in a single chat.startStream lifecycle:
+
+Phase 1 (before the first tool call): text_deltas stream as markdown_text
+chunks — native Slack streaming animation. The stream is opened lazily on
+the first signal we can act on.
+
+Phase 2 (after the first tool call): text_deltas buffer between tool calls
+and surface as 💭 steps in the plan block, sandwiched between the tool
+call steps. This is the plan-block-driven mode.
+
+On turn_completed the last narrative burst (post-last-tool-call, or the
+only content in phase 1) streams as the final markdown_text and the
+stream closes with the trailing @-mention.
+"""
+
+from dataclasses import dataclass
+from datetime import timedelta
+from typing import Any, Optional
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+with workflow.unsafe.imports_passed_through():
+ from .activities.slack_agent_design import (
+ AppendSlackAgentDesignStepsInput,
+ StartSlackAgentDesignStreamInput,
+ StopSlackAgentDesignStreamInput,
+ TaskUpdateChunk,
+ append_slack_agent_design_steps,
+ start_slack_agent_design_stream,
+ stop_slack_agent_design_stream,
+ )
+
+
+STATUS_DEBOUNCE_SECONDS = 1.0
+STATUS_MIN_INTERVAL_SECONDS = 2.0
+TURN_IDLE_TIMEOUT_MINUTES = 5
+_STEP_FIELD_LIMIT = 256
+_NARRATIVE_STEP_TITLE = "💭"
+
+
+@dataclass
+class PendingStep:
+ title: str
+ details: Optional[str]
+
+
+@dataclass
+class SlackAgentDesignRelayInput:
+ slack_thread_context: dict[str, Any]
+
+
[email protected](name="slack-agent-design-relay")
+class SlackAgentDesignRelayWorkflow(PostHogWorkflow):
+ def __init__(self) -> None:
+ self._pending_steps: list[PendingStep] = []
+ # Narrative buffer. In phase 1 this is streamed and reset on each flush.
+ # In phase 2 it accumulates until the next tool call promotes it to a
+ # 💭 step, or until turn_completed streams it as the final answer.
+ self._current_narrative: str = ""
+ self._has_seen_tool_call: bool = False
+ self._stream_ts: Optional[str] = None
+ self._current_task_id: Optional[str] = None
+ self._current_task_title: Optional[str] = None
+ self._current_task_details: Optional[str] = None
+ self._last_dispatched_at: float = 0.0
+ self._turn_complete: bool = False
+
+ @workflow.signal
+ async def agent_status_update(self, payload: dict[str, Any] | str) -> None:
+ """New tool call → transition to phase 2 and queue steps."""
+ if isinstance(payload, str):
+ title = payload
+ details = None
+ if not title:
+ return
+ else:
+ raw_title = payload.get("title") or payload.get("text")
+ if not isinstance(raw_title, str) or not raw_title:
+ return
+ title = raw_title
+ details_raw = payload.get("details")
+ details = details_raw if isinstance(details_raw, str) and details_raw else None
+
+ # Any pending narrative becomes a 💭 step preceding the tool call step.
+ # In phase 1 → phase 2 transition, this converts the last (unstreamed)
+ # narrative burst into a step rather than losing it.
+ narrative = self._current_narrative.strip()
+ if narrative:
+ self._pending_steps.append(PendingStep(title=_NARRATIVE_STEP_TITLE, details=narrative[:_STEP_FIELD_LIMIT]))
+ self._current_narrative = ""
+
+ self._has_seen_tool_call = True
+ self._pending_steps.append(PendingStep(title=title, details=details))
+
+ @workflow.signal
+ async def agent_text_delta(self, text: str) -> None:
+ if isinstance(text, str) and text:
+ self._current_narrative += text
+
+ @workflow.signal
+ async def complete_turn(self) -> None:
+ self._turn_complete = True
+
+ def _build_transition_chunks(self, steps: list[PendingStep]) -> list[TaskUpdateChunk]:
+ """Previous step → complete, intermediates → complete, last → in_progress.
+ Mutates ``self._current_*`` to point at the new in-progress step."""
+ chunks: list[TaskUpdateChunk] = []
+ if not steps:
+ return chunks
+ if self._current_task_id and self._current_task_title:
+ chunks.append(
+ TaskUpdateChunk(
+ id=self._current_task_id,
+ title=self._current_task_title,
+ status="complete",
+ details=self._current_task_details,
+ )
+ )
+ for s in steps[:-1]:
+ chunks.append(
+ TaskUpdateChunk(
+ id=str(workflow.uuid4()),
+ title=s.title,
+ status="complete",
+ details=s.details,
+ )
+ )
+ last = steps[-1]
+ last_id = str(workflow.uuid4())
+ chunks.append(
+ TaskUpdateChunk(
+ id=last_id,
+ title=last.title,
+ status="in_progress",
+ details=last.details,
+ )
+ )
+ self._current_task_id = last_id
+ self._current_task_title = last.title
+ self._current_task_details = last.details
+ return chunks
+
+ def _has_pending(self) -> bool:
+ if not self._has_seen_tool_call:
+ return bool(self._current_narrative)
+ return bool(self._pending_steps)
+
+ @workflow.run
+ async def run(self, input: SlackAgentDesignRelayInput) -> None:
+ try:
+ while not self._turn_complete:
+ try:
+ await workflow.wait_condition(
+ lambda: self._has_pending() or self._turn_complete,
+ timeout=timedelta(minutes=TURN_IDLE_TIMEOUT_MINUTES),
+ )
+ except TimeoutError:
+ workflow.logger.warning(
+ "slack_app_agent_design_relay_idle_timeout",
+ extra={"workflow_id": workflow.info().workflow_id},
+ )
+ return
+
+ if self._turn_complete:
+ break # type: ignore[unreachable]
+
+ await workflow.sleep(STATUS_DEBOUNCE_SECONDS)
+
+ elapsed = workflow.now().timestamp() - self._last_dispatched_at
+ if elapsed < STATUS_MIN_INTERVAL_SECONDS:
+ await workflow.sleep(STATUS_MIN_INTERVAL_SECONDS - elapsed)
+
+ if not self._has_seen_tool_call:
+ # Phase 1: stream narrative as markdown_text.
+ to_stream = self._current_narrative
+ if not to_stream:
+ continue
+ self._current_narrative = ""
+ self._last_dispatched_at = workflow.now().timestamp()
+
+ if self._stream_ts is None:
+ self._stream_ts = await workflow.execute_activity(
+ start_slack_agent_design_stream,
+ StartSlackAgentDesignStreamInput(
+ slack_thread_context=input.slack_thread_context,
+ first_markdown_text=to_stream,
+ ),
+ start_to_close_timeout=timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ if self._stream_ts is None:
+ return
+ else:
+ await workflow.execute_activity(
+ append_slack_agent_design_steps,
+ AppendSlackAgentDesignStepsInput(
+ slack_thread_context=input.slack_thread_context,
+ ts=self._stream_ts,
+ markdown_text=to_stream,
+ ),
+ start_to_close_timeout=timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ continue
+
+ # Phase 2: flush queued steps into the plan block.
+ steps = self._pending_steps
+ self._pending_steps = []
+ if not steps:
+ continue
+
+ self._last_dispatched_at = workflow.now().timestamp()
+
+ if self._stream_ts is None:
+ first = steps[0]
+ first_id = str(workflow.uuid4())
+ self._stream_ts = await workflow.execute_activity(
+ start_slack_agent_design_stream,
+ StartSlackAgentDesignStreamInput(
+ slack_thread_context=input.slack_thread_context,
+ first_task_id=first_id,
+ first_task_title=first.title,
+ first_task_details=first.details,
+ ),
+ start_to_close_timeout=timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ if self._stream_ts is None:
+ return
+ self._current_task_id = first_id
+ self._current_task_title = first.title
+ self._current_task_details = first.details
+ remaining = steps[1:]
+ if remaining:
+ await workflow.execute_activity(
+ append_slack_agent_design_steps,
+ AppendSlackAgentDesignStepsInput(
+ slack_thread_context=input.slack_thread_context,
+ ts=self._stream_ts,
+ task_updates=self._build_transition_chunks(remaining),
+ ),
+ start_to_close_timeout=timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ continue
+
+ await workflow.execute_activity(
+ append_slack_agent_design_steps,
+ AppendSlackAgentDesignStepsInput(
+ slack_thread_context=input.slack_thread_context,
+ ts=self._stream_ts,
+ task_updates=self._build_transition_chunks(steps),
+ ),
+ start_to_close_timeout=timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ finally:
+ final_answer = self._current_narrative.strip()
+ # If turn_completed beat the first flush, open the stream now with
+ # the final answer as the seed. Keeps the streaming lifecycle
+ # consistent — no chat.postMessage fallback that would flicker
+ # against Slack's stream animation.
+ final_for_stop: Optional[str] = final_answer or None
+ if self._stream_ts is None and final_answer:
+ self._stream_ts = await workflow.execute_activity(
+ start_slack_agent_design_stream,
+ StartSlackAgentDesignStreamInput(
+ slack_thread_context=input.slack_thread_context,
+ first_markdown_text=final_answer,
+ ),
+ start_to_close_timeout=timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ # Already streamed as the opening chunk — don't re-emit in stop.
+ final_for_stop = None
+ if self._stream_ts is not None:
+ await workflow.execute_activity(
+ stop_slack_agent_design_stream,
+ StopSlackAgentDesignStreamInput(
+ slack_thread_context=input.slack_thread_context,
+ ts=self._stream_ts,
+ complete_task_id=self._current_task_id,
+ complete_task_title=self._current_task_title,
+ complete_task_details=self._current_task_details,
+ final_markdown=final_for_stop,
+ ),
+ start_to_close_timeout=timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 1a2f5a0ac732..216b4f4c2029 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -23,6 +23,10 @@ from .activities.cleanup_sandbox import CleanupSandboxInput, cleanup_sandbox
from .activities.create_resume_snapshot import CreateResumeSnapshotInput, create_resume_snapshot
from .activities.emit_progress_activity import EmitProgressInput, emit_progress_activity
from .activities.execute_task_in_sandbox import ExecuteTaskOutput
+from .activities.feature_flags import (
+ IsSlackAppAgentDesignEnabledForTaskActivityInput,
+ is_slack_app_agent_design_enabled_for_task_activity,
+)
from .activities.forward_pending_message import forward_pending_user_message
from .activities.get_sandbox_for_repository import GetSandboxForRepositoryOutput
from .activities.get_task_processing_context import (
@@ -59,6 +63,7 @@ from .activities.start_agent_server import (
from .activities.track_workflow_event import TrackWorkflowEventInput, track_workflow_event
from .activities.update_task_run_status import UpdateTaskRunStatusInput, update_task_run_status
from .credential_refresh import SANDBOX_GONE_ERROR_MESSAGE, CredentialRefreshExitReason, run_credential_refresh_loop
+from .slack_agent_design_relay import SlackAgentDesignRelayInput, SlackAgentDesignRelayWorkflow
@dataclass
@@ -143,6 +148,10 @@ _PATCH_ID_FOLLOWUP_QUEUE = "tasks-follow-up-message-queue"
# schedule it. Same two-step cleanup lifecycle as the patches above.
_PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING = "tasks-drop-slack-post-after-provisioning"
+# Gates the new agent-design flag-eval execute_activity site.
+# Two-step deprecate-then-delete cleanup lifecycle as above.
+_PATCH_ID_SLACK_AGENT_DESIGN_STATUS = "tasks-slack-agent-design-status"
+
def _deprecate_ci_follow_up_pr_context_patch() -> None:
workflow.deprecate_patch(_PATCH_ID_CI_FOLLOW_UP_PR_CONTEXT)
@@ -174,6 +183,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# Emit the "PR opened / keeping CI green" progress once, the first time we observe a PR — the
# agent opens it mid-run and then keeps it green, so without this the UI dead-ends at "Started agent".
self._pr_progress_emitted: bool = False
+ # Decided once at workflow start; gates the placeholder skip + relay spawn.
+ self._is_agent_design_enabled: bool = False
+ self._current_slack_relay_workflow_id: Optional[str] = None
@property
def context(self) -> TaskProcessingContext:
@@ -441,6 +453,16 @@ class ProcessTaskWorkflow(PostHogWorkflow):
try:
self._context = await self._get_task_processing_context(input)
self._posthog_mcp_scopes = input.posthog_mcp_scopes
+ # See _PATCH_ID_SLACK_AGENT_DESIGN_STATUS. Short-circuit on
+ # ``_slack_thread_context`` so non-Slack runs never call the
+ # workflow-scoped ``workflow.patched`` API (unit tests that
+ # invoke ``run`` outside a Temporal event loop would otherwise
+ # raise "Not in workflow event loop" here). Skipping the marker
+ # is safe: ``_resolve_agent_design_flag`` itself returns False
+ # for these runs, so recording the patch would have no
+ # observable effect on their behavior.
+ if self._slack_thread_context and workflow.patched(_PATCH_ID_SLACK_AGENT_DESIGN_STATUS):
+ self._is_agent_design_enabled = await self._resolve_agent_design_flag()
await self._update_task_run_status("in_progress")
# Announce the first progress step immediately so the desktop card
@@ -457,7 +479,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
},
)
- await self._post_slack_update()
+ # Agent-design path owns this surface via per-turn relay children.
+ if not self._is_agent_design_enabled:
+ await self._post_slack_update()
sandbox_output = await self._get_sandbox_for_repository()
sandbox_id = sandbox_output.sandbox_id
@@ -470,7 +494,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# pre-rollout histories still post here; new executions skip the
# redundant update to keep determinism for in-flight workflows.
if not workflow.patched(_PATCH_ID_DROP_SLACK_POST_AFTER_PROVISIONING):
- await self._post_slack_update()
+ if not self._is_agent_design_enabled:
+ await self._post_slack_update()
# Run the PostHog setup wizard before the agent, when this is a cloud wizard run.
# The wizard integrates PostHog and dirties the working tree; the agent then commits
@@ -1040,6 +1065,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
team_id=self.context.team_id,
distinct_id=self.context.distinct_id,
sandbox_id=sandbox_id,
+ slack_thread_context=self._slack_thread_context,
+ is_agent_design_enabled=self._is_agent_design_enabled,
)
await workflow.execute_activity(
relay_sandbox_events,
@@ -1127,12 +1154,102 @@ class ProcessTaskWorkflow(PostHogWorkflow):
retry_policy=RetryPolicy(maximum_attempts=2),
)
+ async def _resolve_agent_design_flag(self) -> bool:
+ if not self._slack_thread_context:
+ return False
+ integration_id = self._slack_thread_context.get("integration_id")
+ if not integration_id:
+ return False
+ try:
+ return await workflow.execute_activity(
+ is_slack_app_agent_design_enabled_for_task_activity,
+ IsSlackAppAgentDesignEnabledForTaskActivityInput(
+ integration_id=int(integration_id),
+ run_id=self.context.run_id,
+ ),
+ start_to_close_timeout=timedelta(seconds=10),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ except Exception:
+ # Fail closed.
+ workflow.logger.warning("slack_app_agent_design_flag_eval_failed", extra={"run_id": self.context.run_id})
+ return False
+
@temporalio.workflow.signal
async def complete_task(self, status: str = "completed", error_message: Optional[str] = None) -> None:
self._completion_status = status
self._completion_error = error_message
self._task_completed = True
+ # ─── Slack agent-design streaming ─── (per-turn signals from relay_sandbox_events)
+
+ @temporalio.workflow.signal
+ async def turn_started(self, payload: dict[str, Any]) -> None:
+ if not self._is_agent_design_enabled:
+ return
+ # Any orphaned previous-turn child times out on its own.
+ slack_ctx = payload.get("slack_thread_context") or self._slack_thread_context or {}
+ if not slack_ctx:
+ return
+ relay_workflow_id = f"slack-agent-design-relay-{self.context.run_id}-{workflow.uuid4()}"
+ self._current_slack_relay_workflow_id = relay_workflow_id
+ asyncio.ensure_future(
+ workflow.execute_child_workflow(
+ SlackAgentDesignRelayWorkflow.run,
+ SlackAgentDesignRelayInput(slack_thread_context=slack_ctx),
+ id=relay_workflow_id,
+ task_queue=workflow.info().task_queue,
+ # Cancel on parent close so the relay's finally block runs
+ # stop_slack_agent_design_stream — otherwise the plan-block
+ # stream is orphaned until Slack's own GC.
+ parent_close_policy=ParentClosePolicy.REQUEST_CANCEL,
+ execution_timeout=timedelta(hours=1),
+ )
+ )
+
+ @temporalio.workflow.signal
+ async def agent_status_update(self, payload: dict[str, Any]) -> None:
+ """Forward {title, details} step update to the current per-turn child."""
+ if not self._is_agent_design_enabled or not self._current_slack_relay_workflow_id:
+ return
+ try:
+ handle = workflow.get_external_workflow_handle(self._current_slack_relay_workflow_id)
+ await handle.signal(SlackAgentDesignRelayWorkflow.agent_status_update, payload)
+ except Exception as e:
+ # Child already gone — drop the update.
+ workflow.logger.debug(
+ "slack_status_forward_failed",
+ extra={"run_id": self.context.run_id, "error": str(e)},
+ )
+
+ @temporalio.workflow.signal
+ async def agent_text_delta(self, text: str) -> None:
+ if not self._is_agent_design_enabled or not self._current_slack_relay_workflow_id:
+ return
+ try:
+ handle = workflow.get_external_workflow_handle(self._current_slack_relay_workflow_id)
+ await handle.signal(SlackAgentDesignRelayWorkflow.agent_text_delta, text)
+ except Exception as e:
+ workflow.logger.debug(
+ "slack_text_forward_failed",
+ extra={"run_id": self.context.run_id, "error": str(e)},
+ )
+
+ @temporalio.workflow.signal
+ async def turn_completed(self) -> None:
+ if not self._is_agent_design_enabled or not self._current_slack_relay_workflow_id:
+ return
+ relay_id = self._current_slack_relay_workflow_id
+ self._current_slack_relay_workflow_id = None
+ try:
+ handle = workflow.get_external_workflow_handle(relay_id)
+ await handle.signal(SlackAgentDesignRelayWorkflow.complete_turn)
+ except Exception as e:
+ workflow.logger.debug(
+ "slack_status_complete_failed",
+ extra={"run_id": self.context.run_id, "error": str(e)},
+ )
+
@temporalio.workflow.signal
async def heartbeat(self, agent_active: bool = False) -> None:
if not agent_active: