Skip to content

fix(adapters): accept dict StreamChunks in slack/github/google_chat streams#97

Closed
tony-chinchill-ai wants to merge 2 commits into
Chinchill-AI:mainfrom
tony-chinchill-ai:fix/slack-adapter-accepts-dict-chunks
Closed

fix(adapters): accept dict StreamChunks in slack/github/google_chat streams#97
tony-chinchill-ai wants to merge 2 commits into
Chinchill-AI:mainfrom
tony-chinchill-ai:fix/slack-adapter-accepts-dict-chunks

Conversation

@tony-chinchill-ai
Copy link
Copy Markdown
Contributor

@tony-chinchill-ai tony-chinchill-ai commented May 21, 2026

Summary

The SDK's _from_full_stream (thread.py:1218-1226) is documented and implemented to forward dict-shaped StreamChunks — {"type": "markdown_text" | "task_update" | "plan_update", ...} — to downstream adapters unchanged. The Teams adapter honors that contract correctly (adapters/teams/adapter.py:927), but slack, github, and google_chat only check hasattr(chunk, \"type\"), which is always False for plain dicts in Python.

Concrete failure mode in Slack: a dict-shaped chunk would miss the dispatch loop's hasattr check, fall to send_structured_chunk, raise AttributeError(\"'dict' object has no attribute 'type'\") on the first field access, get caught by a broad except that flips structured_chunks_supported = False, and log a warning that points the operator at a Slack OAuth scope issue — even though scopes have nothing to do with the failure. Every subsequent chunk in the stream is silently downgraded to text-only.

This PR aligns slack/github/google_chat with the dict-handling contract that thread.py already promises.

Changes

  • adapters/slack/adapter.py

    • Main dispatch loop: added an isinstance(chunk, dict) and chunk.get(\"type\") == \"markdown_text\" branch that routes through the markdown renderer, mirroring the existing dataclass branch.
    • send_structured_chunk: replaced the hardcoded chunk.type / hasattr(chunk, ...) accesses with a small _read(name) helper that handles both dict and dataclass shapes through one code path. Also added an early-return + log when type is missing entirely, instead of letting that case fall into the fallback warning.
    • Fallback warning message: rewritten to enumerate the actual possible causes (missing assistant_view / assistant:write scope OR malformed chunk payload OR transient Slack API error) instead of pinning the blame on the app manifest.
  • adapters/github/adapter.py & adapters/google_chat/adapter.py

    • Added the same isinstance(chunk, dict) and chunk.get(\"type\") == \"markdown_text\" branch in each adapter's stream accumulator.
  • tests/test_slack_api.py

    • Added two regression tests in TestStream that exercise the two distinct adapter branches affected (renderer dispatch + structured chunk forwarding). Both fail when the dict branches are reverted, and their assert messages name what broke.

Why this is the right shape for the fix

  • It's a port-correctness change, not a new contract. In the original TypeScript chat-sdk the dict-vs-dataclass distinction doesn't exist — JS object property access works for both interface-typed objects and plain objects. Python's hasattr check is strictly object-only, so the Python port has to add the dict branch explicitly to preserve the same behavior.
  • It mirrors the dict branches that already exist elsewhere in the same SDK (thread.py:640, thread.py:661, thread.py:1218, adapters/teams/adapter.py:927). It does not introduce a new mode or option.

Test plan

  • uv run pytest tests/test_slack_api.py::TestStream — 8/8 pass (6 existing + 2 new).
  • uv run pytest — full SDK suite: 3584 passed, 11 skipped, no regressions.
  • uv run ruff check src/ tests/ — clean.
  • Mental trace: each new assertion fails when the corresponding dict branch is reverted in the source.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Enhanced streaming support across GitHub, Google Chat, and Slack adapters to handle message chunks in multiple formats, improving compatibility and data handling flexibility
    • Slack adapter now provides more informative error messages when streaming encounters failures, including diagnostic hints about potential causes

Review Change Stack

…treams

`_from_full_stream` (thread.py:1218-1226) explicitly forwards
`{"type": "markdown_text" | "task_update" | "plan_update", ...}` dict
chunks unchanged, so downstream adapters MUST accept both the dataclass
and dict shapes of `StreamChunk`. The Teams adapter already does
(adapter.py:927), but slack/github/google_chat only check
`hasattr(chunk, "type")` — which is False for dicts in Python — so dict
chunks were silently dropped or, worse, raised AttributeError inside
Slack's `send_structured_chunk` and downgraded the entire stream to
text-only with a misleading warning about missing assistant_view scopes.

Changes:
- slack/adapter.py: route dict markdown_text through the renderer; add
  a `_read(name)` helper in `send_structured_chunk` so dict and dataclass
  field access share one code path; tighten the fallback warning to
  enumerate the actual possible causes (missing scope OR malformed
  chunk OR transient Slack API error) instead of pointing solely at
  the manifest.
- github/adapter.py: accept dict markdown_text chunks in the accumulator.
- google_chat/adapter.py: same.
- test_slack_api.py: two regression tests in TestStream covering the two
  distinct adapter branches affected (renderer dispatch + structured
  chunk forwarding). Both fail when the dict branches are reverted.

This brings the Python adapters in line with the SDK's own internal
contract — adapters do not enforce a dataclass-only shape for chunks
that `_from_full_stream` is documented and tested to pass through as
dicts.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 21, 2026

Warning

Review limit reached

@patrick-chinchill, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 25 minutes and 10 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 92f2d08e-f0ca-473b-a6e7-0c6b1c7afd54

📥 Commits

Reviewing files that changed from the base of the PR and between 4b76134 and 38614ee.

📒 Files selected for processing (4)
  • src/chat_sdk/adapters/github/adapter.py
  • src/chat_sdk/adapters/google_chat/adapter.py
  • src/chat_sdk/adapters/slack/adapter.py
  • tests/test_slack_api.py
📝 Walkthrough

Walkthrough

The PR extends all three SDK adapters to accept streamed chunks as dictionaries with type and optional text fields. GitHub and Google Chat receive straightforward dict-form markdown text support. Slack's implementation refactors structured chunk handling to use a field reader supporting both dataclass and dict representations, adds detailed failure diagnostics, and extends the stream loop to recognize dict-shaped markdown chunks.

Changes

Dict-shaped chunk support across adapters

Layer / File(s) Summary
GitHub adapter dict chunk support
src/chat_sdk/adapters/github/adapter.py
GitHubAdapter.stream recognizes {"type": "markdown_text"} dictionary chunks and appends their text field to accumulated markdown, consistent with existing string and attribute-based handling.
Google Chat adapter dict chunk support
src/chat_sdk/adapters/google_chat/adapter.py
GoogleChatAdapter.stream recognizes {"type": "markdown_text"} dictionary chunks and appends their text field, extending support beyond string and attribute-based chunks.
Slack structured chunk refactoring
src/chat_sdk/adapters/slack/adapter.py
send_structured_chunk signature now accepts StreamChunk | dict[str, Any]. A field reader helper extracts type and optional attributes (id, title, status, output, text) uniformly from both representations. Missing type fields trigger an early return with a warning. Structured-chunk append failures now log specific likely causes (missing Slack scopes, malformed payload, transient API errors).
Slack stream loop dict markdown handling
src/chat_sdk/adapters/slack/adapter.py
SlackAdapter.stream detects dict-shaped chunks where type == "markdown_text", extracts their text field, and routes it through the incremental markdown flush path, mirroring dataclass chunk behavior.
Slack dict chunk streaming tests
tests/test_slack_api.py
Two new test cases validate dict-shaped chunk handling: one confirms dict markdown_text chunks produce rendered markdown output, another confirms dict task_update chunks are forwarded as structured chunks with type preservation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Chunks now shape-shift—dict or class, they're all the same!
GitHub, Google Chat, and Slack now speak the universal frame.
From markdown to tasks, the adapters align,
A flexible feast where dictionaries and objects intertwine. 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: adding dict StreamChunk support across three adapters (Slack, GitHub, Google Chat).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/test_slack_api.py`:
- Around line 967-1051: The failing CI is due to formatting errors in the test
file affecting the two tests test_stream_accepts_dict_markdown_text_chunks and
test_stream_accepts_dict_task_update_chunks; fix by running the project's
formatter (ruff) over the tests to apply the required style rules (e.g., run the
equivalent of `ruff format` on the test sources) and re-commit the updated
formatting so ruff format --check passes. Ensure the signatures and
async/generator yields in those tests remain unchanged while only fixing
whitespace/line-break/indentation per ruff.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 5006498d-029d-4bd5-8142-ec2f6bc6ba7e

📥 Commits

Reviewing files that changed from the base of the PR and between 08c42fa and 4b76134.

📒 Files selected for processing (4)
  • src/chat_sdk/adapters/github/adapter.py
  • src/chat_sdk/adapters/google_chat/adapter.py
  • src/chat_sdk/adapters/slack/adapter.py
  • tests/test_slack_api.py

Comment thread tests/test_slack_api.py
Comment on lines +967 to +1051
@pytest.mark.asyncio
async def test_stream_accepts_dict_markdown_text_chunks(self):
"""Dict-shaped markdown_text chunks must flow into the renderer the
same as the dataclass form — `_from_full_stream` in thread.py
forwards them unchanged, so adapters must accept both shapes.
"""
adapter, client, _ = await _init_adapter()

mock_streamer = MagicMock()
mock_streamer.append = AsyncMock()
mock_streamer.stop = AsyncMock(return_value={"message": {"ts": "666.666"}})
client.chat_stream = AsyncMock(return_value=mock_streamer)

async def chunk_gen() -> AsyncIterator[Any]:
yield {"type": "markdown_text", "text": "Hello "}
yield {"type": "markdown_text", "text": "world"}

result = await adapter.stream(
"slack:C123:1234567890.000000",
chunk_gen(),
StreamOptions(recipient_user_id="U1", recipient_team_id="T1"),
)

assert result.id == "666.666"
appended_text = "".join(
call.kwargs.get("markdown_text", "")
for call in mock_streamer.append.call_args_list
)
assert "Hello world" in appended_text, (
"dict markdown_text chunks were not routed through the "
f"markdown renderer; streamer.append received {appended_text!r}"
)

@pytest.mark.asyncio
async def test_stream_accepts_dict_task_update_chunks(self):
"""Dict-shaped task_update chunks must be forwarded as structured
chunks to `streamer.append(chunks=...)`, matching the dataclass form.
"""
adapter, client, _ = await _init_adapter()

mock_streamer = MagicMock()
mock_streamer.append = AsyncMock()
mock_streamer.stop = AsyncMock(return_value={"message": {"ts": "555.555"}})
client.chat_stream = AsyncMock(return_value=mock_streamer)

async def chunk_gen() -> AsyncIterator[Any]:
yield "Starting "
yield {
"type": "task_update",
"id": "task1",
"title": "Search",
"status": "in_progress",
}
yield {
"type": "task_update",
"id": "task1",
"title": "Search",
"status": "complete",
"output": "Found 5",
}

result = await adapter.stream(
"slack:C123:1234567890.000000",
chunk_gen(),
StreamOptions(recipient_user_id="U1", recipient_team_id="T1"),
)

assert result.id == "555.555"
structured_calls = [
call for call in mock_streamer.append.call_args_list
if "chunks" in call.kwargs
]
assert structured_calls, (
"dict-shaped task_update chunks were not forwarded as "
"structured chunks to streamer.append(chunks=...)"
)
all_forwarded_chunks = [
chunk
for call in structured_calls
for chunk in call.kwargs["chunks"]
]
assert any(c.get("type") == "task_update" for c in all_forwarded_chunks), (
"no forwarded chunk had type=task_update; got: "
f"{all_forwarded_chunks!r}"
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix formatting to pass CI.

The pipeline indicates ruff format --check failed for this file. Run uv run ruff format tests/ to apply the required formatting.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_slack_api.py` around lines 967 - 1051, The failing CI is due to
formatting errors in the test file affecting the two tests
test_stream_accepts_dict_markdown_text_chunks and
test_stream_accepts_dict_task_update_chunks; fix by running the project's
formatter (ruff) over the tests to apply the required style rules (e.g., run the
equivalent of `ruff format` on the test sources) and re-commit the updated
formatting so ruff format --check passes. Ensure the signatures and
async/generator yields in those tests remain unchanged while only fixing
whitespace/line-break/indentation per ruff.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request updates the GitHub, Google Chat, and Slack adapters to support stream chunks provided as dictionaries, ensuring compatibility with normalized stream data. The changes include updating the stream methods to handle dictionary-shaped chunks and refactoring the Slack adapter's send_structured_chunk function with a unified _read helper for attribute and key access. Additionally, new unit tests were added to verify the Slack adapter's handling of these dictionary chunks. Feedback was provided regarding the use of truthiness checks for text_value and chunk_type in the Slack adapter, which could lead to valid empty strings being incorrectly ignored; it is recommended to use explicit None or type checks instead.

# `{type: "markdown_text", ...}` items unchanged, so adapters
# must handle them the same as the dataclass form.
text_value = chunk.get("text")
if isinstance(text_value, str) and text_value:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The truthiness check and text_value will silently ignore empty string chunks (""). While an empty string is a no-op for the markdown renderer, it is still a valid value. Per the general rules, use is not None (or rely on the isinstance(text_value, str) check which already excludes None) to maintain consistency with the dataclass branch and other adapters in this PR.

Suggested change
if isinstance(text_value, str) and text_value:
if isinstance(text_value, str):
References
  1. When checking for optional values that can be falsy but valid (e.g., 0, empty string, empty list), use is not None instead of a truthiness check to avoid silently ignoring them.

return getattr(chunk, name, None)

chunk_type = _read("type")
if not chunk_type:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using a truthiness check if not chunk_type: on an optional value violates the general rule to use is not None. If chunk_type is an empty string, it will be silently ignored and the function will return early without processing the chunk.

Suggested change
if not chunk_type:
if chunk_type is None:
References
  1. When checking for optional values that can be falsy but valid (e.g., 0, empty string, empty list), use is not None instead of a truthiness check to avoid silently ignoring them.

Copy link
Copy Markdown
Collaborator

Replaced by #105 (could not push the ruff format fix to the fork branch from an automated session). All original commits preserved in #105's branch history; @tony-chinchill-ai credited.


Generated by Claude Code

patrick-chinchill added a commit that referenced this pull request May 28, 2026
…treams (#105)

Aligns slack/github/google_chat stream loops with the dict-shaped StreamChunk contract that thread.py:1218 and the Teams adapter already honor.

Port-correctness fix: Python's hasattr check is object-only, so dict-shaped chunks forwarded by _from_full_stream silently fell through to send_structured_chunk, raised AttributeError on the first field access, got caught by a broad except, and downgraded the rest of the stream to text-only with a misleading "check your Slack scopes" warning.

- Slack: dispatch loop gets isinstance(chunk, dict) and chunk.get("type") == "markdown_text" branch; send_structured_chunk rewritten to use a _read() helper that handles both dict and dataclass shapes; fallback warning rewritten to name the actual possible causes
- GitHub & Google Chat: same isinstance(chunk, dict) branch in each stream accumulator
- 2 new regression tests in TestStream covering both dispatch branches

Original authorship: @tony-chinchill-ai. Replaces #97.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants