diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 7e550d0..50da1a6 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,6 +1,7 @@ { "recommendations": [ "ms-vscode.cpptools", + "ms-vscode.cpp-devtools", "ms-vscode.cpptools-extension-pack", "ms-vscode.cpptools-themes", "ms-vscode.cmake-tools", @@ -9,6 +10,11 @@ "xaver.clang-format", "foxundermoon.shell-format", "timonwong.shellcheck", - "redhat.vscode-yaml" + "redhat.vscode-yaml", + "jasonnutter.vscode-codeowners", + "github.vscode-github-actions", + "ms-python.python", + "ms-python.vscode-pylance", + "ms-python.vscode-python-envs" ] -} +} \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 9050090..25ae094 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.20) -project(cpp-workspace VERSION 0.2.1 LANGUAGES CXX) +project(cpp-workspace VERSION 0.3.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -14,9 +14,14 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) add_executable(cpp-workspace-app src/main.cpp src/interface/progress_spinner.cpp - src/interface/user-interface.cpp + src/interface/user_interface.cpp src/ollama/ollama_client.cpp - src/utils/text-utils.cpp + src/storage/qdrant_client.cpp + src/utils/curl_utils.cpp + src/utils/text_utils.cpp + src/utils/system_utils.cpp + src/utils/embedding_utils.cpp + src/utils/http_utils.hpp ) target_include_directories(cpp-workspace-app @@ -24,6 +29,7 @@ target_include_directories(cpp-workspace-app ${CMAKE_SOURCE_DIR}/src ${CMAKE_SOURCE_DIR}/src/interface ${CMAKE_SOURCE_DIR}/src/ollama + ${CMAKE_SOURCE_DIR}/src/storage ${CMAKE_SOURCE_DIR}/src/utils ) diff --git a/README.md b/README.md index 099a0ce..acfa8f6 100644 --- a/README.md +++ b/README.md @@ -52,11 +52,10 @@ In order to run your own copy of the project one must fulfill the following requ šŸ† **Visual Studio Code** - recommended for all operating systems Suggested extensions: -- C/C++ Extension Pack (Microsoft) -- CMake Tools (Microsoft) -- CMake (twxs) +- [C/C++ Extension Pack](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools-extension-pack) +- [CMake Tools](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cmake-tools) -šŸ†— **Visual Studio** - for Windows development +See [`.vscode/extensions`](.vscode/extensions.json) for the complete list. ### Core dependencies @@ -120,6 +119,26 @@ cz c ## FAQ +### Commands + +1. Install + +```bash +bash ./tools/shell/install.sh --help +``` + +2. Build + +```bash +bash ./tools/shell/build.sh --help +``` + +3. Format + +```bash +bash ./tools/shell/format.sh +``` + ### Manual build ```bash diff --git a/src/interface/progress_spinner.cpp b/src/interface/progress_spinner.cpp index c69cf79..5f74cf2 100644 --- a/src/interface/progress_spinner.cpp +++ b/src/interface/progress_spinner.cpp @@ -5,24 +5,51 @@ #include #include +/** + * Constructs a ProgressSpinner in manual mode. + * + * Creates a spinner that displays to stdout without UI integration. + * Must be manually started with start(). + */ ProgressSpinner::ProgressSpinner() : ui(nullptr), active(false) { } +/** + * Constructs a ProgressSpinner with optional UI integration. + * + * @param user_interface Pointer to a UserInterface instance for rendering, + * or nullptr for manual mode (CLI spinner). + * @param activate If true and user_interface is not nullptr, automatically + * starts the spinner. Default: false. + * + * @note The UserInterface pointer must remain valid for the lifetime of + * the ProgressSpinner object. + */ ProgressSpinner::ProgressSpinner(UserInterface* user_interface, bool activate) : ui(user_interface), active(false) { if (activate && ui != nullptr) { start(); } } +/** + * Destructs the ProgressSpinner, ensuring the spinner thread is stopped. + * + * Calls stop() to cleanly shut down the spinner thread. + */ ProgressSpinner::~ProgressSpinner() { stop(); } /** - * Implementation details: - * - In manual mode, renders spinner characters and progress directly to stdout. - * - In interactive mode, delegates animation and progress updates to the UserInterface. - * - Resets completion_shown flag and initializes progress to 0%. + * Starts the spinner animation on a background thread. + * + * - If no UserInterface is set, displays an animated spinner (| / - \) to stdout. + * - If a UserInterface is set, delegates animation to the UI via start_spinner() + * and advance_spinner_frame(). + * + * Sets progress to 0% and resets the completion_shown flag. + * + * @note Safe to call multiple times; subsequent calls are no-ops if already running. */ void ProgressSpinner::start() { this->completion_shown = false; @@ -39,7 +66,7 @@ void ProgressSpinner::start() { std::cout << "\r" << spinner_chars[i++ % 4] << " Loading..." << std::flush; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - printf("\n"); + UserInterface::print_message_noninteractive("\n"); }); } else { this->ui->start_spinner(); @@ -54,8 +81,12 @@ void ProgressSpinner::start() { } /** - * Sets active flag to false, waits for the spinner thread to finish, - * and notifies the UserInterface to stop its spinner if present. + * Stops the spinner animation and cleans up the background thread. + * + * Waits for the spinner thread to finish (via join()) and notifies the + * UserInterface to stop its spinner, if set. + * + * @note Safe to call multiple times or if start() was never called. */ void ProgressSpinner::stop() { this->active = false; @@ -68,10 +99,17 @@ void ProgressSpinner::stop() { } /** - * Implementation notes: - * - In manual mode, displays progress percentage if total is known, otherwise shows spinner. - * - In interactive mode, updates both spinner frame and progress bar in the UI. - * - Returns 0 to allow CURL to continue operation. + * Internal progress callback for CURL integration. + * + * Processes download progress information and updates the spinner or UI accordingly. + * Displays a progress bar (ā–°ā–°ā–°ā–±) with percentage if total size is known. + * + * @param dltotal Total bytes to download (0 if unknown). + * @param dlnow Bytes downloaded so far. + * + * @return 0 to continue the CURL operation, non-zero to abort. + * + * @note This method is called frequently by CURL; keep it lightweight. */ int ProgressSpinner::progress_callback_impl(curl_off_t dltotal, curl_off_t dlnow) { if (this->ui == nullptr || !this->ui->is_running()) { @@ -98,10 +136,23 @@ int ProgressSpinner::progress_callback_impl(curl_off_t dltotal, curl_off_t dlnow } /** - * Static callback adapter that casts the clientp void pointer to a ProgressSpinner - * instance and delegates to the progress_callback_impl() method. + * Static CURL callback adapter for progress tracking. + * + * This static method serves as the callback function for CURL's + * CURLOPT_XFERINFOFUNCTION option. It casts the clientp parameter to a + * ProgressSpinner instance and delegates to progress_callback_impl(). + * + * @param clientp Opaque pointer to the ProgressSpinner instance (passed via + * CURLOPT_XFERINFODATA). + * @param dltotal Total bytes to download (0 if unknown). + * @param dlnow Bytes downloaded so far. + * @param ultotal Total bytes to upload (unused). + * @param ulnow Bytes uploaded so far (unused). + * + * @return 0 to continue the CURL operation, 1 to abort if clientp is nullptr. * - * @return 0 to continue the operation, 1 if clientp is nullptr. + * @note CURL calls this frequently; ensure your clientp points to a valid + * ProgressSpinner instance. */ int ProgressSpinner::progress_callback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { diff --git a/src/interface/progress_spinner.hpp b/src/interface/progress_spinner.hpp index 333993d..4fb2c42 100644 --- a/src/interface/progress_spinner.hpp +++ b/src/interface/progress_spinner.hpp @@ -1,55 +1,19 @@ #pragma once -#include "user-interface.hpp" +#include "user_interface.hpp" #include #include #include #include /** - * Displays a progress indicator for asynchronous operations, with optional UI integration. + * Displays and manages an animated progress spinner with optional download tracking. * - * ProgressSpinner supports two modes: - * - **Manual mode**: Displays an animated spinner to stdout for CLI applications. - * - **Interactive mode**: Integrates with a UserInterface instance for display within - * a graphical or TUI framework. - * - * The spinner runs on a separate thread and updates independently of the main operation. - * Designed to work seamlessly with CURL operations via the static progress_callback method. - * - * @note Thread-safe: Uses std::atomic for synchronization without locks. - * - * @example Manual mode (CLI spinner): - * @code - * ProgressSpinner spinner; - * spinner.start(); - * curl_easy_perform(curl_handle); - * spinner.stop(); - * @endcode - * - * @example Interactive mode (with UserInterface): - * @code - * UserInterface ui; - * ProgressSpinner spinner(&ui, true); // auto-starts - * // UI displays progress and spinner animation - * curl_easy_perform(curl_handle); - * spinner.stop(); - * @endcode - * - * @example CURL integration with progress tracking: - * @code - * ProgressSpinner spinner(&ui); - * spinner.start(); - * - * CURL* curl = curl_easy_init(); - * curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, ProgressSpinner::progress_callback); - * curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &spinner); - * curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); - * curl_easy_perform(curl); - * - * spinner.stop(); - * curl_easy_cleanup(curl); - * @endcode + * Runs a spinner animation in a dedicated background thread, providing visual feedback + * during network operations. Supports two modes: UI-driven (displays via UserInterface) + * and manual mode (spinner_thread active but output deferred). Integrates with CURL + * progress callbacks to track download progress. Thread-safe via atomic flags for + * state management (active, completion_shown). */ class ProgressSpinner { private: @@ -74,91 +38,18 @@ class ProgressSpinner { std::atomic completion_shown{false}; public: - /** - * Constructs a ProgressSpinner in manual mode. - * - * Creates a spinner that displays to stdout without UI integration. - * Must be manually started with start(). - */ ProgressSpinner(); - /** - * Constructs a ProgressSpinner with optional UI integration. - * - * @param user_interface Pointer to a UserInterface instance for rendering, - * or nullptr for manual mode (CLI spinner). - * @param activate If true and user_interface is not nullptr, automatically - * starts the spinner. Default: false. - * - * @note The UserInterface pointer must remain valid for the lifetime of - * the ProgressSpinner object. - */ explicit ProgressSpinner(UserInterface* user_interface, bool activate = false); - /** - * Destructs the ProgressSpinner, ensuring the spinner thread is stopped. - * - * Calls stop() to cleanly shut down the spinner thread. - */ ~ProgressSpinner(); - /** - * Starts the spinner animation on a background thread. - * - * - If no UserInterface is set, displays an animated spinner (| / - \) to stdout. - * - If a UserInterface is set, delegates animation to the UI via start_spinner() - * and advance_spinner_frame(). - * - * Sets progress to 0% and resets the completion_shown flag. - * - * @note Safe to call multiple times; subsequent calls are no-ops if already running. - */ void start(); - /** - * Stops the spinner animation and cleans up the background thread. - * - * Waits for the spinner thread to finish (via join()) and notifies the - * UserInterface to stop its spinner, if set. - * - * @note Safe to call multiple times or if start() was never called. - */ void stop(); - /** - * Internal progress callback for CURL integration. - * - * Processes download progress information and updates the spinner or UI accordingly. - * Displays a progress bar (ā–°ā–°ā–°ā–±) with percentage if total size is known. - * - * @param dltotal Total bytes to download (0 if unknown). - * @param dlnow Bytes downloaded so far. - * - * @return 0 to continue the CURL operation, non-zero to abort. - * - * @note This method is called frequently by CURL; keep it lightweight. - */ int progress_callback_impl(curl_off_t dltotal, curl_off_t dlnow); - /** - * Static CURL callback adapter for progress tracking. - * - * This static method serves as the callback function for CURL's - * CURLOPT_XFERINFOFUNCTION option. It casts the clientp parameter to a - * ProgressSpinner instance and delegates to progress_callback_impl(). - * - * @param clientp Opaque pointer to the ProgressSpinner instance (passed via - * CURLOPT_XFERINFODATA). - * @param dltotal Total bytes to download (0 if unknown). - * @param dlnow Bytes downloaded so far. - * @param ultotal Total bytes to upload (unused). - * @param ulnow Bytes uploaded so far (unused). - * - * @return 0 to continue the CURL operation, 1 to abort if clientp is nullptr. - * - * @note CURL calls this frequently; ensure your clientp points to a valid - * ProgressSpinner instance. - */ static int progress_callback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow); }; diff --git a/src/interface/user-interface.cpp b/src/interface/user-interface.cpp deleted file mode 100644 index 4d5fba6..0000000 --- a/src/interface/user-interface.cpp +++ /dev/null @@ -1,577 +0,0 @@ -#include "user-interface.hpp" -#include -#include -#include -#include -#include -#include -#include -#include - -UserInterface* UserInterface::instance = nullptr; - -enum ColorPair { - DEFAULT_PAIR = 1, - HIGHLIGHT_PAIR = 2, - SUCCESS_PAIR = 3, - WARNING_PAIR = 4, - ERROR_PAIR = 5, - INFO_PAIR = 6, - MUTED_PAIR = 7, - ACCENT_PAIR = 8, - FOCUS_PAIR = 9 -}; - -void UserInterface::init_dark_theme(void) { - start_color(); - use_default_colors(); - - // Purpose | Foreground | Background - init_pair(DEFAULT_PAIR, COLOR_WHITE, -1); - init_pair(HIGHLIGHT_PAIR, COLOR_BLACK, COLOR_WHITE); - init_pair(SUCCESS_PAIR, COLOR_GREEN, -1); - init_pair(WARNING_PAIR, COLOR_YELLOW, -1); - init_pair(ERROR_PAIR, COLOR_RED, -1); - init_pair(INFO_PAIR, COLOR_CYAN, -1); - init_pair(ACCENT_PAIR, COLOR_MAGENTA, -1); - init_pair(FOCUS_PAIR, COLOR_WHITE, COLOR_BLUE); -} - -void UserInterface::init_light_theme(void) { - start_color(); - use_default_colors(); - - // Purpose | Foreground | Background - init_pair(DEFAULT_PAIR, COLOR_BLACK, COLOR_WHITE); - init_pair(HIGHLIGHT_PAIR, COLOR_WHITE, COLOR_BLACK); - init_pair(SUCCESS_PAIR, COLOR_GREEN, COLOR_WHITE); - init_pair(WARNING_PAIR, COLOR_YELLOW, COLOR_WHITE); - init_pair(ERROR_PAIR, COLOR_RED, COLOR_WHITE); - init_pair(INFO_PAIR, COLOR_BLUE, COLOR_WHITE); - init_pair(ACCENT_PAIR, COLOR_MAGENTA, COLOR_WHITE); - init_pair(FOCUS_PAIR, COLOR_BLACK, COLOR_CYAN); -} - -void UserInterface::init_ncurses(void) { - // Set up locale for UTF-8 support. - setlocale(LC_ALL, ""); - - // Set TERMINFO to system database if Conan ncurses can't find it. - if (!std::getenv("TERMINFO")) { - setenv("TERMINFO", "/usr/share/terminfo", 0); - } - - // Initialize ncurses. - const WINDOW* w = initscr(); - if (!w) { - const char* term = getenv("TERM"); - std::cerr << "Failed to initialize ncurses with TERM=" << (term ? term : "unset") << "\n"; - std::exit(EXIT_FAILURE); - } - - this->update_layout(); - - // Setup terminal. - if (cbreak() == ERR || noecho() == ERR) { - endwin(); - std::cerr << "Terminal setup failed\n"; - std::exit(EXIT_FAILURE); - } - - // Enable function keys and arrow keys. - if (keypad(stdscr, TRUE) == ERR) { - std::cerr << "Warning: keypad() not supported\n"; - } - - // Block on input (getch waits for input). - nodelay(stdscr, FALSE); - - // Cursor hiding (may not be supported). - if (curs_set(0) == ERR) { - std::cerr << "Warning: cursor control not supported on this terminal\n"; - } - - if (has_colors()) { - printf("DEBUG: Checking theme - use_dark_theme = %s\n", this->use_dark_theme ? "true" : "false"); - if (this->use_dark_theme == true) { - this->init_dark_theme(); - } else { - this->init_light_theme(); - } - bkgd(COLOR_PAIR(DEFAULT_PAIR)); - } - - signal(SIGWINCH, UserInterface::handle_resize); - signal(SIGINT, UserInterface::handle_interrupt); -} - -void UserInterface::cleanup_ncurses(void) { - endwin(); -} - -void UserInterface::draw_ui(void) { - clear(); - - int max_y; - int max_x; - getmaxyx(stdscr, max_y, max_x); - - int i; - - // Top border - mvprintw(0, 0, "ā•”"); - for (i = 1; i < max_x - 1; i += 1) { - mvprintw(0, i, "═"); - } - mvprintw(0, max_x - 1, "ā•—"); - - // Side borders - for (i = 1; i < max_y - 1; i += 1) { - mvprintw(i, 0, "ā•‘"); - mvprintw(i, max_x - 1, "ā•‘"); - } - - // Bottom border - mvprintw(max_y - 1, 0, "ā•š"); - for (i = 1; i < max_x - 1; i += 1) { - mvprintw(max_y - 1, i, "═"); - } - mvprintw(max_y - 1, max_x - 1, "ā•"); - - refresh(); -} - -void UserInterface::update_layout() { - int max_y, max_x; - getmaxyx(stdscr, max_y, max_x); - - layout.status_y = max_y - 1; - layout.input_y = max_y - 3; - layout.input_x = 2; - layout.spinner_y = max_y - 2; - layout.spinner_x = 2; - layout.output_y = 1; - layout.output_height = layout.input_y - layout.output_y - 1; -} - -void UserInterface::clear_input_area() { - int max_y, max_x; - getmaxyx(stdscr, max_y, max_x); - - mvhline(layout.input_y, 1, ' ', max_x - 2); - mvhline(layout.input_y + 1, 1, ' ', max_x - 2); -} - -void UserInterface::draw_input_area() { - this->clear_input_area(); - if (this->is_spinner_active()) { - return; - } - - mvprintw(layout.input_y, layout.input_x, "ā³ Type your prompt (q/Q to quit): "); - - // Draw the actual input buffer that user typed - mvprintw(layout.input_y, layout.input_x + 37, "%s", input_buffer.c_str()); -} - -UserInterface::UserInterface() : resize_flag(0), running(0), input_cursor_x(0), layout({}), use_dark_theme(true) { - printf("DEBUG: use_dark_theme = %s\n", this->use_dark_theme ? "true" : "false"); - UserInterface::instance = this; -} - -UserInterface::UserInterface(bool dark_theme) - : resize_flag(0), running(0), input_cursor_x(0), layout({}), use_dark_theme(dark_theme) { - printf("DEBUG: use_dark_theme = %s\n", this->use_dark_theme ? "true" : "false"); - UserInterface::instance = this; -} - -UserInterface::~UserInterface() { - this->cleanup_ncurses(); - UserInterface::instance = nullptr; -} - -bool UserInterface::is_running() { - return this->running == 1; -} - -void UserInterface::handle_resize(int sig) { - if (UserInterface::instance) { - UserInterface::instance->resize_flag = 1; - } - - signal(SIGWINCH, UserInterface::handle_resize); -} - -void UserInterface::handle_interrupt(int sig) { - if (UserInterface::instance) { - UserInterface::instance->running = 0; - endwin(); - exit(EXIT_SUCCESS); - } -} - -void UserInterface::run(void) { - this->init_ncurses(); - - this->draw_ui(); - - this->running = 1; - - this->start_render_thread(); -} - -void UserInterface::end_session(int exit_code) { - this->print("šŸ The session has ended."); - - napms(1000); - - this->stop_render_thread(); - - this->cleanup_ncurses(); - - exit(exit_code); -} - -void UserInterface::print_args(const std::string& model, const std::string& prompt, bool stream, bool interactive, - bool dark_theme) { - std::string buffer; - buffer += "šŸ›ˆ model = " + model + "\n"; - buffer += "šŸ›ˆ prompt = " + prompt + "\n"; - buffer += "šŸ›ˆ stream = " + std::string(stream ? "true" : "false") + "\n"; - buffer += "šŸ›ˆ interactive = " + std::string(interactive ? "true" : "false") + "\n"; - buffer += "šŸ›ˆ dark_theme = " + std::string(dark_theme ? "true" : "false") + "\n"; - - this->print(buffer, UserInterface::MESSAGE_TYPE_NORMAL); -} - -void UserInterface::print_args_noninteractive(const std::string& model, const std::string& prompt, bool stream, - bool interactive, bool dark_theme) { - printf("\n"); - printf("šŸ›ˆ model = %s\n", model.c_str()); - printf("šŸ›ˆ prompt = %s\n", prompt.c_str()); - printf("šŸ›ˆ stream = %s\n", stream ? "true" : "false"); - printf("šŸ›ˆ interactive = %s\n", interactive ? "true" : "false"); - printf("šŸ›ˆ dark_theme = %s\n", dark_theme ? "true" : "false"); - printf("\n"); -} - -void UserInterface::print_model_list(const std::vector& models) { - std::string buffer; - buffer += "\nšŸ›ˆ Select a model from the list below:\n"; - for (size_t i = 0; i < models.size(); i += 1) { - buffer += "[" + std::to_string(i) + "] " + models[i] + "\n"; - } - - this->print(buffer, UserInterface::MESSAGE_TYPE_NORMAL); -} - -void UserInterface::print_model_list_noninteractive(const std::vector& models) { - printf("\nšŸ›ˆ Select a model from the list below:\n"); - for (size_t i = 0; i < models.size(); i += 1) { - printf("[%zu] %s\n", i, models[i].c_str()); - } -} - -void UserInterface::select_model(const std::vector& models, std::string* model) { - int index{}; - - if (models.size() == 0) { - this->print_error("There are no available models to select from.\n"); - exit(1); - } - - this->request_redraw(); - - this->input_buffer.clear(); - int ch; - - while ((ch = getch()) != '\n') { - if (ch == KEY_BACKSPACE || ch == 127) { - if (!input_buffer.empty()) { - input_buffer.pop_back(); - input_cursor_x--; - this->request_redraw(); - } - } else if (ch != ERR && isprint(ch)) { - if (input_buffer.length() < COLS - 40) { // Leave room for prompt - input_buffer.push_back(ch); - input_cursor_x++; - this->request_redraw(); - } - } - } - - if (this->input_buffer == "q" || this->input_buffer == "Q") { - this->end_session(EXIT_SUCCESS); - } - - index = stoi(this->input_buffer); - - if (index < 0 || index >= models.size()) { - std::string message = std::format("Model index %d does not exist.\n", index); - this->print_error(message); - this->select_model(models, model); - } else { - *model = models[index]; - } -} - -void UserInterface::select_model_noninteractive(const std::vector& models, std::string* model) { - int index{}; - int read_result{}; - - if (models.size() == 0) { - fprintf(stderr, "There are no available models to select from.\n"); - exit(1); - } - - while (read_result != 1 || index < 0 || index >= models.size()) { - if (index < 0 || index >= models.size()) { - fprintf(stderr, "Model index %d does not exist.\n", index); - } - printf("Model index: "); - read_result = scanf("%d", &index); - } - - *model = models[index]; -} - -bool UserInterface::next_prompt(std::string* prompt) { - bool done = false; - - this->request_redraw(); - - this->input_buffer.clear(); - int ch; - - while ((ch = getch()) != '\n') { - if (ch == KEY_BACKSPACE || ch == 127) { - if (!input_buffer.empty()) { - input_buffer.pop_back(); - input_cursor_x--; - this->request_redraw(); - } - } else if (ch != ERR && isprint(ch)) { - if (input_buffer.length() < COLS - 40) { // Leave room for prompt - input_buffer.push_back(ch); - input_cursor_x++; - this->request_redraw(); - } - } - } - - *prompt = this->input_buffer; - - if (*prompt == "q" || *prompt == "Q") { - done = true; - } - - return done; -} - -bool UserInterface::next_prompt_noninteractive(std::string* prompt) { - bool done = false; - printf("ā³ Type your prompt (q/Q to quit): "); - if (!std::getline(std::cin, *prompt, '\n')) { - fprintf(stderr, "Error reading user input.\n"); - exit(1); - } - - if (*prompt == "q" || *prompt == "Q") { - done = true; - } - - return done; -} - -/** - * Prints a message using ncurses. - */ -void UserInterface::print(const std::string& text, int type) { - { - std::lock_guard lock(this->ui_mutex); - output_buffer.push_back({text, type}); - } - this->request_redraw(); -} - -/** - * Prints an error message using ncurses. - */ -void UserInterface::print_error(const std::string& text) { - this->print(text, UserInterface::MESSAGE_TYPE_ERROR); -} - -/** - * Prints a success message using ncurses. - */ -void UserInterface::print_success(const std::string& text) { - this->print(text, UserInterface::MESSAGE_TYPE_SUCCESS); -} - -/** - * Prints a normal message using ncurses. - */ -void UserInterface::print_message(const std::string& text) { - this->print(text, UserInterface::MESSAGE_TYPE_NORMAL); -} - -/** - * Prints a message using `std::cout`. - */ -void UserInterface::print_message_noninteractive(const std::string& text) { - std::cout << text; - std::cout.flush(); -} - -void UserInterface::draw_output_area() { - // Clear the output area - for (int i = 0; i < layout.output_height; i++) { - mvhline(layout.output_y + i, 1, ' ', COLS - 2); - } - - int current_line = layout.input_y - 2; // Start from bottom - int max_content_width = COLS - 4; - - // Iterate backwards through buffer (newest first) - for (auto it = output_buffer.rbegin(); it != output_buffer.rend(); ++it) { - if (current_line <= layout.output_y) { - break; - } - - const auto& [text, type] = *it; - std::istringstream stream(text); - std::string line; - std::vector display_lines; - - // Process each logical line from the message - while (std::getline(stream, line)) { - // Wrap long lines at word boundaries - auto wrapped = TextUtils::wrap_text(line, max_content_width); - display_lines.insert(display_lines.end(), wrapped.begin(), wrapped.end()); - } - - // Render from bottom to top (reverse order) - for (auto line_it = display_lines.rbegin(); line_it != display_lines.rend(); ++line_it) { - if (current_line <= layout.output_y) break; - - if (type == UserInterface::MESSAGE_TYPE_ERROR) { - wattron(stdscr, COLOR_PAIR(ERROR_PAIR) | A_BOLD); - mvprintw(current_line, 2, "āŒ %s", line_it->c_str()); - wattroff(stdscr, COLOR_PAIR(ERROR_PAIR) | A_BOLD); - } else if (type == UserInterface::MESSAGE_TYPE_SUCCESS) { - wattron(stdscr, A_BOLD); - mvprintw(current_line, 2, "āœ… %s", line_it->c_str()); - wattroff(stdscr, A_BOLD); - } else { - mvprintw(current_line, 2, "%s", line_it->c_str()); - } - - current_line--; - } - } - - refresh(); -} - -void UserInterface::start_render_thread(void) { - this->thread_running = true; - this->render_thread = std::thread(&UserInterface::render_loop, this); -} - -void UserInterface::stop_render_thread(void) { - this->thread_running = false; - this->cv_redraw.notify_one(); - if (this->render_thread.joinable()) { - this->render_thread.join(); - } -} - -void UserInterface::request_redraw(void) { - this->should_redraw = true; - this->cv_redraw.notify_one(); -} - -void UserInterface::render_loop(void) { - while (this->thread_running) { - std::unique_lock lock(this->ui_mutex); - - // Wait for redraw request or timeout (100ms) - this->cv_redraw.wait_for(lock, std::chrono::milliseconds(1500), [this] { return this->should_redraw.load(); }); - - // Handle resize (under lock) - if (this->resize_flag) { - this->resize_flag = 0; - endwin(); - refresh(); - this->update_layout(); - - // Recalculate cursor position after resize - input_cursor_x = layout.input_x + 37 + input_buffer.length(); - this->should_redraw = true; // Force redraw after resize - } - - // Redraw UI (all ncurses calls under lock) - if (this->should_redraw) { - this->draw_ui(); - this->draw_output_area(); - this->draw_input_area(); - this->draw_spinner(); - - refresh(); - this->should_redraw = false; - } - - lock.unlock(); - } -} - -void UserInterface::start_spinner() { - std::lock_guard lock(ui_mutex); - this->spinner_active = true; - this->spinner_frame = 0; - this->should_redraw = true; -} - -void UserInterface::stop_spinner() { - std::lock_guard lock(ui_mutex); - this->spinner_active = false; - this->spinner_frame = 0; - this->should_redraw = true; -} - -void UserInterface::advance_spinner_frame() { - if (this->is_spinner_active()) { - this->spinner_frame = (spinner_frame + 1) % 4; - this->should_redraw = true; - } -} - -bool UserInterface::is_spinner_active() const { - return spinner_active.load(); -} - -void UserInterface::set_progress(int percent) { - this->progress_percent = std::clamp(percent, 0, 100); - this->should_redraw = true; -} - -void UserInterface::draw_spinner() { - if (!this->is_spinner_active()) { - return; - } - - const char spinner_chars[] = {'|', '/', '-', '\\'}; - int frame = this->spinner_frame.load(); - int progress = this->progress_percent.load(); - - attron(COLOR_PAIR(DEFAULT_PAIR)); - - if (progress > 0) { - mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Progress: %d%%", spinner_chars[frame], progress); - } else { - mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Loading...", spinner_chars[frame]); - } - - attroff(COLOR_PAIR(DEFAULT_PAIR)); -} diff --git a/src/interface/user-interface.hpp b/src/interface/user-interface.hpp deleted file mode 100644 index 6469421..0000000 --- a/src/interface/user-interface.hpp +++ /dev/null @@ -1,350 +0,0 @@ -#pragma once - -#include "utils/text-utils.hpp" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -struct Layout { - int input_y; // Row for input prompt. - int input_x; // Column for input start. - int output_y; // Row where output begins. - int output_height; - int status_y; // Row for status messages. - int spinner_y; // Row for the progress spinner. - int spinner_x; // Column for the progress spinner. -}; - -class UserInterface { - private: - // Message configuration constants. - static constexpr int MESSAGE_TYPE_NORMAL = 0; - static constexpr int MESSAGE_TYPE_ERROR = 1; - static constexpr int MESSAGE_TYPE_SUCCESS = 2; - - // User Interface state. - volatile sig_atomic_t resize_flag; - volatile sig_atomic_t running; - static UserInterface* instance; - - // Layout state. - struct Layout layout; - - // Input buffer state. - std::string input_buffer; - int input_cursor_x; - - // Output buffer state. - std::vector> output_buffer; - - // Renderer state. - std::thread render_thread; - std::mutex ui_mutex; - std::condition_variable cv_redraw; - std::atomic should_redraw{true}; - std::atomic thread_running{false}; - - // Spinner state. - std::atomic spinner_active{false}; - std::atomic spinner_frame{0}; - std::atomic progress_percent{0}; - - // Color theme configuration. - bool use_dark_theme = true; - - // Initialization methods. - - /** - * Initializes the color pairs for the UI dark theme. - */ - void init_dark_theme(void); - - /** - * Initializes the color pairs for the UI light theme. - */ - void init_light_theme(void); - - /** - * Initializes the ncurses library for terminal UI rendering. - * Sets up color pairs, configures terminal mode (raw mode, no echo), - * hides cursor, enables keypad input, and initializes screen dimensions. - */ - void init_ncurses(void); - - /** - * Cleans up and restores the terminal to its original state. - * Disables raw mode, re-enables echo, restores cursor visibility, - * and deallocates ncurses resources. - */ - void cleanup_ncurses(void); - - // Renderer methods. - - /** - * Spawns a dedicated background thread that runs render_loop(). - * The thread handles periodic UI redraws without blocking input handling. - */ - void start_render_thread(void); - - /** - * Signals the render thread to stop and waits for it to join. - * Sets thread_running to false and notifies the condition variable. - */ - void stop_render_thread(void); - - /** - * Main loop executed by the render thread. - * Waits for redraw requests (via condition_variable), then redraws - * the entire UI if the terminal wasn't resized. Exits when thread_running is false. - * Thread-safe: uses ui_mutex to protect rendering operations. - */ - void render_loop(void); - - // Layout manpulation methods. - - /** - * Redraws the entire user interface. - * Clears the screen and calls draw_input_area(), draw_output_area(), - * draw_spinner(), and refreshes the display. - */ - void draw_ui(void); - - /** - * Draws the progress spinner at the designated position. - * Displays an animated character based on the current spinner frame. - */ - void draw_spinner(void); - - /** - * Recalculates layout positions and dimensions based on current terminal size. - * Called when SIGWINCH (terminal resize) is detected. - * Updates the Layout struct fields (input_y, output_y, status_y, etc.). - */ - void update_layout(); - - // Input area methods. - - /** - * Renders the input prompt and user input buffer. - * Displays the prompt text and the current contents of input_buffer, - * with cursor positioned at input_cursor_x. - */ - void draw_input_area(); - - /** - * Clears the input area of the screen. - * Used before redrawing to prevent display artifacts. - */ - void clear_input_area(); - - // Output area methods. - - /** - * Renders all messages in the output buffer. - * Iterates through output_buffer and draws each message with its - * associated type (normal, error, success) which may affect coloring. - */ - void draw_output_area(); - - public: - /** - * Constructor: Initializes the UserInterface object. - * Sets up initial state, layout, and registers signal handlers - * but does NOT start the render thread (that happens in run()). - */ - UserInterface(); - /** - * Constructor: Initializes the UserInterface object. - * Sets up initial state, layout, and registers signal handlers - * but does NOT start the render thread (that happens in run()). - * @param dark_theme Whether to active the dark theme. - */ - explicit UserInterface(bool dark_theme); - - /** - * Destructor: Cleans up resources. - * Stops the render thread and restores the terminal via cleanup_ncurses(). - */ - ~UserInterface(); - - /** - * Returns whether the UI is currently running. - * Reads the volatile 'running' flag in a thread-safe manner. - * @return true if the UI is running, false otherwise. - */ - bool is_running(); - - /** - * Static signal handler for SIGWINCH (terminal resize). - * Sets resize_flag to 1 to trigger layout recalculation. - * Must be static to comply with C signal API. - * @param sig The signal number (unused, present for signal handler compliance). - */ - static void handle_resize(int sig); - - /** - * Static signal handler for SIGINT (Ctrl+C). - * Sets running to 0 to gracefully shut down the UI. - * Must be static to comply with C signal API. - * @param sig The signal number (unused, present for signal handler compliance). - */ - static void handle_interrupt(int sig); - - /** - * Starts the interactive user interface. - * Registers signal handlers, initializes ncurses, starts the render thread, - * and enters the main input loop. Blocks until running becomes false. - */ - void run(void); - - /** - * Ends the current session and exits. - * Stops the render thread, cleans up ncurses, and terminates the application. - * @param exit_code The program exit code to return to the operating system. - */ - void end_session(int exit_code); - - /** - * Displays configuration/arguments at the start of the session (interactive mode). - * Outputs model, prompt, and mode information to the UI. - * @param model The model being used. - * @param prompt The initial prompt text. - * @param stream Whether streaming is enabled. - * @param interactive Whether interactive mode is enabled. - * @param dark_theme Whether to active the dark theme. - */ - void print_args(const std::string& model, const std::string& prompt, bool stream, bool interactive, - bool dark_theme); - - /** - * Static version of print_args() for non-interactive mode. - * Outputs arguments to stdout instead of the UI. - * @param model The model being used. - * @param prompt The initial prompt text. - * @param stream Whether streaming is enabled. - * @param interactive Whether interactive mode is enabled. - * @param dark_theme Whether to active the dark theme. - */ - static void print_args_noninteractive(const std::string& model, const std::string& prompt, bool stream, - bool interactive, bool dark_theme); - - /** - * Prints available models and their corresponding indexes for selection. - * @param models The list of available local models. - */ - void print_model_list(const std::vector& models); - - /** - * Static version of print_model_list() for non-interactive mode. - * @param models The list of available local models. - */ - static void print_model_list_noninteractive(const std::vector& models); - - /** - * Prompts for user input to select a model form the list of available local models. - * @param models The list of available local models. - * @param model Pointer to a std::string to receive the user input. - */ - void select_model(const std::vector& models, std::string* model); - - /** - * Static version of the select_model() for non-interactive mode. - * @param models The list of available local models. - * @param model Pointer to a std::string to receive the user input. - */ - static void select_model_noninteractive(const std::vector& models, std::string* model); - - /** - * Waits for and retrieves the next user input prompt (interactive mode). - * Blocks until the user presses Enter and a prompt is available. - * @param prompt Pointer to a std::string to receive the user input. - * @return true if a prompt was successfully read, false if the session ended. - */ - bool next_prompt(std::string* prompt); - - /** - * Static version of next_prompt() for non-interactive mode. - * Reads from stdin instead of the interactive UI. - * @param prompt Pointer to a std::string to receive the user input. - * @return true if input was read, false on EOF or error. - */ - static bool next_prompt_noninteractive(std::string* prompt); - - /** - * Prints a message to the output area with a specified type. - * Appends the message to output_buffer and triggers a redraw. - * @param text The message to display. - * @param type The message type (MESSAGE_TYPE_NORMAL, MESSAGE_TYPE_ERROR, or - * MESSAGE_TYPE_SUCCESS). Defaults to MESSAGE_TYPE_NORMAL if not specified. - */ - void print(const std::string& text, int type = UserInterface::MESSAGE_TYPE_NORMAL); - - /** - * Convenience method: prints an error message (MESSAGE_TYPE_ERROR). - * @param text The error message to display. - */ - void print_error(const std::string& text); - - /** - * Convenience method: prints a success message (MESSAGE_TYPE_SUCCESS). - * @param text The success message to display. - */ - void print_success(const std::string& text); - - /** - * Convenience method: prints a normal message (MESSAGE_TYPE_NORMAL). - * @param text The message to display. - */ - void print_message(const std::string& text); - - void print_message_noninteractive(const std::string& text); - - /** - * Requests that the UI be redrawn on the next render cycle. - * Sets should_redraw to true and notifies the render thread via condition variable. - * Safe to call from multiple threads. - */ - void request_redraw(void); - - // Spinner methods. - - /** - * Activates the progress spinner animation. - * Sets spinner_active to true. - */ - void start_spinner(void); - - /** - * Deactivates the progress spinner. - * Sets spinner_active to false. - */ - void stop_spinner(void); - - /** - * Advances the spinner animation to the next frame. - * Increments spinner_frame (wraps around after reaching max). - * Called periodically during render_loop(). - */ - void advance_spinner_frame(void); - - /** - * Returns the current state of the spinner. - * @return true if the spinner is currently active, false otherwise. - */ - bool is_spinner_active(void) const; - - /** - * Sets the progress percentage displayed with the spinner. - * @param percent Progress as a percentage (0–100). - */ - void set_progress(int percent); - - // Grant friend access to ProgressSpinner - friend class ProgressSpinner; -}; diff --git a/src/interface/user_interface.cpp b/src/interface/user_interface.cpp new file mode 100644 index 0000000..b1837c7 --- /dev/null +++ b/src/interface/user_interface.cpp @@ -0,0 +1,1219 @@ +#include "user_interface.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +UserInterface* UserInterface::instance = nullptr; + +/** + * Semantic color pair identifiers for terminal UI rendering. + * + * Defines named color pair constants for consistent theming across the application. + * Each constant maps to an ncurses color pair ID, enabling semantic color assignment + * for different UI contexts and message types. Values range from 1 to 9, matching + * ncurses color pair initialization indices. + * + * - DEFAULT_PAIR: Standard text color for neutral content + * - HIGHLIGHT_PAIR: Emphasis color for selected or important items + * - SUCCESS_PAIR: Color for successful operations or positive messages + * - WARNING_PAIR: Color for cautionary messages or non-critical issues + * - ERROR_PAIR: Color for error messages and critical failures + * - INFO_PAIR: Color for informational messages + * - MUTED_PAIR: Subdued color for de-emphasized content + * - ACCENT_PAIR: Decorative color for visual variety and UI separation + * - FOCUS_PAIR: Color for focused or active UI elements + */ +enum ColorPair { + DEFAULT_PAIR = 1, + HIGHLIGHT_PAIR = 2, + SUCCESS_PAIR = 3, + WARNING_PAIR = 4, + ERROR_PAIR = 5, + INFO_PAIR = 6, + MUTED_PAIR = 7, + ACCENT_PAIR = 8, + FOCUS_PAIR = 9 +}; + +/** + * Initializes ncurses color pairs with a dark theme color scheme. + * + * Enables ncurses color support via start_color(), allows the terminal's default + * background color to be used via use_default_colors(), and defines all ColorPair + * color pair constants with semantic foreground/background combinations. + * + * Most pairs use -1 as background, preserving the terminal's default background + * color. HIGHLIGHT_PAIR uses black text on white background for strong contrast, + * and FOCUS_PAIR uses white text on blue background for focused element visibility. + * + * This method should be called early during UserInterface initialization, before + * any colored text is rendered to the terminal. + */ +void UserInterface::init_dark_theme(void) { + start_color(); + use_default_colors(); + + // Purpose | Foreground | Background + init_pair(DEFAULT_PAIR, COLOR_WHITE, -1); + init_pair(HIGHLIGHT_PAIR, COLOR_BLACK, COLOR_WHITE); + init_pair(SUCCESS_PAIR, COLOR_GREEN, -1); + init_pair(WARNING_PAIR, COLOR_YELLOW, -1); + init_pair(ERROR_PAIR, COLOR_RED, -1); + init_pair(INFO_PAIR, COLOR_CYAN, -1); + init_pair(ACCENT_PAIR, COLOR_MAGENTA, -1); + init_pair(FOCUS_PAIR, COLOR_WHITE, COLOR_BLUE); +} + +/** + * Initializes ncurses color pairs with a light theme color scheme. + * + * Enables ncurses color support via start_color(), allows the terminal's default + * background color to be used via use_default_colors(), and defines all ColorPair + * color pair constants with semantic foreground/background combinations optimized + * for light terminal backgrounds. + * + * Unlike the dark theme, most pairs use white backgrounds for contrast against + * darker text. DEFAULT_PAIR uses black text on white for standard content, and + * HIGHLIGHT_PAIR inverts to white text on black for strong emphasis. FOCUS_PAIR + * uses black text on cyan background for focused element visibility. + * + * This method should be called early during UserInterface initialization, before + * any colored text is rendered to the terminal. Select init_dark_theme() or + * init_light_theme() based on the user's terminal background preference. + */ +void UserInterface::init_light_theme(void) { + start_color(); + use_default_colors(); + + // Purpose | Foreground | Background + init_pair(DEFAULT_PAIR, COLOR_BLACK, COLOR_WHITE); + init_pair(HIGHLIGHT_PAIR, COLOR_WHITE, COLOR_BLACK); + init_pair(SUCCESS_PAIR, COLOR_GREEN, COLOR_WHITE); + init_pair(WARNING_PAIR, COLOR_YELLOW, COLOR_WHITE); + init_pair(ERROR_PAIR, COLOR_RED, COLOR_WHITE); + init_pair(INFO_PAIR, COLOR_BLUE, COLOR_WHITE); + init_pair(ACCENT_PAIR, COLOR_MAGENTA, COLOR_WHITE); + init_pair(FOCUS_PAIR, COLOR_BLACK, COLOR_CYAN); +} + +/** + * Initializes the ncurses terminal UI with locale support, terminal configuration, color theming, and signal handling. + * + * Sets the locale to UTF-8 for character encoding support and establishes TERMINFO fallback to the system + * terminfo database if not already set (handles Conan ncurses builds). Initializes ncurses with initscr(), + * terminating with error diagnostics on failure. Updates window layout via update_layout(). + * + * Configures terminal I/O: enables cbreak mode (immediate input) and disables echo. Attempts to enable + * function key and arrow key support via keypad(); non-fatal warning if unsupported. Sets input blocking + * mode (getch() waits for user input). Attempts to hide the cursor; non-fatal warning if unsupported. + * + * If the terminal supports colors, initializes color pairs by calling init_dark_theme() or init_light_theme() + * based on the use_dark_theme flag, and sets the terminal background to DEFAULT_PAIR. Registers SIGWINCH + * signal handler for terminal window resize detection and SIGINT handler for interrupt cleanup. + * + * Terminates the program on critical failures (initscr failure or terminal setup failure). + * Non-critical feature failures (keypad, cursor hiding) produce warnings but do not halt initialization. + */ +void UserInterface::init_ncurses(void) { + // Set up locale for UTF-8 support. + setlocale(LC_ALL, ""); + + // Set TERMINFO to system database if Conan ncurses can't find it. + if (!std::getenv("TERMINFO")) { + setenv("TERMINFO", "/usr/share/terminfo", 0); + } + + // Initialize ncurses. + const WINDOW* w = initscr(); + if (!w) { + const char* term = getenv("TERM"); + std::cerr << "Failed to initialize ncurses with TERM=" << (term ? term : "unset") << "\n"; + std::exit(EXIT_FAILURE); + } + + this->update_layout(); + + // Setup terminal. + if (cbreak() == ERR || noecho() == ERR) { + endwin(); + std::cerr << "Terminal setup failed\n"; + std::exit(EXIT_FAILURE); + } + + // Enable function keys and arrow keys. + if (keypad(stdscr, TRUE) == ERR) { + std::cerr << "Warning: keypad() not supported\n"; + } + + // Block on input (getch waits for input). + nodelay(stdscr, FALSE); + + // Cursor hiding (may not be supported). + if (curs_set(0) == ERR) { + std::cerr << "Warning: cursor control not supported on this terminal\n"; + } + + if (has_colors()) { +#ifdef DEBUG + if (this->is_running() == false) { + UserInterface::print_message_noninteractive( + std::format("\t[DEBUG] Checking theme - use_dark_theme = {}\n", this->use_dark_theme)); + } +#endif + + if (this->use_dark_theme == true) { + this->init_dark_theme(); + } else { + this->init_light_theme(); + } + bkgd(COLOR_PAIR(DEFAULT_PAIR)); + } + + signal(SIGWINCH, UserInterface::handle_resize); + signal(SIGINT, UserInterface::handle_interrupt); +} + +/** + * Cleans up ncurses and restores the terminal to its normal state. + * + * Calls endwin() to tear down the ncurses library, which restores terminal settings (echo, cbreak mode, + * cursor visibility, color state) and clears the screen. Must be called before program termination to + * prevent terminal corruption. + */ +void UserInterface::cleanup_ncurses(void) { + endwin(); +} + +/** + * Draws the terminal UI frame with a Unicode box border. + * + * Clears the screen and retrieves the current terminal dimensions (max_y, max_x) via getmaxyx(). + * Draws a complete box frame using Unicode box-drawing characters: ā•” and ā•— (top corners), ā•š and ā• + * (bottom corners), ═ (horizontal edges), and ā•‘ (vertical edges). Positions characters using mvprintw() + * to create a full-terminal border with proper corner and edge placement. + * + * Refreshes the display with refresh() to flush buffered output and show the drawn frame on screen. + */ +void UserInterface::draw_ui(void) { + clear(); + + int max_y; + int max_x; + getmaxyx(stdscr, max_y, max_x); + + int i; + + // Top border + mvprintw(0, 0, "ā•”"); + for (i = 1; i < max_x - 1; i += 1) { + mvprintw(0, i, "═"); + } + mvprintw(0, max_x - 1, "ā•—"); + + // Side borders + for (i = 1; i < max_y - 1; i += 1) { + mvprintw(i, 0, "ā•‘"); + mvprintw(i, max_x - 1, "ā•‘"); + } + + // Bottom border + mvprintw(max_y - 1, 0, "ā•š"); + for (i = 1; i < max_x - 1; i += 1) { + mvprintw(max_y - 1, i, "═"); + } + mvprintw(max_y - 1, max_x - 1, "ā•"); + + refresh(); +} + +/** + * Draws an animated spinner with optional progress percentage at the UI layout position. + * + * Returns early if the spinner is not active (checked via is_spinner_active()). Loads the current + * animation frame index and progress percentage from atomic variables (spinner_frame, progress_percent) + * in a thread-safe manner. Selects the appropriate spinner character from a rotating set (|, /, -, \) + * based on the frame index. + * + * Enables DEFAULT_PAIR color styling and renders the spinner at the layout-defined position + * (layout.spinner_y, layout.spinner_x) using mvprintw(). If progress > 0, displays "X Loading..." + * with the progress percentage; otherwise displays "X Loading..." without percentage. Disables color + * styling after rendering. + * + * Thread-safe via atomic variable loads; does not modify shared state. + */ +void UserInterface::draw_spinner() { + if (!this->is_spinner_active()) { + return; + } + + const char spinner_chars[] = {'|', '/', '-', '\\'}; + int frame = this->spinner_frame.load(); + int progress = this->progress_percent.load(); + + attron(COLOR_PAIR(DEFAULT_PAIR)); + + if (progress > 0) { + mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Progress: %d%%", spinner_chars[frame], progress); + } else { + mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Loading...", spinner_chars[frame]); + } + + attroff(COLOR_PAIR(DEFAULT_PAIR)); +} + +/** + * Recalculates UI layout positions and dimensions based on current terminal size. + * + * Retrieves the current terminal dimensions (max_y, max_x) via getmaxyx() and updates the layout + * structure to position UI elements relative to terminal boundaries. Sets status_y to the bottom row + * (max_y - 1), input area to max_y - 3 with left margin of 2 columns, and spinner to max_y - 2 + * (between input and status rows). Sets output area to start at row 1 (below top border) with height + * calculated as the vertical space between output_y and input_y minus one row for spacing. + * + * Intended to be called during initialization and in response to terminal resize events (SIGWINCH) + * to ensure all UI elements remain properly positioned and sized when the terminal is resized. + */ +void UserInterface::update_layout() { + int max_y, max_x; + getmaxyx(stdscr, max_y, max_x); + + layout.status_y = max_y - 1; + layout.input_y = max_y - 3; + layout.input_x = 2; + layout.spinner_y = max_y - 2; + layout.spinner_x = 2; + layout.output_y = 1; + layout.output_height = layout.input_y - layout.output_y - 1; +} + +/** + * Clears the input area rows by overwriting them with spaces. + * + * Retrieves the current terminal dimensions (max_y, max_x) via getmaxyx(). Erases two rows of the + * input area (layout.input_y and layout.input_y + 1) by drawing horizontal lines of spaces from + * column 1 to max_x - 2, leaving the left and right borders intact. + * + * Used to erase previous user input or prompts before rendering new content in the input area. + * Maintains visual consistency by preserving the terminal border structure. + */ +void UserInterface::clear_input_area() { + int max_y, max_x; + getmaxyx(stdscr, max_y, max_x); + + mvhline(layout.input_y, 1, ' ', max_x - 2); + mvhline(layout.input_y + 1, 1, ' ', max_x - 2); +} + +/** + * Renders the input prompt and user-typed content in the input area. + * + * Clears the input area via clear_input_area(). Returns early if the spinner is currently active, + * preventing prompt and input display while a background operation (query execution) is in progress. + * + * When the spinner is inactive, renders a static prompt "ā³ Type your prompt (q/Q to quit): " at + * the layout-defined input position (layout.input_y, layout.input_x). Renders the contents of the + * input_buffer (user-typed characters) immediately following the prompt text at a fixed column offset + * (+37 from input_x). + * + * Provides visual feedback and instructions to the user while maintaining a clean, non-overlapping + * layout during asynchronous spinner operation. + */ +void UserInterface::draw_input_area() { + this->clear_input_area(); + if (this->is_spinner_active()) { + return; + } + + mvprintw(layout.input_y, layout.input_x, "ā³ Type your prompt (q/Q to quit): "); + + // Draw the actual input buffer that user typed + mvprintw(layout.input_y, layout.input_x + 37, "%s", input_buffer.c_str()); +} + +/** + * Renders the message output buffer in reverse chronological order (newest first), + * from the bottom of the output area upward. + * + * Clears the entire output area by filling each row with spaces, preserving the border columns. + * Iterates backwards through output_buffer, starting from the most recently added message. + * For each message, extracts the text content and message type (error/success/default). + * + * Splits multi-line message text by newline characters. Wraps each logical line at word + * boundaries using TextUtils::wrap_text() to fit within max_content_width (COLS - 4). + * Renders wrapped lines from bottom to top (reverse order) within the allocated output area, + * decrementing current_line after each rendered line. + * + * Applies semantic color and icon styling based on message type: + * - MESSAGE_TYPE_ERROR: bold red (ERROR_PAIR) with āŒ emoji prefix. + * - MESSAGE_TYPE_SUCCESS: bold default color with āœ… emoji prefix. + * - Default: plain text without icon. + * + * Breaks iteration early if current_line reaches or falls below layout.output_y (top boundary). + * Calls refresh() to update the terminal display. + * + * Provides a scrollable-like view of the most recent messages within the constrained output area, + * with automatic wrapping and visual differentiation for errors and successful operations. + */ +void UserInterface::draw_output_area() { + // Clear the output area + for (int i = 0; i < layout.output_height; i++) { + mvhline(layout.output_y + i, 1, ' ', COLS - 2); + } + + int current_line = layout.input_y - 2; // Start from bottom + int max_content_width = COLS - 4; + + // Iterate backwards through buffer (newest first) + for (auto it = output_buffer.rbegin(); it != output_buffer.rend(); ++it) { + if (current_line <= layout.output_y) { + break; + } + + const auto& [text, type] = *it; + std::istringstream stream(text); + std::string line; + std::vector display_lines; + + // Process each logical line from the message + while (std::getline(stream, line)) { + // Wrap long lines at word boundaries + auto wrapped = TextUtils::wrap_text(line, max_content_width); + display_lines.insert(display_lines.end(), wrapped.begin(), wrapped.end()); + } + + // Render from bottom to top (reverse order) + for (auto line_it = display_lines.rbegin(); line_it != display_lines.rend(); ++line_it) { + if (current_line <= layout.output_y) break; + + if (type == UserInterface::MESSAGE_TYPE_ERROR) { + wattron(stdscr, COLOR_PAIR(ERROR_PAIR) | A_BOLD); + mvprintw(current_line, 2, "āŒ %s", line_it->c_str()); + wattroff(stdscr, COLOR_PAIR(ERROR_PAIR) | A_BOLD); + } else if (type == UserInterface::MESSAGE_TYPE_SUCCESS) { + wattron(stdscr, A_BOLD); + mvprintw(current_line, 2, "āœ… %s", line_it->c_str()); + wattroff(stdscr, A_BOLD); + } else { + mvprintw(current_line, 2, "%s", line_it->c_str()); + } + + current_line--; + } + } + + refresh(); +} + +/** + * @brief Spawns the background rendering thread and sets the thread_running flag. + * + * Sets thread_running to true and creates a new std::thread that invokes render_loop(). + * The thread is joinable and must be cleaned up via stop_render_thread() or equivalent. + * + * @note Call this after init_ncurses() to begin continuous UI rendering. + * @see render_loop(), stop_render_thread() + */ +void UserInterface::start_render_thread(void) { + this->thread_running = true; + this->render_thread = std::thread(&UserInterface::render_loop, this); +} + +/** + * @brief Gracefully shuts down the background rendering thread. + * + * Sets thread_running to false and notifies the condition variable cv_redraw to + * wake the render loop. Joins the thread if it is joinable, ensuring complete cleanup. + * + * @note Call this during session shutdown or before destroying the UserInterface instance. + * @see start_render_thread(), render_loop() + */ +void UserInterface::stop_render_thread(void) { + this->thread_running = false; + this->cv_redraw.notify_one(); + if (this->render_thread.joinable()) { + this->render_thread.join(); + } +} + +/** + * @brief Main rendering loop executed by the background render thread. + * + * Runs continuously while thread_running is true. Uses cv_redraw condition variable + * with a 1500ms timeout to wait efficiently for redraw requests. Handles terminal resize + * events (endwin(), refresh(), update_layout(), cursor recalculation). Conditionally + * redraws UI components (draw_ui, draw_output_area, draw_input_area, draw_spinner) + * when should_redraw is set. All ncurses operations are protected by ui_mutex. + * + * @note This method is the entry point for the render thread and should not be called directly. + * Call start_render_thread() to spawn it. Terminate via stop_render_thread(). + * @see start_render_thread(), stop_render_thread(), draw_ui(), draw_output_area(), draw_input_area(), draw_spinner() + */ +void UserInterface::render_loop(void) { + while (this->thread_running) { + std::unique_lock lock(this->ui_mutex); + + // Wait for redraw request or timeout (100ms) + this->cv_redraw.wait_for(lock, std::chrono::milliseconds(1500), [this] { return this->should_redraw.load(); }); + + // Handle resize (under lock) + if (this->resize_flag) { + this->resize_flag = 0; + endwin(); + refresh(); + this->update_layout(); + + // Recalculate cursor position after resize + input_cursor_x = layout.input_x + 37 + input_buffer.length(); + this->should_redraw = true; // Force redraw after resize + } + + // Redraw UI (all ncurses calls under lock) + if (this->should_redraw) { + this->draw_ui(); + this->draw_output_area(); + this->draw_input_area(); + this->draw_spinner(); + + refresh(); + this->should_redraw = false; + } + + lock.unlock(); + } +} + +/** + * Constructs a UserInterface instance and initializes member variables. + * + * Initializes atomic flags resize_flag and running to 0 (false/inactive). + * Initializes input_cursor_x to 0 (cursor at leftmost position). + * Initializes layout struct to default-constructed values (all fields zeroed/default). + * Sets use_dark_theme to true, establishing dark theme as the default color scheme preference. + * + * Stores a static instance pointer (UserInterface::instance = this) to enable the singleton pattern, + * allowing static methods and signal handlers to access the active UI instance. + * + * Emits debug output to verify use_dark_theme initialization state. + * + * Note: This constructor performs only member initialization and singleton registration. + * Full ncurses initialization (terminal setup, color pair configuration, input handling) is deferred + * to init_ncurses(), which must be called explicitly after construction to establish the UI environment. + */ +UserInterface::UserInterface() : resize_flag(0), running(0), input_cursor_x(0), layout({}), use_dark_theme(true) { + UserInterface::instance = this; +} + +/** + * Constructs a UserInterface instance with a caller-specified color theme preference. + * + * @param dark_theme: Boolean flag to select color scheme; true for dark theme, false for light theme. + * + * Initializes atomic flags resize_flag and running to 0 (false/inactive). + * Initializes input_cursor_x to 0 (cursor at leftmost position). + * Initializes layout struct to default-constructed values (all fields zeroed/default). + * Sets use_dark_theme to the caller-provided dark_theme value, establishing the preferred + * color scheme that will be applied during init_ncurses(). + * + * Stores a static instance pointer (UserInterface::instance = this) to enable the singleton pattern, + * allowing static methods and signal handlers to access the active UI instance. + * + * Emits debug output to verify use_dark_theme initialization state. + * + * Note: This constructor performs only member initialization and singleton registration. + * Full ncurses initialization (terminal setup, color pair configuration, input handling) is deferred + * to init_ncurses(), which must be called explicitly after construction to establish the UI environment. + */ +UserInterface::UserInterface(bool dark_theme) + : resize_flag(0), running(0), input_cursor_x(0), layout({}), use_dark_theme(dark_theme) { + UserInterface::instance = this; +} + +/** + * Destructs a UserInterface instance and releases ncurses resources. + * + * Calls cleanup_ncurses() to restore terminal settings and release ncurses state. + * This operation calls endwin() to exit ncurses mode and prevent terminal corruption upon program exit. + * + * Nullifies the static instance pointer (UserInterface::instance = nullptr) to clear the singleton reference. + * This prevents accidental use-after-free from static methods or signal handlers attempting to access + * a destroyed UI instance. + * + * Ensures proper terminal state restoration and safe cleanup of the singleton pattern. + * + * Note: Should be called when the UI environment is no longer needed, typically before program termination. + */ +UserInterface::~UserInterface() { + this->cleanup_ncurses(); + UserInterface::instance = nullptr; +} + +/** + * Queries the current running state of the UI application. + * + * @return Boolean indicating whether the application is actively running. + * + * - true if running == 1 (active/running); + * + * - false if running == 0 (inactive/stopped). + * + * Performs a thread-safe atomic read of the running flag, allowing safe concurrent + * queries from multiple threads without synchronization overhead. + * + * Typically used in main event loops or background threads to determine whether + * to continue processing, poll for input, or exit gracefully. + */ +bool UserInterface::is_running() { + return this->running == 1; +} + +/** + * Static signal handler for SIGWINCH (terminal resize) events. + * + * @param sig Signal number (SIGWINCH); unused but required by signal handler signature. + * + * Checks if the singleton UserInterface instance exists. If it does, sets the atomic + * resize_flag to 1, signaling to the main event loop that a terminal resize has occurred + * and the layout must be recalculated. + * + * Re-registers this handler with signal(SIGWINCH, ...) to ensure continued handling of + * subsequent resize events. This re-registration is necessary on systems where signal handlers + * are one-time (non-persistent) and must be re-armed after each invocation. + * + * Uses atomic flag-setting rather than directly invoking layout recalculation, deferring + * resize handling to the main event loop to avoid complex operations within signal context. + * Provides defensive null-check of the singleton instance in case the handler is invoked + * after the UI is destroyed. + * + * Enables responsive terminal resizing without blocking signal delivery or causing + * signal-safe function violations. + */ +void UserInterface::handle_resize(int sig) { + if (UserInterface::instance) { + UserInterface::instance->resize_flag = 1; + } + + signal(SIGWINCH, UserInterface::handle_resize); +} + +/** + * Static signal handler for SIGINT (interrupt) signal. + * + * @param sig Signal number (SIGINT); unused but required by signal handler signature. + * + * Handles graceful shutdown triggered by user interrupt (Ctrl+C). Checks if the singleton + * UserInterface instance exists. If it does, performs immediate cleanup: sets the atomic + * running flag to 0 to signal the main event loop to stop, calls endwin() to restore + * terminal settings and prevent terminal corruption, and exits with EXIT_SUCCESS. + * + * Ensures the terminal is properly restored to its original state even when the program + * terminates abnormally via interrupt. This prevents the terminal from being left in a + * curses-altered state (e.g., hidden cursor, no echo) after exit. + * + * Provides defensive null-check of the singleton instance in case the handler is invoked + * after the UI is destroyed. + * + * Does not require signal re-registration, as SIGINT handler persists across invocations. + * Terminates the process immediately with exit(); does not return to caller. + * + * Enables clean shutdown with guaranteed terminal restoration and prevents resource leaks + * by terminating the entire process rather than returning to potentially inconsistent state. + */ +void UserInterface::handle_interrupt(int sig) { + if (UserInterface::instance) { + UserInterface::instance->running = 0; + endwin(); + exit(EXIT_SUCCESS); + } +} + +/** + * Initializes and starts the UserInterface subsystem. + * + * Performs full initialization pipeline: calls init_ncurses() to set up the ncurses + * library, terminal settings, and signal handlers; calls draw_ui() to render the initial + * full-terminal Unicode box border; sets the atomic running flag to 1 to signal active + * state; and calls start_render_thread() to spawn the background rendering thread. + * + * The rendering thread continuously redraws the UI (output area, input area, spinner) + * in response to state changes and terminal resize events (resize_flag). The running + * flag controls the render thread's event loop; setting it to 1 enables the thread to + * proceed; setting it to 0 causes the thread to exit gracefully. + * + * No parameters; operates on the current UserInterface instance state. + * + * @return void + * + * Initialization status is communicated via successful completion (or + * program termination if init_ncurses() encounters a fatal error). + * + * Acts as the entry point for the UI system. Should be called once after UserInterface + * instantiation and before any event processing or input handling. + * + * Enables the interactive terminal UI with responsive rendering and asynchronous + * screen updates via the background thread, while the main thread handles user input + * and application logic. + */ +void UserInterface::run(void) { + this->init_ncurses(); + + this->draw_ui(); + + this->running = 1; + + this->start_render_thread(); +} + +/** + * Gracefully terminates the UserInterface subsystem and exits the application. + * + * @param exit_code Exit status code passed to exit(); typically EXIT_SUCCESS (0) or EXIT_FAILURE (1). + * + * Performs an orderly shutdown sequence: prints a farewell message ("šŸ The session has ended."), + * sleeps for 1000 milliseconds to ensure the message is visible on screen, stops the background + * render thread via stop_render_thread(), restores terminal settings via cleanup_ncurses(), + * and exits the process with the provided exit_code. + * + * The delay (napms) between printing and thread shutdown allows the message to be displayed + * before the render thread is terminated and the screen is cleared, ensuring the user sees + * the farewell notification. + * + * Guarantees terminal restoration even when exiting via this controlled path, preventing + * the terminal from being left in a corrupted ncurses state. The cleanup_ncurses() call + * ensures endwin() is invoked to restore terminal settings (cursor, echo, etc.). + * + * Acts as the primary exit point for controlled application termination. Should be called + * in response to user quit command (q/Q) or successful completion of application logic. + * + * Terminates the process immediately with exit(); does not return to caller. + * + * Enables clean, user-facing shutdown with guaranteed terminal restoration and thread cleanup. + */ +void UserInterface::end_session(int exit_code) { + this->print("šŸ The session has ended."); + + napms(1000); + + this->stop_render_thread(); + + this->cleanup_ncurses(); + + exit(exit_code); +} + +/** + * Displays runtime configuration arguments as formatted diagnostic output. + * + * @param model Name of the primary language model in use. + * @param embedding_model Name of the embedding model in use. + * @param prompt Initial prompt or query string provided by the user. + * @param stream Boolean flag indicating whether streaming mode is enabled. + * @param interactive Boolean flag indicating whether interactive mode is enabled. + * @param dark_theme Boolean flag indicating whether dark theme is active. + * + * Constructs a multi-line diagnostic string containing all provided configuration parameters. + * Each parameter is formatted with a šŸ›ˆ (information) icon prefix for visual consistency. + * Boolean parameters are converted to human-readable "true" or "false" strings using conditional + * operators, then concatenated into the buffer. + * + * Prints the formatted buffer via this->print() with MESSAGE_TYPE_NORMAL styling, displaying + * the configuration summary in the output area for user visibility. + * + * @return void + * + * Output is displayed via print() and committed to the output buffer. + * + * Acts as a diagnostic utility to confirm application startup parameters and aid in + * troubleshooting configuration issues. Typically called early during initialization to + * provide user confirmation of active settings. + * + * Enables transparency into runtime configuration and helps users verify that the correct + * models, modes, and theme are in effect. + */ +void UserInterface::print_args(const std::string& model, const std::string& embedding_model, const std::string& prompt, + bool stream, bool interactive, bool dark_theme) { + std::string buffer; + buffer += "šŸ›ˆ model = " + model + "\n"; + buffer += "šŸ›ˆ embedding_model = " + embedding_model + "\n"; + buffer += "šŸ›ˆ prompt = " + prompt + "\n"; + buffer += "šŸ›ˆ stream = " + std::string(stream ? "true" : "false") + "\n"; + buffer += "šŸ›ˆ interactive = " + std::string(interactive ? "true" : "false") + "\n"; + buffer += "šŸ›ˆ dark_theme = " + std::string(dark_theme ? "true" : "false") + "\n"; + + this->print(buffer, UserInterface::MESSAGE_TYPE_NORMAL); +} + +/** + * @brief Displays runtime configuration arguments to stdout in non-interactive mode. + * + * @param model Name of the primary language model in use. + * @param embedding_model Name of the embedding model in use. + * @param prompt Initial prompt or query string provided by the user. + * @param stream Boolean flag indicating whether streaming mode is enabled. + * @param interactive Boolean flag indicating whether interactive mode is enabled. + * @param dark_theme Boolean flag indicating whether dark theme is active. + * + * @return void + * + * Outputs runtime configuration to standard output (stdout) using printf(), bypassing the + * ncurses UI buffer. This method is used when the application runs in non-interactive mode, + * where the terminal UI is not initialized and direct console output is required. + * + * Constructs and prints a multi-line diagnostic string containing all provided configuration + * parameters. Each parameter is formatted with a šŸ›ˆ (information) icon prefix for visual + * consistency with interactive mode output. Boolean parameters are converted to human-readable + * "true" or "false" strings using conditional operators. + * + * Includes leading and trailing newlines (printf("\n")) to visually separate the configuration + * summary from other console output, improving readability in log files and terminal sessions. + * + * Acts as the non-interactive counterpart to print_args(). Enables configuration transparency + * and aids in troubleshooting when the application runs in batch or command-line mode without + * the interactive terminal UI. + * + * @note This method uses direct printf() calls and should only be used before ncurses + * initialization or after cleanup, to avoid conflicts with the ncurses output buffer. + */ +void UserInterface::print_args_noninteractive(const std::string& model, const std::string& embedding_model, + const std::string& prompt, bool stream, bool interactive, + bool dark_theme) { + printf("\n"); + printf("šŸ›ˆ model = %s\n", model.c_str()); + printf("šŸ›ˆ embedding_model = %s\n", embedding_model.c_str()); + printf("šŸ›ˆ prompt = %s\n", prompt.c_str()); + printf("šŸ›ˆ stream = %s\n", stream ? "true" : "false"); + printf("šŸ›ˆ interactive = %s\n", interactive ? "true" : "false"); + printf("šŸ›ˆ dark_theme = %s\n", dark_theme ? "true" : "false"); + printf("\n"); +} + +/** + * @brief Displays a numbered list of available models to the user via the UI buffer. + * + * @param models A constant reference to a vector of model name strings to be displayed. + * + * @return void + * + * Renders an interactive model selection menu by formatting each model name with its + * zero-indexed position. This method is used during interactive sessions to present + * available Ollama models to the user, enabling selection via numeric input. + * + * Constructs a formatted string buffer containing an information message ("šŸ›ˆ Select a + * model from the list below:") followed by a numbered list. Each entry is formatted as + * "[index] model_name" on a separate line, where index is zero-based and automatically + * converted from the loop counter using std::to_string(). + * + * Outputs the constructed buffer to the ncurses UI using print() with MESSAGE_TYPE_NORMAL + * styling, ensuring the model list appears in the output area and is preserved in the UI's + * output_buffer for proper rendering and scrolling. + * + * @note This method assumes models is not empty; calling with an empty vector will display + * only the header message without any selectable options. Typically called after successfully + * retrieving the model list from the Ollama server via query_model_list(). + * + * @see print(), MESSAGE_TYPE_NORMAL + */ +void UserInterface::print_model_list(const std::vector& models) { + std::string buffer; + buffer += "\nšŸ›ˆ Select a model from the list below:\n"; + for (size_t i = 0; i < models.size(); i += 1) { + buffer += "[" + std::to_string(i) + "] " + models[i] + "\n"; + } + + this->print(buffer, UserInterface::MESSAGE_TYPE_NORMAL); +} + +/** + * @brief Outputs a numbered list of available models to stdout in non-interactive mode. + * + * @param models A constant reference to a vector of model name strings. + * + * @return void + * + * Formats and prints each model with its zero-indexed position as "[index] model_name" + * using printf() directly, bypassing the ncurses UI buffer. Called when the application + * runs in non-interactive mode and the terminal UI is not initialized. + * + * @note This method should only be used before ncurses initialization or after cleanup. + */ +void UserInterface::print_model_list_noninteractive(const std::vector& models) { + printf("\nšŸ›ˆ Select a model from the list below:\n"); + for (size_t i = 0; i < models.size(); i += 1) { + printf("[%zu] %s\n", i, models[i].c_str()); + } +} + +/** + * @brief Prompts the user to select a model by numeric index via interactive keyboard input. + * + * @param models A constant reference to a vector of available model name strings. + * @param model A pointer to a string where the selected model name will be stored. + * + * @return void + * + * Validates that models is not empty; exits with error if no models are available. + * Clears the input buffer and enters a getch() loop to capture user input, supporting + * backspace (KEY_BACKSPACE or 127) and printable characters with length constraints. + * Input terminates on newline (Enter key). + * + * Interprets input as a zero-indexed model position via stoi(). If input is "q" or "Q", + * terminates the session. If the index is out of bounds, prints an error and recursively + * re-prompts. If valid, dereferences model and assigns the selected model name. + * + * @note Input buffer length is capped at COLS - 40 to prevent overflow. Invalid indices + * trigger recursive retry. Quit commands (q/Q) terminate the entire session. + */ +void UserInterface::select_model(const std::vector& models, std::string* model) { + int index{}; + + if (models.size() == 0) { + this->print_error("There are no available models to select from.\n"); + exit(1); + } + + this->request_redraw(); + + this->input_buffer.clear(); + int ch; + + while ((ch = getch()) != '\n') { + if (ch == KEY_BACKSPACE || ch == 127) { + if (!input_buffer.empty()) { + input_buffer.pop_back(); + input_cursor_x--; + this->request_redraw(); + } + } else if (ch != ERR && isprint(ch)) { + if (input_buffer.length() < COLS - 40) { // Leave room for prompt + input_buffer.push_back(ch); + input_cursor_x++; + this->request_redraw(); + } + } + } + + if (this->input_buffer == "q" || this->input_buffer == "Q") { + this->end_session(EXIT_SUCCESS); + } + + index = stoi(this->input_buffer); + + if (index < 0 || index >= models.size()) { + std::string message = std::format("Model index {} does not exist.\n", index); + this->print_error(message); + this->select_model(models, model); + } else { + *model = models[index]; + } +} + +/** + * @brief Prompts for a model selection via stdin in non-interactive mode. + * + * @param models A constant reference to a vector of available model name strings. + * @param model A pointer to a string where the selected model name will be stored. + * + * @return void + * + * Validates that models is not empty; exits with error if none are available. + * Loops until a valid zero-indexed model position is successfully read from stdin via scanf(). + * Repeats the prompt if scanf() fails to read exactly one integer or if the index is out of bounds. + * Prints validation errors to stderr. On valid input, dereferences model and assigns the + * selected model name. + * + * @note Uses stderr for error messages and stdout for prompts. Loop continues until + * scanf() succeeds and index is within [0, models.size()). + */ +void UserInterface::select_model_noninteractive(const std::vector& models, std::string* model) { + int index{}; + int read_result{}; + + if (models.size() == 0) { + UserInterface::print_error_noninteractive("There are no available models to select from.\n"); + exit(1); + } + + while (read_result != 1 || index < 0 || index >= models.size()) { + if (index < 0 || index >= models.size()) { + UserInterface::print_error_noninteractive(std::format("Model index {} does not exist.\n", index)); + } + UserInterface::print_message_noninteractive("Model index: "); + read_result = scanf("%d", &index); + } + + *model = models[index]; +} + +/** + * @brief Captures the next user prompt via interactive keyboard input and detects quit commands. + * + * @param prompt A pointer to a string where the captured prompt will be stored. + * + * @return bool True if the user entered "q" or "Q" (quit command); false otherwise. + * + * Clears the input buffer and enters a getch() loop to capture keyboard input, supporting + * backspace (KEY_BACKSPACE or 127) and printable characters with length constraints. + * Input terminates on newline (Enter key). Copies the input buffer to prompt and returns + * true if the prompt is a quit command, signaling session termination. + * + * @note Input buffer length is capped at COLS - 40. Requests a UI redraw on each keypress. + */ +bool UserInterface::next_prompt(std::string* prompt) { + bool done = false; + + this->request_redraw(); + + this->input_buffer.clear(); + int ch; + + while ((ch = getch()) != '\n') { + if (ch == KEY_BACKSPACE || ch == 127) { + if (!input_buffer.empty()) { + input_buffer.pop_back(); + input_cursor_x--; + this->request_redraw(); + } + } else if (ch != ERR && isprint(ch)) { + if (input_buffer.length() < COLS - 40) { // Leave room for prompt + input_buffer.push_back(ch); + input_cursor_x++; + this->request_redraw(); + } + } + } + + *prompt = this->input_buffer; + + if (*prompt == "q" || *prompt == "Q") { + done = true; + } + + return done; +} + +/** + * @brief Captures the next user prompt via stdin in non-interactive mode and detects quit commands. + * + * @param prompt A pointer to a string where the captured prompt will be stored. + * + * @return bool True if the user entered "q" or "Q" (quit command); false otherwise. + * + * Prompts the user via stdout and reads a line from stdin using std::getline(). + * Terminates the program with exit code 1 if input reading fails. + * Detects quit commands ("q" or "Q") and returns true to signal session termination. + * + * @note Must be used outside an active ncurses session. Uses stdout/stderr for I/O. + * @see next_prompt() + */ +bool UserInterface::next_prompt_noninteractive(std::string* prompt) { + bool done = false; + printf("ā³ Type your prompt (q/Q to quit): "); + if (!std::getline(std::cin, *prompt, '\n')) { + fprintf(stderr, "Error reading user input.\n"); + exit(1); + } + + if (*prompt == "q" || *prompt == "Q") { + done = true; + } + + return done; +} + +/** + * @brief Queues a typed message to the output buffer and requests a UI redraw. + * + * @param text The message content to be displayed. + * @param type The message type (MESSAGE_TYPE_NORMAL, MESSAGE_TYPE_ERROR, MESSAGE_TYPE_SUCCESS) that controls styling. + * Defaults to MESSAGE_TYPE_NORMAL if not specified. + * + * Thread-safe: acquires ui_mutex before adding the message to output_buffer. + * Automatically requests a redraw via request_redraw() to display the new message. + * + * @see draw_output_area() + */ +void UserInterface::print(const std::string& text, int type) { + { + std::lock_guard lock(this->ui_mutex); + output_buffer.push_back({text, type}); + } + this->request_redraw(); +} + +/** + * @brief Queues an error message (bold red with āŒ prefix) and requests a redraw. + * + * @param text The error message content. + * + * @see print() + */ +void UserInterface::print_error(const std::string& text) { + this->print(text, UserInterface::MESSAGE_TYPE_ERROR); +} + +/** + * @brief Queues a success message (bold with āœ… prefix) and requests a redraw. + * + * @param text The success message content. + * + * @see print() + */ +void UserInterface::print_success(const std::string& text) { + this->print(text, UserInterface::MESSAGE_TYPE_SUCCESS); +} + +/** + * @brief Queues a normal message (plain text) and requests a redraw. + * + * @param text The message content. + * + * @see print() + */ +void UserInterface::print_message(const std::string& text) { + this->print(text, UserInterface::MESSAGE_TYPE_NORMAL); +} + +/** + * @brief Outputs a message directly to stderr in non-interactive mode. + * + * @param text The message content to be displayed. + * + * Writes the text to stderr and immediately flushes the output buffer to ensure + * the message is visible without waiting for a newline. + * Adds an icon āŒ before the text. + * + * @note Must be used outside an active ncurses session. + * @see print_error() + */ +void UserInterface::print_error_noninteractive(const std::string& text) { + std::cerr << "āŒ " << text; + std::cerr.flush(); +} + +/** + * @brief Outputs a message directly to stdout in non-interactive mode. + * + * @param text The message content to be displayed. + * + * Writes the text to stdout and immediately flushes the output buffer to ensure + * the message is visible without waiting for a newline. + * Adds an icon āœ… before the text. + * + * @note Must be used outside an active ncurses session. + * @see print_error() + */ +void UserInterface::print_success_noninteractive(const std::string& text) { + std::cout << "āœ… " << text; + std::cout.flush(); +} + +/** + * @brief Outputs a message directly to stdout in non-interactive mode. + * + * @param text The message content to be displayed. + * + * Writes the text to stdout and immediately flushes the output buffer to ensure + * the message is visible without waiting for a newline. + * + * @note Must be used outside an active ncurses session. + * @see print_message() + */ +void UserInterface::print_message_noninteractive(const std::string& text) { + std::cout << text; + std::cout.flush(); +} + +/** + * @brief Signals the render thread to perform a UI redraw on the next cycle. + * + * Sets should_redraw to true and notifies cv_redraw to wake the render loop, + * ensuring a timely UI update without waiting for the 1500ms timeout. + * + * @note Thread-safe: uses atomic operations and condition variable signaling. + * @see render_loop() + */ +void UserInterface::request_redraw(void) { + this->should_redraw = true; + this->cv_redraw.notify_one(); +} + +/** + * @brief Activates the spinner animation and triggers a UI redraw. + * + * Acquires ui_mutex, sets spinner_active to true, resets spinner_frame to 0, + * and sets should_redraw to true to display the spinner on the next render cycle. + * + * @note Thread-safe: acquires exclusive lock via lock_guard before modifying state. + * @see stop_spinner(), draw_spinner() + */ +void UserInterface::start_spinner() { + std::lock_guard lock(ui_mutex); + this->spinner_active = true; + this->spinner_frame = 0; + this->should_redraw = true; +} + +/** + * @brief Deactivates the spinner animation and triggers a UI redraw. + * + * Acquires ui_mutex, sets spinner_active to false, resets spinner_frame to 0, + * and sets should_redraw to true to clear the spinner on the next render cycle. + * + * @note Thread-safe: acquires exclusive lock via lock_guard before modifying state. + * @see start_spinner(), draw_spinner() + */ +void UserInterface::stop_spinner() { + std::lock_guard lock(ui_mutex); + this->spinner_active = false; + this->spinner_frame = 0; + this->should_redraw = true; +} + +/** + * @brief Increments the spinner frame counter if the spinner is active. + * + * If spinner_active is true, advances spinner_frame with modulo 4 (cycling + * through frames 0–3 to rotate the spinner characters |, /, -, \) and signals + * a redraw to display the new frame. + * + * @note Called by render loop to update spinner animation each cycle. + * @see is_spinner_active(), draw_spinner() + */ +void UserInterface::advance_spinner_frame() { + if (this->is_spinner_active()) { + this->spinner_frame = (spinner_frame + 1) % 4; + this->should_redraw = true; + } +} + +/** + * @brief Atomically queries whether the spinner animation is currently active. + * + * Returns the current value of the spinner_active atomic flag. + * + * @return true if spinner is active, false otherwise. + * @note Thread-safe: uses atomic load for safe concurrent access. + * @see start_spinner(), stop_spinner() + */ +bool UserInterface::is_spinner_active() const { + return spinner_active.load(); +} + +/** + * @brief Updates the progress percentage displayed with the spinner. + * + * Clamps the provided percent value to the range [0, 100] and assigns it to + * progress_percent, then signals a redraw to reflect the updated progress. + * + * @param percent Progress value to set; automatically clamped to [0, 100]. + * @note Clipping prevents invalid percentage values from being displayed. + * @see draw_spinner() + */ +void UserInterface::set_progress(int percent) { + this->progress_percent = std::clamp(percent, 0, 100); + this->should_redraw = true; +} diff --git a/src/interface/user_interface.hpp b/src/interface/user_interface.hpp new file mode 100644 index 0000000..42fcea7 --- /dev/null +++ b/src/interface/user_interface.hpp @@ -0,0 +1,202 @@ +#pragma once + +#include "utils/text_utils.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * @brief UI layout positioning configuration. + * + * Stores calculated row and column positions for all major UI elements + * relative to terminal dimensions. Updated by update_layout() when terminal + * is resized. + */ +struct Layout { + // Row for input prompt. + int input_y; + // Column for input start. + int input_x; + // Row where output begins. + int output_y; + // Output area height. + int output_height; + // Row for status messages. + int status_y; + // Row for the progress spinner. + int spinner_y; + // Column for the progress spinner. + int spinner_x; +}; + +/** + * @brief ncurses-based terminal user interface for interactive prompting and output display. + * + * Manages full-screen UI rendering with UTF-8 box borders, input buffer, scrollable output, + * animated progress spinner, and configurable dark/light themes. Runs a background render + * thread that updates the display on demand or every 1500ms. Handles terminal resize + * (SIGWINCH) and interrupt (SIGINT) signals. Supports dual interactive/noninteractive modes. + * + * Message types: MESSAGE_TYPE_NORMAL (plain text), MESSAGE_TYPE_ERROR (bold red with āŒ), + * MESSAGE_TYPE_SUCCESS (bold with āœ…). + * + * @note Singleton pattern via static instance pointer; used by signal handlers. + * @note Thread-safe: output_buffer and spinner state protected by ui_mutex and atomic flags. + * @note Must call run() to initialize ncurses and start rendering before using print/spinner methods. + * @note Noninteractive methods (print_*_noninteractive, select_model_noninteractive, next_prompt_noninteractive) + * must be used outside an active ncurses session. + * @see run(), end_session(), ProgressSpinner (friend class) + */ +class UserInterface { + private: + // Message configuration constants. + + // Plain text, default styling. + static constexpr int MESSAGE_TYPE_NORMAL = 0; + // Bold red with āŒ prefix. + static constexpr int MESSAGE_TYPE_ERROR = 1; + // Bold with āœ… prefix. + static constexpr int MESSAGE_TYPE_SUCCESS = 2; + + // User Interface state. + + volatile sig_atomic_t resize_flag; + volatile sig_atomic_t running; + // A pointer to the user interface instance. + static UserInterface* instance; + + // Layout state. + struct Layout layout; + + // Input buffer state. + std::string input_buffer; + int input_cursor_x; + + // Output buffer state. + std::vector> output_buffer; + + // Renderer state. + std::thread render_thread; + std::mutex ui_mutex; + std::condition_variable cv_redraw; + std::atomic should_redraw{true}; + std::atomic thread_running{false}; + + // Spinner state. + std::atomic spinner_active{false}; + std::atomic spinner_frame{0}; + std::atomic progress_percent{0}; + + // Color theme configuration. + bool use_dark_theme = true; + + // Initialization methods. + + void init_dark_theme(void); + + void init_light_theme(void); + + void init_ncurses(void); + + void cleanup_ncurses(void); + + // Layout manpulation methods. + + void draw_ui(void); + + void draw_spinner(void); + + void update_layout(); + + // Input area methods. + + void clear_input_area(); + + void draw_input_area(); + + // Output area methods. + + void draw_output_area(); + + // Renderer methods. + + void start_render_thread(void); + + void stop_render_thread(void); + + void render_loop(void); + + public: + UserInterface(); + + explicit UserInterface(bool dark_theme); + + ~UserInterface(); + + bool is_running(); + + static void handle_resize(int sig); + + static void handle_interrupt(int sig); + + void run(void); + + void end_session(int exit_code); + + void print_args(const std::string& model, const std::string& embedding_model, const std::string& prompt, + bool stream, bool interactive, bool dark_theme); + + static void print_args_noninteractive(const std::string& model, const std::string& embedding_model, + const std::string& prompt, bool stream, bool interactive, bool dark_theme); + + void print_model_list(const std::vector& models); + + static void print_model_list_noninteractive(const std::vector& models); + + void select_model(const std::vector& models, std::string* model); + + static void select_model_noninteractive(const std::vector& models, std::string* model); + + bool next_prompt(std::string* prompt); + + static bool next_prompt_noninteractive(std::string* prompt); + + void print(const std::string& text, int type = UserInterface::MESSAGE_TYPE_NORMAL); + + void print_error(const std::string& text); + + static void print_error_noninteractive(const std::string& text); + + void print_success(const std::string& text); + + static void print_success_noninteractive(const std::string& text); + + void print_message(const std::string& text); + + static void print_message_noninteractive(const std::string& text); + + // Rendered methods + + void request_redraw(void); + + // Spinner methods. + + void start_spinner(void); + + void stop_spinner(void); + + void advance_spinner_frame(void); + + bool is_spinner_active(void) const; + + void set_progress(int percent); + + // Grant friend access to ProgressSpinner + friend class ProgressSpinner; +}; diff --git a/src/main.cpp b/src/main.cpp index 1c6fe61..06389a2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,22 +1,33 @@ -#include "interface/user-interface.hpp" +#include "interface/user_interface.hpp" #include "ollama/ollama_client.hpp" +#include "storage/qdrant_client.hpp" +#include "utils/curl_utils.hpp" +#include "utils/embedding_utils.hpp" +#include "utils/system_utils.hpp" +#include "utils/text_utils.hpp" #include #include +#include int main(int argc, const char* argv[]) { std::string model = "gemma3n:latest"; + std::string embedding_model = "embeddinggemma:latest"; std::string prompt = "Hey! What's up!"; bool stream = false; bool interactive = false; bool dark_theme = true; + bool skip_embedding = false; bool done = false; + std::string message{}; std::string arg{}; for (int i = 1; i < argc; i += 1) { arg = argv[i]; if (arg.starts_with("--model=") == true) { model = arg.substr(8); + } else if (arg.starts_with("--embedding_model=") == true) { + embedding_model = arg.substr(18); } else if (arg.starts_with("--prompt=") == true) { prompt = arg.substr(9); } else if (arg.starts_with("--stream=") == true) { @@ -25,6 +36,8 @@ int main(int argc, const char* argv[]) { interactive = arg.substr(14) == "true" ? true : false; } else if (arg.starts_with("--dark_theme=") == true) { dark_theme = arg.substr(13) == "true" ? true : false; + } else if (arg.starts_with("--skip_embedding=") == true) { + skip_embedding = arg.substr(17) == "true" ? true : false; } } @@ -40,7 +53,7 @@ int main(int argc, const char* argv[]) { printf("---\n"); ui.run(); - ui.print_args(model, prompt, stream, interactive, dark_theme); + ui.print_args(model, embedding_model, prompt, stream, interactive, dark_theme); while (prompt.length() == 0) { done = ui.next_prompt(&prompt); @@ -50,7 +63,7 @@ int main(int argc, const char* argv[]) { } } } else { - UserInterface::print_args_noninteractive(model, prompt, stream, interactive, dark_theme); + UserInterface::print_args_noninteractive(model, embedding_model, prompt, stream, interactive, dark_theme); if (prompt.length() == 0) { done = UserInterface::next_prompt_noninteractive(&prompt); @@ -67,9 +80,19 @@ int main(int argc, const char* argv[]) { } } - OllamaClient client = OllamaClient(&ui); + CurlUtils curl(&ui); - std::vector models = client.query_model_list(); + SystemUtils system_utils(&ui); + + QdrantClient storage_client(&ui, &curl, &system_utils); + + struct OllamaClientConfig config {}; + + OllamaClient ollama_client(&config, &ui, &curl, &system_utils); + + EmbeddingUtils embedding_utils(&ui, &curl, &ollama_client, &storage_client); + + std::vector models = ollama_client.query_model_list(); bool force_model_selection = true; for (size_t i = 0; i < models.size(); i += 1) { if (models[i] == model) { @@ -78,23 +101,56 @@ int main(int argc, const char* argv[]) { } if (force_model_selection == true) { + message = "⚠ A Language model is not selected.\n"; if (interactive == true) { + ui.print_message(message); ui.print_model_list(models); ui.select_model(models, &model); - ui.print_args(model, prompt, stream, interactive, dark_theme); + ui.print_args(model, embedding_model, prompt, stream, interactive, dark_theme); } else { + UserInterface::print_message_noninteractive(message); UserInterface::print_model_list_noninteractive(models); UserInterface::select_model_noninteractive(models, &model); - UserInterface::print_args_noninteractive(model, prompt, stream, interactive, dark_theme); + UserInterface::print_args_noninteractive(model, embedding_model, prompt, stream, interactive, dark_theme); + } + } + + if (skip_embedding == false) { + bool force_embedding_model_selection = true; + for (size_t i = 0; i < models.size(); i += 1) { + if (models[i] == embedding_model) { + force_embedding_model_selection = false; + } + } + if (force_embedding_model_selection == true) { + message = "⚠ An Embedding model is not selected.\n"; + if (interactive == true) { + ui.print_message(message); + ui.print_model_list(models); + ui.select_model(models, &embedding_model); + ui.print_args(model, embedding_model, prompt, stream, interactive, dark_theme); + } else { + UserInterface::print_message_noninteractive(message); + UserInterface::print_model_list_noninteractive(models); + UserInterface::select_model_noninteractive(models, &embedding_model); + UserInterface::print_args_noninteractive(model, embedding_model, prompt, stream, interactive, + dark_theme); + } } } - struct OllamaPromptConfig config; config.model = model; + config.embedding_model = embedding_model; config.prompt = prompt; config.stream = stream; - client.query_model(config); + if (skip_embedding == false) { + std::vector urls = { + "https://raw.githubusercontent.com/rfprod/nx-ng-starter/refs/heads/main/README.md"}; + embedding_utils.create_embedings(urls); + } + + ollama_client.query_model(); if (interactive == true) { while (done == false) { @@ -104,7 +160,7 @@ int main(int argc, const char* argv[]) { } config.prompt = prompt; - client.query_model(config); + ollama_client.query_model(); ui.request_redraw(); } ui.end_session(EXIT_SUCCESS); diff --git a/src/ollama/ollama_client.cpp b/src/ollama/ollama_client.cpp index ce381ad..14fdec3 100644 --- a/src/ollama/ollama_client.cpp +++ b/src/ollama/ollama_client.cpp @@ -1,5 +1,6 @@ #include "ollama_client.hpp" #include +#include #include #include #include @@ -10,55 +11,42 @@ using nlohmann::json_abi_v3_11_2::json; /** - * Web content fetch result. - */ -struct WebContent { - std::string read_buffer; - char error_buffer[CURL_ERROR_SIZE]; - long status = 0; -}; - -/** - * CURL write callback for accumulating response data. + * Constructs an OllamaClient connected to a UserInterface. * - * Called by CURL whenever data is received. Appends the chunk to the - * userp string buffer. + * Initializes the Ollama API endpoint URLs, verifies the Ollama binary + * is installed, and creates a ProgressSpinner for network operations. * - * @param contents Pointer to the received data chunk. - * @param size Size of each element (always 1 for this use case). - * @param nmemb Number of elements received. - * @param userp Pointer to the std::string buffer to append data to. + * @param config Pointer to the Ollama Client configuration options. + * @param ui Pointer to the UserInterface for displaying output. + * @param curl Pointer to a CurlUtils instance for HTTP communication with Qdrant. + * @param system_utils Pointer to a SustemUtils instance for `system()` call status handling. * - * @return Total bytes processed (size * nmemb). + * @note Calls check_ollama() during construction. Exits if Ollama is not found. */ -static size_t WriteCallback(char* contents, size_t size, size_t nmemb, std::string* userp) { - userp->append(contents, size * nmemb); - return size * nmemb; -} - -/** - * Constructs an OllamaClient and initializes Ollama API endpoints. - * - * Sets up endpoint URLs for the local Ollama instance (localhost:11434), - * verifies that Ollama is installed, and creates a ProgressSpinner for - * use during network operations. - * - * Prints a newline in CLI mode for clean output formatting. - */ -OllamaClient::OllamaClient(UserInterface* ui) { - this->urls = {generate_url : "http://localhost:11434/api/generate", tags_url : "http://localhost:11434/api/tags"}; - this->curl = nullptr; - this->headers = nullptr; +OllamaClient::OllamaClient(OllamaClientConfig* config, UserInterface* ui, CurlUtils* curl, SystemUtils* system_utils) { + this->urls = { + generate_url : "http://localhost:11434/api/generate", + tags_url : "http://localhost:11434/api/tags", + embed_url : "http://localhost:11434/api/embed" + }; + + this->config = config; + this->curl = curl; this->ui = ui; - this->spinner = std::make_unique(ui, false); + this->system_utils = system_utils; this->check_ollama(); if (ui->is_running() == false) { - printf("\n"); + UserInterface::print_message_noninteractive("\n"); } } +OllamaClient::~OllamaClient() { + int status = system("echo \"\" > ~/.ollama/history"); + this->system_utils->catch_error(status); +} + /** * Verifies that the Ollama binary is available on the system. * @@ -68,6 +56,8 @@ OllamaClient::OllamaClient(UserInterface* ui) { * and exits or ends the session. * * Output is routed through the UserInterface (if available) or stdout/stderr. + * + * Displays a checkmark on success. */ void OllamaClient::check_ollama() { std::string message{}; @@ -75,7 +65,7 @@ void OllamaClient::check_ollama() { message = "Ollama binary does not exist.\nInstallation instructions: " "https://docs.ollama.com/linux\n"; if (this->ui->is_running() == false) { - fprintf(stderr, "āŒ %s", message.c_str()); + UserInterface::print_error_noninteractive(message); exit(0); } else { this->ui->print_error(message); @@ -84,60 +74,13 @@ void OllamaClient::check_ollama() { } else { message = "Ollama binary exists.\n"; if (this->ui->is_running() == false) { - printf("āœ… %s", message.c_str()); + UserInterface::print_success_noninteractive(message); } else { this->ui->print_success(message); } } }; -/** - * Initializes the CURL library and allocates a CURL handle. - * - * On failure, displays an error message and either exits (CLI mode) or - * ends the session (interactive mode). On success, displays a checkmark. - */ -void OllamaClient::init_curl() { - this->curl = curl_easy_init(); - std::string message{}; - if (!this->curl) { - message = "Failed to initialize CURL.\n"; - if (this->ui->is_running() == false) { - fprintf(stderr, "āŒ %s", message.c_str()); - exit(1); - } else { - this->ui->print_error(message); - this->ui->end_session(EXIT_FAILURE); - } - } else { - message = "CURL initialized.\n"; - if (this->ui->is_running() == false) { - printf("āœ… %s", message.c_str()); - } else { - this->ui->print_success(message); - } - } -} - -/** - * Configures CURL's progress callback for download tracking. - * - * Enables CURLOPT_NOPROGRESS and sets the progress callback function and - * data pointer. This allows the ProgressSpinner to update during network - * transfers. - * - * Does nothing if curl is nullptr. - */ -void OllamaClient::setup_progress_callback() { - if (this->curl == nullptr) { - return; - } - - curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); - curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, ProgressSpinner::progress_callback); - curl_easy_setopt(curl, CURLOPT_XFERINFODATA, spinner.get()); -} - /** * Removes leading and trailing whitespace from a string. * @@ -173,7 +116,9 @@ void OllamaClient::process_response(std::string response) { json response_json = json::parse(response); if (this->ui->is_running() == false) { - printf("šŸ¦™ llama:\n%s\n---\n", this->trim_response(response_json["response"].get()).c_str()); + std::string message = std ::format( + "šŸ¦™ llama:\n{}\n---\n", this->trim_response(response_json["response"].get()).c_str()); + UserInterface::print_message_noninteractive(message); } else { this->ui->print_message("šŸ¦™ llama:"); this->ui->print_message(this->trim_response(response_json["response"].get())); @@ -182,7 +127,7 @@ void OllamaClient::process_response(std::string response) { } catch (const json::exception& err) { std::string message = std::format("JSON parse error: {}\n", err.what()); if (this->ui->is_running() == false) { - fprintf(stderr, "āŒ %s", message.c_str()); + UserInterface::print_error_noninteractive(message); exit(1); } else { this->ui->print_error(message); @@ -211,7 +156,7 @@ void OllamaClient::process_response_stream(std::string response) { std::string text = "šŸ¦™ llama:\n"; if (this->ui->is_running() == false) { - this->ui->print_message_noninteractive(text); + UserInterface::print_message_noninteractive(text); } else { accumulated += text; } @@ -222,7 +167,7 @@ void OllamaClient::process_response_stream(std::string response) { json chunk = json::parse(line); text = chunk["response"].get(); if (this->ui->is_running() == false) { - this->ui->print_message_noninteractive(text); + UserInterface::print_message_noninteractive(text); } else { accumulated += text; @@ -238,7 +183,7 @@ void OllamaClient::process_response_stream(std::string response) { } catch (const json::exception& err) { std::string message = std::format("JSON parse error: {}\n", err.what()); if (this->ui->is_running() == false) { - fprintf(stderr, "āŒ %s", message.c_str()); + UserInterface::print_error_noninteractive(message); exit(1); } else { this->ui->print_error(message); @@ -250,124 +195,90 @@ void OllamaClient::process_response_stream(std::string response) { text = "\n---\n"; if (this->ui->is_running() == false) { - this->ui->print_message_noninteractive(text); + UserInterface::print_message_noninteractive(text); } else { this->ui->print_message(text); } } -std::string OllamaClient::fetch_web_content(const std::string& url, std::optional post_data) { - struct WebContent content {}; - std::string message{}; - - this->init_curl(); - - this->spinner->start(); - - curl_easy_setopt(this->curl, CURLOPT_URL, url.c_str()); - - if (post_data != std::nullopt) { - curl_easy_setopt(this->curl, CURLOPT_POSTFIELDS, post_data->c_str()); - } - - curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, WriteCallback); - curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, &content.read_buffer); - curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, content.error_buffer); - curl_easy_setopt(this->curl, CURLOPT_FOLLOWLOCATION, 1L); - - this->setup_progress_callback(); +/** + * Generates embeddings for a list of text strings using the Ollama embedding model. + * + * This method sends each text to the Ollama embedding endpoint and retrieves + * the corresponding embedding vectors. Embeddings are processed sequentially. + * + * @param texts A vector of text strings to embed + * @param config_opt Configuration object specifying the embedding model to use + * + * @return A vector of embedding vectors, where each inner vector contains + * the float values representing the embedding for the corresponding text. + * The order of embeddings matches the order of input texts. + * + * @throws std::exception if the web request fails or the response cannot be parsed + */ +std::vector> OllamaClient::generate_embeddings(const std::vector& texts, + std::optional config_opt) { + std::vector> embeddings{}; - this->headers = curl_slist_append(this->headers, "Content-Type: application/json"); - curl_easy_setopt(this->curl, CURLOPT_HTTPHEADER, this->headers); + json request_payload = { + {"model", config_opt != std::nullopt ? config_opt->embedding_model : config->embedding_model}, {"input", ""}}; - CURLcode result = curl_easy_perform(this->curl); - this->spinner->stop(); + for (const auto& text : texts) { + request_payload["input"] = text; - curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &content.status); + std::string post_data = request_payload.dump(); - curl_easy_cleanup(this->curl); - curl_slist_free_all(this->headers); - this->headers = nullptr; + std::string response = this->curl->fetch_web_content(this->urls.embed_url, post_data); - if (result != CURLE_OK) { - message = std::format("CURL error: {}\n", curl_easy_strerror(result)); - if (this->ui->is_running() == false) { - fprintf(stderr, "āŒ %s", message.c_str()); - if (content.error_buffer[0] != '\0') { - message = std::format("Details: {}\n", content.error_buffer); - fprintf(stderr, "%s", message.c_str()); - } - exit(1); - } else { - this->ui->print_error(message); - if (content.error_buffer[0] != '\0') { - message = std::format("Details: {}\n", content.error_buffer); - this->ui->print_error(message); - } - this->ui->end_session(EXIT_FAILURE); - } - } - if (content.status != 200) { - message = std::format("Ollama returned HTTP status: {}\n", content.status); +#ifdef DEBUG if (this->ui->is_running() == false) { - fprintf(stderr, "āŒ %s", message.c_str()); - exit(1); - } else { - this->ui->print_error(message); - this->ui->end_session(EXIT_FAILURE); + UserInterface::print_message_noninteractive( + std::format("\t[DEBUG] generate_embeddings response {}\n", response)); } +#endif + + const json data = json::parse(response); + + embeddings.push_back(data["embeddings"][0].get>()); } - return content.read_buffer; + return embeddings; } /** - * Sends a prompt to an Ollama model and displays the response. - * - * Executes the following workflow: - * 1. Initializes CURL and starts the progress spinner - * 2. Formats and displays the user's prompt via the UI - * 3. Constructs a JSON request payload with model, prompt, and stream settings - * 4. Sends a POST request to the Ollama generate endpoint - * 5. Validates HTTP response status (expects 200 OK) - * 6. Processes the response as either streamed or complete JSON - * 7. Cleans up CURL resources (handle and headers list) + * Sends a prompt query to the Ollama model and processes the response. * - * The prompt is displayed immediately with a "šŸ’¬ user:" prefix. The model's - * response is processed based on the stream setting: - * - If stream=true: Response chunks are printed incrementally as they arrive - * - If stream=false: Entire response is printed after completion + * Displays the formatted user message to either the console or UI based on + * the UI's running state, then constructs a JSON request payload with the + * model, prompt, and stream settings. Fetches the response from the Ollama + * server and processes it either as a stream or as a complete response. * - * @param config OllamaPromptConfig containing: - * - model: Name of the model to query (e.g., "llama2") - * - prompt: The text prompt to send - * - stream: Whether to stream the response - * - * @note Error handling depends on UI mode: - * - CLI mode: Prints error to stderr and calls exit(1) - * - Interactive mode: Calls ui->print_error() and ui->end_session(EXIT_FAILURE) - * - * @note CURL errors include network failures, connection timeouts, and invalid URLs. - * HTTP errors are reported when Ollama returns non-200 status codes. - * - * @warning The method will not return if an error occurs; it terminates the program - * or session instead. + * @param config_opt The prompt configuration containing the model name, prompt + * text, and stream preference */ -void OllamaClient::query_model(OllamaPromptConfig config) { - std::string message = std::format("šŸ’¬ user: {}\n", config.prompt.c_str()); +void OllamaClient::query_model(std::optional config_opt) { + std::string message = + std::format("šŸ’¬ user: {}\n", config_opt != std::nullopt ? config_opt->prompt.c_str() : config->prompt.c_str()); if (this->ui->is_running() == false) { - printf("%s", message.c_str()); + UserInterface::print_message_noninteractive(message); } else { this->ui->print_message(message); } - json request_payload = {{"model", config.model}, {"prompt", config.prompt}, {"stream", config.stream}}; + json request_payload; + if (config_opt != std::nullopt) { + request_payload = { + {"model", config_opt->model}, {"prompt", config_opt->prompt}, {"stream", config_opt->stream}}; + } else { + request_payload = {{"model", config->model}, {"prompt", config->prompt}, {"stream", config->stream}}; + } std::string post_data = request_payload.dump(); - std::string response = this->fetch_web_content(this->urls.generate_url, post_data); + std::string response = this->curl->fetch_web_content(this->urls.generate_url, post_data); - if (config.stream) { + bool stream = config_opt != std::nullopt ? config_opt->stream : config->stream; + if (stream) { this->process_response_stream(response); } else { this->process_response(response); @@ -375,42 +286,24 @@ void OllamaClient::query_model(OllamaPromptConfig config) { } /** - * Retrieves and displays all available models from the Ollama server. - * - * Executes the following workflow: - * 1. Initializes CURL and starts the progress spinner - * 2. Sends a GET request to the Ollama /api/tags endpoint - * 3. Validates HTTP response status (expects 200 OK) - * 4. Parses the JSON response to extract the "models" array - * 5. Displays each model with metadata in a formatted table - * 6. Cleans up CURL resources (handle and headers list) - * - * For each model, displays: - * - Last modified timestamp - * - Size in megabytes (or "size unknown" if unavailable) - * - Model name - * - * Output format: "{modified_at}\t ({size_mb}) \t{name}" - * - * @note Error handling depends on UI mode: - * - CLI mode: Prints error to stderr and calls exit(1) - * - Interactive mode: Calls ui->print_error() and ui->end_session(EXIT_FAILURE) - * - * @note Errors may occur at multiple stages: - * - CURL errors: Network failures, connection issues - * - HTTP errors: Non-200 response codes from Ollama - * - JSON errors: Malformed response or missing "models" field + * Retrieves a list of available models from the Ollama server. * - * @warning The method will not return if an error occurs; it terminates the program - * or session instead. + * Fetches the models list from the Ollama tags endpoint and parses the JSON + * response. Validates that the response contains a valid models array. Extracts + * and displays model metadata including name, modification timestamp, and size + * (converted from bytes to megabytes). Collects valid model names into a vector + * for return. Handles errors (invalid response structure or JSON parsing failures) + * by terminating with an error message directed to either stderr or the UI based + * on the UI's running state. * - * @see OllamaPromptConfig for model information structure + * @return A vector of available model names extracted from the server response. + * Returns an empty vector if an error occurs during fetch or parsing. */ std::vector OllamaClient::query_model_list() { std::string message{}; std::vector models; - std::string response = this->fetch_web_content(this->urls.tags_url); + std::string response = this->curl->fetch_web_content(this->urls.tags_url); try { const json data = json::parse(response); @@ -418,7 +311,7 @@ std::vector OllamaClient::query_model_list() { if (!data.contains("models") || !data["models"].is_array()) { message = "Response has no models array.\n"; if (this->ui->is_running() == false) { - fprintf(stderr, "āŒ %s", message.c_str()); + UserInterface::print_error_noninteractive(message); exit(1); } else { this->ui->print_error(message); @@ -428,7 +321,7 @@ std::vector OllamaClient::query_model_list() { message = "šŸ“ƒ available models:\n"; if (this->ui->is_running() == false) { - printf("%s", message.c_str()); + UserInterface::print_message_noninteractive(message); } else { this->ui->print_message(message); } @@ -446,16 +339,16 @@ std::vector OllamaClient::query_model_list() { message = std::format("{}\t ({}) \t{}\n", modified_at, size, name); if (this->ui->is_running() == false) { - printf("%s", message.c_str()); + UserInterface::print_message_noninteractive(message); } else { this->ui->print_message(message); } } - printf("\n"); + UserInterface::print_message_noninteractive("\n"); } catch (const json::exception& err) { message = std::format("JSON parse error: {}\n", err.what()); if (this->ui->is_running() == false) { - fprintf(stderr, "āŒ %s", message.c_str()); + UserInterface::print_error_noninteractive(message); exit(1); } else { this->ui->print_error(message); diff --git a/src/ollama/ollama_client.hpp b/src/ollama/ollama_client.hpp index 78e19de..ae9e262 100644 --- a/src/ollama/ollama_client.hpp +++ b/src/ollama/ollama_client.hpp @@ -1,7 +1,9 @@ #pragma once #include "interface/progress_spinner.hpp" -#include "interface/user-interface.hpp" +#include "interface/user_interface.hpp" +#include "utils/curl_utils.hpp" +#include "utils/system_utils.hpp" #include #include #include @@ -13,8 +15,9 @@ * @param prompt The text prompt to send to the model. * @param stream Whether to stream the response (true) or receive it all at once (false). */ -struct OllamaPromptConfig { +struct OllamaClientConfig { std::string model; + std::string embedding_model; std::string prompt; bool stream; }; @@ -24,207 +27,72 @@ struct OllamaPromptConfig { * * @param generate_url The endpoint for querying a model. * @param tags_url The endpoint for listing available models. + * @param embed_url The endpoint for creating embeddings. */ struct OllamaServerURLs { std::string generate_url; std::string tags_url; + std::string embed_url; }; /** - * Client for communicating with a local Ollama instance. + * Client for interacting with the Ollama API server. * - * OllamaClient manages HTTP requests to Ollama's REST API, handling both - * model queries and model listing. It integrates with a UserInterface for - * displaying messages and errors, and uses ProgressSpinner to provide - * visual feedback during network operations. + * Manages communication with an Ollama server instance, providing functionality + * to query language models, retrieve available models, and generate embeddings. + * Encapsulates HTTP communication via CURL, response parsing, and dual-mode + * output (console or interactive UI) based on the running state of the user + * interface. Validates server connectivity on initialization and handles errors + * with appropriate logging to either stderr or the UI. * - * The client verifies that the Ollama binary is installed on the system - * and initializes CURL for HTTP communication. All responses are parsed - * as JSON and formatted for display. - * - * @note Designed for local Ollama instances running on localhost:11434. - * - * @example Query a model: - * @code - * UserInterface ui; - * OllamaClient client(&ui); - * - * OllamaPromptConfig config{ - * .model = "llama2", - * .prompt = "What is machine learning?", - * .stream = false - * }; - * client.query_model(config); - * @endcode - * - * @example List available models: - * @code - * UserInterface ui; - * OllamaClient client(&ui); - * client.query_model_list(); - * @endcode + * The client uses pre-configured API endpoint URLs and delegates HTTP operations + * to a CURL wrapper utility. Responses from the server are processed and + * displayed to the user through the provided UI interface. */ class OllamaClient { private: - /** - * CURL handle for HTTP requests. Initialized in init_curl(). - */ - CURL* curl; - /** * API endpoint URLs for the Ollama server. */ OllamaServerURLs urls; /** - * CURL headers list for HTTP requests (Content-Type, etc.). - * Allocated in query methods and freed after each request. + * Pointer to the Ollama Client configuraion. */ - struct curl_slist* headers; + OllamaClientConfig* config; /** * Pointer to the UserInterface for displaying messages and errors. - * Used for both CLI and interactive UI output. */ UserInterface* ui; /** - * Progress spinner for visual feedback during network operations. - * Managed via std::unique_ptr for automatic cleanup. - */ - std::unique_ptr spinner; - - /** - * Verifies that the Ollama binary is available on the system. - * - * Uses the `which` command to check for Ollama in the PATH. If not found, - * displays an error message and either exits (CLI mode) or ends the session - * (interactive mode). - * - * Displays a checkmark on success. + * Pointer to the CURL wrapper containing pre-configured internal logic. */ - void check_ollama(); + CurlUtils* curl; /** - * Initializes the CURL library and allocates a CURL handle. - * - * If initialization fails, displays an error message and exits or ends - * the session depending on the UI state. - * - * Displays a checkmark on success. + * Pointer to the SystemUtils for processing `system()` calls. */ - void init_curl(); + SystemUtils* system_utils; - /** - * Configures the CURL progress callback for download tracking. - * - * Sets up CURLOPT_XFERINFOFUNCTION and CURLOPT_XFERINFODATA to enable - * progress tracking during HTTP transfers via the ProgressSpinner. - * - * @note Must be called before curl_easy_perform(). - */ - void setup_progress_callback(); + void check_ollama(); - /** - * Removes leading and trailing whitespace from a string. - * - * Uses std::find_if with lambda predicates to efficiently trim both ends - * without creating intermediate strings. - * - * @param response The input string to trim. - * @return The trimmed string. - */ std::string trim_response(std::string response); - /** - * Parses and displays a complete (non-streamed) JSON response from Ollama. - * - * Extracts the "response" field from the JSON and displays it formatted - * with a llama emoji. If JSON parsing fails, displays an error and exits - * or ends the session. - * - * @param response The complete JSON response from the Ollama API. - */ void process_response(std::string response); - /** - * Parses and displays a streamed JSON response from Ollama. - * - * Processes the response as newline-delimited JSON chunks, extracting - * the "response" field from each chunk and printing it incrementally. - * Stops processing when a chunk has "done" set to true. - * - * @param response The complete streamed response (newline-delimited JSON). - */ void process_response_stream(std::string response); - /** - * Fetches web content from the specified URL via HTTP/HTTPS request. - * - * Performs an HTTP GET or POST request to the given URL using libcurl, - * with automatic redirect following and JSON content-type header. - * Shows a spinner while the request is in progress. - * - * @param url The target URL to fetch from. Must be a valid URL string. - * @param post_data Optional POST request body. If provided, the request - * will be a POST request; otherwise a GET request. - * Defaults to std::nullopt (GET request). - * - * @return A WebContent struct containing the response body buffer, - * HTTP status code, and error buffer. - * - * @throws Calls exit(1) on CURL errors or non-200 HTTP status codes - * if the UI is not running. If UI is running, terminates the - * session with EXIT_FAILURE instead. - * - * @note Initializes and cleans up CURL resources internally. - * Automatically manages HTTP headers and follows redirects. - */ - std::string fetch_web_content(const std::string& url, std::optional post_data = std::nullopt); - public: - /** - * Constructs an OllamaClient connected to a UserInterface. - * - * Initializes the Ollama API endpoint URLs, verifies the Ollama binary - * is installed, and creates a ProgressSpinner for network operations. - * - * @param ui Pointer to the UserInterface for displaying output. Must remain - * valid for the lifetime of this OllamaClient. - * - * @note Calls check_ollama() during construction. Exits if Ollama is not found. - */ - explicit OllamaClient(UserInterface* ui); + explicit OllamaClient(OllamaClientConfig* config, UserInterface* ui, CurlUtils* curl, SystemUtils* system_utils); - /** - * Sends a prompt to an Ollama model and displays the response. - * - * Performs the following steps: - * 1. Initializes CURL - * 2. Starts the progress spinner - * 3. Builds a JSON request with the model, prompt, and stream settings - * 4. Sends a POST request to the generate endpoint - * 5. Processes the response (streamed or complete) - * 6. Cleans up CURL resources - * - * Displays both the user's prompt and the model's response via the UI. - * Handles both CLI and interactive UI modes. - * - * @param config Configuration containing the model name, prompt, and stream setting. - * - * @note On error, displays an error message and exits or ends the session. - */ - void query_model(OllamaPromptConfig config); + ~OllamaClient(); + + std::vector> generate_embeddings(const std::vector& texts, + std::optional config_opt = std::nullopt); + + void query_model(std::optional config_opt = std::nullopt); - /** - * Retrieves and displays a list of available models from the Ollama server. - * - * Sends a GET request to the /api/tags endpoint and parses the response - * to extract model metadata (name, size, modification date). Displays - * each model with its information formatted as a table. - * - * @note On error, displays an error message and exits or ends the session. - * @returns The list of available local models. - */ std::vector query_model_list(); }; diff --git a/src/storage/qdrant_client.cpp b/src/storage/qdrant_client.cpp new file mode 100644 index 0000000..d2eaa62 --- /dev/null +++ b/src/storage/qdrant_client.cpp @@ -0,0 +1,401 @@ +#include "qdrant_client.hpp" +#include +#include +#include +#include + +using nlohmann::json_abi_v3_11_2::json; + +/** + * Initializes a QdrantClient instance with the provided UI and networking utilities. + * Constructs the base URL from the QDRANT_URL environment variable, defaulting to the local Qdrant service. + * Performs an immediate health check of the Qdrant service upon construction. + * + * @param ui Pointer to a UserInterface instance for status message output. + * @param curl Pointer to a CurlUtils instance for HTTP communication with Qdrant. + * @param system_utils Pointer to a SustemUtils instance for `system()` call status handling. + * + * @note Constructor calls check_qdrant() as a side effect, which may produce console or UI output. + */ +QdrantClient::QdrantClient(UserInterface* ui, CurlUtils* curl, SystemUtils* system_utils) { + this->curl = curl; + this->ui = ui; + this->system_utils = system_utils; + + this->setup(); + + sleep(1); + + const std::string& base_url = std::getenv("QDRANT_URL") ? std::getenv("QDRANT_URL") : "http://localhost:6333"; + this->urls = { + collections_url : std::format("{}/collections", base_url), + }; + + this->check_qdrant(); + + if (ui->is_running() == false) { + UserInterface::print_message_noninteractive("\n"); + } +} + +/** + * Cleans up Docker resources associated with the Qdrant container and network. + * Stops and removes the qdrant-rag-app container and destroys the app-rag-net Docker network. + * Suppresses errors during cleanup to ensure all resources are removed even if individual commands fail. + * + * @note This destructor is called automatically when the QdrantClient instance is destroyed. + */ +QdrantClient::~QdrantClient() { + int status; + std::string message{}; + + message = "šŸ›ˆ Qdrant docker container cleanup...\n"; + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_message(message); + } + + status = system("docker stop qdrant-rag-app >/dev/null 2>&1 || true"); + this->system_utils->catch_error(status); + + status = system("docker rm qdrant-rag-app >/dev/null 2>&1 || true"); + this->system_utils->catch_error(status); + + status = system("docker network rm app-rag-net >/dev/null 2>&1 || true"); + this->system_utils->catch_error(status); + + message = "Done.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_success_noninteractive(message); + } else { + this->ui->print_success(message); + } +} + +/** + * Initializes and starts the Qdrant Docker container with necessary configuration. + * Pulls the Qdrant image, validates the QDRANT_API_KEY and QDRANT_API_KEY_READ_ONLY environment variables, + * creates a persistent data directory, establishes a Docker network, and launches the container with API key + * authentication. If a Qdrant container is already running, this method returns early without restarting it. + * + * @throws Exits with status code 1 if required environment variables are missing or container startup fails. + * + * @note This method should be called before check_qdrant() to ensure the service is available. + * @note Does not wait for the container to be fully operational; health verification is delegated to check_qdrant(). + */ +void QdrantClient::setup() { + int status; + std::string message{}; + + status = system("docker pull qdrant/qdrant"); + this->system_utils->catch_error(status); + + status = system("docker ps | grep -q qdrant"); + if (status == 0) { + message = "Qdrant is already running. Skipping docker run.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_success_noninteractive(message); + } else { + this->ui->print_success(message); + } + return; + } + + message = "šŸ›ˆ Starting Qdrant container...\n"; + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_message(message); + } + + const char* qdrant_key = std::getenv("QDRANT_API_KEY"); + const char* qdrant_key_readonly = std::getenv("QDRANT_API_KEY_READ_ONLY"); + + if (!qdrant_key || std::string(qdrant_key).empty()) { + message = "QDRANT_API_KEY not set.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + + exit(1); + } + + if (!qdrant_key_readonly || std::string(qdrant_key_readonly).empty()) { + message = "QDRANT_API_KEY_READ_ONLY not set.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + + exit(1); + } + + const std::string data_dir = std::string(std::getenv("HOME")) + "/qdrant"; + std::string mkdir_cmd = std::string("mkdir -p ") + data_dir; + status = system(mkdir_cmd.c_str()); + this->system_utils->catch_error(status); + + status = system("docker network create app-rag-net 2>/dev/null || true"); + this->system_utils->catch_error(status); + + std::string docker_run_cmd = + std::format("docker run -d --name qdrant-rag-app --restart always --network app-rag-net " + "-p 6333:6333 -p 6334:6334 -v {}:/qdrant/storage " + "-e QDRANT_API_KEY='{}' -e QDRANT_API_KEY_READ_ONLY='{}' qdrant/qdrant:latest", + data_dir, qdrant_key, qdrant_key_readonly); + + if (system(docker_run_cmd.c_str()) != 0) { + message = "Failed to start Qdrant container.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + + exit(1); + } + + message = std::format("šŸ›ˆ Qdrant container started with data dir {}\n", data_dir.c_str()); + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_message(message); + } + + message = "šŸ›ˆ Qdrant dashboard is available at http://localhost:6333/dashboard\n"; + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_message(message); + } +} + +/** + * Checks the health status of the Qdrant service using the configured API endpoint. + * Retrieves the API key from the QDRANT_API_KEY environment variable for authentication. + * Outputs a status message (success, error, or warning) to the UI or console based on the HTTP response code. + */ +void QdrantClient::check_qdrant() { + std::string message{}; + + const char* qdrant_key = std::getenv("QDRANT_API_KEY"); + long status = this->curl->wait_for_service(this->urls.collections_url, {{"api-key", qdrant_key}}); + + if (status == 200) { + message = "Qdrant is healthy.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_success_noninteractive(message); + } else { + this->ui->print_success(message); + } + } else if (status == -1) { + message = "Failed to connect to Qdrant.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + } else { + message = std::format("āš ļø Qdrant returned {}.\n", status); + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_message(message); + } + } +}; + +/** + * @brief Checks if a collection exists in Qdrant. + * @param collection_name The name of the collection to check. + * @return true if the collection exists, false otherwise. + */ +bool QdrantClient::collection_exists(const std::string& collection_name) { + std::string message{}; + + const char* qdrant_key = std::getenv("QDRANT_API_KEY"); + std::string url = std::format("{}/{}", this->urls.collections_url, collection_name); + + std::map headers{{"api-key", qdrant_key}}; + + try { + this->curl->fetch_web_content(url, std::nullopt, "GET", headers, false); + message = std::format("Collection '{}' exists", collection_name); + if (this->ui->is_running() == false) { + UserInterface::print_success_noninteractive(message); + } else { + this->ui->print_success(message); + } + return true; + } catch (...) { + message = std::format("āš ļø Collection '{}' does not exist", collection_name); + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_message(message); + } + return false; + } +} + +/** + * @brief Deletes a collection from Qdrant. + * @param collection_name The name of the collection to delete. + */ +void QdrantClient::delete_collection(const std::string& collection_name) { + const char* qdrant_key = std::getenv("QDRANT_API_KEY"); + std::string url = std::format("{}/{}", this->urls.collections_url, collection_name); + + std::map headers{{"api-key", qdrant_key}}; + + try { + this->curl->fetch_web_content(url, std::nullopt, "DELETE", headers); + + std::string message = std::format("Deleted collection '{}'\n", collection_name); + if (this->ui->is_running() == false) { + UserInterface::print_success_noninteractive(message); + } else { + this->ui->print_success(message); + } + } catch (const HttpException& e) { + std::string message = + std::format("[{}] Failed to delete collection '{}': {}\n", e.get_status_code(), collection_name, e.what()); + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + throw; + } +} + +/** + * @brief Creates a new collection in Qdrant. + * @param collection_name The name of the collection to create. + * @param vector_size The dimensionality of the vectors (e.g., 384 for embeddinggemma:latest). + */ +void QdrantClient::create_collection(const std::string& collection_name, size_t vector_size) { + const char* qdrant_key = std::getenv("QDRANT_API_KEY"); + + json config = {{"vectors", {{"size", vector_size}, {"distance", "Cosine"}}}}; + + std::string url = std::format("{}/{}", this->urls.collections_url, collection_name); + std::string post_data = config.dump(); + + std::map headers{{"api-key", qdrant_key}}; + + try { + this->curl->fetch_web_content(url, post_data, "PUT", headers); + + std::string message = + std::format("Created collection '{}' with vector size {}\n", collection_name, vector_size); + if (this->ui->is_running() == false) { + UserInterface::print_success_noninteractive(message); + } else { + this->ui->print_success(message); + } + } catch (const HttpException& e) { + std::string message = + std::format("[{}] Failed to create collection '{}': {}\n", e.get_status_code(), collection_name, e.what()); + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + throw; + } +} + +/** + * Stores text documents and their corresponding embeddings into the Qdrant collection. + * Constructs points from the provided texts and embeddings, then sends them to the Qdrant service via PUT request. + * Authentication is performed using the QDRANT_API_KEY environment variable. + * + * @param texts A vector of text strings to be stored as payloads in Qdrant points. + * @param embeddings A vector of embedding vectors (floats) corresponding to each text string. + * + * @note The size of texts and embeddings vectors should match; behavior is undefined if they differ. + */ +void QdrantClient::store(const std::vector& texts, const std::vector>& embeddings) { + std::string message{}; + const char* qdrant_key = std::getenv("QDRANT_API_KEY"); + const std::string collection_name = "rag-app"; + + if (texts.empty() || embeddings.empty()) { + message = "Cannot store: texts or embeddings are empty\n"; + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + return; + } + + if (texts.size() != embeddings.size()) { + message = std::format("Mismatch: {} texts but {} embeddings\n", texts.size(), embeddings.size()); + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + return; + } + + size_t vector_size = embeddings[0].size(); + +#ifdef DEBUG + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive( + std::format("\t[DEBUG] Checking collection '{}'\n", collection_name)); + } +#endif + + if (this->collection_exists(collection_name)) { +#ifdef DEBUG + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive( + std::format("\t[DEBUG] Collection '{}' exists, deleting...\n", collection_name)); + } +#endif + this->delete_collection(collection_name); + } + +#ifdef DEBUG + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive( + std::format("\t[DEBUG] Creating collection '{}' with vector size {}\n", collection_name, vector_size)); + } +#endif + this->create_collection(collection_name, vector_size); + + json points = json::array(); + for (size_t i = 0; i < texts.size(); i += 1) { + points.push_back({{"id", i}, {"vector", embeddings[i]}, {"payload", {{"text", texts[i]}}}}); + } + + json request_payload = {{"points", points}}; + + std::string url = std::format("{}/{}/points", this->urls.collections_url, collection_name); + std::string post_data = request_payload.dump(); + + std::map headers{{"api-key", qdrant_key}}; + +#ifdef DEBUG + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive( + std::format("\t[DEBUG] Storing {} embeddings to URL: {}\n", texts.size(), url)); + } +#endif + std::string response = this->curl->fetch_web_content(url, post_data, "PUT", headers); + + message = std::format("Stored {} embeddings in Qdrant.\nResponse: {}\n", texts.size(), response); + if (this->ui->is_running() == false) { + UserInterface::print_success_noninteractive(message); + } else { + this->ui->print_success(message); + } +} diff --git a/src/storage/qdrant_client.hpp b/src/storage/qdrant_client.hpp new file mode 100644 index 0000000..869ef36 --- /dev/null +++ b/src/storage/qdrant_client.hpp @@ -0,0 +1,85 @@ +#pragma once + +#include "interface/user_interface.hpp" +#include "utils/curl_utils.hpp" +#include "utils/system_utils.hpp" +#include +#include + +/** + * URLs for Qdrant API endpoints. + * + * @param collections_url The endpoint for querying collections. + */ +struct QdrantServerURLs { + std::string collections_url; +}; + +/** + * Manages the lifecycle and API interaction with a Qdrant vector database server running in Docker. + * + * The QdrantClient class is responsible for: + * - Automatically pulling and starting a Qdrant Docker container during construction + * - Validating required environment variables (QDRANT_API_KEY, QDRANT_API_KEY_READ_ONLY) + * - Creating and managing a Docker network for inter-service communication + * - Verifying server health and availability + * - Storing text embeddings as vector points in the Qdrant database + * - Cleaning up Docker resources during destruction + * + * The Qdrant server listens on localhost:6333 (gRPC) and localhost:6334 (HTTP API) by default, + * with configuration via the QDRANT_URL environment variable. + * + * Lifecycle: + * - Constructor calls setup() to initialize Docker resources and check_qdrant() to verify connectivity. + * - Destructor automatically stops and removes the container and associated network. + * + * @param ui Pointer to UserInterface for displaying status messages and errors. + * Must remain valid for the lifetime of this QdrantClient instance. + * @param curl Pointer to CurlUtils for executing HTTP requests to the Qdrant API. + * Must remain valid for the lifetime of this QdrantClient instance. + * + * @note Requires Docker to be installed and running on the host system. + * @note Environment variables QDRANT_API_KEY and QDRANT_API_KEY_READ_ONLY must be set before construction. + * @note Creates persistent data directory at $HOME/qdrant for container use. + * @note Creates Docker network app-rag-net for service communication. + */ +class QdrantClient { + private: + /** + * API endpoint URLs for the Qdrant server. + */ + QdrantServerURLs urls; + + /** + * Pointer to the UserInterface for displaying messages and errors. + * Used for both CLI and interactive UI output. + */ + UserInterface* ui; + + /** + * Pointer to the SystemUtils for processing `system()` calls. + */ + SystemUtils* system_utils; + + /** + * A CURL wrapper containing pre-configured internal logic. + */ + CurlUtils* curl; + + void setup(); + + void check_qdrant(); + + bool collection_exists(const std::string& collection_name); + + void delete_collection(const std::string& collection_name); + + void create_collection(const std::string& collection_name, size_t vector_size); + + public: + explicit QdrantClient(UserInterface* ui, CurlUtils* curl, SystemUtils* system_utils); + + ~QdrantClient(); + + void store(const std::vector& texts, const std::vector>& embeddings); +}; diff --git a/src/utils/curl_utils.cpp b/src/utils/curl_utils.cpp new file mode 100644 index 0000000..db64e2d --- /dev/null +++ b/src/utils/curl_utils.cpp @@ -0,0 +1,327 @@ +#include "curl_utils.hpp" +#include +#include + +/** + * CURL write callback for accumulating response data. + * + * Called by CURL whenever data is received. Appends the chunk to the + * userp string buffer. + * + * @param contents Pointer to the received data chunk. + * @param size Size of each element (always 1 for this use case). + * @param nmemb Number of elements received. + * @param userp Pointer to the std::string buffer to append data to. + * + * @return Total bytes processed (size * nmemb). + */ +static size_t WriteCallback(char* contents, size_t size, size_t nmemb, std::string* userp) { + userp->append(contents, size * nmemb); + return size * nmemb; +} + +/** + * Constructs a CurlUtils instance with dependency injection. + * + * Initializes CURL and headers pointers to nullptr, stores the provided + * UserInterface pointer for logging and status messages, and creates a + * ProgressSpinner instance for visual feedback during network operations. + * The actual CURL easy handle initialization is deferred to the initialize() + * method, typically called after object construction. + * + * @param ui Pointer to the UserInterface for displaying messages and progress + */ +CurlUtils::CurlUtils(UserInterface* ui) { + this->curl = nullptr; + this->headers = nullptr; + this->ui = ui; + this->spinner = std::make_unique(ui, false); +} + +CurlUtils::~CurlUtils() { + this->cleanup(); +} + +/** + * Initializes the CURL easy handle for HTTP operations. + * + * Attempts to create a CURL easy handle via curl_easy_init(). If initialization + * fails, logs an error message to either stderr or the UI based on the UI's + * running state and terminates the program with EXIT_FAILURE. On successful + * initialization, logs a confirmation message to either the console or UI. + * + * @throws Indirectly exits the program if CURL initialization fails. + */ +void CurlUtils::initialize() { + this->curl = curl_easy_init(); + std::string message{}; + if (!this->curl) { + message = "āŒ Failed to initialize CURL.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + exit(1); + } else { + this->ui->print_error(message); + this->ui->end_session(EXIT_FAILURE); + } + } else { + message = "āœ… CURL is initialized.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_success(message); + } + } +} + +/** + * Cleans up CURL resources and frees allocated memory. + * + * Destroys the CURL easy handle and frees the headers list. Sets the headers + * pointer to nullptr to prevent use-after-free. Logs a success message to + * either the console or UI based on the UI's running state. Typically called + * during object destruction or when shutting down HTTP operations. + * + * @note Assumes cleanup operations succeed without error checking. + */ +void CurlUtils::cleanup() { + curl_easy_cleanup(this->curl); + curl_slist_free_all(this->headers); + this->headers = nullptr; + std::string message = "āœ… CURL cleanup is complete.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_success(message); + } +} + +/** + * @brief Checks service availability by querying an HTTP endpoint and returning the HTTP status code. + * + * Makes a silent HEAD request to the specified URL with optional custom headers, + * discards the response body, and returns the HTTP status code. + * On curl failure, returns -1. + * + * @param url Target endpoint URL (e.g., "http://localhost:6333/collections"). + * @param extra_headers Map of custom headers to include (e.g., {"api-key": "secret", "Authorization": "Bearer + * token"}). If empty, request is sent without additional headers. + * @param timeout_seconds Connection and transfer timeout in seconds (default: 5). + * @return HTTP status code on success (e.g., 200, 401, 404); -1 on curl failure. + * @note Initializes and cleans up curl handle internally; manages spinner lifecycle. + * @see initialize(), cleanup() + */ +long CurlUtils::check_service_status(const std::string& url, const std::map& extra_headers, + long timeout_seconds) { + this->initialize(); + this->spinner->start(); + + long http_code = 0; + + curl_easy_setopt(this->curl, CURLOPT_URL, url.c_str()); + + curl_easy_setopt(this->curl, CURLOPT_CUSTOMREQUEST, "GET"); + + curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, + [](void*, size_t size, size_t nmemb, void*) { return size * nmemb; }); + curl_easy_setopt(this->curl, CURLOPT_TIMEOUT, timeout_seconds); + curl_easy_setopt(this->curl, CURLOPT_CONNECTTIMEOUT, timeout_seconds); + curl_easy_setopt(this->curl, CURLOPT_FOLLOWLOCATION, 1L); + + curl_easy_setopt(this->curl, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(this->curl, CURLOPT_XFERINFOFUNCTION, ProgressSpinner::progress_callback); + curl_easy_setopt(this->curl, CURLOPT_XFERINFODATA, this->spinner.get()); + + this->headers = curl_slist_append(this->headers, "Content-Type: application/json"); + + for (const auto& [key, value] : extra_headers) { + std::string header = key + ": " + value; + this->headers = curl_slist_append(this->headers, header.c_str()); + } + + curl_easy_setopt(this->curl, CURLOPT_HTTPHEADER, this->headers); + + CURLcode res = curl_easy_perform(this->curl); + this->spinner->stop(); + + curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &http_code); + + this->cleanup(); + + if (res != CURLE_OK) { + std::string message = std::format("Curl error: {}\n", curl_easy_strerror(res)); + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + + return -1; + } + return http_code; +} + +/** + * @brief Waits for a service to become available with retries and exponential backoff. + * + * @param url Target endpoint URL. + * @param extra_headers Map of custom headers. + * @param max_retries Number of retry attempts (default: 10). + * @param initial_delay_ms Initial delay in milliseconds (default: 500ms). + * @return HTTP status code on success; -1 if service unavailable after retries. + */ +long CurlUtils::wait_for_service(const std::string& url, const std::map& extra_headers, + int max_retries, int initial_delay_ms) { + long http_code = -1; + int delay_ms = initial_delay_ms; + std::string message{}; + + for (int attempt = 0; attempt < max_retries; attempt += 1) { + http_code = this->check_service_status(url, extra_headers); + + if (http_code != -1) { + message = std::format("āœ… Service available (HTTP {}) after {} attempt(s)\n", http_code, attempt + 1); + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_success(message); + } + return http_code; + } + + if (attempt < max_retries - 1) { + message = std::format("ā³ Waiting for service... (attempt {}/{}, retrying in {}ms)\n", attempt + 1, + max_retries, delay_ms); + if (this->ui->is_running() == false) { + UserInterface::print_message_noninteractive(message); + } else { + this->ui->print_message(message); + } + std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); + delay_ms = std::min(delay_ms * 2, 5000); + } + } + + message = std::format("Service unavailable after {} attempts\n", max_retries); + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + return http_code; +} + +/** + * @brief Fetches web content from the specified URL via HTTP/HTTPS request. + * + * Performs an HTTP GET or POST request to the given URL using libcurl, + * with automatic redirect following and JSON content-type header. + * Shows a spinner while the request is in progress. + * + * @param url The target URL to fetch from. Must be a valid URL string. + * @param post_data Optional POST request body. If provided, the request + * will be a POST request; otherwise a GET request. + * Defaults to std::nullopt (GET request). + * @param custom_request_type Custom request type: GET, POST, PUT. Primarily used for PUT. + * @param extra_headers Optional map of custom headers to include (e.g., {"Authorization": "Bearer token"}). + * Content-Type application/json is always added automatically. + * Defaults to std::nullopt (no extra headers). + * @param fail_on_http_error If false, returns response body even on non-200 status codes. + * If true (default), exits on non-200 status. Used for existence checks. + * Defaults to true. + * + * @return A string containing the response body. + * + * @throws Calls exit(1) on CURL errors or non-200 HTTP status codes + * if the UI is not running. If UI is running, terminates the + * session with EXIT_FAILURE instead. + * + * @note Initializes and cleans up CURL resources internally. + * Automatically manages HTTP headers and follows redirects. + * @see check_service_status() + */ +std::string CurlUtils::fetch_web_content(const std::string& url, std::optional post_data, + std::optional custom_request_type, + std::optional> extra_headers, + bool fail_on_http_error) { + struct WebContent content {}; + std::string message{}; + + this->initialize(); + this->spinner->start(); + + curl_easy_setopt(this->curl, CURLOPT_URL, url.c_str()); + + if (post_data != std::nullopt) { + curl_easy_setopt(this->curl, CURLOPT_POSTFIELDS, post_data->c_str()); + } + + if (custom_request_type != std::nullopt) { + curl_easy_setopt(this->curl, CURLOPT_CUSTOMREQUEST, custom_request_type->c_str()); + } + + curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, WriteCallback); + curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, &content.read_buffer); + curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, content.error_buffer); + curl_easy_setopt(this->curl, CURLOPT_FOLLOWLOCATION, 1L); + + curl_easy_setopt(this->curl, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(this->curl, CURLOPT_XFERINFOFUNCTION, ProgressSpinner::progress_callback); + curl_easy_setopt(this->curl, CURLOPT_XFERINFODATA, this->spinner.get()); + + this->headers = curl_slist_append(this->headers, "Content-Type: application/json"); + + if (extra_headers != std::nullopt) { + for (const auto& [key, value] : extra_headers.value()) { + std::string header = key + ": " + value; + this->headers = curl_slist_append(this->headers, header.c_str()); + } + } + + curl_easy_setopt(this->curl, CURLOPT_HTTPHEADER, this->headers); + + CURLcode result = curl_easy_perform(this->curl); + this->spinner->stop(); + + curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &content.status); + + this->cleanup(); + + if (result != CURLE_OK) { + message = std::format("CURL error: {}\n", curl_easy_strerror(result)); + if (this->ui->is_running() == false) { + if (content.error_buffer[0] != '\0') { + message += std::format("Details: {}\n", content.error_buffer); + } + UserInterface::print_error_noninteractive(message); + exit(1); + } else { + this->ui->print_error(message); + if (content.error_buffer[0] != '\0') { + message = std::format("Details: {}\n", content.error_buffer); + this->ui->print_error(message); + } + this->ui->end_session(EXIT_FAILURE); + } + } + if (content.status != 200) { + message = std::format("Request HTTP status: {}\n", content.status); + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + if (fail_on_http_error == true) { + exit(1); + } else { + throw HttpException(content.status, url); + } + } else { + this->ui->print_error(message); + if (fail_on_http_error == true) { + this->ui->end_session(EXIT_FAILURE); + } else { + throw HttpException(content.status, url); + } + } + } + + return content.read_buffer; +} diff --git a/src/utils/curl_utils.hpp b/src/utils/curl_utils.hpp new file mode 100644 index 0000000..8b5baa7 --- /dev/null +++ b/src/utils/curl_utils.hpp @@ -0,0 +1,76 @@ +#pragma once + +#include "http_utils.hpp" +#include "interface/progress_spinner.hpp" +#include "interface/user_interface.hpp" +#include +#include +#include +#include +#include + +/** + * Web content fetch result. + */ +struct WebContent { + std::string read_buffer; + char error_buffer[CURL_ERROR_SIZE]; + long status = 0; +}; + +/** + * CURL HTTP client wrapper for making web requests to the Ollama server. + * + * Provides a simplified interface for HTTP operations by encapsulating CURL + * initialization, request execution, and resource cleanup. Manages CURL easy + * handles and HTTP headers, with support for both GET and POST requests via + * optional POST data parameter. Integrates with the UserInterface for logging + * and progress feedback during network operations. Follows RAII pattern with + * automatic resource cleanup in the destructor. Uses a progress spinner to + * provide visual feedback during potentially long-running HTTP operations. + */ +class CurlUtils { + private: + /** + * CURL handle for HTTP requests. Initialized in init_curl(). + */ + CURL* curl; + + /** + * CURL headers list for HTTP requests (Content-Type, etc.). + * Allocated in query methods and freed after each request. + */ + struct curl_slist* headers; + + /** + * Pointer to the UserInterface for displaying messages and errors. + * Used for both CLI and interactive UI output. + */ + UserInterface* ui; + + /** + * Progress spinner for visual feedback during network operations. + * Managed via std::unique_ptr for automatic cleanup. + */ + std::unique_ptr spinner; + + void initialize(void); + + void cleanup(void); + + long check_service_status(const std::string& url, const std::map& extra_headers = {}, + long timeout_seconds = 5L); + + public: + explicit CurlUtils(UserInterface* ui); + + ~CurlUtils(); + + long wait_for_service(const std::string& url, const std::map& extra_headers = {}, + int max_retries = 3, int initial_delay_ms = 500); + + std::string fetch_web_content(const std::string& url, std::optional post_data = std::nullopt, + std::optional custom_request_type = std::nullopt, + std::optional> extra_headers = std::nullopt, + bool fail_on_http_error = true); +}; diff --git a/src/utils/embedding_utils.cpp b/src/utils/embedding_utils.cpp new file mode 100644 index 0000000..59ec74a --- /dev/null +++ b/src/utils/embedding_utils.cpp @@ -0,0 +1,62 @@ +#include "embedding_utils.hpp" +#include "utils/text_utils.hpp" +#include +#include + +EmbeddingUtils::EmbeddingUtils(UserInterface* ui, CurlUtils* curl, OllamaClient* ollama_client, + QdrantClient* storage_client) + : ui(ui), curl(curl), ollama_client(ollama_client), storage_client(storage_client) { +} + +void EmbeddingUtils::create_embedings(const std::vector& urls) { + std::string message{}; + + message = "ā³ Fetching documents from URLs...\n"; + if (this->ui->is_running() == true) { + this->ui->print_message(message); + } else { + UserInterface::print_message_noninteractive(message); + } + + std::vector all_documents; + for (const auto& url : urls) { + std::string content = this->curl->fetch_web_content(url); + all_documents.push_back(content); + } + + message = "ā³ Splitting documents into chunks...\n"; + if (this->ui->is_running() == true) { + this->ui->print_message(message); + } else { + UserInterface::print_message_noninteractive(message); + } + + std::vector document_chunks; + for (const auto& doc : all_documents) { + auto chunks = TextUtils::split_text(doc, 250, 0); + document_chunks.insert(document_chunks.end(), chunks.begin(), chunks.end()); + } + + message = "ā³ Generating embeddings...\n"; + if (this->ui->is_running() == true) { + this->ui->print_message(message); + } else { + UserInterface::print_message_noninteractive(message); + } + auto embeddings = this->ollama_client->generate_embeddings(document_chunks); + + message = "ā³ Storing embeddings in Qdrant...\n"; + if (this->ui->is_running() == true) { + this->ui->print_message(message); + } else { + UserInterface::print_message_noninteractive(message); + } + this->storage_client->store(document_chunks, embeddings); + + message = "Embeddings created.\n"; + if (this->ui->is_running() == true) { + this->ui->print_success(message); + } else { + UserInterface::print_success_noninteractive(message); + } +} diff --git a/src/utils/embedding_utils.hpp b/src/utils/embedding_utils.hpp new file mode 100644 index 0000000..2807fbe --- /dev/null +++ b/src/utils/embedding_utils.hpp @@ -0,0 +1,33 @@ +#include "interface/user_interface.hpp" +#include "ollama/ollama_client.hpp" +#include "storage/qdrant_client.hpp" +#include "utils/curl_utils.hpp" +#include + +class EmbeddingUtils { + private: + /** + * Pointer to the UserInterface for displaying messages and errors. + */ + UserInterface* ui; + + /** + * Pointer to the CURL wrapper containing pre-configured internal logic. + */ + CurlUtils* curl; + + /** + * Pointer to the OllamaClient for LLM ops. + */ + OllamaClient* ollama_client; + + /** + * Pointer to the QdrantClient for vector database ops. + */ + QdrantClient* storage_client; + + public: + EmbeddingUtils(UserInterface* ui, CurlUtils* curl, OllamaClient* ollama_client, QdrantClient* storage_client); + + void create_embedings(const std::vector& urls); +}; diff --git a/src/utils/http_utils.hpp b/src/utils/http_utils.hpp new file mode 100644 index 0000000..48fa791 --- /dev/null +++ b/src/utils/http_utils.hpp @@ -0,0 +1,73 @@ +#include +#include +#include + +/** + * @brief Exception thrown when an HTTP request fails with a non-2xx status code or CURL error. + * + * Inherits from std::runtime_error and stores the HTTP status code for detailed error handling. + * Allows calling code to distinguish between different HTTP errors (e.g., 404 vs 500) and handle + * them appropriately. + * + * @see CurlUtils::fetch_web_content() + * + * @example + * @code + * try { + * std::string response = curl->fetch_web_content(url); + * } catch (const HttpException& e) { + * if (e.get_status_code() == 404) { + * std::cout << "Resource not found" << std::endl; + * } else { + * std::cout << "HTTP error: " << e.what() << std::endl; + * } + * } + * @endcode + */ +class HttpException : public std::runtime_error { + private: + /** + * The HTTP status code that triggered the exception. + */ + long status_code; + + public: + /** + * @brief Constructs an HttpException with HTTP status code and URL information. + * + * The exception message is formatted as "HTTP {status_code}: {url}" and is accessible + * via std::exception::what(). + * + * @param status_code The HTTP status code (e.g., 404, 500). Pass 0 for CURL errors. + * @param url The URL that was requested when the error occurred. + * + * @example + * @code + * throw HttpException(404, "http://localhost:6333/collections/missing"); + * @endcode + */ + HttpException(long status_code, const std::string& url) + : std::runtime_error(std::format("HTTP {}: {}", status_code, url)), status_code(status_code) { + } + + /** + * @brief Retrieves the HTTP status code associated with this exception. + * + * Useful for determining whether an error is recoverable (e.g., 404 means resource doesn't exist) + * or critical (e.g., 500 means server error). + * + * @return The HTTP status code as a long. Returns 0 for CURL connection errors. + * + * @example + * @code + * catch (const HttpException& e) { + * if (e.get_status_code() == 404) { + * // Handle not found + * } + * } + * @endcode + */ + long get_status_code() const { + return status_code; + } +}; diff --git a/src/utils/system_utils.cpp b/src/utils/system_utils.cpp new file mode 100644 index 0000000..0518101 --- /dev/null +++ b/src/utils/system_utils.cpp @@ -0,0 +1,74 @@ +#include "system_utils.hpp" +#include + +/** + * Initializes a SystemUtils instance with a reference to the UserInterface. + * + * @param ui Pointer to UserInterface for displaying messages and error output. + * Must remain valid for the lifetime of this SystemUtils instance. + * + * @note The SystemUtils class does not take ownership of the ui pointer; + * the caller is responsible for managing the UserInterface lifetime. + */ +SystemUtils::SystemUtils(UserInterface* ui) { + this->ui = ui; +} + +/** + * Evaluates the status code from a system() call and handles errors appropriately. + * + * This method interprets POSIX wait status codes using WIFEXITED and WEXITSTATUS macros. + * If an error is detected (status -1, non-zero exit code, or abnormal termination), + * an error message is displayed via the UserInterface or printed non-interactively, + * and the program exits with status code 1. + * + * A successful command (exit code 0) produces no output and returns normally. + * + * Error cases handled: + * - system() call failure (status == -1): displays "system() failed" error. + * - Non-zero exit code: displays the exit code and terminates the program. + * - Abnormal termination: displays "Command terminated abnormally" and terminates the program. + * + * Output routing: + * - If UserInterface is in interactive mode (is_running() == true), errors are sent via ui->print_error(). + * - Otherwise, errors are printed non-interactively via UserInterface::print_message_noninteractive(). + * + * @param status The wait status code returned from a system() call. + * Interpret using POSIX macros WIFEXITED and WEXITSTATUS. + * + * @throws Terminates the program with exit code 1 on any detected error condition. + * + * @note This method never returns after encountering an error; callers should not + * expect execution to continue beyond a non-zero exit code or abnormal termination. + */ +void SystemUtils::catch_error(int status) { + std::string message{}; + if (status == -1) { + message = "system() failed.\n"; + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + } + if (WIFEXITED(status)) { + int exit_code = WEXITSTATUS(status); + if (exit_code != 0) { + message = std::format("Command failed with exit code {}.\n", exit_code); + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + exit(1); + } + } else { + message = std::format("Command terminated abnormally.\n"); + if (this->ui->is_running() == false) { + UserInterface::print_error_noninteractive(message); + } else { + this->ui->print_error(message); + } + exit(1); + } +} diff --git a/src/utils/system_utils.hpp b/src/utils/system_utils.hpp new file mode 100644 index 0000000..e81f7a6 --- /dev/null +++ b/src/utils/system_utils.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include "interface/user_interface.hpp" + +class SystemUtils { + private: + /** + * Pointer to the UserInterface for displaying messages and errors. + * Used for both CLI and interactive UI output. + */ + UserInterface* ui; + + public: + explicit SystemUtils(UserInterface* ui); + + void catch_error(int status); +}; diff --git a/src/utils/text-utils.cpp b/src/utils/text-utils.cpp deleted file mode 100644 index f0d5331..0000000 --- a/src/utils/text-utils.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include "text-utils.hpp" - -TextUtils::TextUtils() { -} - -TextUtils::~TextUtils() { -} - -/** - * @brief Implementation of wrap_text method. - * - * Algorithm: - * 1. Iteratively extract lines of up to max_width characters - * 2. Prefer breaking at word boundaries (spaces) - * 3. If no space exists within max_width, break at max_width - * 4. Remove leading whitespace from each new line - * 5. Continue until remaining text fits within max_width - */ -std::vector TextUtils::wrap_text(const std::string& text, int max_width) { - std::vector result; - std::string remaining = text; - - while (remaining.length() > max_width) { - // Find the last space within max_width. - int wrap_position = remaining.rfind(' ', max_width); - - if (wrap_position == std::string::npos) { - wrap_position = max_width; - } - - // Add the wrapped line without trailing space. - std::string line = remaining.substr(0, wrap_position); - result.push_back(line); - - // Skip the space and continue with remainder. - remaining = remaining.substr(wrap_position); - - // Trim leading spaces from next line. - size_t first_non_space = remaining.find_first_not_of(' '); - if (first_non_space != std::string::npos) { - remaining = remaining.substr(first_non_space); - } else { - break; - } - } - - if (!remaining.empty()) { - result.push_back(remaining); - } - - return result; -} diff --git a/src/utils/text-utils.hpp b/src/utils/text-utils.hpp deleted file mode 100644 index 616e9b0..0000000 --- a/src/utils/text-utils.hpp +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once - -#include -#include - -/** - * @class TextUtils - * @brief Utility class for text manipulation operations. - * - * Provides static methods for common text processing tasks, including - * line wrapping based on a specified maximum width. - */ -class TextUtils { - public: - /** - * @brief Constructs a TextUtils object. - * - * Default constructor. Since all methods are static, instantiation - * is optional but permitted. - */ - TextUtils(); - - /** - * @brief Destructs the TextUtils object. - * - * Default destructor. Performs no special cleanup. - */ - ~TextUtils(); - - /** - * @brief Wraps text to fit within a specified width. - * - * Splits the input text into multiple lines, breaking at word boundaries - * where possible to avoid exceeding the maximum width. Respects natural - * spaces and removes leading spaces from wrapped lines. - * - * @param text The input text to wrap. - * @param max_width The maximum width (in characters) for each line. - * @return A vector of strings, each representing a wrapped line. - * The last line may be shorter than max_width. - * - * @note If a single word exceeds max_width, it will be placed on its own - * line without being broken. - */ - static std::vector wrap_text(const std::string& text, int max_width); -}; diff --git a/src/utils/text_utils.cpp b/src/utils/text_utils.cpp new file mode 100644 index 0000000..bcee996 --- /dev/null +++ b/src/utils/text_utils.cpp @@ -0,0 +1,85 @@ +#include "text_utils.hpp" + +/** + * @brief Wraps text to fit within a specified width. + * + * Splits the input text into multiple lines, breaking at word boundaries + * where possible to avoid exceeding the maximum width. Respects natural + * spaces and removes leading spaces from wrapped lines. + * + * @param text The input text to wrap. + * @param max_width The maximum width (in characters) for each line. + * @return A vector of strings, each representing a wrapped line. + * The last line may be shorter than max_width. + * + * @note If a single word exceeds max_width, it will be placed on its own + * line without being broken. + * + * Algorithm: + * 1. Iteratively extract lines of up to max_width characters + * 2. Prefer breaking at word boundaries (spaces) + * 3. If no space exists within max_width, break at max_width + * 4. Remove leading whitespace from each new line + * 5. Continue until remaining text fits within max_width + */ +std::vector TextUtils::wrap_text(const std::string& text, int max_width) { + std::vector result; + std::string remaining = text; + + while (remaining.length() > max_width) { + // Find the last space within max_width. + int wrap_position = remaining.rfind(' ', max_width); + + if (wrap_position == std::string::npos) { + wrap_position = max_width; + } + + // Add the wrapped line without trailing space. + std::string line = remaining.substr(0, wrap_position); + result.push_back(line); + + // Skip the space and continue with remainder. + remaining = remaining.substr(wrap_position); + + // Trim leading spaces from next line. + size_t first_non_space = remaining.find_first_not_of(' '); + if (first_non_space != std::string::npos) { + remaining = remaining.substr(first_non_space); + } else { + break; + } + } + + if (!remaining.empty()) { + result.push_back(remaining); + } + + return result; +} + +/** + * Splits text into fixed-size chunks with optional overlap. + * + * Divides the input text into substrings of the specified chunk size. + * If overlap is specified, chunks will share overlapping content, allowing + * for smooth transitions between consecutive chunks. The final chunk may be + * shorter if the text length is not evenly divisible by chunk_size. + * + * @param text The input string to split + * @param chunk_size The size of each chunk in characters + * @param overlap The number of overlapping characters between consecutive chunks + * @return A vector of string chunks + */ +std::vector TextUtils::split_text(const std::string& text, size_t chunk_size, size_t overlap) { + std::vector chunks; + size_t start = 0; + + while (start < text.length()) { + size_t end = std::min(start + chunk_size, text.length()); + chunks.push_back(text.substr(start, end - start)); + start = end - overlap; + if (overlap == 0) start = end; + } + + return chunks; +} diff --git a/src/utils/text_utils.hpp b/src/utils/text_utils.hpp new file mode 100644 index 0000000..e445f8e --- /dev/null +++ b/src/utils/text_utils.hpp @@ -0,0 +1,18 @@ +#pragma once + +#include +#include + +/** + * @class TextUtils + * @brief Utility class for text manipulation operations. + * + * Provides static methods for common text processing tasks, including + * line wrapping based on a specified maximum width. + */ +class TextUtils { + public: + static std::vector wrap_text(const std::string& text, int max_width); + + static std::vector split_text(const std::string& text, size_t chunk_size, size_t overlap = 0); +}; diff --git a/tools/shell/build.sh b/tools/shell/build.sh index e2948eb..2cb55c0 100644 --- a/tools/shell/build.sh +++ b/tools/shell/build.sh @@ -11,25 +11,31 @@ NC='\033[0m' # Help function show_help() { - echo -e "${BLUE}Usage: ./tools/build.sh [OPTIONS]${NC}" + echo -e "${BLUE}Usage: ./tools/shell/build.sh [OPTIONS]${NC}" echo -e "${YELLOW}Options:${NC} -h, --help Show this help message -c, --clean Clean build directory before building -r, --release Build in Release mode (default: Debug) -p, --package Package release artifacts - -b DIR, --build-dir DIR Specify build directory (default: build)" + -b DIR, --build-dir DIR Specify build directory (default: build) + --cxx-flags FLAGS Set CMAKE_CXX_FLAGS (default: -DDEBUG) + --no-debug-flags Build without -DDEBUG flag + --exe-args ARGS Pass arguments to executable (e.g., '--skip_embedding=true')" echo -e "${YELLOW}Environment Variables:${NC} - BUILD_TYPE Set build type: Debug or Release (default: Debug) - CLEAN_BUILD Set to true to clean before building (default: false)" + BUILD_TYPE Set build type: Debug or Release (default: Debug) + CLEAN_BUILD Set to true to clean before building (default: false) + CMAKE_CXX_FLAGS Set C++ compiler flags (default: -DDEBUG) + EXECUTABLE_ARGS Arguments to pass to the executable" echo -e "${YELLOW}Examples:${NC} - ./tools/build.sh # Debug build - ./tools/build.sh --release # Release build - ./tools/build.sh --clean --release # Clean Release build - ./tools/build.sh --package # Debug build + package - BUILD_TYPE=Release ./tools/build.sh # Release build (env var)" + ./tools/shell/build.sh # Debug build + ./tools/shell/build.sh --release # Release build + ./tools/shell/build.sh --cxx-flags '-DDEBUG -Wall' # Custom flags + ./tools/shell/build.sh --no-debug-flags # No debug flags + ./tools/shell/build.sh --exe-args '--skip_embedding=true --other-arg=true' # Pass args to exe + CMAKE_CXX_FLAGS='-O3' ./tools/shell/build.sh # Via env var" } # Configuration @@ -37,6 +43,9 @@ BUILD_DIR="build" BUILD_TYPE="${BUILD_TYPE:-Debug}" CLEAN_BUILD="${CLEAN_BUILD:-false}" PACKAGE_RELEASE="${PACKAGE_RELEASE:-false}" +# Additional configuration +CMAKE_CXX_FLAGS="${CMAKE_CXX_FLAGS:--DDEBUG}" +EXECUTABLE_ARGS="${EXECUTABLE_ARGS:-}" # Parse arguments while [[ $# -gt 0 ]]; do @@ -61,6 +70,18 @@ while [[ $# -gt 0 ]]; do BUILD_DIR="$2" shift 2 ;; + --cxx-flags) + CMAKE_CXX_FLAGS="$2" + shift 2 + ;; + --no-debug-flags) + CMAKE_CXX_FLAGS="" + shift + ;; + --exe-args) + EXECUTABLE_ARGS="$2" + shift 2 + ;; *) echo -e "${RED}Unknown option: $1${NC}" show_help @@ -91,8 +112,71 @@ get_version() { grep -oP 'project\(\s*[\w-]+\s+VERSION\s+\K[0-9]+\.[0-9]+\.[0-9]+' CMakeLists.txt 2>/dev/null || echo "0.0.0" } +# Calculates the project root directory. +get_project_root() { + local SCRIPT_DIR + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + + local TOOLS_SHELL_DIR + TOOLS_SHELL_DIR="$(dirname "$SCRIPT_DIR")" + + dirname "$TOOLS_SHELL_DIR" +} + +# Ensures script runs from the project root. +ensure_project_root() { + # Get the directory where this script is located (tools/shell/) + local SCRIPT_DIR + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + + # Navigate up two levels: tools/shell/ -> tools/ -> PROJECT_ROOT + local TOOLS_SHELL_DIR + TOOLS_SHELL_DIR="$(dirname "$SCRIPT_DIR")" + + local PROJECT_ROOT + PROJECT_ROOT=$(get_project_root) + + # Get the script name + local SCRIPT_NAME + SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")" + + # Verify the complete expected structure + if [ ! -d "$PROJECT_ROOT/tools/shell" ]; then + log_error "Cannot find 'tools/shell' directory. Expected structure: PROJECT_ROOT/tools/shell/" + exit 1 + fi + + if [ ! -f "$PROJECT_ROOT/tools/shell/$SCRIPT_NAME" ]; then + log_error "Script not found at expected location: PROJECT_ROOT/tools/shell/$SCRIPT_NAME" + exit 1 + fi + + # Change to project root + cd "$PROJECT_ROOT" + log_info "Working from project root: $(pwd)" +} + +# Loads environment variables from .env file. +load_env_file() { + local PROJECT_ROOT + PROJECT_ROOT=$(get_project_root) + + local ENV_FILE + ENV_FILE="$PROJECT_ROOT/.env" + + if [ -f "$ENV_FILE" ]; then + log_info "Loading environment from $ENV_FILE" + # shellcheck disable=SC1090 + source "$ENV_FILE" + log_success "Environment variables loaded" + else + log_info "No .env file found at $ENV_FILE" + fi +} + # Main build script main() { + ensure_project_root log_info "Starting build process..." log_info "Build Type: ${BUILD_TYPE}" log_info "Build Directory: ${BUILD_DIR}" @@ -125,7 +209,8 @@ main() { fi log_info "Configuring CMake (${BUILD_TYPE})..." - if cmake -S . -B "$BUILD_DIR"/"$BUILD_TYPE" -DCMAKE_TOOLCHAIN_FILE="$PWD"/"$BUILD_DIR"/"$BUILD_TYPE"/generators/conan_toolchain.cmake -DCMAKE_BUILD_TYPE="$BUILD_TYPE" -DCMAKE_C_COMPILER=gcc-13 -DCMAKE_CXX_COMPILER=g++-13; then + if cmake -S . -B "$BUILD_DIR"/"$BUILD_TYPE" -DCMAKE_TOOLCHAIN_FILE="$PWD"/"$BUILD_DIR"/"$BUILD_TYPE"/generators/conan_toolchain.cmake -DCMAKE_BUILD_TYPE="$BUILD_TYPE" -DCMAKE_CXX_FLAGS="$CMAKE_CXX_FLAGS" -DCMAKE_C_COMPILER=gcc-13 -DCMAKE_CXX_COMPILER=g++-13; then + log_success "CMake configured" else log_error "CMake configuration failed" @@ -152,7 +237,15 @@ main() { if [ -f "$BUILD_DIR/$BUILD_TYPE/bin/$BIN_NAME" ]; then log_info "Running executable..." - "$BUILD_DIR/$BUILD_TYPE/bin/$BIN_NAME" + load_env_file + if [ -n "$EXECUTABLE_ARGS" ]; then + # allow splitting of $EXECUTABLE_ARGS to support multiple executable arguments. + # shellcheck disable=SC2086 + "$BUILD_DIR/$BUILD_TYPE/bin/$BIN_NAME" $EXECUTABLE_ARGS + else + "$BUILD_DIR/$BUILD_TYPE/bin/$BIN_NAME" + fi + log_success "Executable ran successfully" else log_warning "Executable not found at $BUILD_DIR/bin/$BIN_NAME"