Background Task Streaming

Trust: ★★★☆☆ (0.90) · 0 validations · developer_reference

Published: 2026-05-10 · Source: crawler_authoritative

Tình huống

Mastra SDK reference for streaming background task lifecycle events to monitor running tasks, drive status dashboards, or surface progress in UIs.

Insight

mastra.backgroundTaskManager.stream() returns a ReadableStream of background task lifecycle events. It emits the same chunk types as Agent.streamUntilIdle(): background-task-running, background-task-output, background-task-completed, background-task-failed, background-task-cancelled. On connection, the stream emits a snapshot of all currently running tasks, then forwards live events. The stream stays open until the caller’s AbortSignal fires. Filter options include: agentId (tasks from specific agent), runId (specific agent run), threadId (tasks scoped to a memory thread), resourceId (tasks scoped to a resource), taskId (single task), and abortSignal (closes stream). For one-off lookups, getTask(taskId) and listTasks({status, agentId}) read from storage instead of the pubsub stream, suitable for paginated lists and detail views. Chunk payload shapes are documented at the ChunkType reference.

Hành động

Import or access mastra.backgroundTaskManager and call stream() with optional filter options. Always pass an AbortSignal via abortSignal property for clean disconnection. Example: const stream = bgManager.stream({ abortSignal: controller.signal }); then iterate with for await (const chunk of stream) and switch on chunk.type to handle events. For filtered streams, pass filter properties: stream({ agentId: 'researcher', threadId: 't1', resourceId: 'u1', abortSignal: controller.signal }). For direct state lookups, use mastra.backgroundTaskManager?.getTask(taskId) or mastra.backgroundTaskManager?.listTasks({ status: 'running', agentId: 'researcher' }). Note: mastra.backgroundTaskManager is undefined when background tasks are disabled in Mastra config.

Kết quả

Returns a ReadableStream of background task events. On connect, emits a snapshot of running tasks. Live events stream as tasks update. Chunks contain type, payload.taskId, payload.toolName (for running), payload.result (for completed), payload.error (for failed). For lookups, returns task object or paginated task list with total count.

Điều kiện áp dụng

Requires @mastra/[email protected] or later. Background tasks must be enabled on the Mastra instance — when disabled, mastra.backgroundTaskManager is undefined.


Nội dung gốc (Original)

Background task streaming

Added in: @mastra/[email protected]

mastra.backgroundTaskManager.stream() returns a ReadableStream of background task lifecycle events. Use it to monitor running tasks across the system, for example to drive a status dashboard, surface progress in your own UI, or pipe events into an SSE response.

The stream emits the same chunk types that appear inside Agent.streamUntilIdle() (background-task-running, background-task-output, background-task-completed, background-task-failed, background-task-cancelled). See background task chunks for the full payload shapes.

Note: Background tasks must be enabled on the Mastra instance before backgroundTaskManager is available. When disabled, mastra.backgroundTaskManager is undefined.

Subscribe to all task events

Calling stream() with no filter returns a stream of every task event in the system. On connection, the stream emits a snapshot of all currently running tasks, then forwards live events as they happen.

const bgManager = mastra.backgroundTaskManager
if (!bgManager) throw new Error('Background tasks are not enabled')
 
const controller = new AbortController()
const stream = bgManager.stream({ abortSignal: controller.signal })
 
for await (const chunk of stream) {
  switch (chunk.type) {
    case 'background-task-running':
      console.log('started', chunk.payload.taskId, chunk.payload.toolName)
      break
    case 'background-task-completed':
      console.log('done', chunk.payload.taskId, chunk.payload.result)
      break
    case 'background-task-failed':
      console.error('failed', chunk.payload.taskId, chunk.payload.error)
      break
  }
}

The stream stays open until the caller’s AbortSignal fires. Always pass an abortSignal so you can disconnect cleanly.

Filter the stream

Pass any combination of filter options to narrow the events you receive. Filters apply to both the initial snapshot and the live event subscription.

const stream = bgManager.stream({
  agentId: 'researcher',
  threadId: 't1',
  resourceId: 'u1',
  abortSignal: controller.signal,
})
FilterDescription
agentIdOnly events from tasks dispatched by this agent
runIdOnly events from this specific agent run
threadIdOnly events from tasks scoped to this memory thread
resourceIdOnly events from tasks scoped to this resource
taskIdOnly events for a single task
abortSignalCloses the stream when the signal aborts

Look up task state directly

For one-off lookups instead of a live stream, use getTask and listTasks:

const task = await mastra.backgroundTaskManager?.getTask(taskId)
const { tasks, total } = await mastra.backgroundTaskManager?.listTasks({
  status: 'running',
  agentId: 'researcher',
})

These read from storage rather than the pubsub stream, so they’re suitable for paginated lists and detail views.

Liên kết

Xem thêm: