diff --git a/.github/workflows/cross-platform.yml b/.github/workflows/cross-platform.yml index 55938948..c15952cc 100644 --- a/.github/workflows/cross-platform.yml +++ b/.github/workflows/cross-platform.yml @@ -21,21 +21,22 @@ jobs: # Windows builds - name: "Windows MSVC x64" os: windows-latest - generator: "Visual Studio 17 2022" arch: x64 triplet: x64-windows cmake_extra: "-A x64" # macOS builds - - name: "macOS Intel x64" - os: macos-13 - triplet: x64-osx - cmake_extra: "" - - - name: "macOS Apple Silicon ARM64" - os: macos-14 - triplet: arm64-osx - cmake_extra: "" + # macOS is temporarily disabled while the Windows and Linux builds are stabilised. + # Uncomment these two entries to re-enable. + # - name: "macOS Intel x64" + # os: macos-15-intel + # triplet: x64-osx + # cmake_extra: "" + # + # - name: "macOS Apple Silicon ARM64" + # os: macos-15 + # triplet: arm64-osx + # cmake_extra: "" # Linux builds - name: "Linux x64 (Ubuntu)" @@ -43,10 +44,9 @@ jobs: triplet: x64-linux cmake_extra: "" - - name: "Linux x64 (GCC 9)" - os: ubuntu-20.04 + - name: "Linux x64 (Ubuntu 22.04)" + os: ubuntu-22.04 triplet: x64-linux - compiler_version: 9 cmake_extra: "" runs-on: ${{ matrix.os }} @@ -80,14 +80,6 @@ jobs: if: runner.os == 'Windows' uses: microsoft/setup-msbuild@v2 - - name: Setup specific GCC version (Linux) - if: matrix.compiler_version && runner.os == 'Linux' - run: | - sudo apt-get update - sudo apt-get install -y gcc-${{ matrix.compiler_version }} g++-${{ matrix.compiler_version }} - sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${{ matrix.compiler_version }} 100 - sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-${{ matrix.compiler_version }} 100 - - name: Install system dependencies (Linux) if: runner.os == 'Linux' run: | @@ -109,8 +101,13 @@ jobs: - name: Install system dependencies (macOS) if: runner.os == 'macOS' run: | - brew update - brew install cmake ninja pkg-config curl jsoncpp glfw + # No "brew update" and no cmake here. CMake is preinstalled on the + # runner, and updating Homebrew first makes it upgrade cmake, curl + # and their dependencies. Homebrew no longer ships prebuilt packages + # for Intel macOS, so that rebuilt everything from source (over 30 + # minutes) and then exited non-zero. The E2E workflow installs the + # same packages this way without problems. + brew install ninja pkg-config curl jsoncpp glfw - name: Cache vcpkg packages uses: actions/cache@v4 @@ -146,6 +143,7 @@ jobs: - name: Run tests (Windows) if: runner.os == 'Windows' working-directory: build + shell: pwsh run: | $env:PATH = "$PWD\bin;$PWD\${{ env.BUILD_TYPE }};$env:PATH" ctest --build-config ${{ env.BUILD_TYPE }} --output-on-failure --timeout 120 @@ -231,7 +229,7 @@ jobs: -DCMAKE_CXX_COMPILER=${{ matrix.target.gcc }}-g++ \ -DCMAKE_BUILD_TYPE=Release \ -DENABLE_LLAMA_CPP=OFF - make -j$(nproc) || true + make -j"$(nproc)" || true documentation: name: Build documentation diff --git a/.github/workflows/deno.yml b/.github/workflows/deno.yml deleted file mode 100644 index 782af35b..00000000 --- a/.github/workflows/deno.yml +++ /dev/null @@ -1,42 +0,0 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -# This workflow will install Deno then run `deno lint` and `deno test`. -# For more information see: https://github.com/denoland/setup-deno - -name: Deno - -on: - push: - branches: ["main"] - pull_request: - branches: ["main"] - -permissions: - contents: read - -jobs: - test: - runs-on: ubuntu-latest - - steps: - - name: Setup repo - uses: actions/checkout@v4 - - - name: Setup Deno - # uses: denoland/setup-deno@v1 - uses: denoland/setup-deno@61fe2df320078202e33d7d5ad347e7dcfa0e8f31 # v1.1.2 - with: - deno-version: v1.x - - # Uncomment this step to verify the use of 'deno fmt' on each commit. - # - name: Verify formatting - # run: deno fmt --check - - - name: Run linter - run: deno lint - - - name: Run tests - run: deno test -A diff --git a/.github/workflows/e2e-ci.yml b/.github/workflows/e2e-ci.yml index ffbbcc2f..08a3d557 100644 --- a/.github/workflows/e2e-ci.yml +++ b/.github/workflows/e2e-ci.yml @@ -98,8 +98,8 @@ jobs: cc: gcc-13 cxx: g++-13 - compiler: clang - cc: clang-17 - cxx: clang++-17 + cc: clang + cxx: clang++ steps: - uses: actions/checkout@v4 @@ -138,10 +138,9 @@ jobs: if [ "${{ matrix.compiler }}" = "gcc" ]; then sudo apt-get install -y gcc-13 g++-13 else - wget https://apt.llvm.org/llvm.sh - chmod +x llvm.sh - sudo ./llvm.sh 17 - sudo apt-get install -y clang-17 clang++-17 + # Use the distribution's clang: apt.llvm.org has no LLVM 17 + # repository for the current ubuntu-latest release. + sudo apt-get install -y clang fi - name: Setup vcpkg @@ -150,7 +149,7 @@ jobs: git clone https://github.com/microsoft/vcpkg.git ~/vcpkg ~/vcpkg/bootstrap-vcpkg.sh fi - echo "VCPKG_ROOT=$HOME/vcpkg" >> $GITHUB_ENV + echo "VCPKG_ROOT=$HOME/vcpkg" >> "$GITHUB_ENV" - name: Configure CMake run: | @@ -158,12 +157,12 @@ jobs: -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \ -DCMAKE_C_COMPILER=${{ matrix.cc }} \ -DCMAKE_CXX_COMPILER=${{ matrix.cxx }} \ - -DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake \ + "-DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake" \ -DVCPKG_MANIFEST_MODE=ON \ -DBOLT_ENABLE_TESTS=ON - name: Build - run: cmake --build build --config ${{ matrix.build_type }} -j $(nproc) + run: cmake --build build --config ${{ matrix.build_type }} -j "$(nproc)" - name: Run unit tests working-directory: build @@ -177,7 +176,7 @@ jobs: echo "Checking for shared libraries..." find . -name "*.so*" -type f 2>/dev/null | head -20 - ctest --build-config ${{ matrix.build_type }} --output-on-failure --timeout 120 -j $(nproc) + ctest --build-config ${{ matrix.build_type }} --output-on-failure --timeout 120 -j "$(nproc)" - name: Upload test results if: always() @@ -192,10 +191,17 @@ jobs: uses: actions/upload-artifact@v4 with: name: bolt-linux-${{ matrix.compiler }}-${{ matrix.build_type }} + # Include the shared libraries the executables load at run time + # (libbolt_lib, libllama, libggml); without them nothing in this + # artifact can start. path: | build/bolt - build/bolt_lib* + build/gui_main + build/bolt_terminal_ai + build/benchmark_tool build/demo_* + build/libbolt_lib.so* + build/bin/*.so* retention-days: 7 # ============================================ @@ -212,11 +218,12 @@ jobs: compiler: [msvc, mingw] build_type: [Release, Debug] include: + # No explicit generator for MSVC: windows-latest ships a newer + # Visual Studio than "Visual Studio 17 2022", so CMake picks the + # installed one by default. - compiler: msvc - generator: "Visual Studio 17 2022" arch: "-A x64" - compiler: mingw - generator: "MinGW Makefiles" arch: "" steps: @@ -244,7 +251,10 @@ jobs: with: msystem: MINGW64 update: true + # git is needed at test time: the GitRepository tests shell out + # to it, and the MSYS2 shell does not inherit the Windows PATH. install: >- + git mingw-w64-x86_64-gcc mingw-w64-x86_64-cmake mingw-w64-x86_64-ninja @@ -257,7 +267,7 @@ jobs: - name: Configure CMake (MSVC) if: matrix.compiler == 'msvc' run: | - cmake -B build -G "${{ matrix.generator }}" ${{ matrix.arch }} ` + cmake -B build ${{ matrix.arch }} ` -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} ` -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake ` -DVCPKG_MANIFEST_MODE=ON ` @@ -267,7 +277,9 @@ jobs: if: matrix.compiler == 'mingw' shell: msys2 {0} run: | - cmake -B build -G "MinGW Makefiles" \ + # Ninja is what the MSYS2 step installs; "MinGW Makefiles" needs + # mingw32-make, which is not installed. + cmake -B build -G Ninja \ -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \ -DBOLT_ENABLE_TESTS=ON @@ -278,7 +290,7 @@ jobs: - name: Build (MinGW) if: matrix.compiler == 'mingw' shell: msys2 {0} - run: cmake --build build --config ${{ matrix.build_type }} -j $(nproc) + run: cmake --build build --config ${{ matrix.build_type }} -j "$(nproc)" - name: Run tests (MSVC) if: matrix.compiler == 'msvc' @@ -312,20 +324,23 @@ jobs: name: macOS (${{ matrix.arch }}, ${{ matrix.build_type }}) runs-on: ${{ matrix.runner }} needs: preflight - if: needs.preflight.outputs.should_skip != 'true' + # macOS is temporarily disabled while the Windows and Linux builds are stabilised. + # To re-enable, restore: + # if: needs.preflight.outputs.should_skip != 'true' + if: false strategy: fail-fast: false matrix: include: - - runner: macos-13 + - runner: macos-15-intel arch: x64 triplet: x64-osx build_type: Release - - runner: macos-14 + - runner: macos-15 arch: arm64 triplet: arm64-osx build_type: Release - - runner: macos-14 + - runner: macos-15 arch: arm64 triplet: arm64-osx build_type: Debug @@ -353,24 +368,24 @@ jobs: git clone https://github.com/microsoft/vcpkg.git ~/vcpkg ~/vcpkg/bootstrap-vcpkg.sh fi - echo "VCPKG_ROOT=$HOME/vcpkg" >> $GITHUB_ENV + echo "VCPKG_ROOT=$HOME/vcpkg" >> "$GITHUB_ENV" - name: Configure CMake run: | cmake -B build -G Ninja \ -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \ - -DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake \ + "-DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake" \ -DVCPKG_TARGET_TRIPLET=${{ matrix.triplet }} \ -DVCPKG_MANIFEST_MODE=ON \ -DBOLT_ENABLE_TESTS=ON - name: Build - run: cmake --build build --config ${{ matrix.build_type }} -j $(sysctl -n hw.ncpu) + run: cmake --build build --config ${{ matrix.build_type }} -j "$(sysctl -n hw.ncpu)" - name: Run tests working-directory: build run: | - ctest --build-config ${{ matrix.build_type }} --output-on-failure --timeout 120 -j $(sysctl -n hw.ncpu) + ctest --build-config ${{ matrix.build_type }} --output-on-failure --timeout 120 -j "$(sysctl -n hw.ncpu)" - name: Upload build artifacts if: matrix.build_type == 'Release' @@ -431,16 +446,16 @@ jobs: -DBOLT_ENABLE_TESTS=ON - name: Build - run: cmake --build build -j $(nproc) + run: cmake --build build -j "$(nproc)" - name: Run sanitizer tests working-directory: build - env: - ${{ matrix.env_var }}: "" run: | # Set LD_LIBRARY_PATH to include all directories with shared libraries export LD_LIBRARY_PATH="${PWD}/bin:${PWD}:${PWD}/ggml/llama.cpp/src:$LD_LIBRARY_PATH" - export ${{ matrix.env_var }} + # matrix.env_var is a full NAME=value assignment, e.g. + # ASAN_OPTIONS=detect_leaks=1 + export "${{ matrix.env_var }}" ctest --output-on-failure --timeout 300 || true - name: Upload sanitizer report @@ -468,30 +483,45 @@ jobs: path: build/ - name: Make binaries executable - run: chmod +x build/bolt build/demo_* || true + run: chmod +x build/bolt build/gui_main build/bolt_terminal_ai build/benchmark_tool build/demo_* - name: Install runtime dependencies run: | sudo apt-get update + # Install the -dev packages rather than soname-versioned runtime + # packages (libjsoncpp25, libssl3, ...): those names change with + # each Ubuntu release, and the -dev packages pull in whichever + # runtime the current runner ships. + # xvfb and the Mesa software renderer let the smoke test start + # the GUI without a real display. sudo apt-get install -y \ - libcurl4 libjsoncpp25 libglfw3 \ - libgl1 libssl3 zlib1g + libcurl4-openssl-dev libjsoncpp-dev libglfw3-dev \ + libgl1-mesa-dev libssl-dev zlib1g-dev \ + xvfb libgl1-mesa-dri + + - name: Download a small test model + # A 19 MB public model, enough to check that a GGUF file loads and + # generates text. If the download itself fails the model check is + # skipped with a warning; a model that downloads but does not work + # fails the smoke test below. + run: | + mkdir -p test-models + url=https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories15M-q4_0.gguf + if curl -fsSL --retry 3 --retry-delay 5 --max-time 300 \ + -o test-models/stories15M-q4_0.gguf "$url" \ + && [ "$(head -c 4 test-models/stories15M-q4_0.gguf)" = "GGUF" ]; then + echo "BOLT_SMOKE_MODEL=$PWD/test-models/stories15M-q4_0.gguf" >> "$GITHUB_ENV" + else + echo "::warning::Could not download the test model; skipping the model inference check" + fi - name: Run integration tests + # Starts bolt and every demo program and fails if any of them hangs + # or crashes, then runs inference with the test model if it was + # downloaded. See scripts/smoke_test.sh. run: | - export LD_LIBRARY_PATH="build:$LD_LIBRARY_PATH" - - echo "=== Testing main executable ===" - ./build/bolt --version || ./build/bolt --help || echo "Main executable test skipped" - - echo "=== Testing demo executables ===" - for demo in build/demo_*; do - if [ -x "$demo" ]; then - echo "Testing: $demo" - timeout 10 "$demo" --help 2>/dev/null || timeout 5 "$demo" 2>/dev/null || echo " (no --help flag)" - fi - done - continue-on-error: true + set -o pipefail + bash scripts/smoke_test.sh build 2>&1 | tee integration-test-smoke.log - name: Upload integration test results uses: actions/upload-artifact@v4 @@ -525,7 +555,7 @@ jobs: -DCMAKE_BUILD_TYPE=Release \ -DBOLT_ENABLE_TESTS=ON \ -DBOLT_ENABLE_E2E_TESTS=ON - cmake --build build -j $(nproc) + cmake --build build -j "$(nproc)" - name: Run E2E test suite working-directory: build @@ -596,7 +626,7 @@ jobs: -DBOLT_ENABLE_TESTS=ON - name: Build - run: cmake --build build -j $(nproc) + run: cmake --build build -j "$(nproc)" - name: Run tests for coverage working-directory: build @@ -606,15 +636,19 @@ jobs: - name: Generate coverage report run: | + # negative/inconsistent: gcov from current GCC reports bogus hit + # counts for some libstdc++ header lines, which lcov treats as a + # fatal error. Those headers are filtered out below anyway. lcov --capture --directory build --output-file coverage.info \ - --ignore-errors mismatch,empty,unused + --ignore-errors mismatch,empty,unused,negative,inconsistent lcov --remove coverage.info '/usr/*' '*/test/*' '*/ggml/*' \ - --output-file coverage.info --ignore-errors unused - lcov --list coverage.info + --output-file coverage.info \ + --ignore-errors unused,negative,inconsistent + lcov --list coverage.info --ignore-errors negative,inconsistent # Generate HTML report genhtml coverage.info --output-directory coverage-html \ - --ignore-errors source + --ignore-errors source,negative,inconsistent - name: Upload coverage report uses: actions/upload-artifact@v4 @@ -643,16 +677,18 @@ jobs: steps: - name: Check job results run: | - echo "## CI Pipeline Summary" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "| Job | Status |" >> $GITHUB_STEP_SUMMARY - echo "|-----|--------|" >> $GITHUB_STEP_SUMMARY - echo "| Code Quality | ${{ needs.code-quality.result }} |" >> $GITHUB_STEP_SUMMARY - echo "| Linux Build | ${{ needs.linux-build.result }} |" >> $GITHUB_STEP_SUMMARY - echo "| Windows Build | ${{ needs.windows-build.result }} |" >> $GITHUB_STEP_SUMMARY - echo "| macOS Build | ${{ needs.macos-build.result }} |" >> $GITHUB_STEP_SUMMARY - echo "| Integration Tests | ${{ needs.integration-tests.result }} |" >> $GITHUB_STEP_SUMMARY - echo "| E2E Tests | ${{ needs.e2e-tests.result }} |" >> $GITHUB_STEP_SUMMARY + { + echo "## CI Pipeline Summary" + echo "" + echo "| Job | Status |" + echo "|-----|--------|" + echo "| Code Quality | ${{ needs.code-quality.result }} |" + echo "| Linux Build | ${{ needs.linux-build.result }} |" + echo "| Windows Build | ${{ needs.windows-build.result }} |" + echo "| macOS Build | ${{ needs.macos-build.result }} |" + echo "| Integration Tests | ${{ needs.integration-tests.result }} |" + echo "| E2E Tests | ${{ needs.e2e-tests.result }} |" + } >> "$GITHUB_STEP_SUMMARY" - name: Fail if any job failed if: contains(needs.*.result, 'failure') diff --git a/.github/workflows/msbuild.yml b/.github/workflows/msbuild.yml index 695628bf..4bf91ac2 100644 --- a/.github/workflows/msbuild.yml +++ b/.github/workflows/msbuild.yml @@ -36,11 +36,13 @@ jobs: - name: Configure CMake run: | - mkdir build - cd build - cmake -G "Visual Studio 17 2022" -A x64 ` - -DCMAKE_TOOLCHAIN_FILE=..\vcpkg_tool\scripts\buildsystems\vcpkg.cmake ` - -DCMAKE_BUILD_TYPE=${{env.BUILD_CONFIGURATION}} .. + # No explicit -G: windows-latest ships a newer Visual Studio than + # "Visual Studio 17 2022", so let CMake pick the installed one. + # The -D arguments are quoted because PowerShell otherwise splits + # values containing ".." or "." into separate arguments. + cmake -S . -B build -A x64 ` + "-DCMAKE_TOOLCHAIN_FILE=${{ github.workspace }}/vcpkg_tool/scripts/buildsystems/vcpkg.cmake" ` + "-DCMAKE_BUILD_TYPE=${{env.BUILD_CONFIGURATION}}" - name: Build with MSBuild working-directory: build diff --git a/.github/workflows/objective-c-xcode.yml b/.github/workflows/objective-c-xcode.yml deleted file mode 100644 index add007bf..00000000 --- a/.github/workflows/objective-c-xcode.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Xcode - Build and Analyze - -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] - -jobs: - build: - name: Build and analyse default scheme using xcodebuild command - runs-on: macos-latest - - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Set Default Scheme - run: | - scheme_list=$(xcodebuild -list -json | tr -d "\n") - default=$(echo $scheme_list | ruby -e "require 'json'; puts JSON.parse(STDIN.gets)['project']['targets'][0]") - echo $default | cat >default - echo Using default scheme: $default - - name: Build - env: - scheme: ${{ 'default' }} - run: | - if [ $scheme = default ]; then scheme=$(cat default); fi - if [ "`ls -A | grep -i \\.xcworkspace\$`" ]; then filetype_parameter="workspace" && file_to_build="`ls -A | grep -i \\.xcworkspace\$`"; else filetype_parameter="project" && file_to_build="`ls -A | grep -i \\.xcodeproj\$`"; fi - file_to_build=`echo $file_to_build | awk '{$1=$1;print}'` - xcodebuild clean build analyze -scheme "$scheme" -"$filetype_parameter" "$file_to_build" | xcpretty && exit ${PIPESTATUS[0]} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cae93e56..df0b4cc2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -49,8 +49,8 @@ jobs: IS_PRERELEASE="false" fi fi - echo "version=$VERSION" >> $GITHUB_OUTPUT - echo "is_prerelease=$IS_PRERELEASE" >> $GITHUB_OUTPUT + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "is_prerelease=$IS_PRERELEASE" >> "$GITHUB_OUTPUT" echo "Release version: $VERSION (prerelease: $IS_PRERELEASE)" # ============================================ @@ -80,6 +80,7 @@ jobs: build-essential ninja-build pkg-config \ libcurl4-openssl-dev libjsoncpp-dev libglfw3-dev \ libgl1-mesa-dev libglu1-mesa-dev libssl-dev zlib1g-dev \ + libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev \ gcc-13 g++-13 \ patchelf chrpath @@ -94,13 +95,13 @@ jobs: -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=${{ matrix.cc }} \ -DCMAKE_CXX_COMPILER=${{ matrix.cxx }} \ - -DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake \ + "-DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake" \ -DVCPKG_TARGET_TRIPLET=${{ matrix.triplet }} \ -DCMAKE_INSTALL_PREFIX=/usr \ -DBUILD_SHARED_LIBS=OFF - name: Build - run: cmake --build build --config Release -j $(nproc) + run: cmake --build build --config Release -j "$(nproc)" - name: Run tests working-directory: build @@ -165,7 +166,7 @@ jobs: -DCMAKE_CXX_COMPILER=g++-13 \ -DCMAKE_INSTALL_PREFIX=/usr \ -DBUILD_SHARED_LIBS=OFF - cmake --build build -j $(nproc) + cmake --build build -j "$(nproc)" - name: Create DEB package run: | @@ -182,6 +183,17 @@ jobs: cp build/bolt "$PKGDIR/usr/bin/" cp build/bolt_lib* "$PKGDIR/usr/lib/" 2>/dev/null || true + # Work out the runtime dependencies from the libraries the binary + # actually links, so the package installs what bolt needs on a + # clean machine. Fall back to a fixed list if that is not possible. + mkdir -p debian && touch debian/control + DEPENDS="$(dpkg-shlibdeps -O build/bolt 2>/dev/null | sed -n 's/^shlibs:Depends=//p')" + rm -rf debian + if [ -z "$DEPENDS" ]; then + DEPENDS="libc6 (>= 2.31), libstdc++6 (>= 10), libcurl4, libssl3, zlib1g" + fi + echo "Package dependencies: $DEPENDS" + # Create control file cat > "$PKGDIR/DEBIAN/control" << EOF Package: bolt @@ -189,20 +201,28 @@ jobs: Section: devel Priority: optional Architecture: amd64 - Depends: libc6 (>= 2.31), libstdc++6 (>= 10), libcurl4, libssl3, zlib1g + Depends: ${DEPENDS} Maintainer: Bolt Development Team Description: Bolt C++ ML IDE A modern C++ implementation of the Bolt IDE core components with AI integration, LSP support, and real-time collaborative features. EOF - # Build package - dpkg-deb --build "$PKGDIR" - mv "${PKGDIR}.deb" "bolt_${VERSION}_amd64.deb" + # Build package. dpkg-deb names the output after the directory, + # which is already bolt__amd64.deb. + dpkg-deb --root-owner-group --build "$PKGDIR" - # Verify package + # Verify package metadata dpkg -I "bolt_${VERSION}_amd64.deb" + - name: Install and run the DEB package + run: | + VERSION="${{ needs.prepare.outputs.version }}" + sudo dpkg -i "bolt_${VERSION}_amd64.deb" + /usr/bin/bolt --version + printf 'hello\n/exit\n' | /usr/bin/bolt | grep -q 'Echo: hello' + sudo dpkg -r bolt + - name: Create RPM package run: | VERSION="${{ needs.prepare.outputs.version }}" @@ -217,6 +237,10 @@ jobs: # Create spec file cat > rpmbuild/SPECS/bolt.spec << 'EOF' + # The binary is prebuilt; skip the debuginfo subpackage, which needs + # elfutils (eu-strip) and is not installed on the runner. + %global debug_package %{nil} + Name: bolt Version: ${{ needs.prepare.outputs.version }} Release: 1%{?dist} @@ -243,12 +267,19 @@ jobs: /usr/bin/bolt %changelog - * $(date +"%a %b %d %Y") Bolt Team - ${{ needs.prepare.outputs.version }}-1 + * CHANGELOG_DATE Bolt Team - ${{ needs.prepare.outputs.version }}-1 - Initial release EOF - # Build RPM - rpmbuild --define "_topdir $(pwd)/rpmbuild" -bb rpmbuild/SPECS/bolt.spec || true + # The heredoc above is quoted so that rpm macros stay literal, + # which also means $(date) would not expand; fill the date in here. + sed -i "s/CHANGELOG_DATE/$(LC_ALL=C date +'%a %b %d %Y')/" rpmbuild/SPECS/bolt.spec + + # Build RPM. --nodeps: the BuildRequires are RPM package names and + # cannot be checked against the rpm database on an Ubuntu runner; + # the binary was already built above. + rpmbuild --nodeps --define "_topdir $(pwd)/rpmbuild" -bb rpmbuild/SPECS/bolt.spec + ls -l rpmbuild/RPMS/*/*.rpm - name: Upload packages uses: actions/upload-artifact@v4 @@ -329,8 +360,15 @@ jobs: Copy-Item -Path (Join-Path $binDir "bolt*.dll") -Destination $PKGDIR -ErrorAction SilentlyContinue Copy-Item -Path (Join-Path $binDir "demo_*.exe") -Destination $PKGDIR -ErrorAction SilentlyContinue - # Copy dependencies from vcpkg - Get-ChildItem -Path "C:\vcpkg\installed\x64-windows\bin\*.dll" | Copy-Item -Destination $PKGDIR -ErrorAction SilentlyContinue + # Copy the dependency DLLs from vcpkg. The project uses a vcpkg + # manifest, so they are installed under the build tree; classic + # mode would put them under C:\vcpkg\installed. + $vcpkgBin = @("build\vcpkg_installed\x64-windows\bin", "C:\vcpkg\installed\x64-windows\bin") | + Where-Object { Test-Path $_ } | Select-Object -First 1 + if (-not $vcpkgBin) { + throw "vcpkg runtime DLL directory not found; the package would not run without its DLLs" + } + Get-ChildItem -Path (Join-Path $vcpkgBin "*.dll") | Copy-Item -Destination $PKGDIR # Copy documentation Copy-Item -Path "README.md" -Destination $PKGDIR -ErrorAction SilentlyContinue @@ -402,20 +440,31 @@ jobs: - - - - - "@ | Out-File -FilePath "bolt.wxs" -Encoding UTF8 - name: Build MSI + shell: powershell run: | - & "C:\Program Files (x86)\WiX Toolset v3.11\bin\candle.exe" bolt.wxs - & "C:\Program Files (x86)\WiX Toolset v3.11\bin\light.exe" -out bolt-${{ needs.prepare.outputs.version }}-windows-x64.msi bolt.wixobj - continue-on-error: true + $VERSION = "${{ needs.prepare.outputs.version }}" + $SRC = "extracted\bolt-$VERSION-windows-x64" + + # Locate WiX through the WIX variable its installer sets rather + # than a hard-coded version directory (the runner image moves on). + $wixBin = if ($env:WIX) { Join-Path $env:WIX "bin" } else { Split-Path (Get-Command candle.exe).Source } + + # Harvest every file of the release (bolt.exe and the DLLs it + # needs) into the ProductComponents group referenced by bolt.wxs. + & (Join-Path $wixBin "heat.exe") dir $SRC -cg ProductComponents -dr INSTALLFOLDER ` + -gg -sfrag -srd -sreg -var var.SourceDir -out files.wxs + if ($LASTEXITCODE -ne 0) { throw "heat.exe failed" } + + & (Join-Path $wixBin "candle.exe") -arch x64 "-dSourceDir=$SRC" bolt.wxs files.wxs + if ($LASTEXITCODE -ne 0) { throw "candle.exe failed" } + + & (Join-Path $wixBin "light.exe") -out "bolt-$VERSION-windows-x64.msi" bolt.wixobj files.wixobj + if ($LASTEXITCODE -ne 0) { throw "light.exe failed" } - name: Upload MSI uses: actions/upload-artifact@v4 @@ -433,14 +482,18 @@ jobs: name: macOS Release (${{ matrix.arch }}) runs-on: ${{ matrix.runner }} needs: prepare + # macOS is temporarily disabled while the Windows and Linux builds are stabilised. + # Remove this line (and the ones on macos-universal and macos-dmg) and + # restore the macOS entries in create-release to re-enable. + if: false strategy: fail-fast: false matrix: include: - - runner: macos-13 + - runner: macos-15-intel arch: x64 triplet: x64-osx - - runner: macos-14 + - runner: macos-15 arch: arm64 triplet: arm64-osx @@ -460,12 +513,12 @@ jobs: run: | cmake -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake \ + "-DCMAKE_TOOLCHAIN_FILE=$HOME/vcpkg/scripts/buildsystems/vcpkg.cmake" \ -DVCPKG_TARGET_TRIPLET=${{ matrix.triplet }} \ -DBUILD_SHARED_LIBS=OFF - name: Build - run: cmake --build build --config Release -j $(sysctl -n hw.ncpu) + run: cmake --build build --config Release -j "$(sysctl -n hw.ncpu)" - name: Run tests working-directory: build @@ -504,8 +557,9 @@ jobs: # ============================================ macos-universal: name: macOS Universal Binary - runs-on: macos-14 + runs-on: macos-15 needs: [prepare, macos-release] + if: false # macOS temporarily disabled, see macos-release steps: - name: Download x64 build @@ -557,8 +611,9 @@ jobs: # ============================================ macos-dmg: name: macOS DMG Installer - runs-on: macos-14 + runs-on: macos-15 needs: [prepare, macos-universal] + if: false # macOS temporarily disabled, see macos-release steps: - uses: actions/checkout@v4 @@ -641,9 +696,11 @@ jobs: - linux-packages - windows-release - windows-installer - - macos-release - - macos-universal - - macos-dmg + # macOS temporarily disabled. A skipped dependency would skip this + # job too, so the macOS jobs are left out of "needs" until then. + # - macos-release + # - macos-universal + # - macos-dmg if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') permissions: @@ -683,8 +740,7 @@ jobs: - \`bolt-${VERSION}-windows-x64.msi\` - Windows installer ### macOS - - \`bolt-${VERSION}-macos-universal.tar.gz\` - macOS Universal binary (Intel + Apple Silicon) - - \`bolt-${VERSION}-macos.dmg\` - macOS installer + macOS builds are temporarily unavailable. ## Checksums SHA256 checksums are provided for all downloads in \`.sha256\` files. @@ -724,14 +780,16 @@ jobs: notify: name: Notify runs-on: ubuntu-latest - needs: [create-release] + needs: [prepare, create-release] if: always() steps: - name: Release Summary run: | - echo "## Release Summary" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "Version: ${{ needs.prepare.outputs.version }}" >> $GITHUB_STEP_SUMMARY - echo "Pre-release: ${{ needs.prepare.outputs.is_prerelease }}" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "All release artifacts have been uploaded." >> $GITHUB_STEP_SUMMARY + { + echo "## Release Summary" + echo "" + echo "Version: ${{ needs.prepare.outputs.version }}" + echo "Pre-release: ${{ needs.prepare.outputs.is_prerelease }}" + echo "" + echo "Publishing job: ${{ needs.create-release.result }}" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/CMakeLists.txt b/CMakeLists.txt index 4e182a58..71369123 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,6 +15,14 @@ set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) set(CMAKE_BUILD_RPATH "${CMAKE_BINARY_DIR}/bin;${CMAKE_BINARY_DIR}") set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib") +# Portable builds by default. Tuning for the build machine's CPU +# (-march=native, and llama.cpp's GGML_NATIVE) produces binaries that die with +# "Illegal instruction" on any machine whose CPU lacks an instruction the +# build machine had, which is exactly what happened to CI artifacts and would +# happen to release packages. Turn this ON only for a build you will run on +# the machine that built it. +option(BOLT_NATIVE_OPTIMIZATIONS "Optimise for the build machine's CPU (not portable)" OFF) + # Include cross-platform configuration include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/CrossPlatform.cmake") @@ -106,6 +114,32 @@ if(NOT IMGUI_FOUND) # Try alternative package names find_package(ImGui QUIET) set(IMGUI_FOUND ${ImGui_FOUND}) + if(NOT IMGUI_FOUND) + # Distribution packages (Debian/Ubuntu libimgui-dev) ship the headers, + # the backends and a library, but no CMake package config. Without + # this fallback the GUI is silently left out of every build that + # uses system packages instead of vcpkg. + find_path(BOLT_IMGUI_INCLUDE_DIR imgui.h PATH_SUFFIXES imgui) + find_path(BOLT_IMGUI_BACKENDS_DIR imgui_impl_glfw.h + PATH_SUFFIXES imgui/backends imgui) + find_library(BOLT_IMGUI_LIBRARY NAMES imgui) + if(BOLT_IMGUI_INCLUDE_DIR AND BOLT_IMGUI_BACKENDS_DIR AND BOLT_IMGUI_LIBRARY) + add_library(imgui::imgui UNKNOWN IMPORTED) + set_target_properties(imgui::imgui PROPERTIES + IMPORTED_LOCATION "${BOLT_IMGUI_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${BOLT_IMGUI_INCLUDE_DIR};${BOLT_IMGUI_BACKENDS_DIR}" + ) + # The Debian build of ImGui uses the system stb library for its + # font and rectangle packing code instead of bundling it. + find_library(BOLT_STB_LIBRARY NAMES stb) + if(BOLT_STB_LIBRARY) + set_property(TARGET imgui::imgui APPEND PROPERTY + INTERFACE_LINK_LIBRARIES "${BOLT_STB_LIBRARY}") + endif() + set(IMGUI_FOUND TRUE) + message(STATUS "Found ImGui (system package): ${BOLT_IMGUI_LIBRARY}") + endif() + endif() if(NOT IMGUI_FOUND) message(WARNING "ImGui not found - GUI components will be disabled") set(IMGUI_FOUND FALSE) @@ -118,10 +152,24 @@ endif() option(ENABLE_LLAMA_CPP "Enable llama.cpp integration (provides GGML)" ON) +# The vendored llama.cpp declares BUILD_SHARED_LIBS with a default of ON for +# non-MinGW toolchains. That would also turn bolt_lib into a DLL, but bolt_lib +# has no __declspec(dllexport) annotations, so MSVC emits no import library +# and every dependent target fails with LNK1181 (cannot open bolt_lib.lib). +# Declare the option first so the default is static on MSVC; an explicit +# -DBUILD_SHARED_LIBS=... on the command line still wins. +if(MSVC) + option(BUILD_SHARED_LIBS "Build shared libraries" OFF) +endif() + if(ENABLE_LLAMA_CPP AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/ggml/llama.cpp/CMakeLists.txt") message(STATUS "Configuring llama.cpp integration (unified GGML source)...") # Configure llama.cpp build options + # GGML_NATIVE defaults to ON upstream; tie it to our own option so the + # default build is portable. With it OFF, ggml targets a fixed x86-64 + # baseline (AVX2, FMA, F16C, BMI2) instead of the build machine's CPU. + set(GGML_NATIVE ${BOLT_NATIVE_OPTIMIZATIONS} CACHE BOOL "ggml: optimize the build for the current system" FORCE) set(LLAMA_CURL OFF CACHE BOOL "" FORCE) set(LLAMA_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(LLAMA_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) @@ -349,6 +397,7 @@ endif() # Main executable add_executable(bolt src/bolt/main.cpp) target_link_libraries(bolt PRIVATE bolt_lib) +target_compile_definitions(bolt PRIVATE BOLT_VERSION="${PROJECT_VERSION}") if(WIN32) target_sources(bolt PRIVATE ${BOLT_WIN32_RESOURCES}) endif() @@ -543,15 +592,17 @@ endif() # Only the main application ships; demo/test executables are NOT installed. # Everything goes into the "app" component so packaging stays clutter-free. # --------------------------------------------------------------------------- +# COMPONENT applies only to the artifact kind it follows, so it is repeated +# for RUNTIME and BUNDLE (macOS app bundles). install(TARGETS bolt - RUNTIME DESTINATION bin - COMPONENT app + RUNTIME DESTINATION bin COMPONENT app + BUNDLE DESTINATION . COMPONENT app ) if(TARGET gui_main) install(TARGETS gui_main - RUNTIME DESTINATION bin - COMPONENT app + RUNTIME DESTINATION bin COMPONENT app + BUNDLE DESTINATION . COMPONENT app ) endif() diff --git a/README.md b/README.md index 362db540..abb560d6 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ A modern C++ implementation of the Bolt IDE core components with AI integration ### Editor Features - Multi-cursor support - Line numbering system -- Find/Replace functionality +- Find/Replace functionality - Bracket matching - Syntax highlighting - File tree navigation @@ -39,7 +39,7 @@ A modern C++ implementation of the Bolt IDE core components with AI integration ## Project Structure -``` +```text bolt/ ├── include/ # Header files │ └── bolt/ @@ -91,6 +91,20 @@ make -j$(nproc) ./test/bolt_unit_tests ``` +Builds are portable by default: they target a fixed x86-64 baseline (AVX2) +rather than the CPU of the machine doing the build, so the binaries can be +copied to other machines. For a build you will only run locally, add +`-DBOLT_NATIVE_OPTIMIZATIONS=ON` to tune it for your own CPU. + +After building, `scripts/smoke_test.sh ` starts `bolt` and every +demo program and reports any that hang or crash. + +To use a local model, put a GGUF file in `./models` (or +`~/.local/share/bolt/models`) and start `bolt_terminal_ai` or +`demo_direct_gguf` from that directory; the first model found is loaded. +`BOLT_SMOKE_MODEL=/path/to/model.gguf scripts/smoke_test.sh ` +adds a check that the model loads and generates text. + ### Package Manager Integration Features - **🔧 Multi-Manager Support**: vcpkg (primary), Conan (alternative), system packages (fallback) diff --git a/bolt_terminal_ai.cpp b/bolt_terminal_ai.cpp index 6594ff0b..70792966 100644 --- a/bolt_terminal_ai.cpp +++ b/bolt_terminal_ai.cpp @@ -2,7 +2,15 @@ #include #include #include +#include +#include +#ifdef _WIN32 +#include // For _isatty / _fileno +#define isatty _isatty +#define fileno _fileno +#else #include // For isatty +#endif class BoltTerminalAI { private: diff --git a/cmake/platforms/Linux.cmake b/cmake/platforms/Linux.cmake index 9e0a7d13..f0f3d371 100644 --- a/cmake/platforms/Linux.cmake +++ b/cmake/platforms/Linux.cmake @@ -26,7 +26,12 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "GNU") # Optimization settings if(CMAKE_BUILD_TYPE MATCHES Release) - add_compile_options(-O3 -DNDEBUG -march=native) + add_compile_options(-O3 -DNDEBUG) + # -march=native ties the binary to the build machine's CPU; only use + # it when explicitly requested (see BOLT_NATIVE_OPTIMIZATIONS). + if(BOLT_NATIVE_OPTIMIZATIONS) + add_compile_options(-march=native) + endif() elseif(CMAKE_BUILD_TYPE MATCHES Debug) add_compile_options(-g -O0 -fno-omit-frame-pointer) endif() @@ -123,9 +128,13 @@ set(CPACK_RPM_PACKAGE_REQUIRES "libcurl >= 7.0, jsoncpp >= 1.9, glfw >= 3.3, mes set(CPACK_RPM_PACKAGE_GROUP "Development/Tools") set(CPACK_RPM_PACKAGE_LICENSE "MIT") -# Runtime library paths +# Runtime library paths. The same relocatable rpath is used in the build tree +# and after install: $ORIGIN and $ORIGIN/bin let programs run straight from the +# build directory (libbolt_lib.so sits next to them, llama.cpp's libraries in +# bin/) and from an unpacked tarball; $ORIGIN/../lib covers an installed +# bin/ + lib/ layout. set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) -set(CMAKE_INSTALL_RPATH "\$ORIGIN/../lib:\$ORIGIN/lib:/usr/local/lib") +set(CMAKE_INSTALL_RPATH "\$ORIGIN:\$ORIGIN/bin:\$ORIGIN/../lib:\$ORIGIN/lib:/usr/local/lib") # Distribution-specific optimizations if(LINUX_DISTRO MATCHES "ubuntu|debian") diff --git a/cmake/platforms/macOS.cmake b/cmake/platforms/macOS.cmake index 0b259fe1..8ebced90 100644 --- a/cmake/platforms/macOS.cmake +++ b/cmake/platforms/macOS.cmake @@ -109,7 +109,11 @@ if(BOLT_BUILD_UNIVERSAL) endif() # macOS-specific runtime settings -set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) +# Keep build-tree rpaths while building. With the install rpath +# (@executable_path/../lib) baked in at build time, executables in the build +# tree cannot find libbolt_lib/libllama/libggml and every test aborts in +# dyld. CMake rewrites the rpath to CMAKE_INSTALL_RPATH on install. +set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) set(CMAKE_INSTALL_RPATH "@executable_path/../lib;@loader_path/../lib") set(CMAKE_MACOSX_RPATH TRUE) diff --git a/demo_advanced_ai_features.cpp b/demo_advanced_ai_features.cpp index 60c544d2..a9b19566 100644 --- a/demo_advanced_ai_features.cpp +++ b/demo_advanced_ai_features.cpp @@ -1,6 +1,8 @@ #include #include #include +#include +#include #include #include #include @@ -136,8 +138,20 @@ void handleRequest(const Request& req) { displayMenu(); int choice; - std::cin >> choice; - std::cin.ignore(); // Clear the newline + if (!(std::cin >> choice)) { + if (std::cin.eof()) { + // Input closed: exit instead of redrawing the menu forever. + std::cout << "\n"; + return; + } + // Not a number: clear the error and drop the rest of the + // line, otherwise every later read fails immediately. + std::cin.clear(); + std::cin.ignore(std::numeric_limits::max(), '\n'); + std::cout << "❌ Invalid choice. Please try again.\n"; + continue; + } + std::cin.ignore(std::numeric_limits::max(), '\n'); switch (choice) { case 1: diff --git a/demo_widget_framework.cpp b/demo_widget_framework.cpp index 41164499..97e295c0 100644 --- a/demo_widget_framework.cpp +++ b/demo_widget_framework.cpp @@ -7,8 +7,12 @@ #include #include #include +#ifdef __APPLE__ +#include // macOS ships OpenGL headers as a framework +#else #include #endif +#endif #include #include diff --git a/include/bolt/bolt.hpp b/include/bolt/bolt.hpp index 4793d61f..6ccd2f3a 100644 --- a/include/bolt/bolt.hpp +++ b/include/bolt/bolt.hpp @@ -52,6 +52,7 @@ class BoltApp { BoltApp() = default; std::unique_ptr workbench_; bool running_ = false; + bool initialized_ = false; }; } // namespace bolt diff --git a/include/bolt/editor/bracket_matcher.hpp b/include/bolt/editor/bracket_matcher.hpp index 9f97112f..d172519d 100644 --- a/include/bolt/editor/bracket_matcher.hpp +++ b/include/bolt/editor/bracket_matcher.hpp @@ -69,7 +69,9 @@ class BracketMatcher { char openBracket = getMatchingBracket(closeBracket); std::stack brackets; - for (size_t i = closePos; i-- > 0;) { + // Start at closePos itself so the closing bracket is counted; + // otherwise the first opening bracket pops an empty stack. + for (size_t i = closePos + 1; i-- > 0;) { if (text[i] == closeBracket) { brackets.push(closeBracket); } else if (text[i] == openBracket) { diff --git a/include/bolt/network/network_metrics.hpp b/include/bolt/network/network_metrics.hpp index 599493db..936481ae 100644 --- a/include/bolt/network/network_metrics.hpp +++ b/include/bolt/network/network_metrics.hpp @@ -224,6 +224,8 @@ class BandwidthTracker { double peakBandwidth_; void cleanup(); + // Requires mutex_ to be held by the caller. + double currentBandwidthLocked() const; }; /** @@ -290,6 +292,12 @@ class NetworkMetrics { bool detailedMetrics_; NetworkStats& getOrCreateEndpointStats(const std::string& endpoint); + + // Unlocked variants of the bandwidth getters; metricsMutex_ must be held. + double globalBandwidthInLocked() const; + double globalBandwidthOutLocked() const; + double endpointBandwidthInLocked(const std::string& endpoint) const; + double endpointBandwidthOutLocked(const std::string& endpoint) const; BandwidthTracker& getOrCreateBandwidthTracker( std::unordered_map>& trackers, const std::string& endpoint diff --git a/scripts/smoke_test.sh b/scripts/smoke_test.sh new file mode 100755 index 00000000..fd6afff7 --- /dev/null +++ b/scripts/smoke_test.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash +# Smoke test for a built tree: checks that the bolt application and the demo +# programs actually start, respond and exit, rather than only that they link. +# +# Usage: scripts/smoke_test.sh [build-dir] (default: build) +# +# A program fails the smoke test if it hangs (timeout) or dies from a signal. +# A demo that exits with an ordinary non-zero status is reported but not +# treated as a failure, because several demos need tools that may not be +# installed (clangd, a model file). GUI programs are started under xvfb when +# there is no display and must stay up for a few seconds. +# +# Set BOLT_SMOKE_MODEL=/path/to/model.gguf to also load a real model and +# generate text with it. + +set -u + +BUILD_DIR="${1:-build}" +TIMEOUT_SECS="${SMOKE_TIMEOUT:-60}" + +if [ ! -x "$BUILD_DIR/bolt" ]; then + echo "error: $BUILD_DIR/bolt not found or not executable" >&2 + exit 2 +fi + +BUILD_DIR="$(cd "$BUILD_DIR" && pwd)" + +failures=0 +pass() { echo " ok $1"; } +fail() { echo " FAIL $1"; failures=$((failures + 1)); } + +echo "== shared libraries ==" + +# The programs must find their own libraries from the build tree without any +# help from the environment, so this check runs before LD_LIBRARY_PATH is set. +if out="$(env -u LD_LIBRARY_PATH timeout "$TIMEOUT_SECS" "$BUILD_DIR/bolt" --version 2>&1)"; then + pass "bolt starts without LD_LIBRARY_PATH" +else + fail "bolt does not start without LD_LIBRARY_PATH: $out" +fi + +export LD_LIBRARY_PATH="$BUILD_DIR:$BUILD_DIR/bin:${LD_LIBRARY_PATH:-}" + +echo "== bolt command line ==" + +out="$(timeout "$TIMEOUT_SECS" "$BUILD_DIR/bolt" --version 2>&1)"; rc=$? +if [ "$rc" -eq 0 ] && printf '%s' "$out" | grep -q '^bolt '; then + pass "--version ($out)" +else + fail "--version (exit $rc): $out" +fi + +out="$(timeout "$TIMEOUT_SECS" "$BUILD_DIR/bolt" --help 2>&1)"; rc=$? +if [ "$rc" -eq 0 ] && printf '%s' "$out" | grep -q 'Usage:'; then + pass "--help" +else + fail "--help (exit $rc)" +fi + +timeout "$TIMEOUT_SECS" "$BUILD_DIR/bolt" --no-such-option >/dev/null 2>&1; rc=$? +if [ "$rc" -eq 2 ]; then + pass "unknown option is rejected" +else + fail "unknown option should exit 2, got $rc" +fi + +echo "== bolt interactive session ==" + +out="$(printf 'hello smoke test\n/help\n/exit\n' | timeout "$TIMEOUT_SECS" "$BUILD_DIR/bolt" 2>&1)"; rc=$? +if [ "$rc" -eq 0 ] && printf '%s' "$out" | grep -q 'Echo: hello smoke test' \ + && printf '%s' "$out" | grep -q 'Available commands'; then + pass "scripted session answers and exits on /exit" +else + fail "scripted session (exit $rc)" +fi + +timeout "$TIMEOUT_SECS" "$BUILD_DIR/bolt" /dev/null 2>&1; rc=$? +if [ "$rc" -eq 0 ]; then + pass "exits cleanly at end of input" +else + fail "end of input (exit $rc; 124 means it hung)" +fi + +echo "== demo programs ==" + +# Programs that open a window. They are run under a virtual display when no +# real one is available, and are expected to keep running until stopped. +gui_programs="demo_lsp_ui_integration demo_widget_framework gui_main" +GUI_SECS="${SMOKE_GUI_SECS:-10}" + +for prog in "$BUILD_DIR"/demo_* "$BUILD_DIR"/bolt_terminal_ai "$BUILD_DIR"/benchmark_tool "$BUILD_DIR"/gui_main; do + if [ ! -f "$prog" ] || [ ! -x "$prog" ]; then + continue + fi + name="$(basename "$prog")" + + case " $gui_programs " in + *" $name "*) + if [ -n "${DISPLAY:-}" ] || [ -n "${WAYLAND_DISPLAY:-}" ]; then + timeout "$GUI_SECS" "$prog" /dev/null 2>&1; rc=$? + elif command -v xvfb-run >/dev/null 2>&1; then + LIBGL_ALWAYS_SOFTWARE=1 xvfb-run -a timeout "$GUI_SECS" "$prog" /dev/null 2>&1; rc=$? + else + echo " skip $name (needs a display; install xvfb to test it headlessly)" + continue + fi + # 124 means it was still running when the time was up, which is + # what a healthy GUI does; 0 means it closed by itself. + if [ "$rc" -eq 124 ] || [ "$rc" -eq 0 ]; then + pass "$name (GUI started and stayed up for ${GUI_SECS}s)" + else + fail "$name GUI exited with status $rc" + fi + continue + ;; + esac + + timeout "$TIMEOUT_SECS" "$prog" /dev/null 2>&1; rc=$? + if [ "$rc" -eq 0 ]; then + pass "$name" + elif [ "$rc" -eq 124 ]; then + fail "$name hung (no exit within ${TIMEOUT_SECS}s)" + elif [ "$rc" -ge 126 ]; then + fail "$name crashed or could not start (exit $rc)" + else + echo " note $name exited $rc (usually a missing optional tool)" + fi +done + +# Optional: real inference with a GGUF model. Set BOLT_SMOKE_MODEL to a model +# file; the program looks for models in ./models, so it is run from a scratch +# directory that has the model linked there. +if [ -n "${BOLT_SMOKE_MODEL:-}" ]; then + echo "== model inference ==" + if [ ! -f "$BOLT_SMOKE_MODEL" ]; then + fail "BOLT_SMOKE_MODEL=$BOLT_SMOKE_MODEL does not exist" + elif [ ! -x "$BUILD_DIR/demo_direct_gguf" ]; then + fail "demo_direct_gguf is not built, cannot test model inference" + else + model_path="$(cd "$(dirname "$BOLT_SMOKE_MODEL")" && pwd)/$(basename "$BOLT_SMOKE_MODEL")" + work_dir="$(mktemp -d)" + mkdir -p "$work_dir/models" + ln -s "$model_path" "$work_dir/models/$(basename "$model_path")" + out="$(cd "$work_dir" && timeout "${SMOKE_MODEL_TIMEOUT:-300}" "$BUILD_DIR/demo_direct_gguf" &1)"; rc=$? + rm -rf "$work_dir" + if [ "$rc" -ne 0 ]; then + fail "model inference exited $rc" + elif ! printf '%s' "$out" | grep -q 'Model loaded successfully'; then + fail "model was not loaded" + elif ! printf '%s' "$out" | grep -q 'Current provider: direct_gguf'; then + fail "AI manager did not switch to the loaded model" + elif printf '%s' "$out" | grep -q 'Failed: [1-9]'; then + fail "model inference reported failed requests" + else + pass "model loads and generates text ($(basename "$model_path"))" + fi + fi +fi + +echo +if [ "$failures" -eq 0 ]; then + echo "Smoke test passed." + exit 0 +fi +echo "Smoke test failed: $failures problem(s)." +exit 1 diff --git a/src/bolt/core/bolt.cpp b/src/bolt/core/bolt.cpp index 97114c27..2a9314c8 100644 --- a/src/bolt/core/bolt.cpp +++ b/src/bolt/core/bolt.cpp @@ -70,6 +70,13 @@ class BoltImpl { }; void BoltApp::initialize() { + // main() calls initialize() and run() calls it again; set up only once so + // the banner is not printed twice and shortcuts are not registered twice. + if (initialized_) { + return; + } + initialized_ = true; + std::cout << "Bolt C++ - AI-Powered Development Environment\n"; std::cout << "Initializing keyboard shortcuts system...\n"; @@ -129,8 +136,15 @@ void BoltApp::run() { std::string input; while (running_) { - std::cout << "\nUser > "; - std::getline(std::cin, input); + std::cout << "\nUser > " << std::flush; + if (!std::getline(std::cin, input)) { + // End of input (Ctrl+D, closed pipe or redirected file): leave + // the loop instead of spinning on a stream that can never + // produce another line. + std::cout << "\n"; + running_ = false; + break; + } if (!input.empty()) { processUserInput(input); diff --git a/src/bolt/editor/bracket_matcher.cpp b/src/bolt/editor/bracket_matcher.cpp index e4982a8f..a32c88ca 100644 --- a/src/bolt/editor/bracket_matcher.cpp +++ b/src/bolt/editor/bracket_matcher.cpp @@ -63,7 +63,9 @@ std::optional BracketMatcher::findOpeningBracket(const std::string char openBracket = getMatchingBracket(closeBracket); std::stack brackets; - for (size_t i = closePos; i-- > 0;) { + // Start at closePos itself so the closing bracket is counted; + // otherwise the first opening bracket pops an empty stack. + for (size_t i = closePos + 1; i-- > 0;) { if (text[i] == closeBracket) { brackets.push(closeBracket); } else if (text[i] == openBracket) { diff --git a/src/bolt/git/git_repository.cpp b/src/bolt/git/git_repository.cpp index 5398f8a4..1dd97808 100644 --- a/src/bolt/git/git_repository.cpp +++ b/src/bolt/git/git_repository.cpp @@ -120,16 +120,25 @@ bool GitRepository::commit(const std::string& message) { return success; } -bool GitRepository::push(const std::string& remote, const std::string& branch) { - std::vector args = {"push"}; +namespace { +// Arguments for "git push" / "git pull": the branch is only meaningful when a +// remote is given. +std::vector remoteCommandArgs(const std::string& command, + const std::string& remote, + const std::string& branch) { + std::vector args = {command}; if (!remote.empty()) { args.push_back(remote); if (!branch.empty()) { args.push_back(branch); } } - - auto [success, output] = executeGitCommand(args); + return args; +} +} // namespace + +bool GitRepository::push(const std::string& remote, const std::string& branch) { + auto [success, output] = executeGitCommand(remoteCommandArgs("push", remote, branch)); if (statusCallback_) { statusCallback_(success, success ? "Pushed to remote" : "Failed to push: " + output); @@ -139,15 +148,7 @@ bool GitRepository::push(const std::string& remote, const std::string& branch) { } bool GitRepository::pull(const std::string& remote, const std::string& branch) { - std::vector args = {"pull"}; - if (!remote.empty()) { - args.push_back(remote); - if (!branch.empty()) { - args.push_back(branch); - } - } - - auto [success, output] = executeGitCommand(args); + auto [success, output] = executeGitCommand(remoteCommandArgs("pull", remote, branch)); if (statusCallback_) { statusCallback_(success, success ? "Pulled from remote" : "Failed to pull: " + output); @@ -215,7 +216,13 @@ std::pair GitRepository::executeGitCommand(const std::vector< for (const auto& arg : args) { command += " " + arg; } +#ifdef _WIN32 + // cmd.exe has no /dev/null; redirecting there makes every command fail + // with "The system cannot find the path specified." + command += " 2>NUL"; +#else command += " 2>/dev/null"; +#endif FILE* rawPipe = popen(command.c_str(), "r"); if (!rawPipe) { diff --git a/src/bolt/gui/bolt_gui_app.cpp b/src/bolt/gui/bolt_gui_app.cpp index 5546815c..9e9cbaf3 100644 --- a/src/bolt/gui/bolt_gui_app.cpp +++ b/src/bolt/gui/bolt_gui_app.cpp @@ -8,7 +8,11 @@ #include #include #include +#ifdef __APPLE__ +#include // macOS ships OpenGL headers as a framework +#else #include +#endif #include #include diff --git a/src/bolt/main.cpp b/src/bolt/main.cpp index 459e1a46..f30e836f 100644 --- a/src/bolt/main.cpp +++ b/src/bolt/main.cpp @@ -1,8 +1,42 @@ #include "bolt/bolt.hpp" #include +#include + +#ifndef BOLT_VERSION +#define BOLT_VERSION "unknown" +#endif + +namespace { + +void printUsage(const char* program) { + std::cout << "Bolt C++ - AI-Powered Development Environment\n\n" + << "Usage: " << program << " [options]\n\n" + << "Options:\n" + << " -h, --help Show this help message and exit\n" + << " -v, --version Show version information and exit\n\n" + << "With no options, bolt starts an interactive session.\n" + << "Type /help inside the session for commands and /exit to quit.\n"; +} + +} // namespace + +int main(int argc, char* argv[]) { + for (int i = 1; i < argc; ++i) { + const std::string arg = argv[i]; + if (arg == "-h" || arg == "--help") { + printUsage(argv[0]); + return 0; + } + if (arg == "-v" || arg == "--version") { + std::cout << "bolt " << BOLT_VERSION << "\n"; + return 0; + } + std::cerr << "bolt: unknown option '" << arg << "'\n\n"; + printUsage(argv[0]); + return 2; + } -int main() { try { auto& app = bolt::BoltApp::getInstance(); app.initialize(); diff --git a/src/bolt/network/network_metrics.cpp b/src/bolt/network/network_metrics.cpp index 9aa9f704..2aaaa35b 100644 --- a/src/bolt/network/network_metrics.cpp +++ b/src/bolt/network/network_metrics.cpp @@ -19,8 +19,10 @@ void BandwidthTracker::recordBytes(uint64_t bytes) { cleanup(); - // Update peak bandwidth - double currentBandwidth = getCurrentBandwidth(); + // Update peak bandwidth. mutex_ is already held here, so use the + // unlocked helper: calling getCurrentBandwidth() would lock the same + // non-recursive mutex again and deadlock. + double currentBandwidth = currentBandwidthLocked(); if (currentBandwidth > peakBandwidth_) { peakBandwidth_ = currentBandwidth; } @@ -28,7 +30,10 @@ void BandwidthTracker::recordBytes(uint64_t bytes) { double BandwidthTracker::getCurrentBandwidth() const { std::lock_guard lock(mutex_); - + return currentBandwidthLocked(); +} + +double BandwidthTracker::currentBandwidthLocked() const { if (dataPoints_.size() < 2) { return 0.0; } @@ -287,24 +292,43 @@ std::vector NetworkMetrics::getEndpoints() const { double NetworkMetrics::getGlobalBandwidthIn() const { std::lock_guard lock(metricsMutex_); - return globalBandwidthIn_ ? globalBandwidthIn_->getCurrentBandwidth() : 0.0; + return globalBandwidthInLocked(); } double NetworkMetrics::getGlobalBandwidthOut() const { std::lock_guard lock(metricsMutex_); - return globalBandwidthOut_ ? globalBandwidthOut_->getCurrentBandwidth() : 0.0; + return globalBandwidthOutLocked(); } double NetworkMetrics::getEndpointBandwidthIn(const std::string& endpoint) const { std::lock_guard lock(metricsMutex_); - - auto it = endpointBandwidthIn_.find(endpoint); - return it != endpointBandwidthIn_.end() ? it->second->getCurrentBandwidth() : 0.0; + return endpointBandwidthInLocked(endpoint); } double NetworkMetrics::getEndpointBandwidthOut(const std::string& endpoint) const { std::lock_guard lock(metricsMutex_); - + return endpointBandwidthOutLocked(endpoint); +} + +// The *Locked helpers below require metricsMutex_ to be held by the caller. +// The report generators hold the mutex for their whole body, so they must use +// these instead of the public getters: metricsMutex_ is not recursive and +// locking it twice on one thread deadlocks. + +double NetworkMetrics::globalBandwidthInLocked() const { + return globalBandwidthIn_ ? globalBandwidthIn_->getCurrentBandwidth() : 0.0; +} + +double NetworkMetrics::globalBandwidthOutLocked() const { + return globalBandwidthOut_ ? globalBandwidthOut_->getCurrentBandwidth() : 0.0; +} + +double NetworkMetrics::endpointBandwidthInLocked(const std::string& endpoint) const { + auto it = endpointBandwidthIn_.find(endpoint); + return it != endpointBandwidthIn_.end() ? it->second->getCurrentBandwidth() : 0.0; +} + +double NetworkMetrics::endpointBandwidthOutLocked(const std::string& endpoint) const { auto it = endpointBandwidthOut_.find(endpoint); return it != endpointBandwidthOut_.end() ? it->second->getCurrentBandwidth() : 0.0; } @@ -409,8 +433,8 @@ std::string NetworkMetrics::generateReport() const { } report << " Bandwidth: in=" << std::fixed << std::setprecision(2) - << getGlobalBandwidthIn() / 1024.0 << " KB/s, " - << "out=" << getGlobalBandwidthOut() / 1024.0 << " KB/s\n"; + << globalBandwidthInLocked() / 1024.0 << " KB/s, " + << "out=" << globalBandwidthOutLocked() / 1024.0 << " KB/s\n"; report << " Errors: send=" << globalStats_.sendErrors.load() << ", receive=" << globalStats_.receiveErrors.load() @@ -432,8 +456,8 @@ std::string NetworkMetrics::generateReport() const { } report << " Bandwidth: in=" << std::fixed << std::setprecision(2) - << getEndpointBandwidthIn(name) / 1024.0 << " KB/s, " - << "out=" << getEndpointBandwidthOut(name) / 1024.0 << " KB/s\n"; + << endpointBandwidthInLocked(name) / 1024.0 << " KB/s, " + << "out=" << endpointBandwidthOutLocked(name) / 1024.0 << " KB/s\n"; } } @@ -477,8 +501,8 @@ std::string NetworkMetrics::generateEndpointReport(const std::string& endpoint) report << "Bandwidth:\n"; report << " Inbound: " << std::fixed << std::setprecision(2) - << getEndpointBandwidthIn(endpoint) / 1024.0 << " KB/s\n"; - report << " Outbound: " << getEndpointBandwidthOut(endpoint) / 1024.0 << " KB/s\n\n"; + << endpointBandwidthInLocked(endpoint) / 1024.0 << " KB/s\n"; + report << " Outbound: " << endpointBandwidthOutLocked(endpoint) / 1024.0 << " KB/s\n\n"; report << "Errors:\n"; report << " Send Errors: " << stats.sendErrors.load() << "\n"; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index a6de06c1..c681fbc5 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -10,6 +10,14 @@ option(BOLT_ENABLE_INTEGRATION_TESTS "Enable integration tests" ON) option(BOLT_ENABLE_UNIT_TESTS "Enable unit tests" ON) option(BOLT_ENABLE_PERFORMANCE_TESTS "Enable performance tests" OFF) +# Test programs are built into /test and are not installed, so on Linux +# point their rpath at the build root (libbolt_lib.so) and /bin +# (llama.cpp's libraries). They can then be run directly, e.g. +# ./test/bolt_unit_tests, without setting LD_LIBRARY_PATH. +if(UNIX AND NOT APPLE) + set(CMAKE_INSTALL_RPATH "\$ORIGIN/..:\$ORIGIN/../bin") +endif() + # Find if GoogleTest is available find_package(GTest QUIET) @@ -350,9 +358,11 @@ if(BOLT_ENABLE_UNIT_TESTS) add_test(NAME unit_memory_leak_detector_tests COMMAND bolt_unit_tests MemoryLeakDetector) add_test(NAME unit_sanitizer_integration_tests COMMAND bolt_sanitizer_tests SanitizerIntegration) add_test(NAME unit_collaboration_tests COMMAND bolt_collaboration_tests) - # Network tests - DISABLED: Requires network server, times out in CI - # The executable is still built and can be run manually for local testing - # add_test(NAME unit_network_tests COMMAND bolt_network_tests) + # Network tests. These were disabled as "requires network server, times + # out in CI". The timeout was a self-deadlock in BandwidthTracker and + # NetworkMetrics, not a missing server: the tests that need a listener + # skip themselves when the connection fails. + add_test(NAME unit_network_tests COMMAND bolt_network_tests) # LSP tests - DISABLED: executable not built # add_test(NAME unit_lsp_tests COMMAND bolt_lsp_tests) @@ -431,6 +441,7 @@ if(BOLT_ENABLE_UNIT_TESTS) unit_ggml_tests unit_ai_models_tests unit_debugger_tests unit_logging_tests unit_memory_leak_detector_tests unit_sanitizer_integration_tests unit_collaboration_tests + unit_network_tests e2e_comprehensive_all e2e_string_utils e2e_math_utils e2e_data_processor e2e_filesystem_utils e2e_memory_manager e2e_message_handler e2e_chat_store e2e_workbench_store diff --git a/test/test_ai_models_complete.cpp b/test/test_ai_models_complete.cpp index 702449fc..61df107d 100644 --- a/test/test_ai_models_complete.cpp +++ b/test/test_ai_models_complete.cpp @@ -84,10 +84,11 @@ BOLT_TEST(AIModels, GGMLTensorTypes) { const size_t mem_size = 5 * 1024 * 1024; // 5MB bolt::GGMLContext context(mem_size); - // Test different tensor types - auto* fp32_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 100); - auto* fp16_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F16, 100); - auto* q8_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_Q8_0, 100); + // Test different tensor types. The element count must be a multiple of + // the Q8_0 block size (32): ggml asserts on that in debug builds. + auto* fp32_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 128); + auto* fp16_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F16, 128); + auto* q8_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_Q8_0, 128); BOLT_ASSERT_NOT_NULL(fp32_tensor); BOLT_ASSERT_NOT_NULL(fp16_tensor); diff --git a/test/test_ai_models_simple.cpp b/test/test_ai_models_simple.cpp index c22dd190..522587b7 100644 --- a/test/test_ai_models_simple.cpp +++ b/test/test_ai_models_simple.cpp @@ -84,10 +84,11 @@ BOLT_TEST(AIModels, GGMLTensorTypes) { const size_t mem_size = 5 * 1024 * 1024; // 5MB bolt::GGMLContext context(mem_size); - // Test different tensor types - auto* fp32_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 100); - auto* fp16_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F16, 100); - auto* q8_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_Q8_0, 100); + // Test different tensor types. The element count must be a multiple of + // the Q8_0 block size (32): ggml asserts on that in debug builds. + auto* fp32_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 128); + auto* fp16_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F16, 128); + auto* q8_tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_Q8_0, 128); BOLT_ASSERT_NOT_NULL(fp32_tensor); BOLT_ASSERT_NOT_NULL(fp16_tensor); diff --git a/test/test_comprehensive_e2e.cpp b/test/test_comprehensive_e2e.cpp index 12a5fd0f..1d743b9e 100644 --- a/test/test_comprehensive_e2e.cpp +++ b/test/test_comprehensive_e2e.cpp @@ -2421,6 +2421,26 @@ BOLT_TEST(E2E_BoltApp, ChatEmptyMessage) { BOLT_ASSERT_EQ("", msg.getContent()); } +// Regression test: run() used to loop forever once standard input reached +// end of file. Feed it scripted input followed by EOF and require it to +// return. If the bug comes back this test hangs and CTest times it out. +BOLT_TEST(E2E_BoltApp, RunReturnsAtEndOfInput) { + std::istringstream scripted("hello\n/help\n"); + std::ostringstream captured; + std::streambuf* oldIn = std::cin.rdbuf(scripted.rdbuf()); + std::streambuf* oldOut = std::cout.rdbuf(captured.rdbuf()); + + bolt::BoltApp::getInstance().run(); + + std::cin.rdbuf(oldIn); + std::cin.clear(); + std::cout.rdbuf(oldOut); + + const std::string output = captured.str(); + BOLT_ASSERT_TRUE(output.find("Echo: hello") != std::string::npos); + BOLT_ASSERT_TRUE(output.find("Available commands") != std::string::npos); +} + // ============================================================================ // E2E_BenchmarkSuite: Test BenchmarkSuite functions // ============================================================================ diff --git a/test/test_debugger.cpp b/test/test_debugger.cpp index 07dbdceb..afea82ee 100644 --- a/test/test_debugger.cpp +++ b/test/test_debugger.cpp @@ -215,11 +215,13 @@ BOLT_TEST(Debugger, VM_CallStackInspection) { } BOLT_TEST(Debugger, DebuggerInterface_EventCallback) { - auto debugger = std::make_unique(); - + // Declared before the debugger so they outlive it: the debugger's + // destructor stops the session and invokes the callback once more. bool callbackCalled = false; - DebugEvent lastEvent; + DebugEvent lastEvent{}; std::string lastMessage; + + auto debugger = std::make_unique(); // Set up event callback debugger->set_event_callback([&](DebugEvent event, const std::string& message) { diff --git a/test/test_error_handling.cpp b/test/test_error_handling.cpp index 16ccebbd..00d82c8e 100644 --- a/test/test_error_handling.cpp +++ b/test/test_error_handling.cpp @@ -216,6 +216,9 @@ BOLT_TEST(ChatStoreErrors, MessageValidation) { // Valid message should work bolt::SimpleChatMessage validMsg("user", "Hello"); store.addMessage(validMsg); // Should not throw + // The store is a process-wide singleton: leave it as we found it so + // tests that run afterwards (order varies by toolchain) see defaults. + store.clearMessages(); // Invalid messages should throw BOLT_ASSERT_THROWS(bolt::StoreException, @@ -253,6 +256,10 @@ BOLT_TEST(ChatStoreErrors, ThreadSafety) { store.setShowChat(false); bool showChat = store.getShowChat(); BOLT_ASSERT_FALSE(showChat); + + // Restore the singleton's defaults for tests that run afterwards. + store.setChatStarted(false); + store.setShowChat(true); } // ===== Editor Store Error Handling Tests ===== @@ -354,6 +361,9 @@ BOLT_TEST(WorkbenchStoreErrors, ViewValidation) { std::string oversizedView(1000, 'x'); BOLT_ASSERT_THROWS(bolt::StoreException, store.setCurrentView(oversizedView)); + + // Restore the singleton's default for tests that run afterwards. + store.setCurrentView("code"); } BOLT_TEST(WorkbenchStoreErrors, FilePathValidation) { @@ -393,6 +403,10 @@ BOLT_TEST(WorkbenchStoreErrors, ThreadSafety) { store.toggleTerminal(true); bool terminal = store.getShowTerminal(); BOLT_ASSERT_TRUE(terminal); + + // Restore the singleton's defaults for tests that run afterwards. + store.setShowWorkbench(false); + store.toggleTerminal(false); } // ===== Error Recovery Tests ===== diff --git a/test/test_extended_e2e.cpp b/test/test_extended_e2e.cpp index 08665b81..0c1c71b6 100644 --- a/test/test_extended_e2e.cpp +++ b/test/test_extended_e2e.cpp @@ -33,6 +33,12 @@ #include #include +// (pulled in by some of the headers above on Windows) defines +// DELETE as a macro, which breaks OperationType::DELETE. +#ifdef DELETE +#undef DELETE +#endif + using namespace bolt::collaboration; // ═══════════════════════════════════════════════════════════════════════ diff --git a/test/test_file_tree.cpp b/test/test_file_tree.cpp index 8ca77d25..8cd34a85 100644 --- a/test/test_file_tree.cpp +++ b/test/test_file_tree.cpp @@ -123,7 +123,9 @@ BOLT_TEST(FileTree, FileSelection) { auto selectedNode = manager.getSelectedNode(); BOLT_ASSERT(selectedNode != nullptr); - BOLT_ASSERT_EQ(selectedPath, selectedNode->fullPath); + // Compare as paths: on Windows the tree joins components with '\\'. + BOLT_ASSERT(std::filesystem::path(selectedPath) == + std::filesystem::path(selectedNode->fullPath)); BOLT_ASSERT(selectedNode->isSelected); manager.clearSelection(); diff --git a/test/test_logging.cpp b/test/test_logging.cpp index a6d79d1a..4b96220c 100644 --- a/test/test_logging.cpp +++ b/test/test_logging.cpp @@ -2,10 +2,62 @@ #include "bolt/core/logging.hpp" #include "bolt/core/error_handling.hpp" #include +#include #include #include +#include #include #include +#include + +namespace { +// Best-effort cleanup of a test log file. Windows refuses to delete a file +// that a sink or stream still has open, and that must not fail the test. +void removeTestFile(const std::filesystem::path& file) { + std::error_code ec; + std::filesystem::remove(file, ec); +} + +// Removes a rotating log file and its numbered backups (file, file.1, ...). +void removeRotatedFiles(const std::string& baseFile) { + for (int i = 0; i <= 5; ++i) { + removeTestFile(baseFile + (i > 0 ? "." + std::to_string(i) : "")); + } +} + +int countLines(const std::string& path) { + std::ifstream file(path); + std::string line; + int lineCount = 0; + while (std::getline(file, line)) { + lineCount++; + } + return lineCount; +} + +bool fileContainsAll(const std::string& path, std::initializer_list words) { + std::ifstream file(path); + std::string content((std::istreambuf_iterator(file)), + std::istreambuf_iterator()); + for (const char* word : words) { + if (content.find(word) == std::string::npos) { + return false; + } + } + return true; +} + +// One message at every level, from TRACE to FATAL. +void logAtEveryLevel(bolt::Logger& logger) { + logger.trace("Trace message"); + logger.debug("Debug message"); + logger.info("Info message"); + logger.warn("Warning message"); + logger.error("Error message"); + logger.fatal("Fatal message"); + logger.flush(); +} +} // namespace // ===== Basic Logging Tests ===== @@ -93,7 +145,7 @@ BOLT_TEST(Logging, FileSink) { // Clean up any existing file if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } { @@ -116,19 +168,14 @@ BOLT_TEST(Logging, FileSink) { BOLT_ASSERT_TRUE(content == "Test message for file"); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); } BOLT_TEST(Logging, RotatingFileSink) { std::string baseFile = "/tmp/bolt_rotating_test.log"; // Clean up any existing files - for (int i = 0; i <= 5; ++i) { - std::string file = baseFile + (i > 0 ? "." + std::to_string(i) : ""); - if (std::filesystem::exists(file)) { - std::filesystem::remove(file); - } - } + removeRotatedFiles(baseFile); { // Create sink with small file size to trigger rotation @@ -152,12 +199,7 @@ BOLT_TEST(Logging, RotatingFileSink) { BOLT_ASSERT_TRUE(std::filesystem::exists(baseFile)); // Clean up - for (int i = 0; i <= 5; ++i) { - std::string file = baseFile + (i > 0 ? "." + std::to_string(i) : ""); - if (std::filesystem::exists(file)) { - std::filesystem::remove(file); - } - } + removeRotatedFiles(baseFile); } // ===== Filter Tests ===== @@ -221,7 +263,7 @@ BOLT_TEST(Logging, LoggerWithSinks) { // Add test file sink std::string testFile = "/tmp/bolt_logger_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } logger.addSink(std::make_unique(testFile)); @@ -247,7 +289,7 @@ BOLT_TEST(Logging, LoggerWithSinks) { BOLT_ASSERT_TRUE(lineCount == 3); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); } BOLT_TEST(Logging, LoggerLevelFiltering) { @@ -255,34 +297,18 @@ BOLT_TEST(Logging, LoggerLevelFiltering) { std::string testFile = "/tmp/bolt_level_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } logger.addSink(std::make_unique(testFile)); - // These should be filtered out - logger.trace("Trace message"); - logger.debug("Debug message"); - logger.info("Info message"); - - // These should be logged - logger.warn("Warning message"); - logger.error("Error message"); - logger.fatal("Fatal message"); + // TRACE, DEBUG and INFO are below the logger's level and are dropped. + logAtEveryLevel(logger); - logger.flush(); - - // Count lines in file - std::ifstream file(testFile); - std::string line; - int lineCount = 0; - while (std::getline(file, line)) { - lineCount++; - } - BOLT_ASSERT_TRUE(lineCount == 3); // Only WARN, ERROR, FATAL + BOLT_ASSERT_TRUE(countLines(testFile) == 3); // Only WARN, ERROR, FATAL // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); } BOLT_TEST(Logging, LoggerWithFilters) { @@ -290,7 +316,7 @@ BOLT_TEST(Logging, LoggerWithFilters) { std::string testFile = "/tmp/bolt_filter_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } logger.addSink(std::make_unique(testFile)); @@ -299,25 +325,12 @@ BOLT_TEST(Logging, LoggerWithFilters) { BOLT_ASSERT_TRUE(logger.getFilterCount() == 1); // Only ERROR and FATAL should pass through filter - logger.debug("Debug message"); - logger.info("Info message"); - logger.warn("Warning message"); - logger.error("Error message"); - logger.fatal("Fatal message"); + logAtEveryLevel(logger); - logger.flush(); - - // Count lines in file - std::ifstream file(testFile); - std::string line; - int lineCount = 0; - while (std::getline(file, line)) { - lineCount++; - } - BOLT_ASSERT_TRUE(lineCount == 2); // Only ERROR, FATAL + BOLT_ASSERT_TRUE(countLines(testFile) == 2); // Only ERROR, FATAL // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); } BOLT_TEST(Logging, LoggerCategoryLogging) { @@ -325,7 +338,7 @@ BOLT_TEST(Logging, LoggerCategoryLogging) { std::string testFile = "/tmp/bolt_category_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } logger.addSink(std::make_unique(testFile)); @@ -338,18 +351,12 @@ BOLT_TEST(Logging, LoggerCategoryLogging) { logger.flush(); - // Verify messages contain correct categories - std::ifstream file(testFile); - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - - BOLT_ASSERT_TRUE(content.find("CORE") != std::string::npos); - BOLT_ASSERT_TRUE(content.find("MEMORY") != std::string::npos); - BOLT_ASSERT_TRUE(content.find("EDITOR") != std::string::npos); - // AI message might be filtered out due to DEBUG level + // Verify messages contain correct categories. + // The AI message might be filtered out due to DEBUG level. + BOLT_ASSERT_TRUE(fileContainsAll(testFile, {"CORE", "MEMORY", "EDITOR"})); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); } BOLT_TEST(Logging, LoggerMetrics) { @@ -375,7 +382,7 @@ BOLT_TEST(Logging, LoggerEnableDisable) { std::string testFile = "/tmp/bolt_enable_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } logger.addSink(std::make_unique(testFile)); @@ -405,7 +412,7 @@ BOLT_TEST(Logging, LoggerEnableDisable) { BOLT_ASSERT_TRUE(lineCount == 2); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); } // ===== Utility Function Tests ===== @@ -468,7 +475,7 @@ BOLT_TEST(Logging, LogManagerSingleton) { BOLT_TEST(Logging, LogManagerConfiguration) { std::string testFile = "/tmp/bolt_manager_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } // Configure file logging @@ -483,7 +490,7 @@ BOLT_TEST(Logging, LogManagerConfiguration) { BOLT_ASSERT_TRUE(std::filesystem::exists(testFile)); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); bolt::LogManager::reset(); } @@ -492,7 +499,7 @@ BOLT_TEST(Logging, LogManagerConfiguration) { BOLT_TEST(Logging, LoggingMacros) { std::string testFile = "/tmp/bolt_macro_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } bolt::LogManager::configureFileLogging(testFile, bolt::LogLevel::TRACE, true); @@ -519,14 +526,14 @@ BOLT_TEST(Logging, LoggingMacros) { BOLT_ASSERT_TRUE(lineCount == 6); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); bolt::LogManager::reset(); } BOLT_TEST(Logging, CategoryMacros) { std::string testFile = "/tmp/bolt_category_macro_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } bolt::LogManager::configureFileLogging(testFile, bolt::LogLevel::DEBUG, true); @@ -540,17 +547,10 @@ BOLT_TEST(Logging, CategoryMacros) { bolt::LogManager::getInstance().flush(); // Verify messages contain correct categories - std::ifstream file(testFile); - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - - BOLT_ASSERT_TRUE(content.find("CORE") != std::string::npos); - BOLT_ASSERT_TRUE(content.find("MEMORY") != std::string::npos); - BOLT_ASSERT_TRUE(content.find("EDITOR") != std::string::npos); - BOLT_ASSERT_TRUE(content.find("AI") != std::string::npos); + BOLT_ASSERT_TRUE(fileContainsAll(testFile, {"CORE", "MEMORY", "EDITOR", "AI"})); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); bolt::LogManager::reset(); } @@ -559,7 +559,7 @@ BOLT_TEST(Logging, CategoryMacros) { BOLT_TEST(Logging, ThreadSafety) { std::string testFile = "/tmp/bolt_thread_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } bolt::LogManager::configureFileLogging(testFile, bolt::LogLevel::INFO, true); @@ -596,7 +596,7 @@ BOLT_TEST(Logging, ThreadSafety) { BOLT_ASSERT_TRUE(lineCount == numThreads * messagesPerThread); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); bolt::LogManager::reset(); } @@ -605,7 +605,7 @@ BOLT_TEST(Logging, ThreadSafety) { BOLT_TEST(Logging, ScopedLogger) { std::string testFile = "/tmp/bolt_scoped_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } bolt::LogManager::configureFileLogging(testFile, bolt::LogLevel::TRACE, true); @@ -630,7 +630,7 @@ BOLT_TEST(Logging, ScopedLogger) { BOLT_ASSERT_TRUE(content.find("Inside scoped function") != std::string::npos); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); bolt::LogManager::reset(); } @@ -661,7 +661,7 @@ BOLT_TEST(Logging, PerformanceMetrics) { BOLT_TEST(Logging, ErrorHandlingIntegration) { std::string testFile = "/tmp/bolt_error_integration_test.log"; if (std::filesystem::exists(testFile)) { - std::filesystem::remove(testFile); + removeTestFile(testFile); } bolt::LogManager::configureFileLogging(testFile, bolt::LogLevel::DEBUG, true); @@ -687,6 +687,6 @@ BOLT_TEST(Logging, ErrorHandlingIntegration) { BOLT_ASSERT_TRUE(content.find("Test exception") != std::string::npos); // Clean up - std::filesystem::remove(testFile); + removeTestFile(testFile); bolt::LogManager::reset(); } \ No newline at end of file diff --git a/test/test_network_optimizations.cpp b/test/test_network_optimizations.cpp index 1f4825d6..c2126bd5 100644 --- a/test/test_network_optimizations.cpp +++ b/test/test_network_optimizations.cpp @@ -112,12 +112,20 @@ BOLT_TEST(NetworkOptimizations, MessageCompressionBasic) { MessageCompressor compressor(CompressionType::GZIP, 6); - std::string originalMessage = "This is a test message that should compress well when repeated. " - "This is a test message that should compress well when repeated. " - "This is a test message that should compress well when repeated."; + // Messages under the compressor's 256-byte minimum are passed through + // uncompressed, so build one comfortably above that threshold. + std::string originalMessage; + for (int i = 0; i < 8; ++i) { + originalMessage += "This is a test message that should compress well when repeated. "; + } auto compressed = compressor.compress(originalMessage); +#ifdef BOLT_HAVE_ZLIB BOLT_ASSERT_LT(compressed.size(), originalMessage.size()); // Should be smaller +#else + // Without zlib the compressor passes data through unchanged, so only the + // round trip below can be checked. +#endif auto decompressed = compressor.decompress(compressed); BOLT_ASSERT_EQ(decompressed, originalMessage);