Skip to content

Open-source design agent: on-brand stills, decks, diagrams, charts and motion graphics from a chat thread, built on Deep Agents.

Slack: keep progress streaming after one refused message, and check the app name before a deploy (#23)

Amal Irgashev9966ac604582
diff --git a/examples/brands/example-studio/tokens.json b/examples/brands/example-studio/tokens.json
index 4237327..245248c 100644
--- a/examples/brands/example-studio/tokens.json
+++ b/examples/brands/example-studio/tokens.json
@@ -61,7 +61,7 @@
"creativeTypography": {
"monoLetterSpacing": "0",
"allowMonoUppercaseTransform": false,
- "bannedDecorativeChars": ["•"],
+ "bannedDecorativeChars": ["•", "·"],
"bannedDecorativeMarkerClasses": ["bullet", "dot", "tick", "marker"],
"bannedGenericMotifClasses": ["dot-grid", "dot-field", "node-cloud", "node-network", "network-lattice", "particle-field"],
"allowedAllCapsTerms": ["API", "CLI", "CSS", "HTML", "JSON", "PDF", "PNG", "SVG", "MP4", "URL", "UI", "UX", "AI", "FAQ", "Q1", "Q2", "Q3", "Q4", "KPI", "ROI", "US", "EU", "UK"],
diff --git a/src/design_agent/config.py b/src/design_agent/config.py
index 8140308..c092dec 100644
--- a/src/design_agent/config.py
+++ b/src/design_agent/config.py
@@ -171,7 +171,12 @@ class Settings(BaseSettings):
"""For models without native tool search: MCP tools a selector may expose per call."""
# MDA Slack appearance
- slack_name: str = Field(default="Design Agent", max_length=35)
+ # MDA's own rule for a Slack app name; checked here so a bad name fails before a deploy does.
+ slack_name: str = Field(
+ default="Design Agent",
+ max_length=35,
+ pattern=r"^[A-Za-z0-9_.](?:[A-Za-z0-9 _.\-]*[A-Za-z0-9_.])?$",
+ )
slack_description: str = Field(
default="On-brand design and motion from a chat thread.", max_length=139
)
diff --git a/src/design_agent/surfaces/slack/stream.py b/src/design_agent/surfaces/slack/stream.py
index 8b48fa3..db7da5b 100644
--- a/src/design_agent/surfaces/slack/stream.py
+++ b/src/design_agent/surfaces/slack/stream.py
@@ -53,8 +53,13 @@ HEARTBEAT_LIFETIME = 3 * 3600.0
MIN_UPDATE_SECONDS = 1.5
#: Refusals no fallback can fix: the stream goes dark instead.
_FINAL = AUTH_ERRORS | {"ratelimited", "channel_not_found", "not_in_channel", "is_archived"}
+#: Refusals about one message's fields (`missing_recipient_team_id`), not the workspace: that
+#: message falls back, and the next one streams again.
+_PER_MESSAGE = ("missing_", "invalid_")
+#: Steps a fallback message shows while it works; the native stream folds the rest away.
+FALLBACK_STEPS = 4
_GLYPHS = {
- "complete": ":white_check_mark:",
+ "complete": ":heavy_check_mark:",
"in_progress": ":hourglass_flowing_sand:",
"error": ":x:",
"pending": ":white_circle:",
@@ -147,6 +152,7 @@ class SlackProgress:
self._ts = ""
self._streaming = False
self._dead = False
+ self._closed = False
self._header = ""
self._lock = asyncio.Lock()
self._last = time.monotonic()
@@ -223,18 +229,14 @@ class SlackProgress:
"task_display_mode": "plan",
"chunks": chunks,
}
- if self._target.user_id and self._target.team_id:
- # Slack refuses a stream in a channel that names no recipient.
- fields |= {
- "recipient_user_id": self._target.user_id,
- "recipient_team_id": self._target.team_id,
- }
+ fields |= await self._recipient()
try:
opened = await self._client.call("chat.startStream", fields)
except SlackError as error:
if error.code in _FINAL:
raise
- _UNSTREAMABLE.add(self._client)
+ if not error.code.startswith(_PER_MESSAGE):
+ _UNSTREAMABLE.add(self._client)
_LOGGER.info(
"[progress] streaming refused (%s); one updated message instead", error.code
)
@@ -257,6 +259,15 @@ class SlackProgress:
self._drawn, self._drawn_at = text + str(blocks), time.monotonic()
self._dead = not self._ts
+ async def _recipient(self) -> dict[str, str]:
+ """Who the stream is shown to. Slack refuses a stream in a channel without both halves,
+ and some events carry no team (a file upload): those take the token's own workspace."""
+ user, team = self._target.user_id, self._target.team_id
+ if user and not team:
+ with contextlib.suppress(SlackError):
+ team = (await self._client.identity()).team_id
+ return {"recipient_user_id": user, "recipient_team_id": team} if user and team else {}
+
async def _append(self, chunks: list[Card]) -> None:
await self._client.call(
"chat.appendStream", {"channel": self._channel, "ts": self._ts, "chunks": chunks}
@@ -283,14 +294,33 @@ class SlackProgress:
self._items.append(("text", str(chunk.get("text") or "")))
def _render(self) -> tuple[str, list[dict[str, object]]]:
- lines = []
+ """The fallback message: the header, narration, and the latest few steps while working.
+
+ Repeats of a step merge into one line ("Read an image ×3"). A closed message keeps only
+ the header and narration, as the native stream folds its steps away.
+ """
+ # (kind, text or title, status, repeats)
+ entries: list[tuple[str, str, str, int]] = []
for kind, value in self._items:
- if kind == "card":
- title, status = self._cards[value]
- lines.append(f"{_GLYPHS.get(status, _GLYPHS['pending'])} {_escape(title)}")
+ if kind == "text":
+ entries.append(("text", value.strip(), "", 0))
+ continue
+ title, status = self._cards[value]
+ if entries and entries[-1][:3] == ("card", title, status):
+ entries[-1] = ("card", title, status, entries[-1][3] + 1)
else:
- lines.append(value.strip())
- body, dropped = "\n".join(lines), 0
+ entries.append(("card", title, status, 1))
+ steps = [i for i, entry in enumerate(entries) if entry[0] == "card"]
+ hidden = set(steps if self._closed else steps[:-FALLBACK_STEPS])
+ earlier = f"… {len(hidden)} earlier step{'s' if len(hidden) > 1 else ''}"
+ lines = [earlier] if hidden and not self._closed else []
+ for i, (kind, text, status, repeats) in enumerate(entries):
+ if kind == "text":
+ lines.append(text)
+ elif i not in hidden:
+ glyph = _GLYPHS.get(status, _GLYPHS["pending"])
+ lines.append(f"{glyph} {_escape(text)}{f' ×{repeats}' if repeats > 1 else ''}")
+ body, dropped = "\n".join(line for line in lines if line), 0
while len(body) > SECTION_LIMIT and len(lines) > 1:
lines.pop(0)
dropped += 1
@@ -402,6 +432,7 @@ class SlackProgress:
await self._client.call("chat.stopStream", where)
else:
self._header = header or self._header
+ self._closed = True
await self._draw(now=True)
if delete and self._ts:
with contextlib.suppress(SlackError):
diff --git a/tests/unit/test_config_and_registry.py b/tests/unit/test_config_and_registry.py
index 2eaec7e..0083266 100644
--- a/tests/unit/test_config_and_registry.py
+++ b/tests/unit/test_config_and_registry.py
@@ -159,3 +159,16 @@ def test_brand_path_falls_back_to_the_sample_brand(tmp_path) -> None: # type: i
(tmp_path / "workspace/brand").mkdir(parents=True)
(tmp_path / "workspace/brand/brand.toml").write_text("name = 'x'\n")
assert settings().resolved_brand_path(tmp_path) == tmp_path / "workspace/brand"
+
+
[email protected]("name", ["Design Agent", "Design Agent Test", "design-agent_2.0", "A"])
+def test_a_slack_name_mda_accepts_is_accepted(name: str) -> None:
+ assert settings(slack_name=name).slack_name == name
+
+
+ "name", ["Design Agent (test)", " Design Agent", "Design Agent-", "Design!"]
+)
+def test_a_slack_name_mda_would_reject_fails_before_the_deploy(name: str) -> None:
+ with pytest.raises(ValueError, match="slack_name"):
+ settings(slack_name=name)
diff --git a/tests/unit/test_progress.py b/tests/unit/test_progress.py
index 2156795..095520e 100644
--- a/tests/unit/test_progress.py
+++ b/tests/unit/test_progress.py
@@ -19,7 +19,15 @@ from design_agent.middleware.progress import HelperProgressMiddleware, ThreadPro
from design_agent.surfaces.slack import stream as stream_module
from design_agent.surfaces.slack.phrasebook import services
from design_agent.surfaces.slack.target import SlackSurface
-from design_agent.testing.fake_slack import BOT, PERSON, TEAM, THREAD_TS, FakeResolver, FakeSlack
+from design_agent.testing.fake_slack import (
+ BOT,
+ PERSON,
+ TEAM,
+ THREAD_TS,
+ FakeResolver,
+ FakeSlack,
+ slack_target,
+)
RUNTIME = SimpleNamespace(config={"configurable": {"thread_id": "t-lead"}})
ANSWERED = {"messages": [HumanMessage("make it blue"), AIMessage(content="Here it is.")]}
@@ -239,14 +247,63 @@ async def test_without_streaming_the_cards_go_in_one_updated_message() -> None:
first, second = list(fake.posted.values())
body = json.dumps(first.blocks)
assert "*Done*" in body
- assert (
- ":white_check_mark: Put a helper on it" in body
- and ":white_check_mark: Generated the image" in body
- )
+ # A closed message folds its steps away, as the native stream does.
+ assert "Put a helper on it" not in body and ":heavy_check_mark:" not in body
assert "in_progress" not in body and ":hourglass" not in body
assert first.text == "Done" and not first.deleted and second.text == "Done"
+async def test_a_message_without_a_team_streams_to_the_tokens_own_workspace() -> None:
+ """Some events carry no team (a file upload), and Slack refuses a channel stream without one:
+ the stream names the token's own workspace instead of falling back."""
+ fake = FakeSlack()
+ surface = SlackSurface(FakeResolver(fake, slack_target(team_id="")))
+ middleware = ThreadProgressMiddleware(surface, servers=services(["paper"]))
+
+ await middleware.abefore_agent({}, RUNTIME)
+ await middleware.awrap_tool_call(call("start_task"), ran)
+ await middleware.aafter_agent(ANSWERED, RUNTIME)
+
+ (opened,) = [fields for method, fields in fake.calls if method == "chat.startStream"]
+ assert (opened["recipient_user_id"], opened["recipient_team_id"]) == (PERSON, TEAM)
+ assert "chat.postMessage" not in fake.methods()
+
+
+async def test_a_refusal_about_one_message_leaves_streaming_on_for_the_next() -> None:
+ """`missing_recipient_team_id` is about that message's fields, not the workspace: one
+ refusal must not turn every later card in the process into the fallback."""
+ fake = FakeSlack(refuse={"chat.startStream": "missing_recipient_team_id"})
+ middleware = lead(fake)
+
+ await middleware.abefore_agent({}, RUNTIME)
+ await middleware.awrap_tool_call(call("start_task"), ran)
+ await middleware.aafter_agent(ANSWERED, RUNTIME)
+ fake.refuse.clear()
+ await middleware.abefore_agent({}, RUNTIME)
+ await middleware.awrap_tool_call(call("generate_image", call_id="c2"), ran)
+ await middleware.aafter_agent(ANSWERED, RUNTIME)
+
+ assert fake.methods().count("chat.startStream") == 2
+ assert fake.methods()[-1] == "chat.stopStream"
+
+
+async def test_the_fallback_merges_repeats_and_shows_only_the_latest_steps() -> None:
+ fake = FakeSlack(refuse={"chat.startStream": "unknown_method"})
+ progress = stream_module.SlackProgress(fake.client(), slack_target(), min_update=0.0)
+ titles = ["Read the brief", *["Read an image"] * 3, "Ran a script", "Shot stills", "Fonts"]
+ for i, title in enumerate(titles):
+ await progress.step(stream_module.card(f"c{i}", title, "complete"))
+
+ (message,) = fake.posted.values()
+ working = json.dumps(message.blocks, ensure_ascii=False)
+ assert "… 1 earlier step" in working and "Read the brief" not in working
+ assert "Read an image ×3" in working and "Fonts" in working
+
+ await progress.close("Done")
+ closed = json.dumps(message.blocks, ensure_ascii=False)
+ assert "*Done*" in closed and "Read an image" not in closed
+
+
async def test_a_run_with_no_slack_thread_says_nothing() -> None:
"""A schedule fire, a CLI ask or a Studio session has no thread to post in, and must not try."""
fake = FakeSlack()