Module: OllamaChat::SessionManagement
- Included in:
- Chat
- Defined in:
- lib/ollama_chat/session_management.rb
Overview
The OllamaChat::SessionHandling module provides methods for managing chat sessions, including creating, listing, switching, renaming, and deleting sessions.
It integrates closely with the database-backed Session model and ensures that session data is persisted correctly, especially the conversation history.
Instance Attribute Summary collapse
-
#session ⇒ OllamaChat::Database::Models::Session
readonly
The session reader returns the current session object.
Instance Method Summary collapse
-
#change_session(name) ⇒ Object
private
Changes to a different session, saving the current one and loading the new one.
-
#choose_session(session_name, except_id: nil, allow_new: false, exit_app: false) ⇒ OllamaChat::Database::Models::Session?
private
Finds or selects a session based on a name, ID, or pattern.
-
#delete_session ⇒ Object
private
Deletes the current session and prompts the user to pick a new one to switch to.
-
#derive_session_name(length: 128) ⇒ String?
private
Derives a title for the session based on its content.
-
#determine_valid_new_name_for_session(action, default_name: nil) ⇒ String?
private
Interactively prompts the user for a unique session name.
-
#duplicate_session ⇒ Object
private
Duplicates the current session into a new one.
-
#list_sessions ⇒ Object
private
Lists all sessions in a formatted table.
-
#load_links_from_session ⇒ Array<String>
Loads the collection of links from the current session.
-
#new_session ⇒ OllamaChat::Database::Models::Session
private
Creates a new, default session instance.
-
#preferred_session ⇒ OllamaChat::Database::Models::Session
private
Retrieves the preferred session from the database, or creates a new one if none exist.
-
#previous_session ⇒ OllamaChat::Database::Models::Session?
private
Returns the session associated with the stored @previous_session_id, provided the session exists in the database and is not currently locked.
-
#rename_session ⇒ Object
private
Prompts the user to rename the current session interactively.
- #repair_group_uuids ⇒ Object private
- #session_apply ⇒ Object private
-
#session_close ⇒ Object
private
Closes the current session by persisting final messages and releasing the process lock.
-
#set_new_session ⇒ nil
private
Creates and activates a new session with a unique name.
-
#set_previous_session_on_change(previous_session_id) ⇒ Object
private
Records the previous session ID after a session transition.
-
#setup_session ⇒ OllamaChat::Database::Models::Session
private
Sets up the current session based on command-line options or the last used session.
-
#show_session(output: STDOUT) ⇒ Object
private
Displays information about the current session.
-
#store_links_in_session(links) ⇒ Object
Persists a collection of links to the session in the database.
-
#store_messages_in_session ⇒ Object
Persists the current conversation messages to the database.
-
#summarize_session(pretty: false, sentence: false, &block) ⇒ String?
private
Generates a summary of the current session's conversation.
Instance Attribute Details
#session ⇒ OllamaChat::Database::Models::Session (readonly)
The session reader returns the current session object.
57 58 59 |
# File 'lib/ollama_chat/session_management.rb', line 57 def session @session end |
Instance Method Details
#change_session(name) ⇒ Object (private)
Changes to a different session, saving the current one and loading the new one.
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 |
# File 'lib/ollama_chat/session_management.rb', line 428 def change_session(name) name.full? or name = ?? previous_session_id = nil loop do if chosen_session = choose_session(name, allow_new: true) if chosen_session.nil? || chosen_session == session confirm?( prompt: "\nā Same session chosen, Press any key to continue (%s). ", timeout: 3 ) break end session_close previous_session_id = session.id @session = chosen_session if session.lock? .read_conversation_jsonl(session..to_s) if current_collection = session.current_collection.full? and database_collection?(current_collection) then set_current_collection(current_collection) else set_current_collection(:default) end session.current_model.full? { use_model(_1) } set_default_persona_name(session.default_persona_name.full? || :none) set_current_system_prompt(session.current_system_prompt.full? || 'default') session_apply log(:info, "Session changed", data: { session_id: session.id, name: session.name, previous_session_id: }) info_session break else confirm?( prompt: "\nā Session locked: could not switch, Press any key to continue (%s). ", timeout: 3 ) redo end else STDOUT.puts "Cancelled." break end end ensure set_previous_session_on_change(previous_session_id) session.update(working_directory: Dir.pwd) end |
#choose_session(session_name, except_id: nil, allow_new: false, exit_app: false) ⇒ OllamaChat::Database::Models::Session? (private)
Finds or selects a session based on a name, ID, or pattern.
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 |
# File 'lib/ollama_chat/session_management.rb', line 496 def choose_session(session_name, except_id: nil, allow_new: false, exit_app: false) session_name = session_name.to_s session_query = models::Session if except_id session_query = session_query.where(Sequel[:id] !~ except_id) end if session_name =~ /\A\d+\z/ and session = session_query.first(id: session_name) then return session end selector = if session_name =~ /\A\?+(.*)\z/ session_name = nil Regexp.new($1) end if session_name and session = session_query.first(name: session_name) session elsif selector now = Time.now sessions = session_query.order(Sequel.desc(:updated_at)).map { |session| duration = session.age(now:) es = session.estimate_tokens count = session. locked = if pid = session.locked? if pid == $$ " š#{pid} " else " š#{pid} " end else ' ' end display = <<~EOT.strip #{session.name} š#{session.id}#{locked}šØ#{count} š§©#{es.tokens_formatted} ā³#{duration} EOT SearchUI::Wrapper.new( session.name, display: ) } selector and sessions = sessions.select { _1 =~ selector } session_name = if sessions.size == 1 sessions.first.value else allow_new and sessions.unshift(SearchUI::Wrapper.new('[new]', display: '[NEW]')) if exit_app sessions.unshift(SearchUI::Wrapper.new('[quit-app]', display: '[QUIT-APP]')) end sessions.unshift(SearchUI::Wrapper.new('[exit]', display: '[EXIT]')) value = choose_entry(sessions, prompt: 'Select a chat session: %s')&.value if value == '[new]' return new_session elsif value == '[quit-app]' return :quit_app elsif value == '[exit]' return nil end value end if session_name session_query.first(name: session_name) end end end |
#delete_session ⇒ Object (private)
Deletes the current session and prompts the user to pick a new one to switch to.
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
# File 'lib/ollama_chat/session_management.rb', line 263 def delete_session current_session_name, current_session_id = session.name, session.id STDOUT.puts <<~EOT The current session #{current_session_name.inspect} (#{current_session_id}) will be deleted, pick a new session to switch to. EOT confirm?(prompt: "\nā Press any key to continue (%s). ", timeout: 3) chosen = choose_session(??, except_id: current_session_id, allow_new: true, exit_app: true) if chosen == :quit_app STDOUT.puts "Exiting application." exit 0 end if chosen chosen.save confirm?( prompt: "š Delete session #{current_session_name.inspect} (#{current_session_id})? (y/n) ", yes: /\Ay/i ) or return change_session(chosen.id) models::Session.where(id: current_session_id).destroy log(:info, "Session deleted", data: { session_id: current_session_id, name: current_session_name }) STDOUT.puts "Just deleted session #{current_session_name.inspect}!" end end |
#derive_session_name(length: 128) ⇒ String? (private)
Derives a title for the session based on its content.
398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
# File 'lib/ollama_chat/session_management.rb', line 398 def derive_session_name(length: 128) content = ..inject('') do |c, | .content.present? or next c sender_name = sender_name_displayed() c << "%s: %s\n\n" % [ sender_name, .content ] end prompt = prompt(:session_title).to_s % { length:, content: } generate(prompt:).full? do |name| name = name. gsub(/(\A(\s|[^A-Za-z])+|(\s|[^A-Za-z])+\z)/m, ''). gsub(/\s+/, ' ') Kramdown::ANSI::Width.truncate(name, length:) end end |
#determine_valid_new_name_for_session(action, default_name: nil) ⇒ String? (private)
Interactively prompts the user for a unique session name.
This method will keep prompting the user until a name is provided that does not already exist in the database, or until the user cancels.
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
# File 'lib/ollama_chat/session_management.rb', line 151 def determine_valid_new_name_for_session(action, default_name: nil) session_name = nil loop do session_name = ask?( prompt: "ā Enter new session name #{action}, C-c ā cancel: ", prefill: default_name ) if session_name.blank? STDOUT.puts "Cancelled." return nil end if models::Session.where(name: session_name).present? STDOUT.puts "Session named #{bold{session_name}} already exists." else break end end session_name end |
#duplicate_session ⇒ Object (private)
Duplicates the current session into a new one.
This method creates a copy of the current session's attributes and prompts the user for a new name and whether to clear the duplicated session's message history.
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'lib/ollama_chat/session_management.rb', line 207 def duplicate_session name = switch_history(:session_name) do determine_valid_new_name_for_session( 'to create', default_name: session.name ) end or return old_session = session old_session.unlock @session = session.duplicate set_previous_session_on_change(old_session.id) session.update(name:) session.lock? or raise OllamaChat::OllamaChatError, "Could not lock session #{session.id} #{session.errors.full?(:inspect)}" confirm?( prompt: "š Clear messages of duplicated session? (y/n) ", yes: /\Ay/i ) and .clear session.current_model.full? { use_model(_1) } log(:info, "Session duplicated", data: { session_id: session.id, name: session.name, old_session_id: old_session.id }) nil end |
#list_sessions ⇒ Object (private)
Lists all sessions in a formatted table.
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/ollama_chat/session_management.rb', line 94 def list_sessions use_pager do |output| table = Terminal::Table.new table.style = { all_separators: true, border: :unicode_round, } table.headings = %w[ ID NAME SIZE #TOK COUNT UPDATED ].map { |header| bold { header } } now = Time.now models::Session.order(Sequel.desc(:updated_at)).each do |s| name = Kramdown::ANSI::Width.truncate(s.name, length: 32) name = session.id == s.id ? bold { name } : name name = if pid = s.locked? if pid == $$ "#{name} š" else "#{name} š" end else name end es = s.estimate_tokens table << [ s.id.to_s, name, es.bytes_formatted, es.tokens_formatted, s., s.age(now:), ] end table.align_column 0, :right table.align_column 2, :left table.align_column 3, :right table.align_column 4, :right table.align_column 5, :right output.puts table end end |
#load_links_from_session ⇒ Array<String>
Loads the collection of links from the current session.
This method reads the links attribute from the session and
deserializes it from JSONL format.
48 49 50 51 |
# File 'lib/ollama_chat/session_management.rb', line 48 def load_links_from_session input = StringIO.new(session.links) OllamaChat::Utils::JSONJSONLIO.new('as.jsonl').read_io(input:) end |
#new_session ⇒ OllamaChat::Database::Models::Session (private)
Creates a new, default session instance.
65 66 67 |
# File 'lib/ollama_chat/session_management.rb', line 65 def new_session models::Session.with_defaults(self) end |
#preferred_session ⇒ OllamaChat::Database::Models::Session (private)
Retrieves the preferred session from the database, or creates a new one if none exist.
74 75 76 77 78 79 |
# File 'lib/ollama_chat/session_management.rb', line 74 def preferred_session models::Session. where(working_directory: Dir.pwd). order(:updated_at).last || new_session end |
#previous_session ⇒ OllamaChat::Database::Models::Session? (private)
Returns the session associated with the stored @previous_session_id, provided the session exists in the database and is not currently locked.
86 87 88 89 90 91 |
# File 'lib/ollama_chat/session_management.rb', line 86 def previous_session @previous_session_id or return prev = models::Session.where(id: @previous_session_id).first or return prev.locked? and return prev end |
#rename_session ⇒ Object (private)
The use of 1.times do and redo ensures a single-retry
capability for automatic name derivation.
Prompts the user to rename the current session interactively.
This method manages a sophisticated renaming workflow:
- It presents an interactive prompt using
ask?. - If the user provides an empty string, it attempts to automatically
derive a new name using
derive_session_name. - After derivation, it uses
redoto re-prompt the user, now pre-filling the prompt with the newly suggested name. - If the user provides an arbitrary string, the session is renamed.
- If the user interrupts (e.g., via
C-c), the process is cancelled.
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
# File 'lib/ollama_chat/session_management.rb', line 302 def rename_session switch_history(:session_name) do name = nil 1.times do derived = false prefill ||= session.name name = ask?( prompt: "ā Enter the new name for the session (C-u ā auto, C-c ā cancel): ", prefill: ) if name.nil? STDERR.puts "\nInterrupt: Session renaming was cancelled." return end if name.empty? if derived break else derived = true if prefill = derive_session_name.full? redo end end end end if name == session.name STDOUT.puts "Keeping the old name #{name.inspect}." elsif name.present? if exists = models::Session.where(name:).present? STDOUT.puts "Session with name #{name.inspect} already exists." else session.update(name:) log(:info, "Session renamed", data: { session_id: session.id, new_name: name }) STDOUT.puts "Renamed current session to #{name.inspect}." end else STDERR.puts "Could not rename current session!" end rescue Sequel::UniqueConstraintViolation STDERR.puts "Could not rename session to #{name.inspect}, already exists!" end end |
#repair_group_uuids ⇒ Object (private)
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 |
# File 'lib/ollama_chat/session_management.rb', line 561 def repair_group_uuids msgs = . # Direct reference to the internal array msgs.empty? and return # Work backwards to find and repair user-anchored groups i = msgs.size - 1 while i >= 0 # Find the first 'user' message from the back that lacks a group_uuid if msgs[i].role == 'user' && !msgs[i].tool? && msgs[i].group_uuid.nil? anchor_index = i group_uuid = msgs[anchor_index].initialize_group_uuid.group_uuid # 1. Structural Swap: [RuntimeInfo, User] -> [User, RuntimeInfo] if anchor_index > 0 && msgs[anchor_index - 1].tool_name == 'runtime_information' msgs[anchor_index - 1], msgs[anchor_index] = msgs[anchor_index], msgs[anchor_index - 1] i -= 1 anchor_index -= 1 end # 2. Forward Propagation: Assign the same UUID to all following messages # until we hit another user message or the end of the list. ((anchor_index + 1)...msgs.size).each do |k| msgs[k].group_uuid and break msgs[k].group_uuid = group_uuid end # We just fixed a whole block; the next possible anchor is before this one. end i -= 1 end # Handle any orphaned messages that aren't part of a user-led exchange, # e.g. system messages msgs.each(&:initialize_group_uuid) end |
#session_apply ⇒ Object (private)
254 255 256 257 258 259 |
# File 'lib/ollama_chat/session_management.rb', line 254 def session_apply session.update(working_directory: Dir.pwd) init_history repair_group_uuids session end |
#session_close ⇒ Object (private)
Closes the current session by persisting final messages and releasing the process lock. This should be called during application shutdown or when switching sessions to ensure the session is available for future instances.
417 418 419 420 421 422 |
# File 'lib/ollama_chat/session_management.rb', line 417 def session_close links.sync save_history session.unlock end |
#set_new_session ⇒ nil (private)
Creates and activates a new session with a unique name.
This method prompts for a name, initializes a new session record, locks it, and sets up the associated model and options.
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
# File 'lib/ollama_chat/session_management.rb', line 177 def set_new_session name = switch_history(:session_name) do determine_valid_new_name_for_session('to create') end session_close previous_session_id = @session.id @session = new_session set_previous_session_on_change(previous_session_id) session.lock? or raise OllamaChat::OllamaChatError, "Could not lock session #{session.id} #{session.errors.full?(:inspect)}" if name.full? session.update(name:) else session.touch end session_apply .clear session.current_model.full? { use_model(_1) } log(:info, "New session created", data: { session_id: session.id, name: session.name }) nil end |
#set_previous_session_on_change(previous_session_id) ⇒ Object (private)
Records the previous session ID after a session transition.
Stores the ID in @previous_session_id so that #previous_session
can later retrieve it, unless the ID refers to the currently active
session (i.e., the user re-selected the same session).
484 485 486 487 488 |
# File 'lib/ollama_chat/session_management.rb', line 484 def set_previous_session_on_change(previous_session_id) if previous_session_id && previous_session_id != session.id @previous_session_id = previous_session_id end end |
#setup_session ⇒ OllamaChat::Database::Models::Session (private)
Sets up the current session based on command-line options or the last used session.
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
# File 'lib/ollama_chat/session_management.rb', line 236 def setup_session @session = if session_name = @opts[?l] choose_session(session_name, allow_new: true) elsif @opts[?n] new_session else preferred_session end session or abort "No session named #{bold{session_name.inspect}} found." if session.lock? .read_conversation_jsonl(session..to_s) session_apply else raise OllamaChat::OllamaChatError, "Could not lock session #{session.id} #{session.errors.full?(:inspect)}" end end |
#show_session(output: STDOUT) ⇒ Object (private)
Displays information about the current session.
137 138 139 140 141 |
# File 'lib/ollama_chat/session_management.rb', line 137 def show_session(output: STDOUT) es = session.estimate_tokens = session. output.puts "#{bold{session.name}} (#{italic{session.id}}), #{es.bytes_formatted}/#{es.tokens_formatted}, #{} messages" end |
#store_links_in_session(links) ⇒ Object
Persists a collection of links to the session in the database.
This method serializes the links into JSONL format and updates the
links attribute of the current session.
32 33 34 35 36 37 38 39 40 |
# File 'lib/ollama_chat/session_management.rb', line 32 def store_links_in_session(links) output = StringIO.new OllamaChat::Utils::JSONJSONLIO.new('as.jsonl').write_io( output:, collection: links ) session.update(links: output.string) log(:info, "Links stored in session", data: { session_id: session.id, count: links.count }) self end |
#store_messages_in_session ⇒ Object
Persists the current conversation messages to the database.
This method serializes the current message list into JSONL format and
updates the messages attribute of the current session.
12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/ollama_chat/session_management.rb', line 12 def output = StringIO.new .write_conversation_jsonl(output) session.update(messages: output.string) es = session.estimate_tokens log(:info, "Messages stored in session", data: { session_id: session.id, size: es.bytes_formatted, tokens: es.tokens_formatted, messages: session. }) self end |
#summarize_session(pretty: false, sentence: false, &block) ⇒ String? (private)
Generates a summary of the current session's conversation.
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
# File 'lib/ollama_chat/session_management.rb', line 351 def summarize_session(pretty: false, sentence: false, &block) unit = sentence ? 'sentence' : 'paragraph' contents = [] = . = .( label: 'Summarizing message', total: .count, message: , ) .each do || = .content.full? = .thinking.full? unless || - next end sender_name_output = sender_name_displayed() sender_name = sender_name_displayed(, template: false) context = contents * "\n\n" summary = generate( prompt: prompt(:session_summarize).to_s % { sender_name:, unit:, message_content:, message_thinking:, context: } ) content = if pretty '**%s**: %s' % [ sender_name_output, summary ] else '%s: %s' % [ sender_name_output, summary ] end block&.(content) contents << content + end contents.empty? and return if pretty contents.unshift(%{# Summary of session "#{session.name}"}) contents * "\n\n" else contents * ?\n end end |