Skip to content

fix(core): broadcast to channels on any run on a channel-backed thread#18630

Open
CalebBarnes wants to merge 5 commits into
mainfrom
caleb/channels-self-sufficient
Open

fix(core): broadcast to channels on any run on a channel-backed thread#18630
CalebBarnes wants to merge 5 commits into
mainfrom
caleb/channels-self-sufficient

Conversation

@CalebBarnes

@CalebBarnes CalebBarnes commented Jun 29, 2026

Copy link
Copy Markdown
Member

What & why

Channel broadcast (Slack/Discord/etc.) only worked for agent runs that started from an inbound platform webhook. ChatChannelOutputProcessor read its render context from a requestContext key that AgentChannels sets only on those inbound paths (processChatMessage, approve/decline). Any other run on a channel-backed thread — a heartbeat fire, a Studio run, a custom UI, or user code calling the agent directly — never posted its output back to the channel, because that key was absent.

This makes the output processor self-sufficient: when there's no inbound render context, it reconstructs one from the thread itself.

How

  • ChatChannelOutputProcessor is now bound to its owning AgentChannels at construction.
  • On each run it resolves the render context in two ordered ways, cached once per run on state:
    1. Fast path (unchanged): the inbound CHAT_CHANNEL_RENDER_CONTEXT_KEY on requestContext.
    2. Fallback (new): read the run's threadId from the framework-populated MastraMemory request-context key (via the validated parseMemoryRequestContext accessor), then call agentChannels.buildRenderContextForThread(threadId).
  • buildRenderContextForThread loads the Mastra thread, reads its persisted channel coordinates (channel_platform, channel_externalThreadId), materializes the live Chat SDK Thread handle via chat.thread(externalThreadId), and delegates to the same _buildRenderContext the inbound path uses — so both paths produce an identical render context (single source of truth). Returns null for non-channel threads, which pass through untouched.

Nothing new is persisted; the fallback rebuilds all live handles from the bound AgentChannels instance plus the thread's stored coordinates.

Test plan

  • New ChatChannelOutputProcessor fallback render context suite in output-processor.test.ts:
    • broadcasts on a channel-backed thread with no inbound requestContext key
    • passes through when the thread has no channel metadata
    • passes through when the thread doesn't exist / no threadId
    • inbound requestContext render context still wins (fast path unchanged)
  • pnpm --filter ./packages/core test -- --run src/channels/ — 238 pass (9 files)
  • pnpm --filter ./packages/core check — clean

ELI5

When a run is started from a channel thread without an inbound “webhook” context, the system previously didn’t know where to send the model’s output. Now it can look up the thread and rebuild the channel routing info, so channel output broadcasting keeps working.

Summary

  • Updated ChatChannelOutputProcessor to support a fallback render-context path when requestContext does not contain CHAT_CHANNEL_RENDER_CONTEXT_KEY.
  • Kept the existing “inbound” fast path: if CHAT_CHANNEL_RENDER_CONTEXT_KEY is present, it uses that render context and does not run the fallback.
  • Added fallback reconstruction by:
    • Reading threadId from the framework-stashed MastraMemory request context.
    • Loading the thread from the memory store, validating persisted channel metadata (channel_platform, channel_externalThreadId) with runtime typeof checks, and ensuring the platform adapter/chat SDK prerequisites exist.
    • Recreating the live chat thread handle via chat.thread(externalThreadId) and building the ChatChannelRenderContext via AgentChannels.buildRenderContextForThread(...).
  • Ensured non-channel threads (or missing/invalid thread + metadata) safely pass through unchanged without broadcasting.
  • Wired AgentChannels.getOutputProcessors / ChatChannelOutputProcessor construction so the processor can call agentChannels.buildRenderContextForThread(threadId).
  • Added tests covering the fallback render-context behavior and verifying the inbound fast path remains unchanged.
  • Added a patch release note for @mastra/core describing the channel broadcasting fix.

…context

Channel broadcast (Slack/Discord/etc.) only worked for agent runs that
started from an inbound platform webhook, because ChatChannelOutputProcessor
read its render context from a key that AgentChannels sets only on those
inbound paths. Heartbeat, Studio, and custom-UI/user-code runs on a
channel-backed thread never posted back to the channel.

The output processor now reconstructs the render context from the thread
itself when no inbound context is present: it reads the run's threadId from
the framework-populated MastraMemory request-context key, then asks the bound
AgentChannels to rebuild the render context from the thread's persisted
channel coordinates (channel_platform, channel_externalThreadId) via the same
_buildRenderContext used by the inbound path. Non-channel threads pass through
untouched and the inbound fast path is unchanged.

Co-Authored-By: Mastra Code (anthropic/claude-opus-4-8) <noreply@mastra.ai>
@vercel

vercel Bot commented Jun 29, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
mastra-docs-1.x Ready Ready Preview, Comment Jun 29, 2026 10:07pm
mastra-playground-ui Ready Ready Preview, Comment Jun 29, 2026 10:07pm
1 Skipped Deployment
Project Deployment Actions Updated (UTC)
mastra-studio-preview Ignored Ignored Preview Jun 29, 2026 10:07pm

Request Review

@changeset-bot

changeset-bot Bot commented Jun 29, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 3bf0157

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 22 packages
Name Type
@mastra/core Patch
mastracode Patch
@mastra/mcp-docs-server Patch
@internal/playground Patch
@mastra/client-js Patch
@mastra/opencode Patch
@mastra/longmemeval Patch
mastra Patch
@mastra/deployer-cloud Patch
@mastra/react Patch
@mastra/playground-ui Patch
@mastra/server Patch
@mastra/deployer Patch
create-mastra Patch
@mastra/express Patch
@mastra/fastify Patch
@mastra/hono Patch
@mastra/koa Patch
@mastra/nestjs Patch
@mastra/next Patch
@mastra/tanstack-start Patch
@mastra/temporal Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0e1f16e0-8a3d-4a97-98d9-5a9d0eba1b30

📥 Commits

Reviewing files that changed from the base of the PR and between 550d782 and aed2229.

📒 Files selected for processing (2)
  • packages/core/src/channels/__tests__/output-processor.test.ts
  • packages/core/src/channels/agent-channels.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core/src/channels/tests/output-processor.test.ts
  • packages/core/src/channels/agent-channels.ts

Walkthrough

Adds fallback render-context resolution in ChatChannelOutputProcessor for channel-backed threads, reconstructing context from persisted thread metadata through AgentChannels when the inbound request context marker is missing. Also adds tests and a patch changeset.

Changes

Channel Broadcast Fallback

Layer / File(s) Summary
AgentChannels.buildRenderContextForThread
packages/core/src/channels/agent-channels.ts
Adds buildRenderContextForThread(threadId) that loads the thread from memory, reads channel_platform/channel_externalThreadId metadata, materializes a Chat SDK thread handle, and delegates to _buildRenderContext; returns null when prerequisites are missing. Updates getOutputProcessors to pass this to ChatChannelOutputProcessor.
ChatChannelOutputProcessor fallback resolution
packages/core/src/channels/output-processor.ts
Adds optional AgentChannels constructor param and replaces direct requestContext read with async #resolveRenderContext. Resolution first checks CHAT_CHANNEL_RENDER_CONTEXT_KEY (fast path), then falls back to buildRenderContextForThread via parseMemoryRequestContext, caching both resolved and null results.
Fallback render-context tests
packages/core/src/channels/__tests__/output-processor.test.ts
New test suite with makeFallbackChannels and driveFallback helpers covering: broadcast when thread has channel metadata, no-post when metadata/thread/threadId is absent, and fast-path precedence when CHAT_CHANNEL_RENDER_CONTEXT_KEY is already present.
Patch changeset
.changeset/wide-signs-send.md
Adds a @mastra/core patch changeset documenting the channel broadcasting fix.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • smthomas
  • TheIsrael1
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 clearly matches the PR’s main change: broadcasting output to channels for runs on channel-backed threads.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch caleb/channels-self-sufficient

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

@dane-ai-mastra

dane-ai-mastra Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

PR triage

Linked issue check skipped for core contributor @CalebBarnes.


PR complexity score

Factor Value Score impact
Files changed 4 +8
Lines changed 289 +15
Author merged PRs 230 -20
Test files changed Yes -10
Final score -7

Applied label: complexity: low


Changed test gate

Changed tests failed against the base branch as expected.

Label: tests: green ✅

@coderabbitai coderabbitai Bot left a comment

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.

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 `@packages/core/src/channels/agent-channels.ts`:
- Around line 1208-1210: The thread metadata read in the channel lookup path is
being cast directly to string, which bypasses strict validation and can pass
non-string persisted values into chat.thread(externalThreadId). Update the
metadata handling in the code that reads thread.metadata?.channel_platform and
thread.metadata?.channel_externalThreadId to validate both values are actually
strings before use, and return null when either is missing or invalid instead of
relying on casts.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6aa6935a-3314-4260-9bcb-8b4870b150df

📥 Commits

Reviewing files that changed from the base of the PR and between 56ea17e and 550d782.

📒 Files selected for processing (4)
  • .changeset/wide-signs-send.md
  • packages/core/src/channels/__tests__/output-processor.test.ts
  • packages/core/src/channels/agent-channels.ts
  • packages/core/src/channels/output-processor.ts

Comment thread packages/core/src/channels/agent-channels.ts Outdated
@dane-ai-mastra dane-ai-mastra Bot added the tests: green ✅ Changed tests failed against base as expected label Jun 29, 2026
… render

thread.metadata is persisted unknown; the previous `as string` casts let
truthy non-strings reach chat.thread(externalThreadId). Narrow both values
with a runtime typeof guard and pass through (return null) on invalid
metadata. Addresses CodeRabbit review on #18630.

Co-Authored-By: Mastra Code (anthropic/claude-opus-4-8) <noreply@mastra.ai>
@vercel vercel Bot temporarily deployed to Preview – mastra-docs-1.x June 29, 2026 18:24 Inactive
@dane-ai-mastra dane-ai-mastra Bot added tests: failing ❌ Changed tests passed against base and removed tests: green ✅ Changed tests failed against base as expected labels Jun 29, 2026
@dane-ai-mastra dane-ai-mastra Bot added tests: green ✅ Changed tests failed against base as expected and removed tests: failing ❌ Changed tests passed against base labels Jun 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

complexity: low Low-complexity PR tests: green ✅ Changed tests failed against base as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant