: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(slack-app): stream a live progress plan in agent slack replies (#108250)
Vojta Bartošeb3c38b95228
diff --git a/packages/agent/packages/agent/src/server/agent-server.test.ts b/packages/agent/packages/agent/src/server/agent-server.test.tsindex c6901cb80920..d32971d1c5c8 100644--- a/packages/agent/packages/agent/src/server/agent-server.test.ts+++ b/packages/agent/packages/agent/src/server/agent-server.test.ts@@ -252,6 +252,7 @@ interface TestableServer {detectedPrUrl: string | null;slackArtifactDelivery: "none" | "message" | "canvas_file" | null;slackChartDelivery: boolean;+ slackProgressChecklist: boolean;slackReplyContext: boolean;buildCloudSystemPrompt(prUrl?: string | null,@@ -7611,6 +7612,25 @@ describe("AgentServer HTTP Mode", () => {},);+ it.each([+ { checklist: true, expected: true },+ { checklist: false, expected: false },+ ])(+ "asks for a plain-language task list only when the Slack reply streams it (checklist: $checklist)",+ ({ checklist, expected }) => {+ // The checklist is the Slack progress UI. Without it the task list is invisible,+ // and asking for one only costs the agent turns.+ process.env.POSTHOG_CODE_INTERACTION_ORIGIN = "slack";+ const s = createServer() as unknown as TestableServer;+ s.slackProgressChecklist = checklist;++ const prompt = s.buildCloudSystemPrompt();++ expect(prompt.includes("# Progress checklist")).toBe(expected);+ delete process.env.POSTHOG_CODE_INTERACTION_ORIGIN;+ },+ );+it.each([{ label: "no origin set", origin: undefined },{ label: "signal_report origin", origin: "signal_report" },diff --git a/packages/agent/packages/agent/src/server/agent-server.ts b/packages/agent/packages/agent/src/server/agent-server.tsindex b28d1d13fffd..d252bd853e5a 100644--- a/packages/agent/packages/agent/src/server/agent-server.ts+++ b/packages/agent/packages/agent/src/server/agent-server.ts@@ -550,6 +550,7 @@ export class AgentServer {private stampedRunTraceId: string | null = null;private slackArtifactDelivery: SlackArtifactDelivery | null = null;private slackChartDelivery = false;+ private slackProgressChecklist = false;private slackReplyContext = false;private mobileClient = false;private taskRepositories: string[] = [];@@ -2181,6 +2182,9 @@ export class AgentServer {this.slackChartDelivery = readSlackChartDelivery(preTaskRun);this.slackReplyContext = preTaskRun?.state.slack_reply_context === true;this.mobileClient = preTaskRun?.state.client_platform === "mobile";+ // Set by the backend on runs whose Slack reply streams the agent's task list.+ this.slackProgressChecklist =+ preTaskRun?.state.slack_app_agent_design_enabled === true;// 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@@ -4634,6 +4638,7 @@ export class AgentServer {shouldAutoPublish: this.shouldAutoPublishCloudChanges(),slackArtifactDelivery: this.slackArtifactDelivery,slackChartDelivery: this.slackChartDelivery,+ slackProgressChecklist: this.slackProgressChecklist,storeSkillsInstalledCount: this.storeSkillsInstalledCount,taskId: this.config.taskId,taskRepositories: this.taskRepositories,diff --git a/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.ts b/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.tsindex 04978eb95cc7..191d633dcfeb 100644--- a/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.ts+++ b/packages/agent/packages/harness/src/extensions/task-system-prompt/cloud.ts@@ -25,6 +25,8 @@ export interface CloudTaskPromptOptions {shouldAutoPublish: boolean;slackArtifactDelivery: SlackArtifactDelivery | null;slackChartDelivery: boolean;+ // The Slack thread draws the agent's task list as a live checklist.+ slackProgressChecklist: boolean;storeSkillsInstalledCount: number;taskId: string;taskRepositories: string[];@@ -111,7 +113,8 @@ ${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/\`.${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.+- 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 files and canvas cards to your final answer automatically after you finish, so mention the artifact by name only if useful.+- A pending delivery status only means the artifact waits for your final answer. Do not check it again, and do not tell the user that a link or file has not arrived.- If you created a local file but no upload or delivery tool is available, say that plainly and summarize the result in Slack instead.`;}@@ -187,7 +190,17 @@ To ping a Slack user, reuse a \`<@U…|displayname>\` token that already appearsYou can also open pull requests directly from this Slack thread. When the user's question describes a problem with a plausible code-side fix — a bug visible in errors or logs, missing or broken instrumentation, a broken funnel step traceable to UI code, a stale config that lives in a repo — end your reply with a one-sentence offer to open a PR for the fix and ask if they want you to proceed. Skip the offer for pure data lookups with no actionable code change (e.g. "what was DAU yesterday?"), and skip it when the fix would clearly live outside any repo you can reach.`: "";- const identityInstructions = `${slackIdentityInstructions}${githubIdentityInstructions}`;+ const slackProgressInstructions =+ isSlack && this.options.slackProgressChecklist+ ? `+# Progress checklist+The Slack thread shows your task list as a live checklist, and it is the only progress the user sees while you work. Before your first tool call, create the task list with your task tools (TaskCreate and TaskUpdate, or update_plan): 2 to 5 tasks, each one outcome the user cares about. Mark a task in progress when you start it and completed when you finish it. Add a task when the work grows.+- Write each task in plain words for someone who does not read code, for example "Find the signup event" or "Count weekly signups".+- Do not put tool names, file paths, SQL, or IDs in a task.+- Skip the list only when you answer without any tool call.+`+ : "";+ const identityInstructions = `${slackIdentityInstructions}${slackProgressInstructions}${githubIdentityInstructions}`;const signedCommitInstructions = `## Committing (signed commits required)Commits MUST be signed. \`git commit\` and \`git push\` are blocked in this environment.diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 5a1be045efe0..4434498a3788 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -1450,7 +1450,6 @@2 products/tasks/backend/temporal/process_task/activities/get_sandbox_for_repository.py2 products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py2 products/tasks/backend/temporal/process_task/sandbox_credentials.py-2 products/tasks/backend/temporal/process_task/slack_agent_design_relay.py2 products/warehouse_sources/backend/temporal/data_imports/external_data_job.py2 products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_sync.py2 products/warehouse_sources/backend/temporal/data_imports/sources/adobe_commerce/adobe_commerce.py@@ -1547,7 +1546,6 @@4 products/marketing_analytics/backend/services/campaign_mapping_suggester.py4 products/marketing_analytics/backend/services/conversion_goals_inspector.py4 products/signals/backend/temporal/buffer.py-4 products/tasks/backend/temporal/process_task/activities/slack_agent_design.py4 products/tasks/backend/temporal/process_task/activities/start_agent_server.py4 products/tasks/backend/temporal/process_task/workflow.py4 products/tasks/backend/temporal/task_management/activities/pending_followups.pydiff --git a/products/slack_app/backend/facade/api.py b/products/slack_app/backend/facade/api.pyindex b0ba44eea78f..36ba376170d0 100644--- a/products/slack_app/backend/facade/api.py+++ b/products/slack_app/backend/facade/api.py@@ -4,11 +4,12 @@ The ONLY module other products are allowed to import. Keep the surface narrow:every function here lives behind a tach contract check, so each addition has acost in cross-product coupling.-Today the facade exists for three jobs: letting core's OAuth callback invalidate+Today the facade exists for four jobs: letting core's OAuth callback invalidatethe per-integration auth-state cache when a Slack install is reconnected,-answering whether a channel has been approved for PostHog to speak in, and-telling a product that posts a report whether the bot can answer a follow-up.-All are stable re-exports so the implementations can move around inside+answering whether a channel has been approved for PostHog to speak in,+telling a product that posts a report whether the bot can answer a follow-up,+and turning an agent's tool calls into the progress lines of a streamed Slack+reply. All are stable re-exports so the implementations can move around insideslack_app without breaking their callers.This module's import graph must not reach ``products.signals``. That product now imports this@@ -23,6 +24,23 @@ from typing import Anyfrom posthog.models.integration import Integration+from products.slack_app.backend.logic.progress_phases import (+ ANSWER_LINE_TITLE,+ OTHER_WORK,+ PLAN_TITLE_STOPPED,+ PLAN_TITLE_WORKING,+ PREPARING_LINE_TITLE,+ SLACK_STEP_STATUSES,+ THINKING_LINE_TITLE,+ ProgressPhase,+ agent_plan_steps,+ done_plan_title,+ intent_from_narrative,+ phase_for_key,+ phase_for_tool_call,+ phase_line_title,+ tool_call_from_acp_update,+)from products.slack_app.backend.models import SlackChannelfrom products.slack_app.backend.services.followup_invite import build_followup_invite, build_followup_invite_textfrom products.slack_app.backend.services.slack_auth import invalidate_auth_state@@ -30,6 +48,21 @@ from products.slack_app.backend.services.slack_scopes import has_scopesfrom products.slack_app.backend.services.slack_user_info import invalidate_workspace_bot_user_id__all__ = [+ "ANSWER_LINE_TITLE",+ "OTHER_WORK",+ "PLAN_TITLE_STOPPED",+ "PLAN_TITLE_WORKING",+ "PREPARING_LINE_TITLE",+ "SLACK_STEP_STATUSES",+ "THINKING_LINE_TITLE",+ "ProgressPhase",+ "agent_plan_steps",+ "done_plan_title",+ "intent_from_narrative",+ "phase_for_key",+ "phase_for_tool_call",+ "phase_line_title",+ "tool_call_from_acp_update","invalidate_slack_integration_auth_state","slack_artifact_delivery_state_updates","slack_channel_is_approved",diff --git a/products/slack_app/backend/logic/__init__.py b/products/slack_app/backend/logic/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/slack_app/backend/logic/progress_phases.py b/products/slack_app/backend/logic/progress_phases.pynew file mode 100644index 000000000000..ff6cbe558d3a--- /dev/null+++ b/products/slack_app/backend/logic/progress_phases.py@@ -0,0 +1,318 @@+"""Plain-language progress phases for the Slack agent-design plan block.++A tool call maps to one line per kind of work, never to a tool name or its arguments. A PostHog+tool gets the title the MCP tool catalogue gives it, because some catalogue categories ("Core",+"Query wrappers") are internal names.+"""++import re+from datetime import timedelta+from typing import Any++from posthog.dataclasses import frozen+from posthog.mcp_tool_definitions import get_mcp_tool_definitions+from posthog.slack.channels import clip_text+++@frozen+class ProgressPhase:+ key: str+ title: str+ # The noun that counts calls in the line title, such as "queries". None shows no count.+ counter: str | None+++# Keys of PostHog lines start with this. The rest of the key is the catalogue title of the tool.+POSTHOG_PHASE_PREFIX = "posthog:"+GETTING_CODE = ProgressPhase(key="getting_code", title="Getting the code", counter=None)+READING_CODE = ProgressPhase(key="reading_code", title="Reading the code", counter="lookups")+SEARCHING_WEB = ProgressPhase(key="searching_web", title="Searching the web", counter="lookups")+MAKING_CHANGES = ProgressPhase(key="making_changes", title="Making changes", counter="edits")+RUNNING_CHECKS = ProgressPhase(key="running_checks", title="Running checks", counter="checks")+RUNNING_COMMANDS = ProgressPhase(key="running_commands", title="Running commands", counter="commands")+PREPARING_FILES = ProgressPhase(key="preparing_files", title="Preparing attachments", counter="files")+OPENING_PR = ProgressPhase(key="opening_pr", title="Opening a pull request", counter=None)+# The relay folds phases past its line limit into this line, so the plan stays short.+OTHER_WORK = ProgressPhase(key="other_work", title="Other work", counter="steps")++PHASES: dict[str, ProgressPhase] = {+ phase.key: phase+ for phase in (+ GETTING_CODE,+ READING_CODE,+ SEARCHING_WEB,+ MAKING_CHANGES,+ RUNNING_CHECKS,+ RUNNING_COMMANDS,+ PREPARING_FILES,+ OPENING_PR,+ OTHER_WORK,+ )+}++# Statuses of agent todo items and of the parent's progress steps, as the statuses Slack draws.+SLACK_STEP_STATUSES = {"pending": "pending", "in_progress": "in_progress", "completed": "complete", "failed": "error"}+PLAN_TITLE_WORKING = "Working on it"+# Placeholder lines that keep a spinner in the plan while no step is open.+PREPARING_LINE_TITLE = "Getting ready"+THINKING_LINE_TITLE = "Thinking"+# The placeholder becomes this when the turn answers without a tool.+ANSWER_LINE_TITLE = "Writing the answer"+PLAN_TITLE_STOPPED = "Stopped"++# Tools that manage the agent's own session. They say nothing about the work, so no line shows them.+_IGNORED_TOOL_MARKERS = (+ "task_summary_update",+ "show_actions",+ "toolsearch",+ "skill",+ "todowrite",+ "taskcreate",+ "taskupdate",+ "taskget",+ "tasklist",+ "taskstop",+ "exitplanmode",+ "enterplanmode",+ "monitor",+ "schedulewakeup",+ "list_mcp_resource",+ "write_stdin",+ "list_agents",+ "sendmessage",+)+_IGNORED_TOOL_NAMES = frozenset({"agent", "task", "wait", "sleep", "spawn_agent", "close_agent", "wait_agent"})+_PR_TOOL_MARKERS = ("git_signed_commit", "git_signed_rewrite", "git_signed_merge", "gh_stack")+_REPO_TOOL_MARKERS = ("clone_repo", "list_repos")+_POSTHOG_MCP_PREFIXES = ("mcp__posthog__", "posthog/")+_EDIT_TOOL_NAMES = frozenset({"edit", "write", "multiedit", "notebookedit", "apply_patch"})+_READ_TOOL_NAMES = frozenset({"read", "grep", "glob", "ls", "notebookread", "view_image"})+_WEB_TOOL_NAMES = frozenset({"websearch", "webfetch", "web_search", "web_fetch"})+_SHELL_TOOL_NAMES = frozenset({"bash", "exec_command", "exec", "shell", "terminal"})++# The PostHog MCP server runs its tools through one `exec` tool.+_POSTHOG_EXEC_TOOL = "exec"+_PR_COMMAND = re.compile(r"\b(gh\s+pr\s+(create|edit|ready)|git\s+(commit|push))\b")+_CHECK_COMMAND = re.compile(+ r"\b(pytest|jest|vitest|playwright|hogli\s+(test|lint|ci)|ruff|mypy|tsc|eslint|oxlint|prettier|"+ r"(pnpm|npm|yarn)\s+(run\s+)?(test|lint|typecheck|typescript:check|build)|"+ r"cargo\s+(test|check|clippy|build)|go\s+(test|vet|build)|make\s+(test|lint|check))\b"+)+_READ_COMMAND = re.compile(+ r"^\s*(cd\s+\S+\s*(&&|;)\s*)?(grep|rg|cat|ls|find|head|tail|wc|tree|jq|less|sed\s+-n|awk|"+ r"git\s+(log|show|diff|status|blame|grep|ls-files))\b"+)+# Output redirection to a file, such as `cat > out.csv`. A `2>` or `>&` redirect only moves a stream.+_WRITE_REDIRECT = re.compile(r"(?<![0-9&>])>>?(?![&>])")+_ACTIVITY_LIMIT = 80+_MAX_AGENT_PLAN_STEPS = 10+_MIN_INTENT_LENGTH = 8++_SENTENCE_END = re.compile(r"(?<=[.!?])\s+|\n+")+_OBJECT_TAG = re.compile(r"<[^>]*>")+_MARKDOWN_MARKS = re.compile(r"[*_`#>]+")+_INTENT_PREFIX = re.compile(+ r"^(?:(?:now|next|then|first|ok|okay|great|good)[,:]?\s+)*"+ r"(?:let me|let's|i'll|i will|i'm going to|i am going to|i need to|i should)\s+",+ re.IGNORECASE,+)+++@frozen+class ToolCall:+ """What the classifier needs from one ACP tool call."""++ name: str+ kind: str | None+ command: str | None+ # The plain-language description the agent gave a shell command.+ description: str | None = None+ # The PostHog tool the call runs, or None for a call that is not a PostHog tool call.+ posthog_tool: str | None = None+++def _dict_or_empty(value: Any) -> dict[str, Any]:+ return value if isinstance(value, dict) else {}+++def _short_activity(description: Any) -> str | None:+ if not isinstance(description, str):+ return None+ text = " ".join(description.split()).rstrip(".")+ return clip_text(text, _ACTIVITY_LIMIT) if text else None+++def posthog_phase(tool_title: str) -> ProgressPhase:+ """The line for a PostHog tool, titled as the MCP tool catalogue names it."""+ title = clip_text(" ".join(tool_title.split()), _ACTIVITY_LIMIT)+ return ProgressPhase(key=f"{POSTHOG_PHASE_PREFIX}{title}", title=title, counter="calls")+++def _phase_for_command(command: str) -> ProgressPhase:+ if _PR_COMMAND.search(command):+ return OPENING_PR+ if _CHECK_COMMAND.search(command):+ return RUNNING_CHECKS+ if _READ_COMMAND.match(command) and not _WRITE_REDIRECT.search(command):+ return READING_CODE+ return RUNNING_COMMANDS+++def _phase_for_posthog_tool(tool_name: str) -> ProgressPhase:+ definition = get_mcp_tool_definitions().get(tool_name)+ if definition is None:+ # A tool the catalogue does not know, such as a third-party tool behind the gateway.+ return OTHER_WORK+ return posthog_phase(definition.title)+++def phase_for_key(key: str) -> ProgressPhase | None:+ """The phase a signal names, or None for a key this module does not know."""+ if key.startswith(POSTHOG_PHASE_PREFIX) and len(key) > len(POSTHOG_PHASE_PREFIX):+ return posthog_phase(key.removeprefix(POSTHOG_PHASE_PREFIX))+ return PHASES.get(key)+++def phase_for_tool_call(call: ToolCall) -> ProgressPhase | None:+ """The phase a tool call belongs to, or None when the plan should not show it."""+ name = call.name.strip().lower()+ if not name or call.kind == "think":+ return None+ if name in _IGNORED_TOOL_NAMES or any(marker in name for marker in _IGNORED_TOOL_MARKERS):+ return None+ if any(marker in name for marker in _PR_TOOL_MARKERS):+ return OPENING_PR+ if any(marker in name for marker in _REPO_TOOL_MARKERS):+ return GETTING_CODE+ if "artifact" in name:+ return PREPARING_FILES+ if any(name.startswith(prefix) for prefix in _POSTHOG_MCP_PREFIXES):+ # A PostHog call that only looks up what the server offers is not work on the user's data.+ return _phase_for_posthog_tool(call.posthog_tool) if call.posthog_tool else None+ if name in _WEB_TOOL_NAMES or call.kind == "fetch":+ return SEARCHING_WEB+ if name in _EDIT_TOOL_NAMES or call.kind == "edit":+ return MAKING_CHANGES+ if name in _READ_TOOL_NAMES or call.kind in ("read", "search"):+ return READING_CODE+ if name in _SHELL_TOOL_NAMES or call.kind == "execute":+ return _phase_for_command(call.command or "")+ # Other MCP servers and unknown tools stay out of the plan rather than leak their names.+ return None+++def phase_line_title(phase: ProgressPhase, count: int) -> str:+ """The plan line for a phase, such as "Execute SQL query (3 calls)". A single call shows no count.++ The count goes in the title because Slack replaces a step's title on each update, but+ appends its details.+ """+ if phase.counter is None or count <= 1:+ return phase.title+ return f"{phase.title} ({count} {phase.counter})"+++def done_plan_title(elapsed: timedelta) -> str:+ """The plan title of a finished turn, such as "Done in 1m 12s"."""+ seconds = max(int(elapsed.total_seconds()), 1)+ hours, rest = divmod(seconds, 3600)+ minutes, seconds = divmod(rest, 60)+ if hours:+ duration = f"{hours}h {minutes}m" if minutes else f"{hours}h"+ elif minutes:+ duration = f"{minutes}m {seconds}s" if seconds else f"{minutes}m"+ else:+ duration = f"{seconds}s"+ return f"Done in {duration}"+++def intent_from_narrative(text: str) -> str | None:+ """The last sentence the agent wrote before a tool call, as a short activity.++ "Now let me count daily active users for last week." becomes "Count daily active users+ for last week". A question is left out, because it asks the reader and reports nothing.+ """+ plain = _MARKDOWN_MARKS.sub("", _OBJECT_TAG.sub("", text))+ sentences = [sentence.strip() for sentence in _SENTENCE_END.split(plain) if sentence.strip()]+ if not sentences or sentences[-1].endswith("?"):+ return None+ sentence = _INTENT_PREFIX.sub("", sentences[-1]).rstrip(".:!… ")+ if len(sentence) < _MIN_INTENT_LENGTH:+ return None+ return _short_activity(sentence[0].upper() + sentence[1:])+++def _posthog_tool(name: str, command: str | None) -> str | None:+ """The PostHog tool a call runs, or None when it only looks up what the server offers."""+ for prefix in _POSTHOG_MCP_PREFIXES:+ if not name.startswith(prefix):+ continue+ tool = name.removeprefix(prefix)+ if tool != _POSTHOG_EXEC_TOOL:+ return tool+ return _exec_call_tool(command)+ return None+++def _exec_call_tool(command: str | None) -> str | None:+ """The tool an ``exec`` command such as ``call --json execute-sql {...}`` runs. Other verbs only look up tools."""+ words = (command or "").split()+ if not words or words[0].lower() != "call":+ return None+ tool = next((word for word in words[1:] if not word.startswith("--")), None)+ return tool.lower() if tool else None+++def agent_plan_steps(update: dict[str, Any]) -> list[dict[str, str]] | None:+ """The agent's todo list from an ACP ``plan`` update, as ``{"title", "status"}`` steps.++ Claude sends the list its task tools keep and Codex sends its ``update_plan`` steps. The+ statuses become the ones Slack draws. Returns None for any other update.+ """+ if update.get("sessionUpdate") != "plan":+ return None+ entries = update.get("entries")+ steps: list[dict[str, str]] = []+ for entry in entries if isinstance(entries, list) else []:+ entry = _dict_or_empty(entry)+ title = _short_activity(entry.get("content"))+ if title:+ steps.append({"title": title, "status": SLACK_STEP_STATUSES.get(str(entry.get("status")), "pending")})+ return steps[:_MAX_AGENT_PLAN_STEPS]+++def tool_call_from_acp_update(update: dict[str, Any]) -> ToolCall | None:+ """Read the tool name, kind, command and description from an ACP ``tool_call``/``tool_call_update``.++ Returns None while a Claude shell or PostHog ``exec`` call has no command yet: Claude streams+ the call with an empty ``rawInput`` first, and the command decides the phase.+ """+ meta = _dict_or_empty(update.get("_meta"))+ claude_tool_name = _dict_or_empty(meta.get("claudeCode")).get("toolName")+ posthog_tool_name = _dict_or_empty(meta.get("posthog")).get("toolName")+ title = update.get("title") if isinstance(update.get("title"), str) else None+ kind = update.get("kind") if isinstance(update.get("kind"), str) else None+ name = claude_tool_name or posthog_tool_name+ if not name and kind in ("execute", "read", "search"):+ # Codex sends shell commands with no tool name and the command as the title.+ return ToolCall(name="exec_command", kind=kind, command=title)+ name = name or title+ if not isinstance(name, str) or not name:+ return None++ raw_input = _dict_or_empty(update.get("rawInput"))+ command = raw_input.get("command")+ if isinstance(command, list):+ command = " ".join(str(part) for part in command)+ if not isinstance(command, str) or not command:+ command = None+ lowered = name.lower()+ needs_command = lowered in _SHELL_TOOL_NAMES or kind == "execute" or lowered.endswith(f"__{_POSTHOG_EXEC_TOOL}")+ if command is None and needs_command:+ return None+ # Only Claude's shell tool takes a description written for people. A description argument on+ # other tools is content, such as the text of a new dashboard.+ description = _short_activity(raw_input.get("description")) if lowered == "bash" else None+ return ToolCall(+ name=name, kind=kind, command=command, description=description, posthog_tool=_posthog_tool(lowered, command)+ )diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.pyindex 25935c903df4..0237f6386333 100644--- a/products/slack_app/backend/slack_thread.py+++ b/products/slack_app/backend/slack_thread.py@@ -1,4 +1,5 @@import re+from collections.abc import Callablefrom dataclasses import dataclass, replacefrom typing import TYPE_CHECKING, Anyfrom uuid import UUID@@ -103,6 +104,26 @@ def _task_update_chunk(return chunk+def _plan_update_chunk(title: str) -> dict[str, Any]:+ return {"type": "plan_update", "title": title[:_TASK_FIELD_LIMIT]}+++def _status_chunks(task_updates: list[dict[str, Any]] | None, markdown_text: str | None) -> list[dict[str, Any]]:+ """task_update chunks for the well-formed steps, then markdown_text chunks for the prose."""+ 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 _markdown_text_pieces(markdown_text):+ chunks.append({"type": "markdown_text", "text": piece})+ return chunks++def _format_task_error(error: str) -> str:error = error.strip()if not error:@@ -377,24 +398,22 @@ class SlackThreadHandler:def start_status_stream(self,- first_task_id: str | None = None,- first_task_title: str | None = None,- first_task_details: str | None = None,+ task_updates: list[dict[str, Any]] | None = None,first_markdown_text: str | None = None,+ plan_title: 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)."""+ """chat.startStream in plan-block mode. Seed with plan-block steps, a+ markdown_text chunk, or both. The plan block stays where its first step+ lands, and later task_update chunks change that block in place."""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 _markdown_text_pieces(first_markdown_text):- chunks.append({"type": "markdown_text", "text": piece})+ first_markdown_text = self._with_leading_mention(first_markdown_text)+ chunks = _status_chunks(task_updates, first_markdown_text)if not chunks:return None+ if plan_title:+ chunks.insert(0, _plan_update_chunk(plan_title))try:client = self._get_client()if not slack_message_exists(client, self.context.channel, self.context.thread_ts):@@ -420,69 +439,63 @@ class SlackThreadHandler:ts: str,task_updates: list[dict[str, Any]] | None = None,markdown_text: str | None = None,+ plan_title: 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 _markdown_text_pieces(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))+ chunks = _status_chunks(task_updates, markdown_text)+ if plan_title:+ chunks.insert(0, _plan_update_chunk(plan_title))+ self._append_chunks(ts, chunks, "slack_app_status_stream_append_failed")++ def append_status_blocks(self, ts: str, blocks: list[dict[str, Any]]) -> bool:+ """Append Block Kit blocks, such as chart cards, to an open stream. Returns whether Slack took them."""+ if not blocks:+ return True+ return self._append_chunks(+ ts, [{"type": "blocks", "blocks": blocks}], "slack_app_status_stream_blocks_append_failed"+ )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,+ plan_title: str | None = None,+ append_attachments: Callable[[], None] | None = None,+ mention_sent: bool = False,) -> 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.-- The provenance footer closes the message. It arrives as a `blocks` chunk- because a `context` block is the only way to get muted text, and it goes- after the mention so the ping stays adjacent to the prose it answers."""- final_chunks: list[dict[str, Any]] = []+ """Final flush: mark the last plan-block step complete, stream the answer, then chat.stopStream.++ The answer starts with the @-mention, so the one notification lands with it. With no+ answer to stream here, the mention closes the message instead, unless ``mention_sent``+ says the answer already carried it. ``append_attachments`` runs after the answer, so+ chart cards sit under the text that describes them. The provenance footer is a `blocks`+ chunk because a `context` block is the only way to get muted text."""+ answer_chunks: list[dict[str, Any]] = []+ if plan_title:+ answer_chunks.append(_plan_update_chunk(plan_title))if complete_task_id and complete_task_title:- final_chunks.append(- _task_update_chunk(complete_task_id, complete_task_title, "complete", complete_task_details)- )+ answer_chunks.append(_task_update_chunk(complete_task_id, complete_task_title, "complete", None))if final_markdown:- for piece in _markdown_text_pieces(final_markdown):- final_chunks.append({"type": "markdown_text", "text": piece})+ for piece in _markdown_text_pieces(self._with_leading_mention(final_markdown)):+ answer_chunks.append({"type": "markdown_text", "text": piece})+ self._append_chunks(ts, answer_chunks, "slack_app_status_stream_final_append_failed")+ if append_attachments is not None:+ try:+ append_attachments()+ except Exception as e:+ logger.warning("slack_app_status_stream_attachments_failed", error=str(e))++ final_chunks: list[dict[str, Any]] = []recipient = self.context.mentioning_slack_user_id- if recipient and not (final_markdown and mentions_slack_user(final_markdown, recipient)):+ if recipient and not final_markdown and not mention_sent:# Newlines keep the mention off the tail of the last streamed prose chunk.final_chunks.append({"type": "markdown_text", "text": f"\n\n<@{recipient}>"})footer = self._footer_block()if footer:final_chunks.append({"type": "blocks", "blocks": [footer]})- 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))+ self._append_chunks(ts, final_chunks, "slack_app_status_stream_final_append_failed")if footer:self._append_trailing_blocks(ts)try:@@ -493,6 +506,33 @@ class SlackThreadHandler:except Exception as e:logger.warning("slack_app_status_stream_stop_failed", error=str(e))+ def _with_leading_mention(self, markdown: str) -> str:+ recipient = self.context.mentioning_slack_user_id+ if not recipient or mentions_slack_user(markdown, recipient):+ return markdown+ return f"<@{recipient}> {markdown}"++ def attach_files(self, ts: str, file_ids: list[str]) -> bool:+ """Attach uploaded files to a message whose stream has closed, keeping its blocks and text.++ A streaming message cannot hold a file, and chat.update is the only way to add one later."""+ try:+ self._get_client().chat_update(channel=self.context.channel, ts=ts, file_ids=file_ids)+ except Exception as e:+ logger.warning("slack_app_status_stream_attach_files_failed", error=str(e))+ return False+ return True++ def _append_chunks(self, ts: str, chunks: list[dict[str, Any]], failure_event: str) -> bool:+ if not chunks:+ return True+ try:+ self._get_client().chat_appendStream(channel=self.context.channel, ts=ts, chunks=chunks)+ except Exception as e:+ logger.warning(failure_event, error=str(e))+ return False+ return True+def post_or_update_progress(self, stage: str, task_url: str | None = None) -> None:"""Post a new progress message or update the existing one.diff --git a/products/slack_app/backend/tests/test_progress_phases.py b/products/slack_app/backend/tests/test_progress_phases.pynew file mode 100644index 000000000000..50f8241a7bf8--- /dev/null+++ b/products/slack_app/backend/tests/test_progress_phases.py@@ -0,0 +1,180 @@+from datetime import timedelta+from typing import Any++from parameterized import parameterized++from products.slack_app.backend.logic.progress_phases import (+ agent_plan_steps,+ done_plan_title,+ intent_from_narrative,+ phase_for_tool_call,+ tool_call_from_acp_update,+)+++def _claude(tool_name: str, raw_input: dict[str, Any] | None = None, kind: str | None = None) -> dict[str, Any]:+ update: dict[str, Any] = {"_meta": {"claudeCode": {"toolName": tool_name}}, "rawInput": raw_input or {}}+ if kind:+ update["kind"] = kind+ return update+++def _codex_command(command: str, kind: str) -> dict[str, Any]:+ return {"title": command, "kind": kind}+++def _codex_mcp(server: str, tool: str, raw_input: dict[str, Any] | None = None) -> dict[str, Any]:+ return {+ "title": f"{server}/{tool}",+ "kind": "other",+ "_meta": {"posthog": {"toolName": f"mcp__{server}__{tool}"}},+ "rawInput": raw_input or {},+ }+++class TestPhaseForToolCall:+ @parameterized.expand(+ [+ (+ "posthog_sql",+ _claude("mcp__posthog__exec", {"command": 'call execute-sql {"query": "SELECT 1 FROM events"}'}),+ "posthog:Execute SQL query",+ ),+ (+ "posthog_call_flags",+ _claude("mcp__posthog__exec", {"command": "call --json dashboard-get {}"}),+ "posthog:Get dashboard",+ ),+ (+ "codex_posthog_replays",+ _codex_mcp("posthog", "exec", {"command": "call query-session-recordings-list {}"}),+ "posthog:List session recordings",+ ),+ ("posthog_direct_tool", _claude("mcp__posthog__feature-flag-get-all", {}), "posthog:Get all feature flags"),+ # A tool the catalogue does not know must not put its name on a line.+ ("unknown_posthog_tool", _claude("mcp__posthog__exec", {"command": "call gateway__acme {}"}), "other_work"),+ # Looking up what the server offers is not work on the user's data.+ ("posthog_search", _claude("mcp__posthog__exec", {"command": "search error issues"}), None),+ ("read", _claude("Read", {"file_path": "/repo/a.py"}, kind="read"), "reading_code"),+ (+ "grep_command",+ _claude("Bash", {"command": "grep -rn foo src 2>/dev/null"}, kind="execute"),+ "reading_code",+ ),+ # Writing a file with a read command is not reading.+ (+ "write_redirect",+ _claude("Bash", {"command": "cat > dau.csv <<'EOF'"}, kind="execute"),+ "running_commands",+ ),+ ("codex_read_command", _codex_command("cat README.md", "read"), "reading_code"),+ ("edit", _claude("Edit", {"file_path": "/repo/a.py"}, kind="edit"), "making_changes"),+ ("tests", _claude("Bash", {"command": "cd repo && pytest tests/"}, kind="execute"), "running_checks"),+ ("codex_tests", _codex_command("pnpm run typecheck", "execute"), "running_checks"),+ ("pr_command", _claude("Bash", {"command": "gh pr create --draft"}, kind="execute"), "opening_pr"),+ ("signed_commit", _claude("mcp__posthog-code-tools__git_signed_commit", {"message": "x"}), "opening_pr"),+ ("other_command", _claude("Bash", {"command": "python3 script.py"}, kind="execute"), "running_commands"),+ ("web", _claude("WebFetch", {"url": "https://example.com"}, kind="fetch"), "searching_web"),+ ("artifact", _claude("mcp__posthog-code-tools__upload_artifact", {"path": "a.png"}), "preparing_files"),+ ("clone", _claude("mcp__posthog-code-tools__clone_repo", {"repo": "org/repo"}), "getting_code"),+ ("summary", _claude("mcp__posthog__task_summary_update", {"summary": "x"}), None),+ ("codex_summary", _codex_mcp("posthog-code-tools", "task_summary_update"), None),+ ("tool_search", _claude("ToolSearch", {"query": "select:x"}), None),+ ("other_mcp_server", _codex_mcp("slack", "post_message"), None),+ ]+ )+ def test_maps_tool_calls_to_plain_phases(self, _name: str, update: dict[str, Any], expected: str | None) -> None:+ tool_call = tool_call_from_acp_update(update)+ assert tool_call is not None++ phase = phase_for_tool_call(tool_call)++ assert (phase.key if phase else None) == expected++ @parameterized.expand(+ [+ ("shell", _claude("Bash", {}, kind="execute")),+ ("posthog_exec", _claude("mcp__posthog__exec", {})),+ ]+ )+ def test_call_waits_for_its_command(self, _name: str, update: dict[str, Any]) -> None:+ # Claude streams the call before its input. Classifying it then would file every test run+ # under "Running commands" and hide every PostHog call.+ assert tool_call_from_acp_update(update) is None++ @parameterized.expand(+ [+ (+ "claude_shell",+ _claude("Bash", {"command": "pytest", "description": "Run the relay tests."}, kind="execute"),+ "Run the relay tests",+ ),+ (+ "posthog_exec",+ _claude(+ "mcp__posthog__exec", {"command": "call execute-sql {}", "description": "Count weekly signups"}+ ),+ None,+ ),+ # Another tool's description argument is content, such as a new dashboard's text.+ (+ "posthog_tool",+ _claude("mcp__posthog__dashboard-create", {"description": "Weekly revenue for the board"}),+ None,+ ),+ ]+ )+ def test_only_descriptions_written_for_people_reach_the_plan(+ self, _name: str, update: dict[str, Any], expected: str | None+ ) -> None:+ tool_call = tool_call_from_acp_update(update)++ assert tool_call is not None+ assert tool_call.description == expected+++class TestAgentPlanSteps:+ def test_reads_the_todo_list_in_slack_statuses(self) -> None:+ update = {+ "sessionUpdate": "plan",+ "entries": [+ {"content": "Find the signup event.", "status": "completed"},+ {"content": "Count weekly signups", "status": "in_progress"},+ {"content": "", "status": "pending"},+ {"content": "Write the answer", "status": "pending"},+ ],+ }++ assert agent_plan_steps(update) == [+ {"title": "Find the signup event", "status": "complete"},+ {"title": "Count weekly signups", "status": "in_progress"},+ {"title": "Write the answer", "status": "pending"},+ ]+++class TestIntentFromNarrative:+ @parameterized.expand(+ [+ ("let_me", "Let me pull daily active users for last week.", "Pull daily active users for last week"),+ ("last_sentence", "Great, the table exists. Now I'll count DAU per day:", "Count DAU per day"),+ ("markdown", "The **events** table has data.\n\nLet me check `$pageview` counts", "Check $pageview counts"),+ # A question asks the reader and reports nothing about the work.+ ("question", "Should I use UTC for the week?", None),+ ("too_short", "Ok.", None),+ ]+ )+ def test_reads_the_last_sentence_as_an_activity(self, _name: str, text: str, expected: str | None) -> None:+ assert intent_from_narrative(text) == expected+++class TestDonePlanTitle:+ @parameterized.expand(+ [+ (timedelta(seconds=48), "Done in 48s"),+ (timedelta(seconds=72), "Done in 1m 12s"),+ (timedelta(minutes=2), "Done in 2m"),+ (timedelta(minutes=63, seconds=5), "Done in 1h 3m"),+ ]+ )+ def test_reads_as_a_short_duration(self, elapsed: timedelta, expected: str) -> None:+ assert done_plan_title(elapsed) == expecteddiff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.pyindex 3407f974a5d6..576618aef93b 100644--- a/products/slack_app/backend/tests/test_slack_thread.py+++ b/products/slack_app/backend/tests/test_slack_thread.py@@ -18,6 +18,14 @@ from products.slack_app.backend.slack_thread import ()+def _streamed_text(mock_client: MagicMock) -> str:+ return "".join(+ chunk.get("text", "")+ for call in mock_client.chat_appendStream.call_args_list+ for chunk in call.kwargs["chunks"]+ )++class TestSlackThreadHandler(SimpleTestCase):@parameterized.expand([@@ -56,8 +64,7 @@ class TestSlackThreadHandler(SimpleTestCase):handler.stop_status_stream(ts="1234.9999", final_markdown="Answering <@U094TR1E59V|Radu Raicea> now.")- chunks = mock_client.chat_appendStream.call_args.kwargs["chunks"]- streamed = "".join(chunk.get("text", "") for chunk in chunks)+ streamed = _streamed_text(mock_client)assert "<@U094TR1E59V>" in streamedassert "Radu Raicea" not in streamed@@ -71,9 +78,62 @@ class TestSlackThreadHandler(SimpleTestCase):SlackThreadHandler(context).stop_status_stream(ts="1234.9999", final_markdown="Done, <@U123|Jane Doe>.")- chunks = mock_client.chat_appendStream.call_args.kwargs["chunks"]- streamed = "".join(chunk.get("text", "") for chunk in chunks)- assert streamed.count("<@U123>") == 1+ assert _streamed_text(mock_client).count("<@U123>") == 1++ @patch("products.slack_app.backend.slack_thread.slack_message_exists", return_value=True)+ @patch.object(SlackThreadHandler, "_get_integration")+ @patch.object(SlackThreadHandler, "_get_client")+ def test_start_status_stream_leads_an_answer_with_the_mention(self, mock_get_client, _mock_integration, _exists):+ # An answer that opens the stream is the whole reply, so it carries the one ping.+ mock_client = MagicMock()+ mock_get_client.return_value = mock_client+ context = SlackThreadContext(+ integration_id=1, channel="C001", thread_ts="1234.5678", mentioning_slack_user_id="U123"+ )++ SlackThreadHandler(context).start_status_stream(first_markdown_text="Signups grew.")++ chunks = mock_client.chat_startStream.call_args.kwargs["chunks"]+ assert [chunk.get("text") for chunk in chunks] == ["<@U123> Signups grew."]++ @parameterized.expand(+ [+ ("answer", "Signups grew.", False, ["plan_update", "<@U123> Signups grew.", "blocks"]),+ # The answer went out when the stream opened, and carried the mention there.+ ("answer_streamed_at_start", None, True, ["plan_update", "blocks"]),+ # A stopped run has no answer, so the mention alone notifies the requester.+ ("no_answer", None, False, ["plan_update", "blocks", "\n\n<@U123>"]),+ ]+ )+ @patch.object(SlackThreadHandler, "_get_client")+ def test_stop_status_stream_mentions_the_requester_once_before_the_answer(+ self, _name, final_markdown, mention_sent, expected_order, mock_get_client+ ):+ # Chart cards describe the answer above them, and the reply pings the requester once.+ mock_client = MagicMock()+ mock_get_client.return_value = mock_client+ context = SlackThreadContext(+ integration_id=1, channel="C001", thread_ts="1234.5678", mentioning_slack_user_id="U123"+ )+ handler = SlackThreadHandler(context)++ def append_attachments() -> None:+ handler.append_status_blocks("1234.9999", [{"type": "image"}])++ handler.stop_status_stream(+ ts="1234.9999",+ final_markdown=final_markdown,+ plan_title="Done",+ append_attachments=append_attachments,+ mention_sent=mention_sent,+ )++ order = [+ chunk.get("text") or chunk["type"]+ for call in mock_client.chat_appendStream.call_args_list+ for chunk in call.kwargs["chunks"]+ ]+ assert order == expected_order@patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)@patch.object(SlackThreadHandler, "_get_client")diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 98626f226a54..1648d76150a5 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -523,6 +523,7 @@ _TASK_RUN_PUBLIC_STATE_KEYS = frozenset("run_source","runtime_adapter","sandbox_environment_id",+ "slack_app_agent_design_enabled","slack_artifact_delivery","slack_chart_delivery","slack_thread_url",diff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.pyindex 536215f47565..bb20ec992526 100644--- a/products/tasks/backend/logic/services/living_artifacts.py+++ b/products/tasks/backend/logic/services/living_artifacts.py@@ -9,7 +9,7 @@ import zipfileimport mimetypesfrom abc import ABC, abstractmethodfrom collections.abc import Callable-from dataclasses import dataclass, replace+from dataclasses import dataclass, field, replacefrom datetime import timedeltafrom typing import Anyfrom urllib.parse import urlparse@@ -25,6 +25,7 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.event_usage import groupsfrom posthog.ph_client import ph_scoped_capture+from posthog.slack.channels import MAX_BUTTON_URL_CHARS, SlackButton, section_blockfrom posthog.slack.formatting import escape_slack_mrkdwnfrom posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_blockfrom posthog.storage import object_storage@@ -675,7 +676,8 @@ class SlackCanvasArtifactAdapter(LivingArtifactAdapter):if not canvas_id:raise ValueError("Slack canvas delivery did not return a canvas id")canvas_url = _slack_canvas_url(response, mapping.slack_workspace_id, canvas_id)- _post_canvas_created_message(slack, mapping, name, canvas_id, canvas_url)+ if not _streams_slack_replies(run):+ _post_canvas_created_message(slack, mapping, name, canvas_id, canvas_url)else:canvas_id = str((artifact.location or {}).get("canvas_id") or "")if not canvas_id:@@ -704,6 +706,9 @@ class SlackCanvasArtifactAdapter(LivingArtifactAdapter):}if canvas_url:location["url"] = canvas_url+ if artifact is None and _streams_slack_replies(run):+ # The turn's streamed reply announces the canvas when it closes.+ location["notice_status"] = "pending"return ArtifactCommit(adapter=self.adapter,location=location,@@ -835,11 +840,23 @@ def has_pending_slack_file_artifacts(run: TaskRun) -> bool:return any(_pending_slack_file_version(artifact) is not None for artifact in artifacts)+@dataclass(frozen=True)+class UploadedSlackFile:+ """A file uploaded with no channel share, waiting to be attached to a streamed reply."""++ artifact: TaskArtifact+ version_number: int+ file_id: str+ file_response: dict[str, Any] | None++# Mutable: delivery accumulates into it as each card is posted.@dataclass(frozen=False)class SlackFileDeliveryResult:answer_posted: bool = Falsedelivered_count: int = 0+ # Non-image files of a streamed reply, uploaded but not yet visible in the thread.+ unattached_files: list[UploadedSlackFile] = field(default_factory=list)def has_pending_slack_image_artifacts(run: TaskRun) -> bool:@@ -854,7 +871,10 @@ def has_pending_slack_image_artifacts(run: TaskRun) -> bool:def deliver_pending_slack_file_artifacts(- run: TaskRun, *, answer_sections: list[str] | None = None+ run: TaskRun,+ *,+ answer_sections: list[str] | None = None,+ append_blocks: Callable[[list[dict[str, Any]]], bool] | None = None,) -> SlackFileDeliveryResult:"""Deliver pending slack_file artifacts to the mapped thread.@@ -869,6 +889,11 @@ def deliver_pending_slack_file_artifacts(as channel shares (these do need files:write), after the composed message.``answer_posted`` tells the caller whether the answer text went out in thecomposed message so it isn't posted twice.++ With ``append_blocks`` the chart cards go into a message the caller is streaming,+ under the answer it already streamed, instead of a message of their own. Non-image+ files then upload with no channel share, and ``unattached_files`` lists them for+ ``attach_streamed_slack_files`` once the stream has closed."""result = SlackFileDeliveryResult()mapping = _get_slack_mapping(run, raise_if_missing=False)@@ -963,14 +988,17 @@ def deliver_pending_slack_file_artifacts(delivered_artifact_ids.add(card.artifact.id)_record_chart(card.artifact, None, "url" if card.image_url else "file_upload")- result.answer_posted = _post_composed_answer_message(- slack,- mapping=mapping,- image_cards=image_cards,- answer_sections=answer_sections or [],- mark_delivered=_mark_card_delivered,- deadline=deadline,- )+ if append_blocks is not None:+ _append_image_cards(image_cards, append_blocks=append_blocks, mark_delivered=_mark_card_delivered)+ else:+ result.answer_posted = _post_composed_answer_message(+ slack,+ mapping=mapping,+ image_cards=image_cards,+ answer_sections=answer_sections or [],+ mark_delivered=_mark_card_delivered,+ deadline=deadline,+ )for card in image_cards:if card.artifact.id not in delivered_artifact_ids:_record_chart(card.artifact, "message_not_posted")@@ -995,6 +1023,18 @@ def deliver_pending_slack_file_artifacts(payload = _read_pending_slack_file_bytes(artifact, version_payload)if payload is None:continue+ version_number = int(version_payload.get("version") or artifact.current_version or 0)+ if append_blocks is not None:+ try:+ file_id, file_response = _upload_slack_file(+ slack, channel=None, thread_ts=None, name=artifact.name, content=payload, content_type=content_type+ )+ except Exception:+ logger.warning("task_artifact.slack_file_delivery_failed", artifact_id=str(artifact.id), exc_info=True)+ continue+ if file_id:+ result.unattached_files.append(UploadedSlackFile(artifact, version_number, file_id, file_response))+ continuetry:file_id, file_response = _upload_slack_file(slack,@@ -1102,6 +1142,37 @@ class _SlackImageCard:file_response: dict[str, Any] | None = None+def _append_image_cards(+ image_cards: list[_SlackImageCard],+ *,+ append_blocks: Callable[[list[dict[str, Any]]], bool],+ mark_delivered: Callable[[_SlackImageCard], None],+) -> None:+ """Append chart cards to a streamed message, as many per append as the block cap allows.++ A rejected batch retries card by card, so one bad card can't sink the others. A card+ that never lands stays pending for the next turn."""+ batches: list[list[_SlackImageCard]] = [[]]+ batch_size = 0+ for card in image_cards:+ size = len(_chart_card_blocks(card))+ if batches[-1] and batch_size + size > _SLACK_MESSAGE_BLOCK_LIMIT:+ batches.append([])+ batch_size = 0+ batches[-1].append(card)+ batch_size += size+ for batch in batches:+ if append_blocks([block for card in batch for block in _chart_card_blocks(card)]):+ for card in batch:+ mark_delivered(card)+ continue+ if len(batch) == 1:+ continue+ for card in batch:+ if append_blocks(_chart_card_blocks(card)):+ mark_delivered(card)++def _post_composed_answer_message(slack: Any,*,@@ -1562,6 +1633,85 @@ def _slack_canvas_url(response: dict[str, Any] | None, workspace_id: str | None,return None+def _streams_slack_replies(run: TaskRun) -> bool:+ """Whether this run's Slack replies stream through the agent-design message."""+ from products.tasks.backend.temporal.process_task.activities.feature_flags import ( # noqa: PLC0415 — keeps temporal off the artifact import path+ AGENT_DESIGN_STATE_KEY,+ )++ return bool((run.state or {}).get(AGENT_DESIGN_STATE_KEY))+++def stream_pending_slack_attachments(+ run: TaskRun, *, append_blocks: Callable[[list[dict[str, Any]]], bool]+) -> SlackFileDeliveryResult:+ """Deliver the run's pending attachments into the reply the caller is streaming.++ Chart and image cards and canvas notices go into the streamed message. Other files+ upload now and attach to the message after its stream closes (see+ ``attach_streamed_slack_files``), because a message cannot take a file while it streams.+ """+ result = (+ deliver_pending_slack_file_artifacts(run, append_blocks=append_blocks)+ if has_pending_slack_file_artifacts(run)+ else SlackFileDeliveryResult()+ )+ _append_pending_canvas_notices(run, append_blocks)+ return result+++def attach_streamed_slack_files(+ run: TaskRun, result: SlackFileDeliveryResult, *, attach_files: Callable[[list[str]], bool]+) -> None:+ """Attach the files a streamed reply uploaded to that reply, once its stream has closed.++ When Slack refuses the update, the files post to the thread as their own messages instead."""+ uploaded = result.unattached_files+ if not uploaded:+ return+ if not attach_files([file.file_id for file in uploaded]):+ logger.warning("task_artifact.slack_file_attach_failed", task_run_id=str(run.id))+ deliver_pending_slack_file_artifacts(run)+ return+ for file in uploaded:+ if _mark_slack_file_artifact_delivered(+ artifact=file.artifact,+ version_number=file.version_number,+ file_id=file.file_id,+ file_response=file.file_response,+ ):+ result.delivered_count += 1+ result.unattached_files = []+++def _append_pending_canvas_notices(run: TaskRun, append_blocks: Callable[[list[dict[str, Any]]], bool]) -> None:+ canvases = (+ TaskArtifact.objects.for_team(run.team_id)+ .filter(+ task_id=run.task_id,+ adapter=TaskArtifact.Adapter.SLACK_CANVAS,+ status=TaskArtifact.Status.ACTIVE,+ location__notice_status="pending",+ )+ .order_by("created_at", "id")+ )+ for artifact in canvases:+ location = artifact.location or {}+ if not append_blocks([_canvas_notice_block(artifact.name, location.get("url"))]):+ continue+ artifact.location = {**location, "notice_status": "posted"}+ artifact.save(update_fields=["location", "updated_at"])+++def _canvas_notice_block(name: str, canvas_url: str | None) -> dict[str, Any]:+ button = (+ SlackButton(text="Open canvas", url=canvas_url)+ if canvas_url and len(canvas_url) <= MAX_BUTTON_URL_CHARS+ else None+ )+ return section_block(f":spiral_note_pad: *{escape_slack_mrkdwn(name)}*", button)++def _post_canvas_created_message(slack: Any, mapping: Any, name: str, canvas_id: str | None, canvas_url: str | None) -> None: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.pyindex b789153f855c..2f5e7477b346 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@@ -19,6 +19,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import close_db_connections+from products.slack_app.backend.facade.api import agent_plan_steps, phase_for_tool_call, tool_call_from_acp_updatefrom products.tasks.backend.feature_flags import run_stream_presence_gated, run_stream_thin_tailfrom products.tasks.backend.logic.services.agent_command import (is_hogland_sandbox_url,@@ -617,7 +618,7 @@ async def _relay_loop(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)+ step_payload = _extract_progress_update(event_data, emitted_tool_call_ids)if step_payload is not None:# Flush buffered prose first to keep text-before-tool order.await _flush_pending_text(workflow_handle, pending_text_parts, last_text_flush)@@ -828,33 +829,18 @@ 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.+def _extract_progress_update(event_data: dict, seen: set[str]) -> dict[str, Any] | None:+ """The Slack plan payload for an ACP tool call (``{"phase", "activity"}``) or todo list (``{"plan"}``).- Streaming Claude tools arrive with empty rawInput first; we defer the- emit + seen-write until rawInput populates so the step gets a details line.+ It carries no tool name or arguments, only the call's description written for people. An id is+ marked seen only once its command is known, so a call that arrives without input retries."""if not _is_session_update(event_data):return Noneupdate = (event_data.get("notification", {}).get("params") or {}).get("update") or {}+ steps = agent_plan_steps(update)+ if steps is not None:+ return {"plan": steps} if steps else Noneif update.get("sessionUpdate") not in ("tool_call", "tool_call_update"):return None@@ -862,44 +848,18 @@ def _extract_tool_call_step(event_data: dict, seen: set[str]) -> dict[str, Any]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.+ tool_call = tool_call_from_acp_update(update)+ if tool_call is None: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+ phase = phase_for_tool_call(tool_call)+ # A hidden tool still ends the narrative burst before it, so it is signaled without a phase.+ if phase is None:+ return {"phase": None}+ payload: dict[str, Any] = {"phase": phase.key}+ if tool_call.description:+ payload["activity"] = tool_call.description+ return payloaddef _extract_agent_message_text(event_data: dict) -> str | None: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.pyindex 8bddca942d02..9b5ea2b4b46f 100644--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design.py@@ -1,12 +1,11 @@"""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.+Every turn shape rides the same three-activity lifecycle. Plan-block steps, the final+answer and the turn's attachments 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 dataclasses import fieldfrom typing import Any, Optionalfrom temporalio import activity@@ -19,32 +18,37 @@ from posthog.temporal.common.utils import close_db_connectionslogger = get_logger(__name__)-@dataclass+@frozenclass TaskUpdateChunk:"""One plan-block step. Flat so Temporal can serialize it."""id: strtitle: str- status: str # "in_progress" | "complete"+ status: str # "in_progress" | "complete" | "error"details: Optional[str] = None-@dataclass+@frozenclass 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+ task_updates: list[TaskUpdateChunk] = field(default_factory=list)first_markdown_text: Optional[str] = None+ plan_title: Optional[str] = None-@dataclass+@frozen+class SlackAgentDesignStream:+ ts: str+ # Whether the message has a plan block, so closing it can set the plan title.+ has_plan: bool+++@frozenclass AppendSlackAgentDesignStepsInput:slack_thread_context: dict[str, Any]ts: strtask_updates: list[TaskUpdateChunk] = field(default_factory=list)- markdown_text: Optional[str] = None+ plan_title: Optional[str] = None@frozen@@ -53,15 +57,16 @@ class StopSlackAgentDesignStreamInput:ts: strcomplete_task_id: Optional[str] = Nonecomplete_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- # Sources the provenance footer. Optional so a relay started before this field- # existed replays cleanly — it just closes without one.+ # Sources the provenance footer and the run's pending attachments.run_id: Optional[str] = None# Gateway trace id of the turn being closed, so the thumbs appended to the reply# report against that turn.trace_id: Optional[str] = None+ plan_title: Optional[str] = None+ # The stream opened with the answer, which already carried the @-mention.+ mention_sent: bool = Falsedef _rewrite_object_tags(text: Optional[str], project_url: str) -> Optional[str]:@@ -76,22 +81,26 @@ def _rewrite_object_tags(text: Optional[str], project_url: str) -> Optional[str]return rewrite_object_tags_for_slack(text, project_url=project_url)+def _chunk_dicts(task_updates: list[TaskUpdateChunk]) -> list[dict[str, Any]]:+ return [{"id": t.id, "title": t.title, "status": t.status, "details": t.details} for t in task_updates]++@activity.defn@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."""+def start_slack_agent_design_stream(input: StartSlackAgentDesignStreamInput) -> Optional[SlackAgentDesignStream]:+ """Open the turn's stream and seed it. Returns None when no stream opened."""from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandlertry:context = SlackThreadContext.from_dict(input.slack_thread_context)handler = SlackThreadHandler(context)- return handler.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=_rewrite_object_tags(input.first_markdown_text, handler.project_url),+ markdown_text = _rewrite_object_tags(input.first_markdown_text, handler.project_url)+ new_ts = handler.start_status_stream(+ task_updates=_chunk_dicts(input.task_updates),+ first_markdown_text=markdown_text,+ plan_title=input.plan_title,)+ return SlackAgentDesignStream(ts=new_ts, has_plan=bool(input.task_updates)) if new_ts else Noneexcept Exception as e:logger.warning("slack_app_start_agent_design_stream_failed", error=str(e))return None@@ -100,7 +109,7 @@ def start_slack_agent_design_stream(input: StartSlackAgentDesignStreamInput) ->@activity.defn@close_db_connectionsdef append_slack_agent_design_steps(input: AppendSlackAgentDesignStepsInput) -> None:- """Append plan-block step transitions and/or a markdown_text chunk."""+ """Append plan-block step transitions and a new plan title."""from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandlertry:@@ -108,10 +117,8 @@ def append_slack_agent_design_steps(input: AppendSlackAgentDesignStepsInput) ->handler = SlackThreadHandler(context)handler.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=_rewrite_object_tags(input.markdown_text, handler.project_url),+ task_updates=_chunk_dicts(input.task_updates),+ plan_title=input.plan_title,)except Exception as e:logger.warning("slack_app_append_agent_design_steps_failed", error=str(e))@@ -120,18 +127,43 @@ def append_slack_agent_design_steps(input: AppendSlackAgentDesignStepsInput) ->@activity.defn@close_db_connectionsdef stop_slack_agent_design_stream(input: StopSlackAgentDesignStreamInput) -> None:- """Mark the last step complete, stream the final answer, append @-mention, close."""+ """Mark the last step complete, stream the answer and the turn's attachments, close, attach files."""from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler+ from products.tasks.backend.logic.services.living_artifacts import (+ SlackFileDeliveryResult,+ attach_streamed_slack_files,+ stream_pending_slack_attachments,+ )+ from products.tasks.backend.models import TaskRuntry:context = SlackThreadContext.from_dict(input.slack_thread_context)handler = SlackThreadHandler.for_run(context, input.run_id, turn_trace_id=input.trace_id)+ task_run = TaskRun.objects.get(id=input.run_id) if input.run_id else None+ deliveries: list[SlackFileDeliveryResult] = []++ def _append_attachments() -> None:+ if task_run is None:+ return+ deliveries.append(+ stream_pending_slack_attachments(+ task_run, append_blocks=lambda blocks: handler.append_status_blocks(input.ts, blocks)+ )+ )+handler.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=_rewrite_object_tags(input.final_markdown, handler.project_url),+ plan_title=input.plan_title,+ append_attachments=_append_attachments,+ mention_sent=input.mention_sent,)+ for delivery in deliveries:+ if task_run is not None:+ attach_streamed_slack_files(+ task_run, delivery, attach_files=lambda file_ids: handler.attach_files(input.ts, file_ids)+ )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/activities/slack_agent_design_signals.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.pyindex fcd80bb932ca..0936582b4925 100644--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py@@ -35,7 +35,7 @@ from .relay_sandbox_events import (SSE_CONNECT_TIMEOUT_SECONDS,SSE_READ_TIMEOUT_SECONDS,_extract_agent_message_text,- _extract_tool_call_step,+ _extract_progress_update,_is_session_update,_signal_safely,)@@ -103,7 +103,7 @@ class SlackAgentDesignSignalEmitter:signals.append(("turn_started", {"slack_thread_context": self._slack_thread_context}))if self._turn_active:- step_payload = _extract_tool_call_step(event_data, self._emitted_tool_call_ids)+ step_payload = _extract_progress_update(event_data, self._emitted_tool_call_ids)if step_payload is not None:signals.append(("agent_status_update", step_payload))if _is_session_update(event_data):diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py b/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.pyindex 784c37980255..b15ca4e06dfb 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_slack_agent_design_signals.py@@ -2,6 +2,8 @@ from typing import Anyfrom unittest.mock import MagicMock, patch+from parameterized import parameterized+from products.tasks.backend.temporal.process_task.activities.slack_agent_design_signals import (SlackAgentDesignSignalEmitter,_event_method,@@ -70,16 +72,68 @@ class TestSlackAgentDesignSignalEmitter:assert signals == [("agent_text_delta", "second")]- def test_tool_call_emits_status_update_and_dedupes(self) -> None:+ def test_tool_call_emits_its_phase_only_and_dedupes(self) -> None:+ # The Slack plan names the kind of work, so the tool name and its arguments must not+ # travel with the signal.emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)emitter.process(_text_chunk("thinking"))first = emitter.process(_tool_call("call-1", "Read", "/etc/hosts"))repeat = emitter.process(_tool_call("call-1", "Read", "/etc/hosts"))- assert first == [("agent_status_update", {"title": "Read", "details": "/etc/hosts"})]+ assert first == [("agent_status_update", {"phase": "reading_code"})]assert repeat == []+ @parameterized.expand(+ [+ (+ "shell_description",+ "Bash",+ {"command": "pytest", "description": "Run the tests"},+ {"phase": "running_checks", "activity": "Run the tests"},+ ),+ (+ "posthog_query",+ "mcp__posthog__exec",+ {"command": 'call execute-sql {"query": "SELECT 1 FROM events"}'},+ {"phase": "posthog:Execute SQL query"},+ ),+ ]+ )+ def test_call_carries_what_runs_now_to_the_open_line(+ self, _name: str, tool_name: str, raw_input: dict[str, Any], expected: dict[str, Any]+ ) -> None:+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)+ emitter.process(_text_chunk("thinking"))+ call = _tool_call("call-2", tool_name, "")+ call["notification"]["params"]["update"]["rawInput"] = raw_input++ signals = emitter.process(call)++ assert signals == [("agent_status_update", expected)]++ def test_agent_todo_list_reaches_the_relay(self) -> None:+ emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)+ emitter.process(_text_chunk("thinking"))+ plan = {+ "type": "notification",+ "notification": {+ "method": "session/update",+ "params": {+ "update": {+ "sessionUpdate": "plan",+ "entries": [{"content": "Count weekly signups", "status": "in_progress"}],+ }+ },+ },+ }++ signals = emitter.process(plan)++ assert signals == [+ ("agent_status_update", {"plan": [{"title": "Count weekly signups", "status": "in_progress"}]})+ ]+def test_turn_completed_emitted_only_when_turn_active(self) -> None:emitter = SlackAgentDesignSignalEmitter(SLACK_CTX)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.pyindex 4ad9e7910c64..c5ceba6e3c11 100644--- a/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py+++ b/products/tasks/backend/temporal/process_task/slack_agent_design_relay.py@@ -1,34 +1,45 @@-"""Per-turn child of ProcessTaskWorkflow.+"""Per-turn child of ProcessTaskWorkflow that streams one Slack reply.-Two phases in a single chat.startStream lifecycle:+The reply is a plan block and the final answer. The plan shows one line per kind of work (see+``products.slack_app.backend.logic.progress_phases``), or the agent's todo list when it keeps one. Each line lists the+descriptions of its calls. The agent's prose does not stream: the last burst before the turn+ends is the answer. While the turn runs, one line always spins and the plan title says what+happens now.-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.+The first turn's relay starts before the sandbox exists, so the plan shows the setup steps the+parent sends through ``setup_step``. Slack ends a stream that gets no update for a few minutes,+so a quiet relay re-sends its open line."""-from dataclasses import dataclass-from datetime import timedelta+from dataclasses import replace+from datetime import datetime, timedeltafrom typing import Any, Optionalfrom temporalio import workflowfrom temporalio.common import RetryPolicy+from posthog.dataclasses import frozenfrom posthog.temporal.common.base import PostHogWorkflowwith workflow.unsafe.imports_passed_through():- from posthog.object_tags.slack import split_incomplete_tag_suffix+ from products.slack_app.backend.facade.api import (+ ANSWER_LINE_TITLE,+ OTHER_WORK,+ PLAN_TITLE_STOPPED,+ PLAN_TITLE_WORKING,+ PREPARING_LINE_TITLE,+ SLACK_STEP_STATUSES,+ THINKING_LINE_TITLE,+ ProgressPhase,+ done_plan_title,+ intent_from_narrative,+ phase_for_key,+ phase_line_title,+ )from .activities.slack_agent_design import (AppendSlackAgentDesignStepsInput,+ SlackAgentDesignStream,StartSlackAgentDesignStreamInput,StopSlackAgentDesignStreamInput,TaskUpdateChunk,@@ -40,41 +51,54 @@ with workflow.unsafe.imports_passed_through():STATUS_DEBOUNCE_SECONDS = 1.0STATUS_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]+KEEPALIVE_SECONDS = 60+MAX_PLAN_LINES = 7+# One tool call, such as a long test run, can keep the agent quiet for a long time.+TURN_IDLE_TIMEOUT_MINUTES = 30+_ACTIVITY_TIMEOUT = timedelta(seconds=30)+_ACTIVITY_RETRY = RetryPolicy(maximum_attempts=3)+# The parent's progress step that the first setup line shows.+_SANDBOX_SETUP_STEP = "sandbox"-@dataclass+@frozenclass SlackAgentDesignRelayInput:slack_thread_context: dict[str, Any]- # Trailing and defaulted so a relay already in flight decodes it as absent and- # simply closes without a footer, rather than failing replay.run_id: Optional[str] = None+ # Set for the relay that starts before the sandbox exists: the title of the first setup line.+ setup_title: Optional[str] = None@workflow.defn(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+ # Slack task id per phase line, in the order the lines appeared.+ self._line_ids: dict[str, str] = {}+ self._phases: dict[str, ProgressPhase] = {}+ self._counts: dict[str, int] = {}+ self._current_key: Optional[str] = None+ # Slack appends a step's details, so each call description is sent once.+ self._unsent_details: dict[str, list[str]] = {}+ self._keys_with_details: set[str] = set()+ self._last_description: dict[str, str] = {}+ self._plan_title: Optional[str] = None+ self._latest_description: Optional[str] = None+ # The spinning line shown while no step is open, until the next line takes over its id.+ self._placeholder: Optional[TaskUpdateChunk] = None+ self._setup_lines: dict[str, TaskUpdateChunk] = {}+ self._changed_setup_steps: list[str] = []+ self._agent_plan: list[TaskUpdateChunk] = []+ self._agent_plan_changed: bool = False+ # Lines added, and lines whose counter moved, since the last flush.+ self._new_keys: list[str] = []+ self._changed_keys: set[str] = set()+ # Prose since the last tool call, and the last non-empty burst before it.+ self._narrative: str = ""+ self._last_burst: str = ""+ self._stream: Optional[SlackAgentDesignStream] = Noneself._last_dispatched_at: float = 0.0- # Length of a narrative held back whole (an unfinished tag); a flush waits for it to grow.- self._held_length: int = 0+ self._last_signal_at: Optional[datetime] = None+ self._started_at: datetime = datetime.minself._turn_complete: bool = False# Gateway trace id of the turn this relay is streaming, as ``complete_turn``# reports it. The closing reply carries the thumbs, so this is what a rating on@@ -83,248 +107,326 @@ class SlackAgentDesignRelayWorkflow(PostHogWorkflow):@workflow.signalasync 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+ """A tool call or a new agent todo list. Either ends the prose burst before it."""+ self._last_signal_at = workflow.now()+ narrative, self._narrative = self._narrative, ""+ if narrative.strip():+ self._last_burst = narrative++ if not isinstance(payload, dict):+ return+ # The agent is working, so the sandbox is ready.+ self._finish_setup("complete")+ if isinstance(payload.get("plan"), list):+ self._set_agent_plan(payload["plan"])+ return+ if self._agent_plan:+ return+ key = payload.get("phase")+ phase = phase_for_key(key) if isinstance(key, str) else None+ if phase is None:+ return+ if phase.key not in self._line_ids and len(self._line_ids) >= MAX_PLAN_LINES - 1:+ phase = OTHER_WORK+ key = phase.key+ self._phases[key] = phase+ description = payload.get("activity")+ if not isinstance(description, str) or not description:+ description = intent_from_narrative(narrative) if narrative.strip() else None+ self._latest_description = description+ if description and description != self._last_description.get(key):+ self._last_description[key] = description+ self._unsent_details.setdefault(key, []).append(description)+ self._counts[key] = self._counts.get(key, 0) + 1+ if key not in self._line_ids:+ self._line_ids[key] = self._claim_line_id()+ self._new_keys.append(key)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))+ self._changed_keys.add(key)++ def _set_agent_plan(self, steps: list[Any]) -> None:+ lines: list[TaskUpdateChunk] = []+ for index, step in enumerate(steps):+ if not isinstance(step, dict) or not isinstance(step.get("title"), str):+ continue+ line_id = self._agent_plan[index].id if index < len(self._agent_plan) else self._claim_line_id()+ lines.append(TaskUpdateChunk(id=line_id, title=step["title"], status=str(step.get("status") or "pending")))+ if lines:+ # A step the agent dropped keeps its line, because Slack cannot remove one.+ self._agent_plan = lines + self._agent_plan[len(lines) :]+ self._agent_plan_changed = True++ @workflow.signal+ async def setup_step(self, payload: dict[str, Any]) -> None:+ """A sandbox setup step, such as "Cloning repository", before the agent runs."""+ self._last_signal_at = workflow.now()+ step, title = payload.get("step"), payload.get("title")+ if not isinstance(step, str) or not isinstance(title, str) or not title:+ return+ existing = self._setup_lines.get(step)+ self._setup_lines[step] = TaskUpdateChunk(+ id=existing.id if existing else self._claim_line_id(),+ title=title,+ status=SLACK_STEP_STATUSES.get(str(payload.get("status")), "in_progress"),+ )+ self._mark_setup_changed(step)++ def _claim_line_id(self) -> str:+ """The Slack task id for a new line. The placeholder's id turns the placeholder into it."""+ if self._placeholder is None:+ return str(workflow.uuid4())+ line_id = self._placeholder.id+ self._placeholder = None+ return line_id++ def _needs_placeholder(self) -> bool:+ if self._turn_complete or self._placeholder is not None or self._current_key is not None:+ return False+ if self._agent_plan or not self._setup_lines:+ return False+ return all(line.status != "in_progress" for line in self._setup_lines.values())++ def _mark_setup_changed(self, step: str) -> None:+ if step not in self._changed_setup_steps:+ self._changed_setup_steps.append(step)++ def _finish_setup(self, status: str) -> None:+ for step, line in self._setup_lines.items():+ if line.status == "in_progress":+ self._setup_lines[step] = replace(line, status=status)+ self._mark_setup_changed(step)@workflow.signalasync def agent_text_delta(self, text: str) -> None:+ self._last_signal_at = workflow.now()if isinstance(text, str) and text:- self._current_narrative += text+ self._narrative += text@workflow.signalasync def complete_turn(self, trace_id: str | None = None) -> None:self._turn_complete = Trueself._trace_id = trace_id- 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+ def _line_chunk(self, key: str, status: str, *, with_details: bool = False) -> TaskUpdateChunk:+ title = phase_line_title(self._phases[key], self._counts.get(key, 0))+ details = None+ unsent = self._unsent_details.pop(key, None) if with_details else None+ if unsent:+ # Slack appends details to the text it shows, so later descriptions start a new line.+ details = ("\n" if key in self._keys_with_details else "") + "\n".join(unsent)+ self._keys_with_details.add(key)+ return TaskUpdateChunk(id=self._line_ids[key], title=title, status=status, details=details)++ def _open_agent_step(self) -> Optional[TaskUpdateChunk]:+ return next((line for line in self._agent_plan if line.status == "in_progress"), None)++ def _open_line(self) -> Optional[TaskUpdateChunk]:+ """The line shown in progress right now."""+ if self._agent_plan:+ return self._open_agent_step() or self._agent_plan[-1]+ if self._current_key is not None:+ return self._line_chunk(self._current_key, "in_progress")+ setup_line = next((line for line in reversed(self._setup_lines.values()) if line.status == "in_progress"), None)+ return setup_line or self._placeholder++ def _take_pending_chunks(self, *, allow_placeholder: bool = True) -> list[TaskUpdateChunk]:+ """Chunks for the lines added or changed since the last flush, in plan order."""+ chunks = [self._setup_lines[step] for step in self._changed_setup_steps]+ self._changed_setup_steps = []+ for key in self._line_ids:+ if key in self._changed_keys and key not in self._new_keys:+ status = "in_progress" if key == self._current_key else "complete"+ chunks.append(self._line_chunk(key, status, with_details=True))+ for key in self._new_keys:+ if self._current_key is not None:+ chunks.append(self._line_chunk(self._current_key, "complete"))+ self._current_key = key+ chunks.append(self._line_chunk(key, "in_progress", with_details=True))+ self._new_keys = []+ self._changed_keys = set()+ if self._agent_plan_changed:+ if self._current_key is not None:+ # The todo list takes over from here, so the phase line it interrupts is done.+ chunks.append(self._line_chunk(self._current_key, "complete"))+ self._current_key = None+ chunks.extend(self._agent_plan)+ self._agent_plan_changed = False+ if allow_placeholder and self._needs_placeholder():+ agent_ready = self._setup_lines.get("agent")+ title = THINKING_LINE_TITLE if agent_ready and agent_ready.status == "complete" else PREPARING_LINE_TITLE+ self._placeholder = TaskUpdateChunk(id=str(workflow.uuid4()), title=title, status="in_progress")+ chunks.append(self._placeholder)return chunks+ def _current_plan_title(self) -> str:+ """What happens now: the open line, or the description of the call it runs."""+ if self._agent_plan:+ open_step = self._open_agent_step()+ return open_step.title if open_step else PLAN_TITLE_WORKING+ if self._current_key is not None:+ return self._latest_description or self._phases[self._current_key].title+ open_line = self._open_line()+ return open_line.title if open_line else PLAN_TITLE_WORKING++ def _plan_title_update(self) -> Optional[str]:+ """The plan title to send with the next lines, when it changed."""+ title = self._current_plan_title()+ if title == self._plan_title:+ return None+ self._plan_title = title+ return title+def _has_pending(self) -> bool:- if not self._has_seen_tool_call:- return bool(self._current_narrative)- return bool(self._pending_steps)+ return bool(self._new_keys or self._changed_keys or self._agent_plan_changed or self._changed_setup_steps)++ def _closing_plan_title(self) -> Optional[str]:+ if self._stream is None or not (self._stream.has_plan or self._line_ids or self._agent_plan):+ return None+ if not self._turn_complete:+ return PLAN_TITLE_STOPPED+ return done_plan_title(workflow.now() - self._started_at)++ def _final_answer(self) -> str:+ return (self._narrative if self._narrative.strip() else self._last_burst).strip()++ def _idle_for(self) -> timedelta:+ return workflow.now() - (self._last_signal_at or self._started_at)++ async def _start_stream(self, input: SlackAgentDesignRelayInput, **fields: Any) -> Optional[SlackAgentDesignStream]:+ return await workflow.execute_activity(+ start_slack_agent_design_stream,+ StartSlackAgentDesignStreamInput(slack_thread_context=input.slack_thread_context, **fields),+ start_to_close_timeout=_ACTIVITY_TIMEOUT,+ retry_policy=_ACTIVITY_RETRY,+ )++ async def _append(+ self, input: SlackAgentDesignRelayInput, chunks: list[TaskUpdateChunk], plan_title: Optional[str] = None+ ) -> None:+ assert self._stream is not None+ await workflow.execute_activity(+ append_slack_agent_design_steps,+ AppendSlackAgentDesignStepsInput(+ slack_thread_context=input.slack_thread_context,+ ts=self._stream.ts,+ task_updates=chunks,+ plan_title=plan_title,+ ),+ start_to_close_timeout=_ACTIVITY_TIMEOUT,+ retry_policy=_ACTIVITY_RETRY,+ )@workflow.runasync def run(self, input: SlackAgentDesignRelayInput) -> None:+ self._started_at = workflow.now()try:+ if input.setup_title:+ setup_line = TaskUpdateChunk(id=str(workflow.uuid4()), title=input.setup_title, status="in_progress")+ self._setup_lines[_SANDBOX_SETUP_STEP] = setup_line+ self._plan_title = input.setup_title+ self._stream = await self._start_stream(input, task_updates=[setup_line], plan_title=input.setup_title)+ if self._stream is None:+ return+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),+ timeout=timedelta(seconds=KEEPALIVE_SECONDS),)except TimeoutError:- workflow.logger.warning(- "slack_app_agent_design_relay_idle_timeout",- extra={"workflow_id": workflow.info().workflow_id},- )- return+ if self._idle_for() >= timedelta(minutes=TURN_IDLE_TIMEOUT_MINUTES):+ workflow.logger.warning(+ "slack_app_agent_design_relay_idle_timeout",+ extra={"workflow_id": workflow.info().workflow_id},+ )+ return+ open_line = self._open_line()+ if self._stream is not None and open_line is not None:+ await self._append(input, [open_line])+ continueif self._turn_complete:break # type: ignore[unreachable]await workflow.sleep(STATUS_DEBOUNCE_SECONDS)-elapsed = workflow.now().timestamp() - self._last_dispatched_atif 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.- if not self._current_narrative:- continue- if workflow.patched("slack-agent-design-hold-split-tags-2026-08"):- # An object tag or code fence cut by the flush boundary would post as- # raw XML; keep its start for the next flush. Patched because a history- # recorded before this branch cleared the narrative here and then waited.- split = split_incomplete_tag_suffix(self._current_narrative)- if not split.sendable:- self._held_length = len(self._current_narrative)- try:- await workflow.wait_condition(- lambda: len(self._current_narrative) != self._held_length 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- continue- to_stream = split.sendable- self._current_narrative = split.held- else:- to_stream = self._current_narrative- 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),- )+ chunks = self._take_pending_chunks()+ if not chunks: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:+ plan_title = self._plan_title_update()+ if self._stream is None:+ self._stream = await self._start_stream(input, task_updates=chunks, plan_title=self._plan_title)+ if self._stream 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),- )+ await self._append(input, chunks, plan_title)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,- run_id=input.run_id,- trace_id=self._trace_id,- ),- start_to_close_timeout=timedelta(seconds=10),- retry_policy=RetryPolicy(maximum_attempts=3),- )+ await self._close_stream(input)++ def _closing_line(self) -> Optional[TaskUpdateChunk]:+ """The open line, which the stop call marks complete."""+ if self._agent_plan:+ return None+ if self._current_key is not None:+ return self._line_chunk(self._current_key, "complete")+ if self._placeholder is not None:+ # The turn answered without a tool, so the placeholder is where the answer came from.+ title = ANSWER_LINE_TITLE if self._turn_complete else self._placeholder.title+ return replace(self._placeholder, title=title, status="complete")+ return None++ async def _close_stream(self, input: SlackAgentDesignRelayInput) -> None:+ final_answer = self._final_answer()+ final_for_stop: Optional[str] = final_answer or None+ mention_sent = False+ # Slack marks a step still open at the end as failed. A finished turn completes the setup+ # and agent steps left open, and a stopped one leaves every unfinished step failed.+ final_status = "complete" if self._turn_complete else "error"+ self._finish_setup(final_status)+ # Lines that never reached Slack because the turn ended inside the debounce window.+ pending = self._take_pending_chunks(allow_placeholder=False)+ if self._stream is None and (final_answer or pending):+ # A turn with no flushed step still streams its answer in a stream of its own.+ self._stream = await self._start_stream(+ input,+ task_updates=pending,+ first_markdown_text=final_answer or None,+ plan_title=PLAN_TITLE_WORKING if pending else None,+ )+ final_for_stop = None+ mention_sent = bool(final_answer)+ pending = []+ if self._stream is None:+ return+ pending.extend(replace(line, status=final_status) for line in self._agent_plan if line.status != "complete")+ closing = self._closing_line()+ if closing is not None and not self._turn_complete:+ # The run stopped inside this step, so it must not read as done.+ pending.append(replace(closing, status="error"))+ closing = None+ if pending:+ await self._append(input, pending)+ await workflow.execute_activity(+ stop_slack_agent_design_stream,+ StopSlackAgentDesignStreamInput(+ slack_thread_context=input.slack_thread_context,+ ts=self._stream.ts,+ complete_task_id=closing.id if closing else None,+ complete_task_title=closing.title if closing else None,+ final_markdown=final_for_stop,+ run_id=input.run_id,+ trace_id=self._trace_id,+ plan_title=self._closing_plan_title(),+ mention_sent=mention_sent,+ ),+ # Attachments upload inside this activity. One attempt, because a retry would+ # append the answer a second time.+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )diff --git a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.pyindex 02a93bed57b2..4d5e4a8fda69 100644--- a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py+++ b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design.py@@ -9,20 +9,17 @@ from parameterized import parameterizedfrom posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team-from posthog.object_tags.slack import split_incomplete_tag_suffixfrom products.slack_app.backend.slack_thread import SlackThreadHandlerfrom products.tasks.backend.temporal.process_task.activities.slack_agent_design import (- AppendSlackAgentDesignStepsInput,StopSlackAgentDesignStreamInput,- append_slack_agent_design_steps,stop_slack_agent_design_stream,)PROJECT_URL = "https://us.posthog.com/project/7"-class TestBufferedSlackAgentDesignStream(SimpleTestCase):+class TestStreamedAnswerCodeElements(SimpleTestCase):@parameterized.expand([("backticks", "```", True),@@ -33,40 +30,25 @@ class TestBufferedSlackAgentDesignStream(SimpleTestCase):)@patch.object(SlackThreadHandler, "project_url", new_callable=PropertyMock, return_value=PROJECT_URL)@patch.object(SlackThreadHandler, "_get_client")- def test_buffered_code_elements_reach_slack_intact(+ def test_code_elements_reach_slack_intact(self, _name: str, fence: str, closed: bool, mock_get_client: MagicMock, _project_url: PropertyMock) -> None:- # Goes through the activities, so the rewriter runs on every flush. A tag cut by a flush- # boundary is held back and sent whole in the next one, and a tag inside a fence stays- # literal, so the example arrives as the agent typed it.+ # The final answer goes through the tag rewriter. A tag inside a fence stays literal,+ # so the example arrives as the agent typed it.client = mock_get_client.return_valuecontext = {"integration_id": 1, "channel": "C001", "thread_ts": "1234.5678"}- updates = [f"Before\n\n{fence}xml\n", '<insight id="1">', "Example</insight>\n"]+ answer = f'Before\n\n{fence}xml\n<insight id="1">Example</insight>\n'if closed:- updates.append(f"{fence}\n\nAfter\n")- pending = ""- for update in updates:- split = split_incomplete_tag_suffix(pending + update)- pending = split.held- if split.sendable:- append_slack_agent_design_steps(- AppendSlackAgentDesignStepsInput(- slack_thread_context=context,- ts="1234.9999",- markdown_text=split.sendable,- )- )+ answer += f"{fence}\n\nAfter\n"+stop_slack_agent_design_stream(- StopSlackAgentDesignStreamInput(- slack_thread_context=context,- ts="1234.9999",- final_markdown=pending,- )+ StopSlackAgentDesignStreamInput(slack_thread_context=context, ts="1234.9999", final_markdown=answer))+streamed = "".join(chunk.get("text", "") for call in client.chat_appendStream.call_args_list for chunk in call.kwargs["chunks"])- assert streamed == "".join(updates)+ assert streamed == answer@override_settings(SITE_URL="https://us.posthog.com")diff --git a/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.py b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.pynew file mode 100644index 000000000000..9fd42c9b2d43--- /dev/null+++ b/products/tasks/backend/temporal/process_task/tests/test_slack_agent_design_relay.py@@ -0,0 +1,293 @@+import uuid+import asyncio+from typing import Any++import pytest++from temporalio import activity+from temporalio.client import WorkflowFailureError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from products.tasks.backend.temporal.process_task.activities.slack_agent_design import (+ AppendSlackAgentDesignStepsInput,+ SlackAgentDesignStream,+ StartSlackAgentDesignStreamInput,+ StopSlackAgentDesignStreamInput,+ TaskUpdateChunk,+)+from products.tasks.backend.temporal.process_task.slack_agent_design_relay import (+ SlackAgentDesignRelayInput,+ SlackAgentDesignRelayWorkflow,+)++pytestmark = [pytest.mark.asyncio]++# A pseudo signal for ``_run_relay``: skip this many seconds, so the relay flushes what it has.+WAIT = "__wait__"++SLACK_CTX = {"integration_id": 1, "channel": "C1", "thread_ts": "1.0", "mentioning_slack_user_id": "U1"}+++class _SlackCalls:+ def __init__(self) -> None:+ self.starts: list[StartSlackAgentDesignStreamInput] = []+ self.appends: list[AppendSlackAgentDesignStepsInput] = []+ self.stops: list[StopSlackAgentDesignStreamInput] = []++ def activities(self) -> list[Any]:+ @activity.defn(name="start_slack_agent_design_stream")+ async def start(input: StartSlackAgentDesignStreamInput) -> SlackAgentDesignStream:+ self.starts.append(input)+ return SlackAgentDesignStream(ts="2.0", has_plan=bool(input.task_updates))++ @activity.defn(name="append_slack_agent_design_steps")+ async def append(input: AppendSlackAgentDesignStepsInput) -> None:+ self.appends.append(input)++ @activity.defn(name="stop_slack_agent_design_stream")+ async def stop(input: StopSlackAgentDesignStreamInput) -> None:+ self.stops.append(input)++ return [start, append, stop]++ def final_lines(self) -> dict[str, tuple[str, str | None, str]]:+ lines: dict[str, tuple[str, str]] = {}+ details: dict[str, str] = {}+ for chunk in self.sent_chunks():+ lines[chunk.id] = (chunk.title, chunk.status)+ if chunk.details:+ details[chunk.id] = details.get(chunk.id, "") + chunk.details+ for stop in self.stops:+ if stop.complete_task_id and stop.complete_task_title:+ lines[stop.complete_task_id] = (stop.complete_task_title, "complete")+ return {line_id: (title, details.get(line_id), status) for line_id, (title, status) in lines.items()}++ def sent_chunks(self) -> list[TaskUpdateChunk]:+ return [chunk for start in self.starts for chunk in start.task_updates] + [+ chunk for append in self.appends for chunk in append.task_updates+ ]++ def answer(self) -> str | None:+ return next((s.final_markdown for s in self.stops if s.final_markdown), None) or next(+ (s.first_markdown_text for s in self.starts if s.first_markdown_text), None+ )+++async def _run_relay(+ signals: list[tuple[str, Any]], *, setup_title: str | None = None, cancel: bool = False+) -> _SlackCalls:+ calls = _SlackCalls()+ async with await WorkflowEnvironment.start_time_skipping() as env:+ task_queue = f"test-{uuid.uuid4()}"+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[SlackAgentDesignRelayWorkflow],+ activities=calls.activities(),+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ handle = await env.client.start_workflow(+ SlackAgentDesignRelayWorkflow.run,+ SlackAgentDesignRelayInput(slack_thread_context=SLACK_CTX, run_id="run-1", setup_title=setup_title),+ id=f"relay-{uuid.uuid4()}",+ task_queue=task_queue,+ )+ for name, arg in signals:+ if name == WAIT:+ await env.sleep(arg)+ continue+ await handle.signal(name, arg)+ if cancel:+ await asyncio.sleep(0.5)+ await handle.cancel()+ with pytest.raises(WorkflowFailureError):+ await handle.result()+ else:+ await handle.signal("complete_turn", "trace-1")+ await handle.result()+ return calls+++class TestSlackAgentDesignRelay:+ @pytest.mark.timeout(60, func_only=True)+ async def test_tool_calls_collapse_into_one_line_per_phase(self) -> None:+ calls = await _run_relay(+ [+ ("agent_text_delta", "Let me look at the data."),+ ("agent_status_update", {"phase": "posthog:Execute SQL query"}),+ ("agent_status_update", {"phase": "posthog:Execute SQL query"}),+ ("agent_status_update", {"phase": "reading_code", "activity": "Search for callers"}),+ ("agent_text_delta", "Now I need to look into this."),+ ("agent_status_update", {"phase": "posthog:Execute SQL query"}),+ ("agent_status_update", {"phase": "making_changes"}),+ ("agent_text_delta", "Signups grew."),+ ]+ )++ # Each call's description stays under its line. With no description, the agent's own last+ # sentence says what the call is for. Slack appends details, so a resent one shows twice.+ assert sorted(calls.final_lines().values()) == [+ ("Execute SQL query (3 calls)", "Look at the data\nLook into this", "complete"),+ ("Making changes", None, "complete"),+ ("Reading the code", "Search for callers", "complete"),+ ]+ assert calls.answer() == "Signups grew."+ assert [(s.plan_title or "").startswith("Done in ") for s in calls.stops] == [True]++ @pytest.mark.parametrize(+ "tail",+ [+ [("agent_text_delta", "Answer.")],+ # A trailing hidden tool, such as a summary update, must not cost the answer.+ [("agent_text_delta", "Answer."), ("agent_status_update", {"phase": None})],+ ],+ ids=["answer_after_last_tool", "answer_before_hidden_tool"],+ )+ @pytest.mark.timeout(60, func_only=True)+ async def test_last_prose_burst_is_the_answer(self, tail: list[tuple[str, Any]]) -> None:+ calls = await _run_relay(+ [("agent_text_delta", "Checking."), ("agent_status_update", {"phase": "posthog:Execute SQL query"}), *tail]+ )++ assert calls.answer() == "Answer."++ @pytest.mark.parametrize(+ "work, work_lines",+ [+ (+ [("agent_status_update", {"phase": "posthog:Execute SQL query"})],+ [("Execute SQL query", None, "complete")],+ ),+ ([("agent_text_delta", "Hi! What should I look at?")], []),+ ],+ ids=["tool_call", "answer_without_tools"],+ )+ @pytest.mark.timeout(60, func_only=True)+ async def test_setup_steps_change_in_place_and_complete(+ self, work: list[tuple[str, Any]], work_lines: list[tuple[str, None, str]]+ ) -> None:+ # A later update of a setup step must not add a second line, and a step still open when+ # the agent works must not keep spinning, or end as a failure.+ calls = await _run_relay(+ [+ ("setup_step", {"step": "sandbox", "status": "completed", "title": "Sandbox ready"}),+ ("setup_step", {"step": "clone", "status": "in_progress", "title": "Cloning repository"}),+ *work,+ ],+ setup_title="Setting up sandbox",+ )++ assert [[(c.title, c.status) for c in s.task_updates] for s in calls.starts] == [+ [("Setting up sandbox", "in_progress")]+ ]+ assert list(calls.final_lines().values()) == [+ ("Sandbox ready", None, "complete"),+ ("Cloning repository", None, "complete"),+ *work_lines,+ ]+ assert [(s.plan_title or "").startswith("Done in ") for s in calls.stops] == [True]++ @pytest.mark.parametrize(+ "work, last_line, plan_title",+ [+ (+ [("agent_status_update", {"phase": "posthog:Execute SQL query", "activity": "Count weekly signups"})],+ ("Execute SQL query", "Count weekly signups", "complete"),+ "Count weekly signups",+ ),+ (+ [("agent_text_delta", "Hi! What should I look at?")],+ ("Writing the answer", None, "complete"),+ "Thinking",+ ),+ ],+ ids=["tool_call", "answer_without_tools"],+ )+ @pytest.mark.timeout(60, func_only=True)+ async def test_a_line_spins_between_setup_and_work(+ self, work: list[tuple[str, Any]], last_line: tuple[str, str | None, str], plan_title: str+ ) -> None:+ # With setup done and no call yet, nothing else shows that the agent is working. The+ # next line must take over the placeholder, or a finished "Thinking" line stays behind.+ calls = await _run_relay(+ [+ ("setup_step", {"step": "sandbox", "status": "completed", "title": "Sandbox ready"}),+ ("setup_step", {"step": "agent", "status": "completed", "title": "Agent ready"}),+ (WAIT, 10),+ *work,+ ],+ setup_title="Setting up sandbox",+ )++ assert ("Thinking", "in_progress") in [(c.title, c.status) for c in calls.sent_chunks()]+ # A collapsed plan shows only its title, so the title must say what happens now.+ assert [s.plan_title for s in calls.starts] == ["Setting up sandbox"]+ assert [a.plan_title for a in calls.appends if a.plan_title][-1] == plan_title+ assert list(calls.final_lines().values()) == [+ ("Sandbox ready", None, "complete"),+ ("Agent ready", None, "complete"),+ last_line,+ ]++ @pytest.mark.timeout(60, func_only=True)+ async def test_quiet_relay_resends_its_open_line(self) -> None:+ # Slack ends a stream that gets no update for a few minutes and fails its open step.+ calls = await _run_relay([(WAIT, 130)], setup_title="Setting up sandbox")++ resent = [c for a in calls.appends for c in a.task_updates if c.title == "Setting up sandbox"]+ assert len(resent) >= 2++ @pytest.mark.timeout(60, func_only=True)+ async def test_answer_without_steps_opens_the_stream_with_its_mention(self) -> None:+ # The stop call must not mention the requester again, or they get a second ping.+ calls = await _run_relay([("agent_text_delta", "Signups grew.")])++ assert [s.first_markdown_text for s in calls.starts] == ["Signups grew."]+ assert [s.mention_sent for s in calls.stops] == [True]++ @pytest.mark.timeout(60, func_only=True)+ async def test_stopped_run_marks_the_open_step_failed(self) -> None:+ # A run that fails during provisioning must not leave the setup step spinning, or read as done.+ calls = await _run_relay([], setup_title="Setting up sandbox", cancel=True)++ assert list(calls.final_lines().values()) == [("Setting up sandbox", None, "error")]+ assert [s.plan_title for s in calls.stops] == ["Stopped"]++ @pytest.mark.timeout(60, func_only=True)+ async def test_phases_past_the_line_limit_fold_into_other_work(self) -> None:+ keys = [f"posthog:Category {index}" for index in range(9)]+ calls = await _run_relay([("agent_status_update", {"phase": key}) for key in keys])++ titles = [title for title, _details, _status in calls.final_lines().values()]+ assert len(titles) == 7+ assert "Other work (3 steps)" in titles++ @pytest.mark.parametrize(+ "cancel, expected_status, expected_title",+ [(False, "complete", "Done in "), (True, "error", "Stopped")],+ ids=["turn_completes", "run_stops"],+ )+ @pytest.mark.timeout(60, func_only=True)+ async def test_agent_todo_list_replaces_the_phase_lines(+ self, cancel: bool, expected_status: str, expected_title: str+ ) -> None:+ # Slack turns a step still pending at the end into a failure, so a finished turn must+ # complete the leftovers, and a stopped run must not read as done.+ plan = [+ {"title": "Find the signup event", "status": "in_progress"},+ {"title": "Count weekly signups", "status": "pending"},+ ]+ calls = await _run_relay(+ [+ ("agent_status_update", {"plan": plan}),+ ("agent_status_update", {"phase": "reading_code"}),+ ],+ cancel=cancel,+ )++ assert sorted(calls.final_lines().values()) == [+ ("Count weekly signups", None, expected_status),+ ("Find the signup event", None, expected_status),+ ]+ assert [(s.plan_title or "").startswith(expected_title) for s in calls.stops] == [True]diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.pyindex afe6031b4953..36198eb271af 100644--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py@@ -2242,6 +2242,8 @@ class TestProcessTaskWorkflowUnit:)monkeypatch.setattr(workflow, "_relay_sandbox_events", relay_sandbox_events_mock)monkeypatch.setattr(workflow, "_relay_agent_design_signals", relay_agent_design_signals_mock)+ start_slack_relay_mock = AsyncMock()+ monkeypatch.setattr(workflow, "_start_slack_agent_design_relay", start_slack_relay_mock)monkeypatch.setattr(process_task_workflow_module.workflow, "patched", Mock(return_value=True))result = await workflow.run(ProcessTaskInput(run_id="run-id", slack_thread_context={"channel": "C1"}))@@ -2249,6 +2251,47 @@ class TestProcessTaskWorkflowUnit:assert result.success is Truerelay_sandbox_events_mock.assert_not_called()relay_agent_design_signals_mock.assert_called_once()+ # The plan shows while the sandbox provisions, so the relay starts before the first turn.+ start_slack_relay_mock.assert_awaited_once_with({"channel": "C1"}, setup_title="Setting up sandbox")++ @pytest.mark.parametrize("early_relay_open, starts_relay", [(True, False), (False, True)])+ async def test_turn_started_reuses_the_relay_started_during_provisioning(self, early_relay_open, starts_relay):+ # A second relay for the first turn would post a second reply in the thread.+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123)+ workflow._is_agent_design_enabled = True+ workflow._early_slack_relay_open = early_relay_open+ start_relay_mock = AsyncMock()+ workflow._start_slack_agent_design_relay = start_relay_mock # type: ignore[method-assign]++ await workflow.turn_started({"slack_thread_context": {"channel": "C1"}})++ assert start_relay_mock.called is starts_relay+ assert workflow._early_slack_relay_open is False++ @pytest.mark.parametrize(+ "relay_open, step, forwarded",+ [+ (True, "clone", True),+ # Pull request and CI steps come after the agent starts, and its own lines cover them.+ (True, "pr", False),+ # A follow-up turn reuses the running sandbox, so no setup shows in its plan.+ (False, "clone", False),+ ],+ )+ async def test_emit_progress_shows_sandbox_setup_in_the_early_slack_plan(+ self, monkeypatch, relay_open, step, forwarded+ ):+ workflow = ProcessTaskWorkflow()+ workflow._context = _build_context(github_integration_id=123)+ workflow._early_slack_relay_open = relay_open+ monkeypatch.setattr(workflow, "_run_progress_activity", AsyncMock(return_value=True))+ forward_mock = Mock()+ monkeypatch.setattr(workflow, "_forward_slack_setup_step", forward_mock)++ await workflow._emit_progress(step, "in_progress", "Cloning repository", "setup")++ assert forward_mock.called is forwarded@pytest.mark.parametrize("origin_product, pr_progress_emitted, ci_repetitions, end_of_turn_received, expected_status",diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex e5b3686d9c31..a025a98e1726 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -403,6 +403,9 @@ _ORIGIN_PRODUCT_SIGNAL_REPORT = "signal_report"# Two-step deprecate-then-delete cleanup lifecycle as above._PATCH_ID_SLACK_AGENT_DESIGN_STATUS = "tasks-slack-agent-design-status"+# Progress steps of sandbox setup. The Slack plan shows them until the first turn starts.+_SLACK_SETUP_PROGRESS_STEPS = frozenset({"sandbox", "clone", "checkout", "wizard", "agent"})+# Gates the refusal to execute local-environment (desktop-driven) runs. Pre-guard# histories of such runs proceeded into provisioning; the marker keeps their replays# deterministic. Same two-step cleanup lifecycle as above.@@ -564,6 +567,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._self_driving_quota_next_check_at: Optional[datetime] = Noneself._self_driving_quota_checks_active: bool = Trueself._current_slack_relay_workflow_id: Optional[str] = None+ # A relay started during provisioning that the first turn_started must reuse.+ self._early_slack_relay_open: bool = Falseself._agent_shadow_launched = Falseself._first_command_dispatched_recorded = Falseself._first_agent_activity_recorded = False@@ -572,6 +577,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):self._agent_ready_at: datetime | None = Noneself._boot_telemetry_tasks: list[asyncio.Task[None]] = []self._progress_chain: asyncio.Task[None] | None = None+ self._slack_setup_chain: asyncio.Task[None] | None = Noneself._pending_progress_activities: dict[asyncio.Task[None], str] = {}self._agent_boot_interaction_telemetry_enabled = False@@ -1827,6 +1833,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):# Agent-design path owns this surface via per-turn relay children.if not self._is_agent_design_enabled:await self._post_slack_update()+ elif self._slack_thread_context:+ # The first turn's relay starts now, so the plan shows while the sandbox provisions.+ await self._start_slack_agent_design_relay(self._slack_thread_context, setup_title=sandbox_label)+ self._early_slack_relay_open = Truesandbox_output = await self._get_sandbox_for_repository()sandbox_id = sandbox_output.sandbox_id@@ -2781,6 +2791,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):scoped id is what actually goes on the wire — callers don't need tothink about uniqueness."""+ if self._early_slack_relay_open and group == "setup" and step in _SLACK_SETUP_PROGRESS_STEPS:+ self._forward_slack_setup_step(step, status, label)activity_input = EmitProgressInput(run_id=self.context.run_id,step=step,@@ -2801,6 +2813,29 @@ class ProcessTaskWorkflow(PostHogWorkflow):if wait:await emission+ def _forward_slack_setup_step(self, step: str, status: str, label: str) -> None:+ """Show a sandbox setup step in the Slack plan, in the order the steps happen."""+ payload = {"step": step, "status": status, "title": label}+ self._slack_setup_chain = asyncio.create_task(+ self._signal_slack_setup_step_in_order(self._slack_setup_chain, payload)+ )++ async def _signal_slack_setup_step_in_order(+ self, previous: "asyncio.Task[None] | None", payload: dict[str, str]+ ) -> None:+ if previous is not None:+ await asyncio.wait([previous])+ if 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.setup_step, payload)+ except Exception as e:+ workflow.logger.debug(+ "slack_setup_step_forward_failed",+ extra={"run_id": self.context.run_id, "error": str(e)},+ )+async def _emit_progress_in_order(self,previous: "asyncio.Task[None] | None",@@ -3426,27 +3461,39 @@ class ProcessTaskWorkflow(PostHogWorkflow):async def turn_started(self, payload: dict[str, Any]) -> None:if not self._is_agent_design_enabled:return+ if self._early_slack_relay_open:+ # The relay started during provisioning already streams the first turn.+ self._early_slack_relay_open = False+ 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+ await self._start_slack_agent_design_relay(slack_ctx)++ async def _start_slack_agent_design_relay(+ self, slack_ctx: dict[str, Any], setup_title: Optional[str] = None+ ) -> None:relay_workflow_id = f"slack-agent-design-relay-{self.context.run_id}-{workflow.uuid4()}"self._current_slack_relay_workflow_id = relay_workflow_idawait workflow.start_child_workflow(SlackAgentDesignRelayWorkflow.run,- SlackAgentDesignRelayInput(slack_thread_context=slack_ctx, run_id=self.context.run_id),+ SlackAgentDesignRelayInput(+ slack_thread_context=slack_ctx, run_id=self.context.run_id, setup_title=setup_title+ ),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),+ # The first turn's relay also spans provisioning, and a coding turn can run for hours.+ execution_timeout=timedelta(hours=6),)@temporalio.workflow.signalasync def agent_status_update(self, payload: dict[str, Any]) -> None:- """Forward {title, details} step update to the current per-turn child."""+ """Forward a {phase} tool-call update to the current per-turn child."""if not self._is_agent_design_enabled or not self._current_slack_relay_workflow_id:returntry:diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.pyindex a23c93f07d6a..adaa397c658d 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,11 @@ from posthog.models.user import Userfrom posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LENfrom products.slack_app.backend.models import SlackThreadTaskMapping-from products.tasks.backend.logic.services.living_artifacts import SlackFileDeliveryResult+from products.tasks.backend.logic.services.living_artifacts import (+ SlackFileDeliveryResult,+ attach_streamed_slack_files,+ stream_pending_slack_attachments,+)from products.tasks.backend.models import Task, TaskArtifact, TaskRunfrom products.tasks.backend.temporal.slack_relay.activities import (RelaySlackMessageInput,@@ -645,6 +649,122 @@ class TestRelaySlackMessage(TestCase):self.assertEqual(artifact.location["delivery_status"], "pending")mock_post.assert_called_once_with("<@U123> Here's the trend.", with_footer=True, markdown=True)+ @parameterized.expand(+ [("slack_takes_the_blocks", True, "delivered"), ("slack_rejects_the_blocks", False, "pending")]+ )+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")+ @patch(+ "products.tasks.backend.logic.services.living_artifacts.get_delivery_image_url",+ return_value="http://localhost:8010/exporter/export-chart.png?token=abc",+ )+ @override_settings(SITE_URL="http://localhost:8010")+ def test_streamed_reply_carries_chart_and_canvas_cards(+ self, _name, append_ok, expected_status, _mock_delivery_url, mock_integration_for_mapping+ ):+ # The streamed reply is the only delivery path under the agent design, so a chart it+ # drops is lost, and one Slack rejected must stay pending for the next turn.+ artifact, _storage_path = self._create_pending_slack_file_artifact(+ name="Signups by week",+ filename="signups.v1.png",+ content_type="image/png",+ metadata={},+ export_asset_id=321,+ )+ TaskArtifact.objects.for_team(self.team.id).create(+ team=self.team,+ task=self.task,+ task_run=self.task_run,+ created_by=self.user,+ name="Q3 review",+ artifact_type=TaskArtifact.ArtifactType.DOCUMENT,+ adapter=TaskArtifact.Adapter.SLACK_CANVAS,+ status=TaskArtifact.Status.ACTIVE,+ location={"kind": "slack_canvas", "url": "https://app.slack.com/docs/T123/F9", "notice_status": "pending"},+ )+ slack = unittest.mock.MagicMock()+ mock_integration_for_mapping.return_value.client = slack+ mock_integration_for_mapping.return_value.missing_scopes.return_value = set()+ appended: list[list[dict]] = []++ def append_blocks(blocks: list[dict]) -> bool:+ appended.append(blocks)+ return append_ok++ stream_pending_slack_attachments(self.task_run, append_blocks=append_blocks)+ stream_pending_slack_attachments(self.task_run, append_blocks=append_blocks)++ slack.chat_postMessage.assert_not_called()+ block_types = [block["type"] for blocks in appended for block in blocks]+ assert "image" in block_types+ canvas_cards = [block for blocks in appended for block in blocks if "Q3 review" in str(block)]+ assert len(canvas_cards) == (1 if append_ok else 2)+ artifact.refresh_from_db()+ self.assertEqual(artifact.location["delivery_status"], expected_status)++ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")+ @patch(+ "products.tasks.backend.logic.services.living_artifacts.get_delivery_image_url",+ return_value="http://localhost:8010/exporter/export-chart.png?token=abc",+ )+ def test_streamed_reply_retries_charts_one_by_one_when_slack_rejects_the_batch(+ self, _mock_delivery_url, mock_integration_for_mapping+ ):+ # One bad card must not cost the other charts their place in the reply.+ charts = [+ self._create_pending_slack_file_artifact(+ name=f"Chart {index}",+ filename=f"chart-{index}.v1.png",+ content_type="image/png",+ metadata={},+ export_asset_id=320 + index,+ )[0]+ for index in range(2)+ ]+ mock_integration_for_mapping.return_value.client = unittest.mock.MagicMock()+ mock_integration_for_mapping.return_value.missing_scopes.return_value = set()++ def append_blocks(blocks: list[dict]) -> bool:+ return sum(block["type"] == "image" for block in blocks) <= 1++ stream_pending_slack_attachments(self.task_run, append_blocks=append_blocks)++ for chart in charts:+ chart.refresh_from_db()+ self.assertEqual(chart.location["delivery_status"], "delivered")++ @parameterized.expand([("slack_attaches", True, [None]), ("slack_refuses", False, [None, "C123"])])+ @patch(+ "products.tasks.backend.logic.services.living_artifacts._upload_slack_file", return_value=("F1", {"id": "F1"})+ )+ @patch("products.tasks.backend.logic.services.living_artifacts._slack_integration_for_mapping")+ @patch(+ "products.tasks.backend.logic.services.living_artifacts.object_storage.read_bytes",+ return_value=b"week,signups\n2026-09-21,42\n",+ )+ def test_streamed_reply_attaches_its_files_after_the_stream(+ self, _name, attach_ok, expected_upload_channels, _mock_read_bytes, mock_integration_for_mapping, mock_upload+ ):+ # A file shared to the thread lands as its own message under the reply. It must attach to+ # the reply instead, and still reach the thread when Slack refuses the update.+ artifact, _storage_path = self._create_pending_slack_file_artifact(+ name="Weekly signups", filename="signups.v1.csv", content_type="text/csv", metadata={}+ )+ mock_integration_for_mapping.return_value.client = unittest.mock.MagicMock()+ mock_integration_for_mapping.return_value.missing_scopes.return_value = set()+ attached: list[list[str]] = []++ def attach_files(file_ids: list[str]) -> bool:+ attached.append(file_ids)+ return attach_ok++ result = stream_pending_slack_attachments(self.task_run, append_blocks=lambda blocks: True)+ attach_streamed_slack_files(self.task_run, result, attach_files=attach_files)++ assert attached == [["F1"]]+ assert [call.kwargs["channel"] for call in mock_upload.call_args_list] == expected_upload_channels+ artifact.refresh_from_db()+ self.assertEqual(artifact.location["delivery_status"], "delivered")+class TestAppendUnconfirmedAttachmentNotice(unittest.TestCase):def test_appends_notice_for_local_file_delivery_claim_without_artifacts(self):diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 979394e68f52..20522e4de35d 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -7484,6 +7484,7 @@ class TestTaskRunAPI(BaseTaskAPITest):state={"ai_stage": "scout:custom","ai_agent_name": "signals-scout-errors",+ "slack_app_agent_design_enabled": True,"sandbox_connect_token": "connect-token",},)@@ -7494,6 +7495,7 @@ class TestTaskRunAPI(BaseTaskAPITest):state = response.json()["state"]self.assertEqual(state["ai_stage"], "scout:custom")self.assertEqual(state["ai_agent_name"], "signals-scout-errors")+ self.assertTrue(state["slack_app_agent_design_enabled"])self.assertNotIn("sandbox_connect_token", state)def test_list_runs_only_returns_task_runs(self):