Module: RobotLab::RailsIntegration::TurboStreamCallbacks

Defined in:
lib/robot_lab/rails_integration/turbo_stream_callbacks.rb

Overview

Stateless utility module that builds callback Procs for Turbo Stream broadcasting.

Safe to require even without turbo-rails installed — checks at call time via ‘defined?(Turbo::StreamsChannel)`.

Examples:

Wire streaming in a background job

stream_name = "robot_lab_thread_#{thread_id}"
on_content = RobotLab::RailsIntegration::TurboStreamCallbacks.build_content_callback(
  stream_name: stream_name
)
robot = MyRobot.build(on_content: on_content)
robot.run(message)

Class Method Summary collapse

Class Method Details

.available?Boolean

Check whether Turbo Streams broadcasting is available at runtime.

Returns:

  • (Boolean)


23
24
25
# File 'lib/robot_lab/rails_integration/turbo_stream_callbacks.rb', line 23

def self.available?
  defined?(Turbo::StreamsChannel) ? true : false
end

.build_content_callback(stream_name:, target: "robot_response") ⇒ Proc

Build a Proc that broadcasts content chunks via Turbo Streams.

The returned Proc receives a chunk object (e.g. RubyLLM::Chunk) and broadcasts ‘chunk.content` as HTML-escaped text via `broadcast_append_to`.

Parameters:

  • stream_name (String)

    the Turbo Stream channel name

  • target (String) (defaults to: "robot_response")

    the DOM target ID (default: “robot_response”)

Returns:

  • (Proc)

    a callback suitable for ‘on_content:`



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/robot_lab/rails_integration/turbo_stream_callbacks.rb', line 36

def self.build_content_callback(stream_name:, target: "robot_response")
  ->(chunk) {
    content = chunk.respond_to?(:content) ? chunk.content : chunk.to_s
    return unless content && TurboStreamCallbacks.available?

    Turbo::StreamsChannel.broadcast_append_to(
      stream_name,
      target: target,
      html: ERB::Util.html_escape(content)
    )
  }
end

.build_tool_call_callback(stream_name:, target: "robot_tools") ⇒ Proc

Build a Proc that broadcasts tool call badges via Turbo Streams.

The returned Proc receives a tool_call object and broadcasts a badge showing the tool name.

Parameters:

  • stream_name (String)

    the Turbo Stream channel name

  • target (String) (defaults to: "robot_tools")

    the DOM target ID (default: “robot_tools”)

Returns:

  • (Proc)

    a callback suitable for ‘on_tool_call:`



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/robot_lab/rails_integration/turbo_stream_callbacks.rb', line 58

def self.build_tool_call_callback(stream_name:, target: "robot_tools")
  ->(tool_call) {
    return unless TurboStreamCallbacks.available?

    name = tool_call.respond_to?(:name) ? tool_call.name : tool_call.to_s
    Turbo::StreamsChannel.broadcast_append_to(
      stream_name,
      target: target,
      html: "<span class=\"tool-badge\">Using: #{ERB::Util.html_escape(name)}</span>"
    )
  }
end