Module: RubyCoded::Chat::State::Messages

Included in:
RubyCoded::Chat::State
Defined in:
lib/ruby_coded/chat/state/messages.rb

Overview

Core message storage: add, append, clear, and snapshot.

Constant Summary collapse

ZERO_TOKEN_USAGE =
{
  input_tokens: 0, output_tokens: 0,
  thinking_tokens: 0, cached_tokens: 0, cache_creation_tokens: 0
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#message_generationObject (readonly)

Returns the value of attribute message_generation.



8
9
10
# File 'lib/ruby_coded/chat/state/messages.rb', line 8

def message_generation
  @message_generation
end

Instance Method Details

#add_message(role, content) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/ruby_coded/chat/state/messages.rb', line 22

def add_message(role, content)
  @mutex.synchronize do
    @messages << build_message(role, content)
    @message_generation += 1
    @dirty = true
  end

  scroll_to_bottom
end

#append_to_last_message(text) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/ruby_coded/chat/state/messages.rb', line 36

def append_to_last_message(text)
  @mutex.synchronize do
    return if @messages.empty?

    @messages.last[:content] << text.to_s
    @message_generation += 1
    @dirty = true
  end
end

#build_message(role, content = "") ⇒ Object



32
33
34
# File 'lib/ruby_coded/chat/state/messages.rb', line 32

def build_message(role, content = "")
  { role: role, content: String.new(content.to_s), timestamp: Time.now, **ZERO_TOKEN_USAGE }
end

#clear_messages!Object



46
47
48
49
50
51
52
53
54
# File 'lib/ruby_coded/chat/state/messages.rb', line 46

def clear_messages!
  @mutex.synchronize do
    @messages.clear
    @token_usage_by_model.clear
    @message_generation += 1
    @dirty = true
  end
  @scroll_offset = 0
end

#init_messagesObject



15
16
17
18
19
20
# File 'lib/ruby_coded/chat/state/messages.rb', line 15

def init_messages
  @message_generation = 0
  @snapshot_cache = nil
  @snapshot_cache_gen = -1
  @token_usage_by_model = Hash.new { |h, k| h[k] = ZERO_TOKEN_USAGE.dup }
end

#messages_snapshotObject



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/ruby_coded/chat/state/messages.rb', line 56

def messages_snapshot
  @mutex.synchronize do
    return @snapshot_cache if @snapshot_cache_gen == @message_generation

    @snapshot_cache = @messages.map do |msg|
      msg.dup.tap { |m| m[:content] = m[:content].dup }
    end
    @snapshot_cache_gen = @message_generation
    @snapshot_cache
  end
end