diff --git a/.devops/cann.Dockerfile b/.devops/cann.Dockerfile index 182c71cdf172..791b583ca6a5 100644 --- a/.devops/cann.Dockerfile +++ b/.devops/cann.Dockerfile @@ -19,12 +19,16 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI and Llama Voice from their sources next to it +COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json +COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${CANN_BASE_IMAGE} AS build @@ -40,7 +44,7 @@ WORKDIR /app # -- Copy project files -- COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist # -- Set CANN environment variables (required for compilation) -- # Using ENV instead of `source` allows environment variables to persist across the entire image layer diff --git a/.devops/cpu.Dockerfile b/.devops/cpu.Dockerfile index 0809c8b7ec90..f63e005ec930 100644 --- a/.devops/cpu.Dockerfile +++ b/.devops/cpu.Dockerfile @@ -9,12 +9,16 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI and Llama Voice from their sources next to it +COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json +COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build @@ -28,7 +32,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN if [ "$TARGETARCH" = "amd64" ] || [ "$TARGETARCH" = "arm64" ]; then \ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DGGML_NATIVE=OFF -DLLAMA_BUILD_TESTS=OFF -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON; \ diff --git a/.devops/cuda.Dockerfile b/.devops/cuda.Dockerfile index 2c872ab4adeb..cf1715d43a4c 100644 --- a/.devops/cuda.Dockerfile +++ b/.devops/cuda.Dockerfile @@ -17,12 +17,16 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI and Llama Voice from their sources next to it +COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json +COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_CUDA_DEV_CONTAINER} AS build @@ -40,7 +44,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN if [ "${CUDA_DOCKER_ARCH}" != "default" ]; then \ export CMAKE_ARGS="-DCMAKE_CUDA_ARCHITECTURES=${CUDA_DOCKER_ARCH}"; \ diff --git a/.devops/intel.Dockerfile b/.devops/intel.Dockerfile index 9f4a8fc992e5..0783ef738c9f 100644 --- a/.devops/intel.Dockerfile +++ b/.devops/intel.Dockerfile @@ -11,12 +11,16 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI and Llama Voice from their sources next to it +COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json +COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build @@ -41,7 +45,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN if [ "${GGML_SYCL_F16}" = "ON" ]; then \ echo "GGML_SYCL_F16 is set" \ diff --git a/.devops/musa.Dockerfile b/.devops/musa.Dockerfile index 84969675a2df..3ae62a676e4b 100644 --- a/.devops/musa.Dockerfile +++ b/.devops/musa.Dockerfile @@ -15,12 +15,16 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI and Llama Voice from their sources next to it +COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json +COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_MUSA_DEV_CONTAINER} AS build @@ -45,7 +49,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN if [ "${MUSA_DOCKER_ARCH}" != "default" ]; then \ export CMAKE_ARGS="-DMUSA_ARCHITECTURES=${MUSA_DOCKER_ARCH}"; \ diff --git a/.devops/nix/package.nix b/.devops/nix/package.nix index e807b4d711eb..4ac844ff959d 100644 --- a/.devops/nix/package.nix +++ b/.devops/nix/package.nix @@ -22,12 +22,19 @@ spirv-headers, nodejs, importNpmLock, + syclToolkit ? null, + level-zero, + ocl-icd, + intel-graphics-compiler, + intel-compute-runtime, + makeBinaryWrapper, useBlas ? builtins.all (x: !x) [ useCuda useMetalKit useRocm useVulkan + useSycl ] && blas.meta.available, useCuda ? config.cudaSupport, @@ -38,11 +45,28 @@ rocmGpuTargets ? builtins.concatStringsSep ";" rocmPackages.clr.gpuTargets, useVulkan ? false, useRpc ? false, + useSycl ? false, + # Rebuild, not a runtime switch. cmake default is off. + syclF16 ? false, + # null keeps JIT. AOT makes icpx run ocloc, which DPC++ does not ship. + syclDeviceArch ? null, + syclMaxParallelLinkJobs ? null, llamaVersion ? "0.0.0", # Arbitrary version, substituted by the flake - # It's necessary to consistently use backendStdenv when building with CUDA support, - # otherwise we get libstdc++ errors downstream. - effectiveStdenv ? if useCuda then cudaPackages.backendStdenv else stdenv, + # CUDA needs its backend stdenv or libstdc++ mismatches downstream. + # SYCL needs icpx which is provided by the oneAPI stdenv + effectiveStdenv ? + if useCuda && useSycl then + throw "llama-cpp: useCuda and useSycl are mutually exclusive" + else if useCuda then + cudaPackages.backendStdenv + else if useSycl then + if syclToolkit == null then + throw "llama-cpp: useSycl requires syclToolkit, consider setting it to intel-oneapi-toolkit" + else + syclToolkit.stdenv + else + stdenv, enableStatic ? effectiveStdenv.hostPlatform.isStatic, precompileMetalShaders ? false, useWebUi ? true, @@ -65,7 +89,8 @@ let ++ lib.optionals useMetalKit [ "MetalKit" ] ++ lib.optionals useMpi [ "MPI" ] ++ lib.optionals useRocm [ "ROCm" ] - ++ lib.optionals useVulkan [ "Vulkan" ]; + ++ lib.optionals useVulkan [ "Vulkan" ] + ++ lib.optionals useSycl [ "SYCL" ]; pnameSuffix = strings.optionalString (suffices != [ ]) @@ -108,6 +133,26 @@ let shaderc spirv-headers ]; + + syclAot = useSycl && syclDeviceArch != null && syclDeviceArch != ""; + + # source ocloc binary from intel-compute-runtime + oclocAot = runCommand "ocloc-aot" { nativeBuildInputs = [ makeBinaryWrapper ]; } '' + mkdir -p "$out/bin" + shopt -s nullglob + exact=(${lib.getBin intel-compute-runtime}/bin/ocloc) + vers=(${lib.getBin intel-compute-runtime}/bin/ocloc-*) + if [ ''${#exact[@]} -eq 1 ]; then + src=''${exact[0]} + elif [ ''${#vers[@]} -eq 1 ]; then + src=''${vers[0]} + else + echo "expected one ocloc binary from intel-compute-runtime" >&2 + exit 1 + fi + makeWrapper "$src" "$out/bin/ocloc" \ + --prefix LD_LIBRARY_PATH : ${lib.makeLibraryPath [ intel-graphics-compiler ]} + ''; in effectiveStdenv.mkDerivation (finalAttrs: { @@ -133,11 +178,13 @@ effectiveStdenv.mkDerivation (finalAttrs: { src = lib.cleanSource ../../.; }; - # Builds the webui locally, taking care not to require updating any sha256 hash. + # Builds Llama Chat locally, taking care not to require updating any sha256 hash. webui = stdenvNoCC.mkDerivation { pname = "webui"; version = llamaVersion; - src = lib.cleanSource ../../tools/ui; + # the app compiles Llama UI from its source in ../../lib/ui, so the source is ui/ as a whole + src = lib.cleanSource ../../ui; + sourceRoot = "source/apps/chat"; nativeBuildInputs = [ nodejs @@ -146,7 +193,7 @@ effectiveStdenv.mkDerivation (finalAttrs: { # no sha256 required when using buildNodeModules npmDeps = importNpmLock.buildNodeModules { - npmRoot = ../../tools/ui; + npmRoot = ../../ui/apps/chat; inherit nodejs; }; @@ -156,8 +203,8 @@ effectiveStdenv.mkDerivation (finalAttrs: { }; postPatch = lib.optionalString useWebUi '' - cp -r ${finalAttrs.webui} tools/ui/dist - chmod -R u+w tools/ui/dist + cp -r ${finalAttrs.webui} ui/apps/chat/dist + chmod -R u+w ui/apps/chat/dist ''; # With PR#6015 https://github.com/ggml-org/llama.cpp/pull/6015, @@ -168,6 +215,13 @@ effectiveStdenv.mkDerivation (finalAttrs: { # see https://github.com/ggml-org/llama.cpp/pull/6118 for discussion __noChroot = effectiveStdenv.hostPlatform.isDarwin && useMetalKit && precompileMetalShaders; + # Do not fortify under SYCL as it breaks compiled memcpy invocations + # _FORTIFY_SOURCE rewrites memcpy -> __memcpy_chk + hardeningDisable = optionals useSycl [ + "fortify" + "fortify3" + ]; + nativeBuildInputs = [ cmake @@ -181,7 +235,12 @@ effectiveStdenv.mkDerivation (finalAttrs: { autoAddDriverRunpath ] ++ optionals (effectiveStdenv.hostPlatform.isGnu && enableStatic) [ glibc.static ] - ++ optionals (effectiveStdenv.hostPlatform.isDarwin && useMetalKit && precompileMetalShaders) [ xcrunHost ]; + ++ optionals (effectiveStdenv.hostPlatform.isDarwin && useMetalKit && precompileMetalShaders) [ xcrunHost ] + ++ optionals useSycl [ + autoAddDriverRunpath + makeBinaryWrapper + ] + ++ optionals syclAot [ oclocAot ]; buildInputs = optionals effectiveStdenv.hostPlatform.isDarwin darwinBuildInputs @@ -190,39 +249,53 @@ effectiveStdenv.mkDerivation (finalAttrs: { ++ optionals useRocm rocmBuildInputs ++ optionals useBlas [ blas ] ++ optionals useVulkan vulkanBuildInputs + ++ optionals useSycl [ + level-zero + ocl-icd + intel-graphics-compiler + ] ++ [ openssl ]; - cmakeFlags = - [ - (cmakeBool "LLAMA_BUILD_SERVER" true) - (cmakeBool "LLAMA_BUILD_WEBUI" useWebUi) - (cmakeBool "BUILD_SHARED_LIBS" (!enableStatic)) - (cmakeBool "CMAKE_SKIP_BUILD_RPATH" true) - (cmakeBool "GGML_NATIVE" false) - (cmakeBool "GGML_BLAS" useBlas) - (cmakeBool "GGML_CUDA" useCuda) - (cmakeBool "GGML_HIP" useRocm) - (cmakeBool "GGML_METAL" useMetalKit) - (cmakeBool "GGML_VULKAN" useVulkan) - (cmakeBool "GGML_STATIC" enableStatic) - (cmakeBool "GGML_RPC" useRpc) - ] - ++ optionals useCuda [ - ( - with cudaPackages.flags; - cmakeFeature "CMAKE_CUDA_ARCHITECTURES" ( - builtins.concatStringsSep ";" (map dropDot cudaCapabilities) - ) + cmakeFlags = [ + (cmakeBool "LLAMA_BUILD_SERVER" true) + (cmakeBool "LLAMA_BUILD_WEBUI" useWebUi) + (cmakeBool "BUILD_SHARED_LIBS" (!enableStatic)) + (cmakeBool "CMAKE_SKIP_BUILD_RPATH" true) + (cmakeBool "GGML_NATIVE" false) + (cmakeBool "GGML_BLAS" useBlas) + (cmakeBool "GGML_CUDA" useCuda) + (cmakeBool "GGML_HIP" useRocm) + (cmakeBool "GGML_METAL" useMetalKit) + (cmakeBool "GGML_VULKAN" useVulkan) + (cmakeBool "GGML_STATIC" enableStatic) + (cmakeBool "GGML_RPC" useRpc) + ] + ++ optionals useCuda [ + ( + with cudaPackages.flags; + cmakeFeature "CMAKE_CUDA_ARCHITECTURES" ( + builtins.concatStringsSep ";" (map dropDot cudaCapabilities) ) - ] - ++ optionals useRocm [ - (cmakeFeature "CMAKE_HIP_COMPILER" "${rocmPackages.llvm.clang}/bin/clang") - (cmakeFeature "CMAKE_HIP_ARCHITECTURES" rocmGpuTargets) - ] - ++ optionals useMetalKit [ - (lib.cmakeFeature "CMAKE_C_FLAGS" "-D__ARM_FEATURE_DOTPROD=1") - (cmakeBool "GGML_METAL_EMBED_LIBRARY" (!precompileMetalShaders)) - ]; + ) + ] + ++ optionals useRocm [ + (cmakeFeature "CMAKE_HIP_COMPILER" "${rocmPackages.llvm.clang}/bin/clang") + (cmakeFeature "CMAKE_HIP_ARCHITECTURES" rocmGpuTargets) + ] + ++ optionals useMetalKit [ + (lib.cmakeFeature "CMAKE_C_FLAGS" "-D__ARM_FEATURE_DOTPROD=1") + (cmakeBool "GGML_METAL_EMBED_LIBRARY" (!precompileMetalShaders)) + ] + ++ optionals useSycl [ + (cmakeBool "GGML_SYCL" true) + (cmakeBool "GGML_SYCL_F16" syclF16) + ] + ++ optionals syclAot [ + (cmakeFeature "GGML_SYCL_DEVICE_ARCH" syclDeviceArch) + ] + ++ optionals (syclAot && syclMaxParallelLinkJobs != null) [ + (cmakeFeature "GGML_SYCL_MAX_PARALLEL_LINK_JOBS" (toString syclMaxParallelLinkJobs)) + ]; # Environment variables needed for ROCm env = optionalAttrs useRocm { @@ -237,11 +310,35 @@ effectiveStdenv.mkDerivation (finalAttrs: { cp $src/include/llama.h $out/include/ ''; + # Fix SYCL binary calling missing important libraries + # Also use Level Zero + sysman INSTEAD of OpenCL + # due to OpenCL reporting free memory as total memory, + # breaking `-fit` functionality + postFixup = lib.optionalString useSycl '' + driverLibs=${ + lib.makeLibraryPath [ + intel-graphics-compiler + ocl-icd + ] + } + for b in "$out"/bin/*; do + [ -f "$b" ] && [ -x "$b" ] || continue + patchelf --print-interpreter "$b" >/dev/null 2>&1 || continue + patchelf --add-needed libOpenCL.so.1 --add-needed libigc.so.2 \ + --add-rpath "$driverLibs" "$b" + wrapProgram "$b" \ + --set-default ONEAPI_DEVICE_SELECTOR level_zero:gpu \ + --set-default ZES_ENABLE_SYSMAN 1 + done + ''; + meta = { # Configurations we don't want even the CI to evaluate. Results in the # "unsupported platform" messages. This is mostly a no-op, because # cudaPackages would've refused to evaluate anyway. - badPlatforms = optionals useCuda lib.platforms.darwin; + badPlatforms = + optionals useCuda lib.platforms.darwin + ++ optionals useSycl (lib.subtractLists [ "x86_64-linux" ] lib.platforms.all); # Configurations that are known to result in build failures. Can be # overridden by importing Nixpkgs with `allowBroken = true`. diff --git a/.devops/nix/python-scripts.nix b/.devops/nix/python-scripts.nix index 56ea18278876..873b2ebe503a 100644 --- a/.devops/nix/python-scripts.nix +++ b/.devops/nix/python-scripts.nix @@ -22,10 +22,6 @@ let gitpython tabulate - # for examples/pydantic-models-to-grammar-examples.py - docstring-parser - pydantic - ]; llama-python-test-deps = with python3Packages; [ diff --git a/.devops/openvino.Dockerfile b/.devops/openvino.Dockerfile index 680ad7db6968..fb8cb4c61f66 100644 --- a/.devops/openvino.Dockerfile +++ b/.devops/openvino.Dockerfile @@ -3,11 +3,11 @@ ARG OPENVINO_VERSION_FULL=2026.4.1.22982.07f9c262b05 ARG UBUNTU_VERSION=24.04 # Intel GPU driver versions. https://github.com/intel/compute-runtime/releases -ARG IGC_VERSION=v2.41.5 -ARG IGC_VERSION_FULL=2_2.41.5+22716 -ARG COMPUTE_RUNTIME_VERSION=26.35.39758.10 -ARG COMPUTE_RUNTIME_VERSION_FULL=26.35.39758.10-0 -ARG IGDGMM_VERSION=22.10.0 +ARG IGC_VERSION=v2.42.6 +ARG IGC_VERSION_FULL=2_2.42.6+23070 +ARG COMPUTE_RUNTIME_VERSION=26.40.40196.8 +ARG COMPUTE_RUNTIME_VERSION_FULL=26.40.40196.8-0 +ARG IGDGMM_VERSION=22.10.2 # Intel NPU driver versions. https://github.com/intel/linux-npu-driver/releases ARG NPU_DRIVER_VERSION=v1.38.0 @@ -28,12 +28,16 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI and Llama Voice from their sources next to it +COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json +COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ## Build Image @@ -83,7 +87,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist # Build Stage RUN bash -c "source ${OpenVINO_DIR}/setupvars.sh && \ diff --git a/.devops/rocm.Dockerfile b/.devops/rocm.Dockerfile index 310f4f6d9485..ba9e85a0ed19 100644 --- a/.devops/rocm.Dockerfile +++ b/.devops/rocm.Dockerfile @@ -17,12 +17,16 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI and Llama Voice from their sources next to it +COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json +COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ### Build image @@ -52,7 +56,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN HIPCXX="$(hipconfig -l)/clang" HIP_PATH="$(hipconfig -R)" \ cmake -S . -B build \ diff --git a/.devops/vulkan.Dockerfile b/.devops/vulkan.Dockerfile index 96b7e66ec0e0..023847628366 100644 --- a/.devops/vulkan.Dockerfile +++ b/.devops/vulkan.Dockerfile @@ -9,12 +9,16 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI and Llama Voice from their sources next to it +COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json +COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build @@ -31,7 +35,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN cmake -B build -DGGML_NATIVE=OFF -DGGML_VULKAN=ON -DLLAMA_BUILD_TESTS=OFF -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON && \ cmake --build build --config Release -j$(nproc) diff --git a/.devops/zendnn.Dockerfile b/.devops/zendnn.Dockerfile index a6e54ca8511f..e49df81ca45f 100644 --- a/.devops/zendnn.Dockerfile +++ b/.devops/zendnn.Dockerfile @@ -9,12 +9,16 @@ FROM docker.io/node:$NODE_VERSION AS web ARG APP_VERSION -WORKDIR /app/tools/ui +WORKDIR /app/ui/apps/chat -COPY tools/ui/package.json tools/ui/package-lock.json ./ +COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci -COPY tools/ui/ ./ +COPY ui/apps/chat/ ./ +# the app compiles Llama UI and Llama Voice from their sources next to it +COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json +COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build @@ -28,7 +32,7 @@ WORKDIR /app COPY . . -COPY --from=web /app/tools/ui/dist tools/ui/dist +COPY --from=web /app/ui/apps/chat/dist ui/apps/chat/dist RUN cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DGGML_NATIVE=OFF -DLLAMA_BUILD_TESTS=OFF -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DGGML_ZENDNN=ON && \ cmake --build build -j $(nproc) diff --git a/.dockerignore b/.dockerignore index 0b81e83bf5d4..083eaed9c459 100644 --- a/.dockerignore +++ b/.dockerignore @@ -10,7 +10,7 @@ build*/ -tools/ui/node_modules/ +ui/apps/chat/node_modules/ models/* diff --git a/.editorconfig b/.editorconfig index 1474554f8ab7..5272e6ce0985 100644 --- a/.editorconfig +++ b/.editorconfig @@ -48,7 +48,7 @@ insert_final_newline = unset [vendor/**.patch] trim_trailing_whitespace = unset -[tools/ui/**] +[ui/**] indent_style = unset indent_size = unset end_of_line = unset diff --git a/.github/actions/get-tag-name/action.yml b/.github/actions/get-tag-name/action.yml index 46acce5828e9..ad50f8cfc390 100644 --- a/.github/actions/get-tag-name/action.yml +++ b/.github/actions/get-tag-name/action.yml @@ -14,7 +14,9 @@ runs: run: | BUILD_NUMBER="$(git rev-list --count HEAD)" SHORT_HASH="$(git rev-parse --short=7 HEAD)" - if [[ "${{ env.BRANCH_NAME }}" == "master" || "${{ env.BRANCH_NAME }}" == "b${BUILD_NUMBER}" ]]; then + if [[ "$GITHUB_REF_TYPE" == "tag" && "${{ env.BRANCH_NAME }}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "name=${{ env.BRANCH_NAME }}" >> $GITHUB_OUTPUT + elif [[ "${{ env.BRANCH_NAME }}" == "master" || "${{ env.BRANCH_NAME }}" == "b${BUILD_NUMBER}" ]]; then echo "name=b${BUILD_NUMBER}" >> $GITHUB_OUTPUT else SAFE_NAME=$(echo "${{ env.BRANCH_NAME }}" | tr '/' '-') diff --git a/.github/actions/windows-setup-cuda/action.yml b/.github/actions/windows-setup-cuda/action.yml index 51f1147e18b8..7548719bc7a5 100644 --- a/.github/actions/windows-setup-cuda/action.yml +++ b/.github/actions/windows-setup-cuda/action.yml @@ -25,7 +25,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/visual_studio_integration/windows-x86_64/visual_studio_integration-windows-x86_64-11.7.91-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvprof/windows-x86_64/cuda_nvprof-windows-x86_64-11.7.101-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cccl/windows-x86_64/cuda_cccl-windows-x86_64-11.7.91-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-x86_64/cuda_nvml_dev-windows-x86_64-11.7.91-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\cuda_nvml_dev-windows-x86_64-11.7.91-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\cuda_cudart-windows-x86_64-11.7.99-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\cuda_nvcc-windows-x86_64-11.7.99-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\cuda_nvrtc-windows-x86_64-11.7.99-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7" /E /I /H /Y @@ -54,7 +56,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/visual_studio_integration/windows-x86_64/visual_studio_integration-windows-x86_64-12.4.127-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvprof/windows-x86_64/cuda_nvprof-windows-x86_64-12.4.127-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cccl/windows-x86_64/cuda_cccl-windows-x86_64-12.4.127-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-x86_64/cuda_nvml_dev-windows-x86_64-12.4.127-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\cuda_nvml_dev-windows-x86_64-12.4.127-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\cuda_cudart-windows-x86_64-12.4.127-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\cuda_nvcc-windows-x86_64-12.4.131-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4\cuda_nvrtc-windows-x86_64-12.4.127-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.4" /E /I /H /Y @@ -85,7 +89,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_profiler_api/windows-x86_64/cuda_profiler_api-windows-x86_64-13.1.80-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/visual_studio_integration/windows-x86_64/visual_studio_integration-windows-x86_64-13.1.68-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cccl/windows-x86_64/cuda_cccl-windows-x86_64-13.1.78-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-x86_64/cuda_nvml_dev-windows-x86_64-13.1.68-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1\cuda_nvml_dev-windows-x86_64-13.1.68-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1\cuda_crt-windows-x86_64-13.1.80-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1\cuda_cudart-windows-x86_64-13.1.80-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1\cuda_nvcc-windows-x86_64-13.1.80-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.1" /E /I /H /Y @@ -116,7 +122,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_profiler_api/windows-x86_64/cuda_profiler_api-windows-x86_64-13.5.25-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/visual_studio_integration/windows-x86_64/visual_studio_integration-windows-x86_64-13.5.25-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cccl/windows-x86_64/cccl-windows-x86_64-13.3.5.0.6-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-x86_64/cuda_nvml_dev-windows-x86_64-13.5.37-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_nvml_dev-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_crt-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_cudart-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_nvcc-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y @@ -143,7 +151,9 @@ runs: curl -O "https://developer.download.nvidia.com/compute/cuda/redist/libnvvm/windows-x86_64/libnvvm-windows-x86_64-13.5.37-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_cudart/windows-arm64/cuda_cudart-windows-arm64-13.5.37-archive.zip" curl -O "https://developer.download.nvidia.com/compute/cuda/redist/libcublas/windows-arm64/libcublas-windows-arm64-13.10.0.20-archive.zip" + curl -O "https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/windows-arm64/cuda_nvml_dev-windows-arm64-13.5.37-archive.zip" unzip '*.zip' -d "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" + xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_nvml_dev-windows-arm64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cccl-windows-x86_64-13.3.5.0.6-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_crt-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y xcopy "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5\cuda_nvcc-windows-x86_64-13.5.37-archive\*" "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.5" /E /I /H /Y diff --git a/.github/labeler.yml b/.github/labeler.yml index 20e19c35234e..6b1b0046762d 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -48,7 +48,6 @@ examples: - all-globs-to-all-files: - '!tools/server/**' - '!tools/mtmd/**' - - '!tools/ui/**' testing: - changed-files: - any-glob-to-any-file: @@ -72,7 +71,7 @@ android: server/ui: - changed-files: - any-glob-to-any-file: - - tools/ui/** + - ui/** server: - changed-files: - any-glob-to-any-file: diff --git a/.github/workflows/behavior-check.yml b/.github/workflows/behavior-check.yml index 73c3b8fe223a..544fb6caf600 100644 --- a/.github/workflows/behavior-check.yml +++ b/.github/workflows/behavior-check.yml @@ -140,6 +140,11 @@ jobs: source .venv/Scripts/activate pip install -r requirements/requirements-convert_hf_to_gguf.txt + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build shell: cmd diff --git a/.github/workflows/build-cpu.yml b/.github/workflows/build-cpu.yml index 35d610e1e9fc..285a01a7c860 100644 --- a/.github/workflows/build-cpu.yml +++ b/.github/workflows/build-cpu.yml @@ -187,6 +187,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build run: | diff --git a/.github/workflows/build-cuda-ubuntu.yml b/.github/workflows/build-cuda-ubuntu.yml index db97aeb15b29..cdbbb4767332 100644 --- a/.github/workflows/build-cuda-ubuntu.yml +++ b/.github/workflows/build-cuda-ubuntu.yml @@ -98,7 +98,7 @@ jobs: hip: runs-on: ubuntu-22.04 - container: rocm/dev-ubuntu-22.04:6.1.2 + container: rocm/dev-ubuntu-22.04:6.3.4 steps: - name: Clone diff --git a/.github/workflows/build-opencl.yml b/.github/workflows/build-opencl.yml index ab9ed3ec2cb6..4b45ae666b4e 100644 --- a/.github/workflows/build-opencl.yml +++ b/.github/workflows/build-opencl.yml @@ -61,6 +61,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Install OpenCL Headers and Libs id: install_opencl run: | diff --git a/.github/workflows/build-vulkan.yml b/.github/workflows/build-vulkan.yml index d2375b0141fb..b699f2a1723c 100644 --- a/.github/workflows/build-vulkan.yml +++ b/.github/workflows/build-vulkan.yml @@ -213,6 +213,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build run: | diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index ad1a9de9a05f..917f3b97fff0 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -16,6 +16,10 @@ on: description: "Skip the s390x build target (useful for fast test runs that do not need the IBM Z runner)" type: boolean default: false + skip_ref_check: + description: "Skip the requirement to run from a tag (allows branch refs)" + type: boolean + default: false schedule: # Rebuild daily rather than on every push because it is expensive - cron: '12 4 * * *' @@ -38,6 +42,14 @@ jobs: source_tag: ${{ steps.srctag.outputs.name }} steps: + - name: Check manual run ref + if: ${{ github.event_name == 'workflow_dispatch' && !inputs.skip_ref_check }} + run: | + if [[ "$GITHUB_REF_TYPE" != "tag" ]]; then + echo "::error::Manual runs of this workflow must be started from a tag" + exit 1 + fi + - name: Clone id: checkout uses: actions/checkout@v6 @@ -108,6 +120,9 @@ jobs: mv build-matrix.json.tmp build-matrix.json fi + jq 'map(select(.tag != "musa"))' build-matrix.json > build-matrix.json.tmp + mv build-matrix.json.tmp build-matrix.json + BUILD_MATRIX="$(jq -c . build-matrix.json)" MERGE_MATRIX="$(jq -c ' reduce .[] as $entry ({}; .[$entry.tag] |= ( @@ -170,7 +185,7 @@ jobs: uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist # - name: Set up QEMU # if: ${{ contains(matrix.config.platforms, 'linux/amd64') }} diff --git a/.github/workflows/pr-video-demo-label.yml b/.github/workflows/pr-video-demo-label.yml index 9b3165fa22ab..f6f8567531c3 100644 --- a/.github/workflows/pr-video-demo-label.yml +++ b/.github/workflows/pr-video-demo-label.yml @@ -22,7 +22,7 @@ jobs: BODY: ${{ github.event.pull_request.body }} HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'video demo') }} run: | - # sections written by demo:pr (see tools/ui/demo/cli.ts): the managed comment + # sections written by demo:pr (see ui/apps/chat/demo/cli.ts): the managed comment # markers, or a preview linking to a demo video uploaded for this PR has_demo=false if { grep -qF '' <<< "$BODY" && grep -qF '' <<< "$BODY"; } || diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 867dcaf49420..c918feb06916 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -130,7 +130,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: ccache uses: ggml-org/ccache-action@v1.2.24 @@ -196,7 +196,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends @@ -274,7 +274,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends @@ -381,7 +381,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends @@ -479,7 +479,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Set up JDK uses: actions/setup-java@v5 @@ -571,7 +571,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Build id: cmake_build @@ -624,7 +624,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Build id: cmake_build @@ -672,7 +672,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: ccache uses: ggml-org/ccache-action@v1.2.24 @@ -894,12 +894,17 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Install Ninja run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: ccache uses: ggml-org/ccache-action@v1.2.24 with: @@ -1146,6 +1151,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + # TODO: these jobs need to use llvm toolchain in order to utilize the ccache #- name: ccache # uses: ggml-org/ccache-action@v1.2.24 @@ -1239,6 +1249,7 @@ jobs: with: key: release-windows-2022-${{ matrix.arch }}-cuda-${{ matrix.cuda }} evict-old-files: 1d + max-size: "1G" - name: Build id: cmake_build @@ -1459,7 +1470,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends @@ -1531,7 +1542,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Free up disk space uses: ggml-org/free-disk-space@v1.3.1 @@ -1646,7 +1657,7 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist + path: ui/apps/chat/dist - name: Dependencies id: depends diff --git a/.github/workflows/server-speculative.yml b/.github/workflows/server-speculative.yml index de247afb6fb7..e90eb21c4942 100644 --- a/.github/workflows/server-speculative.yml +++ b/.github/workflows/server-speculative.yml @@ -7,6 +7,40 @@ on: description: 'Commit SHA1 to build' required: false type: string + spec_methods: + description: 'Speculative methods to test' + required: true + default: 'compact' + type: choice + options: + - compact + - nightly + - all + push: + branches: + - master + paths: [ + '.github/workflows/server-speculative.yml', + 'common/speculative.*', + 'src/models/dflash*.cpp', + 'src/models/dspark.cpp', + 'src/models/eagle3.cpp', + 'src/models/lilicorr.cpp', + 'src/models/qwen35.cpp', + 'tools/server/tests/unit/test_spec_methods.py' + ] + pull_request: + types: [opened, synchronize, reopened] + paths: [ + '.github/workflows/server-speculative.yml', + 'common/speculative.*', + 'src/models/dflash*.cpp', + 'src/models/dspark.cpp', + 'src/models/eagle3.cpp', + 'src/models/lilicorr.cpp', + 'src/models/qwen35.cpp', + 'tools/server/tests/unit/test_spec_methods.py' + ] cache-mode: none permissions: @@ -56,8 +90,9 @@ jobs: - name: Test speculative decoding env: - SPEC_METHODS: compact - SPEC_MODEL_DIR: ${{ vars.SPEC_METHOD_MODEL_DIR || format('{0}/spec-models', runner.temp) }} + SPEC_METHODS: ${{ github.event.inputs.spec_methods || 'compact' }} + # pull requests from forks do not get repository variables + SPEC_MODEL_DIR: ${{ vars.SPEC_METHOD_MODEL_DIR || '/mnt/cache/spec-models' }} N_GPU_LAYERS: 99 run: | cd tools/server/tests diff --git a/.github/workflows/server.yml b/.github/workflows/server.yml index f3c577ec6d28..38231317ed3a 100644 --- a/.github/workflows/server.yml +++ b/.github/workflows/server.yml @@ -175,6 +175,11 @@ jobs: evict-old-files: 1d save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build shell: cmd diff --git a/.github/workflows/ui-build-self-hosted.yml b/.github/workflows/ui-build-self-hosted.yml index 0ba2eb983fc2..660786ff7f86 100644 --- a/.github/workflows/ui-build-self-hosted.yml +++ b/.github/workflows/ui-build-self-hosted.yml @@ -23,20 +23,20 @@ jobs: with: node-version: "24" # cache: "npm" - # cache-dependency-path: "tools/ui/package-lock.json" + # cache-dependency-path: "ui/apps/chat/package-lock.json" package-manager-cache: false - name: Install dependencies run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Build application run: npm run build - working-directory: tools/ui + working-directory: ui/apps/chat - name: Upload built UI uses: actions/upload-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ retention-days: 1 diff --git a/.github/workflows/ui-build.yml b/.github/workflows/ui-build.yml index f229fcd04480..67fc2fadc9d7 100644 --- a/.github/workflows/ui-build.yml +++ b/.github/workflows/ui-build.yml @@ -37,26 +37,26 @@ jobs: with: node-version: "24" # cache: "npm" - # cache-dependency-path: "tools/ui/package-lock.json" + # cache-dependency-path: "ui/apps/chat/package-lock.json" package-manager-cache: false - name: Install dependencies run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Build application env: LLAMA_BUILD_NUMBER: ${{ steps.version.outputs.ui_version }} run: npm run build - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run PWA unit tests (versioned build output) run: npx vitest --project=unit --run tests/unit/pwa.spec.ts - working-directory: tools/ui + working-directory: ui/apps/chat - name: Upload built UI uses: actions/upload-artifact@v7 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ retention-days: 1 diff --git a/.github/workflows/ui-chat-publish.yml b/.github/workflows/ui-chat-publish.yml new file mode 100644 index 000000000000..193aa375fe78 --- /dev/null +++ b/.github/workflows/ui-chat-publish.yml @@ -0,0 +1,183 @@ +name: UI Chat Publish + +# Publishes Llama Chat to npm: @ggml-org/llama-chat (ui/apps/chat, the app and its CLI) and +# llama-chat (ui/apps/chat/alias, the short name for npx), always at the same version. +# +# The version in ui/apps/chat/package.json is the release, set by hand, as for @ggml-org/llama-ui +# in ui-lib-publish.yml. A commit that reaches master with a version npm does not have builds the +# app and publishes both packages; any other commit publishes nothing. Bump both package.json +# files in the PR that should ship. +# +# Auth: no npm token is stored here. The job exchanges its OIDC identity for one (npm trusted +# publishing) and signs the tarballs with provenance. One-time setup, before this can publish: on +# each of the two packages, Publishing settings, Trusted Publisher, GitHub Actions, with +# organization ggml-org, repository llama.cpp, workflow file ui-chat-publish.yml and Environment +# left blank. Until then the publish step fails on master; re-running the job publishes it. + +on: + workflow_dispatch: + inputs: + dry_run: + description: 'Build and pack, but do not publish' + required: false + type: boolean + default: false + push: + branches: + - master + paths: [ + '.github/workflows/ui-chat-publish.yml', + 'ui/apps/chat/package.json', + 'ui/apps/chat/alias/package.json' + ] + # a dry run for PRs that change what goes into the packages + pull_request: + types: [opened, synchronize, reopened] + paths: [ + '.github/workflows/ui-chat-publish.yml', + 'ui/apps/chat/package.json', + 'ui/apps/chat/alias/**', + 'ui/apps/chat/bin/**', + 'ui/apps/chat/cli/**' + ] + +cache-mode: none +permissions: + contents: read + id-token: write + +concurrency: + # never cancel a run mid-publish: a version half-published cannot be taken back + group: ${{ github.workflow }} + cancel-in-progress: false + +env: + APP_DIR: ui/apps/chat + ALIAS_DIR: ui/apps/chat/alias + VERSION_CHECK: ui/lib/ui/scripts/npm-version-check.mjs + +jobs: + publish: + name: Publish @ggml-org/llama-chat and llama-chat + if: github.repository == 'ggml-org/llama.cpp' + runs-on: ubuntu-26.04-arm + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + registry-url: 'https://registry.npmjs.org' + package-manager-cache: false + + - name: Check npm can publish with an OIDC token + run: | + node -e ' + const v = process.argv[1]; + const [major, minor] = v.split(".").map(Number); + if (major < 11 || (major === 11 && minor < 5)) { + console.error(`npm ${v} cannot publish with trusted publishing: 11.5.1 or newer is needed`); + process.exit(1); + } + ' "$(npm -v)" + + - name: Install dependencies + run: npm ci + working-directory: ${{ env.APP_DIR }} + + - name: Build the app + # the same build.json version as the UI that llama-server embeds, for the app's update check. + # This folder's .npmrc sets ignore-scripts, so npm never builds it: this step does. + run: LLAMA_BUILD_NUMBER="b$(git rev-list --count HEAD)" npm run build + working-directory: ${{ env.APP_DIR }} + + - name: Test the CLI and the alias version + run: npx vitest --project=unit --run tests/unit/cli.test.ts + working-directory: ${{ env.APP_DIR }} + + - name: Check what goes into the package + run: | + npm pack --dry-run --json > "$RUNNER_TEMP/pack.json" + node -e ' + const [{ files }] = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); + const paths = files.map((file) => file.path); + const maps = paths.filter((path) => path.endsWith(".map")); + if (!paths.includes("dist/index.html")) { + console.error("dist/index.html is not in the package: nothing would be served"); + process.exit(1); + } + if (maps.length > 0) { + console.error(`source maps in the package: ${maps.join(", ")}`); + process.exit(1); + } + console.log(`${paths.length} files, no source maps`); + ' "$RUNNER_TEMP/pack.json" + working-directory: ${{ env.APP_DIR }} + + - name: Compare @ggml-org/llama-chat with npm + id: app + continue-on-error: ${{ github.event_name == 'pull_request' }} + run: node "$VERSION_CHECK" "$APP_DIR" + + - name: Compare llama-chat with npm + id: alias + continue-on-error: ${{ github.event_name == 'pull_request' }} + run: node "$VERSION_CHECK" "$ALIAS_DIR" + + # master only: npm's trusted publisher matches the repository and the workflow file, not the + # branch, so this condition is what keeps a manual run on a PR branch from publishing. + # The app goes first, since the alias depends on it at the same version. + - name: Publish @ggml-org/llama-chat + if: github.ref == 'refs/heads/master' && steps.app.outputs.should_publish == 'true' && inputs.dry_run != true + env: + TAG: ${{ steps.app.outputs.tag }} + run: npm publish --access public --provenance --ignore-scripts --tag "$TAG" + working-directory: ${{ env.APP_DIR }} + + - name: Publish llama-chat + if: github.ref == 'refs/heads/master' && steps.alias.outputs.should_publish == 'true' && inputs.dry_run != true + env: + TAG: ${{ steps.alias.outputs.tag }} + run: npm publish --access public --provenance --ignore-scripts --tag "$TAG" + working-directory: ${{ env.ALIAS_DIR }} + + - name: Report + if: always() + # values reach the shell through env, so a name from a PR's package.json cannot inject here + env: + APP: ${{ steps.app.outputs.name }}@${{ steps.app.outputs.version }} + APP_VERDICT: ${{ steps.app.outputs.verdict || 'not reached' }} + APP_NOTE: ${{ steps.app.outputs.note }} + ALIAS: ${{ steps.alias.outputs.name }}@${{ steps.alias.outputs.version }} + ALIAS_VERDICT: ${{ steps.alias.outputs.verdict || 'not reached' }} + ALIAS_NOTE: ${{ steps.alias.outputs.note }} + DRY: ${{ inputs.dry_run }} + EVENT: ${{ github.event_name }} + run: | + { + echo "### Llama Chat on npm" + echo + echo "| package | verdict | note |" + echo "| --- | --- | --- |" + echo "| \`$APP\` | \`$APP_VERDICT\` | $APP_NOTE |" + echo "| \`$ALIAS\` | \`$ALIAS_VERDICT\` | $ALIAS_NOTE |" + echo + if [ "$EVENT" = "pull_request" ] || [ "$DRY" = "true" ]; then echo "Dry run: nothing was published."; fi + } >> "$GITHUB_STEP_SUMMARY" + + - name: Mind the verdict + # a version going backwards is a mistake; an unchanged version is a package.json edit that + # is not a release, such as a dependency update + if: always() && github.event_name != 'pull_request' + env: + VERDICTS: ${{ steps.app.outputs.verdict }} ${{ steps.alias.outputs.verdict }} + run: | + case " $VERDICTS " in + *" stale "*) + echo "::error::a version in package.json is older than the one on npm" + exit 1 ;; + esac diff --git a/.github/workflows/ui-lib-publish.yml b/.github/workflows/ui-lib-publish.yml new file mode 100644 index 000000000000..a1258cda4549 --- /dev/null +++ b/.github/workflows/ui-lib-publish.yml @@ -0,0 +1,230 @@ +name: UI Lib Publish + +# Publishes @ggml-org/llama-ui, the library in ui/lib/ui, to npm. +# +# The version in ui/lib/ui/package.json is the release. A commit that reaches master with a +# version npm does not have builds the library and publishes it; a commit that changes the +# library without bumping it publishes nothing and says so on the run, which is the drift that +# let 0.3.0 sit a day behind master. Bump the version in the PR whose change should ship, and +# this workflow does the rest. +# +# Auth: no npm token is stored here. The job exchanges its OIDC identity for one (npm trusted +# publishing) and signs the tarball with a provenance attestation. release-publish.yml has done +# the same exchange on every push to master since it landed, its actions/attest step being the +# proof that this repository can be issued a token. +# +# One-time setup, before this can publish: on the package, Publishing settings, Trusted +# Publisher, GitHub Actions, with organization ggml-org, repository llama.cpp, workflow file +# ui-lib-publish.yml, and Environment left blank - this job names no environment, since creating +# one needs repository admin. Merging this workflow before that exists leaves the publish step +# red on master: the release is late rather than wrong, and re-running the job publishes it. +# +# The unscoped llama-ui is an alias: once the scoped package is out, the same build is renamed +# and published again at the same version, so the two never drift. It is a package of its own +# on npm, and needs the same trusted publisher set on it. + +on: + workflow_dispatch: + inputs: + dry_run: + description: 'Build and pack, but do not publish' + required: false + type: boolean + default: false + push: + branches: + - master + paths: [ + '.github/workflows/ui-lib-publish.yml', + 'ui/lib/ui/**.*' + ] + # the advisory half, so a library change without a bump is annotated on the PR rather than + # discovered after the merge: the path filter keeps it off PRs that touch only Llama Chat + pull_request: + types: [opened, synchronize, reopened] + paths: [ + '.github/workflows/ui-lib-publish.yml', + 'ui/lib/ui/**.*' + ] + +cache-mode: none +permissions: + contents: read + id-token: write + +concurrency: + # never cancel a run mid-publish: a version half-published cannot be taken back. GitHub holds + # one pending run per group, so a newer push replaces an older queued one - no release is lost, + # as each run reads the version from its own commit. + group: ${{ github.workflow }} + cancel-in-progress: false + +env: + LIB_DIR: ui/lib/ui + +jobs: + publish: + name: Publish @ggml-org/llama-ui + if: github.repository == 'ggml-org/llama.cpp' + runs-on: ubuntu-26.04-arm + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + registry-url: 'https://registry.npmjs.org' + package-manager-cache: false + + - name: Check npm can publish with an OIDC token + run: | + npm -v + node -e ' + const v = process.argv[1]; + const [major, minor] = v.split(".").map(Number); + if (major < 11 || (major === 11 && minor < 5)) { + console.error(`npm ${v} cannot publish with trusted publishing: 11.5.1 or newer is needed`); + process.exit(1); + } + ' "$(npm -v)" + + - name: Install dependencies + run: npm ci + working-directory: ${{ env.LIB_DIR }} + + - name: Run type checking + run: npm run check + working-directory: ${{ env.LIB_DIR }} + + - name: Build the package and lint it + run: npm run prepack + working-directory: ${{ env.LIB_DIR }} + + - name: Compare the version with npm + id: version + # on a PR this is advisory and must not fail the job: a registry outage is not the + # contributor's mistake. On master the publish decision rests on the answer, so it fails. + continue-on-error: ${{ github.event_name == 'pull_request' }} + run: node scripts/npm-version-check.mjs + working-directory: ${{ env.LIB_DIR }} + + - name: Note a library change that ships no new version + if: github.event_name == 'pull_request' && always() && steps.version.outcome == 'success' && steps.version.outputs.should_publish != 'true' + env: + NOTE: ${{ steps.version.outputs.note }} + run: echo "::warning::$NOTE" + + - name: Publish + # master only. npm's trusted publisher matches on the repository and the workflow file, + # not the branch, so this condition is the only thing stopping a manual run from a PR + # branch - one that anyone with write access can start - from publishing code that no + # one reviewed. A dispatch on master remains the way to re-run a release. + if: github.ref == 'refs/heads/master' && steps.version.outputs.should_publish == 'true' && inputs.dry_run != true + # --ignore-scripts publishes the tarball prepack built and publint passed rather than + # rebuilding it here; --provenance is implied by trusted publishing and named to be + # explicit. A package published with nothing in it cannot be taken back, so refuse first. + env: + TAG: ${{ steps.version.outputs.tag }} + run: | + test -d dist || { echo "dist/ is missing: nothing was built, so nothing is published"; exit 1; } + npm publish --access public --provenance --ignore-scripts --tag "$TAG" + working-directory: ${{ env.LIB_DIR }} + + - name: Rename the build to the unscoped alias + # after the scoped publish, so nothing above sees the changed name. Not on a PR: the + # advisory check there is about the version, which the alias shares. + if: github.event_name != 'pull_request' + run: node scripts/alias-package.mjs + working-directory: ${{ env.LIB_DIR }} + + - name: Compare the alias with npm + id: alias + if: github.event_name != 'pull_request' + run: node scripts/npm-version-check.mjs + working-directory: ${{ env.LIB_DIR }} + + - name: Publish the alias + # its own verdict rather than the scoped one's, so an alias that fell behind catches up + # on the next run instead of waiting for a bump + if: github.ref == 'refs/heads/master' && steps.alias.outputs.should_publish == 'true' && inputs.dry_run != true + env: + TAG: ${{ steps.alias.outputs.tag }} + run: | + test -d dist || { echo "dist/ is missing: nothing was built, so nothing is published"; exit 1; } + npm publish --access public --provenance --ignore-scripts --tag "$TAG" + working-directory: ${{ env.LIB_DIR }} + + - name: Report + if: always() + # every value reaches the shell through env, not through the script, so a package name + # from a PR's package.json cannot inject into this step + env: + NAME: ${{ steps.version.outputs.name || '@ggml-org/llama-ui' }} + VERSION: ${{ steps.version.outputs.version || 'unknown' }} + LATEST: ${{ steps.version.outputs.latest }} + VERDICT: ${{ steps.version.outputs.verdict || 'not reached' }} + NOTE: ${{ steps.version.outputs.note }} + SHOULD: ${{ steps.version.outputs.should_publish }} + DRY: ${{ inputs.dry_run }} + ALIAS_LATEST: ${{ steps.alias.outputs.latest }} + ALIAS_VERDICT: ${{ steps.alias.outputs.verdict || 'not reached' }} + ALIAS_NOTE: ${{ steps.alias.outputs.note }} + ALIAS_SHOULD: ${{ steps.alias.outputs.should_publish }} + EVENT: ${{ github.event_name }} + run: | + if [ "$DRY" = "true" ]; then published="no (dry run)" + elif [ "$SHOULD" = "true" ]; then published=yes + else published=no + fi + { + echo "### $NAME $VERSION" + echo + echo "| | |" + echo "| --- | --- |" + echo "| npm latest was | ${LATEST:-nothing published yet} |" + echo "| verdict | \`$VERDICT\` |" + echo "| published | $published |" + echo + echo "> $NOTE" + } >> "$GITHUB_STEP_SUMMARY" + [ "$EVENT" = "pull_request" ] && exit 0 + if [ "$DRY" = "true" ]; then published="no (dry run)" + elif [ "$ALIAS_SHOULD" = "true" ]; then published=yes + else published=no + fi + { + echo + echo "### llama-ui (alias) $VERSION" + echo + echo "| | |" + echo "| --- | --- |" + echo "| npm latest was | ${ALIAS_LATEST:-nothing published yet} |" + echo "| verdict | \`$ALIAS_VERDICT\` |" + echo "| published | $published |" + echo + echo "> $ALIAS_NOTE" + } >> "$GITHUB_STEP_SUMMARY" + + - name: Mind the verdict + if: always() && github.event_name != 'pull_request' && steps.version.outcome == 'success' + # a version going backwards is a mistake; a version not bumped is usually one too, but it + # is also what a stories-only commit looks like, so that only fails the run when the + # repository variable UI_LIB_PUBLISH_FAIL_ON_UNBUMPED is set to true + env: + NOTE: ${{ steps.version.outputs.note }} + VERDICT: ${{ steps.version.outputs.verdict }} + FAIL_ON_UNBUMPED: ${{ vars.UI_LIB_PUBLISH_FAIL_ON_UNBUMPED }} + run: | + case "$VERDICT" in + stale) + echo "::error::$NOTE" + exit 1 ;; + published) + if [ "$FAIL_ON_UNBUMPED" = "true" ]; then + echo "::error::$NOTE" + exit 1 + fi + echo "::warning::$NOTE" ;; + esac diff --git a/.github/workflows/ui-publish.yml b/.github/workflows/ui-publish.yml index d77b899b2302..fc624e3e8241 100644 --- a/.github/workflows/ui-publish.yml +++ b/.github/workflows/ui-publish.yml @@ -33,15 +33,15 @@ jobs: uses: actions/download-artifact@v8 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ run-id: ${{ inputs.run_id }} github-token: ${{ github.token }} - name: Create distribution archive run: | - tar -czf dist.tar.gz -C tools/ui/dist . + tar -czf dist.tar.gz -C ui/apps/chat/dist . sha256sum dist.tar.gz > dist.tar.gz.sha256 - mv dist.tar.gz dist.tar.gz.sha256 tools/ui/dist/ + mv dist.tar.gz dist.tar.gz.sha256 ui/apps/chat/dist/ - name: Install Hugging Face Hub CLI run: pip install -U huggingface_hub @@ -52,12 +52,12 @@ jobs: - name: Sync built files to Hugging Face bucket (version tag) run: | # Upload the built files to the Hugging Face bucket under the release version - hf buckets sync tools/ui/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/${{ inputs.version_tag }} --delete --quiet + hf buckets sync ui/apps/chat/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/${{ inputs.version_tag }} --delete --quiet - name: Sync built files to Hugging Face bucket (latest) run: | # Also upload to the 'latest' directory for fallback downloads - hf buckets sync tools/ui/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/latest --delete --quiet + hf buckets sync ui/apps/chat/dist hf://buckets/ggml-org/${{ env.HF_BUCKET_NAME }}/latest --delete --quiet - name: Verify upload run: | diff --git a/.github/workflows/ui-self-hosted.yml b/.github/workflows/ui-self-hosted.yml index 93b7805f18d9..4967de07ca21 100644 --- a/.github/workflows/ui-self-hosted.yml +++ b/.github/workflows/ui-self-hosted.yml @@ -17,7 +17,9 @@ on: paths: [ '.github/workflows/ui-self-hosted.yml', '.github/workflows/ui-build-self-hosted.yml', - 'tools/ui/**.*', + 'ui/apps/chat/**.*', + 'ui/lib/ui/**.*', + 'ui/lib/voice/**.*', 'tools/server/tests/**.*' ] pull_request: @@ -25,7 +27,9 @@ on: paths: [ '.github/workflows/ui-self-hosted.yml', '.github/workflows/ui-build-self-hosted.yml', - 'tools/ui/**.*', + 'ui/apps/chat/**.*', + 'ui/lib/ui/**.*', + 'ui/lib/voice/**.*', 'tools/server/tests/**.*' ] @@ -67,33 +71,33 @@ jobs: - name: Install dependencies id: setup run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Download built UI artifacts uses: actions/download-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ - name: Run type checking if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run check - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run linting if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run lint - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run Client tests if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run test:client - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run Unit tests if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run test:unit - working-directory: tools/ui + working-directory: ui/apps/chat e2e-tests: name: E2E Tests @@ -109,25 +113,25 @@ jobs: - name: Install dependencies id: setup run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Download built UI artifacts uses: actions/download-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ - name: Build Storybook if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run build-storybook - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run UI tests if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run test:ui -- --testTimeout=60000 - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run E2E tests if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run test:e2e - working-directory: tools/ui + working-directory: ui/apps/chat diff --git a/.github/workflows/ui-storybook.yml b/.github/workflows/ui-storybook.yml new file mode 100644 index 000000000000..fe922b1a2d80 --- /dev/null +++ b/.github/workflows/ui-storybook.yml @@ -0,0 +1,84 @@ +name: UI Storybook + +# Builds Llama UI and Llama Chat's Storybook (ui/apps/chat) and publishes it to its Hugging Face Space +# whenever the UI changes on master, so the Space always shows the latest build. + +on: + workflow_dispatch: + push: + branches: + - master + paths: [ + '.github/workflows/ui-storybook.yml', + 'ui/apps/chat/**', + 'ui/lib/ui/**' + ] + +cache-mode: none +permissions: + contents: read + +# only the newest build matters: a newer push replaces a deploy still in progress +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: true + +jobs: + deploy: + name: Deploy to Hugging Face Spaces + if: github.repository == 'ggml-org/llama.cpp' + runs-on: hf-jobs-cpu-upgrade:ubuntu26_04 + + env: + HF_SPACE: ${{ vars.HF_SPACE_UI_STORYBOOK || 'ggml-org/llama-ui-storybook' }} + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Install dependencies + run: npm ci + working-directory: ui/apps/chat + + - name: Build Storybook + run: npm run build-storybook + working-directory: ui/apps/chat + + - name: Write the Space card + run: | + cat > ui/apps/chat/storybook-static/README.md << EOF + --- + title: Llama UI Storybook + emoji: 🦙 + colorFrom: gray + colorTo: gray + sdk: static + pinned: false + --- + + The Storybook of Llama UI and Llama Chat, built from [ggml-org/llama.cpp](https://github.com/ggml-org/llama.cpp) (\`ui/apps/chat\`) at ${GITHUB_SHA}. + EOF + + - name: Install Hugging Face Hub CLI + run: | + sudo apt-get update + sudo apt-get install -y python3 python3-venv + python3 -m venv .venv-hf + .venv-hf/bin/pip install -U huggingface_hub==1.28.0 + + - name: Upload to the Space + env: + # a token with write access to the Space; HF_TOKEN_UI_STATIC_OUTPUT if that one has it + HF_TOKEN: ${{ secrets.HF_TOKEN_UI_STORYBOOK || secrets.HF_TOKEN_UI_STATIC_OUTPUT }} + run: | + # --delete '*' removes files the new build no longer has; the Space's .gitattributes is always kept + .venv-hf/bin/hf upload "$HF_SPACE" ui/apps/chat/storybook-static . \ + --repo-type space \ + --delete '*' \ + --commit-message "Storybook from ggml-org/llama.cpp@${GITHUB_SHA::10}" diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index c5c6a32a8177..65e5c36ffdbf 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -13,7 +13,8 @@ on: paths: [ '.github/workflows/ui.yml', '.github/workflows/ui-build.yml', - 'tools/ui/**.*', + 'ui/apps/chat/**.*', + 'ui/lib/**.*', 'tools/server/tests/**.*' ] pull_request: @@ -21,7 +22,8 @@ on: paths: [ '.github/workflows/ui.yml', '.github/workflows/ui-build.yml', - 'tools/ui/**.*', + 'ui/apps/chat/**.*', + 'ui/lib/**.*', 'tools/server/tests/**.*' ] @@ -66,46 +68,118 @@ jobs: with: node-version: "24" # cache: "npm" - # cache-dependency-path: "tools/ui/package-lock.json" + # cache-dependency-path: "ui/apps/chat/package-lock.json" package-manager-cache: false - name: Download built UI artifacts uses: actions/download-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ - name: Install dependencies id: setup if: ${{ steps.node.conclusion == 'success' }} run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run type checking if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run check - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run linting if: ${{ always() && steps.setup.conclusion == 'success' }} run: npm run lint - working-directory: tools/ui + working-directory: ui/apps/chat + + - name: Check DESIGN.md is current with the tokens + if: ${{ always() && steps.setup.conclusion == 'success' }} + run: npm run check:design + working-directory: ui/apps/chat - name: Install Playwright browsers id: playwright if: ${{ always() && steps.setup.conclusion == 'success' }} run: npx playwright install --with-deps - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run Client tests if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run test:client - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run Unit tests (uses pre-built dist/ from ui-build) if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run test:unit - working-directory: tools/ui + working-directory: ui/apps/chat + + lib-checks: + name: Library checks + runs-on: ubuntu-24.04 + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }} + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Install dependencies + run: npm ci + working-directory: ui/lib/ui + + - name: Run type checking + run: npm run check + working-directory: ui/lib/ui + + - name: Install Playwright browsers + run: npx playwright install --with-deps chromium + working-directory: ui/lib/ui + + # the unit tests and the Storybook stories (ui/lib/ui/tests/stories), which run as tests in Chromium + - name: Run tests + run: npm test + working-directory: ui/lib/ui + + - name: Build the package + run: npm run prepack + working-directory: ui/lib/ui + + voice-checks: + name: Voice checks + runs-on: ubuntu-24.04 + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }} + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Install dependencies + run: npm ci + working-directory: ui/lib/voice + + - name: Run type checking + run: npm run check + working-directory: ui/lib/voice + + - name: Run tests + run: npm test + working-directory: ui/lib/voice + + - name: Build the package + run: npm run prepack + working-directory: ui/lib/voice e2e-tests: name: E2E Tests @@ -124,38 +198,38 @@ jobs: with: node-version: "24" # cache: "npm" - # cache-dependency-path: "tools/ui/package-lock.json" + # cache-dependency-path: "ui/apps/chat/package-lock.json" package-manager-cache: false - name: Install dependencies id: setup if: ${{ steps.node.conclusion == 'success' }} run: npm ci - working-directory: tools/ui + working-directory: ui/apps/chat - name: Download built UI artifacts (reuses ui-build) uses: actions/download-artifact@v6 with: name: llama-ui.zip - path: tools/ui/dist/ + path: ui/apps/chat/dist/ - name: Install Playwright browsers id: playwright if: ${{ always() && steps.setup.conclusion == 'success' }} run: npx playwright install --with-deps - working-directory: tools/ui + working-directory: ui/apps/chat - name: Build Storybook if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run build-storybook - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run UI tests if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run test:ui -- --testTimeout=60000 - working-directory: tools/ui + working-directory: ui/apps/chat - name: Run E2E tests (uses pre-built dist/ from ui-build) if: ${{ always() && steps.playwright.conclusion == 'success' }} run: npm run test:e2e - working-directory: tools/ui + working-directory: ui/apps/chat diff --git a/AUTHORS b/AUTHORS index 96ca4c1d9bff..721a0a1a43de 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,4 +1,4 @@ -# date: Wed Nov 4 12:03:31 EET 2026 +# date: Mon Nov 16 10:05:56 EET 2026 # this file is auto-generated by scripts/gen-authors.sh Нияз Гарифзянов <112617865+garrnizon@users.noreply.github.com> @@ -43,7 +43,9 @@ Aarni Koskela Aaron Miller Aaron Teo <57927438+taronaeo@users.noreply.github.com> Aaron Teo +Aaron Thomas <84493696+arxhr007@users.noreply.github.com> Aaryaman Vasishta +Aayan Karmali <44980366+StockerMC@users.noreply.github.com> Abheek Gulati abhijain1204fujitsu <139222713+abhijain1204fujitsu@users.noreply.github.com> Abhijit Ramesh @@ -112,10 +114,12 @@ Aleksander Grygier Aleksander Grygier Aleksander Grygier Aleksei Nikiforov <103434461+AlekseiNikiforovIBM@users.noreply.github.com> +Alen Požun Alessandro de Oliveira Faria (A.K.A.CABELO) Alessandro98-git <61804547+Alessandro98-git@users.noreply.github.com> Alex <18387287+wadealexc@users.noreply.github.com> Alex <59368173+AlexGabbia@users.noreply.github.com> +Alex Alex Alex Azarov Alex Azarov @@ -132,6 +136,7 @@ Alex Trotta <44127594+Ahajha@users.noreply.github.com> Alex Tuddenham <61622354+AlexsCode@users.noreply.github.com> Alex von Gluck IV Alex Wu +Alex-JP-93 alex-spacemit Alexander Batischev Alexander Heisler <126129661+heislera763@users.noreply.github.com> @@ -143,6 +148,7 @@ Alexis Williams alexpinel <93524949+alexpinel@users.noreply.github.com> Alfred Ali Chraghi <63465728+alichraghi@users.noreply.github.com> +Ali F. Al-Ramadan <55710790+aalramadan@users.noreply.github.com> Ali Nehzat Ali Tariq Ali Tariq @@ -158,6 +164,7 @@ Aman Karki Aman Karki amd-dwang amd-lalithnc +AMIR <127450356+amirthn6533@users.noreply.github.com> Amir amirai21 <89905406+amirai21@users.noreply.github.com> AmirAli Mirian <37371367+amiralimi@users.noreply.github.com> @@ -213,6 +220,7 @@ Antoine Viallon Anton I Anton Mitkov Anton Mitkov +Anton Sokolchenko Antonis Makropoulos anubhavfujitsu Anudit Nagar @@ -233,10 +241,12 @@ arlo-phoenix <140345165+arlo-phoenix@users.noreply.github.com> Armen Kaleshian Arsen Arutunan <58118221+limloop@users.noreply.github.com> Arseniy Obolenskiy +ArshM17-NV Artem Artem Zinnatullin Artyom Lebedev aryantandon01 <80969509+aryantandon01@users.noreply.github.com> +Asahi-Prv <246092086+Asahi-Prv@users.noreply.github.com> Asahi-Prv asbelin <71226900+asbelin@users.noreply.github.com> Asbjørn Olling @@ -258,6 +268,7 @@ AustinMroz AUTOMATIC1111 <16777216c@gmail.com> automaticcat awatuna <23447591+awatuna@users.noreply.github.com> +Awss b4b4o Bach Le BADR @@ -351,6 +362,7 @@ CarterLi999 <664681047@qq.com> Casey Primozic Casey Primozic CausalLM <148736309+CausalLM@users.noreply.github.com> +CC <65151926+realMoana@users.noreply.github.com> ccbinn cduk <19917266+cduk@users.noreply.github.com> cebtenzzre @@ -379,6 +391,7 @@ Cheng Shao Chenguang Li <757486878@qq.com> Chenguang Li <87689256+noemotiovon@users.noreply.github.com> chiheb ben cheikh <100644963+ChihebBENCHEIKH1@users.noreply.github.com> +chinmaykamjith001 Chipmunk <101038159+CHIPMUNK-T0T@users.noreply.github.com> chiranko <96988916+chiranko@users.noreply.github.com> Chris Danis @@ -434,6 +447,7 @@ crasm crat0z <11581854+crat0z@users.noreply.github.com> CRD716 CrispStrobe <154636388+CrispStrobe@users.noreply.github.com> +Cristian Adam Cristiano Pinto <140563307+crowmoed@users.noreply.github.com> crsawyer <7572190+crsawyer@users.noreply.github.com> Csaba Kecskemeti @@ -527,6 +541,7 @@ Djip007 <3705339+Djip007@users.noreply.github.com> Djip007 dm4 dm4 +Dmitrii Panchev Dmitry Atamanov Dmytro Minochkin Dmytro Romanov @@ -567,6 +582,7 @@ Ed Addario <29247825+EAddario@users.noreply.github.com> Ed Lee Ed Lepedus Eddie-Wang +eddiechen Eden eduardopessin <100053075+eduardopessin@users.noreply.github.com> Edward Taylor @@ -598,6 +614,7 @@ Erik Winter <93544977+ewintr@users.noreply.github.com> Ervin Áron Tasnádi Esko Toivonen Ethan Guo +Ethan Lin Ethan Turner Ettore Di Giacinto EugeoSynthesisThirtyTwo @@ -625,6 +642,7 @@ fanyang Farbod Bijary <110523279+farbodbj@users.noreply.github.com> Fathi Boudra Fattire <528174+fat-tire@users.noreply.github.com> +Feiteng felix Felix Felix Ye @@ -632,6 +650,7 @@ fengerhu1 <2748250768@qq.com> feni6 fidoriel <49869342+fidoriel@users.noreply.github.com> fiesh +figkcoci-debug FINAL-Bench Finn Voorhees Firat @@ -646,6 +665,7 @@ Foad Abo Dahood <32059146+masterFoad@users.noreply.github.com> Folko-Ven <71110216+Folko-Ven@users.noreply.github.com> forforever73 <63285796+forforever73@users.noreply.github.com> Foul-Tarnished <107711110+Foul-Tarnished@users.noreply.github.com> +fox5611 <66219952+fox5611@users.noreply.github.com> Francisco Herrera Francisco Melo <43780565+francis2tm@users.noreply.github.com> Francois Dugast @@ -709,6 +729,7 @@ GiviMAD gliptic gn64 goerch +Gotya-OFFCIAL Govlzkoy grahameth <96447521+grahameth@users.noreply.github.com> Gregor Jasny @@ -749,6 +770,7 @@ Haowei Wu Haoxiang Fei Harald Fernengel Harapan Rachman +Harkanwal Bedi Harkirat Gill HarrisonSec Hatsune Miku <129688334+at8u@users.noreply.github.com> @@ -768,6 +790,7 @@ Henrik Forstén Henry Linjamäki Henry Linjamäki Henry147147 <44851451+Henry147147@users.noreply.github.com> +Hera <58063257+hera2019@users.noreply.github.com> Herman Semenoff Herman Semenov Hesen Peng @@ -846,6 +869,7 @@ Imad Saddik <79410781+ImadSaddik@users.noreply.github.com> iMil Incarnas <119618389+bit-incarnas@users.noreply.github.com> InflexCZE +Iñigo Imaz <49730431+inimaz@users.noreply.github.com> Intel AI Get-to Market Customer Success and Solutions intelmatt <61025942+intelmatt@users.noreply.github.com> iohub @@ -857,7 +881,9 @@ IsaacDynamo <61521674+IsaacDynamo@users.noreply.github.com> Ishaan Gandhi iSma Ismail <115064057+AlrIsmail@users.noreply.github.com> +IsNot <209144869@qq.com> issixx <46835150+issixx@users.noreply.github.com> +Iswarya Alex <47045679+iswaryaalex@users.noreply.github.com> itsnotoger <19309683+itsnotoger@users.noreply.github.com> itterative <190138728+itterative@users.noreply.github.com> Ivan @@ -888,6 +914,7 @@ James Francis <6763899+JamesFranc@users.noreply.github.com> James O'Leary <65884233+jpohhhh@users.noreply.github.com> James Reynolds jameswu2014 <545426914@qq.com> +JamieBordoni Jan Boon Jan Boon Jan Ekström @@ -956,8 +983,10 @@ Jinyang He jinzihao Jiří Podivín <66251151+jpodivin@users.noreply.github.com> Jiří Sejkora +Jiří Svítil <32205472+mistrjirka@users.noreply.github.com> Jiwoong Song <55657581+jwsong98@users.noreply.github.com> JJJYmmm <92386084+JJJYmmm@users.noreply.github.com> +jjperry69 jklincn <985765408@qq.com> jklincn JM Robles @@ -970,6 +999,7 @@ Joe Rowell Joe Todd joecryptotoo <80373433+joecryptotoo@users.noreply.github.com> Joel +Joel Fernandes Johan Johannes Gäßler Johannes Rudolph @@ -988,6 +1018,7 @@ Jonas J <111707981+John-194@users.noreply.github.com> Jonas Jankaitis <111707981+John-194@users.noreply.github.com> Jonas Wunderlich <32615971+jonas-w@users.noreply.github.com> Jonathan <47618606+jbuchananr@users.noreply.github.com> +Jonathan Buck Jonathan Clohessy Jonathan Graehl <99024+graehl@users.noreply.github.com> Jorge A <161275481+jorgealias@users.noreply.github.com> @@ -1097,6 +1128,7 @@ klosax <131523366+klosax@users.noreply.github.com> KnightYao KokerZhou <111279477+KokerZhou@users.noreply.github.com> Kolen Cheung +Kong Jiale <2049447146@qq.com> kononnable Konrad Moren konradmb @@ -1167,6 +1199,7 @@ li-lizhe <82501526+li-lizhe@users.noreply.github.com> liangliangchang liminfei-amd <91481003+liminfei-amd@users.noreply.github.com> limitedAtonement +Lines lingyezhixing <144504450+lingyezhixing@users.noreply.github.com> linsen458-spec Linux User @@ -1227,6 +1260,7 @@ makomk manayang manikbhandari Manuel <44313466+makuche@users.noreply.github.com> +ManuelPDM <153872964+ManuelPDM@users.noreply.github.com> maor-ps <154728172+maor-ps@users.noreply.github.com> Maphist0 <28743569+Maphist0@users.noreply.github.com> Marc Köhlbrugge @@ -1336,6 +1370,7 @@ Michael Hueschen Michael Kesper Michael Klimenko Michael Lamothe +Michael Paulauski Michael Podvitskiy Michael Potter Michael Taylor <162068037+mctylr-gh@users.noreply.github.com> @@ -1455,6 +1490,7 @@ Nikolay Popov <131475237+npopov-vst@users.noreply.github.com> Nils Gladitz Nindaleth ningshanwutuobang +Nisbenz Noah <99681487+NoahOksuz@users.noreply.github.com> nold nopperl <54780682+nopperl@users.noreply.github.com> @@ -1462,6 +1498,7 @@ nullname Nuno nuri nusu-github <29514220+nusu-github@users.noreply.github.com> +nv-vankit <162085734+nv-vankit@users.noreply.github.com> nwyin o7si <32285332+o7si@users.noreply.github.com> Oğuzhan Akkaya @@ -1485,6 +1522,7 @@ oobabooga opparco Ori Pekelman Oscar Barenys +Oscar M. Herrera OSecret <135510162+OLSecret@users.noreply.github.com> ostix360 <55257054+ostix360@users.noreply.github.com> Ouadie EL FAROUKI @@ -1611,6 +1649,7 @@ Raj Hammeer Singh Hada Rajendra Matcha Ralph Soika Raman Shinde +Ramzi <146260554+rmz-24@users.noreply.github.com> Rand Xie Randall Fitzgerald Random Fly @@ -1651,6 +1690,7 @@ Rich Dougherty Richard Richard Davison Richard Kiss +Richard Palethorpe Richard Roberson RichardScottOZ Rick G <26732651+TheFlipbook@users.noreply.github.com> @@ -1695,6 +1735,7 @@ Roni Ronny Brendel Ronny Brendel Ronsor +Roshan Kumar <52444089+roshankumarg529@users.noreply.github.com> Rotem Dan Rowan Hart rspOverflow <217881046+rspOverflow@users.noreply.github.com> @@ -1727,9 +1768,11 @@ Saba Fallah <10401143+sfallah@users.noreply.github.com> Saba Fallah Sachin Desai Sachin Sharma +Saejin Kim-Heinert Safi Ullah safranowith Said Taghadouini <84044788+staghado@users.noreply.github.com> +SaidSultani <62264302+SaidSultani@users.noreply.github.com> Sait Furkan Teke <35101659+stfurkan@users.noreply.github.com> SakuraUmi Salvador E. Tropea @@ -1754,6 +1797,7 @@ Sang-Kil Park Sanjay Ahari Sarah Wu Sarah Wu +sargentmajord Sascha Rogmann <59577610+srogmann@users.noreply.github.com> sasha0552 Satinder Grewal @@ -1786,6 +1830,7 @@ Sergiu <8598216+mzsergiu@users.noreply.github.com> serhii-nakon <57632032+serhii-nakon@users.noreply.github.com> Sertaç Özercan <852750+sozercan@users.noreply.github.com> seryogakovalyov +Seungjun Bae Seungmin Kim <8457324+ehfd@users.noreply.github.com> SeungWon Jeong <65549245+redlion0929@users.noreply.github.com> Seyoung Jeong @@ -1871,6 +1916,7 @@ SmartestWashingMachine smugman-dot SnA1lGo <44647694+skrandy@users.noreply.github.com> snadampal <87143774+snadampal@users.noreply.github.com> +Sofian Elmotiem SoftwareRenderer <138734813+SoftwareRenderer@users.noreply.github.com> Someone Someone Serge @@ -1886,6 +1932,7 @@ sprayandwipe Sreeram SRHMorris <69468379+SRHMorris@users.noreply.github.com> Srihari-mcw <96763064+Srihari-mcw@users.noreply.github.com> +Srijan Keshri <212402043+arcusbuilds@users.noreply.github.com> Srinivas Billa srkizer ssweens <1149151+ssweens@users.noreply.github.com> @@ -1919,6 +1966,7 @@ Sutou Kouhei Svetlozar Georgiev <55534064+sgeor255@users.noreply.github.com> Swigler <124839156+Swigler@users.noreply.github.com> swittk +sxq <18856096915@163.com> SXX SXX Tai Duc Nguyen @@ -2044,6 +2092,7 @@ Ulrich Drepper unbounded Unbug Lee unraido <127105806+unraido@users.noreply.github.com> +usrlocalben uvos uvos uvos @@ -2084,6 +2133,7 @@ vk <89937361+itsvedantkumar@users.noreply.github.com> Vlad Vladimir Vladimir Malyutin +Vladimir Sotnikov Vladimir Vuksanovic <109677816+vvuksanovic@users.noreply.github.com> Vladimir Zorin Vladislav @@ -2139,6 +2189,7 @@ Wroclaw wsbagnsv1 Wu Jian Ping Wu Jian Ping +WuXin wwoodsTM <104587230+wwoodsTM@users.noreply.github.com> Wyatt Caldwell <218154709+Detensable@users.noreply.github.com> wzy <32936898+Freed-Wu@users.noreply.github.com> @@ -2162,6 +2213,7 @@ Xinpeng Dou <15529241576@163.com> Xinpeng Dou <81913537+Dou-Git@users.noreply.github.com> xloem <0xloem@gmail.com> xris99 <79798089+xris99@users.noreply.github.com> +Xuan Son Nguyen Xuan Son Nguyen Xuan-Son Nguyen Xuan-Son Nguyen @@ -2247,6 +2299,7 @@ zhangrunda zhangtao2-1 <478679312@qq.com> ZHAOKAI WANG Zhaolun Yin <129580161+ZhaolunYin@users.noreply.github.com> +zhaoyshine <30611065+zhaoyshine@users.noreply.github.com> Zheng.Deng <32841220+dengzheng-cloud@users.noreply.github.com> zhentaoyu Zhenwei Jin <109658203+kylo5aby@users.noreply.github.com> diff --git a/CMakeLists.txt b/CMakeLists.txt index b8b40e75f68f..7be920fbb377 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,8 +3,8 @@ project("llama.cpp" C CXX) include(CheckIncludeFileCXX) ### llama.cpp version -set(LLAMA_VERSION_MAJOR 0) -set(LLAMA_VERSION_MINOR 9) +set(LLAMA_VERSION_MAJOR 1) +set(LLAMA_VERSION_MINOR 0) set(LLAMA_VERSION_PATCH 0) set(LLAMA_VERSION_BASE "${LLAMA_VERSION_MAJOR}.${LLAMA_VERSION_MINOR}.${LLAMA_VERSION_PATCH}") @@ -134,7 +134,7 @@ option(LLAMA_BUILD_TOOLS "llama: build tools" option(LLAMA_BUILD_EXAMPLES "llama: build examples" ${LLAMA_STANDALONE}) option(LLAMA_BUILD_SERVER "llama: build server example" ${LLAMA_STANDALONE}) option(LLAMA_BUILD_APP "llama: build the unified binary" ${LLAMA_STANDALONE}) -option(LLAMA_BUILD_UI "llama: build the embedded Web UI for server" OFF) +option(LLAMA_BUILD_UI "llama: build Llama Chat, the embedded chat app, for server" OFF) option(LLAMA_USE_PREBUILT_UI "llama: use prebuilt UI from HF Bucket when available" ON) option(LLAMA_CONNECT "llama: include the llama-connect tool (downloads a prebuilt binary)" OFF) diff --git a/CODEOWNERS b/CODEOWNERS index f34a07f02255..af0553ac4fdc 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -102,7 +102,7 @@ /tools/rpc/ @ggml-org/ggml-rpc /tools/server/* @ggml-org/llama-server # no subdir /tools/server/tests/ @ggml-org/llama-server -/tools/ui/ @ggml-org/llama-ui +/ui/ @ggml-org/llama-ui /tools/tokenize/ @ggerganov /tools/tts/ @ggerganov /vendor/ @ggerganov diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 59ec3f311b5d..5b6327d11bc6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,6 +16,8 @@ The project differentiates between 3 levels of contributors: > > Detailed information regarding permissible and restricted uses of AI can be found in the [AGENTS.md](AGENTS.md) file. +### Requirements + If AI is used to generate any portion of the code, contributors must adhere to the following requirements: 1. Explicitly disclose the manner in which AI was employed. @@ -24,6 +26,16 @@ If AI is used to generate any portion of the code, contributors must adhere to t 4. Be prepared to explain every line of code you submit when asked about it by a maintainer. 5. It is strictly prohibited to use AI to write your posts for you (bug reports, feature requests, pull request descriptions, Github discussions, responding to humans, ...). +### Checklist + +> [!IMPORTANT] +> +> **If you use AI, do all of the following:** +> +> 1. **Make sure [AGENTS.md](AGENTS.md) is loaded into your agent's context.** Skipping this step is one of the most common reasons PRs get rejected. +> 2. **Search for related discussions, PRs and issues** to get the broader context before writing any code. +> 3. **Run a local review pass before pushing anything**, using the [`code-review`](skills/code-review/SKILL.md) skill, once the change is implemented. Fix what it finds. + For more info, please refer to the [AGENTS.md](AGENTS.md) file. # Pull requests (for contributors & collaborators) diff --git a/SECURITY.md b/SECURITY.md index bc6ed9d809a1..e781871647d4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -46,7 +46,7 @@ Only vulnerabilities that fall within these parts of the project are considered - `ggml/**/*` - `gguf-py/**/*` - `tools/server/*`, **excluding** the following topics: - - Web UI + - Llama Chat, the built-in chat app (`ui/apps/chat`) - Features marked as experimental - Features not recommended for use in untrusted environments (e.g., router, MCP) - Bugs that can lead to Denial-of-Service attack diff --git a/ci/run.sh b/ci/run.sh index 1beb54b0759d..cb8918ab9c86 100755 --- a/ci/run.sh +++ b/ci/run.sh @@ -122,6 +122,8 @@ if [ ! -z ${GG_BUILD_VULKAN} ]; then MACOS_RUNNER_CUSTOM_SPIRV_HEADERS_LOCATION="${MACOS_RUNNER_CUSTOM_VULKAN_CMAKE_LOCATION}/SPIRV-Headers/SPIRV-HeadersConfig.cmake" if [[ -f "${MACOS_RUNNER_CUSTOM_SPIRV_HEADERS_LOCATION}" || -h "${MACOS_RUNNER_CUSTOM_SPIRV_HEADERS_LOCATION}" ]]; then CMAKE_EXTRA="${CMAKE_EXTRA} -DSPIRV-Headers_DIR=${MACOS_RUNNER_CUSTOM_VULKAN_CMAKE_LOCATION}/SPIRV-Headers" + # SPIRV-Headers walks up three directories and appends /include, yielding /usr/local/lib/include; the extra vulkan/ level likely breaks its prefix calculation. + CMAKE_EXTRA="${CMAKE_EXTRA} -DGGML_VULKAN_SPIRV_INCLUDE_DIR=/usr/local/include" fi fi diff --git a/common/arg.cpp b/common/arg.cpp index 6bf9355fb0ff..a638237672bd 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -349,6 +349,14 @@ common_models_handler common_models_handler_init(const common_params & params, l params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH) != params.speculative.types.end(); + const bool spec_type_draft_dflash2 = std::find(params.speculative.types.begin(), + params.speculative.types.end(), + COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2) != params.speculative.types.end(); + + const bool spec_type_draft_lilicorr = std::find(params.speculative.types.begin(), + params.speculative.types.end(), + COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR) != params.speculative.types.end(); + const bool spec_type_draft_eagle3 = std::find(params.speculative.types.begin(), params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3) != params.speculative.types.end(); @@ -373,7 +381,7 @@ common_models_handler common_models_handler_init(const common_params & params, l opts.offline = params.offline; opts.download_mtp = spec_type_draft_mtp; opts.download_eagle3 = spec_type_draft_eagle3; - opts.download_dflash = spec_type_draft_dflash; + opts.download_dflash = spec_type_draft_dflash || spec_type_draft_dflash2 || spec_type_draft_lilicorr; opts.download_dspark = spec_type_draft_dspark; opts.download_mmproj = use_mmproj && !params.no_mmproj && params.mmproj.path.empty() && params.mmproj.url.empty(); @@ -904,6 +912,10 @@ static bool common_params_parse_ex(int argc, char ** argv, common_params_context throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n"); } + if (params.sampling.ignore_eos && !common_grammar_value(params.sampling.grammar).empty()) { + throw std::invalid_argument("error: --ignore-eos is not supported with --grammar or --json-schema\n"); + } + const bool skip_model_download = // server will call common_params_handle_models() later, so we skip it here ctx_arg.ex == LLAMA_EXAMPLE_SERVER || @@ -2821,7 +2833,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex const std::regex regex{ R"([,/]+)" }; std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 }; std::vector split_arg{ it, {} }; - if (split_arg.size() >= llama_max_devices()) { + if (split_arg.size() > llama_max_devices()) { throw std::invalid_argument( string_format("got %zu input configs, but system only has %zu devices", split_arg.size(), llama_max_devices()) ); @@ -2887,7 +2899,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex const std::regex regex{ R"([,/]+)" }; std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 }; std::vector split_arg{ it, {} }; - if (split_arg.size() >= llama_max_devices()) { + if (split_arg.size() > llama_max_devices()) { throw std::invalid_argument( string_format("got %zu input configs, but system only has %zu devices", split_arg.size(), llama_max_devices()) ); @@ -3408,12 +3420,20 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--ui-mcp-proxy", "--webui-mcp-proxy"}, {"--no-ui-mcp-proxy", "--no-webui-mcp-proxy"}, - "experimental: whether to enable MCP CORS proxy, for the Web UI to reach public MCP servers without CORS headers; local and private addresses are refused - do not enable in untrusted environments (default: disabled)\n" + "experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused unless --ui-mcp-proxy-allow-private-urls is set - do not enable in untrusted environments (default: disabled)\n" "note: for security reasons, this will limit --cors-origins to localhost by default", [](common_params & params, bool value) { params.ui_mcp_proxy = value; } ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_MCP_PROXY")); + add_opt(common_arg( + {"--ui-mcp-proxy-allow-private-urls"}, + "allow the MCP CORS proxy to reach local or private addresses (e.g. MCP servers on localhost or LAN) - anyone who can reach the proxy can then reach your local network (default: disabled, only public addresses)\n" + "note: only has effect with --ui-mcp-proxy", + [](common_params & params) { + params.ui_mcp_proxy_allow_private_urls = true; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_MCP_PROXY_ALLOW_PRIVATE_URLS")); add_opt(common_arg( {"--tools"}, "TOOL1,TOOL2,...", "experimental: whether to enable built-in tools for AI agents - do not enable in untrusted environments (default: no tools)\n" @@ -3477,7 +3497,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--ui", "--webui"}, {"--no-ui", "--no-webui"}, - string_format("whether to enable the Web UI (default: %s)", params.ui ? "enabled" : "disabled"), + string_format("whether to enable Llama Chat, the built-in chat app (default: %s)", params.ui ? "enabled" : "disabled"), [](common_params & params, bool value) { params.ui = value; } @@ -4494,7 +4514,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--tts-lang"}, "FNAME", "language (ISO 639-1) for audio generation\n" - "see tts/README.md for per-model usage notes", + "see docs/multimodal/tts.md for per-model usage notes", [](common_params & params, const std::string & value) { params.tts_lang = value; } @@ -4502,7 +4522,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--tts-voice"}, "VOICE", "voice for audio generation (model-dependent)\n" - "see tts/README.md for per-model usage notes", + "see docs/multimodal/tts.md for per-model usage notes", [](common_params & params, const std::string & value) { params.tts_voice = value; } @@ -4514,6 +4534,14 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.tts_speaker_file = value; } ).set_examples({LLAMA_EXAMPLE_TTS})); + add_opt(common_arg( + {"--tts-speaker-text"}, "TEXT", + "transcript of --tts-speaker-file, for models that need it to clone the voice\n" + "see docs/multimodal/tts.md for per-model usage notes", + [](common_params & params, const std::string & value) { + params.tts_speaker_text = value; + } + ).set_examples({LLAMA_EXAMPLE_TTS})); // // diffusion params diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp index 968cbfa98f6c..56938d5efcd1 100644 --- a/common/chat-peg-parser.cpp +++ b/common/chat-peg-parser.cpp @@ -562,7 +562,8 @@ common_peg_parser common_chat_peg_builder::python_or_json_value() { common_peg_parser common_chat_peg_builder::python_style_tool_calls( const ordered_json & tools, bool parallel_tool_calls, - bool allow_json_literals) { + bool allow_json_literals, + bool allow_undeclared) { if (!tools.is_array() || tools.empty()) { return eps(); } @@ -620,6 +621,18 @@ common_peg_parser common_chat_peg_builder::python_style_tool_calls( tool_choices |= rule("tool-" + std::to_string(i), tool_parser); } + // last, so declared tools win when parsing + if (allow_undeclared) { + auto ident = rule("tool-undeclared-ident", chars("[a-zA-Z_]", 1, 1) + chars("[a-zA-Z0-9_.]", 0, -1)); + auto value = tool_arg_value(allow_json_literals ? python_or_json_value() : python_value()); + auto arg = tool_arg(tool_arg_open(tool_arg_name(ident) + literal("=")) + value + tool_arg_close(eps())); + auto args = optional(arg + zero_or_more("," + space() + arg)); + + tool_choices |= rule("tool-undeclared", tool(tool_open(tool_name(ident) + literal("(")) + + space() + tool_args(args) + space() + tool_close(literal(")")) + )); + } + if (parallel_tool_calls) { return "[" + space() + tool_choices + zero_or_more("," + space() + tool_choices) + space() + "]"; } diff --git a/common/chat-peg-parser.h b/common/chat-peg-parser.h index b827b60b059c..c77ec117b5aa 100644 --- a/common/chat-peg-parser.h +++ b/common/chat-peg-parser.h @@ -161,9 +161,11 @@ class common_chat_peg_builder : public common_peg_parser_builder { // Helper for Python-style function call format: name(arg1="value1", arg2=123) // Used by LFM2 and similar templates + // allow_undeclared: also accept calls to names not in tools (any identifier, any arguments) common_peg_parser python_style_tool_calls(const common_json & tools, bool parallel_tool_calls, - bool allow_json_literals); + bool allow_json_literals, + bool allow_undeclared = false); private: // Python values plus JSON true/false/null. diff --git a/common/chat-tts-norm.cpp b/common/chat-tts-norm.cpp index f84540ff96e0..b828ed9b4e18 100644 --- a/common/chat-tts-norm.cpp +++ b/common/chat-tts-norm.cpp @@ -2,6 +2,7 @@ #include "jinja/runtime.h" #include "jinja/value.h" +#include "json.h" #include #include @@ -857,8 +858,45 @@ static value tts_norm_builtin_sub(const func_args & args) { return mk_val(string(res, text_val.all_parts_are_input())); } -void common_chat_tts_norm_add_builtins(context & ctx) { +bool common_tts_dict_find(const common_tts_dict & dict, const std::string & key, std::string & value) { + const auto it = std::lower_bound(dict.keys.begin(), dict.keys.end(), key); + if (it == dict.keys.end() || *it != key) { + return false; + } + const size_t idx = it - dict.keys.begin(); + if (idx >= dict.values.size()) { + throw std::runtime_error("tts_dict: malformed dictionary, a key has no value"); + } + value = dict.values[idx]; + return true; +} + +void common_chat_tts_norm_add_builtins(context & ctx, std::shared_ptr dicts, common_tts_g2p g2p) { ctx.set_val("tts_norm_scan", mk_val("tts_norm_scan", tts_norm_builtin_scan)); ctx.set_val("tts_norm_sub", mk_val("tts_norm_sub", tts_norm_builtin_sub)); + ctx.set_val("tts_dict", mk_val("tts_dict", [dicts](const func_args & args) -> value { + args.ensure_count(2, 2); + args.ensure_vals(); + const std::string name = args.get_pos(0)->as_string().str(); + const auto it = dicts ? dicts->find(name) : common_tts_dicts::const_iterator(); + if (!dicts || it == dicts->end()) { + throw std::runtime_error("tts_dict: unknown dictionary '" + name + "'"); + } + std::string doc; + if (!common_tts_dict_find(it->second, args.get_pos(1)->as_string().str(), doc)) { + return mk_val(); + } + return value_from_json(common_json::parse(doc), false); + })); + // none when the caller gives no letter-to-sound model, or the model has no pronunciation + ctx.set_val("tts_g2p", mk_val("tts_g2p", [g2p](const func_args & args) -> value { + args.ensure_count(1, 1); + args.ensure_vals(); + const std::string out = g2p ? g2p(args.get_pos(0)->as_string().str()) : std::string(); + if (out.empty()) { + return mk_val(); + } + return mk_val(out); + })); } diff --git a/common/chat-tts-norm.h b/common/chat-tts-norm.h index 14695bb52d99..b96486078602 100644 --- a/common/chat-tts-norm.h +++ b/common/chat-tts-norm.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include #include #include @@ -11,9 +13,10 @@ // it is NOT a regex engine: the semantics are defined by llama.cpp (see docs/tts-norm-patterns.md), so that this // implementation and the python reference (scripts/chat_tts_norm.py) give the same result for every input // -// two functions are exposed to task templates (e.g. "tts") via common_chat_tts_norm_add_builtins(): +// functions exposed to task templates (e.g. "tts") via common_chat_tts_norm_add_builtins(): // tts_norm_scan(text, rules) -> list of segments {rule, text, groups} // tts_norm_sub(text, pattern, repl) -> string +// tts_dict(name, key) -> value of key in a dictionary of the model, or none namespace jinja { struct context; @@ -57,6 +60,22 @@ std::vector common_tts_norm_scan(const std::string & te // repl references: %0 (whole match), %1..%9 (groups), %% (literal percent) std::string common_tts_norm_sub(const std::string & text, const common_tts_norm_pattern & pattern, const std::string & repl); -// add tts_norm_scan() and tts_norm_sub() to the context of a task template +// a dictionary of the model, e.g. a pronunciation lexicon +struct common_tts_dict { + std::vector keys; // sorted by their bytes + std::vector values; // the JSON document of each key +}; + +using common_tts_dicts = std::map; + +// binary search of key in a dictionary; on success, value is set to the JSON document +bool common_tts_dict_find(const common_tts_dict & dict, const std::string & key, std::string & value); + +// pronunciation of a word by a letter-to-sound model, as phonemes separated by spaces (e.g. CMUdict notation) +// empty when there is none; the notation is the one of the model, its "tts" template knows it +using common_tts_g2p = std::function; + +// add tts_norm_scan(), tts_norm_sub(), tts_dict() and tts_g2p() to the context of a task template // they are not jinja global builtins on purpose: chat templates are not affected -void common_chat_tts_norm_add_builtins(jinja::context & ctx); +void common_chat_tts_norm_add_builtins(jinja::context & ctx, std::shared_ptr dicts = nullptr, + common_tts_g2p g2p = nullptr); diff --git a/common/chat.cpp b/common/chat.cpp index da29cd671d4c..de5f1c490303 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -318,6 +318,7 @@ struct common_chat_templates { std::unique_ptr template_default; // always set (defaults to chatml) std::unique_ptr template_tool_use; std::unique_ptr template_tts; // the prompt of a text to speak + std::shared_ptr tts_dicts; // dictionaries of the model for tts_dict(), by name }; common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice) { @@ -806,10 +807,11 @@ bool common_chat_templates_was_explicit(const struct common_chat_templates * tmp } // renders a task template (e.g. "tts") with the given variables -static std::string common_chat_template_render(const common_chat_template & tmpl, const json & vars) { +static std::string common_chat_template_render(const common_chat_template & tmpl, const json & vars, const std::shared_ptr & tts_dicts, + const common_tts_g2p & g2p = nullptr) { jinja::context ctx(tmpl.source()); - // text normalization helpers: tts_norm_scan() and tts_norm_sub(), see docs/tts-norm-patterns.md - common_chat_tts_norm_add_builtins(ctx); + // text normalization helpers: tts_norm_scan(), tts_norm_sub(), tts_dict() and tts_g2p(), see docs/tts-norm-patterns.md + common_chat_tts_norm_add_builtins(ctx, tts_dicts, g2p); jinja::global_from_json(ctx, vars, false); ctx.set_val("bos_token", jinja::mk_val(tmpl.bos_token())); ctx.set_val("eos_token", jinja::mk_val(tmpl.eos_token())); @@ -827,6 +829,11 @@ static std::string string_lower(std::string s) { return s; } +// VibeVoice-ASR: default system prompt of the template written by the converter +static bool is_vibevoice_asr_template(const std::string & src) { + return src.find("transcribes audio input into text output in JSON format") != std::string::npos; +} + // LFM3-Audio: language code -> name static std::string lfm3_language_name(const std::string & language) { static const std::map names = { @@ -847,7 +854,8 @@ static std::string lfm3_asr_system_prompt(const std::string & language) { return "Perform ASR in " + lfm3_language_name(language) + "."; } -common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language) { +common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language, + double audio_length, const std::string & context) { common_chat_prompt_preset asr_preset; asr_preset.system = ""; asr_preset.user = "Transcribe audio to text"; @@ -861,6 +869,17 @@ common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates asr_preset.system = lfm3_asr_system_prompt(language); asr_preset.user = ""; asr_preset.has_language = true; + } else if (is_vibevoice_asr_template(src)) { + // without the audio length the model does not know where the audio ends and loops + const char * keys = "transcribe it with these keys: Start time, End time, Speaker ID, Content"; + if (context.empty()) { + asr_preset.user = string_format("\nThis is a %.2f seconds audio, please %s", audio_length, keys); + } else { + asr_preset.user = string_format("\nThis is a %.2f seconds audio, with extra info: %s\n\nPlease %s", audio_length, context.c_str(), keys); + asr_preset.has_context = true; + } + asr_preset.media_first = true; + asr_preset.needs_audio_length = true; } } @@ -868,7 +887,7 @@ common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates } std::string common_chat_get_tts_prompt(const common_chat_templates * chat_templates, const std::string & text, - const std::string & language, const std::string & voice) { + const std::string & language, const std::string & voice, const common_tts_g2p & g2p) { if (!chat_templates || !chat_templates->template_tts) { return ""; } @@ -876,7 +895,7 @@ std::string common_chat_get_tts_prompt(const common_chat_templates * chat_templa {"messages", json::array({{{"role", "user"}, {"content", text}}})}, {"language", language}, {"voice", voice}, - }); + }, chat_templates->tts_dicts, g2p); } std::string common_chat_get_speech_system_prompt(const common_chat_templates * chat_templates, @@ -955,18 +974,6 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * "{%- if false %}"); } - // TODO @aldehir : this is a temporary fix, pending Minja changes - // Ref: https://github.com/ggml-org/llama.cpp/pull/17713#issuecomment-3631342664 - if (default_template_src.find("[TOOL_CALLS]") != std::string::npos - // search for the error message and patch it - && default_template_src.find("if (message['content'] is none or") != std::string::npos) { - string_replace_all(default_template_src, - "{%- if (message['content'] is none or message['content'] == '' or " - "message['content']|length == 0) and (message['tool_calls'] is not defined or " - "message['tool_calls'] is none or message['tool_calls']|length == 0) %}", - "{%- if false %}"); - } - std::string token_bos = bos_token_override; std::string token_eos = eos_token_override; bool add_bos = false; @@ -1019,6 +1026,25 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * LOG_ERR("%s: failed to parse the tts chat template (ignoring it): %s\n", __func__, e.what()); } } + // dictionaries for tts_dict(), listed by name in tokenizer.tts_dicts + tmpls->tts_dicts = std::make_shared(); + for (int32_t i = 0; i < llama_model_meta_arr_n(model, "tokenizer.tts_dicts"); i++) { + const std::string name = llama_model_meta_arr_str(model, "tokenizer.tts_dicts", i); + const std::string key = "tokenizer.tts_dict." + name + ".keys"; + const std::string val_key = "tokenizer.tts_dict." + name + ".values"; + const int32_t n = llama_model_meta_arr_n(model, key.c_str()); + if (n < 0 || llama_model_meta_arr_n(model, val_key.c_str()) != n) { + LOG_ERR("%s: the tts dictionary '%s' has no value for each of its keys (ignoring it)\n", __func__, name.c_str()); + continue; + } + auto & dict = (*tmpls->tts_dicts)[name]; + dict.keys.reserve(n); + dict.values.reserve(n); + for (int32_t j = 0; j < n; j++) { + dict.keys.emplace_back(llama_model_meta_arr_str(model, key.c_str(), j)); + dict.values.emplace_back(llama_model_meta_arr_str(model, val_key.c_str(), j)); + } + } } return tmpls; } @@ -1439,6 +1465,12 @@ static common_chat_params_init_fn common_chat_template_detect_params_init(const return common_chat_params_init_qwen3_coder; } + // Inkling 1 and 2 + if (is_inkling_template(src)) { + LOG_DBG("Using specialized template: Inkling\n"); + return common_chat_params_init_inkling; + } + return nullptr; } @@ -1971,5 +2003,6 @@ common_json common_chat_templates_get_caps(const common_chat_templates * chat_te : chat_templates->template_default->caps; common_json result = caps.to_map(); result["reasoning_effort_levels"] = caps.reasoning_effort_levels; + result["reasoning_effort_rejected"] = caps.reasoning_effort_rejected; return result; } diff --git a/common/chat.h b/common/chat.h index 304ccf9eca38..43331b16d4a0 100644 --- a/common/chat.h +++ b/common/chat.h @@ -491,15 +491,23 @@ std::optional common_chat_try_specialized_template( struct common_chat_prompt_preset { std::string system; std::string user; - bool has_language = false; // the preset already names the requested language + bool has_language = false; // the preset already names the requested language + bool has_context = false; // the user text already holds the context + bool media_first = false; // the media goes before the user text + bool needs_audio_length = false; // the user text depends on the audio length, call again with it }; -common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language = ""); +// audio_length: in seconds, 0 if unknown +// context: extra info from the user (e.g. names, hotwords), only used by some presets, see has_context +common_chat_prompt_preset common_chat_get_asr_prompt(const common_chat_templates * chat_templates, const std::string & language = "", + double audio_length = 0.0, const std::string & context = ""); // prompt of the model's "tts" chat template for the text to speak, empty if the model has none // language and voice are optional, the template defines their defaults +// g2p (optional): the letter-to-sound model of the template's tts_g2p(), e.g. mtmd_gen_audio_g2p() std::string common_chat_get_tts_prompt(const common_chat_templates * chat_templates, const std::string & text, - const std::string & language = "", const std::string & voice = ""); + const std::string & language = "", const std::string & voice = "", + const std::function & g2p = nullptr); // system prompt line for the speech language and voice (e.g. LFM3-Audio), empty if not used std::string common_chat_get_speech_system_prompt(const common_chat_templates * chat_templates, diff --git a/common/common.cpp b/common/common.cpp index 657dcdbf530c..b009d460d697 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1313,6 +1313,11 @@ common_init_result::common_init_result(common_params & params, bool model_only) LOG_INF("%s", "decision model reads the embeddings output, enabling embedding mode\n"); } + // 0 is n_batch + if ((decision_type == COMMON_DECISION_TYPE_LFM3_D1 || decision_type == COMMON_DECISION_TYPE_LFM3_D1_OMNI) && cparams.n_outputs_max != 0) { + cparams.n_outputs_max = std::max(cparams.n_outputs_max, (uint32_t) COMMON_DECISION_LFM3_D1_SET_SIZE); + } + if (llama_model_classifier_free_guidance(model)) { params.kv_unified = true; cparams.kv_unified = true; @@ -2334,6 +2339,9 @@ llama_batch_ext * common_batch::get_sub_batch(int32_t off, int32_t n) { if (t.decision_order != 0) { llama_batch_ext_set_decision_order(res, idx, (llama_decision_order) t.decision_order); } + if (t.decision_group != 0 && !llama_batch_ext_set_decision_group(res, idx, t.decision_group)) { + GGML_ABORT("%s: failed to set the decision group of the entry at index %d\n", __func__, i); + } } return res; diff --git a/common/common.h b/common/common.h index 6043ab34239f..a8e89ed2dd65 100644 --- a/common/common.h +++ b/common/common.h @@ -174,18 +174,20 @@ enum common_params_sampling_config : uint64_t { }; enum common_speculative_type { - COMMON_SPECULATIVE_TYPE_NONE, // no speculative decoding - COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE, // standalone draft model speculative decoding - COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3, // Eagle3 speculative decoding - COMMON_SPECULATIVE_TYPE_DRAFT_MTP, // Multi-token prediction - COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, // DFlash speculative decoding - COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, // DSpark speculative decoding (DFlash + Markov head) - COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE, // simple self-speculative decoding based on n-grams - COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K, // self-speculative decoding with n-gram keys only - COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V, // self-speculative decoding with n-gram keys and 4 m-gram values + COMMON_SPECULATIVE_TYPE_NONE, // no speculative decoding + COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE, // standalone draft model speculative decoding + COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3, // Eagle3 speculative decoding + COMMON_SPECULATIVE_TYPE_DRAFT_MTP, // Multi-token prediction + COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, // DFlash speculative decoding + COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, // DSpark speculative decoding (DFlash + Markov head) + COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2, // DFlash2 speculative decoding (DFlash + selector) + COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR, // LiliCorr speculative decoding (DFlash + scorer) + COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE, // simple self-speculative decoding based on n-grams + COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K, // self-speculative decoding with n-gram keys only + COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V, // self-speculative decoding with n-gram keys and 4 m-gram values COMMON_SPECULATIVE_TYPE_NGRAM_MOD, - COMMON_SPECULATIVE_TYPE_NGRAM_CACHE, // self-speculative decoding with 3-level n-gram cache - COMMON_SPECULATIVE_TYPE_COUNT // number of types, unknown type + COMMON_SPECULATIVE_TYPE_NGRAM_CACHE, // self-speculative decoding with 3-level n-gram cache + COMMON_SPECULATIVE_TYPE_COUNT // number of types, unknown type }; // Grammar type enumeration @@ -414,7 +416,12 @@ struct common_params_speculative { uint32_t need_n_rs_seq() const { bool needs_rs_seq = std::any_of(types.begin(), types.end(), [&](auto t) { - return t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP || t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 || t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK; + return t == COMMON_SPECULATIVE_TYPE_DRAFT_MTP || + t == COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3 || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2 || + t == COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR; }); return needs_rs_seq ? draft.n_max : 0u; @@ -695,6 +702,7 @@ struct common_params { // UI configs bool ui = true; bool ui_mcp_proxy = false; + bool ui_mcp_proxy_allow_private_urls = false; // allow the MCP CORS proxy to reach local or private addresses std::string ui_config_json; // "advanced" endpoints are disabled by default for better security @@ -789,6 +797,7 @@ struct common_params { std::string tts_lang = ""; std::string tts_voice = ""; std::string tts_speaker_file = ""; + std::string tts_speaker_text = ""; bool is_gen_docs = false; // whether we are running inside llama-gen-docs }; @@ -994,6 +1003,9 @@ enum common_decision_type { COMMON_DECISION_TYPE_UNKNOWN, // a decision model of a type that is not supported }; +// lfm3-d1: max questions packed in one prompt +#define COMMON_DECISION_LFM3_D1_SET_SIZE 16 + common_decision_type common_get_decision_type(const struct llama_model * model); // metadata of a GGUF file, read without loading the model @@ -1109,6 +1121,7 @@ struct common_batch { llama_embd state; // non-owning view of the data passed to set_embd_state(), data == NULL if none std::vector seq_ids_extra; // see add_seq() int32_t decision_order = 0; // see llama_batch_ext_set_decision_order() + int32_t decision_group = 0; // see llama_batch_ext_set_decision_group() int32_t embd_row = -1; // see add_embd_row(), -1 if none int32_t state_row = -1; // see set_embd_state_row(), -1 if none }; diff --git a/common/jinja/caps.cpp b/common/jinja/caps.cpp index de7780bdf77c..cf14c71c56d9 100644 --- a/common/jinja/caps.cpp +++ b/common/jinja/caps.cpp @@ -627,9 +627,14 @@ caps caps_get(jinja::program & prog) { // levels sharing a render are aliases and the highest one is kept const auto unknown = render("REASONING_EFFORT_UNKNOWN"); std::vector renders; + std::vector rejected; for (const auto & level : candidates) { const auto rendered = render(level); - if (!rendered || rendered == unknown) { + if (!rendered) { + rejected.push_back(level); + continue; + } + if (rendered == unknown) { continue; } const auto it = std::find(renders.begin(), renders.end(), *rendered); @@ -640,6 +645,11 @@ caps caps_get(jinja::program & prog) { result.reasoning_effort_levels.push_back(level); } } + + // a template that renders no level fails the probe for another reason, so its failures say nothing about the levels + if (!result.reasoning_effort_levels.empty()) { + result.reasoning_effort_rejected = rejected; + } } JJ_DEBUG("%s\n", result.to_string().c_str()); diff --git a/common/jinja/caps.h b/common/jinja/caps.h index 108501e06b7c..f231309e6d1b 100644 --- a/common/jinja/caps.h +++ b/common/jinja/caps.h @@ -23,6 +23,9 @@ struct caps { // reasoning effort levels the template renders distinctly, from lowest to highest std::vector reasoning_effort_levels; + // reasoning effort levels the template raises on + std::vector reasoning_effort_rejected; + // one of the 2 content capabilities must be true bool supports_string_content = true; bool supports_typed_content = false; diff --git a/common/jinja/lexer.cpp b/common/jinja/lexer.cpp index bf2dfacdadd2..8007631534ce 100644 --- a/common/jinja/lexer.cpp +++ b/common/jinja/lexer.cpp @@ -263,41 +263,6 @@ lexer_result lexer::tokenize(const std::string & source) { char ch = src[pos]; - bool is_closing_block = ch == '-' && next_pos_is( {'%', '}'} ); - - // Check for unary operators - if (!is_closing_block && (ch == '-' || ch == '+')) { - start_pos = pos; - token::type last_token_type = tokens.empty() ? token::eof : tokens.back().t; - if (last_token_type == token::text || last_token_type == token::eof) { - throw lexer_exception(std::string("unexpected character: ") + ch, source, pos); - } - switch (last_token_type) { - case token::identifier: - case token::numeric_literal: - case token::string_literal: - case token::close_paren: - case token::close_square_bracket: - // Part of a binary operator - // a - 1, 1 - 1, true - 1, "apple" - 1, (1) - 1, a[1] - 1 - // Continue parsing normally - break; - default: { - // Is part of a unary operator - // (-1), [-1], (1 + -1), not -1, -apple - ++pos; // Consume the operator - - // Check for numbers following the unary operator - std::string num = consume_numeric(); - std::string value = std::string(1, ch) + num; - token::type t = num.empty() ? token::unary_operator : token::numeric_literal; - // JJ_DEBUG("consumed unary operator or numeric literal: '%s'", value.c_str()); - tokens.push_back({t, value, start_pos}); - continue; - } - } - } - // Try to match one of the tokens in the mapping table bool matched = false; for (const auto & [seq, typ] : ordered_mapping_table) { diff --git a/common/jinja/lexer.h b/common/jinja/lexer.h index 3f4ebb62a8d5..3b203c6f1819 100644 --- a/common/jinja/lexer.h +++ b/common/jinja/lexer.h @@ -39,7 +39,6 @@ struct token { multiplicative_binary_operator, // * / % power_operator, // ** comparison_binary_operator, // < > <= >= == != - unary_operator, // ! - + comment, // {# ... #} }; type t; @@ -74,7 +73,6 @@ static std::string type_to_string(token::type t) { case token::multiplicative_binary_operator: return "multiplicative_binary_operator"; case token::power_operator: return "power_operator"; case token::comparison_binary_operator: return "comparison_binary_operator"; - case token::unary_operator: return "unary_operator"; case token::comment: return "comment"; default: return "unknown"; } @@ -141,6 +139,7 @@ struct lexer { {"~", token::additive_binary_operator}, {"**", token::power_operator}, {"*", token::multiplicative_binary_operator}, + {"//", token::multiplicative_binary_operator}, {"/", token::multiplicative_binary_operator}, {"%", token::multiplicative_binary_operator}, // Assignment operator diff --git a/common/jinja/parser.cpp b/common/jinja/parser.cpp index 0841828c454a..4807b69951e7 100644 --- a/common/jinja/parser.cpp +++ b/common/jinja/parser.cpp @@ -482,7 +482,8 @@ class parser { } statement_ptr parse_unary_expression() { - if (is(token::unary_operator)) { + // a sign where an operand is expected is unary: -x, 1 + -x, x if c else -1 + if (is(token::additive_binary_operator) && peek().value != "~") { depth_guard guard(*this); size_t start_pos = current; auto op = next(); diff --git a/common/jinja/runtime.cpp b/common/jinja/runtime.cpp index d60a99d2591e..433707d71ae6 100644 --- a/common/jinja/runtime.cpp +++ b/common/jinja/runtime.cpp @@ -89,21 +89,22 @@ value statement::execute(context & ctx) const { } value identifier::execute_impl(context & ctx) const { - auto it = ctx.get_val(val); - auto builtins = global_builtins(); - if (!it->is_undefined()) { + auto it = ctx.find_val(key); + if (it && !it->is_undefined()) { if (ctx.is_get_stats) { value_t::stats_t::mark_used(it); } JJ_DEBUG("Identifier '%s' found, type = %s", val.c_str(), it->type().c_str()); return it; - } else if (builtins.find(val) != builtins.end()) { + } + const auto & builtins = global_builtins(); + auto builtin = builtins.find(val); + if (builtin != builtins.end()) { JJ_DEBUG("Identifier '%s' found in builtins", val.c_str()); - return mk_val(val, builtins.at(val)); - } else { - JJ_DEBUG("Identifier '%s' not found, returning undefined", val.c_str()); - return mk_val(val); + return mk_val(val, builtin->second); } + JJ_DEBUG("Identifier '%s' not found, returning undefined", val.c_str()); + return mk_val(val); } value object_literal::execute_impl(context & ctx) const { @@ -190,11 +191,30 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val if (is_float) { return mk_val(res); } else { - return mk_val(static_cast(res)); + return mk_val(float_to_int(res)); } } else if (op.value == "/") { JJ_DEBUG("Division operation: %f / %f", a, b); return mk_val(a / b); + } else if (op.value == "//") { + // python semantics: round toward -inf + if (is_val(left_val) && is_val(right_val)) { + const int64_t x = left_val->as_int(); + const int64_t y = right_val->as_int(); + if (y == 0) { + throw std::runtime_error("integer division by zero"); + } + if (y == -1) { + // INT64_MIN / -1 is UB, wrap around instead + return mk_val((int64_t) (0 - (uint64_t) x)); + } + int64_t q = x / y; + if (x % y != 0 && (x < 0) != (y < 0)) { + q -= 1; + } + return mk_val(q); + } + return mk_val(std::floor(a / b)); } else if (op.value == "%") { double rem = std::fmod(a, b); JJ_DEBUG("Modulo operation: %f %% %f = %f", a, b, rem); @@ -202,7 +222,7 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val if (is_float) { return mk_val(rem); } else { - return mk_val(static_cast(rem)); + return mk_val(float_to_int(rem)); } } else if (op.value == "<") { JJ_DEBUG("Comparison operation: %f < %f is %d", a, b, a < b); @@ -273,12 +293,17 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val // String membership if (is_val(left_val) && is_val(right_val)) { // case: "a" in "abc" - bool member = test_is_in(); - if (op.value == "in") { - return mk_val(member); - } else if (op.value == "not in") { - return mk_val(!member); + if (op.value == "in" || op.value == "not in") { + bool member = test_is_in(); + return mk_val(op.value == "in" ? member : !member); } + // case: "a" < "b"; UTF-8 byte order is the same as codepoint order, like python + const std::string a = left_val->as_string().str(); + const std::string b = right_val->as_string().str(); + if (op.value == "<") { return mk_val(a < b); } + if (op.value == ">") { return mk_val(a > b); } + if (op.value == "<=") { return mk_val(a <= b); } + if (op.value == ">=") { return mk_val(a >= b); } } // Value key in object @@ -693,7 +718,7 @@ value set_statement::execute_impl(context & ctx) const { } auto obj_ptr = cast_val(object); JJ_DEBUG("Setting object property '%s' with value type %s", prop_name.c_str(), rhs->type().c_str()); - obj_ptr->insert(prop_name, rhs); + obj_ptr->insert(cached_val(ctx, member->static_property), rhs); } else { throw std::runtime_error("Invalid LHS inside assignment expression: " + assignee->type()); @@ -786,13 +811,14 @@ value call_statement::execute_impl(context & ctx) const { } auto * callee_func = cast_val(callee_val); - context caller_ctx(ctx); // new scope for caller execution + // caller() can be saved and called after this scope ended, it owns a snapshot of the variables + auto caller_ctx = std::make_shared(ctx.snapshot()); - const func_handler func = [this, caller_ctx = std::move(caller_ctx)](const func_args & args) -> value { + const func_handler func = [this, caller_ctx](const func_args & args) -> value { if (args.ctx.macro_depth >= JINJA_RECURSIVE_LIMIT) { throw std::runtime_error("macro calls are nested more than " + std::to_string(JINJA_RECURSIVE_LIMIT) + " levels deep"); } - context block_ctx(caller_ctx); // new scope for block execution + context block_ctx(*caller_ctx); // new scope for block execution block_ctx.macro_depth = args.ctx.macro_depth + 1; bind_parameters("caller", this->caller_args, args, block_ctx); @@ -813,6 +839,19 @@ value call_statement::execute_impl(context & ctx) const { return callee_func->invoke(args); } +member_expression::member_expression(statement_ptr && object, statement_ptr && property, bool computed) : + object(std::move(object)), + property(std::move(property)), + computed(computed) { + chk_type(this->object); + chk_type(this->property); + if (!computed) { + if (const auto * id = cast_stmt(this->property)) { + static_property = id->key; + } + } +} + value member_expression::execute_impl(context & ctx) const { value object = this->object->execute(ctx); @@ -821,14 +860,13 @@ value member_expression::execute_impl(context & ctx) const { // syntax: obj[expr] JJ_DEBUG("Member expression, computing property type %s", this->property->type().c_str()); - int64_t arr_size = 0; - if (is_val(object)) { - arr_size = object->as_array().size(); - } else if (is_val(object)) { - arr_size = object->as_string().length(); - } - if (is_stmt(this->property)) { + int64_t arr_size = 0; + if (is_val(object)) { + arr_size = static_cast(object->as_array().size()); + } else if (is_val(object)) { + arr_size = static_cast(cast_val(object)->val_str.length()); + } auto s = cast_stmt(this->property); value step_val = s->step_expr ? s->step_expr->execute(ctx) : mk_val(1); value start_val = s->start_expr ? s->start_expr->execute(ctx) : (step_val->as_int() < 0 ? mk_val(arr_size - 1) : mk_val(0)); @@ -850,7 +888,7 @@ value member_expression::execute_impl(context & ctx) const { } } else if (is_stmt(this->property)) { // syntax: obj.index - property = mk_val(cast_stmt(this->property)->val); + property = this->property->execute(ctx); if (property->as_int() < 0) { throw std::runtime_error("Static member property cannot be negative"); } @@ -859,8 +897,8 @@ value member_expression::execute_impl(context & ctx) const { if (!is_stmt(this->property)) { throw std::runtime_error("Static member property must be an identifier"); } - property = mk_val(cast_stmt(this->property)->val); - std::string prop = property->as_string().str(); + property = cached_val(ctx, static_property); + const auto & prop = cast_stmt(this->property)->val; JJ_DEBUG("Member expression, object type %s, static property '%s'", object->type().c_str(), prop.c_str()); // behavior of jinja2: obj having prop as a built-in function AND 'prop', as an object key, @@ -868,51 +906,56 @@ value member_expression::execute_impl(context & ctx) const { // while obj['prop'] returns the property value. // example: {"obj": {"items": 123}} -> obj.items is the built-in function, obj['items'] is 123 - value val = try_builtin_func(ctx, prop, object, true); - if (!is_val(val)) { + value val = find_builtin_func(ctx, prop, object); + if (val) { return val; } // else, fallthrough to normal property access below } JJ_DEBUG("Member expression on object type %s, property type %s", object->type().c_str(), property->type().c_str()); - value val = mk_val("object_property"); + value val; if (property->is_undefined()) { JJ_DEBUG("%s", "Member expression property is undefined, returning undefined"); - return val; + return mk_val("object_property"); } ensure_key_type_allowed(property); if (is_val(object)) { JJ_DEBUG("%s", "Accessing property on undefined object, returning undefined"); - return val; + return mk_val("object_property"); } else if (is_val(object)) { - auto key = property->as_string().str(); - val = object->at(property, val); - if (is_val(val)) { - val = try_builtin_func(ctx, key, object, true); + val = object->find(property); + if (!val || is_val(val)) { + val = try_builtin_func(ctx, property->as_string().str(), object, true); } - JJ_DEBUG("Accessed property '%s' value, got type: %s", key.c_str(), val->type().c_str()); + JJ_DEBUG("Accessed property '%s' value, got type: %s", property->as_string().str().c_str(), val->type().c_str()); } else if (is_val(object) || is_val(object)) { if (is_val(property) || is_val(property)) { int64_t index = property->as_int(); JJ_DEBUG("Accessing %s index %d", object->type().c_str(), (int)index); if (is_val(object)) { - auto & arr = object->as_array(); + const auto * arr = cast_val(object); + const auto count = arr->as_array().size(); if (index < 0) { - index += static_cast(arr.size()); - } - if (index >= 0 && index < static_cast(arr.size())) { - val = arr[index]; + // Avoid negating INT64_MIN. + const uint64_t distance = static_cast(-(index + 1)) + 1; + if (distance <= count) { + val = arr->as_array().at(static_cast(count - distance)); + } + } else if (static_cast(index) < count) { + val = arr->as_array().at(static_cast(index)); } } else { // value_string - auto str = object->as_string().str(); - if (index >= 0 && index < static_cast(str.size())) { - val = mk_val(std::string(1, str[index])); + if (index >= 0) { + const auto byte = cast_val(object)->val_str.byte_at(static_cast(index)); + if (byte) { + val = mk_val(std::string(1, *byte)); + } } } @@ -930,7 +973,10 @@ value member_expression::execute_impl(context & ctx) const { val = try_builtin_func(ctx, key, object, true); } - if (ctx.is_get_stats && val && object && property) { + if (!val) { + val = mk_val("object_property"); + } + if (ctx.is_get_stats && object && property) { value_t::stats_t::mark_used(val); value_t::stats_t::mark_used(object); value_t::stats_t::mark_used(property); diff --git a/common/jinja/runtime.h b/common/jinja/runtime.h index 43e1085516da..066c4e0c0ed3 100644 --- a/common/jinja/runtime.h +++ b/common/jinja/runtime.h @@ -81,12 +81,43 @@ struct context { current_time(parent.current_time), is_get_stats(parent.is_get_stats), macro_depth(parent.macro_depth), - // inherit variables (for example, when entering a new scope) - env(mk_val(*parent.env)) {} + // child scope: own variables only, lookups fall back to the parent (which must outlive this scope) + parent(&parent), + env(mk_val()) { + env->has_builtins = false; + } + + context(context &&) = default; + + // copy with all visible variables flattened in, for a scope that can outlive its parents (caller() of a call block) + context snapshot() const { + std::vector chain; + for (const context * c = this; c; c = c->parent) { + chain.push_back(c); + } + context res(*this); + res.parent = nullptr; + for (auto it = chain.rbegin(); it != chain.rend(); ++it) { + for (const auto & kv : (*it)->env->as_ordered_object()) { + res.env->insert(kv.first, kv.second); + } + } + return res; + } + + // returns nullptr if not found + value find_val(const value & key) { + for (const context * c = this; c; c = c->parent) { + if (value v = c->env->find(key)) { + return v; + } + } + return nullptr; + } value get_val(const std::string & name) { - value default_val = mk_val(name); - return env->at(name, default_val); + auto result = find_val(mk_val(name)); + return result ? result : mk_val(name); } void set_val(const std::string & name, const value & val) { @@ -102,9 +133,16 @@ struct context { } private: + const context * parent = nullptr; value_object env; }; +// values cached in the AST are shared across renders, but stats mutate values, so stats mode gets a fresh copy +template +value cached_val(const context & ctx, const value & cached) { + return ctx.is_get_stats ? mk_val(*cast_val(cached)) : cached; +} + // utils for visiting AST nodes static std::vector stmts_to_ptr(const statements & stmts) { std::vector children; @@ -328,11 +366,8 @@ struct member_expression : public expression { statement_ptr property; bool computed; // true if obj[expr] and false if obj.prop - member_expression(statement_ptr && object, statement_ptr && property, bool computed) - : object(std::move(object)), property(std::move(property)), computed(computed) { - chk_type(this->object); - chk_type(this->property); - } + value static_property; // set if property is an identifier, see cached_val() + member_expression(statement_ptr && object, statement_ptr && property, bool computed); std::string type() const override { return "MemberExpression"; } value execute_impl(context & ctx) const override; void visit(context & ctx) const override { @@ -367,7 +402,8 @@ struct call_expression : public expression { */ struct identifier : public expression { std::string val; - explicit identifier(const std::string & val) : val(val) {} + const value key; // lookup key, safe to share across renders as lookups do not touch stats + explicit identifier(const std::string & val) : val(val), key(mk_val(val)) {} std::string type() const override { return "Identifier"; } value execute_impl(context & ctx) const override; }; @@ -376,28 +412,31 @@ struct identifier : public expression { struct integer_literal : public expression { int64_t val; - explicit integer_literal(int64_t val) : val(val) {} + const value constant; // see cached_val() + explicit integer_literal(int64_t val) : val(val), constant(mk_val(val)) {} std::string type() const override { return "IntegerLiteral"; } - value execute_impl(context &) const override { - return mk_val(val); + value execute_impl(context & ctx) const override { + return cached_val(ctx, constant); } }; struct float_literal : public expression { double val; - explicit float_literal(double val) : val(val) {} + const value constant; // see cached_val() + explicit float_literal(double val) : val(val), constant(mk_val(val)) {} std::string type() const override { return "FloatLiteral"; } - value execute_impl(context &) const override { - return mk_val(val); + value execute_impl(context & ctx) const override { + return cached_val(ctx, constant); } }; struct string_literal : public expression { std::string val; - explicit string_literal(const std::string & val) : val(val) {} + const value constant; // see cached_val() + explicit string_literal(const std::string & val) : val(val), constant(mk_val(val)) {} std::string type() const override { return "StringLiteral"; } - value execute_impl(context &) const override { - return mk_val(val); + value execute_impl(context & ctx) const override { + return cached_val(ctx, constant); } }; @@ -748,7 +787,7 @@ static void gather_string_parts_recursive(const value & val, value_string & part } else if (is_val(val) && depth >= JINJA_RECURSIVE_LIMIT) { throw std::runtime_error("value is nested more than " + std::to_string(JINJA_RECURSIVE_LIMIT) + " levels deep"); } else if (is_val(val)) { - auto items = cast_val(val)->as_array(); + const auto & items = cast_val(val)->as_array(); for (const auto & item : items) { gather_string_parts_recursive(item, parts, depth + 1); } diff --git a/common/jinja/string.cpp b/common/jinja/string.cpp index bde679e4e9df..22189fa6f47c 100644 --- a/common/jinja/string.cpp +++ b/common/jinja/string.cpp @@ -43,14 +43,59 @@ void string::mark_input() { } std::string string::str() const { - if (parts.size() == 1) { - return parts[0].val; + std::string result; + result.reserve(length()); + for (const auto & part : parts) { + result += part.val; + } + return result; +} + +bool string::empty() const { + for (const auto & part : parts) { + if (!part.val.empty()) { + return false; + } } - std::ostringstream oss; + return true; +} + +std::optional string::byte_at(size_t index) const { for (const auto & part : parts) { - oss << part.val; + if (index < part.val.size()) { + return part.val[index]; + } + index -= part.val.size(); + } + return {}; +} + +bool string::equals(const string & other) const { + size_t part = 0, offset = 0; + for (const auto & left : parts) { + std::string_view text(left.val); + while (!text.empty()) { + while (part < other.parts.size() && offset == other.parts[part].val.size()) { + ++part; + offset = 0; + } + if (part == other.parts.size()) { + return false; + } + const auto & right = other.parts[part].val; + const auto count = std::min(text.size(), right.size() - offset); + if (text.substr(0, count) != std::string_view(right).substr(offset, count)) { + return false; + } + text.remove_prefix(count); + offset += count; + } + } + while (part < other.parts.size() && offset == other.parts[part].val.size()) { + ++part; + offset = 0; } - return oss.str(); + return part == other.parts.size(); } size_t string::length() const { diff --git a/common/jinja/string.h b/common/jinja/string.h index 669afb8f1da0..119ad11c2b0e 100644 --- a/common/jinja/string.h +++ b/common/jinja/string.h @@ -39,6 +39,9 @@ struct string { std::string str() const; size_t length() const; + bool empty() const; + bool equals(const string & other) const; + std::optional byte_at(size_t index) const; void hash_update(hasher & hash) const noexcept; bool all_parts_are_input() const; bool is_uppercase() const; diff --git a/common/jinja/value.cpp b/common/jinja/value.cpp index 333241d7a9e7..9692d7cab2f9 100644 --- a/common/jinja/value.cpp +++ b/common/jinja/value.cpp @@ -276,19 +276,17 @@ static value tojson(const func_args & args) { if (args.ctx.is_get_stats) { // mark as used (recursively) for stats auto val_input = args.get_pos(0); - value_t::stats_t::mark_used(const_cast(val_input), true); + value_t::stats_t::mark_used(val_input, true); } if (is_val(val_indent)) { indent = static_cast(val_indent->as_int()); } - if (val_sort->as_bool()) { // undefined == false - throw not_implemented_exception("tojson sort_keys=true not implemented"); - } + const bool sort_keys = val_sort->as_bool(); // undefined == false const bool ensure_ascii = val_ascii->as_bool(); // undefined == false auto separators = (is_val(val_separators) ? val_separators : mk_val())->as_array(); std::string item_sep = separators.size() > 0 ? separators[0]->as_string().str() : (indent < 0 ? ", " : ","); std::string key_sep = separators.size() > 1 ? separators[1]->as_string().str() : ": "; - std::string json_str = value_to_json(args.get_pos(0), indent, item_sep, key_sep); + std::string json_str = value_to_json(args.get_pos(0), indent, item_sep, key_sep, sort_keys); if (ensure_ascii) { json_str = json_ensure_ascii_preserving_format(json_str); } @@ -507,7 +505,12 @@ const func_builtins & global_builtins() { }}, {"test_is_divisibleby", [](const func_args & args) -> value { args.ensure_vals(); - bool res = args.get_pos(0)->val_int % args.get_pos(1)->val_int == 0; + const int64_t a = args.get_pos(0)->as_int(); + const int64_t b = args.get_pos(1)->as_int(); + if (b == 0) { + throw std::runtime_error("divisibleby: division by zero"); + } + bool res = b == -1 || a % b == 0; // avoid INT64_MIN % -1 overflow return mk_val(res); }}, {"test_is_string", test_type_fn}, @@ -519,11 +522,11 @@ const func_builtins & global_builtins() { {"test_is_mapping", test_type_fn}, {"test_is_lower", [](const func_args & args) -> value { args.ensure_vals(); - return mk_val(args.get_pos(0)->val_str.is_lowercase()); + return mk_val(cast_val(args.get_pos(0))->val_str.is_lowercase()); }}, {"test_is_upper", [](const func_args & args) -> value { args.ensure_vals(); - return mk_val(args.get_pos(0)->val_str.is_uppercase()); + return mk_val(cast_val(args.get_pos(0))->val_str.is_uppercase()); }}, {"test_is_none", test_type_fn}, {"test_is_defined", [](const func_args & args) -> value { @@ -571,7 +574,7 @@ const func_builtins & global_builtins() { {"test_is_test", [](const func_args & args) -> value { args.ensure_vals(); auto & builtins = global_builtins(); - std::string test_name = args.get_pos(0)->val_str.str(); + std::string test_name = cast_val(args.get_pos(0))->val_str.str(); auto it = builtins.find("test_is_" + test_name); bool res = it != builtins.end(); return mk_val(res); @@ -613,18 +616,26 @@ const func_builtins & global_builtins() { return builtins; } -value try_builtin_func(context & ctx, const std::string & name, value & input, bool undef_on_missing) { +value find_builtin_func(context & ctx, const std::string & name, value & input) { JJ_DEBUG("Trying built-in function '%s' for type %s", name.c_str(), input->type().c_str()); if (ctx.is_get_stats) { value_t::stats_t::mark_used(input); input->stats.ops.insert(name); } - auto builtins = input->get_builtins(); + const auto & builtins = input->get_builtins(); auto it = builtins.find(name); if (it != builtins.end()) { JJ_DEBUG("Binding built-in '%s'", name.c_str()); return mk_val(name, it->second, input); } + return nullptr; +} + +value try_builtin_func(context & ctx, const std::string & name, value & input, bool undef_on_missing) { + value func = find_builtin_func(ctx, name, input); + if (func) { + return func; + } if (undef_on_missing) { return mk_val(name); } @@ -700,7 +711,7 @@ const func_builtins & value_float_t::get_builtins() const { }}, {"int", [](const func_args & args) -> value { args.ensure_vals(); - int64_t val = static_cast(args.get_pos(0)->as_float()); + int64_t val = float_to_int(args.get_pos(0)->as_float()); return mk_val(val); }}, {"float", [](const func_args & args) -> value { @@ -831,7 +842,7 @@ const func_builtins & value_string_t::get_builtins() const { --maxsplit; } auto res = mk_val(str); - res->val_str.mark_input_based_on(args.get_pos(0)->val_str); + res->val_str.mark_input_based_on(cast_val(args.get_pos(0))->val_str); result->push_back(std::move(res)); return result; }}, @@ -858,7 +869,7 @@ const func_builtins & value_string_t::get_builtins() const { --maxsplit; } auto res = mk_val(str); - res->val_str.mark_input_based_on(args.get_pos(0)->val_str); + res->val_str.mark_input_based_on(cast_val(args.get_pos(0))->val_str); result->push_back(std::move(res)); result->reverse(); return result; @@ -891,7 +902,7 @@ const func_builtins & value_string_t::get_builtins() const { } } auto res = mk_val(str); - res->val_str.mark_input_based_on(args.get_pos(0)->val_str); + res->val_str.mark_input_based_on(cast_val(args.get_pos(0))->val_str); return res; }}, {"format", [](const func_args & args) -> value { @@ -1088,8 +1099,28 @@ const func_builtins & value_bool_t::get_builtins() const { return builtins; } -[[noreturn]] static value array_sum_not_implemented(const func_args &) { - throw not_implemented_exception("Array sum builtin not implemented"); +static value array_sum(const func_args & args) { + args.ensure_kwargs({"attribute", "start"}); + args.ensure_count(1, 3); + args.ensure_vals(); + value undef = mk_val(); + value attribute = args.get_kwarg_or_pos("attribute", 1); + value start = args.get_kwarg_or_pos("start", 2); + // same as the + operator: compute in double, int result if all operands are int + bool is_float = is_val(start); + double sum = start->is_undefined() ? 0.0 : start->as_float(); + for (const auto & item : args.get_pos(0)->as_array()) { + value v = attribute->is_undefined() ? item : get_attribute(item, attribute, undef); + if (v->is_undefined() && !attribute->is_undefined()) { + throw raised_exception("sum: " + item->type() + " has no attribute '" + attribute->as_string().str() + "'"); + } + if (!is_val(v) && !is_val(v)) { + throw raised_exception("sum: unsupported operand type " + v->type()); + } + is_float = is_float || is_val(v); + sum += v->as_float(); + } + return is_float ? value(mk_val(sum)) : value(mk_val(float_to_int(sum))); } const func_builtins & value_array_t::get_builtins() const { @@ -1158,7 +1189,7 @@ const func_builtins & value_array_t::get_builtins() const { {"select", select_or_reject}, {"rejectattr", select_or_reject}, {"reject", select_or_reject}, - {"sum", array_sum_not_implemented}, + {"sum", array_sum}, {"join", [](const func_args & args) -> value { args.ensure_kwargs({"d", "attribute"}); args.ensure_count(1, 3); @@ -1191,7 +1222,7 @@ const func_builtins & value_array_t::get_builtins() const { if (args.ctx.is_get_stats) { // mark as used (recursively) for stats auto val_input = args.get_pos(0); - value_t::stats_t::mark_used(const_cast(val_input), true); + value_t::stats_t::mark_used(val_input, true); } return mk_val(args.get_pos(0)->as_string()); }}, @@ -1439,7 +1470,7 @@ const func_builtins & value_object_t::get_builtins() const { if (args.ctx.is_get_stats) { // mark as used (recursively) for stats auto val_input = args.get_pos(0); - value_t::stats_t::mark_used(const_cast(val_input), true); + value_t::stats_t::mark_used(val_input, true); } return mk_val(args.get_pos(0)->as_string()); }}, @@ -1643,6 +1674,11 @@ bool value_compare(const value & a, const value & b, value_compare_op op) { return result; } +template<> +value value_from_json(const common_json & json_val, bool mark_input) { + return from_json(json_val, mark_input); +} + template<> void global_from_json(context & ctx, const common_json & json_obj, bool mark_input) { // printf("global_from_json: %s\n" , json_obj.dump(2).c_str()); @@ -1728,7 +1764,7 @@ static std::string float_json(double val) { // recursively convert value to JSON string // TODO: avoid circular references -static void value_to_json_internal(std::ostringstream & oss, const value & val, int curr_lvl, int indent, const std::string_view item_sep, const std::string_view key_sep) { +static void value_to_json_internal(std::ostringstream & oss, const value & val, int curr_lvl, int indent, const std::string_view item_sep, const std::string_view key_sep, bool sort_keys) { auto indent_str = [indent, curr_lvl]() -> std::string { return (indent > 0) ? std::string(curr_lvl * indent, ' ') : ""; }; @@ -1775,7 +1811,7 @@ static void value_to_json_internal(std::ostringstream & oss, const value & val, oss << newline(); for (size_t i = 0; i < arr.size(); ++i) { oss << indent_str() << (indent > 0 ? std::string(indent, ' ') : ""); - value_to_json_internal(oss, arr[i], curr_lvl + 1, indent, item_sep, key_sep); + value_to_json_internal(oss, arr[i], curr_lvl + 1, indent, item_sep, key_sep, sort_keys); if (i < arr.size() - 1) { oss << item_sep; } @@ -1786,17 +1822,25 @@ static void value_to_json_internal(std::ostringstream & oss, const value & val, oss << "]"; } else if (is_val(val)) { const auto & obj = val->as_ordered_object(); // IMPORTANT: need to keep exact order + std::vector> items; + items.reserve(obj.size()); + for (const auto & pair : obj) { + items.emplace_back(is_val(pair.first) ? float_json(pair.first->as_float()) : pair.first->as_string().str(), pair.second); + } + if (sort_keys) { + // same order as python json.dumps(sort_keys=True): utf-8 byte order is code point order + std::stable_sort(items.begin(), items.end(), [](const auto & a, const auto & b) { return a.first < b.first; }); + } oss << "{"; - if (!obj.empty()) { + if (!items.empty()) { oss << newline(); size_t i = 0; - for (const auto & pair : obj) { + for (const auto & [key, item] : items) { oss << indent_str() << (indent > 0 ? std::string(indent, ' ') : ""); - const std::string key = is_val(pair.first) ? float_json(pair.first->as_float()) : pair.first->as_string().str(); - value_to_json_internal(oss, mk_val(key), curr_lvl + 1, indent, item_sep, key_sep); + value_to_json_internal(oss, mk_val(key), curr_lvl + 1, indent, item_sep, key_sep, sort_keys); oss << key_sep; - value_to_json_internal(oss, pair.second, curr_lvl + 1, indent, item_sep, key_sep); - if (i < obj.size() - 1) { + value_to_json_internal(oss, item, curr_lvl + 1, indent, item_sep, key_sep, sort_keys); + if (i < items.size() - 1) { oss << item_sep; } oss << newline(); @@ -1810,9 +1854,9 @@ static void value_to_json_internal(std::ostringstream & oss, const value & val, } } -std::string value_to_json(const value & val, int indent, const std::string_view item_sep, const std::string_view key_sep) { +std::string value_to_json(const value & val, int indent, const std::string_view item_sep, const std::string_view key_sep, bool sort_keys) { std::ostringstream oss; - value_to_json_internal(oss, val, 0, indent, item_sep, key_sep); + value_to_json_internal(oss, val, 0, indent, item_sep, key_sep, sort_keys); JJ_DEBUG("value_to_json: result=%s", oss.str().c_str()); return oss.str(); } @@ -1833,18 +1877,18 @@ std::string value_to_string_repr(const value & val) { } // stats utility -void value_t::stats_t::mark_used(value & val, bool deep, int depth) { +void value_t::stats_t::mark_used(const value & val, bool deep, int depth) { val->stats.used = true; if (deep && (is_val(val) || is_val(val)) && depth >= JINJA_RECURSIVE_LIMIT) { throw std::runtime_error("value is nested more than " + std::to_string(JINJA_RECURSIVE_LIMIT) + " levels deep"); } if (deep) { if (is_val(val)) { - for (auto & item : val->val_arr) { + for (auto & item : val->as_array()) { mark_used(item, deep, depth + 1); } } else if (is_val(val)) { - for (auto & pair : val->val_obj) { + for (auto & pair : val->as_ordered_object()) { mark_used(pair.first, deep, depth + 1); mark_used(pair.second, deep, depth + 1); } diff --git a/common/jinja/value.h b/common/jinja/value.h index 8fdff884edee..6843bf57a7e0 100644 --- a/common/jinja/value.h +++ b/common/jinja/value.h @@ -21,6 +21,20 @@ namespace jinja { struct value_t; using value = std::shared_ptr; +enum class value_kind { + INTEGER, + REAL, + STRING, + BOOLEAN, + ARRAY, + TUPLE, + OBJECT, + NONE, + UNDEFINED, + FUNCTION, + KEYWORD +}; +bool has_value_kind(const value_t * val, value_kind kind); // Helper to check the type of a value template @@ -34,12 +48,12 @@ struct extract_pointee> { template bool is_val(const value & ptr) { using PointeeType = typename extract_pointee::type; - return dynamic_cast(ptr.get()) != nullptr; + return has_value_kind(ptr.get(), PointeeType::kind_id); } template bool is_val(const value_t * ptr) { using PointeeType = typename extract_pointee::type; - return dynamic_cast(ptr) != nullptr; + return has_value_kind(ptr, PointeeType::kind_id); } template std::shared_ptr::type> mk_val(Args&&... args) { @@ -49,12 +63,12 @@ std::shared_ptr::type> mk_val(Args&&... args) { template const typename extract_pointee::type * cast_val(const value & ptr) { using PointeeType = typename extract_pointee::type; - return dynamic_cast(ptr.get()); + return is_val(ptr) ? static_cast(ptr.get()) : nullptr; } template typename extract_pointee::type * cast_val(value & ptr) { using PointeeType = typename extract_pointee::type; - return dynamic_cast(ptr.get()); + return is_val(ptr) ? static_cast(ptr.get()) : nullptr; } // End Helper @@ -91,6 +105,10 @@ struct context; // forward declaration template void global_from_json(context & ctx, const T_JSON & json_obj, bool mark_input); +// convert a single JSON value, same rules as global_from_json() +template +value value_from_json(const T_JSON & json_val, bool mark_input); + // // base value type // @@ -105,14 +123,7 @@ enum value_compare_op { eq, ge, gt, lt, ne }; bool value_compare(const value & a, const value & b, value_compare_op op); struct value_t { - int64_t val_int; - double val_flt; - string val_str; - - std::vector val_arr; - std::vector> val_obj; - - func_handler val_func; + const value_kind kind; // only used if ctx.is_get_stats = true struct stats_t { @@ -120,10 +131,10 @@ struct value_t { // ops can be builtin calls or operators: "array_access", "object_access" std::set ops; // utility to recursively mark value and its children as used - static void mark_used(value & val, bool deep = false, int depth = 0); + static void mark_used(const value & val, bool deep = false, int depth = 0); } stats; - value_t() = default; + explicit value_t(value_kind kind) : kind(kind) {} value_t(const value_t &) = default; virtual ~value_t() = default; @@ -141,6 +152,10 @@ struct value_t { virtual bool is_undefined() const { return false; } virtual const func_builtins & get_builtins() const { throw_type_error("has no builtins"); } + virtual value find(const value & key) { + value missing; + return at(key, missing); + } virtual bool has_key(const value &) { throw_type_error("is not an object value"); } virtual void insert(const value & /* key */, const value & /* val */) { throw_type_error("is not an object value"); } virtual value & at(const value & /* key */, value & /* default_val */) { throw_type_error("is not an object value"); } @@ -172,15 +187,23 @@ struct value_t { virtual bool nonequal(const value_t & other) const { return !equivalent(other); } }; +inline bool has_value_kind(const value_t * val, value_kind kind) { + return val && (val->kind == kind || + (kind == value_kind::ARRAY && (val->kind == value_kind::TUPLE))); +} + // // utils // const func_builtins & global_builtins(); +// returns nullptr if input has no built-in named `name` +value find_builtin_func(context & ctx, const std::string & name, value & input); +// returns value_undefined(name) if not found and undef_on_missing is set, throws otherwise value try_builtin_func(context & ctx, const std::string & name, value & input, bool undef_on_missing = false); value apply_filter_by_name(context & ctx, std::string filter_id, value input, const func_args & args); -std::string value_to_json(const value & val, int indent = -1, const std::string_view item_sep = ", ", const std::string_view key_sep = ": "); +std::string value_to_json(const value & val, int indent = -1, const std::string_view item_sep = ", ", const std::string_view key_sep = ": ", bool sort_keys = false); // Note: only used for debugging purposes std::string value_to_string_repr(const value & val); @@ -214,11 +237,28 @@ struct value_equality { // primitive value types // +// double to int64, saturating and with nan as 0; a plain cast is undefined outside the int64 range +inline int64_t float_to_int(double v) { + if (std::isnan(v)) { + return 0; + } + if (v >= 9223372036854775808.0) { + return INT64_MAX; + } + if (v <= -9223372036854775808.0) { + return INT64_MIN; + } + return static_cast(v); +} + struct value_int_t : public value_t { - value_int_t(int64_t v) { + static constexpr auto kind_id = value_kind::INTEGER; + int64_t val_int; + double val_flt; + value_int_t(int64_t v) : value_t(kind_id) { val_int = v; val_flt = static_cast(v); - if (static_cast(val_flt) != v) { + if (float_to_int(val_flt) != v) { val_flt = v < 0 ? -INFINITY : INFINITY; } } @@ -239,21 +279,22 @@ struct value_int_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return other.is_numeric() && val_int == other.val_int && val_flt == other.val_flt; + return other.is_numeric() && val_int == other.as_int() && val_flt == other.as_float(); } virtual bool nonequal(const value_t & other) const override { - return !(typeid(*this) == typeid(other) && val_int == other.val_int); + return !(kind == other.kind && val_int == other.as_int()); } }; using value_int = std::shared_ptr; struct value_float_t : public value_t { - value val; - value_float_t(double v) { + static constexpr auto kind_id = value_kind::REAL; + int64_t val_int; + double val_flt; + value_float_t(double v) : value_t(kind_id) { val_flt = v; - val_int = std::isfinite(v) ? static_cast(v) : 0; - val = mk_val(val_int); + val_int = std::isfinite(v) ? float_to_int(v) : 0; } virtual std::string type() const override { return "Float"; } virtual double as_float() const override { return val_flt; } @@ -272,7 +313,7 @@ struct value_float_t : public value_t { virtual bool is_hashable() const override { return true; } virtual hasher unique_hash() const noexcept override { if (static_cast(val_int) == val_flt) { - return val->unique_hash(); + return value_int_t(val_int).unique_hash(); } else { return hasher(typeid(*this)) .update(&val_int, sizeof(val_int)) @@ -281,19 +322,22 @@ struct value_float_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return other.is_numeric() && val_int == other.val_int && val_flt == other.val_flt; + return other.is_numeric() && val_int == other.as_int() && val_flt == other.as_float(); } virtual bool nonequal(const value_t & other) const override { - return !(typeid(*this) == typeid(other) && val_flt == other.val_flt); + return !(kind == other.kind && val_flt == other.as_float()); } }; using value_float = std::shared_ptr; struct value_string_t : public value_t { - value_string_t() { val_str = string(); } - value_string_t(const std::string & v) { val_str = string(v); } - value_string_t(const string & v) { val_str = v; } + static constexpr auto kind_id = value_kind::STRING; + string val_str; + value_string_t() : value_t(kind_id) {} + value_string_t(const std::string & v) : value_t(kind_id), val_str(v) {} + value_string_t(const string & v) : value_t(kind_id), val_str(v) {} + value_string_t(string && v) : value_t(kind_id), val_str(std::move(v)) {} virtual std::string type() const override { return "String"; } virtual string as_string() const override { return val_str; } virtual std::string as_repr() const override { @@ -304,7 +348,7 @@ struct value_string_t : public value_t { return ss.str(); } virtual bool as_bool() const override { - return val_str.length() > 0; + return !val_str.empty(); } virtual const func_builtins & get_builtins() const override; virtual bool is_hashable() const override { return true; } @@ -320,51 +364,50 @@ struct value_string_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return typeid(*this) == typeid(other) && val_str.str() == other.val_str.str(); + return kind == other.kind && val_str.equals(static_cast(other).val_str); } }; using value_string = std::shared_ptr; struct value_bool_t : public value_t { - value val; - value_bool_t(bool v) { + static constexpr auto kind_id = value_kind::BOOLEAN; + int64_t val_int; + double val_flt; + value_bool_t(bool v) : value_t(kind_id) { val_int = static_cast(v); val_flt = static_cast(v); - val = mk_val(val_int); } virtual std::string type() const override { return "Boolean"; } virtual int64_t as_int() const override { return val_int; } + virtual double as_float() const override { return val_flt; } virtual bool as_bool() const override { return val_int; } virtual string as_string() const override { return std::string(val_int ? "True" : "False"); } virtual const func_builtins & get_builtins() const override; virtual bool is_numeric() const override { return true; } virtual bool is_hashable() const override { return true; } virtual hasher unique_hash() const noexcept override { - return val->unique_hash(); + return value_int_t(val_int).unique_hash(); } protected: virtual bool equivalent(const value_t & other) const override { - return other.is_numeric() && val_int == other.val_int && val_flt == other.val_flt; + return other.is_numeric() && val_int == other.as_int() && val_flt == other.as_float(); } virtual bool nonequal(const value_t & other) const override { - return !(typeid(*this) == typeid(other) && val_int == other.val_int); + return !(kind == other.kind && val_int == other.as_int()); } }; using value_bool = std::shared_ptr; struct value_array_t : public value_t { - value_array_t() = default; - value_array_t(value & v) { - val_arr = v->val_arr; - } - value_array_t(std::vector && arr) { - val_arr = arr; - } - value_array_t(const std::vector & arr) { - val_arr = arr; - } + static constexpr auto kind_id = value_kind::ARRAY; + std::vector val_arr; + + value_array_t() : value_t(kind_id) {} + value_array_t(value & v) : value_t(kind_id), val_arr(v->as_array()) {} + value_array_t(std::vector && arr) : value_t(kind_id), val_arr(std::move(arr)) {} + value_array_t(const std::vector & arr) : value_t(kind_id), val_arr(arr) {} void reverse() { if (is_immutable()) { throw std::runtime_error("Attempting to modify immutable type"); @@ -462,24 +505,27 @@ struct value_array_t : public value_t { return hash; } protected: + explicit value_array_t(value_kind kind) : value_t(kind) {} + virtual bool equivalent(const value_t & other) const override { - return typeid(*this) == typeid(other) && is_hashable() && other.is_hashable() && std::equal(val_arr.begin(), val_arr.end(), other.val_arr.begin(), other.val_arr.end(), value_equivalence()); + return kind == other.kind && is_hashable() && other.is_hashable() && std::equal(val_arr.begin(), val_arr.end(), other.as_array().begin(), other.as_array().end(), value_equivalence()); } }; using value_array = std::shared_ptr; struct value_tuple_t : public value_array_t { - value_tuple_t(value & v) { - val_arr = v->val_arr; + static constexpr auto kind_id = value_kind::TUPLE; + value_tuple_t(value & v) : value_array_t(kind_id) { + val_arr = v->as_array(); } - value_tuple_t(std::vector && arr) { - val_arr = arr; + value_tuple_t(std::vector && arr) : value_array_t(kind_id) { + val_arr = std::move(arr); } - value_tuple_t(const std::vector & arr) { + value_tuple_t(const std::vector & arr) : value_array_t(kind_id) { val_arr = arr; } - value_tuple_t(const std::pair & pair) { + value_tuple_t(const std::pair & pair) : value_array_t(kind_id) { val_arr.push_back(pair.first); val_arr.push_back(pair.second); } @@ -490,21 +536,23 @@ using value_tuple = std::shared_ptr; struct value_object_t : public value_t { - std::unordered_map unordered; + static constexpr auto kind_id = value_kind::OBJECT; + std::vector> val_obj; + std::unordered_map key_index; // key -> index in val_obj bool has_builtins = true; // context and loop objects do not have builtins - value_object_t() = default; - value_object_t(value & v) { - val_obj = v->val_obj; - for (const auto & pair : val_obj) { - unordered[pair.first] = pair.second; + value_object_t() : value_t(kind_id) {} + value_object_t(value & v) : value_t(kind_id) { + val_obj = v->as_ordered_object(); + for (size_t i = 0; i < val_obj.size(); i++) { + key_index[val_obj[i].first] = i; } } - value_object_t(const std::map & obj) { + value_object_t(const std::map & obj) : value_t(kind_id) { for (const auto & pair : obj) { insert(pair.first, pair.second); } } - value_object_t(const std::vector> & obj) { + value_object_t(const std::vector> & obj) : value_t(kind_id) { for (const auto & pair : obj) { insert(pair.first, pair.second); } @@ -527,45 +575,40 @@ struct value_object_t : public value_t { return ss.str(); } virtual bool as_bool() const override { - return !unordered.empty(); + return !val_obj.empty(); } virtual bool has_key(const value & key) override { if (!key->is_immutable() || !key->is_hashable()) { throw std::runtime_error("Object key of unhashable type: " + key->type()); } - return unordered.find(key) != unordered.end(); + return key_index.find(key) != key_index.end(); } virtual void insert(const value & key, const value & val) override { - bool replaced = false; if (is_immutable()) { throw std::runtime_error("Attempting to modify immutable type"); } - if (has_key(key)) { - // if key exists, replace value in ordered list instead of appending - for (auto & pair : val_obj) { - if (*(pair.first) == *key) { - pair.second = val; - replaced = true; - break; - } - } - } - unordered[key] = val; - if (!replaced) { + if (!key->is_immutable() || !key->is_hashable()) { + throw std::runtime_error("Object key of unhashable type: " + key->type()); + } + const auto entry = key_index.try_emplace(key, val_obj.size()); + if (entry.second) { val_obj.push_back({key, val}); + } else { + val_obj[entry.first->second].second = val; } } virtual value & at(const value & key, value & default_val) override { - if (!has_key(key)) { - return default_val; + if (!key->is_immutable() || !key->is_hashable()) { + throw std::runtime_error("Object key of unhashable type: " + key->type()); } - return unordered.at(key); + const auto found = key_index.find(key); + return found == key_index.end() ? default_val : val_obj[found->second].second; } virtual value & at(const value & key) override { if (!has_key(key)) { throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type()); } - return unordered.at(key); + return val_obj[key_index.at(key)].second; } virtual value & at(const std::string & key, value & default_val) override { value key_val = mk_val(key); @@ -599,7 +642,7 @@ struct value_object_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return typeid(*this) == typeid(other) && is_hashable() && other.is_hashable() && std::equal(val_obj.begin(), val_obj.end(), other.val_obj.begin(), other.val_obj.end(), value_equivalence()); + return kind == other.kind && is_hashable() && other.is_hashable() && std::equal(val_obj.begin(), val_obj.end(), other.as_ordered_object().begin(), other.as_ordered_object().end(), value_equivalence()); } }; using value_object = std::shared_ptr; @@ -609,6 +652,8 @@ using value_object = std::shared_ptr; // struct value_none_t : public value_t { + static constexpr auto kind_id = value_kind::NONE; + value_none_t() : value_t(kind_id) {} virtual std::string type() const override { return "None"; } virtual bool is_none() const override { return true; } virtual bool as_bool() const override { return false; } @@ -621,14 +666,15 @@ struct value_none_t : public value_t { } protected: virtual bool equivalent(const value_t & other) const override { - return typeid(*this) == typeid(other); + return kind == other.kind; } }; using value_none = std::shared_ptr; struct value_undefined_t : public value_t { + static constexpr auto kind_id = value_kind::UNDEFINED; std::string hint; // for debugging, to indicate where undefined came from - value_undefined_t(const std::string & h = "") : hint(h) {} + value_undefined_t(const std::string & h = "") : value_t(kind_id), hint(h) {} virtual std::string type() const override { return hint.empty() ? "Undefined" : "Undefined (hint: '" + hint + "')"; } virtual bool is_undefined() const override { return true; } virtual bool as_bool() const override { return false; } @@ -705,12 +751,14 @@ struct func_args { }; struct value_func_t : public value_t { + static constexpr auto kind_id = value_kind::FUNCTION; + func_handler val_func; std::string name; value arg0; // bound "this" argument, if any - value_func_t(const std::string & name, const func_handler & func) : name(name) { + value_func_t(const std::string & name, const func_handler & func) : value_t(kind_id), name(name) { val_func = func; } - value_func_t(const std::string & name, const func_handler & func, const value & arg_this) : name(name), arg0(arg_this) { + value_func_t(const std::string & name, const func_handler & func, const value & arg_this) : value_t(kind_id), name(name), arg0(arg_this) { val_func = func; } virtual value invoke(const func_args & args) const override { @@ -735,18 +783,22 @@ struct value_func_t : public value_t { // Note: this is unused for now, we don't support function as object keys // compare function pointers // (val_func == other.val_func does not work as std::function::operator== is only used for nullptr check) + if (kind != other.kind) { + return false; + } const auto target_this = this->val_func.target(); - const auto target_other = other.val_func.target(); - return typeid(*this) == typeid(other) && target_this == target_other; + const auto target_other = static_cast(other).val_func.target(); + return target_this == target_other; } }; using value_func = std::shared_ptr; // special value for kwarg struct value_kwarg_t : public value_t { + static constexpr auto kind_id = value_kind::KEYWORD; std::string key; value val; - value_kwarg_t(const std::string & k, const value & v) : key(k), val(v) {} + value_kwarg_t(const std::string & k, const value & v) : value_t(kind_id), key(k), val(v) {} virtual std::string type() const override { return "KwArg"; } virtual std::string as_repr() const override { return type(); } virtual bool is_hashable() const override { return true; } @@ -760,7 +812,7 @@ struct value_kwarg_t : public value_t { protected: virtual bool equivalent(const value_t & other) const override { const value_kwarg_t & other_val = static_cast(other); - return typeid(*this) == typeid(other) && key == other_val.key && val == other_val.val; + return kind == other.kind && key == other_val.key && val == other_val.val; } }; using value_kwarg = std::shared_ptr; diff --git a/common/parsers/gemma4.cpp b/common/parsers/gemma4.cpp index 5902e290bbc6..2a2e929e19a3 100644 --- a/common/parsers/gemma4.cpp +++ b/common/parsers/gemma4.cpp @@ -303,7 +303,8 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template & data.format = COMMON_CHAT_FORMAT_PEG_GEMMA4; data.supports_thinking = true; data.thinking_start_tag = "<|channel>thought"; - data.thinking_end_tags = {""}; + // a tool call may start before the thought channel is closed; stays first, the budget sampler forces it + data.thinking_end_tags = {"", "<|tool_call>"}; data.preserved_tokens = { "<|channel>", @@ -334,9 +335,10 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template & auto start = p.rule("start", p.optional(p.literal("<|turn>model\n"))); if (extract_reasoning) { - p.rule("thought", p.literal("<|channel>thought") + p.space() + p.reasoning(p.until("")) + p.literal("")); + // the model may start a tool call before closing the thought channel + p.rule("thought", p.literal("<|channel>thought") + p.space() + p.reasoning(p.until_one_of({"", "<|tool_call>"})) + (p.literal("") | p.peek(p.literal("<|tool_call>")))); } else { - p.rule("thought", p.content(p.literal("<|channel>thought") + p.space() + p.until("") + p.literal(""))); + p.rule("thought", p.content(p.literal("<|channel>thought") + p.space() + p.until_one_of({"", "<|tool_call>"}) + (p.literal("") | p.peek(p.literal("<|tool_call>"))))); } auto consume_empty_channels = p.gbnf(p.zero_or_more(p.literal("<|channel>") + p.negate(p.literal("thought"))), ""); diff --git a/common/parsers/inkling.cpp b/common/parsers/inkling.cpp new file mode 100644 index 000000000000..9c30cdb87962 --- /dev/null +++ b/common/parsers/inkling.cpp @@ -0,0 +1,165 @@ +#include "parsers.h" + +bool is_inkling_template(const std::string & src) { + return src.find("<|message_user|>") != std::string::npos && + src.find("<|content_image|>") != std::string::npos; +} + +// the template makes one message block per content part, but a media marker comes inside the text of a message +//
<|content_text|>{media}text<|end_message|> -->
{media}<|end_message|>
<|content_text|>text<|end_message|> +static void inkling_split_media(common_chat_prompt & prompt) { + const std::string TEXT = "<|content_text|>"; + const std::string END = "<|end_message|>"; + const std::string MEDIA_BEG = "<__media_"; + const std::string MEDIA_END = "__>"; + + std::vector out; + for (size_t i = 0; i < prompt.parts.size(); i++) { + const auto & part = prompt.parts[i]; + const bool in_text_block = part.is_input && part.text.find(MEDIA_BEG) != std::string::npos && + !out.empty() && !out.back().is_input && string_ends_with(out.back().text, TEXT) && + i + 1 < prompt.parts.size() && !prompt.parts[i + 1].is_input && string_starts_with(prompt.parts[i + 1].text, END); + const size_t header_pos = in_text_block ? out.back().text.rfind("<|message_") : std::string::npos; + if (header_pos == std::string::npos) { + out.push_back(part); + continue; + } + const std::string header = out.back().text.substr(header_pos, out.back().text.size() - TEXT.size() - header_pos); + + std::string rest = part.text; + for (bool first = true; !rest.empty(); first = false) { + const size_t beg = rest.find(MEDIA_BEG); + const size_t end = beg == std::string::npos ? beg : rest.find(MEDIA_END, beg); + const bool is_media = beg == 0 && end != std::string::npos; + const size_t len = is_media ? end + MEDIA_END.size() : (end == std::string::npos ? rest.size() : beg); + if (!first) { + out.push_back({ END + header + (is_media ? "" : TEXT), false }); + } else if (is_media) { + // mtmd opens the media block + out.back().text.resize(out.back().text.size() - TEXT.size()); + } + out.push_back({ rest.substr(0, len), true }); + rest.erase(0, len); + } + } + prompt.parts = std::move(out); +} + +// Inkling 1 and 2 - the assistant turn is a list of blocks, all closed by <|end_message|>: +// <|message_model|><|content_thinking|>...<|end_message|> +// <|message_model|><|content_text|>...<|end_message|> +// <|message_model|>NAME<|content_invoke_tool_json|>{"name":"NAME","args":{...}}<|end_message|> +common_chat_params common_chat_params_init_inkling(const common_chat_template & tmpl, + const autoparser::generation_params & inputs) { + common_chat_params data; + + data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs); + data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs); + data.format = COMMON_CHAT_FORMAT_PEG_NATIVE; + data.supports_thinking = true; + + inkling_split_media(data.prompt); + + const std::string HEADER = "<|message_model|>"; + const std::string THINK = "<|content_thinking|>"; + const std::string TEXT = "<|content_text|>"; + const std::string TOOL_JSON = "<|content_invoke_tool_json|>"; + const std::string END = "<|end_message|>"; + + data.preserved_tokens = { HEADER, THINK, TEXT, TOOL_JSON, END }; + + data.thinking_start_tag = THINK; + data.thinking_end_tags = { END }; + + data.message_delimiters = { + { COMMON_CHAT_ROLE_ASSISTANT, HEADER }, + { COMMON_CHAT_ROLE_USER, "<|message_user|>" }, + { COMMON_CHAT_ROLE_SYSTEM, "<|message_system|>" }, + { COMMON_CHAT_ROLE_TOOL, "<|message_tool|>" }, + }; + + if (inputs.has_continuation()) { + const auto & msg = inputs.continue_msg; + + data.generation_prompt.clear(); + if (!msg.reasoning_content.empty()) { + data.generation_prompt = HEADER + THINK + msg.reasoning_content; + } + if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) { + if (!data.generation_prompt.empty()) { + data.generation_prompt += END; + } + data.generation_prompt += HEADER + TEXT + msg.render_content(); + } + + data.prompt.append(data.generation_prompt); + } + + auto has_tools = inputs.tools.is_array() && !inputs.tools.empty(); + auto has_response_format = !inputs.json_schema.is_null() && inputs.json_schema.is_object(); + auto use_tools = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE; + auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; + + data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { + auto header = p.literal(HEADER); + auto end = p.literal(END); + + auto think = p.literal(THINK); + auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(END)) + end : + p.atomic(p.content(think)) + p.content(p.until(END) + end)); + auto text = p.rule("text", p.literal(TEXT) + p.content(p.until(END)) + end); + + if (has_response_format) { + auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema))); + return p.zero_or_more(header + thinking) + header + p.literal(TEXT) + response_format + end; + } + + auto blocks = p.zero_or_more(header + (thinking | text)); + + if (!use_tools) { + return blocks; + } + + auto tool_choice = p.choice(); + foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { + const auto & function = tool.at("function"); + std::string name = function.at("name"); + + auto open = p.tool_name(p.literal(name)) + p.literal(TOOL_JSON) + p.literal("{\"name\":" + json(name).dump() + ",\"args\":"); + auto args = p.tool_args(p.json()); + + tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.tool_open(open) + args + p.tool_close(p.literal("}")) + end)); + }); + + // tool calls are the last blocks of the turn + auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice; + auto tool_calls = header + p.trigger_rule("tool-calls", calls); + + if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { + return blocks + tool_calls; + } + + return blocks + p.optional(tool_calls); + }); + + if (has_response_format || use_tools) { + data.grammar_lazy = !has_response_format && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED; + data.grammar = build_grammar([&](const common_grammar_builder & builder) { + data.parser.build_grammar(builder, data.grammar_lazy); + }); + + if (data.grammar_lazy) { + // a header followed by text and not by a content token is a tool call, the grammar starts at the name + data.grammar_triggers = { + { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" }, + }; + // Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt. + // an output that starts with no content token is a tool call. not for a continuation, it starts with text + if (!inputs.has_continuation()) { + data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL, "[^<]+" }); + } + } + } + + return data; +} diff --git a/common/parsers/k2-horizon.cpp b/common/parsers/k2-horizon.cpp index 1afd578c83eb..e688cd919382 100644 --- a/common/parsers/k2-horizon.cpp +++ b/common/parsers/k2-horizon.cpp @@ -48,6 +48,11 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template data.thinking_start_tag = THINK_START; data.thinking_end_tags = { THINK_END }; + // The models sometimes close medium/low reasoning with the generic + if (think != "ifm|think") { + data.thinking_end_tags.push_back(""); + } + data.preserved_tokens = data.thinking_end_tags; data.preserved_tokens.insert(data.preserved_tokens.end(), { THINK_START, SECTION_START, SECTION_END, CALL_START, CALL_END, diff --git a/common/parsers/lfm2.cpp b/common/parsers/lfm2.cpp index 1bb1e672879e..3ecd9573d82c 100644 --- a/common/parsers/lfm2.cpp +++ b/common/parsers/lfm2.cpp @@ -83,7 +83,8 @@ common_chat_params common_chat_params_init_lfm2(const common_chat_template & auto tool_calls = p.rule("tool-calls", p.trigger_rule("tool-call", p.literal(TOOL_CALL_START) + - p.python_style_tool_calls(inputs.tools, inputs.parallel_tool_calls, /* allow_json_literals = */ true) + + p.python_style_tool_calls(inputs.tools, inputs.parallel_tool_calls, /* allow_json_literals = */ true, + /* allow_undeclared = */ true) + p.literal(TOOL_CALL_END) ) ); diff --git a/common/parsers/ministral3.cpp b/common/parsers/ministral3.cpp index c865a3cae40a..9a37d0299845 100644 --- a/common/parsers/ministral3.cpp +++ b/common/parsers/ministral3.cpp @@ -50,7 +50,7 @@ common_chat_params common_chat_params_init_ministral_3(const common_chat_templat data.supports_thinking = true; data.thinking_start_tag = "[THINK]"; - data.thinking_end_tags = {"[/THINK]"}; + data.thinking_end_tags = {"[/THINK]", "[TOOL_CALLS]"}; data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs, /* messages_override = */ adjusted_messages); data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, /* messages_override = */ adjusted_messages); data.format = COMMON_CHAT_FORMAT_PEG_NATIVE; @@ -75,7 +75,7 @@ common_chat_params common_chat_params_init_ministral_3(const common_chat_templat data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { auto generation_prompt = p.eps(); auto reasoning = - extract_reasoning ? p.optional("[THINK]" + p.reasoning(p.until("[/THINK]")) + "[/THINK]") : p.eps(); + extract_reasoning ? p.optional("[THINK]" + p.reasoning(p.until_one_of({"[/THINK]", "[TOOL_CALLS]"})) + p.choice({p.literal("[/THINK]"), p.peek(p.literal("[TOOL_CALLS]"))})) : p.eps(); // Response format parser if (has_response_format) { diff --git a/common/parsers/parsers.h b/common/parsers/parsers.h index b1b6d166a124..867403370968 100644 --- a/common/parsers/parsers.h +++ b/common/parsers/parsers.h @@ -41,6 +41,8 @@ std::string common_chat_template_generation_prompt_impl( bool is_lfm2_template(const std::string & src); +bool is_inkling_template(const std::string & src); + common_chat_params common_chat_params_init_cohere2moe(const common_chat_template & tmpl, const autoparser::generation_params & inputs); common_chat_params common_chat_params_init_deepseek_v3_2(const common_chat_template & tmpl, const autoparser::generation_params & inputs); @@ -55,6 +57,8 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template & common_chat_params common_chat_params_init_harmony_xml(const common_chat_template & tmpl, const autoparser::generation_params & inputs); +common_chat_params common_chat_params_init_inkling(const common_chat_template & tmpl, const autoparser::generation_params & inputs); + common_chat_params common_chat_params_init_k2_horizon(const common_chat_template & tmpl, const autoparser::generation_params & inputs); common_chat_params common_chat_params_init_kimi_k2(const common_chat_template & tmpl, const autoparser::generation_params & inputs); diff --git a/common/parsers/sources.cmake b/common/parsers/sources.cmake index 2174f4519a64..934e22673e89 100644 --- a/common/parsers/sources.cmake +++ b/common/parsers/sources.cmake @@ -10,6 +10,7 @@ set(LLAMA_CHAT_PARSERS_SOURCES ${CMAKE_CURRENT_LIST_DIR}/gigachat-v3.cpp ${CMAKE_CURRENT_LIST_DIR}/gpt-oss.cpp ${CMAKE_CURRENT_LIST_DIR}/harmony-xml.cpp + ${CMAKE_CURRENT_LIST_DIR}/inkling.cpp ${CMAKE_CURRENT_LIST_DIR}/k2-horizon.cpp ${CMAKE_CURRENT_LIST_DIR}/kimi-k2.cpp ${CMAKE_CURRENT_LIST_DIR}/kimi-k3.cpp diff --git a/common/peg-parser.cpp b/common/peg-parser.cpp index e2ccb77bb14f..d980cfc76dca 100644 --- a/common/peg-parser.cpp +++ b/common/peg-parser.cpp @@ -1003,9 +1003,9 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id } else if constexpr (std::is_same_v) { return "Ref(" + p.name + ")"; } else if constexpr (std::is_same_v) { - return "Tag(" + p.tag + ", " + dump(p.child) + ")"; + return "Tag(" + p.tag + ", " + dump_impl(p.child, visited) + ")"; } else if constexpr (std::is_same_v) { - return "Atomic(" + dump(p.child) + ")"; + return "Atomic(" + dump_impl(p.child, visited) + ")"; } else { return "Unknown"; } diff --git a/common/sampling.cpp b/common/sampling.cpp index 564fa9c4dbf4..078bfd984f42 100644 --- a/common/sampling.cpp +++ b/common/sampling.cpp @@ -203,6 +203,13 @@ struct common_sampler * common_sampler_init( throw std::invalid_argument("penalty_present must be finite"); } const llama_vocab * vocab = llama_model_get_vocab(model); + if (!common_grammar_value(params.grammar).empty()) { + for (const auto & b : params.logit_bias) { + if (b.bias == -INFINITY && llama_vocab_is_eog(vocab, b.token)) { + throw std::invalid_argument("EOG tokens cannot be banned when a grammar is set"); + } + } + } llama_sampler_chain_params lparams = llama_sampler_chain_default_params(); lparams.no_perf = params.no_perf; @@ -255,7 +262,8 @@ struct common_sampler * common_sampler_init( break; } default: - GGML_ASSERT(false && "unknown trigger type"); + throw std::runtime_error( + "unknown grammar trigger type: " + std::to_string(trigger.type)); } } diff --git a/common/speculative.cpp b/common/speculative.cpp index a7bd221127a3..b40eb5535f73 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -70,17 +70,19 @@ static void spec_retune( } const std::map common_speculative_type_from_name_map = { - {"none", COMMON_SPECULATIVE_TYPE_NONE}, - {"draft-simple", COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE}, - {"draft-eagle3", COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3}, - {"draft-mtp", COMMON_SPECULATIVE_TYPE_DRAFT_MTP}, - {"draft-dflash", COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH}, - {"draft-dspark", COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK}, - {"ngram-simple", COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE}, - {"ngram-map-k", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K}, - {"ngram-map-k4v", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V}, - {"ngram-mod", COMMON_SPECULATIVE_TYPE_NGRAM_MOD}, - {"ngram-cache", COMMON_SPECULATIVE_TYPE_NGRAM_CACHE} + {"none", COMMON_SPECULATIVE_TYPE_NONE}, + {"draft-simple", COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE}, + {"draft-eagle3", COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3}, + {"draft-mtp", COMMON_SPECULATIVE_TYPE_DRAFT_MTP}, + {"draft-dflash", COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH}, + {"draft-dspark", COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK}, + {"draft-dflash2", COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2}, + {"draft-lilicorr", COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR}, + {"ngram-simple", COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE}, + {"ngram-map-k", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K}, + {"ngram-map-k4v", COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V}, + {"ngram-mod", COMMON_SPECULATIVE_TYPE_NGRAM_MOD}, + {"ngram-cache", COMMON_SPECULATIVE_TYPE_NGRAM_CACHE} }; static std::string common_speculative_get_devices_str(const std::vector & devices) { @@ -999,26 +1001,6 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { int32_t block_size = 0; llama_token mask_token_id = 0; - bool is_lilicorr = false; - int32_t lilicorr_top_k = 0; - size_t lilicorr_rows = 0; - std::vector lilicorr_embd; - std::vector lilicorr_pos; - - bool is_dflash2 = false; - bool is_mrope = false; - int32_t selector_top_k = 0; - - // DFlash2 probabilistic drafting: one generator per sequence and the seed it was last seeded with (-1: reseed) - std::vector dflash2_rng; - std::vector dflash2_seed; - - // draft-dspark: the draft carries a Markov head and uses an anchor-first block layout - const bool is_dspark; - - // dspark speculators - bool sample_from_anchor = true; - // block-internal attention bool causal_attn = false; @@ -1028,11 +1010,31 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { // inject target features from the target's device buffer instead of host copies (env LLAMA_DFLASH_DEV=0 disables) bool use_dev_features = false; + common_speculative_impl_draft_dflash(const common_params_speculative & params, uint32_t n_seq) + : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH) + { + // DFlash input is [id_last, * (block_size-1)]: in-place denoising yields at most block_size-1 draft tokens + init({ + /* .n_draft_max = */ block_size - 1, + /* .backend_sampling = */ true, + /* .dev_features = */ true, + /* .nextn_masked = */ true, + }); + } + +protected: + // what init() sets up, per draft type + struct dflash_options { + int32_t n_draft_max; // longest draft a block yields, n_max and n_min are clamped to it + bool backend_sampling; // the block logits can be sampled on the backend + bool dev_features; // the target features can come from the target's device buffer + bool nextn_masked; // h_nextn is only read at the output rows + }; + common_speculative_impl_draft_dflash(const common_params_speculative & params, uint32_t n_seq, - common_speculative_type type = COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH) + common_speculative_type type) : common_speculative_impl(type, n_seq, params.draft.n_max) , params(params.draft) - , is_dspark(type == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) { auto * ctx_tgt = this->params.ctx_tgt; auto * ctx_dft = this->params.ctx_dft; @@ -1056,48 +1058,26 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { if (llama_model_meta_val_str(model_dft, "dflash.block_size", buf, sizeof(buf)) >= 0) { block_size = std::atoi(buf); } - if (llama_model_meta_val_str(model_dft, "dflash.sample_from_anchor", buf, sizeof(buf)) >= 0) { - sample_from_anchor = std::strcmp(buf, "true") == 0; - } if (llama_model_meta_val_str(model_dft, "dflash.attention.causal", buf, sizeof(buf)) >= 0) { causal_attn = std::strcmp(buf, "true") == 0; } } - selector_top_k = llama_model_dflash_selector_top_k(model_dft); - is_dflash2 = selector_top_k > 0; - dflash2_rng.resize(n_seq); - dflash2_seed.assign(n_seq, -1); - char lilicorr_meta[32] = {}; - lilicorr_top_k = llama_model_meta_val_str(model_dft, "lilicorr.candidate_topk", lilicorr_meta, sizeof(lilicorr_meta)) >= 0 - ? std::atoi(lilicorr_meta) : 0; - is_lilicorr = lilicorr_top_k > 0; - if (is_lilicorr) { - lilicorr_rows = (size_t) block_size + 1; - const size_t lilicorr_slots = (size_t) n_seq * lilicorr_rows; - lilicorr_embd.resize(lilicorr_slots * (size_t) n_embd_dec); - lilicorr_pos.assign(lilicorr_slots, -1); - } mask_token_id = llama_vocab_mask(llama_model_get_vocab(model_dft)); - if (is_dspark && this->params.p_min > 0.0f) { - char buf[16] = {}; - const bool has_conf = - llama_model_meta_val_str(model_dft, "dflash.has_confidence_head", buf, sizeof(buf)) < 0 || - std::strcmp(buf, "true") == 0; - if (!has_conf) { - throw std::runtime_error("DSpark draft has no confidence head: please set --spec-draft-p-min 0"); - } - } - LOG_INF("%s: adding speculative implementation '%s'\n", __func__, common_speculative_type_to_str(type).c_str()); LOG_INF("%s: - n_max=%d, n_min=%d, p_min=%.2f\n", __func__, this->params.n_max, this->params.n_min, this->params.p_min); - LOG_INF("%s: - block_size=%d, mask_token_id=%d, n_extract=%u, sample_from_anchor=%s\n", __func__, - block_size, mask_token_id, target_layer_ids_n, sample_from_anchor ? "true" : "false"); + LOG_INF("%s: - block_size=%d, mask_token_id=%d, n_extract=%u\n", __func__, + block_size, mask_token_id, target_layer_ids_n); + } + + void init(const dflash_options & opt) { + auto * ctx_tgt = this->params.ctx_tgt; + auto * ctx_dft = this->params.ctx_dft; - // DFlash input is [id_last, * (block_size-1)]: in-place denoising yields at most - // block_size-1 draft tokens, anchor-first DSpark yields a full block_size draft tokens - const int32_t n_draft_max = is_dspark && sample_from_anchor ? block_size : block_size - 1; + const llama_model * model_dft = llama_get_model(ctx_dft); + + const int32_t n_draft_max = opt.n_draft_max; if (this->params.n_max > n_draft_max || this->params.n_min > n_draft_max) { LOG_WRN("%s: requested draft size (n_max=%d, n_min=%d) exceeds the trained block size %d -- clamping to %d\n", __func__, this->params.n_max, this->params.n_min, block_size, n_draft_max); @@ -1109,9 +1089,6 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { batch = common_batch(ctx_dft); batch_inject = common_batch(ctx_dft); - // embd batches on an M-RoPE draft carry 4 position rows per token - is_mrope = llama_model_rope_type(model_dft) == LLAMA_ROPE_TYPE_MROPE; - smpls.resize(n_seq); for (auto & s : smpls) { common_params_sampling sparams; @@ -1123,7 +1100,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { // offload draft sampling to the backend backend_chains.assign(n_seq, nullptr); - if (this->params.backend_sampling && !is_dflash2 && !is_lilicorr) { + if (this->params.backend_sampling && opt.backend_sampling) { for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { llama_sampler * chain = llama_sampler_chain_init(llama_sampler_chain_default_params()); llama_sampler_chain_add(chain, llama_sampler_init_top_k(10)); @@ -1148,7 +1125,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { const bool ascending = std::adjacent_find(target_layer_ids, target_layer_ids + target_layer_ids_n, [](int32_t a, int32_t b) { return a >= b; }) == target_layer_ids + target_layer_ids_n; - use_dev_features = !is_lilicorr && ascending && (env == nullptr || atoi(env) != 0); + use_dev_features = opt.dev_features && ascending && (env == nullptr || atoi(env) != 0); if (use_dev_features) { llama_set_embeddings_layer_inp_dev(ctx_tgt, true); use_dev_features = llama_supports_embd_row(ctx_dft); @@ -1159,11 +1136,15 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { LOG_INF("%s: DFlash target features via %s\n", __func__, use_dev_features ? "device buffer" : "host copies"); } - // DFlash2 reads its selector lattice from h_nextn and never consumes raw logits. - llama_set_embeddings_nextn(ctx_dft, true, /*masked*/ !is_dflash2 && !is_lilicorr); + llama_set_embeddings_nextn(ctx_dft, true, opt.nextn_masked); llama_set_causal_attn(ctx_dft, causal_attn); // DFlash needs non-causal attention unless the model says otherwise } + // only LiliCorr uses this, to keep the context features for its scorer; the other heads only need the KV cache + // called after the host copy injection of a chunk, while h_nextn still holds the context features of batch_inject + virtual void store_context_features(llama_seq_id /*seq_id*/, int32_t /*n_chunk*/) {} + +public: ~common_speculative_impl_draft_dflash() override { auto * ctx_dft = this->params.ctx_dft; for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) backend_chains.size(); ++seq_id) { @@ -1183,9 +1164,6 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { return; } - // reseed per request rather than per round, or two identical requests differ - dflash2_seed[seq_id] = -1; - const int32_t N = (int32_t) prompt.size(); if (N <= 0) { return; @@ -1297,24 +1275,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { __func__, rc, (int) n_chunk, (int) offset); return false; } - if (is_lilicorr) { - // Ordinary DFlash can write to the KV cache, but LiliCorr needs to store embeddings across sequences. - const float * projected = llama_get_embeddings_nextn(ctx_dft); - if (projected) { - const size_t seq_offset = (size_t) seq_id * lilicorr_rows; - const llama_pos pos_min = std::max(0, batch_inject.tokens.back().pos[0] - block_size); - for (int32_t i = 0; i < n_chunk; ++i) { - const llama_pos pos = batch_inject.tokens[i].pos[0]; - if (pos < pos_min) { - continue; - } - const size_t slot = seq_offset + (size_t) pos % lilicorr_rows; - std::memcpy(lilicorr_embd.data() + slot * (size_t) n_embd_dec, - projected + (size_t) i * n_embd_dec, (size_t) n_embd_dec * sizeof(float)); - lilicorr_pos[slot] = pos; - } - } - } + store_context_features(seq_id, n_chunk); } } @@ -1326,7 +1287,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { batch.clear(); - // build one batch holding every drafting sequence's noise block into a single decode) + // build one batch holding every drafting sequence's noise block into a single decode // record where each block starts and its size std::vector i_block_beg(n_seq, -1); std::vector n_block (n_seq, 0); @@ -1342,17 +1303,136 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { const int32_t n = (int32_t) dp.pos0; const int32_t n_draft = params.n_max; - const int32_t n_block_tokens = is_lilicorr ? block_size : n_draft + (is_dspark && sample_from_anchor ? 0 : 1); + const int32_t n_block_tokens = n_draft + 1; i_block_beg[seq_id] = batch.size(); n_block [seq_id] = n_block_tokens; for (int32_t i = 0; i < n_block_tokens; ++i) { - const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, !is_dflash2 && !is_lilicorr); - if (is_lilicorr) { - // For LiliCorr drafting batch, set state embeddings for use in the associated transformer head. - const llama_pos pos = dp.pos0 - 1; - const size_t slot = (size_t) seq_id * lilicorr_rows + (size_t) pos % lilicorr_rows; - batch.set_embd_state(idx, { lilicorr_embd.data() + slot * (size_t) n_embd_dec, 1, (size_t) n_embd_dec }); + batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true); + } + } + + if (batch.size() == 0) { + return; + } + + // decode all sequence's noise block in a single batch + int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + if (ret != 0) { + LOG_WRN("%s: llama_process returned %d\n", __func__, ret); + return; + } + + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_block_beg[seq_id] < 0) { + continue; + } + auto & dp = dparams[seq_id]; + + const int32_t beg = i_block_beg[seq_id]; + const int32_t n_block_tokens = n_block[seq_id]; + + auto * smpl = smpls[seq_id].get(); + + auto & result = *dp.result; + + // greedily read the predicted block at this sequence's noise positions 1..n_block_tokens-1 + for (int32_t i = 1; i < n_block_tokens; ++i) { + common_sampler_sample(smpl, ctx_dft, beg + i, true); + + const auto * cur_p = common_sampler_get_candidates(smpl, true); + + for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { + LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", + seq_id, k, i - 1, cur_p->data[k].id, cur_p->data[k].p, + common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); } + + const llama_token id = cur_p->data[0].id; + + if (cur_p->data[0].p < params.p_min) { + break; + } + + common_sampler_accept(smpl, id, true); + + result.push_back(id); + } + + if (result.size() < (size_t) params.n_min) { + result.clear(); + } + } + } + + void accept(llama_seq_id /*seq_id*/, uint16_t /*n_accepted*/, bool /*is_other*/) override { + // noop + } +}; + +// DSpark: a semi-autoregressive Markov head (+ Confidence head) on the block, anchor-first block layout +struct common_speculative_impl_draft_dspark final : public common_speculative_impl_draft_dflash { + // bonus anchor (SpecForge exports) when false: slot 0 is a bonus token, not a prediction slot + bool sample_from_anchor = true; + + common_speculative_impl_draft_dspark(const common_params_speculative & params, uint32_t n_seq) + : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) + { + const llama_model * model_dft = llama_get_model(this->params.ctx_dft); + + { + char buf[32] = {}; + if (llama_model_meta_val_str(model_dft, "dflash.sample_from_anchor", buf, sizeof(buf)) >= 0) { + sample_from_anchor = std::strcmp(buf, "true") == 0; + } + } + + if (this->params.p_min > 0.0f) { + char buf[16] = {}; + const bool has_conf = + llama_model_meta_val_str(model_dft, "dflash.has_confidence_head", buf, sizeof(buf)) < 0 || + std::strcmp(buf, "true") == 0; + if (!has_conf) { + throw std::runtime_error("DSpark draft has no confidence head: please set --spec-draft-p-min 0"); + } + } + + LOG_INF("%s: - sample_from_anchor=%s\n", __func__, sample_from_anchor ? "true" : "false"); + + // anchor-first DSpark yields a full block_size draft tokens + init({ + /* .n_draft_max = */ sample_from_anchor ? block_size : block_size - 1, + /* .backend_sampling = */ true, + /* .dev_features = */ true, + /* .nextn_masked = */ true, + }); + } + + void draft(common_speculative_draft_params_vec & dparams) override { + auto & ctx_dft = params.ctx_dft; + + batch.clear(); + + // build one batch holding every drafting sequence's noise block into a single decode + // record where each block starts and its size + std::vector i_block_beg(n_seq, -1); + std::vector n_block (n_seq, 0); + + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + auto & dp = dparams[seq_id]; + if (!dp.drafting) { + continue; + } + + common_sampler_reset(smpls[seq_id].get()); + + const int32_t n = (int32_t) dp.pos0; + + const int32_t n_draft = params.n_max; + const int32_t n_block_tokens = n_draft + (sample_from_anchor ? 0 : 1); + i_block_beg[seq_id] = batch.size(); + n_block [seq_id] = n_block_tokens; + for (int32_t i = 0; i < n_block_tokens; ++i) { + batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true); } } @@ -1380,136 +1460,327 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { auto & result = *dp.result; - if (is_dflash2 || is_lilicorr) { - // Both DFlash and LiliCorr greedily walk the candidate lattice. - const float * lattice = llama_get_embeddings_nextn(ctx_dft); - GGML_ASSERT(lattice && "DFlash2 selector produced no lattice"); + // DSpark: read from the first draft slot, truncate below the confidence threshold + const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr; + // bonus-anchor drafts read the mask positions only, like DFlash + const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; + for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) { + const int32_t idx = beg + i; - // DFlash2 can instead sample each step and hand q to the verifier for rejection sampling - const bool sample = is_dflash2 && params.probabilistic && dp.result_q; + if (conf && conf[(size_t) idx * n_embd_dec] < params.p_min) { + break; + } - // greedy keeps temperature 1, sampling uses the target's - const float temp = sample ? dp.temp : 1.0f; + common_sampler_sample(smpl, ctx_dft, idx, true); - if (sample && dflash2_seed[seq_id] != dp.seed) { - dflash2_seed[seq_id] = dp.seed; - // the default seed means random; mixed so it differs from the target's, as in spec_retune - dflash2_rng[seq_id].seed(dp.seed == LLAMA_DEFAULT_SEED ? std::random_device{}() : dp.seed ^ 0x85ebca6bu); + const auto * cur_p = common_sampler_get_candidates(smpl, true); + + for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { + LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", + seq_id, k, i, cur_p->data[k].id, cur_p->data[k].p, + common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); } - std::vector probs; - std::vector sorted_idx; - - int32_t predecessor = 0; - for (int32_t i = 1; i < (is_dflash2 ? n_block_tokens : params.n_max + 1); ++i) { - const float * row = lattice + (size_t) (beg + i) * n_embd_dec; - const int32_t top_k = is_dflash2 ? selector_top_k : lilicorr_top_k; - const float * scores = row + top_k + (size_t) predecessor * top_k; - - predecessor = (int32_t) std::distance(scores, - std::max_element(scores, scores + top_k)); - if (params.p_min > 0.0f || sample) { - // softmax(scores / temp) at the argmax, i.e. 1 / sum(exp((s_k - s_max) / temp)) - probs.resize(top_k); - float sum = 0.0f; - for (int32_t k = 0; k < top_k; ++k) { - probs[k] = std::exp((scores[k] - scores[predecessor]) / temp); - sum += probs[k]; - } - if (1.0f / sum < params.p_min) { + const llama_token id = cur_p->data[0].id; + + common_sampler_accept(smpl, id, true); + + result.push_back(id); + } + + if (result.size() < (size_t) params.n_min) { + result.clear(); + } + } + } +}; + +// DFlash2: walks the lattice of the selector over the top-k candidates of the block +struct common_speculative_impl_draft_dflash2 final : public common_speculative_impl_draft_dflash { + int32_t selector_top_k = 0; + + // probabilistic drafting: one generator per sequence and the seed it was last seeded with (-1: reseed) + std::vector dflash2_rng; + std::vector dflash2_seed; + + common_speculative_impl_draft_dflash2(const common_params_speculative & params, uint32_t n_seq) + : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2) + { + selector_top_k = llama_model_dflash_selector_top_k(llama_get_model(this->params.ctx_dft)); + dflash2_rng.resize(n_seq); + dflash2_seed.assign(n_seq, -1); + + // DFlash2 reads its selector lattice from h_nextn and never consumes raw logits + init({ + /* .n_draft_max = */ block_size - 1, + /* .backend_sampling = */ false, + /* .dev_features = */ true, + /* .nextn_masked = */ false, + }); + } + + void begin(llama_seq_id seq_id, const llama_tokens & prompt) override { + if (seq_id >= 0 && seq_id < (llama_seq_id) n_seq) { + // reseed per request rather than per round, or two identical requests differ + dflash2_seed[seq_id] = -1; + } + + common_speculative_impl_draft_dflash::begin(seq_id, prompt); + } + + void draft(common_speculative_draft_params_vec & dparams) override { + auto & ctx_dft = params.ctx_dft; + + batch.clear(); + + // build one batch holding every drafting sequence's noise block into a single decode + // record where each block starts and its size + std::vector i_block_beg(n_seq, -1); + std::vector n_block (n_seq, 0); + + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + auto & dp = dparams[seq_id]; + if (!dp.drafting) { + continue; + } + + common_sampler_reset(smpls[seq_id].get()); + + const int32_t n = (int32_t) dp.pos0; + + const int32_t n_draft = params.n_max; + const int32_t n_block_tokens = n_draft + 1; + i_block_beg[seq_id] = batch.size(); + n_block [seq_id] = n_block_tokens; + for (int32_t i = 0; i < n_block_tokens; ++i) { + batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, false); + } + } + + if (batch.size() == 0) { + return; + } + + // decode all sequence's noise block in a single batch + int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + if (ret != 0) { + LOG_WRN("%s: llama_process returned %d\n", __func__, ret); + return; + } + + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_block_beg[seq_id] < 0) { + continue; + } + auto & dp = dparams[seq_id]; + + const int32_t beg = i_block_beg[seq_id]; + const int32_t n_block_tokens = n_block[seq_id]; + + auto & result = *dp.result; + + const float * lattice = llama_get_embeddings_nextn(ctx_dft); + GGML_ASSERT(lattice && "DFlash2 selector produced no lattice"); + + // DFlash2 can instead sample each step and hand q to the verifier for rejection sampling + const bool sample = params.probabilistic && dp.result_q; + + // greedy keeps temperature 1, sampling uses the target's + const float temp = sample ? dp.temp : 1.0f; + + if (sample && dflash2_seed[seq_id] != dp.seed) { + dflash2_seed[seq_id] = dp.seed; + // the default seed means random; mixed so it differs from the target's, as in spec_retune + dflash2_rng[seq_id].seed(dp.seed == LLAMA_DEFAULT_SEED ? std::random_device{}() : dp.seed ^ 0x85ebca6bu); + } + + std::vector probs; + std::vector sorted_idx; + + int32_t predecessor = 0; + for (int32_t i = 1; i < n_block_tokens; ++i) { + const float * row = lattice + (size_t) (beg + i) * n_embd_dec; + const int32_t top_k = selector_top_k; + const float * scores = row + top_k + (size_t) predecessor * top_k; + + predecessor = (int32_t) std::distance(scores, + std::max_element(scores, scores + top_k)); + if (params.p_min > 0.0f || sample) { + // softmax(scores / temp) at the argmax, i.e. 1 / sum(exp((s_k - s_max) / temp)) + probs.resize(top_k); + float sum = 0.0f; + for (int32_t k = 0; k < top_k; ++k) { + probs[k] = std::exp((scores[k] - scores[predecessor]) / temp); + sum += probs[k]; + } + if (1.0f / sum < params.p_min) { + break; + } + for (int32_t k = 0; k < top_k; ++k) { + probs[k] /= sum; + } + } + if (sample) { + // ggml_top_k leaves candidates unordered, so walk them by token id to keep a seed's draft stable + sorted_idx.resize(top_k); + for (int32_t k = 0; k < top_k; ++k) { + sorted_idx[k] = k; + } + std::sort(sorted_idx.begin(), sorted_idx.end(), [row](int32_t a, int32_t b) { return row[a] < row[b]; }); + + // a round-off overshoot keeps the argmax, which has q > 0 + double u = std::uniform_real_distribution(0.0, 1.0)(dflash2_rng[seq_id]); + for (const int32_t k : sorted_idx) { + u -= probs[k]; + if (u < 0.0) { + predecessor = k; break; } - for (int32_t k = 0; k < top_k; ++k) { - probs[k] /= sum; - } } - if (sample) { - // ggml_top_k leaves candidates unordered, so walk them by token id to keep a seed's draft stable - sorted_idx.resize(top_k); - for (int32_t k = 0; k < top_k; ++k) { - sorted_idx[k] = k; - } - std::sort(sorted_idx.begin(), sorted_idx.end(), [row](int32_t a, int32_t b) { return row[a] < row[b]; }); - - // a round-off overshoot keeps the argmax, which has q > 0 - double u = std::uniform_real_distribution(0.0, 1.0)(dflash2_rng[seq_id]); - for (const int32_t k : sorted_idx) { - u -= probs[k]; - if (u < 0.0) { - predecessor = k; - break; - } - } - auto & q = dp.result_q->emplace_back(); - q.reserve(top_k); - for (int32_t k = 0; k < top_k; ++k) { - q.push_back({ (llama_token) row[k], scores[k], probs[k] }); - } + auto & q = dp.result_q->emplace_back(); + q.reserve(top_k); + for (int32_t k = 0; k < top_k; ++k) { + q.push_back({ (llama_token) row[k], scores[k], probs[k] }); } - result.push_back((llama_token) row[predecessor]); } + result.push_back((llama_token) row[predecessor]); + } - if (result.size() < (size_t) params.n_min) { - result.clear(); - if (sample) { - dp.result_q->clear(); - } + if (result.size() < (size_t) params.n_min) { + result.clear(); + if (sample) { + dp.result_q->clear(); } - continue; } + } + } +}; - if (is_dspark) { - // DSpark: read from the first draft slot, truncate below the confidence threshold - const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr; - // bonus-anchor drafts read the mask positions only, like DFlash - const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; - for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) { - const int32_t idx = beg + i; +// LiliCorr: walks the lattice of the scorer over the top-k candidates of the block, which reads the +// context features of the anchor; they come back from the injection and are kept per sequence +struct common_speculative_impl_draft_lilicorr final : public common_speculative_impl_draft_dflash { + int32_t lilicorr_top_k = 0; - if (conf && conf[(size_t) idx * n_embd_dec] < params.p_min) { - break; - } + // context features of the last lilicorr_rows positions of each sequence, indexed by position + size_t lilicorr_rows = 0; + std::vector lilicorr_embd; + std::vector lilicorr_pos; - common_sampler_sample(smpl, ctx_dft, idx, true); + common_speculative_impl_draft_lilicorr(const common_params_speculative & params, uint32_t n_seq) + : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR) + { + char lilicorr_meta[32] = {}; + lilicorr_top_k = llama_model_meta_val_str(llama_get_model(this->params.ctx_dft), "lilicorr.candidate_topk", lilicorr_meta, sizeof(lilicorr_meta)) >= 0 + ? std::atoi(lilicorr_meta) : 0; + lilicorr_rows = (size_t) block_size + 1; + const size_t lilicorr_slots = (size_t) n_seq * lilicorr_rows; + lilicorr_embd.resize(lilicorr_slots * (size_t) n_embd_dec); + lilicorr_pos.assign(lilicorr_slots, -1); + + // the context features are read back from h_nextn after a host copy injection + init({ + /* .n_draft_max = */ block_size - 1, + /* .backend_sampling = */ false, + /* .dev_features = */ false, + /* .nextn_masked = */ false, + }); + } - const auto * cur_p = common_sampler_get_candidates(smpl, true); +protected: + void store_context_features(llama_seq_id seq_id, int32_t n_chunk) override { + // Ordinary DFlash can write to the KV cache, but LiliCorr needs to store embeddings across sequences. + const float * projected = llama_get_embeddings_nextn(params.ctx_dft); + if (projected) { + const size_t seq_offset = (size_t) seq_id * lilicorr_rows; + const llama_pos pos_min = std::max(0, batch_inject.tokens.back().pos[0] - block_size); + for (int32_t i = 0; i < n_chunk; ++i) { + const llama_pos pos = batch_inject.tokens[i].pos[0]; + if (pos < pos_min) { + continue; + } + const size_t slot = seq_offset + (size_t) pos % lilicorr_rows; + std::memcpy(lilicorr_embd.data() + slot * (size_t) n_embd_dec, + projected + (size_t) i * n_embd_dec, (size_t) n_embd_dec * sizeof(float)); + lilicorr_pos[slot] = pos; + } + } + } - for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { - LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", - seq_id, k, i, cur_p->data[k].id, cur_p->data[k].p, - common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); - } +public: + void draft(common_speculative_draft_params_vec & dparams) override { + auto & ctx_dft = params.ctx_dft; - const llama_token id = cur_p->data[0].id; + batch.clear(); - common_sampler_accept(smpl, id, true); + // build one batch holding every drafting sequence's noise block into a single decode + // record where each block starts, all blocks have the same size + std::vector i_block_beg(n_seq, -1); - result.push_back(id); - } - } else { - // greedily read the predicted block at this sequence's noise positions 1..n_block_tokens-1 - for (int32_t i = 1; i < n_block_tokens; ++i) { - common_sampler_sample(smpl, ctx_dft, beg + i, true); + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + auto & dp = dparams[seq_id]; + if (!dp.drafting) { + continue; + } - const auto * cur_p = common_sampler_get_candidates(smpl, true); + common_sampler_reset(smpls[seq_id].get()); - for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { - LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", - seq_id, k, i - 1, cur_p->data[k].id, cur_p->data[k].p, - common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); - } + const int32_t n = (int32_t) dp.pos0; - const llama_token id = cur_p->data[0].id; + // the scorer reads a full block + i_block_beg[seq_id] = batch.size(); + for (int32_t i = 0; i < block_size; ++i) { + const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, false); + // For LiliCorr drafting batch, set state embeddings for use in the associated transformer head. + const llama_pos pos = dp.pos0 - 1; + const size_t slot = (size_t) seq_id * lilicorr_rows + (size_t) pos % lilicorr_rows; + batch.set_embd_state(idx, { lilicorr_embd.data() + slot * (size_t) n_embd_dec, 1, (size_t) n_embd_dec }); + } + } - if (cur_p->data[0].p < params.p_min) { - break; - } + if (batch.size() == 0) { + return; + } + + // decode all sequence's noise block in a single batch + int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + if (ret != 0) { + LOG_WRN("%s: llama_process returned %d\n", __func__, ret); + return; + } - common_sampler_accept(smpl, id, true); + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_block_beg[seq_id] < 0) { + continue; + } + auto & dp = dparams[seq_id]; + + const int32_t beg = i_block_beg[seq_id]; - result.push_back(id); + auto & result = *dp.result; + + const float * lattice = llama_get_embeddings_nextn(ctx_dft); + GGML_ASSERT(lattice && "LiliCorr scorer produced no lattice"); + + int32_t predecessor = 0; + for (int32_t i = 1; i < params.n_max + 1; ++i) { + const float * row = lattice + (size_t) (beg + i) * n_embd_dec; + const int32_t top_k = lilicorr_top_k; + const float * scores = row + top_k + (size_t) predecessor * top_k; + + predecessor = (int32_t) std::distance(scores, + std::max_element(scores, scores + top_k)); + if (params.p_min > 0.0f) { + // softmax(scores) at the argmax, i.e. 1 / sum(exp(s_k - s_max)) + float sum = 0.0f; + for (int32_t k = 0; k < top_k; ++k) { + sum += std::exp(scores[k] - scores[predecessor]); + } + if (1.0f / sum < params.p_min) { + break; + } } + result.push_back((llama_token) row[predecessor]); } if (result.size() < (size_t) params.n_min) { @@ -1517,10 +1788,6 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { } } } - - void accept(llama_seq_id /*seq_id*/, uint16_t /*n_accepted*/, bool /*is_other*/) override { - // noop - } }; struct common_speculative_impl_draft_mtp : public common_speculative_impl { @@ -2535,18 +2802,20 @@ const char * common_speculative_all_types_str() { std::string common_speculative_type_to_str(common_speculative_type type) { switch (type) { - case COMMON_SPECULATIVE_TYPE_NONE: return "none"; - case COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE: return "draft-simple"; - case COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3: return "draft-eagle3"; - case COMMON_SPECULATIVE_TYPE_DRAFT_MTP: return "draft-mtp"; - case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: return "draft-dflash"; - case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: return "draft-dspark"; - case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: return "ngram-simple"; - case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K: return "ngram-map-k"; - case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V: return "ngram-map-k4v"; - case COMMON_SPECULATIVE_TYPE_NGRAM_MOD: return "ngram-mod"; - case COMMON_SPECULATIVE_TYPE_NGRAM_CACHE: return "ngram-cache"; - default: return "unknown"; + case COMMON_SPECULATIVE_TYPE_NONE: return "none"; + case COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE: return "draft-simple"; + case COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3: return "draft-eagle3"; + case COMMON_SPECULATIVE_TYPE_DRAFT_MTP: return "draft-mtp"; + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: return "draft-dflash"; + case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: return "draft-dspark"; + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2: return "draft-dflash2"; + case COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR: return "draft-lilicorr"; + case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: return "ngram-simple"; + case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K: return "ngram-map-k"; + case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V: return "ngram-map-k4v"; + case COMMON_SPECULATIVE_TYPE_NGRAM_MOD: return "ngram-mod"; + case COMMON_SPECULATIVE_TYPE_NGRAM_CACHE: return "ngram-cache"; + default: return "unknown"; } } @@ -2604,10 +2873,8 @@ std::vector common_speculative_types_from_gguf(const st return {}; } - // the Markov head distinguishes draft-dspark from draft-dflash - const auto type = gguf_find_tensor(gguf_ctx.get(), "markov_w1.weight") >= 0 - ? COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK - : COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH; + // draft-dflash runs every DFlash family draft, the head of the loaded draft picks the driver + const auto type = COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH; SPC_INF("auto-detected speculative type '%s' from the draft model metadata\n", common_speculative_type_to_str(type).c_str()); @@ -2632,6 +2899,8 @@ int32_t common_speculative_n_max(const common_params_speculative * spec) { case COMMON_SPECULATIVE_TYPE_DRAFT_MTP: case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2: + case COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR: n_max = std::max(n_max, std::max(0, spec->draft.n_max)); break; case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: @@ -2803,7 +3072,10 @@ common_params common_base_params_to_speculative(const common_params & params) { const bool has_block_draft = std::any_of( params.speculative.types.begin(), params.speculative.types.end(), [](common_speculative_type t) { - return t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK; + return t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK || + t == COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2 || + t == COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR; }); if (has_block_draft) { // per-seq output positions: DFlash decodes anchor + n_max masks (n_max + 1); DSpark n_max -> +1 covers both @@ -2919,6 +3191,14 @@ common_speculative * common_speculative_init(common_params_speculative & params, { uint32_t enabled_configs = common_get_enabled_speculative_configs(params.types); + // the DFlash family types share the draft context, so one run uses at most one of them + const uint32_t dflash_configs = enabled_configs & ( + (1u << COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH) | (1u << COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) | + (1u << COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2) | (1u << COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR)); + if (dflash_configs & (dflash_configs - 1)) { + throw std::runtime_error("draft-dflash, draft-dflash2, draft-dspark and draft-lilicorr cannot be combined"); + } + auto add_config_if_enabled = [&](common_speculative_type type, bool available = true) { if (available && (enabled_configs & (1u << type))) { configs.emplace_back(type, params); @@ -2926,7 +3206,7 @@ common_speculative * common_speculative_init(common_params_speculative & params, }; // when adding a new type - update here the logic above - static_assert(COMMON_SPECULATIVE_TYPE_COUNT == 11); + static_assert(COMMON_SPECULATIVE_TYPE_COUNT == 13); // this list here defines the priority of the speculators // the one with highest priority are listed first @@ -2937,10 +3217,12 @@ common_speculative * common_speculative_init(common_params_speculative & params, add_config_if_enabled(COMMON_SPECULATIVE_TYPE_NGRAM_CACHE); add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_SIMPLE); - add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3, params.draft.ctx_dft != nullptr); - add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_MTP, params.draft.ctx_dft != nullptr); - add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, params.draft.ctx_dft != nullptr); - add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_EAGLE3, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_MTP, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2, params.draft.ctx_dft != nullptr); + add_config_if_enabled(COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR, params.draft.ctx_dft != nullptr); } std::vector> impls = {}; @@ -2961,13 +3243,43 @@ common_speculative * common_speculative_init(common_params_speculative & params, impls.push_back(std::make_unique(config.params, n_seq)); break; } - case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: { - impls.push_back(std::make_unique(config.params, n_seq)); - break; - } - case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: { - impls.push_back(std::make_unique( - config.params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK)); + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH: + case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2: + case COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR: { + common_speculative_type type_model = COMMON_SPECULATIVE_TYPE_NONE; + switch (llama_model_dflash_variant(llama_get_model(config.params.draft.ctx_dft))) { + case LLAMA_DFLASH_VARIANT_DFLASH: type_model = COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH; break; + case LLAMA_DFLASH_VARIANT_DFLASH2: type_model = COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2; break; + case LLAMA_DFLASH_VARIANT_DSPARK: type_model = COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK; break; + case LLAMA_DFLASH_VARIANT_LILICORR: type_model = COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR; break; + case LLAMA_DFLASH_VARIANT_NONE: break; + } + if (type_model == COMMON_SPECULATIVE_TYPE_NONE) { + throw std::runtime_error(string_format("--spec-type %s requires a DFlash draft model", + common_speculative_type_to_str(config.type).c_str())); + } + + // draft-dflash runs every DFlash family draft, the other types must match the head of the draft + if (config.type != COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH && config.type != type_model) { + throw std::runtime_error(string_format("--spec-type %s does not match the draft model: use %s", + common_speculative_type_to_str(config.type).c_str(), common_speculative_type_to_str(type_model).c_str())); + } + + switch (type_model) { + case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + impls.push_back(std::make_unique(config.params, n_seq)); + break; + case COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH2: + impls.push_back(std::make_unique(config.params, n_seq)); + break; + case COMMON_SPECULATIVE_TYPE_DRAFT_LILICORR: + impls.push_back(std::make_unique(config.params, n_seq)); + break; + default: + impls.push_back(std::make_unique(config.params, n_seq)); + break; + } break; } case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: { @@ -3019,6 +3331,26 @@ common_speculative * common_speculative_init(common_params_speculative & params, return nullptr; } + // the n-gram drafters ignore p_min, and DSpark uses it as the cutoff of its confidence head + const bool uses_p_min = std::any_of(impls.begin(), impls.end(), [](const auto & impl) { + switch (impl->type) { + case COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK: + case COMMON_SPECULATIVE_TYPE_NGRAM_SIMPLE: + case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K: + case COMMON_SPECULATIVE_TYPE_NGRAM_MAP_K4V: + case COMMON_SPECULATIVE_TYPE_NGRAM_MOD: + case COMMON_SPECULATIVE_TYPE_NGRAM_CACHE: + return false; + default: + return true; + } + }); + + if (params.draft.probabilistic && params.draft.p_min > 0.0f && uses_p_min) { + LOG_WRN("%s: --spec-draft-p-min %.2f stops sampled drafts early, consider setting it to 0 with --spec-draft-sampling probabilistic\n", + __func__, (double) params.draft.p_min); + } + common_speculative_ptr result(new common_speculative { /* .dparams = */ common_speculative_draft_params_vec(n_seq), /* .impls = */ std::move(impls), diff --git a/common/speculative.h b/common/speculative.h index 4262327cbbc2..949114f35609 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -73,7 +73,7 @@ struct common_speculative_draft_params { // the generated draft from the last _draft() call llama_tokens * result; - // candidate distribution per drafted token; set it to make draft-simple, draft-mtp and draft-dflash (DFlash2 only) sample + // candidate distribution per drafted token; set it to make draft-simple, draft-mtp and draft-dflash2 sample std::vector> * result_q = nullptr; // the target's temp and seed, read only when the drafter samples probabilistically diff --git a/conversion/__init__.py b/conversion/__init__.py index 6800093ae4be..253a18fd48aa 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -78,6 +78,7 @@ "DistilBertForMaskedLM": "bert", "DistilBertForSequenceClassification": "bert", "DistilBertModel": "bert", + "DomynEdgeForCausalLM": "domynedge", "Dots1ForCausalLM": "dots1", "Dots3NoteForCausalLM": "dots3", "Dots3NoteForConditionalGeneration": "dots3", @@ -126,6 +127,7 @@ "GlmOcrForConditionalGeneration": "glm", "GptOssForCausalLM": "gpt_oss", "GraniteForCausalLM": "granite", + "Granite4VisionForConditionalGeneration": "granite", "GraniteMoeForCausalLM": "granite", "GraniteMoeHybridForCausalLM": "granite", "GraniteMoeSharedForCausalLM": "granite", @@ -137,6 +139,7 @@ "Grok1ForCausalLM": "grok", "GrokForCausalLM": "grok", "GroveMoeForCausalLM": "grovemoe", + "HiggsAudio3Model": "higgs_audio", "HunYuanDenseV1ForCausalLM": "hunyuan", "HunYuanMoEV1ForCausalLM": "hunyuan", "HunYuanVLForConditionalGeneration": "hunyuan", @@ -144,6 +147,8 @@ "HYV3ForCausalLM": "hunyuan", "HYV4ForCausalLM": "hy_v4", "IQuestCoderForCausalLM": "llama", + "Inkling2ForCausalLM": "inkling2", + "Inkling2ForConditionalGeneration": "inkling2", "InternLM2ForCausalLM": "internlm", "InternLM3ForCausalLM": "internlm", "JAISLMHeadModel": "jais", @@ -217,6 +222,7 @@ "MiniMaxM2ForCausalLM": "minimax", "MiniMaxM3SparseForCausalLM": "minimax", "MiniMaxM3SparseForConditionalGeneration": "minimax", + "DSparkMiniMaxDraftModel": "minimax", "Ministral3ForCausalLM": "mistral3", "Ministral3Model": "mistral3", "Mistral3ForConditionalGeneration": "mistral3", @@ -278,6 +284,12 @@ "Qwen3NextForCausalLM": "qwen", "Qwen3OmniMoeForConditionalGeneration": "qwen3vl", "PocketTTSModel": "pockettts", + "KokoroModel": "kokoro", + "TinyVocaModel": "tiny_voca", + "Zonos3Model": "zonos3", + "YuE2ForCausalLM": "yue2", + "VoxCPM2Model": "voxcpm", + "MiniMaxMusic3ForConditionalGeneration": "minimax_music3", "Qwen3TTSForConditionalGeneration": "qwen3tts", "Qwen3VLForConditionalGeneration": "qwen3vl", "Qwen3VLMoeForConditionalGeneration": "qwen3vl", @@ -320,6 +332,7 @@ "UMT5Model": "t5", "UltravoxModel": "ultravox", "UnlimitedOCRForCausalLM": "deepseek", + "VibeVoiceAsrForConditionalGeneration": "vibevoice_asr", "VLlama3ForCausalLM": "llama", "VllmDecision2Model": "vllm_decision2", "VoxtralForConditionalGeneration": "llama", @@ -329,6 +342,8 @@ "XverseForCausalLM": "xverse", "YoutuForCausalLM": "deepseek", "YoutuVLForConditionalGeneration": "deepseek", + "ZayaForCausalLM": "zaya1", + "fish_qwen3_omni": "fish_s2", "modeling_grove_moe.GroveMoeForCausalLM": "grovemoe", "modeling_sarvam_moe.SarvamMoEForCausalLM": "bailingmoe", } @@ -352,6 +367,10 @@ "EmbeddingGemma2Model": "gemma", "Exaone4_5_ForConditionalGeneration": "exaone", "FishOmniModel": "drama3", + "Zonos3Model": "zonos3", + "YuE2ForCausalLM": "yue2", + "VoxCPM2Model": "voxcpm", + "MiniMaxMusic3ForConditionalGeneration": "minimax_music3", "Gemma3ForConditionalGeneration": "gemma", "Gemma3nForConditionalGeneration": "gemma", "Gemma4ForConditionalGeneration": "gemma", @@ -366,8 +385,10 @@ "Granite4VisionForConditionalGeneration": "granite", "GraniteSpeechForConditionalGeneration": "granite", "GraniteSpeechPlusForConditionalGeneration": "granite", + "HiggsAudio3Model": "higgs_audio", "HunYuanVLForConditionalGeneration": "hunyuan", "Idefics3ForConditionalGeneration": "smolvlm", + "Inkling2ForConditionalGeneration": "inkling2", "InternVisionModel": "internvl", "JanusForConditionalGeneration": "januspro", "KimiK25ForConditionalGeneration": "kimivl", @@ -408,6 +429,8 @@ "Qwen3ASRForConditionalGeneration": "qwen3vl", "Qwen3OmniMoeForConditionalGeneration": "qwen3vl", "PocketTTSModel": "pockettts", + "KokoroModel": "kokoro", + "TinyVocaModel": "tiny_voca", "SopranoModel": "soprano", "Qwen3TTSForConditionalGeneration": "qwen3tts", "Qwen3VLForConditionalGeneration": "qwen3vl", @@ -424,9 +447,11 @@ "Step3p7ForConditionalGeneration": "step3", "UltravoxModel": "ultravox", "UnlimitedOCRForCausalLM": "deepseek", + "VibeVoiceAsrForConditionalGeneration": "vibevoice_asr", "VoxtralForConditionalGeneration": "ultravox", "VoxtralRealtimeForConditionalGeneration": "ultravox", "YoutuVLForConditionalGeneration": "youtuvl", + "fish_qwen3_omni": "fish_s2", } diff --git a/conversion/base.py b/conversion/base.py index 58ddb5defe55..540a66ba5098 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -398,6 +398,9 @@ def dequant_bitnet(weight: Tensor, scale: Tensor) -> Tensor: return data / scale.float() def dequant_simple(weight: Tensor, scale: Tensor, block_size: Sequence[int] | None = None) -> Tensor: + if scale.dtype == torch.uint8: + # E8M0 exponent stored as raw bytes (MXFP8) + scale = (scale.float() - 127.0).exp2() scale = scale.float() # ModelOpt block scales are pre-shaped for broadcasting, e.g. [out/128, 1, in/128, 1] @@ -538,7 +541,7 @@ def dequant_fp8(fp8_configs: list[dict[str, Any]] | None = None) -> None: s = self.model_tensors[name] self.model_tensors[weight_name] = lambda w=w, s=s: dequant_bitnet(w(), s()) tensors_to_remove.append(name) - elif quant_method in ("fp8", "bsgemm-moe"): # bsgemm-moe: drama-3, same block layout + elif quant_method in ("fp8", "bsgemm-moe", "mxfp8"): # bsgemm-moe: drama-3, same block layout block_size = quant_config.get("weight_block_size") for name in self.model_tensors.keys(): if name.endswith("_scale_inv"): @@ -650,6 +653,28 @@ def dequant_fp8(fp8_configs: list[dict[str, Any]] | None = None) -> None: raise NotImplementedError(f"Quant format {quant_format!r} for method {quant_method!r} is not yet supported") elif quant_method in ("modelopt", "modelopt_mixed"): dequant_fp8() + # FP8_PB_WO: one scale per block, the block size follows from the two shapes + for name in self.model_tensors.keys(): + if not name.endswith(".weight_scale_inv"): + continue + weight_name = name.removesuffix("_scale_inv") + if weight_name not in self.model_tensors: + tensors_to_remove.append(name) + continue + w = self.model_tensors[weight_name] + s = self.model_tensors[name] + if w().dtype != torch.float8_e4m3fn: + continue + w_shape, s_shape = w().shape, s().shape + block_size = None + if prod(s_shape) != 1: + if len(s_shape) != len(w_shape) or any(ws % ss for ws, ss in zip(w_shape, s_shape)): + raise ValueError(f"FP8 weight {weight_name!r} {list(w_shape)} is not tiled by its scale {list(s_shape)}") + block_size = [ws // ss for ws, ss in zip(w_shape, s_shape)] + self.model_tensors[weight_name] = lambda w=w, s=s, bs=block_size: dequant_simple(w(), s(), bs) + tensors_to_remove.append(name) + if self._fp8_as_q8: + self._fp8_dequantized.add(weight_name) elif quant_method is not None: raise NotImplementedError(f"Quant method is not yet supported: {quant_method!r}") @@ -1357,10 +1382,10 @@ def _generate_nvfp4_tensors(self): consumed.append(input_scale_name) # Check if this is a per-expert tensor - m = re.search(r'\.experts\.(\d+)\.(gate_proj|up_proj|down_proj)\.weight$', name) + m = re.search(r'\.experts\.(\d+)\.(gate_proj|up_proj|down_proj|w1|w2|w3)\.weight$', name) if m: expert_id = int(m.group(1)) - proj_type = m.group(2) + proj_type = {"w1": "gate_proj", "w2": "down_proj", "w3": "up_proj"}.get(m.group(2), m.group(2)) bid_m = re.search(r'\.layers\.(\d+)\.', name) bid = int(bid_m.group(1)) if bid_m else 0 key = (bid, proj_type) @@ -1451,6 +1476,8 @@ def prepare_tensors(self): quant_layers = quant_config.get("quantized_layers", quant_layers) or {} nvfp4_compressed_tensors = self._is_nvfp4_compressed_tensors(quant_method, quant_format, quant_groups) + # e.g. MXFP8 dense weights with compressed-tensors NVFP4 experts + nvfp4_compressed_tensors |= quantization_config.get("moe_quant_format") == "nvfp4-pack-quantized" self._nvfp4_global_algo = quant_algo @@ -1979,6 +2006,14 @@ def set_gguf_parameters(self): if (local_rope_theta := self.rope_parameters.get("sliding_attention", {}).get("rope_theta")) is not None: self.gguf_writer.add_rope_freq_base_swa(local_rope_theta) logger.info(f"gguf: rope theta swa = {local_rope_theta}") + # Add rope_pattern from no_rope_layers + if no_rope_layers := self.hparams.get("no_rope_layers"): + if len(no_rope_layers) == self.block_count: # "no_rope_layers": [0, 0, 0, 1] + rope_pattern = [bool(x) for x in no_rope_layers] + else: # "no_rope_layers": [3] + rope_pattern = [i not in no_rope_layers for i in range(self.block_count)] + self.gguf_writer.add_rope_pattern(rope_pattern) + logger.info(f"gguf: rope_pattern = {sum(rope_pattern)} RoPE layers / {len(rope_pattern)} total") if (f_rms_eps := self.find_hparam(["rms_norm_eps", "norm_eps"], optional=True)) is not None: self.gguf_writer.add_layer_norm_rms_eps(f_rms_eps) logger.info(f"gguf: rms norm epsilon = {f_rms_eps}") @@ -2432,6 +2467,12 @@ def get_vocab_base_pre(self, tokenizer) -> str: if chkhsh == "a9af07a84191f55098b248ae6f3dfe9e32d3190bebe8eafd91c1ddec9bc3449f": # ref: https://huggingface.co/IFM/K2-Horizon-36B res = "k2-horizon" + if chkhsh == "5635e1c8d621dff7b4825f41f2f97b6ceb39bcf2d5c541db28577080d6efd5e5": + # ref: https://huggingface.co/thinkingmachines/Inkling-2-Small + res = "inkling2" + if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3": + # ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF + res = "domyn-edge" if res is None: logger.warning("\n") @@ -3461,7 +3502,7 @@ def get_model_architecture(hparams: dict[str, Any], model_type: ModelType) -> st # Kimi-K3's text_config reports "KimiLinearForCausalLM", which is the older # Kimi-Linear-48B architecture and cannot load K3 (no attention residuals, # latent MoE, situ, ...). Route on the top-level architecture instead. - if model_type == ModelType.TEXT and arch in ("NEOChatModel", "StepVLForConditionalGeneration", "Sarashina2VisionForCausalLM", "Exaone4_5_ForConditionalGeneration", "Step3p7ForConditionalGeneration", "KimiK3ForConditionalGeneration", "KimiK31ForConditionalGeneration", "Nemotron3_5TranscribeForConditionalGeneration"): + if model_type == ModelType.TEXT and arch in ("NEOChatModel", "StepVLForConditionalGeneration", "Sarashina2VisionForCausalLM", "Exaone4_5_ForConditionalGeneration", "Step3p7ForConditionalGeneration", "KimiK3ForConditionalGeneration", "KimiK31ForConditionalGeneration", "Nemotron3_5TranscribeForConditionalGeneration", "HiggsAudio3Model"): return arch # if "architectures" is found in the sub-config, use that instead @@ -3472,6 +3513,9 @@ def get_model_architecture(hparams: dict[str, Any], model_type: ModelType) -> st # some models (llava_onevision2) only declare the architecture inside text_config if arch is None and text_config.get("architectures") is not None: arch = text_config["architectures"][0] + # some configs only have a model_type (fishaudio/s2-pro) + if arch is None: + arch = hparams.get("model_type") if arch is None: raise ValueError("Failed to detect model architecture") return arch diff --git a/conversion/domynedge.py b/conversion/domynedge.py new file mode 100644 index 000000000000..df07add83cbf --- /dev/null +++ b/conversion/domynedge.py @@ -0,0 +1,53 @@ +from .base import TextModel, ModelBase +import gguf + + +@ModelBase.register("DomynEdgeForCausalLM") +@ModelBase.example("domyn/Domyn-Edge-Teacher-IF") +class DomynEdgeModel(TextModel): + model_arch = gguf.MODEL_ARCH.DOMYN_EDGE + + def set_gguf_parameters(self): + super().set_gguf_parameters() + hparams = self.hparams + self.gguf_writer.add_vocab_size(hparams["vocab_size"]) + + position_layers = hparams["position_layers"] # list of "rope"/"nope" strings per layer + head_sizes = hparams["head_sizes"] # list of int head dims per layer + + # Per-layer rope/SWA pattern: True="rope", False="nope" + rope_pattern = [v == "rope" for v in position_layers] + self.gguf_writer.add_rope_pattern(rope_pattern) + self.gguf_writer.add_sliding_window_pattern(rope_pattern) # SWA <-> RoPE in domyn-edge + + # window_sizes entries are flash-attn style [left, right] (current token excluded; -1 = full attention), + # while llama.cpp's n_swa counts the current token, hence the +1 (matches HF's sliding_window=1025) + swa_window = hparams.get("sliding_window") + if swa_window is None: + window_sizes = hparams.get("window_sizes") # list of [size, offset] pairs per layer + if window_sizes is None: + raise KeyError("Neither `sliding_window` nor `window_sizes` found among domyn edge hyperparameters") + left = next((ws[0] for v, ws in zip(position_layers, window_sizes) if v == "rope"), None) + swa_window = left + 1 if left is not None and left > 0 else None + if swa_window is None: + raise ValueError("No sliding window size found among domyn edge hyperparameters") + self.gguf_writer.add_sliding_window(swa_window) + + # Head dims differ between full-attention ("nope") and SWA ("rope") layers + full_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "nope"} + swa_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "rope"} + + if len(full_head_dims) != 1: + raise ValueError(f"Expected one head dimension for full attention layers, found {len(full_head_dims)}") + full_head_dim = full_head_dims.pop() + + self.gguf_writer.add_key_length(full_head_dim) + self.gguf_writer.add_value_length(full_head_dim) + + if len(swa_head_dims) != 1: + raise ValueError(f"Expected one head dimension for SWA attention layers, found {len(swa_head_dims)}") + swa_head_dim = swa_head_dims.pop() + + self.gguf_writer.add_key_length_swa(swa_head_dim) + self.gguf_writer.add_value_length_swa(swa_head_dim) + self.gguf_writer.add_rope_dimension_count_swa(swa_head_dim) diff --git a/conversion/drama3.py b/conversion/drama3.py index ac01f481c98a..9b490900a44d 100644 --- a/conversion/drama3.py +++ b/conversion/drama3.py @@ -18,6 +18,139 @@ _TOWER_RESIDUAL = "audio_decoder_mtp.layers." +def load_codec(dir_model) -> dict[str, Tensor]: + sd = torch.load(dir_model / "codec.pth", map_location="cpu", mmap=True, weights_only=True) + return sd.get("state_dict", sd) + + +def fold_conv(sd: dict[str, Tensor], prefix: str) -> Tensor: + # fold weight norm + if prefix + ".conv.weight" in sd: + return sd[prefix + ".conv.weight"].float() + g = sd[prefix + ".conv.parametrizations.weight.original0"].float() + v = sd[prefix + ".conv.parametrizations.weight.original1"].float() + return g * v / v.norm(dim=(1, 2), keepdim=True) + + +def fold_wn(g: Tensor, v: Tensor) -> Tensor: + # fold old-style weight norm of a 1x1 conv, returns [out, in] + return (g.float() * v.float() / v.float().norm(dim=(1, 2), keepdim=True)).squeeze(-1) + + +def fold_snake(alpha: Tensor) -> tuple[Tensor, Tensor]: + alpha = alpha.float().flatten() + return alpha, 1.0 / (alpha + 1e-9) + + +# codec encoder strides (encoder_rates of the codec config), the quantizer then downsamples 2x2 +_CODEC_ENC_STRIDES = (2, 4, 8, 8) + +# codec encoder transformers, both 1024 wide with 16 heads of 64 +# generic audio layers a.blk.0..3: last encoder block, a.blk.4..11: quantizer pre_module +_N_ENC_TFM_LAYERS = 4 +_N_PRE_TFM_LAYERS = 8 +_CODEC_HEAD_DIM = 64 + + +def _neox_rows(w: Tensor, head_dim: int) -> Tensor: + # checkpoint uses interleaved RoPE, reorder the rows of each head so NEOX RoPE gives the same result + order = torch.cat([torch.arange(0, head_dim, 2), torch.arange(1, head_dim, 2)]) + return w.reshape(-1, head_dim, *w.shape[1:])[:, order].reshape(w.shape) + + +def codec_encoder_tensors(sd: dict[str, Tensor], num_codebooks: int) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + + def get(name: str) -> Tensor: + return sd[name].float() + + def tn(tensor: gguf.MODEL_TENSOR, bid: int | None = None, xid: int | None = None) -> str: + return gguf.TENSOR_NAMES[tensor].format(bid=bid, xid=xid) + + def fmt(tensor: gguf.MODEL_TENSOR, bid: int | None = None, suffix: str = ".weight") -> str: + return tn(tensor, bid) + suffix + + def conv_wb(tensor: gguf.MODEL_TENSOR, prefix: str, bid: int | None = None, xid: int | None = None, stride: int = 1): + # taps-major [K / stride, OC, stride * IC], see conv() in tools/mtmd/models/fish-s2-spkenc.cpp + w = fold_conv(sd, prefix) + n_out, n_in, k = w.shape + w = w.reshape(n_out, n_in, k // stride, stride).permute(2, 0, 3, 1).reshape(k // stride, n_out, stride * n_in) + yield (tn(tensor, bid, xid) + ".weight", w) + yield (tn(tensor, bid, xid) + ".bias", get(prefix + ".conv.bias")) + + def snake_ab(tensor: gguf.MODEL_TENSOR, name: str, bid: int | None = None, xid: int | None = None): + a, b = fold_snake(get(name)) + yield (tn(tensor, bid, xid) + ".alpha", a) + yield (tn(tensor, bid, xid) + ".beta", b) + + def tfm_layers(prefix: str, n_layer: int, offset: int): + for il in range(n_layer): + p = f"{prefix}layers.{il}." + bid = offset + il + wq, wk, wv = get(p + "attention.wqkv.weight").chunk(3, dim=0) + yield (fmt(T.A_ENC_ATTN_Q, bid), _neox_rows(wq, _CODEC_HEAD_DIM)) + yield (fmt(T.A_ENC_ATTN_K, bid), _neox_rows(wk, _CODEC_HEAD_DIM)) + yield (fmt(T.A_ENC_ATTN_V, bid), wv) + yield (fmt(T.A_ENC_OUTPUT, bid), get(p + "attention.wo.weight")) + yield (fmt(T.A_ENC_INPUT_NORM, bid), get(p + "attention_norm.weight")) + yield (fmt(T.A_ENC_ATTN_SCALE, bid), get(p + "attention_layer_scale.gamma")) + yield (fmt(T.A_ENC_OUTPUT_NORM, bid), get(p + "ffn_norm.weight")) + yield (fmt(T.A_ENC_FFN_GATE, bid), get(p + "feed_forward.w1.weight")) + yield (fmt(T.A_ENC_FFN_UP, bid), get(p + "feed_forward.w3.weight")) + yield (fmt(T.A_ENC_FFN_DOWN, bid), get(p + "feed_forward.w2.weight")) + yield (fmt(T.A_ENC_FFN_SCALE_LS, bid), get(p + "ffn_layer_scale.gamma")) + + # encoder: entry conv, 4x (3 residual units, Snake, strided conv), Snake, post conv + e = "encoder.block." + yield from conv_wb(T.A_CODEC_ENC_ENTRY, e + "0") + for bid, stride in enumerate(_CODEC_ENC_STRIDES): + p = f"{e}{bid + 1}.block." + for xid in range(3): + r = f"{p}{xid}.block." + yield from snake_ab(T.A_CODEC_ENC_RES_ACT1, r + "0.alpha", bid, xid) + yield from conv_wb(T.A_CODEC_ENC_RES_CONV1, r + "1", bid, xid) + yield from snake_ab(T.A_CODEC_ENC_RES_ACT2, r + "2.alpha", bid, xid) + yield from conv_wb(T.A_CODEC_ENC_RES_CONV2, r + "3", bid, xid) + yield from snake_ab(T.A_CODEC_ENC_SNAKE, p + "3.alpha", bid) + yield from conv_wb(T.A_CODEC_ENC_CONV, p + "4", bid, stride=stride) + # the last block ends with a windowed transformer + yield from tfm_layers(f"{e}4.block.5.", _N_ENC_TFM_LAYERS, 0) + yield (fmt(T.A_POST_NORM), get(f"{e}4.block.5.norm.weight")) + yield from snake_ab(T.A_CODEC_ENC_POST_SNAKE, e + "5.alpha") + yield from conv_wb(T.A_CODEC_ENC_POST_CONV, e + "6") + + # quantizer: 2x (strided conv + ConvNeXt), windowed transformer, then semantic + residual VQ + q = "quantizer." + for bid in range(2): + p = f"{q}downsample.{bid}." + yield from conv_wb(T.A_CODEC_DOWN_CONV, p + "0", bid, stride=2) + # depthwise: one [C] row per tap + yield (tn(T.A_CODEC_DOWN_DWCONV, bid) + ".weight", fold_conv(sd, p + "1.dwconv").squeeze(1).T.contiguous()) + yield (tn(T.A_CODEC_DOWN_DWCONV, bid) + ".bias", get(p + "1.dwconv.conv.bias")) + for key, tensor in (("norm", T.A_CODEC_DOWN_NORM), ("pwconv1", T.A_CODEC_DOWN_PW1), ("pwconv2", T.A_CODEC_DOWN_PW2)): + yield (tn(tensor, bid) + ".weight", get(f"{p}1.{key}.weight")) + yield (tn(tensor, bid) + ".bias", get(f"{p}1.{key}.bias")) + yield (tn(T.A_CODEC_DOWN_GAMMA, bid), get(p + "1.gamma")) + yield from tfm_layers(q + "pre_module.", _N_PRE_TFM_LAYERS, _N_ENC_TFM_LAYERS) + yield (fmt(T.A_CODEC_PRE_NORM), get(q + "pre_module.norm.weight")) + + # nearest codebook entry by cosine similarity, see VectorQuantize.decode_latents() + def vq(prefix: str) -> tuple[Tensor, Tensor, Tensor]: + w = fold_wn(sd[prefix + ".in_proj.weight_g"], sd[prefix + ".in_proj.weight_v"]) + cb = torch.nn.functional.normalize(get(prefix + ".codebook.weight"), dim=-1) + return w, get(prefix + ".in_proj.bias"), cb + + w, b, cb = vq(q + "semantic_quantizer.quantizers.0") + yield (fmt(T.A_CODEC_VQ_FIRST_IN, suffix=".weight"), w) + yield (fmt(T.A_CODEC_VQ_FIRST_IN, suffix=".bias"), b) + yield (fmt(T.A_CODEC_VQ_FIRST_CB), cb) + n_rest = num_codebooks - 1 + rest = [vq(f"{q}quantizer.quantizers.{i}") for i in range(n_rest)] + yield (fmt(T.A_CODEC_VQ_REST_IN, suffix=".weight"), torch.stack([r[0] for r in rest])) + yield (fmt(T.A_CODEC_VQ_REST_IN, suffix=".bias"), torch.stack([r[1] for r in rest])) + yield (fmt(T.A_CODEC_VQ_REST_CB), torch.stack([r[2] for r in rest])) + + @ModelBase.register("FishOmniModel") @ModelBase.example("fishaudio/drama-3") class Drama3TextModel(Qwen3_5MoeTextModel): @@ -35,7 +168,8 @@ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Ca @ModelBase.example("fishaudio/drama-3") class Drama3MmprojModel(MmprojModel): has_vision_encoder = False - has_audio_encoder = False + has_audio_encoder = True # codec encoder, for voice cloning + gen_projector_type = gguf.VisionProjectorType.DRAMA3_GEN _LAYER_MAP = { "enorm.weight": (gguf.MODEL_TENSOR.A_GEN_CODE_ENORM, True), @@ -69,7 +203,7 @@ def set_gguf_parameters(self): cfg = self.hparams self.gguf_writer.add_file_type(self.ftype) self.gguf_writer.add_clip_has_gen_audio_encoder(True) - self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.DRAMA3_GEN) + self.gguf_writer.add_clip_gen_audio_projector_type(self.gen_projector_type) self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) self.gguf_writer.add_gen_audio_embedding_length(cfg["dim"]) self.gguf_writer.add_gen_audio_feed_forward_length(cfg["intermediate_size"]) @@ -78,6 +212,16 @@ def set_gguf_parameters(self): self.gguf_writer.add_gen_audio_head_count_kv(cfg["n_local_heads"]) self.gguf_writer.add_gen_audio_attention_layernorm_eps(cfg["norm_eps"]) # other tower and codec hparams are hardcoded in tools/mtmd + # codec encoder: raw 44.1 kHz waveform -> backbone input rows, other hparams are hardcoded in tools/mtmd + self.gguf_writer.add_clip_has_audio_encoder(True) + self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.FISH_S2_SPKENC) + self.gguf_writer.add_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_audio_num_mel_bins(1) + self.gguf_writer.add_audio_block_count(_N_ENC_TFM_LAYERS + _N_PRE_TFM_LAYERS) + self.gguf_writer.add_audio_embedding_length(1024) + self.gguf_writer.add_audio_feed_forward_length(3072) + self.gguf_writer.add_audio_head_count(1024 // _CODEC_HEAD_DIM) + self.gguf_writer.add_audio_attention_layernorm_eps(1e-5) @classmethod def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: @@ -87,6 +231,12 @@ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Ca return None def tensor_force_quant(self, name, new_name, bid, n_dims): + # the VQ picks the nearest codebook entry, small errors in the encoder change the codes + if new_name.startswith("a.codec."): + return gguf.GGMLQuantizationType.F32 + # codec transformers: F16 gives codes closer to the reference than BF16 + if new_name.startswith("a.blk.") and n_dims == 2: + return gguf.GGMLQuantizationType.F16 # conv1d/conv1d_dw kernels must be F16, ggml_conv_1d(_dw) has no BF16 path if new_name.endswith(".weight") and ( new_name in ("a.gen.wav.dac.entry.weight", "a.gen.wav.dac.post_conv.weight") @@ -105,7 +255,7 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter T = gguf.MODEL_TENSOR cfg = self.hparams - if name.startswith("a.gen.wav."): + if name.startswith("a."): yield (name, data_torch) return @@ -152,33 +302,21 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter raise ValueError(f"unexpected tensor {name}") def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: - # only the DAC decoder, the encoder is for voice cloning (not supported yet) - sd = torch.load(self.dir_model / "codec.pth", map_location="cpu", mmap=True, weights_only=True) - sd = sd.get("state_dict", sd) + # Fish DAC decoder, then the shared codec encoder for voice cloning + sd = load_codec(self.dir_model) T = gguf.MODEL_TENSOR def get(name: str) -> Tensor: return sd[name].float() def conv(prefix: str) -> Tensor: - # fold weight norm - if prefix + ".conv.weight" in sd: - return get(prefix + ".conv.weight") - g = get(prefix + ".conv.parametrizations.weight.original0") - v = get(prefix + ".conv.parametrizations.weight.original1") - return g * v / v.norm(dim=(1, 2), keepdim=True) + return fold_conv(sd, prefix) def quant_table(prefix: str) -> Tensor: # fold out_proj into the codebook, so decoding is a row lookup - g = get(prefix + ".out_proj.weight_g") - v = get(prefix + ".out_proj.weight_v") - w = (g * v / v.norm(dim=(1, 2), keepdim=True)).squeeze(-1) + w = fold_wn(sd[prefix + ".out_proj.weight_g"], sd[prefix + ".out_proj.weight_v"]) return get(prefix + ".codebook.weight") @ w.T + get(prefix + ".out_proj.bias") - def snake(alpha: Tensor) -> tuple[Tensor, Tensor]: - alpha = alpha.flatten() - return alpha, 1.0 / (alpha + 1e-9) - q = "quantizer." yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_FIRST_CB), quant_table(q + "semantic_quantizer.quantizers.0")) n_rest = sum(1 for k in sd if k.startswith(q + "quantizer.quantizers.") and k.endswith(".codebook.weight")) @@ -228,7 +366,7 @@ def neox_rows(w: Tensor) -> Tensor: yield (self.format_tensor_name(T.A_GEN_WAV_DAC_ENTRY, suffix=".bias"), get(d + "0.conv.bias")) for bid in range(4): p = f"{d}{bid + 1}.block." - a, b = snake(get(p + "0.alpha")) + a, b = fold_snake(get(p + "0.alpha")) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_UP_SNAKE, bid, suffix=".alpha"), a) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_UP_SNAKE, bid, suffix=".beta"), b) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_UP_CONV, bid, suffix=".weight"), conv(p + "1")) @@ -236,7 +374,7 @@ def neox_rows(w: Tensor) -> Tensor: for xid in range(3): r = f"{p}{xid + 2}.block." for act, tensor in (("0", T.A_GEN_WAV_DAC_RES_ACT1), ("2", T.A_GEN_WAV_DAC_RES_ACT2)): - a, b = snake(get(r + act + ".alpha")) + a, b = fold_snake(get(r + act + ".alpha")) name = gguf.TENSOR_NAMES[tensor].format(bid=bid, xid=xid) yield (name + ".alpha", a) yield (name + ".beta", b) @@ -244,8 +382,10 @@ def neox_rows(w: Tensor) -> Tensor: name = gguf.TENSOR_NAMES[tensor].format(bid=bid, xid=xid) yield (name + ".weight", conv(r + cv)) yield (name + ".bias", get(r + cv + ".conv.bias")) - a, b = snake(get(d + "5.alpha")) + a, b = fold_snake(get(d + "5.alpha")) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_POST_SNAKE, suffix=".alpha"), a) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_POST_SNAKE, suffix=".beta"), b) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_POST_CONV, suffix=".weight"), conv(d + "6")) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_POST_CONV, suffix=".bias"), get(d + "6.conv.bias")) + + yield from codec_encoder_tensors(sd, self.hparams["num_codebooks"]) diff --git a/conversion/fish_s2.py b/conversion/fish_s2.py new file mode 100644 index 000000000000..563b52b126af --- /dev/null +++ b/conversion/fish_s2.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, Callable, Iterable, TYPE_CHECKING + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, gguf +from .drama3 import Drama3MmprojModel, _neox_rows +from .qwen import Qwen3Model + +# Fish Audio S2 Pro (dual-AR) +# text model: Qwen3 backbone (slow AR), samples the semantic code of each frame +# mmproj: fast AR code predictor (other codebooks) and Fish DAC decoder (codec.pth, same as drama3) + +# residual codebook size of codec.pth, the fast AR head is cut to it +_N_RESIDUAL_CODES = 1024 + + +def _load_hparams(dir_model: Path) -> dict[str, Any]: + hparams = ModelBase.load_hparams(dir_model, is_mistral_format=False) + cfg = hparams["text_config"] + hparams["text_config"] = { + "hidden_size": cfg["dim"], + "num_hidden_layers": cfg["n_layer"], + "num_attention_heads": cfg["n_head"], + "num_key_value_heads": cfg["n_local_heads"], + "head_dim": cfg["head_dim"], + "intermediate_size": cfg["intermediate_size"], + "rms_norm_eps": cfg["norm_eps"], + "rope_theta": cfg["rope_base"], + "max_position_embeddings": cfg["max_seq_len"], + "vocab_size": cfg["vocab_size"], + "tie_word_embeddings": cfg["tie_word_embeddings"], + } + return hparams + + +@ModelBase.register("fish_qwen3_omni") +@ModelBase.example("fishaudio/s2-pro") +class FishS2TextModel(Qwen3Model): + model_arch = gguf.MODEL_ARCH.QWEN3 + + def __init__(self, dir_model: Path, *args, **kwargs): + kwargs.pop("hparams", None) + super().__init__(dir_model, *args, hparams=_load_hparams(dir_model), **kwargs) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # the rest is mapped by tensor_mapping.py + name = name.removeprefix("text_model.") + T = gguf.MODEL_TENSOR + head_dim = self.hparams["head_dim"] + if name.endswith(".attention.wqkv.weight"): + n_q = self.hparams["num_attention_heads"] * head_dim + n_kv = self.hparams["num_key_value_heads"] * head_dim + q, k, v = data_torch.split([n_q, n_kv, n_kv], dim=0) + yield (self.format_tensor_name(T.ATTN_Q, bid), _neox_rows(q, head_dim)) + yield (self.format_tensor_name(T.ATTN_K, bid), _neox_rows(k, head_dim)) + yield (self.format_tensor_name(T.ATTN_V, bid), v) + return + if name.endswith(".attention.q_norm.weight"): + yield (self.format_tensor_name(T.ATTN_Q_NORM, bid), _neox_rows(data_torch, head_dim)) + return + if name.endswith(".attention.k_norm.weight"): + yield (self.format_tensor_name(T.ATTN_K_NORM, bid), _neox_rows(data_torch, head_dim)) + return + yield from super().modify_tensors(data_torch, name, bid) + + +@ModelBase.register("fish_qwen3_omni") +@ModelBase.example("fishaudio/s2-pro") +class FishS2MmprojModel(Drama3MmprojModel): + gen_projector_type = gguf.VisionProjectorType.FISH_S2_GEN + + _FAST_AR_MAP = { + "attention_norm.weight": gguf.MODEL_TENSOR.A_GEN_CODE_ATTN_NORM, + "attention.wo.weight": gguf.MODEL_TENSOR.A_GEN_CODE_ATTN_OUT, + "ffn_norm.weight": gguf.MODEL_TENSOR.A_GEN_CODE_FFN_NORM, + "feed_forward.w1.weight": gguf.MODEL_TENSOR.A_GEN_CODE_FFN_GATE, + "feed_forward.w3.weight": gguf.MODEL_TENSOR.A_GEN_CODE_FFN_UP, + "feed_forward.w2.weight": gguf.MODEL_TENSOR.A_GEN_CODE_FFN_DOWN, + } + + def __init__(self, dir_model: Path, *args, **kwargs): + kwargs.pop("hparams", None) + super().__init__(dir_model, *args, hparams=_load_hparams(dir_model), **kwargs) + + def get_audio_config(self) -> dict[str, Any] | None: + cfg = dict(self.global_config["audio_decoder_config"]) + cfg["num_hidden_layers"] = cfg["n_layer"] + return cfg + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name = item[0] + if name.startswith("audio_decoder.") or name == "text_model.model.embeddings.weight": + return item + return None + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + cfg = self.hparams + + # already named by generate_extra_tensors() + if name.startswith("a."): + yield (name, data_torch) + return + + if name == "text_model.model.embeddings.weight": + # semantic band of the backbone embeddings + begin = self.global_config["semantic_start_token_id"] + yield (self.format_tensor_name(T.A_GEN_CODE_OUT_EMBD), data_torch[begin:begin + cfg["vocab_size"]]) + return + + if name == "audio_decoder.codebook_embeddings.weight": + # backbone input of a speech row, one table per codebook + yield (self.format_tensor_name(T.A_GEN_CODE_EMBD), data_torch.reshape(cfg["num_codebooks"], -1, data_torch.shape[-1])) + return + + if name == "audio_decoder.embeddings.weight": + yield (self.format_tensor_name(T.A_GEN_CODE_TOK_EMBD), data_torch) + return + + if name == "audio_decoder.output.weight": + yield (self.format_tensor_name(T.A_GEN_CODE_HEAD), data_torch[:_N_RESIDUAL_CODES]) + return + + if name == "audio_decoder.norm.weight": + yield (self.format_tensor_name(T.A_GEN_CODE_OUTPUT_NORM), data_torch) + return + + assert bid is not None and name.startswith(f"audio_decoder.layers.{bid}.") + key = name.removeprefix(f"audio_decoder.layers.{bid}.") + if key == "attention.wqkv.weight": + head_dim = cfg["head_dim"] + n_q = cfg["n_head"] * head_dim + n_kv = cfg["n_local_heads"] * head_dim + q, k, v = data_torch.split([n_q, n_kv, n_kv], dim=0) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_Q, bid), _neox_rows(q, head_dim)) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_K, bid), _neox_rows(k, head_dim)) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_V, bid), v) + return + yield (self.format_tensor_name(self._FAST_AR_MAP[key], bid), data_torch) diff --git a/conversion/granite.py b/conversion/granite.py index 4c6c5a0e4cc5..66b03ceca52c 100644 --- a/conversion/granite.py +++ b/conversion/granite.py @@ -14,7 +14,7 @@ from .mamba import Mamba2Model -@ModelBase.register("GraniteForCausalLM") +@ModelBase.register("GraniteForCausalLM", "Granite4VisionForConditionalGeneration") @ModelBase.example("ibm-granite/granite-3.3-2b-instruct") class GraniteModel(LlamaModel): """Conversion for IBM's GraniteForCausalLM""" @@ -112,14 +112,6 @@ def set_gguf_parameters(self): logger.info("gguf: (granite_swa) sliding_window_pattern (inferred) = %d SWA layers / %d total", sum(is_swa), n_layers) - # Add rope_pattern from no_rope_layers - if no_rope_layers := self.hparams.get("no_rope_layers"): - # Convert 1/0 to bool (1 = use RoPE, 0 = NoPE) - rope_pattern = [bool(x) for x in no_rope_layers] - self.gguf_writer.add_rope_pattern(rope_pattern) - logger.info("gguf: (granite_swa) rope_pattern = %d RoPE layers / %d total", - sum(rope_pattern), len(rope_pattern)) - @ModelBase.register("GraniteMoeSWAForCausalLM") class GraniteMoeSWAModel(GraniteSWAModel): @@ -560,7 +552,9 @@ def set_gguf_parameters(self): or not self._ssm_layers ) self.gguf_writer.add_rope_scaling_finetuned(use_rope) - if not use_rope: + # Set context length to an arbitrary large value if rope is not used AND no previous value is present. + # https://huggingface.co/ibm-granite/granite-4.0-h-micro-GGUF/discussions/1 + if not use_rope and "max_position_embeddings" not in self.hparams: self.gguf_writer.add_context_length(2**20) ## Validation ## diff --git a/conversion/higgs_audio.py b/conversion/higgs_audio.py new file mode 100644 index 000000000000..9e4d8b2b89ee --- /dev/null +++ b/conversion/higgs_audio.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Any, Callable, TYPE_CHECKING + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, gguf +from .qwen import Qwen3Model +from .ultravox import WhisperEncoderModel + + +# plain ChatML as built by transcribe.py upstream, the Qwen3 template renders past assistant turns differently from the last one +HIGGS_AUDIO_CHAT_TEMPLATE = ( + "{%- for message in messages -%}" + "{{- '<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>\\n' -}}" + "{%- endfor -%}" + "{%- if add_generation_prompt -%}" + "{{- '<|im_start|>assistant\\n' -}}" + "{%- if enable_thinking is defined and enable_thinking is false -%}" + "{{- '\\n\\n\\n\\n' -}}" + "{%- endif -%}" + "{%- endif -%}" +) + + +@ModelBase.register("HiggsAudio3Model") +@ModelBase.example("bosonai/higgs-audio-v3-stt") +class HiggsAudioModel(Qwen3Model): + model_arch = gguf.MODEL_ARCH.QWEN3 + + def set_vocab(self): + super().set_vocab() + self.gguf_writer.add_chat_template(HIGGS_AUDIO_CHAT_TEMPLATE) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + + # the audio_* tensors are dropped by TextModel, rename the text head before that + if name == "audio_decoder_proj.text_lm_head.weight": + name = "lm_head.weight" + else: + name = "model." + name + + return super().filter_tensors((name, gen)) + + +@ModelBase.register("HiggsAudio3Model") +class HiggsAudioWhisperEncoderModel(WhisperEncoderModel): + has_vision_encoder = False + has_audio_encoder = True + + def get_audio_config(self) -> dict[str, Any] | None: + return self.global_config["audio_encoder_config"] + + def tensor_force_quant(self, name, new_name, bid, n_dims): + # depthwise conv kernel, same as the whisper convs + if name == "audio_encoder_proj.temporal.weight": + return gguf.GGMLQuantizationType.F16 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + def set_gguf_parameters(self): + assert self.global_config["projector_type"] == "mlp" and self.global_config["projector_temporal_downsample"] == 2 + assert self.global_config["audio_adapter_type"] == "stack" and not self.global_config.get("duplicate_audio_triplet", False) + super().set_gguf_parameters() + self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.HIGGS_AUDIO) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, _ = item + if not name.startswith(("audio_tower.", "audio_encoder_proj.")): + return None + return super().filter_tensors(item) diff --git a/conversion/inkling2.py b/conversion/inkling2.py new file mode 100644 index 000000000000..a8e8b892ed72 --- /dev/null +++ b/conversion/inkling2.py @@ -0,0 +1,331 @@ +from __future__ import annotations + +import json +import re +from pathlib import Path +from functools import partial +from typing import Callable, Iterable, TYPE_CHECKING, cast + +import numpy as np +import torch + +if TYPE_CHECKING: + from torch import Tensor + +from .base import LazyTorchTensor, ModelBase, MmprojModel, TextModel, gguf, logger + + +def _e4m3_table() -> np.ndarray: + codes = np.arange(256, dtype=np.uint8) + exponent = ((codes & 0x7F) >> 3).astype(np.int32) + mantissa = (codes & 7).astype(np.float32) + values = np.where(exponent == 0, np.ldexp(mantissa, -9), np.ldexp(1 + mantissa / 8, exponent - 7)) + values = np.where(codes & 0x80, -values, values) + values[(codes & 0x7F) == 0x7F] = np.nan + return values.astype(np.float32) + + +_E4M3 = _e4m3_table() +_E2M1 = np.array([0, 0.5, 1, 1.5, 2, 3, 4, 6, -0.0, -0.5, -1, -1.5, -2, -3, -4, -6], dtype=np.float32) +_EXPERT_CHUNK_ROWS = 128 + + +def _dequant_expert_chunk(weight: Callable[[], Tensor], scale: Callable[[], Tensor], amax: Callable[[], Tensor] | None, denominator: Callable[[], Tensor] | None, name: str, expert: int, rows: slice) -> np.ndarray: + # Fresh lazy tensors release their mappings after each chunk instead of caching the layer. + packed = LazyTorchTensor.to_eager(weight().view(torch.uint8)[expert, rows]).numpy() + scales = LazyTorchTensor.to_eager(scale().view(torch.uint8)[expert, rows]).numpy() + if amax is not None: + block_scale = _E4M3[scales] + if np.isnan(block_scale).any(): + raise ValueError(f"Inkling2: {name}_scale expert {expert}: E4M3FN NaN") + values = np.empty((packed.shape[0], packed.shape[1] * 2), dtype=np.float32) + values[:, 0::2] = _E2M1[packed & 15] + values[:, 1::2] = _E2M1[packed >> 4] + values.reshape(values.shape[0], -1, 16)[:] *= block_scale[:, :, None] + assert denominator is not None + a = LazyTorchTensor.to_eager(amax()[expert]).item() + d = LazyTorchTensor.to_eager(denominator()).item() + if not np.isfinite(a) or a < 0: + raise ValueError(f"Inkling2: {name}_amax expert {expert}: expected finite nonnegative value") + if not np.isfinite(d) or d <= 0: + raise ValueError(f"Inkling2: {name}_outer_scale_denominator expert {expert}: expected finite positive value") + with np.errstate(over="ignore", invalid="ignore"): + values *= np.float32(a) / np.float32(d) + else: + if np.any(scales == 255): + raise ValueError(f"Inkling2: {name}_scale expert {expert}: UE8M0 byte 255 is NaN") + values = _E4M3[packed] + if np.isnan(values).any(): + raise ValueError(f"Inkling2: {name} expert {expert}: E4M3FN NaN") + block_scale = np.ldexp(np.ones(scales.shape, dtype=np.float32), scales.astype(np.int32) - 127) + with np.errstate(over="ignore", invalid="ignore"): + values.reshape(values.shape[0], -1, 32)[:] *= block_scale[:, :, None] + if not np.isfinite(values).all(): + raise ValueError(f"Inkling2: {name} expert {expert}: non-finite dequantized weight") + return values + + +def _is_inkling2(dir_model: Path) -> bool: + if not (dir_model / "config.json").is_file(): + return False + with open(dir_model / "config.json", encoding="utf-8") as f: + return json.load(f).get("model_type") in ("inkling2", "inkling2_text") + + +@ModelBase.register_hparams_loader(_is_inkling2) +def _load_inkling2_hparams(dir_model: Path): + # AutoConfig injects MXFP8 defaults and can replace the original layer schedule. + with open(dir_model / "config.json", encoding="utf-8") as f: + return json.load(f) + + +@ModelBase.register("Inkling2ForConditionalGeneration", "Inkling2ForCausalLM") +@ModelBase.example("thinkingmachines/Inkling-2-Small") +class Inkling2Model(TextModel): + model_arch = gguf.MODEL_ARCH.INKLING2 + + def __init__(self, dir_model: Path, *args, **kwargs): + self._expert_quant: dict[str, dict] = {} + self._packed_experts: dict[str, gguf.LazyChunkedTensor] = {} + quant_path = dir_model / "hf_quant_config.json" + if quant_path.is_file(): + with open(quant_path, encoding="utf-8") as f: + groups = json.load(f).get("model", {}).get("parameter_groups", []) + for group in groups: + for name in group.get("tensors", []): + item = self.filter_tensors((name, lambda: torch.empty(0))) + if item is not None and item[0].endswith((".w13_weight", ".w2_weight")): + name = item[0] + if name in self._expert_quant: + raise ValueError(f"Inkling2: duplicate hf_quant_config.json scheme for {name}") + self._expert_quant[name] = group + super().__init__(dir_model, *args, **kwargs) + logger.warning("Inkling2: converting the text backbone only; vision and MTP tensors are skipped") + hp = self.hparams + for name, default in (("q_bias", False), ("o_bias", False), ("n_shared_experts", 0), ("use_value_norm_no_gamma", True), ("attn_res_normalize_values", True), ("scoring_func", "sigmoid")): + if hp.get(name, default) != default: + raise ValueError(f"Inkling2: unsupported {name}={hp[name]!r}") + types = hp.get("layer_types") + if types is None: + local = hp["local_layer_ids"] + types = ["hybrid_sliding" if i in local else "hybrid" for i in range(self.block_count)] + if len(types) != self.block_count or set(types) - {"hybrid", "hybrid_sliding"}: + raise ValueError("Inkling2: invalid layer_types") + self.is_swa = [t == "hybrid_sliding" for t in types] + + def dequant_model(self): + for name in list(self.model_tensors): + if not name.endswith((".w13_weight", ".w2_weight")): + continue + weight = self.model_tensors[name] + tensor = weight() + companions = [name + suffix for suffix in ("_scale", "_amax", "_outer_scale_denominator")] + if tensor.dtype.is_floating_point and tensor.element_size() > 1: + if any(n in self.model_tensors for n in companions): + raise ValueError(f"Inkling2: floating-point {name} has packed quantization companions") + continue + config = self._expert_quant.get(name, {}) + scheme = config.get("weight_transform") + if scheme not in ("nvfp4_nearest", "mxfp8_nearest"): + raise ValueError(f"Inkling2: {name}: missing or unsupported hf_quant_config.json scheme {scheme!r}") + nvfp4 = scheme == "nvfp4_nearest" + if nvfp4 and config.get("weight_scale_format") != "amax_denominator": + raise ValueError(f"Inkling2: {name}: expected NVFP4 amax_denominator scale format") + required = companions if nvfp4 else companions[:1] + for companion in required: + if companion not in self.model_tensors: + raise ValueError(f"Inkling2: {name}: missing companion {companion}") + if not nvfp4 and any(n in self.model_tensors for n in companions[1:]): + raise ValueError(f"Inkling2: {name}: MXFP8 must not have amax or outer_scale_denominator") + scale = self.model_tensors[companions[0]] + scale_tensor = scale() + weight_dtype, scale_dtype = (torch.uint8, torch.float8_e4m3fn) if nvfp4 else (torch.float8_e4m3fn, torch.uint8) + if tensor.dtype != weight_dtype or scale_tensor.dtype != scale_dtype: + raise ValueError(f"Inkling2: {name}: expected {weight_dtype} weights and {scale_dtype} scales, got {tensor.dtype} and {scale_tensor.dtype}") + experts = self.hparams["n_routed_experts"] + hidden = self.hparams["hidden_size"] + inter = self.find_hparam(["moe_intermediate_size", "intermediate_size"]) + w13 = name.endswith(".w13_weight") + rows, cols = (2 * inter, hidden) if w13 else (hidden, inter) + shape = (experts, rows, cols) + if min(shape) <= 0 or cols % (16 if nvfp4 else 32) or tuple(tensor.shape) != (experts, rows, cols // (2 if nvfp4 else 1)): + raise ValueError(f"Inkling2: {name}: invalid packed shape {tuple(tensor.shape)} for logical shape {shape}") + ss = tuple(scale_tensor.shape) + if len(ss) != 3 or ss[0] != experts or min(ss) <= 0 or rows % ss[1] or cols % ss[2]: + raise ValueError(f"Inkling2: {name}_scale: shape {ss} does not divide logical shape {shape}") + block = (rows // ss[1], cols // ss[2]) + if block != (1, 16 if nvfp4 else 32): + raise ValueError(f"Inkling2: {name}_scale: unsupported stored block shape {block}") + if list(block) != config.get("weight_block_shape"): + logger.warning("Inkling2: %s: hf_quant_config.json weight_block_shape %s conflicts with stored weight/scale shapes %s/%s; using %s", name, config.get("weight_block_shape"), tuple(tensor.shape), ss, list(block)) + amax = denominator = None + if nvfp4: + amax, denominator = (self.model_tensors[n] for n in companions[1:]) + for companion, gen, expected in ((companions[1], amax, (experts,)), (companions[2], denominator, (1,))): + t = gen() + if t.dtype != torch.float32 or tuple(t.shape) != expected: + raise ValueError(f"Inkling2: {companion}: expected F32 {expected}, got {t.dtype} {tuple(t.shape)}") + chunks: list[Callable[[], np.ndarray]] = [] + for expert in range(experts): + for half in range(2 if w13 else 1): + for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS): + stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows) + # The same packed row slice selects the weight and its scale groups. + row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop) + chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice)) + self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32) + self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta") + for companion in required: + del self.model_tensors[companion] + for name, gen in self.model_tensors.items(): + t = gen() + if not t.dtype.is_floating_point or t.element_size() == 1 or name.endswith(("_weight_scale", "_weight_amax", "_weight_outer_scale_denominator")): + raise ValueError(f"Inkling2: unexpected packed tensor or orphan companion {name}") + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + if any(p in name for p in ("visual.", "vision_tower.", "mtp.", "markov_head", "nextn_predict")): + return None + name = name.replace("model.language_model.", "model.").replace("model.llm.", "model.") + # the mapping table cannot shift a block index: attn_queries.{i} feeds block i + 1 + name = re.sub(r"attn_res\.attn_queries\.(\d+)", lambda m: f"layers.{int(m[1]) + 1}.attention_input.query", name) + # the table maps a module, not its bias: gate.weight is the router, gate.bias the score correction + name = name.replace("mlp.gate.bias", "mlp.gate.e_score_correction_bias") + return name, gen + + def get_vocab_base(self): + tokens, types, pre = super().get_vocab_base() + n = self.hparams["unpadded_vocab_size"] + return tokens[:n], types[:n], pre + + def set_vocab(self): + tokens, types, pre = self.get_vocab_base() + self.gguf_writer.add_tokenizer_model("gpt2") + self.gguf_writer.add_tokenizer_pre(pre) + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_types(types) + special = gguf.SpecialVocab(self.dir_model, load_merges=True) + eos = self.hparams["eos_token_id"] + special.special_token_ids["eos"] = eos + special.special_token_ids["eot"] = eos + special.add_special_token["bos"] = False + special.add_to_gguf(self.gguf_writer) + + def set_gguf_parameters(self): + hp = self.hparams + hp["num_attention_heads"] = [hp.get("swa_num_attention_heads", hp["num_attention_heads"]) if s else hp["num_attention_heads"] for s in self.is_swa] + hp["num_key_value_heads"] = [hp.get("swa_num_key_value_heads", hp["num_key_value_heads"]) if s else hp["num_key_value_heads"] for s in self.is_swa] + for name in ("n_routed_experts", "num_experts_per_tok"): + if name not in hp: + raise KeyError(f"Inkling2: missing {name}") + super().set_gguf_parameters() + w = self.gguf_writer + w.add_vocab_size(hp["vocab_size"]) + w.add_vocab_size_unpadded(hp["unpadded_vocab_size"]) + w.add_expert_feed_forward_length(self.find_hparam(["moe_intermediate_size", "intermediate_size"])) + w.add_key_length_swa(hp.get("swa_head_dim", hp["head_dim"])) + w.add_value_length_swa(hp.get("swa_head_dim", hp["head_dim"])) + w.add_rope_dimension_count(0) + w.add_sliding_window(hp["sliding_window_size"]) + w.add_sliding_window_pattern(self.is_swa) + w.add_shortconv_l_cache(self.find_hparam(["conv_kernel_size", "sconv_kernel_size"])) + w.add_expert_weights_scale(hp["route_scale"]) + w.add_activation_situ_beta(hp["mlp_gate_softcap"]) + w.add_activation_situ_linear_beta(hp["mlp_up_softcap"]) + w.add_attn_res_block_size(hp["n_layers_per_attn_res_block"]) + w.add_final_logit_softcapping(hp["final_logit_softcapping"]) + w.add_relative_length(hp["d_rel"]) + w.add_relative_extent(hp["rel_extent"]) + w.add_qk_clip(hp["qk_l2_clip_threshold"]) + w.add_relative_clip(hp["rel_l2_clip_threshold"]) + w.add_log_scale_floor(hp["log_scaling_n_floor"]) + w.add_log_scale_alpha(hp["log_scaling_alpha"]) + + def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool: + if new_name.endswith(("_conv.weight", "_clip.weight", "_res_query.weight", "attn_rel_bias.weight")): + return gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + if name in self._packed_experts: + target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj") + yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name]) + return + if name.endswith(".w13_weight"): + shape = data_torch.shape + data_torch = data_torch.reshape(shape[0], shape[1] // 2, 2, shape[2]).transpose(1, 2).reshape(shape) + name = name.replace(".w13_weight", ".gate_up_proj") + name = name.replace(".w2_weight", ".down_proj") + for static, conv in ((".static_weight", ".conv1d.weight"), (".static_w", ".weight")): + if name.endswith(static): + data_torch = data_torch.flip(0).T.contiguous() + name = name.removesuffix(static) + conv + if name.endswith((".conv1d.weight", "sconv.weight")): + data_torch = data_torch.squeeze(1) if data_torch.ndim == 3 else data_torch + elif name.endswith(".rel_logits_proj.proj"): + data_torch = data_torch.T.contiguous() + # a name the table maps without a suffix is a bare parameter + new_name = self.tensor_map.get_name(name) + if new_name is not None: + suffix = ".bias" if name.endswith(".e_score_correction_bias") else ".weight" + yield new_name + suffix, data_torch + else: + yield from super().modify_tensors(data_torch, name, bid) + + +@ModelBase.register("Inkling2ForConditionalGeneration") +class Inkling2VisionModel(MmprojModel): + def get_vision_config(self): + config = self.global_config.get("vision_config") + if not config: + return None + config = dict(config) + config["patch_size"] = config.get("native_patch_size", config.get("patch_size", 20)) + config["spatial_merge_size"] = config.get("adapter_merge_size", config.get("spatial_merge_size", 2)) + config["intermediate_size"] = config.get("intermediate_size") or int(config["hidden_size"] * config.get("mlp_ratio", 4.0)) + config["image_size"] = config["posemb_grid_size"] * config["patch_size"] + if config.get("num_channels", 3) != 3 or config.get("hidden_act", "gelu") != "gelu": + raise ValueError("Inkling2 vision requires RGB patches and exact GELU") + return config + + def set_gguf_parameters(self): + self.preprocessor_config.setdefault("image_mean", [0.5, 0.5, 0.5]) + self.preprocessor_config.setdefault("image_std", [0.5, 0.5, 0.5]) + super().set_gguf_parameters() + config = self.hparams + rope = config.get("rope_parameters") or {"rope_type": "axial", "rope_theta": 10000.0} + if rope["rope_type"] != "axial" or rope["rope_theta"] != 10000.0: + raise ValueError("Inkling2 vision requires axial RoPE with theta 10000") + w = self.gguf_writer + w.add_clip_vision_projector_type(gguf.VisionProjectorType.INKLING2V) + w.add_vision_attention_layernorm_eps(config["layer_norm_eps"]) + w.add_vision_spatial_merge_size(config["spatial_merge_size"]) + + def dequant_model(self): + # vision tensors are BF16, only the text experts are quantized + return + + @classmethod + def filter_tensors(cls, item): + name, gen = item + if not name.startswith(("model.visual.", "model.vision_tower.")): + return None + return name, gen + + # mm.{bid} takes the projector layer index, the mapping table cannot derive it from these names + _projector_layers = {"model.visual.proj_in": 1, "model.visual.proj_out": 2, "model.vision_tower.merger.linear_1": 1, "model.vision_tower.merger.linear_2": 2} + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + module, _, suffix = name.rpartition(".") + if module in self._projector_layers: + yield self.format_tensor_name(gguf.MODEL_TENSOR.V_MMPROJ, self._projector_layers[module], "." + suffix), data_torch + return + # lay out the linear patch embedding (HWC patches) as a conv2d for build_inp() + if name.endswith(".patch_embedding.weight"): + ps = self.hparams["patch_size"] + data_torch = data_torch.reshape(data_torch.shape[0], ps, ps, 3).permute(0, 3, 1, 2) + # these are bare parameters, they have no .weight + if name.endswith(("position_embedding", ".lambda_1", ".lambda_2", ".gamma")): + name = name.removesuffix(".gamma") + ".weight" + yield from super().modify_tensors(data_torch, name, bid) diff --git a/conversion/kokoro.py b/conversion/kokoro.py new file mode 100644 index 000000000000..945eccdaa271 --- /dev/null +++ b/conversion/kokoro.py @@ -0,0 +1,419 @@ +from __future__ import annotations + +import importlib +import importlib.util +import json +import math +import re +from collections import Counter, defaultdict +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path +from typing import Any, Callable, Iterable + +import torch +from torch import Tensor + +from .base import ModelBase, TextModel, MmprojModel, gguf, logger + +# Kokoro (StyleTTS2 with an iSTFTNet decoder), https://huggingface.co/hexgrad/Kokoro-82M +# text model: the PL-BERT phoneme encoder (ALBERT), one token per phoneme character +# mmproj: bert_encoder, prosody predictor, text encoder, decoder and the voices +# the text to phonemes step is the "tts" chat template, its dictionaries come from the misaki and nltk python packages + +DEFAULT_VOICE = "af_heart" + +MODULE_PREFIX = { + "bert_encoder": "a.gen.bert_enc.", + "predictor": "a.gen.pred.", + "text_encoder": "a.gen.text.", + "decoder": "a.gen.dec.", +} + + +def _checkpoint(dir_model: Path) -> Path | None: + paths = sorted(dir_model.glob("kokoro-*.pth")) + return paths[0] if paths else None + + +def _is_kokoro_checkpoint(dir_model: Path) -> bool: + if _checkpoint(dir_model) is None or not (dir_model / "config.json").is_file(): + return False + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) + return "plbert" in config and "istftnet" in config and "vocab" in config + + +@ModelBase.register_hparams_loader(_is_kokoro_checkpoint) +def _load_kokoro_hparams(dir_model: Path) -> dict[str, Any]: + logger.info("gguf: detected Kokoro checkpoint") + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) + plbert = config["plbert"] + return { + "architectures": ["KokoroModel"], + "model_type": "kokoro", + "num_hidden_layers": plbert["num_hidden_layers"], + "hidden_size": plbert["hidden_size"], + "intermediate_size": plbert["intermediate_size"], + "num_attention_heads": plbert["num_attention_heads"], + "max_position_embeddings": plbert["max_position_embeddings"], + "vocab_size": config["n_token"], + "layer_norm_eps": 1e-12, # AlbertConfig default + "kokoro": config, + # the mmproj tensors are named explicitly, they do not go through the block tensor map + "audio_config": {"num_hidden_layers": 0}, + } + + +def _load_modules(dir_model: Path, modules: Iterable[str]) -> dict[str, dict[str, Tensor]]: + path = _checkpoint(dir_model) + assert path is not None + state = torch.load(path, map_location="cpu", mmap=True, weights_only=True) + # every module was saved from a DataParallel wrapper + return {m: {k.removeprefix("module."): v for k, v in state[m].items()} for m in modules} + + +def _g2p_fallback(lexicons: list[dict[str, Any]]) -> dict[str, Any]: + # model for the words missing from the lexicon: n-grams over units "letter:sounds", learned from the lexicon + # key "<0 to 4 units before> " -> {sounds: probability}; "" pads the start of a word, the letter "$" is its end + # the "tts" template decodes it with a beam search + order, min_count, stress = 5, 3, "\u02c8\u02cc" + vowels = set("AIOQWYaiu\u00e6\u0251\u0252\u0254\u0259\u025b\u025c\u026a\u028a\u028c\u1d7b\u1d4a") + + def sounds(ps: str) -> list[str]: + # a stress mark goes with the sound after it, a length mark with the one before + out: list[str] = [] + pre = "" + for c in ps: + if c in stress: + pre += c + elif c == "\u02d0" and out: + out[-1] += c + else: + out.append(pre + c) + pre = "" + return out + + def penalty(letter: str, chunk: str) -> float: + # a consonant letter says consonants only; a vowel letter says a vowel, with at most a glide + flat = [c for c in chunk if c not in stress and c != "\u02d0"] + n_vowel = sum(c in vowels for c in flat) + if letter in "bcdfgjkmnpqstvxz" and n_vowel > 0: + return -8.0 + if letter in "aeiou" and flat and (n_vowel == 0 or any(c not in vowels and c not in "jw" for c in flat)): + return -8.0 + return 0.0 + + words: dict[str, list[str]] = {} + for lexicon in lexicons: + for word, v in lexicon.items(): + ps = v["DEFAULT"] if isinstance(v, dict) else v + # same spelling normalization as the template: doubled consonants and "ck" say one sound + w = re.sub(r"([b-df-hj-np-tv-z])\1", r"\1", word.lower()).replace("ck", "k") + if ps and " " not in ps and len(w) >= 2 and re.fullmatch(r"[a-z']+", w) and w not in words: + t = sounds(ps) + if len(t) <= 2 * len(w): + words[w] = t + + def align(w: str, t: list[str], cost: dict[str, dict[str, float]]) -> list[str] | None: + # best split of the sounds over the letters, each letter takes 0, 1 or 2 of them + n_l, n_t = len(w), len(t) + two = [t[j] + t[j + 1] for j in range(n_t - 1)] + best = [[-1e18] * (n_t + 1) for _ in range(n_l + 1)] + back = [[0] * (n_t + 1) for _ in range(n_l + 1)] + best[0][0] = 0.0 + for i in range(n_l): + letter = w[i] + row = cost.setdefault(letter, {}) + cur, nxt, bk = best[i], best[i + 1], back[i + 1] + # the sounds left must fit in the letters left + for j in range(max(0, n_t - 2 * (n_l - i)), n_t + 1): + base = cur[j] + if base < -1e17: + continue + for k, chunk in ((0, ""), (1, t[j] if j < n_t else None), (2, two[j] if j + 1 < n_t else None)): + if chunk is None: + break + c = row.get(chunk) + if c is None: + # not seen yet for this letter + c = row[chunk] = -12.0 + penalty(letter, chunk) + if base + c > nxt[j + k]: + nxt[j + k] = base + c + bk[j + k] = k + if best[n_l][n_t] < -1e17: + return None + out: list[str] = [] + j = n_t + for i in range(n_l, 0, -1): + k = back[i][j] + out.append("".join(t[j - k:j])) + j -= k + return out[::-1] + + # hard EM: align with the current letter -> sounds costs, count, repeat + # the costs are learned on a sample of the words, then every word is aligned once + def step(items: Iterable[tuple[str, list[str]]], cost: dict[str, dict[str, float]]) -> list[tuple[str, list[str]]]: + return [(w, a) for w, a in ((w, align(w, t, cost)) for w, t in items) if a is not None] + + sample = list(words.items())[::max(1, len(words) // 20000)] + cost: dict[str, dict[str, float]] = {} + for _ in range(5): + counts: dict[str, Counter[str]] = defaultdict(Counter) + for w, a in step(sample, cost): + for c, o in zip(w, a): + counts[c][o] += 1 + # small cost for a silent letter, so that a sound stays on its own letter + cost = {c: {o: math.log(n / sum(cnt.values())) - (0.5 if o == "" else 0.0) + penalty(c, o) for o, n in cnt.items()} + for c, cnt in counts.items()} + aligned = step(words.items(), cost) + + # counts of a unit after each of its contexts, from 4 units down to none + ngram: dict[str, Counter[str]] = defaultdict(Counter) + n_ctx: Counter[str] = Counter() + for w, a in aligned: + units = [""] * (order - 1) + [c + ":" + o for c, o in zip(w, a)] + ["$:"] + for i in range(order - 1, len(units)): + letter, _, o = units[i].partition(":") + for n in range(order): + ctx = " ".join(units[i - n:i]) + ngram[(ctx + " " if ctx else "") + letter][o] += 1 + n_ctx[ctx] += 1 + + # the probability is over all the units after the context, not only the ones of this letter + # this tells the search how likely the letter is after the sounds it chose, so it can drop a bad choice + model: dict[str, Any] = {} + for key, cnt in ngram.items(): + ctx, _, letter = key.rpartition(" ") + # the two shortest contexts keep all the readings that the letter has min_count times or more + kept = {o: float(f"{n / n_ctx[ctx]:.4g}") for o, n in cnt.most_common() + if n >= min_count or (key.count(" ") < 2 and ngram[letter][o] >= min_count)} + if kept: + model[key] = kept + return model + + +def _g2p_dicts() -> dict[str, dict[str, Any]] | None: + # dictionaries of the "tts" template: the misaki lexicon and the nltk averaged perceptron tagger + spec = importlib.util.find_spec("misaki") + if spec is None or spec.origin is None: + logger.warning("misaki is not installed, the model will take phonemes as prompt (pip install misaki nltk)") + return None + data = Path(spec.origin).parent / "data" + try: + nltk = importlib.import_module("nltk") + base = Path(str(nltk.data.find("taggers/averaged_perceptron_tagger_eng"))) / "averaged_perceptron_tagger_eng" + except (ImportError, LookupError): + logger.warning("the nltk tagger is not available, the model will take phonemes as prompt " + "(pip install nltk && python -m nltk.downloader averaged_perceptron_tagger_eng)") + return None + + def load(path: Path) -> Any: + with open(path, encoding="utf-8") as f: + return json.load(f) + + # tagger: classes sorted by label, feature -> {"c": weight} + # (index keys: jinja2's map(attribute=...) splits on "." and some labels are punctuation) + classes = sorted(load(Path(f"{base}.classes.json"))) + cid = {c: f"c{i}" for i, c in enumerate(classes)} + weights = load(Path(f"{base}.weights.json")) + lex = { + "gold": load(data / "us_gold.json"), + "silver": load(data / "us_silver.json"), + "gold_gb": load(data / "gb_gold.json"), + "silver_gb": load(data / "gb_silver.json"), + } + logger.info("gguf: learning the pronunciation of unknown words from the lexicon, this takes a few minutes") + # one process per variant + with ProcessPoolExecutor(max_workers=2) as pool: + lts, lts_gb = pool.map(_g2p_fallback, [[lex["gold"], lex["silver"]], [lex["gold_gb"], lex["silver_gb"]]]) + return { + **lex, + "lts": lts, + "lts_gb": lts_gb, + "pos_weights": {f: {cid[t]: w for t, w in tw.items()} for f, tw in weights.items()}, + "pos_tagdict": load(Path(f"{base}.tagdict.json")), + "pos_classes": {"": classes}, + } + + +@ModelBase.register("KokoroModel") +@ModelBase.example("hexgrad/Kokoro-82M") +class KokoroTextModel(TextModel): + model_arch = gguf.MODEL_ARCH.KOKORO + + _LAYER = "encoder.albert_layer_groups.0.albert_layers.0." + _TENSOR_MAP = { + "embeddings.LayerNorm": gguf.MODEL_TENSOR.TOKEN_EMBD_NORM, + "encoder.embedding_hidden_mapping_in": gguf.MODEL_TENSOR.TOKEN_EMBD_PROJ, + } + # the layers share their weights, stored as block 0 + _LAYER_TENSOR_MAP = { + "attention.query": gguf.MODEL_TENSOR.ATTN_Q, + "attention.key": gguf.MODEL_TENSOR.ATTN_K, + "attention.value": gguf.MODEL_TENSOR.ATTN_V, + "attention.dense": gguf.MODEL_TENSOR.ATTN_OUT, + "attention.LayerNorm": gguf.MODEL_TENSOR.ATTN_OUT_NORM, + "ffn": gguf.MODEL_TENSOR.FFN_UP, + "ffn_output": gguf.MODEL_TENSOR.FFN_DOWN, + "full_layer_layer_norm": gguf.MODEL_TENSOR.LAYER_OUT_NORM, + } + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + del remote_hf_model_id + bert = _load_modules(self.dir_model, ["bert"])["bert"] + return {name: (lambda t=t: t) for name, t in bert.items()} + + def set_vocab(self): + config = self.hparams["kokoro"] + n_vocab = config["n_token"] + tokens: list[str] = [f"[UNUSED_{i}]" for i in range(n_vocab)] + toktypes = [gguf.TokenType.UNUSED] * n_vocab + for text, i in config["vocab"].items(): + tokens[i] = text + toktypes[i] = gguf.TokenType.NORMAL + # id 0 pads both ends of the phoneme sequence + tokens[0] = "" + toktypes[0] = gguf.TokenType.CONTROL + + # the phonemes are mapped to tokens one character at a time by the audio pipeline + self.gguf_writer.add_tokenizer_model("llama") + self.gguf_writer.add_tokenizer_pre("default") + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_scores([0.0] * n_vocab) + self.gguf_writer.add_token_types(toktypes) + self.gguf_writer.add_bos_token_id(0) + self.gguf_writer.add_eos_token_id(0) + self.gguf_writer.add_pad_token_id(0) + self.gguf_writer.add_add_bos_token(False) + self.gguf_writer.add_add_eos_token(False) + + dicts = _g2p_dicts() + if dicts is not None: + template_path = Path(__file__).parent.parent / "models" / "templates" / "hexgrad-Kokoro-82M-tts.jinja" + with open(template_path, encoding="utf-8") as f: + self.gguf_writer.add_chat_template([{"name": "tts", "template": f.read()}]) + self.gguf_writer.add_tts_dicts(dicts) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_causal_attention(False) + self.gguf_writer.add_pooling_type(gguf.PoolingType.NONE) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + n_embd = self.hparams["hidden_size"] + + if name == "embeddings.word_embeddings.weight": + # zero-pad the rows to n_embd, llama.cpp wants token and embedding inputs of the same width + data_torch = torch.nn.functional.pad(data_torch, (0, n_embd - data_torch.shape[1])) + yield (self.format_tensor_name(gguf.MODEL_TENSOR.TOKEN_EMBD), data_torch) + return + if name == "embeddings.position_embeddings.weight": + # every token has type 0, fold its embedding into the positions + type0 = self.model_tensors["embeddings.token_type_embeddings.weight"]()[0] + yield (self.format_tensor_name(gguf.MODEL_TENSOR.POS_EMBD), data_torch + type0) + return + if name.startswith(("embeddings.token_type_embeddings.", "pooler.")): + return + + key, suffix = name.rsplit(".", 1) + if key in self._TENSOR_MAP: + yield (self.format_tensor_name(self._TENSOR_MAP[key], suffix="." + suffix), data_torch) + return + if key.startswith(self._LAYER): + tensor = self._LAYER_TENSOR_MAP[key.removeprefix(self._LAYER)] + yield (self.format_tensor_name(tensor, 0, suffix="." + suffix), data_torch) + return + raise ValueError(f"unexpected tensor {name}") + + +@ModelBase.register("KokoroModel") +@ModelBase.example("hexgrad/Kokoro-82M") +class KokoroMmprojModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = False + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._wnorm_g: dict[str, Tensor] = {} + self._wnorm_v: dict[str, Tensor] = {} + self._lstm_bias: dict[str, Tensor] = {} + + def get_audio_config(self) -> dict[str, Any] | None: + return self.global_config.get("audio_config") + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + del remote_hf_model_id + tensors: dict[str, Callable[[], Tensor]] = {} + for module, state in _load_modules(self.dir_model, MODULE_PREFIX.keys()).items(): + for name, t in state.items(): + tensors[MODULE_PREFIX[module] + name] = (lambda t=t: t) + return tensors + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + # the names are final already + return item + + def set_gguf_parameters(self): + config = self.global_config["kokoro"] + self.gguf_writer.add_file_type(self.ftype) + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.KOKORO) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(config["hidden_dim"]) + self.gguf_writer.add_gen_audio_feed_forward_length(config["hidden_dim"]) + self.gguf_writer.add_gen_audio_block_count(config["n_layer"]) + self.gguf_writer.add_gen_audio_head_count(1) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-5) + if (self.dir_model / "voices" / f"{DEFAULT_VOICE}.pt").is_file(): + self.gguf_writer.add_gen_audio_default_voice(DEFAULT_VOICE) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + # torch weight_norm: weight = g * v / |v| over dims 1..n + if name.endswith((".weight_g", ".weight_v")): + base = name[:-len(".weight_g")] + (self._wnorm_g if name.endswith("_g") else self._wnorm_v)[base] = data_torch + if base in self._wnorm_g and base in self._wnorm_v: + g = self._wnorm_g.pop(base).float() + v = self._wnorm_v.pop(base).float() + w = g * v / v.norm(dim=tuple(range(1, v.dim())), keepdim=True) + if base.endswith(".pool"): + # depthwise transposed conv [C, 1, 3], stored as one row per tap + w = w.squeeze(1).T.contiguous() + yield (base + ".weight", w) + return + # the two LSTM biases are always added + if ".bias_ih_l0" in name or ".bias_hh_l0" in name: + base = name.replace(".bias_ih_l0", ".bias_l0").replace(".bias_hh_l0", ".bias_l0") + if base in self._lstm_bias: + yield (base, self._lstm_bias.pop(base).float() + data_torch.float()) + else: + self._lstm_bias[base] = data_torch + return + # snake alphas are per channel + if ".alpha1." in name or ".alpha2." in name: + data_torch = data_torch.reshape(-1) + yield (name, data_torch) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + del name, bid + # tensors read on the host stay F32 + if "lstm" in new_name or ".shared." in new_name or new_name.startswith(("a.gen.bert_enc.", "voice.")) \ + or ".duration_proj." in new_name or ".m_source." in new_name or ".pool." in new_name: + return gguf.GGMLQuantizationType.F32 + # CONV_TRANSPOSE_1D takes only F32 weights on some backends + if ".ups." in new_name: + return gguf.GGMLQuantizationType.F32 + # the conv ops have no BF16 kernels + if n_dims >= 2: + return gguf.GGMLQuantizationType.F16 + return gguf.GGMLQuantizationType.F32 + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + # a voice is a table of style vectors, the row is picked by the number of phonemes + for path in sorted((self.dir_model / "voices").glob("*.pt")): + pack = torch.load(path, map_location="cpu", weights_only=True) + yield (f"voice.{path.stem}", pack.squeeze(1).float()) diff --git a/conversion/minimax.py b/conversion/minimax.py index 4d856fab855f..c9f512f5fa6f 100644 --- a/conversion/minimax.py +++ b/conversion/minimax.py @@ -1,5 +1,7 @@ from __future__ import annotations +import json + from typing import Iterable, Sequence, TYPE_CHECKING import torch @@ -8,6 +10,7 @@ from torch import Tensor from .base import ModelBase, TextModel, MmprojModel, gguf, logger +from .qwen import DSparkModel @ModelBase.register("MiniMaxText01ForCausalLM") @@ -170,6 +173,15 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None): class MiniMaxM3Model(MiniMaxM2Model): model_arch = gguf.MODEL_ARCH.MINIMAXM3 + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # transformers 5.x folds sparse_attention_config and moe_layer_freq into other keys + with open(self.dir_model / "config.json", "r", encoding="utf-8") as f: + raw_hparams = json.load(f) + for key, value in raw_hparams.get("text_config", raw_hparams).items(): + self.hparams.setdefault(key, value) + def tensor_force_quant(self, name, new_name, bid, n_dims): if ".indexer." in new_name: return gguf.GGMLQuantizationType.F32 @@ -188,6 +200,7 @@ def set_gguf_parameters(self): self.gguf_writer.add_indexer_top_k(sac["sparse_topk_blocks"]) self.gguf_writer.add_indexer_block_size(sac["sparse_block_size"]) self.gguf_writer.add_indexer_local_blocks(sac["sparse_local_block"]) + self.gguf_writer.add_indexer_types([bool(v) for v in sac["sparse_attention_freq"]]) moe_layer_freq = self.find_hparam(["moe_layer_freq"]) n_dense = 0 @@ -201,7 +214,47 @@ def set_gguf_parameters(self): def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None): # Gemma-style (1 + w) RMSNorm: bake the +1 in so llama.cpp can use plain RMSNorm if name.endswith("norm.weight"): - data_torch = data_torch + 1.0 + data_torch = data_torch.float() + 1.0 + + yield from super().modify_tensors(data_torch, name, bid) + + +@ModelBase.register("DSparkMiniMaxDraftModel") +class MiniMaxM3DSparkModel(DSparkModel): + model_arch = gguf.MODEL_ARCH.DFLASH + + def __init__(self, dir_model, *args, **kwargs): + # transformers drops the draft keys when it parses the minimax_m3_vl config + with open(dir_model / "config.json", "r", encoding="utf-8") as f: + kwargs["hparams"] = json.load(f) + super().__init__(dir_model, *args, **kwargs) + + # draft layers use a dense FFN, the MoE keys are copied from the target config + self.hparams["intermediate_size"] = self.hparams["dspark_ffn_hidden_size"] + for key in ("num_local_experts", "num_experts_per_tok", "scoring_func"): + self.hparams.pop(key, None) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + + self.gguf_writer.add_hidden_act(self.hparams["hidden_act"]) + + layer_types = self.hparams["layer_types"] + self.gguf_writer.add_sliding_window(self.hparams["sliding_window"]) + self.gguf_writer.add_sliding_window_pattern([t == "sliding_attention" for t in layer_types]) + + @classmethod + def filter_tensors(cls, item): + name, gen = item + name = name.removeprefix("language_model.model.dspark.").replace(".decoder_layer.", ".") + if name == "final_norm.weight": + name = "norm.weight" + return super().filter_tensors((name, gen)) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None): + # Gemma-style (1 + w) RMSNorm, same as the target + if name.endswith("norm.weight"): + data_torch = data_torch.float() + 1.0 yield from super().modify_tensors(data_torch, name, bid) diff --git a/conversion/minimax_music3.py b/conversion/minimax_music3.py new file mode 100644 index 000000000000..2fbba8fab4a8 --- /dev/null +++ b/conversion/minimax_music3.py @@ -0,0 +1,285 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, Callable, Iterable, TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, MmprojModel, gguf +from .drama3 import fold_snake +from .qwen import Qwen3Model + +# MiniMax Music 3, diffusers layout: one checkpoint per component +# text model: the global LLM (language_model/), samples the semantic code of each frame +# mmproj: RVQ depth decoder, condition encoder, flow-matching DiT and DAC decoder (vocoder) + +LM_DIR = "language_model" +TOK_DIR = "tokenizer" +MMPROJ_DIRS = ("rvq_depth_decoder", "condition_encoder", "transformer", "vocoder") + +# token ids of the checkpoint, see encoders.py of the diffusers pipeline +AUDIO_START = 151669 +AUDIO_END = 151670 +AUDIO_CODE_OFFSET = 151675 +N_SEMANTIC = 16384 + + +def _load_hparams(dir_model: Path) -> dict[str, Any]: + return ModelBase.load_hparams(dir_model / LM_DIR, is_mistral_format=False) + + +def _index_dirs(model: ModelBase, dirs: Iterable[str], keep: Callable[[str], bool]) -> dict[str, Callable[[], Tensor]]: + # the names get the component dir as prefix + root = model.dir_model + tensors: dict[str, Callable[[], Tensor]] = {} + try: + for d in dirs: + model.dir_model = root / d + prefix = "model" if d == LM_DIR else "diffusion_pytorch_model" + for name, gen in model.index_local_tensors(prefix).items(): + if keep(f"{d}.{name}"): + tensors[f"{d}.{name}"] = gen + finally: + model.dir_model = root + return tensors + + +def _fold_wn(g: Tensor, v: Tensor) -> Tensor: + # torch weight norm, over every dim but 0 + g, v = g.float(), v.float() + return g * v / v.flatten(1).norm(dim=1).view(-1, *[1] * (v.dim() - 1)) + + +@ModelBase.register("MiniMaxMusic3ForConditionalGeneration") +class MiniMaxMusic3TextModel(Qwen3Model): + model_arch = gguf.MODEL_ARCH.QWEN3 + + def __init__(self, dir_model: Path, *args, **kwargs): + kwargs.pop("hparams", None) + super().__init__(dir_model, *args, hparams=_load_hparams(dir_model), **kwargs) + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + tensors = _index_dirs(self, [LM_DIR], lambda _: True) + return {name.removeprefix(LM_DIR + "."): gen for name, gen in tensors.items()} + + def set_gguf_parameters(self): + super().set_gguf_parameters() + # the codes are sampled with classifier-free guidance, the uncond prompt runs as a second sequence + self.gguf_writer.add_classifier_free_guidance(True) + + def set_vocab(self): + root = self.dir_model + self.dir_model = root / TOK_DIR + try: + tokens, toktypes, tokpre = self.get_vocab_base() + special_vocab = gguf.SpecialVocab(self.dir_model, load_merges=True) + finally: + self.dir_model = root + + # the semantic codes are not in the tokenizer, name them for debugging + for i in range(N_SEMANTIC): + tokens[AUDIO_CODE_OFFSET + i] = f"<|audio_code_{i}|>" + toktypes[AUDIO_CODE_OFFSET + i] = gguf.TokenType.CONTROL + + # the generation ends with <|audio_end|>, the chat template of the tokenizer is not used + template_path = Path(__file__).parent.parent / "models" / "templates" / "MiniMaxAI-MiniMax-Music3-tts.jinja" + with open(template_path, encoding="utf-8") as f: + special_vocab.chat_template = [{"name": "tts", "template": f.read()}] + special_vocab.special_token_ids["eos"] = AUDIO_END + + self.gguf_writer.add_tokenizer_model("gpt2") + self.gguf_writer.add_tokenizer_pre(tokpre) + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_types(toktypes) + special_vocab.add_to_gguf(self.gguf_writer) + + +@ModelBase.register("MiniMaxMusic3ForConditionalGeneration") +class MiniMaxMusic3MmprojModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = False + + def __init__(self, dir_model: Path, *args, **kwargs): + kwargs.pop("hparams", None) + hparams = ModelBase.load_hparams(dir_model, is_mistral_format=False) + hparams["text_config"] = _load_hparams(dir_model) + for d in MMPROJ_DIRS: + hparams[d] = ModelBase.load_hparams(dir_model / d, is_mistral_format=False) + super().__init__(dir_model, *args, hparams=hparams, **kwargs) + + def get_audio_config(self) -> dict[str, Any] | None: + # the generic gen layers are the depth decoder + return self.global_config["rvq_depth_decoder"] + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + # from the backbone, only the embeddings of the semantic codes + return _index_dirs(self, (LM_DIR, *MMPROJ_DIRS), + lambda name: not name.startswith(LM_DIR + ".") or name == f"{LM_DIR}.model.embed_tokens.weight") + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + return item + + def set_gguf_parameters(self): + hp = self.hparams + self.gguf_writer.add_file_type(self.ftype) + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.MINIMAX_MUSIC3_GEN) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(hp["hidden_size"]) + self.gguf_writer.add_gen_audio_feed_forward_length(hp["intermediate_size"]) + self.gguf_writer.add_gen_audio_block_count(hp["num_layers"]) + self.gguf_writer.add_gen_audio_head_count(hp["num_attention_heads"]) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-6) + # the DiT, the condition encoder and the vocoder hparams come from the tensor shapes or are hard-coded in tools/mtmd + + def tensor_force_quant(self, name, new_name, bid, n_dims): + # only the transformer layers follow --outtype, the convs and the small projections stay F32 + if n_dims >= 2 and new_name.startswith(("a.gen.code.blk.", "a.gen.flow.blk.")): + return super().tensor_force_quant(name, new_name, bid, n_dims) + if new_name.startswith(("a.gen.code.head", "a.gen.code.embd", "a.gen.code.out_embd", "a.gen.code.proj_in")): + return super().tensor_force_quant(name, new_name, bid, n_dims) + return gguf.GGMLQuantizationType.F32 + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + if name.startswith("a."): + yield (name, data_torch) + return + + comp, key = name.split(".", 1) + if comp == LM_DIR: + yield ("a.gen.code.out_embd.weight", data_torch[AUDIO_CODE_OFFSET:AUDIO_CODE_OFFSET + N_SEMANTIC]) + elif comp == "rvq_depth_decoder": + yield from self._depth(data_torch, key) + elif comp == "condition_encoder": + yield from self._cond(data_torch, key) + elif comp == "transformer": + yield from self._dit(data_torch, key) + # the vocoder is folded in generate_extra_tensors() + + def _depth(self, t: Tensor, key: str) -> Iterable[tuple[str, Tensor]]: + p = "a.gen.code" + n_cb = self.hparams["num_codebooks"] - 1 + if key == "audio_embeddings.weight": + # one table per residual codebook + yield (f"{p}.embd.weight", t.reshape(n_cb, -1, t.shape[-1])) + elif key.startswith("audio_heads."): + if key == "audio_heads.0.weight": + heads = [self._tensor(f"rvq_depth_decoder.audio_heads.{i}.weight") for i in range(n_cb)] + yield (f"{p}.head.weight", torch.stack(heads)) + elif key == "projection.weight": + yield (f"{p}.proj_in.weight", t) + elif key == "pos_embedding.weight": + yield (f"{p}.position_embd.weight", t) + elif key == "norm.weight": + yield (f"{p}.post_ln.weight", t) + else: + _, il, rest = key.split(".", 2) + layer = { + "input_layernorm.weight": "ln1.weight", + "attn.to_q.weight": "attn_q.weight", + "attn.to_k.weight": "attn_k.weight", + "attn.to_v.weight": "attn_v.weight", + "attn.to_out.weight": "attn_out.weight", + "post_attention_layernorm.weight": "ln2.weight", + "gate_proj.weight": "ffn_gate.weight", + "up_proj.weight": "ffn_up.weight", + "down_proj.weight": "ffn_down.weight", + } + yield (f"{p}.blk.{il}.{layer[rest]}", t) + + def _cond(self, t: Tensor, key: str) -> Iterable[tuple[str, Tensor]]: + p = "a.gen.cond" + if key == "layer_weight_logits": + # softmax mix of the 8 hidden states of a frame, with the scale folded in + scale = self._tensor("condition_encoder.layer_scale").float() + yield (f"{p}.layer_w", torch.softmax(t.float(), dim=0) * scale) + elif key == "proj.weight": + yield (f"{p}.proj.weight", t) + elif key == "proj.bias": + yield (f"{p}.proj.bias", t) + + def _dit(self, t: Tensor, key: str) -> Iterable[tuple[str, Tensor]]: + p = "a.gen.flow" + if key.startswith("transformer_blocks."): + _, il, rest = key.split(".", 2) + q = f"{p}.blk.{il}" + if rest.startswith("ff_in."): + # value half first, then the silu gate half + suffix = rest.removeprefix("ff_in.") + up, gate = t.chunk(2, dim=0) + yield (f"{q}.ffn_up.{suffix}", up) + yield (f"{q}.ffn_gate.{suffix}", gate) + return + layer = { + "norm1.weight": "ln1.weight", + "norm1.bias": "ln1.bias", + "attn.to_q.weight": "attn_q.weight", + "attn.to_k.weight": "attn_k.weight", + "attn.to_v.weight": "attn_v.weight", + "attn.to_out.0.weight": "attn_out.weight", + "norm2.weight": "ln2.weight", + "norm2.bias": "ln2.bias", + "ff_out.weight": "ffn_down.weight", + "ff_out.bias": "ffn_down.bias", + } + yield (f"{q}.{layer[rest]}", t) + return + if key == "time_proj.weight": + # random Fourier features, 2 * pi folded in + yield (f"{p}.time_freq", t.float().flatten() * 2.0 * torch.pi) + return + out = { + "time_embed.linear_1.weight": "time_in.weight", + "time_embed.linear_1.bias": "time_in.bias", + "time_embed.linear_2.weight": "time_out.weight", + "time_embed.linear_2.bias": "time_out.bias", + "preprocess_conv.weight": "pre.weight", + "proj_in.weight": "proj_in.weight", + "proj_out.weight": "proj_out.weight", + "postprocess_conv.weight": "post.weight", + }[key] + yield (f"{p}.{out}", t.squeeze(-1) if key.endswith("conv.weight") else t) + + def _tensor(self, name: str) -> Tensor: + # read directly, without the dtype handling of prepare_tensors() + return self.model_tensors[name]().float() + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + # DAC decoder, same layout as the yue2 VAE (a.gen.vae.*), with the snake and the weight norm folded + def get(key: str) -> Tensor: + return self._tensor(f"vocoder.{key}") + + def wn(key: str) -> Tensor: + return _fold_wn(get(key + ".weight_g"), get(key + ".weight_v")) + + def snake(dst: str, key: str) -> Iterable[tuple[str, Tensor]]: + a, b = fold_snake(get(key + ".alpha")) + yield (f"{dst}.alpha", a) + yield (f"{dst}.beta", b) + + p = "a.gen.vae" + yield (f"{p}.in_proj.weight", get("dec_in_proj.weight")) + yield (f"{p}.in_proj.bias", get("dec_in_proj.bias")) + yield (f"{p}.conv_in.weight", wn("conv_in")) + yield (f"{p}.conv_in.bias", get("conv_in.bias")) + n_blk = len(self.global_config["vocoder"]["upsampling_ratios"]) + for b in range(n_blk): + s = f"blocks.{b}" + yield from snake(f"{p}.blk.{b}.snake", f"{s}.snake1") + yield (f"{p}.blk.{b}.up.weight", wn(f"{s}.conv_t1")) + yield (f"{p}.blk.{b}.up.bias", get(f"{s}.conv_t1.bias")) + for r in range(3): + rs = f"{s}.res_unit{r + 1}" + yield from snake(f"{p}.blk.{b}.res.{r}.snake1", f"{rs}.snake1") + yield (f"{p}.blk.{b}.res.{r}.conv1.weight", wn(f"{rs}.conv1")) + yield (f"{p}.blk.{b}.res.{r}.conv1.bias", get(f"{rs}.conv1.bias")) + yield from snake(f"{p}.blk.{b}.res.{r}.snake2", f"{rs}.snake2") + yield (f"{p}.blk.{b}.res.{r}.conv2.weight", wn(f"{rs}.conv2")) + yield (f"{p}.blk.{b}.res.{r}.conv2.bias", get(f"{rs}.conv2.bias")) + yield from snake(f"{p}.post_snake", "snake_out") + yield (f"{p}.conv_out.weight", wn("conv_out")) + yield (f"{p}.conv_out.bias", get("conv_out.bias")) diff --git a/conversion/pplx_decider.py b/conversion/pplx_decider.py index b71bd8a3ad23..6507d29faecb 100644 --- a/conversion/pplx_decider.py +++ b/conversion/pplx_decider.py @@ -18,9 +18,12 @@ def _is_pplx_decider_checkpoint(dir_model: Path) -> bool: if not all((dir_model / name).is_file() for name in ("decision_config.json", "readout.safetensors", "config.json")): return False + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) with open(dir_model / "decision_config.json", encoding="utf-8") as f: - # the same layout with a format_id is a vllm-d3 checkpoint - return "format_id" not in json.load(f) + decision = json.load(f) + # pplx-decider is a Qwen3.5 backbone, and a format_id means vllm-d3 + return config.get("model_type") in ("qwen3_5", "qwen3_5_text") and "format_id" not in decision @ModelBase.register_hparams_loader(_is_pplx_decider_checkpoint) diff --git a/conversion/qwen3tts.py b/conversion/qwen3tts.py index 28bb6e095f56..1ea14692bc4c 100644 --- a/conversion/qwen3tts.py +++ b/conversion/qwen3tts.py @@ -275,6 +275,14 @@ def tensor_force_quant(self, name, new_name, bid, n_dims): or (".dac.blk." in new_name and (new_name.endswith(".conv1.weight") or new_name.endswith(".conv2.weight"))) ): return gguf.GGMLQuantizationType.F16 + # the reference encoder's convs run with an F32 im2col, see f32_im2col in pockettts-seanet.cpp + if new_name.startswith("a.seanet.") or new_name == "a.downsample.conv.weight": + return gguf.GGMLQuantizationType.F32 + # codes are picked by the nearest codebook entry: Q8_0 changes about 8% of them, F16 none + if new_name.startswith("a.gen.enc.tfm.blk.") and new_name.endswith(".weight") and n_dims == 2: + return gguf.GGMLQuantizationType.F16 + if new_name.startswith("a.gen.enc.quant."): + return gguf.GGMLQuantizationType.F32 # ConvTranspose1d kernels: only F16/F32 are implemented, no BF16 if new_name.endswith(".conv.weight") and (".up.blk." in new_name or ".dac.blk." in new_name): return gguf.GGMLQuantizationType.F32 @@ -298,8 +306,8 @@ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Ca return super().filter_tensors((name, gen)) def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: - # code2wav tensors are already named by generate_extra_tensors(), pass them through - if name.startswith("a.gen.wav."): + # code2wav and reference encoder tensors are already named by generate_extra_tensors(), pass them through + if name.startswith(("a.gen.wav.", "a.gen.enc.", "a.seanet.", "a.downsample.")): yield (name, data_torch) return @@ -356,6 +364,68 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: yield from self._generate_code2wav_tensors() + yield from self._generate_ref_encoder_tensors() + + # mimi encoder of the speech tokenizer: reference clip -> codes, for voice cloning with a transcript (ICL) + def _generate_ref_encoder_tensors(self) -> Iterable[tuple[str, Tensor]]: + from safetensors.torch import load_file + + state_dict = load_file(self.dir_model / "speech_tokenizer" / "model.safetensors") + if "encoder.downsample.conv.weight" not in state_dict: + return + + with open(self.dir_model / "speech_tokenizer" / "config.json", "r", encoding="utf-8") as f: + enc_config = json.load(f)["encoder_config"] + n_stage = len(enc_config["upsampling_ratios"]) + + T = gguf.MODEL_TENSOR + + # encoder.encoder.layers: conv_in, then per stage a residual unit, an ELU and a strided conv, then an ELU and conv_out + def seanet(idx: int, suffix: str) -> Tensor: + return state_dict[f"encoder.encoder.layers.{idx}.{suffix}"] + + for suffix in ("weight", "bias"): + yield (self.format_tensor_name(T.A_ENC_SEANET_CONV_IN, suffix=f".{suffix}"), seanet(0, f"conv.{suffix}")) + yield (self.format_tensor_name(T.A_ENC_SEANET_CONV_OUT, suffix=f".{suffix}"), seanet(3 * n_stage + 2, f"conv.{suffix}")) + for stage in range(n_stage): + yield (self.format_tensor_name(T.A_ENC_SEANET_RES_CONV1, stage, suffix=f".{suffix}"), seanet(3 * stage + 1, f"block.1.conv.{suffix}")) + yield (self.format_tensor_name(T.A_ENC_SEANET_RES_CONV2, stage, suffix=f".{suffix}"), seanet(3 * stage + 1, f"block.3.conv.{suffix}")) + yield (self.format_tensor_name(T.A_ENC_SEANET_SCALE_CONV, stage, suffix=f".{suffix}"), seanet(3 * stage + 3, f"conv.{suffix}")) + + yield (self.format_tensor_name(T.A_ENC_DOWNSAMPLE_CONV), state_dict["encoder.downsample.conv.weight"]) + + tfm_layer_map = { + "input_layernorm.weight": (T.A_GEN_ENC_TFM_ATTN_NORM, ".weight"), + "input_layernorm.bias": (T.A_GEN_ENC_TFM_ATTN_NORM, ".bias"), + "self_attn.q_proj.weight": (T.A_GEN_ENC_TFM_ATTN_Q, ".weight"), + "self_attn.k_proj.weight": (T.A_GEN_ENC_TFM_ATTN_K, ".weight"), + "self_attn.v_proj.weight": (T.A_GEN_ENC_TFM_ATTN_V, ".weight"), + "self_attn.o_proj.weight": (T.A_GEN_ENC_TFM_ATTN_OUT, ".weight"), + "self_attn_layer_scale.scale": (T.A_GEN_ENC_TFM_ATTN_SCALE, ".weight"), + "post_attention_layernorm.weight": (T.A_GEN_ENC_TFM_FFN_NORM, ".weight"), + "post_attention_layernorm.bias": (T.A_GEN_ENC_TFM_FFN_NORM, ".bias"), + "mlp.fc1.weight": (T.A_GEN_ENC_TFM_FFN_UP, ".weight"), + "mlp.fc2.weight": (T.A_GEN_ENC_TFM_FFN_DOWN, ".weight"), + "mlp_layer_scale.scale": (T.A_GEN_ENC_TFM_FFN_SCALE, ".weight"), + } + for bid in range(enc_config["num_hidden_layers"]): + for key, (tensor_id, suffix) in tfm_layer_map.items(): + yield (self.format_tensor_name(tensor_id, bid, suffix=suffix), state_dict[f"encoder.encoder_transformer.layers.{bid}.{key}"]) + + def rvq_codebook(prefix: str, idx: int) -> Tensor: + # checkpoint has EMA accumulators, so codebook = embed_sum / cluster_usage + embed_sum = state_dict[f"{prefix}.layers.{idx}.codebook.embed_sum"] + cluster_usage = state_dict[f"{prefix}.layers.{idx}.codebook.cluster_usage"] + return embed_sum / cluster_usage.clamp_min(1e-5).unsqueeze(-1) + + # the tokenizer keeps the semantic codebook and the first acoustic ones, see encoder_valid_num_quantizers + semantic = "encoder.quantizer.semantic_residual_vector_quantizer" + acoustic = "encoder.quantizer.acoustic_residual_vector_quantizer" + yield (self.format_tensor_name(T.A_GEN_ENC_QUANT_FIRST_IN), state_dict[f"{semantic}.input_proj.weight"].squeeze(-1)) + yield (self.format_tensor_name(T.A_GEN_ENC_QUANT_FIRST_CB), rvq_codebook(semantic, 0)) + yield (self.format_tensor_name(T.A_GEN_ENC_QUANT_REST_IN), state_dict[f"{acoustic}.input_proj.weight"].squeeze(-1)) + yield (self.format_tensor_name(T.A_GEN_ENC_QUANT_REST_CB), + torch.stack([rvq_codebook(acoustic, i) for i in range(self._CODE_GEN_N_CODEBOOKS)], dim=0)) def _generate_code2wav_tensors(self) -> Iterable[tuple[str, Tensor]]: # code2wav weights live in speech_tokenizer/model.safetensors, not the main safetensors diff --git a/conversion/qwen4exp.py b/conversion/qwen4exp.py index 9680d2937dfb..fe49cc03d5f3 100644 --- a/conversion/qwen4exp.py +++ b/conversion/qwen4exp.py @@ -8,7 +8,7 @@ import gguf import numpy as np -from .base import ModelBase +from .base import LazyTorchTensor, ModelBase from .qwen import _LinearAttentionVReorderBase, _Qwen35MRopeMixin from .qwen3vl import Qwen3VLVisionModel @@ -41,6 +41,18 @@ def __init__(self, *args, **kwargs): self._ple_shards: dict[int, str] = {} self._ple_row_dim: int | None = None self._mtp_fc: dict[str, Tensor] = {} + self._ple_scale: float | None = None + + def dequant_model(self): + # FP8 checkpoints: all n-gram shards share one scale, stored under the parent module name + # there is no "ngram_embedding.weight", so the generic FP8 pass drops it or cannot map it + for name in list(self.model_tensors): + if name.endswith(".ngram_embedding.weight_scale"): + scale = LazyTorchTensor.to_eager(self.model_tensors.pop(name)()).float().flatten() + if scale.numel() != 1: + raise ValueError(f"PLE scale {name!r} must be a scalar, got {scale.numel()} values") + self._ple_scale = float(scale[0]) + super().dequant_model() @classmethod def filter_tensors(cls, item): @@ -203,21 +215,31 @@ def _place_ple_shard(self, data_torch: Tensor, name: str) -> Iterable[tuple[str, f"PLE shard {shard} has row dim {int(shape[-1])}, expected {self._ple_row_dim}") rows += int(shape[0]) + # an FP8 table keeps its bytes and gets a scale tensor, any other type has the scale folded in + keep_fp8 = name in self._fp8_e4m3_preserved table = gguf.LazyChunkedTensor( - [self._load_ple_shard(shard) for shard in shards], + [self._load_ple_shard(shard, keep_fp8) for shard in shards], shape=(rows, self._ple_row_dim), - dtype=np.float32, + dtype=np.uint8 if keep_fp8 else np.float32, ) gguf_name = gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.PER_LAYER_TOKEN_EMBD] - return [(gguf_name + ".weight", cast(Tensor, table))] + out = [(gguf_name + ".weight", cast(Tensor, table))] + if keep_fp8 and self._ple_scale is not None: + out.append((gguf_name + ".scale", torch.tensor([self._ple_scale], dtype=torch.float32))) + return out - def _load_ple_shard(self, name: str): + def _load_ple_shard(self, name: str, keep_fp8: bool): def load() -> np.ndarray: - from .base import LazyTorchTensor - # a fresh lazy tensor every call, or to_eager() memoizes every shard eager = LazyTorchTensor.to_eager(self.model_tensors[name]()) - return eager.to(torch.float32).contiguous().numpy() + if keep_fp8: + if eager.dtype != torch.float8_e4m3fn: + raise ValueError(f"PLE shard {name} is {eager.dtype}, expected FP8 like the other shards") + return eager.contiguous().view(torch.uint8).numpy() + data = eager.to(torch.float32) + if self._ple_scale is not None: + data = data * self._ple_scale + return data.contiguous().numpy() return load def prepare_tensors(self): diff --git a/conversion/tiny_voca.py b/conversion/tiny_voca.py new file mode 100644 index 000000000000..6bfa5490732d --- /dev/null +++ b/conversion/tiny_voca.py @@ -0,0 +1,443 @@ +from __future__ import annotations + +import importlib.util +import json +import re +import unicodedata +from pathlib import Path +from typing import Any, Callable, Iterable + +import numpy as np +import torch +from torch import Tensor + +from .base import ModelBase, TextModel, MmprojModel, gguf, logger + +# tiny-voca, https://huggingface.co/n4ze3m/tiny-voca +# +# text model: phoneme encoder (4 blocks), the input rows are built by the audio pipeline (token + stress + voice) +# mmproj: input tables, voices, duration predictor, prosody and acoustic stacks, source-filter heads +# +# the text to phonemes step (dizione) is the "tts" chat template, see models/templates/n4ze3m-tiny-voca-tts.jinja +# its lexicon comes from the phonemizer/ directory of the model, the other tables from the dizione python package +# +# the prosody and acoustic stacks have the same blocks as the encoder, they are stored with the libllama names +# of the tiny-voca arch under a.gen.prosody. and a.gen.acoustic., mtmd runs them on llama contexts of its own + +CHECKPOINT = "tiny-voca.pt" +DEFAULT_VOICE = "M2" + +# phone classes of the reference (text.py): the phones get at least one frame, the vowels are always voiced +VOWELS = ("ə", "ɐ", "ɚ", "ᵻ", "ɪ", "i", "iː", "ɛ", "æ", "ʌ", "ɑː", "ɔ", "ɔː", "ʊ", "uː", "ɜː", + "eɪ", "aɪ", "ɔɪ", "oʊ", "aʊ", "iə", "oː", + "ɑːɹ", "ɔːɹ", "oːɹ", "ɪɹ", "ɛɹ", "ʊɹ", "aɪɚ", "aɪə", "əl", "n̩") +CONSONANTS = ("p", "b", "t", "d", "k", "ɡ", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", + "m", "n", "ŋ", "l", "ɹ", "j", "w", "tʃ", "dʒ", "ɾ", "ʔ") + +# input letters and output phonemes of the unknown-word model, fixed in mtmd (see mtmd_graph_tiny_voca) +G2P_LETTERS = "abcdefghijklmnopqrstuvwxyz'" +G2P_SYMBOLS = [v + d for v in ("AA", "AE", "AH", "AO", "AW", "AY") for d in "012"] + ["B", "CH", "D", "DH"] + \ + [v + d for v in ("EH", "ER", "EY") for d in "012"] + ["F", "G", "HH"] + [v + d for v in ("IH", "IY") for d in "012"] + \ + ["JH", "K", "L", "M", "N", "NG"] + [v + d for v in ("OW", "OY") for d in "012"] + ["P", "R", "S", "SH", "T", "TH"] + \ + [v + d for v in ("UH", "UW") for d in "012"] + ["V", "W", "Y", "Z", "ZH"] + +# block tensors: reference name -> libllama name +BLOCK_MAP = { + "norm1": "attn_norm", + "attention.qkv": "attn_qkv", + "attention.out": "attn_output", + "norm2": "ffn_norm", + "depthwise": "ssm_conv1d", + "expand": "ffn_up", + "project": "ffn_down", +} + +# mmproj stacks: reference module -> prefix +STACK_PREFIX = { + "prosody_stack": "a.gen.prosody.", + "acoustic_stack": "a.gen.acoustic.", +} + +# other mmproj tensors: reference module -> name +MMPROJ_MAP = { + "tokens": "a.gen.tok_embd", + "stress": "a.gen.stress_embd", + "duration.conv1": "a.gen.dur.conv1", + "duration.conv2": "a.gen.dur.conv2", + "duration.norm1": "a.gen.dur.norm1", + "duration.norm2": "a.gen.dur.norm2", + "duration.out": "a.gen.dur.out", + "frame_position": "a.gen.frame_pos", + "prosody_head": "a.gen.prosody_head", + "prosody_projection": "a.gen.prosody_proj", + "vocoder.harmonic": "a.gen.voc.harmonic", + "vocoder.noise": "a.gen.voc.noise", +} + + +def _is_tiny_voca_checkpoint(dir_model: Path) -> bool: + if not (dir_model / CHECKPOINT).is_file() or not (dir_model / "config.json").is_file(): + return False + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) + return config.get("phonemizer", {}).get("name") == "dizione" and "vocab" in config and "model" in config + + +@ModelBase.register_hparams_loader(_is_tiny_voca_checkpoint) +def _load_tiny_voca_hparams(dir_model: Path) -> dict[str, Any]: + logger.info("gguf: detected tiny-voca checkpoint") + with open(dir_model / "config.json", encoding="utf-8") as f: + config = json.load(f) + c = config["model"] + return { + "architectures": ["TinyVocaModel"], + "model_type": "tiny-voca", + "num_hidden_layers": c["encoder_layers"], + "hidden_size": c["channels"], + "intermediate_size": c["feedforward"], + "num_attention_heads": c["heads"], + "num_key_value_heads": c["heads"], + "max_position_embeddings": c["max_tokens"], + "vocab_size": c["vocab_size"], + "layer_norm_eps": 1e-5, # torch LayerNorm default + "rope_theta": 10000.0, + "tiny_voca": config, + # the mmproj tensors are named explicitly, they do not go through the block tensor map + "audio_config": {"num_hidden_layers": 0}, + } + + +def _table_rows(path: Path) -> Iterable[list[str]]: + # dizione tables: columns separated by tabs or two or more spaces, "#" comments + for line in path.read_text(encoding="utf-8").splitlines(): + line = line.split("#", 1)[0].rstrip() if line.lstrip().startswith("#") else line.rstrip() + if line.strip(): + yield [c.strip() for c in re.split(r"\t+| {2,}", line.strip())] + + +def _g2p_dicts(dir_model: Path) -> dict[str, dict[str, Any]] | None: + lexicon_path = dir_model / "phonemizer" / "lexicon.tsv" + spec = importlib.util.find_spec("dizione") + if not lexicon_path.is_file() or spec is None or spec.origin is None: + logger.warning("dizione or phonemizer/lexicon.tsv not found, the model will take phonemes as prompt " + "(pip install git+https://github.com/n4ze3m/dizione)") + return None + data = Path(spec.origin).parent / "data" + lexicon: dict[str, str] = {} + for line in lexicon_path.read_text(encoding="utf-8").splitlines(): + if "\t" in line: + word, phones = line.split("\t", 1) + lexicon[word] = phones.strip() + + # word -> [stress class, form, final form or ""], see function_words.txt + functions = {r[0]: [r[1], r[2], r[3] if len(r) > 3 else ""] for r in _table_rows(data / "function_words.txt")} + # words -> [class, forms (one, or one per word), final form or ""], see phrases.txt + phrases = {r[0]: [r[1], [f.strip() for f in r[2].split("|")], r[3] if len(r) > 3 else ""] for r in _table_rows(data / "phrases.txt")} + letters = {r[0]: r[1] for r in _table_rows(data / "letters.txt")} + # a value is phones, or CMUdict notation (converted by the template, like the output of the unknown-word model) + exceptions = {r[0].lower(): r[1] for r in _table_rows(data / "exceptions.txt") if " " not in r[0]} + # a name of several words: "w1 w2 ..." -> one pronunciation per word; first word -> the longest name it starts + names: dict[str, Any] = {} + name_starts: dict[str, int] = {} + for r in _table_rows(data / "exceptions.txt"): + words = r[0].lower().split() + if len(words) > 1: + names[" ".join(words)] = [part.strip() for part in r[1].split("|")] + name_starts[words[0]] = max(name_starts.get(words[0], 0), len(words)) + # phoneme (CMUdict, no stress) -> {letters: log probability}: aligns the letters of a word to its phonemes + with open(dir_model / "phonemizer" / "align.json", encoding="utf-8") as f: + align = json.load(f) + # abbreviation -> [when, words] + abbreviations = {r[0]: [r[1], r[2]] for r in _table_rows(data / "abbreviations.txt")} + # chat spelling -> [words to say ("*LOL": letter by letter, "-": nothing), only as a reply by itself], see chat.txt + chat = {r[0].lower(): [r[1] if len(r) > 1 else "-", len(r) > 2] for r in _table_rows(data / "chat.txt")} + # accented latin letter -> plain letter(s): "café" is in the dictionary as "cafe" (dizione: _plain_letter) + accents = {"ß": "ss", "æ": "ae", "Æ": "Ae", "œ": "oe", "Œ": "Oe", "ø": "o", "Ø": "O", "đ": "d", "ł": "l", "Ł": "L"} + for cp in range(0x80, 0x2000): + char = chr(cp) + if char.isalpha() and char not in accents: + plain = "".join(c for c in unicodedata.normalize("NFKD", char) if not unicodedata.combining(c)) + if plain.isascii() and plain.isalpha(): + accents[char] = plain + # compatibility forms of the text (NFKC), a character at a time: "…" is "...", "fi" is "fi", "№" is "No", full + # width letters. Sequences that NFKC would compose are left as they are + nfkc: dict[str, str] = {} + for cp in list(range(0x80, 0x3000)) + list(range(0xFB00, 0xFB07)) + list(range(0xFF01, 0xFF5F)): + if unicodedata.normalize("NFKC", chr(cp)) != chr(cp): + nfkc[chr(cp)] = unicodedata.normalize("NFKC", chr(cp)) + # units after a number: name -> [one, many]; "exact" ones are written in one letter case only ("m", not "M") + units: dict[str, Any] = {} + exact_units: dict[str, Any] = {} + for r in _table_rows(data / "units.txt"): + if len(r) > 3 and r[3] == "exact": + exact_units[r[0]] = [r[1], r[2]] + else: + units[r[0].lower()] = [r[1], r[2]] + # the unit names as a pattern of tts_norm_scan(), the longest first; a unit does not stop inside a word + unit_names = sorted(set(units) | set(exact_units), key=lambda name: (-len(name), name)) + # (the pattern ignores the case of ASCII letters only, the greek letter is written in both) + unit_pattern = "|".join("".join("[μΜ]" if c == "μ" else c if c.isalnum() else "%" + c for c in name) + "(?![A-Za-z])" for name in unit_names) + # endings of file names and addresses: "word" (dot com) or "letters" (dot P D F) + endings = {r[0]: (r[1] if len(r) > 1 else "") for r in _table_rows(data / "endings.txt")} + out = { + "lexicon": lexicon, + "functions": functions, + "phrases": phrases, + "letters": letters, + "exceptions": exceptions, + "abbreviations": abbreviations, + "align": align, + "names": names, + "chat": chat, + "accents": accents, + "nfkc": nfkc, + "units": units, + "exact_units": exact_units, + "endings": endings, + "patterns": {"units": unit_pattern}, + "name_starts": name_starts, + } + out.update(_homograph_dicts(dir_model, data)) + return out + + +def _homograph_dicts(dir_model: Path, data: Path) -> dict[str, dict[str, Any]]: + # words spelled alike and pronounced differently (dizione homographs.py): a linear classifier on the neighbouring + # words, and hand-written rules that are tried first. Weights are stored x10000 (they have four decimals), so the + # template adds integers. + path = dir_model / "phonemizer" / "homographs.json" + if not path.is_file(): + return {"homographs": {}, "homograph_shared": {}, "homograph_plurals": {}, "homograph_rules": {}} + with open(path, encoding="utf-8") as f: + source = json.load(f) + + def fixed(x: float) -> int: + value = round(x * 10000) + if abs(value - x * 10000) > 1e-6: + raise ValueError(f"homographs.json: weight {x} has more than four decimals") + return value + + words: dict[str, Any] = {} + for word, entry in source["words"].items(): + model = entry["model"] + noun_verb = model["kind"] == "noun-verb" + if not noun_verb and model["kind"] != "senses": + raise ValueError(f"homographs.json: unknown model kind {model['kind']!r}") + words[word] = { + # sense: [id, role, phones] + "senses": [[s["id"], s["role"], s["phones"]] for s in entry["senses"]], + # noun-verb: one score for the verb reading; else one score per sense + "noun_verb": noun_verb, + "bias": [fixed(model["bias"])] if noun_verb else [fixed(b) for b in model["bias"]], + "weights": [{k: fixed(v) for k, v in w.items()} for w in ([model["weights"]] if noun_verb else model["weights"])], + } + # the weights all noun-or-verb homographs share; "" is the bias + shared = {k: fixed(v) for k, v in source["pooled"]["weights"].items()} + shared[""] = fixed(source["pooled"]["bias"]) + # word -> [[sense id, [[condition, [words]], ...]], ...], see homograph_rules.txt + rules: dict[str, Any] = {} + for r in _table_rows(data / "homograph_rules.txt"): + conditions = [] + for part in r[2].split(";"): + name, _, listed = part.strip().partition(":") + conditions.append([name, listed.split()]) + rules.setdefault(r[0], []).append([r[1], conditions]) + return { + "homographs": words, + "homograph_shared": shared, + "homograph_plurals": {base: 1 for base in source.get("plural_bases", ())}, + "homograph_rules": rules, + } + + +def _load_state(dir_model: Path) -> dict[str, Tensor]: + ckpt = torch.load(dir_model / CHECKPOINT, map_location="cpu", weights_only=True) + if ckpt.get("format_version") != 4: + raise ValueError(f"unsupported tiny-voca checkpoint format {ckpt.get('format_version')}") + return ckpt["model"] + + +def _block_name(name: str) -> tuple[int, str] | None: + # "blocks..." -> (i, "blk...") + parts = name.split(".") + if len(parts) < 4 or parts[0] != "blocks": + return None + bid = int(parts[1]) + module, suffix = ".".join(parts[2:-1]), parts[-1] + return bid, f"blk.{bid}.{BLOCK_MAP[module]}.{suffix}" + + +def _block_tensors(new_name: str, t: Tensor) -> Iterable[tuple[str, Tensor]]: + # depthwise conv [C, 1, K] -> [C, K], the layout of ggml_ssm_conv + if ".ssm_conv1d.weight" in new_name: + yield (new_name, t.squeeze(1)) + return + # separate q, k, v: a model that libllama builds from metadata (the mmproj stacks) has no fused qkv + if ".attn_qkv." in new_name: + for part, chunk in zip(("attn_q", "attn_k", "attn_v"), t.chunk(3, dim=0)): + yield (new_name.replace("attn_qkv", part), chunk.contiguous()) + return + yield (new_name, t) + + +@ModelBase.register("TinyVocaModel") +@ModelBase.example("n4ze3m/tiny-voca") +class TinyVocaTextModel(TextModel): + model_arch = gguf.MODEL_ARCH.TINY_VOCA + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + del remote_hf_model_id + state = _load_state(self.dir_model) + out: dict[str, Callable[[], Tensor]] = {} + for name, t in state.items(): + if name == "tokens.weight" or name.startswith("encoder."): + out[name] = (lambda t=t: t) + return out + + def set_vocab(self): + config = self.hparams["tiny_voca"] + n_vocab = config["model"]["vocab_size"] + tokens: list[str] = [""] * n_vocab + toktypes = [gguf.TokenType.NORMAL] * n_vocab + for text, i in config["vocab"].items(): + tokens[i] = text + if text.startswith("<") and text.endswith(">"): + toktypes[i] = gguf.TokenType.CONTROL + assert all(tokens) + + # the prompt is split into phonemes by the audio pipeline, see mtmd-helper-gen.cpp + self.gguf_writer.add_tokenizer_model("llama") + self.gguf_writer.add_tokenizer_pre("default") + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_scores([0.0] * n_vocab) + self.gguf_writer.add_token_types(toktypes) + self.gguf_writer.add_bos_token_id(config["vocab"][""]) + self.gguf_writer.add_eos_token_id(config["vocab"][""]) + self.gguf_writer.add_pad_token_id(config["vocab"][""]) + self.gguf_writer.add_unk_token_id(config["vocab"][""]) + self.gguf_writer.add_add_bos_token(False) + self.gguf_writer.add_add_eos_token(False) + + dicts = _g2p_dicts(self.dir_model) + if dicts is not None: + template_path = Path(__file__).parent.parent / "models" / "templates" / "n4ze3m-tiny-voca-tts.jinja" + with open(template_path, encoding="utf-8") as f: + self.gguf_writer.add_chat_template([{"name": "tts", "template": f.read()}]) + self.gguf_writer.add_tts_dicts(dicts) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_causal_attention(False) + self.gguf_writer.add_pooling_type(gguf.PoolingType.NONE) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + if name == "tokens.weight": + yield ("token_embd.weight", data_torch) + return + if name.startswith("encoder.norm."): + yield ("output_norm." + name.rsplit(".", 1)[1], data_torch) + return + res = _block_name(name.removeprefix("encoder.")) + if res is None: + raise ValueError(f"unexpected tensor {name}") + yield from _block_tensors(res[1], data_torch) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + del name, bid, n_dims + # ggml_ssm_conv takes F32 weights; token_embd is also read row by row on the host side + if ".ssm_conv1d." in new_name or new_name == "token_embd.weight": + return gguf.GGMLQuantizationType.F32 + return False + + +@ModelBase.register("TinyVocaModel") +@ModelBase.example("n4ze3m/tiny-voca") +class TinyVocaMmprojModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = False + + def get_audio_config(self) -> dict[str, Any] | None: + return self.global_config.get("audio_config") + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + del remote_hf_model_id + state = _load_state(self.dir_model) + out: dict[str, Callable[[], Tensor]] = {} + for name, t in state.items(): + if name.startswith("encoder.") or name in ("voices.weight", "frame_voices.weight"): + continue + out[name] = (lambda t=t: t) + return out + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + return item + + def set_gguf_parameters(self): + c = self.global_config["tiny_voca"]["model"] + self.gguf_writer.add_file_type(self.ftype) + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.TINY_VOCA) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(c["channels"]) + self.gguf_writer.add_gen_audio_feed_forward_length(c["feedforward"]) + self.gguf_writer.add_gen_audio_block_count(c["acoustic_layers"]) + self.gguf_writer.add_gen_audio_head_count(c["heads"]) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-5) + self.gguf_writer.add_gen_audio_default_voice(DEFAULT_VOICE) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + # from generate_extra_tensors(), named already + if name.startswith(("voice.", "a.gen.")): + yield (name, data_torch) + return + stack, _, rest = name.partition(".") + if stack in STACK_PREFIX: + prefix = STACK_PREFIX[stack] + if rest.startswith("norm."): + yield (prefix + "output_norm." + rest.rsplit(".", 1)[1], data_torch) + return + res = _block_name(rest) + if res is None: + raise ValueError(f"unexpected tensor {name}") + yield from _block_tensors(prefix + res[1], data_torch) + return + module, suffix = name.rsplit(".", 1) + if module not in MMPROJ_MAP: + raise ValueError(f"unexpected tensor {name}") + yield (MMPROJ_MAP[module] + "." + suffix, data_torch) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + del name, bid + # the blocks of the stacks are loaded by libllama, like the text model + if new_name.startswith(tuple(STACK_PREFIX.values())) and ".ssm_conv1d." not in new_name and n_dims >= 2: + return False + # the rest is small and partly read on the host + return gguf.GGMLQuantizationType.F32 + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + # the unknown-word model of dizione (letters -> CMUdict phonemes), run on the host by mtmd_gen_audio_g2p() + g2p_dir = self.dir_model / "phonemizer" + if (g2p_dir / "g2p.npz").is_file(): + with open(g2p_dir / "g2p.json", encoding="utf-8") as f: + settings = json.load(f) + if settings["letters"] != G2P_LETTERS or settings["symbols"] != G2P_SYMBOLS or settings["convs"] != 0 or settings["slots"] != 2: + raise ValueError("unsupported g2p model in phonemizer/g2p.json") + with np.load(g2p_dir / "g2p.npz") as arrays: + for name in arrays.files: + yield ("a.gen.g2p." + name.replace("__", "."), torch.from_numpy(arrays[name].astype(np.float32))) + config = self.global_config["tiny_voca"] + state = _load_state(self.dir_model) + # a voice row is the embedding added to the encoder input, then the one added to the frames + for i, voice in enumerate(config["voices"]): + yield (f"voice.{voice}", torch.cat([state["voices.weight"][i], state["frame_voices.weight"][i]]).float()) + # class of each token: 0 = pause (special or punctuation), 1 = consonant or , 2 = vowel + vocab = config["vocab"] + cls = torch.zeros(len(vocab), dtype=torch.float32) + for p in CONSONANTS + ("",): + cls[vocab[p]] = 1.0 + for p in VOWELS: + cls[vocab[p]] = 2.0 + yield ("a.gen.token_class", cls) diff --git a/conversion/vibevoice_asr.py b/conversion/vibevoice_asr.py new file mode 100644 index 000000000000..f160c0e01985 --- /dev/null +++ b/conversion/vibevoice_asr.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +from typing import Any, Callable, Iterable, TYPE_CHECKING + +if TYPE_CHECKING: + from torch import Tensor + +from .base import MmprojModel, ModelBase, gguf +from .qwen import Qwen2Model + + +# the upstream chat_template.jinja is a processor template (list content, audio parts), use plain ChatML with its default system prompt +VIBEVOICE_ASR_CHAT_TEMPLATE = ( + "{%- if messages[0]['role'] == 'system' -%}" + "{{- '<|im_start|>system\\n' + messages[0]['content'] + '<|im_end|>\\n' -}}" + "{%- set loop_messages = messages[1:] -%}" + "{%- else -%}" + "{{- '<|im_start|>system\\nYou are a helpful assistant that transcribes audio input into text output in JSON format.<|im_end|>\\n' -}}" + "{%- set loop_messages = messages -%}" + "{%- endif -%}" + "{%- for message in loop_messages -%}" + "{{- '<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>\\n' -}}" + "{%- endfor -%}" + "{%- if add_generation_prompt -%}" + "{{- '<|im_start|>assistant\\n' -}}" + "{%- endif -%}" +) + + +@ModelBase.register("VibeVoiceAsrForConditionalGeneration") +@ModelBase.example("microsoft/VibeVoice-ASR-HF") +class VibeVoiceAsrModel(Qwen2Model): + model_arch = gguf.MODEL_ARCH.QWEN2 + + def set_vocab(self): + super().set_vocab() + self.gguf_writer.add_chat_template(VIBEVOICE_ASR_CHAT_TEMPLATE) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, _ = item + if not name.startswith("language_model."): + return None + return super().filter_tensors(item) + + +@ModelBase.register("VibeVoiceAsrForConditionalGeneration") +class VibeVoiceAsrAudioModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = True + + # values hard-coded in tools/mtmd/models/vibevoice-asr.cpp + _encoder_consts = {"channels": 1, "kernel_size": 7, "num_filters": 32, "ffn_expansion": 4, "hidden_act": "gelu", "rms_norm_eps": 1e-5} + _encoders = ("acoustic_tokenizer_encoder", "semantic_tokenizer_encoder") + + def get_audio_config(self) -> dict[str, Any] | None: + c = self.global_config["acoustic_tokenizer_encoder_config"] + return { + **c, + "intermediate_size": c["ffn_expansion"] * c["hidden_size"], + "num_attention_heads": 1, + "num_hidden_layers": sum(c["depths"]), + } + + def set_gguf_parameters(self): + super().set_gguf_parameters() + for enc in self._encoders: + c = self.global_config[f"{enc}_config"] + for k, v in self._encoder_consts.items(): + assert c[k] == v, f"{enc}.{k} = {c[k]}, expected {v}" + assert c["depths"] == self.hparams["depths"] and c["downsampling_ratios"] == self.hparams["downsampling_ratios"] + + self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.VIBEVOICE_ASR) + # the input is the raw waveform, one channel takes the place of the mel bins + self.gguf_writer.add_audio_num_mel_bins(1) + self.gguf_writer.add_audio_attention_layernorm_eps(self.hparams["rms_norm_eps"]) + self.gguf_writer.add_audio_conv_kernel_size(self.hparams["kernel_size"]) + # stride of each stage, the stem has none + self.gguf_writer.add_audio_patch_sizes([1] + [int(r) for r in self.hparams["downsampling_ratios"]]) + self.gguf_writer.add_audio_depths([int(d) for d in self.hparams["depths"]]) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + if ".dw." in new_name: + return gguf.GGMLQuantizationType.F32 # ggml_ssm_conv + if ".conv." in new_name and new_name.endswith(".weight"): + return gguf.GGMLQuantizationType.F16 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, _ = item + if not name.startswith(cls._encoders + ("multi_modal_projector.",)): + return None + return super().filter_tensors(item) + + _block_tensors = { + "norm.weight": gguf.MODEL_TENSOR.A_ENC_CNX_NORM, + "mixer.conv.weight": gguf.MODEL_TENSOR.A_ENC_CNX_DW, + "mixer.conv.bias": gguf.MODEL_TENSOR.A_ENC_CNX_DW, + "gamma": gguf.MODEL_TENSOR.A_ENC_CNX_LS1, + "ffn_norm.weight": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_NORM, + "ffn.linear1.weight": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_UP, + "ffn.linear1.bias": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_UP, + "ffn.linear2.weight": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_DOWN, + "ffn.linear2.bias": gguf.MODEL_TENSOR.A_ENC_CNX_FFN_DOWN, + "ffn_gamma": gguf.MODEL_TENSOR.A_ENC_CNX_LS2, + } + + # mm.a.mlp.{0,1} + mm.a.mlp_norm.0 for the acoustic connector, {2,3} + 2 for the semantic one + _proj_tensors = { + "acoustic_linear_1": (gguf.MODEL_TENSOR.A_MMPROJ, 0), + "acoustic_norm": (gguf.MODEL_TENSOR.A_MMPROJ_NORM, 0), + "acoustic_linear_2": (gguf.MODEL_TENSOR.A_MMPROJ, 1), + "semantic_linear_1": (gguf.MODEL_TENSOR.A_MMPROJ, 2), + "semantic_norm": (gguf.MODEL_TENSOR.A_MMPROJ_NORM, 2), + "semantic_linear_2": (gguf.MODEL_TENSOR.A_MMPROJ, 3), + } + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # the layer scales (gamma) have no suffix upstream + suffix = "." + name.rsplit(".", 1)[-1] if name.endswith((".weight", ".bias")) else ".weight" + + if name.startswith("multi_modal_projector."): + key, idx = self._proj_tensors[name.split(".")[1]] + yield (self.format_tensor_name(key, idx, suffix=suffix), data_torch) + return + + enc, _, rest = name.partition(".") + enc_id = self._encoders.index(enc) + parts = rest.split(".") + depths = [int(d) for d in self.hparams["depths"]] + + # causal convs of the stages: 0 = stem, 1..6 = downsample, 7 = head + if rest.startswith("stem.conv."): + conv_id = 0 + elif parts[0] == "conv_layers" and parts[2] == "conv": + conv_id = int(parts[1]) + 1 + elif parts[0] == "head": + conv_id = len(depths) + else: + conv_id = None + if conv_id is not None: + yield (gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.A_ENC_CNX_CONV].format(bid=enc_id, xid=conv_id) + suffix, data_torch) + return + + # ConvNeXt blocks are numbered per stage upstream and flat here + if parts[0] == "stem": + stage, blk, tail = 0, int(parts[2]), ".".join(parts[3:]) + else: + assert parts[0] == "conv_layers" and parts[2] == "stage", name + stage, blk, tail = int(parts[1]) + 1, int(parts[3]), ".".join(parts[4:]) + xid = sum(depths[:stage]) + blk + + key = self._block_tensors[tail] + if key == gguf.MODEL_TENSOR.A_ENC_CNX_DW and tail.endswith(".weight"): + data_torch = data_torch.squeeze(1) # [C, 1, K] -> [C, K] for ggml_ssm_conv + yield (gguf.TENSOR_NAMES[key].format(bid=enc_id, xid=xid) + suffix, data_torch) diff --git a/conversion/voxcpm.py b/conversion/voxcpm.py new file mode 100644 index 000000000000..8fc855830c40 --- /dev/null +++ b/conversion/voxcpm.py @@ -0,0 +1,314 @@ +from __future__ import annotations + +import json +import math +import re +from pathlib import Path +from typing import Any, Callable, Iterable, TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, MmprojModel, TextModel, LazyTorchTensor, gguf, logger +from .drama3 import fold_snake +from .minicpm import MiniCPMModel + +# sample rate of the AudioVAE decoder output, picks the row of the sample-rate conditioning +VAE_OUT_SAMPLE_RATE = 48000 + + +def _load_config(dir_model: Path) -> dict[str, Any] | None: + path = dir_model / "config.json" + if not path.is_file(): + return None + with open(path, encoding="utf-8") as f: + config = json.load(f) + return config if config.get("architecture") == "voxcpm2" else None + + +def _is_voxcpm2_checkpoint(dir_model: Path) -> bool: + return _load_config(dir_model) is not None + + +@ModelBase.register_hparams_loader(_is_voxcpm2_checkpoint) +def _load_voxcpm2_hparams(dir_model: Path) -> dict[str, Any]: + logger.info("gguf: detected VoxCPM2 checkpoint") + config = _load_config(dir_model) + assert config is not None + if config["lm_config"].get("use_mup"): + raise NotImplementedError("VoxCPM2: use_mup = true is not supported") + if config["dit_config"].get("mean_mode"): + raise NotImplementedError("VoxCPM2: dit mean_mode = true is not supported") + if not config.get("residual_lm_no_rope"): + raise NotImplementedError("VoxCPM2: residual LM with RoPE is not supported") + for key in ("hidden_dim", "ffn_dim", "num_heads", "num_layers", "kv_channels"): + if config["encoder_config"][key] != config["dit_config"][key]: + raise NotImplementedError(f"VoxCPM2: LocEnc and LocDiT differ in {key}") + return {**config, "architectures": ["VoxCPM2Model"], "text_config": config["lm_config"], "audio_config": config["dit_config"]} + + +@ModelBase.register("VoxCPM2Model") +@ModelBase.example("openbmb/VoxCPM2") +class VoxCPM2TextModel(MiniCPMModel): + model_arch = gguf.MODEL_ARCH.MINICPM + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + # the text-semantic LM is a plain MiniCPM, the rest goes to the mmproj + if not name.startswith("base_lm."): + return None + return super().filter_tensors(("model." + name.removeprefix("base_lm."), gen)) + + def set_gguf_parameters(self): + TextModel.set_gguf_parameters(self) + # use_mup = false: no embedding, residual or logit scaling + self.gguf_writer.add_embedding_scale(1.0) + self.gguf_writer.add_residual_scale(1.0) + self.gguf_writer.add_logit_scale(1.0) + + def set_vocab(self): + # the checkpoint has no tokenizer.model and its tokenizer class is remote code, so read tokenizer.json + # SPM-style BPE: a merged token scores minus its merge rank, so the SPM tokenizer merges in the BPE order + with open(self.dir_model / "tokenizer.json", encoding="utf-8") as f: + tok = json.load(f) + with open(self.dir_model / "tokenizer_config.json", encoding="utf-8") as f: + tok_cfg = json.load(f) + model = tok["model"] + if model["type"] != "BPE" or not model.get("byte_fallback"): + raise NotImplementedError("VoxCPM2: unexpected tokenizer type") + + vocab: dict[str, int] = model["vocab"] + vocab_size = self.hparams["vocab_size"] + tokens = [f"[PAD{i}]" for i in range(vocab_size)] + scores = [-1e9] * vocab_size + toktypes = [gguf.TokenType.UNUSED] * vocab_size + for text, i in vocab.items(): + tokens[i] = text + toktypes[i] = gguf.TokenType.BYTE if re.fullmatch(r"<0x[0-9A-Fa-f]{2}>", text) else gguf.TokenType.NORMAL + for rank, merge in enumerate(model["merges"]): + a, b = merge.split(" ") if isinstance(merge, str) else merge + i = vocab[a + b] + scores[i] = max(scores[i], -float(rank)) + + # the special tokens (e.g. <|audio_start|>) are only listed in tokenizer_config.json + specials = {int(i): t["content"] for i, t in tok_cfg.get("added_tokens_decoder", {}).items() if t.get("special")} + specials.update({t["id"]: t["content"] for t in tok["added_tokens"] if t.get("special")}) + for i, text in specials.items(): + tokens[i] = text + toktypes[i] = gguf.TokenType.CONTROL + + self.gguf_writer.add_tokenizer_model("llama") + self.gguf_writer.add_tokenizer_pre("default") + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_scores(scores) + self.gguf_writer.add_token_types(toktypes) + special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens)) + special_vocab.add_to_gguf(self.gguf_writer) + + +@ModelBase.register("VoxCPM2Model") +@ModelBase.example("openbmb/VoxCPM2") +class VoxCPM2MmprojModel(MmprojModel): + has_vision_encoder = False + has_audio_encoder = True # AudioVAE encoder, for voice cloning + + _LAYER_MAP = { + "input_layernorm.weight": "ln1", + "self_attn.q_proj.weight": "attn_q", + "self_attn.k_proj.weight": "attn_k", + "self_attn.v_proj.weight": "attn_v", + "self_attn.o_proj.weight": "attn_out", + "post_attention_layernorm.weight": "ln2", + "mlp.gate_proj.weight": "ffn_gate", + "mlp.up_proj.weight": "ffn_up", + "mlp.down_proj.weight": "ffn_down", + } + + # libllama names, mtmd loads the residual LM as a text model + _RES_LAYER_MAP = { + "input_layernorm.weight": "attn_norm", + "self_attn.q_proj.weight": "attn_q", + "self_attn.k_proj.weight": "attn_k", + "self_attn.v_proj.weight": "attn_v", + "self_attn.o_proj.weight": "attn_output", + "post_attention_layernorm.weight": "ffn_norm", + "mlp.gate_proj.weight": "ffn_gate", + "mlp.up_proj.weight": "ffn_up", + "mlp.down_proj.weight": "ffn_down", + } + + _PROJ_MAP = { + "fsq_layer.in_proj": "a.gen.fsq.in", + "fsq_layer.out_proj": "a.gen.fsq.out", + "enc_to_lm_proj": "a.gen.enc_to_lm", + "lm_to_dit_proj": "a.gen.lm_to_dit", + "res_to_dit_proj": "a.gen.res_to_dit", + "fusion_concat_proj": "a.gen.fusion", + "stop_proj": "a.gen.stop_proj", + "stop_head": "a.gen.stop_head", + "feat_encoder.in_proj": "a.gen.enc.in_proj", + "feat_decoder.estimator.in_proj": "a.gen.dit.in_proj", + "feat_decoder.estimator.cond_proj": "a.gen.dit.cond_proj", + "feat_decoder.estimator.out_proj": "a.gen.dit.out_proj", + "feat_decoder.estimator.time_mlp.linear_1": "a.gen.dit.time_mlp.0", + "feat_decoder.estimator.time_mlp.linear_2": "a.gen.dit.time_mlp.1", + } + + def set_gguf_parameters(self): + lm = self.global_config["lm_config"] + dit = self.global_config["dit_config"] + vae = self.global_config["audio_vae_config"] + self.gguf_writer.add_file_type(self.ftype) + + # LocEnc + LocDiT + residual LM + AudioVAE decoder, LocEnc has the hparams of LocDiT + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.VOXCPM2_GEN) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(dit["hidden_dim"]) + self.gguf_writer.add_gen_audio_feed_forward_length(dit["ffn_dim"]) + self.gguf_writer.add_gen_audio_block_count(dit["num_layers"]) + self.gguf_writer.add_gen_audio_head_count(dit["num_heads"]) + self.gguf_writer.add_gen_audio_head_count_kv(lm["num_key_value_heads"]) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(lm["rms_norm_eps"]) + + # AudioVAE encoder: raw waveform -> latents, LocEnc in the gen model then makes the backbone rows + self.gguf_writer.add_clip_has_audio_encoder(True) + self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.VOXCPM2_SPKENC) + self.gguf_writer.add_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_audio_num_mel_bins(1) + self.gguf_writer.add_audio_block_count(0) + self.gguf_writer.add_audio_embedding_length(vae["encoder_dim"]) + self.gguf_writer.add_audio_feed_forward_length(vae["encoder_dim"]) + self.gguf_writer.add_audio_head_count(1) + self.gguf_writer.add_audio_attention_layernorm_eps(lm["rms_norm_eps"]) + # the ODE solver, the RoPE factors and the VAE layout are hard-coded in tools/mtmd + + def tensor_force_quant(self, name, new_name, bid, n_dims): + # the AudioVAE convs and the 1D tensors stay F32 + if new_name.startswith(("a.vae.", "a.gen.vae.")) or n_dims < 2: + return gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + if item[0].startswith("base_lm."): + return None + return item + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # already named by generate_extra_tensors() + if name.startswith("a."): + yield (name, data_torch) + return + + # dt is always 0 (mean_mode = false), delta_time_mlp gives a constant that is folded into the time_mlp bias + if name.startswith("feat_decoder.estimator.delta_time_mlp."): + return + if name == "feat_decoder.estimator.time_mlp.linear_2.bias": + data_torch = LazyTorchTensor.to_eager(data_torch).float() + self._dtime_const() + + if name == "feat_encoder.special_token": + yield ("a.gen.enc.special_token", data_torch.reshape(-1)) + return + + for src, dst in (("residual_lm.", "a.gen.res"), ("feat_encoder.encoder.", "a.gen.enc"), + ("feat_decoder.estimator.decoder.", "a.gen.code")): + if not name.startswith(src): + continue + key = name.removeprefix(src) + if key == "norm.weight": + yield (f"{dst}.output_norm.weight" if dst == "a.gen.res" else f"{dst}.post_ln.weight", data_torch) + return + assert bid is not None, name + key = key.removeprefix(f"layers.{bid}.") + layer_map = self._RES_LAYER_MAP if dst == "a.gen.res" else self._LAYER_MAP + yield (f"{dst}.blk.{bid}.{layer_map[key]}.weight", data_torch) + return + + base, _, suffix = name.rpartition(".") + yield (f"{self._PROJ_MAP[base]}.{suffix}", data_torch) + + # delta_time_mlp(SinusoidalPosEmb(0)), see VoxCPMLocDiTV2.forward() + def _dtime_const(self) -> Tensor: + d = {k: LazyTorchTensor.to_eager(self.model_tensors[f"feat_decoder.estimator.delta_time_mlp.{k}"]()).float() + for k in ("linear_1.weight", "linear_1.bias", "linear_2.weight", "linear_2.bias")} + dim = d["linear_1.weight"].shape[1] + emb = torch.cat([torch.zeros(dim // 2), torch.ones(dim // 2)]) # sin(0), cos(0) + h = torch.nn.functional.silu(d["linear_1.weight"] @ emb + d["linear_1.bias"]) + return d["linear_2.weight"] @ h + d["linear_2.bias"] + + @staticmethod + def _wn(sd: dict[str, Tensor], prefix: str) -> Tensor: + # torch weight norm, over every dim but 0 + g, v = sd[prefix + ".weight_g"].float(), sd[prefix + ".weight_v"].float() + return g * v / v.flatten(1).norm(dim=1).view(-1, *[1] * (v.dim() - 1)) + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + # LongRoPE factors of LocEnc and LocDiT, picked as in MiniCPMLongRoPE._set_cos_sin_cache() + lm = self.global_config["lm_config"] + rope = lm["rope_scaling"] + if rope.get("type") != "longrope": + raise NotImplementedError(f"VoxCPM2: unexpected rope_scaling {rope.get('type')}") + if lm["max_position_embeddings"] > rope["original_max_position_embeddings"]: + raise NotImplementedError("VoxCPM2: the long RoPE factors also scale cos/sin, not supported") + yield ("a.gen.rope_factors", torch.tensor(rope["short_factor"], dtype=torch.float32)) + + path = self.dir_model / "audiovae.pth" + logger.info(f"gguf: loading AudioVAE from '{path}'") + sd = torch.load(str(path), map_location="cpu", mmap=True, weights_only=True) + sd = sd.get("state_dict", sd) + vae = self.global_config["audio_vae_config"] + + def conv(dst: str, src: str) -> Iterable[tuple[str, Tensor]]: + yield (f"{dst}.weight", self._wn(sd, src)) + yield (f"{dst}.bias", sd[src + ".bias"].float()) + + def snake(dst: str, src: str) -> Iterable[tuple[str, Tensor]]: + alpha, beta = fold_snake(sd[src + ".alpha"]) + yield (f"{dst}.alpha", alpha) + yield (f"{dst}.beta", beta) + + def res_units(dst: str, src: str, first: int) -> Iterable[tuple[str, Tensor]]: + # dilation 1, 3, 9: Snake, depthwise conv k = 7, Snake, conv k = 1 + for r in range(3): + s = f"{src}.{first + r}.block" + d = f"{dst}.res.{r}" + yield from snake(f"{d}.snake1", f"{s}.0") + yield from conv(f"{d}.conv1", f"{s}.1") + yield from snake(f"{d}.snake2", f"{s}.2") + yield from conv(f"{d}.conv2", f"{s}.3") + + # encoder: conv, then per stride (3 residual units, Snake, strided conv), then fc_mu + p = "a.vae.enc" + yield from conv(f"{p}.conv_in", "encoder.block.0") + for b in range(len(vae["encoder_rates"])): + s = f"encoder.block.{b + 1}.block" + yield from res_units(f"{p}.blk.{b}", s, 0) + yield from snake(f"{p}.blk.{b}.snake", f"{s}.3") + yield from conv(f"{p}.blk.{b}.down", f"{s}.4") + yield from conv(f"{p}.fc_mu", "encoder.fc_mu") + + # decoder: depthwise conv, conv k = 1, then per stride (sample-rate scale and bias, Snake, transposed conv, 3 residual units), then Snake, conv + bounds = vae["sr_bin_boundaries"] + sr_idx = sum(1 for b in bounds if b < VAE_OUT_SAMPLE_RATE) # torch.bucketize + if vae["out_sample_rate"] != VAE_OUT_SAMPLE_RATE: + raise NotImplementedError(f"VoxCPM2: unexpected out_sample_rate {vae['out_sample_rate']}") + p = "a.gen.vae" + yield from conv(f"{p}.conv_in_dw", "decoder.model.0") + yield from conv(f"{p}.conv_in", "decoder.model.1") + n_up = len(vae["decoder_rates"]) + for b in range(n_up): + c = f"decoder.sr_cond_model.{b + 2}" + yield (f"{p}.blk.{b}.sr_scale", sd[c + ".scale_embed.weight"][sr_idx].float()) + yield (f"{p}.blk.{b}.sr_bias", sd[c + ".bias_embed.weight"][sr_idx].float()) + s = f"decoder.model.{b + 2}.block" + yield from snake(f"{p}.blk.{b}.snake", f"{s}.0") + yield from conv(f"{p}.blk.{b}.up", f"{s}.1") + yield from res_units(f"{p}.blk.{b}", s, 2) + yield from snake(f"{p}.post_snake", f"decoder.model.{n_up + 2}") + yield from conv(f"{p}.conv_out", f"decoder.model.{n_up + 3}") + + assert math.prod(vae["encoder_rates"]) * VAE_OUT_SAMPLE_RATE == math.prod(vae["decoder_rates"]) * vae["sample_rate"] diff --git a/conversion/yue2.py b/conversion/yue2.py new file mode 100644 index 000000000000..2242af8ebf60 --- /dev/null +++ b/conversion/yue2.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import base64 +from typing import Any, Callable, Iterable, TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, MmprojModel, gguf, logger +from .qwen import QwenModel, Qwen3Model + +# token ids of the yue2_infer protocol (protocol.py) +EOD = 151643 +ABC_START, ABC_END = 151847, 151848 +MUSIC_START, MUSIC_END = 151851, 151852 +CODEC_OFFSET, CODEC_SIZE = 151853, 32768 +LATENT_START = 184621 + +# the VAE is a separate repo (m-a-p/YuE2-Vae), downloaded into this subdir of the model dir +VAE_DIR = "vae" + +INSTRUCTIONS = { + "off": "Generate music with codec tokens from the given conditions.", + "melody": "Generate a melody-only ABC transcription without chord symbols, then generate music with codec tokens from the given conditions.", + "full": "Generate a chord-annotated ABC transcription, then generate music with codec tokens from the given conditions.", +} + +# the text is "[Tags]\n diff --git a/tools/ui/src/lib/components/app/content/index.ts b/tools/ui/src/lib/components/app/content/index.ts deleted file mode 100644 index 9f6bcf0c6eb5..000000000000 --- a/tools/ui/src/lib/components/app/content/index.ts +++ /dev/null @@ -1,142 +0,0 @@ -/** - * - * CONTENT RENDERING - * - * Components for rendering rich content: markdown, code, and previews. - * - */ - -/** - * **MarkdownContent** - Rich markdown renderer - * - * Renders markdown content with syntax highlighting, LaTeX math, - * tables, links, and code blocks. Optimized for streaming with - * incremental block-based rendering. - * - * **Features:** - * - GFM (GitHub Flavored Markdown): tables, task lists, strikethrough - * - LaTeX math via KaTeX (`$inline$` and `$$block$$`) - * - Syntax highlighting (highlight.js) with language detection - * - Code copy buttons with click feedback - * - External links open in new tab with security attrs - * - Image attachment resolution from message extras - * - Dark/light theme support (auto-switching) - * - Streaming-optimized incremental rendering - * - Code preview dialog for large blocks - * - * @example - * ```svelte - * - * ``` - */ -export { default as MarkdownContent } from './MarkdownContent/MarkdownContent.svelte'; - -/** - * **MarkdownEditor** - Live-preview markdown editor (CodeMirror) - * - * Edits markdown source in place: every block the cursor is not in renders - * exactly like MarkdownContent, and the block being edited shows its raw text - * in the same typography. The document is never rewritten, so the value stays - * byte-exact. Used by the chat form input. - * - * @example - * ```svelte - * (text = v)} placeholder="Write..." /> - * ``` - */ -export { default as MarkdownEditor } from './MarkdownEditor/MarkdownEditor.svelte'; - -/** - * **MentionText** - Plain text with file mention badges - * - * Renders a message verbatim, turning only `[name](file://path)` links - * into the same badge chips the markdown path draws. Nothing else is - * interpreted, so pasted code keeps its `#` comments and underscores. - * - * @example - * ```svelte - * - * ``` - */ -export { default as MentionText } from './MentionText.svelte'; - -/** - * **SyntaxHighlightedCode** - Code syntax highlighting - * - * Renders code with syntax highlighting using highlight.js. - * Supports theme switching and scrollable containers. - * - * **Features:** - * - Auto language detection with fallback - * - Dark/light theme auto-switching - * - Scrollable container with configurable max dimensions - * - Monospace font styling - * - Preserves whitespace and formatting - * - * @example - * ```svelte - * - * ``` - */ -export { default as SyntaxHighlightedCode } from './SyntaxHighlightedCode.svelte'; - -/** - * **CollapsibleContentBlock** - Expandable content card - * - * Reusable collapsible card with header, icon, and auto-scroll. - * Used for tool calls and reasoning blocks in chat messages. - * - * **Features:** - * - Collapsible content with smooth animation - * - Custom icon and title display - * - Optional subtitle/status text - * - Auto-scroll during streaming (pauses on user scroll) - * - Configurable max height with overflow scroll - * - * @example - * ```svelte - * - * {reasoningContent} - * - * ``` - */ -export { default as CollapsibleContentBlock } from './CollapsibleContentBlock.svelte'; - -/** - * **CollapsibleTerminalBlock** - Expandable content card with a terminal-style frame - * - * Same shape as CollapsibleContentBlock, but with a `code-background` - * fill, subtle border, and tightened padding suited for shell command - * output and similar dense / monospace content. - * - * @example - * ```svelte - * - *
{output}
- *
- * ``` - */ -export { default as CollapsibleTerminalBlock } from './CollapsibleTerminalBlock.svelte'; - -/** - * **MermaidPreview** - Interactive Mermaid diagram viewer - * - * Renders Mermaid-generated SVG diagrams with zoom, pan, and fit-to-view controls. - * - * **Features:** - * - Mouse wheel zoom in/out - * - Click-drag panning with pointer capture - * - Fit to view and reset view controls - * - Download as SVG - * - Responsive scaling with viewBox detection - * - * @example - * ```svelte - * - * ``` - */ -export { default as MermaidPreview } from './MermaidPreview.svelte'; diff --git a/tools/ui/src/lib/components/app/dialogs/DialogMcpServers.svelte b/tools/ui/src/lib/components/app/dialogs/DialogMcpServers.svelte deleted file mode 100644 index 8ab425c39544..000000000000 --- a/tools/ui/src/lib/components/app/dialogs/DialogMcpServers.svelte +++ /dev/null @@ -1,35 +0,0 @@ - - - - deviceStore.isMobile && event.preventDefault()} - > - - - - - MCP Servers - - - - - - diff --git a/tools/ui/src/lib/components/app/dialogs/DialogMermaidPreview.svelte b/tools/ui/src/lib/components/app/dialogs/DialogMermaidPreview.svelte deleted file mode 100644 index e741373497aa..000000000000 --- a/tools/ui/src/lib/components/app/dialogs/DialogMermaidPreview.svelte +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - diff --git a/tools/ui/src/lib/components/app/dialogs/DialogSearch.svelte b/tools/ui/src/lib/components/app/dialogs/DialogSearch.svelte deleted file mode 100644 index 185c3c1cb389..000000000000 --- a/tools/ui/src/lib/components/app/dialogs/DialogSearch.svelte +++ /dev/null @@ -1,275 +0,0 @@ - - -{#snippet hint(label: string, keys: (string | Component)[])} - - {label} - - - {#each keys as Key, index (index)} - - {#if typeof Key === 'string'} - {Key} - {:else} - - {/if} - - {/each} - - -{/snippet} - -{#snippet search()} -
-
- 0 ? `search-result-${activeIndex}` : undefined} - aria-controls="search-results" - aria-expanded="true" - autocomplete="off" - class="h-10 min-w-0 flex-1 border-0 bg-transparent px-1 text-lg outline-none placeholder:text-muted-foreground focus:outline-none focus-visible:ring-0" - oninput={() => (highlighted = 0)} - onkeydown={handleKeydown} - placeholder="Search" - role="combobox" - spellcheck={false} - /> - - handleOpenChange(false)} - /> -
-
- -
- {#each sections as section, sectionIndex (section.title)} - {@const offset = sections - .slice(0, sectionIndex) - .reduce((total, previous) => total + previous.entries.length, 0)} - -
-

- {section.title} -

- - {#each section.entries as entry, entryIndex (entry.id)} - {@const index = offset + entryIndex} - {@const isActive = index === activeIndex && !deviceStore.isMobile} - - - - {/each} -
- {:else} -

{emptyMessage}

- {/each} -
- -
- {@render hint('Close', ['Esc'])} - - {@render hint('Navigate', [ArrowUp, ArrowDown])} - - {@render hint('Open', [CornerDownLeft])} -
-{/snippet} - - - - { - event.preventDefault(); - inputRef?.focus(); - }} - > - Search - - {@render search()} - - diff --git a/tools/ui/src/lib/components/app/dialogs/index.ts b/tools/ui/src/lib/components/app/dialogs/index.ts deleted file mode 100644 index 5b3ca761d6f4..000000000000 --- a/tools/ui/src/lib/components/app/dialogs/index.ts +++ /dev/null @@ -1,537 +0,0 @@ -/** - * - * DIALOGS - * - * Modal dialog components for the chat application. - * - * All dialogs use ShadCN Dialog or AlertDialog components for consistent - * styling, accessibility, and animation. They integrate with application - * stores for state management and data access. - * - */ - -/** - * **DialogMcpServerAddNew** - Add new MCP server dialog - * - * Modal dialog for adding a new MCP server with URL and optional headers. - * Validates URL format and integrates with mcpStore and conversationsStore. - */ -export { default as DialogMcpServerAddNew } from './DialogMcpServerAddNew.svelte'; - -/** - * **DialogMcpServers** - MCP servers dialog shown from the chat form - * - * Shows the same MCP server list as the `/mcp-servers` route inside a modal - * dialog. - */ -export { default as DialogMcpServers } from './DialogMcpServers.svelte'; - -/** - * **DialogSettingsChat** - Chat settings shown in a modal dialog - * - * Wraps the full SettingsChat layout (sidebar, mobile header, fields, footer) - * inside a ShadCN Dialog instead of a dedicated route. Section switching is - * handled in-app via `onSectionChange` rather than URL navigation. - */ -export { default as DialogSettingsChat } from './DialogSettingsChat.svelte'; - -/** - * **DialogExportSettings** - Settings export dialog with sensitive data warning - * - * Dialog for exporting settings with an option to include or exclude - * sensitive data (API keys, MCP server custom headers). Defaults to excluding - * sensitive data for security. User must explicitly opt-in to include them. - * - * **Architecture:** - * - Uses ShadCN AlertDialog - * - Checkbox to toggle sensitive data inclusion (defaults to false) - * - Warning icon and message when sensitive data is included - * - Destructive variant for the action button when exporting with sensitive data - * - * **Features:** - * - Secure default: sensitive data excluded by default - * - User must explicitly opt-in to include sensitive data - * - Visual warning (ShieldOff icon) when sensitive data is included - * - Different action text based on sensitive data state - * - * @example - * ```svelte - * showExportSettings = false} - * /> - * ``` - */ -export { default as DialogExportSettings } from './DialogExportSettings.svelte'; - -/** - * - * CONFIRMATION DIALOGS - * - * Dialogs for user action confirmations. Use AlertDialog for blocking - * confirmations that require explicit user decision before proceeding. - * - */ - -/** - * **DialogConfirmation** - Generic confirmation dialog - * - * Reusable confirmation dialog with customizable title, description, - * and action buttons. Supports destructive action styling and custom icons. - * Used for delete confirmations, irreversible actions, and important decisions. - * - * **Architecture:** - * - Uses ShadCN AlertDialog - * - Supports variant styling (default, destructive) - * - Customizable button labels and callbacks - * - * **Features:** - * - Customizable title and description text - * - Destructive variant with red styling for dangerous actions - * - Custom icon support in header - * - Cancel and confirm button callbacks - * - Keyboard accessible (Escape to cancel, Enter to confirm) - * - * @example - * ```svelte - * showDelete = false} - * /> - * ``` - */ -export { default as DialogConfirmation } from './DialogConfirmation.svelte'; - -/** - * **DialogSearch** - Spotlight-style search over chats and sidebar actions - * - * Opens over the app with a focused input and a keyboard-driven result list: - * arrow keys move the highlight, Enter opens, Escape closes. A phone shows it full screen, like - * every dialog. - */ -export { default as DialogSearch } from './DialogSearch.svelte'; - -/** - * **DialogConfirmDownload** - Confirm a destructive download action - * - * Shared confirmation for stopping/cancelling an in-flight download or deleting - * a downloaded model, used by the discover quant chips and the model selector's - * download rows so both word the action identically. Owns the copy and the - * default store removal; render one instance per surface keyed by the acted-on - * repo:tag. - */ -export { default as DialogConfirmDownload } from './DialogConfirmDownload.svelte'; - -/** - * **DialogConversationDelete** - Confirm deleting a conversation - * - * Destructive confirmation shared by every conversation delete entry point - * (keyboard shortcut, sidebar, mobile search). - * - * @example - * ```svelte - * (showDelete = false)} - * /> - * ``` - */ -export { default as DialogConversationDelete } from './DialogConversationDelete.svelte'; - -/** - * **DialogConversationRename** - Rename a conversation - * - * Modal dialog for renaming a conversation. Replaces the prior - * `window.prompt()`-based flow with a styled, accessible AlertDialog - * containing an editable input. Triggered from the sidebar conversation - * item's "Edit" action. - * - * **Architecture:** - * - Uses ShadCN AlertDialog - * - Bindable `value` keeps the new title in sync with parent state - * - Submit is gated on a non-empty trimmed value that differs from the current title - * - * **Features:** - * - Autofocus on open with text selected for quick overwrite - * - Disabled Save button when value is empty or unchanged - * - Trim-on-submit normalization - * - Cancel via AlertDialog.Cancel or `onOpenChange(false)` - * - * @example - * ```svelte - * (showRename = false)} - * /> - * ``` - */ -export { default as DialogConversationRename } from './DialogConversationRename.svelte'; - -/** - * **DialogGroup** - Name a new sidebar group, or rename one - * - * Opened through `uiStore.openGroupDialog()`, from the Recent heading's - * menus to create a group and from a group's menus to rename it. Mounted - * once, in the sidebar. - */ -export { default as DialogGroup } from './DialogGroup.svelte'; - -/** - * **DialogGroupPicker** - Pick the group a chat moves to, on a phone - * - * Opened through `uiStore.openGroupPicker()` where a desktop menu shows the - * group submenu: a search that filters the groups and creates one with - * the typed name. Mounted once, in the sidebar. - */ -export { default as DialogGroupPicker } from './DialogGroupPicker.svelte'; - -/** - * - * CONTENT PREVIEW DIALOGS - * - * Dialogs for previewing and displaying content in full-screen or modal views. - * - */ - -/** - * **DialogCodePreview** - Full-screen code/HTML preview - * - * Full-screen dialog for previewing HTML or code in an isolated iframe. - * Used by MarkdownContent component for previewing rendered HTML blocks - * from code blocks in chat messages. - * - * **Architecture:** - * - Uses ShadCN Dialog with full viewport layout - * - Sandboxed iframe execution (allow-scripts only) - * - Clears content when closed for security - * - * **Features:** - * - Full viewport iframe preview - * - Sandboxed execution environment - * - Close button with mix-blend-difference for visibility over any content - * - Automatic content cleanup on close - * - Supports HTML preview with proper isolation - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogCodePreview } from './DialogCodePreview.svelte'; - -/** - * - * ATTACHMENT DIALOGS - * - * Dialogs for viewing and managing file attachments. Support both - * uploaded files (pending) and stored attachments (in messages). - * - */ - -/** - * **DialogChatAttachmentsPreview** - Unified attachment preview dialog - * - * Modal dialog for previewing file attachments. Automatically adapts to the - * number of items: shows a single file preview without carousel for one item, - * or a gallery with carousel navigation for multiple items. - * - * **Architecture:** - * - Wraps ChatAttachmentsPreview component in ShadCN Dialog - * - Accepts uploadedFiles and attachments arrays as data sources - * - Filters out MCP prompts and MCP resources from display - * - * **Features:** - * - Single item mode: direct preview without navigation controls - * - Multi-item mode: gallery with left/right arrows and thumbnail strip - * - File type aware preview (images, text, PDFs, audio) - * - File name and size/count display in header - * - * @example - * ```svelte - * - * - * ``` - */ -export { default as DialogChatAttachmentsPreview } from './DialogChatAttachmentsPreview.svelte'; - -/** - * - * ERROR & ALERT DIALOGS - * - * Dialogs for displaying errors, warnings, and alerts to users. - * Provide context about what went wrong and recovery options. - * - */ - -/** - * **DialogChatError** - Chat/generation error display - * - * Alert dialog for displaying chat and generation errors with context - * information. Supports different error types with appropriate styling - * and messaging. - * - * **Architecture:** - * - Uses ShadCN AlertDialog for modal display - * - Differentiates between timeout and server errors - * - Shows context info when available (token counts) - * - * **Error Types:** - * - **timeout**: TCP timeout with timer icon, red destructive styling - * - **server**: Server error with warning icon, amber warning styling - * - * **Features:** - * - Type-specific icons (TimerOff for timeout, AlertTriangle for server) - * - Error message display in styled badge - * - Context info showing prompt tokens and context size - * - Close button to dismiss - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogChatError } from './DialogChatError.svelte'; - -/** - * **DialogEmptyFileAlert** - Empty file upload warning - * - * Alert dialog shown when user attempts to upload empty files. Lists the - * empty files that were detected and removed from attachments, with - * explanation of why empty files cannot be processed. - * - * **Architecture:** - * - Uses ShadCN AlertDialog for modal display - * - Receives list of empty file names from ChatScreen - * - Triggered during file upload validation - * - * **Features:** - * - FileX icon indicating file error - * - List of empty file names in monospace font - * - Explanation of what happened and why - * - Single "Got it" dismiss button - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogEmptyFileAlert } from './DialogEmptyFileAlert.svelte'; - -/** - * **DialogFileUploadError** - File upload compatibility error - * - * Alert dialog shown when files cannot be uploaded due to type incompatibility - * or model modality restrictions. Displays a categorized list of problematic - * files with explanations and shows which file types the current model supports. - * - * **Architecture:** - * - Uses ShadCN AlertDialog for modal display - * - Receives structured file error data from ChatScreen - * - Triggered during file upload validation in processFiles() - * - * **Features:** - * - Categorized display: unsupported types vs modality restrictions - * - File name in monospace with contextual error messages - * - Summary of supported file types for the current model - * - Scrollable content area for large error lists - * - Single "Got it" dismiss button - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogFileUploadError } from './DialogFileUploadError.svelte'; - -/** - * **DialogModelNotAvailable** - Model unavailable error - * - * Alert dialog shown when the requested model (from URL params or selection) - * is not available on the server. Displays the requested model name and - * offers selection from available models. - * - * **Architecture:** - * - Uses ShadCN AlertDialog for modal display - * - Integrates with SvelteKit navigation for model switching - * - Receives available models list from modelsStore - * - * **Features:** - * - Warning icon with amber styling - * - Requested model name display in styled badge - * - Scrollable list of available models - * - Click model to navigate with updated URL params - * - Cancel button to dismiss without selection - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogModelNotAvailable } from './DialogModelNotAvailable.svelte'; - -/** - * - * DATA MANAGEMENT DIALOGS - * - * Dialogs for managing conversation data, including import/export - * and selection operations. - * - */ - -/** - * **DialogConversationSelection** - Conversation picker for import/export - * - * Dialog for selecting conversations during import or export operations. - * Displays list of conversations with checkboxes for multi-selection. - * Used by ChatSettingsImportExportTab for data management. - * - * **Architecture:** - * - Wraps ConversationSelection component in ShadCN Dialog - * - Supports export mode (select from local) and import mode (select from file) - * - Resets selection state when dialog opens - * - High z-index to appear above settings dialog - * - * **Features:** - * - Multi-select with checkboxes - * - Conversation title and message count display - * - Select all / deselect all controls - * - Mode-specific descriptions (export vs import) - * - Cancel and confirm callbacks with selected conversations - * - * @example - * ```svelte - * showExportSelection = false} - * /> - * ``` - */ -export { default as DialogConversationSelection } from './DialogConversationSelection.svelte'; - -/** - * **DialogMcpResourcesBrowser** - MCP resources browser dialog - * - * Dialog for browsing and attaching MCP resources to chat context. - * Displays resources from connected MCP servers in a tree structure - * with preview panel and multi-select support. - * - * **Architecture:** - * - Uses ShadCN Dialog with two-panel layout - * - Left panel: McpResourcesBrowser with tree navigation - * - Right panel: McpResourcePreview for selected resource - * - Integrates with mcpStore for resource fetching and attachment - * - * **Features:** - * - Tree-based resource navigation by server and path - * - Single and multi-select with shift+click - * - Resource preview with content display - * - Quick attach button per resource - * - Batch attach for multiple selections - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogMcpResourcesBrowser } from './DialogMcpResourcesBrowser.svelte'; - -/** - * **DialogMcpResourcePreview** - MCP resource content preview - * - * Dialog for previewing the content of a stored MCP resource attachment. - * Displays the resource content with syntax highlighting for code, - * image rendering for images, and plain text for other content. - * - * **Features:** - * - Syntax highlighted code preview - * - Image rendering for image resources - * - Copy to clipboard and download actions - * - Server name and favicon display - * - MIME type badge - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogMcpResourcePreview } from './DialogMcpResourcePreview.svelte'; - -/** - * **DialogMermaidPreview** - Full-screen Mermaid diagram preview with zoom and pan - * - * Full-screen dialog for previewing Mermaid diagrams with interactive controls. - * Supports mouse wheel zoom, drag-to-pan, and toolbar buttons for zoom in/out, - * fit to view, and reset. - * - * **Architecture:** - * - Uses UI dialog components (`Dialog.Root`, `Dialog.Overlay`, `Dialog.Content`) - * for consistent styling, animations, and accessibility - * - CSS transform-based zoom and pan (no external dependencies) - * - Pointer events for cross-device drag support (mouse + touch) - * - Wheel events for zoom-to-cursor functionality - * - * **Features:** - * - Scroll wheel zoom centered on cursor position - * - Click and drag to pan the diagram - * - Toolbar with zoom in, zoom out, fit to view, reset controls - * - Zoom percentage indicator - * - Keyboard accessible close button - * - Dark/light theme support - * - * @example - * ```svelte - * - * ``` - */ -export { default as DialogMermaidPreview } from './DialogMermaidPreview.svelte'; - -/** **DialogDiscoverModels** - shell for the Hugging Face model discovery view. */ -export { default as DialogDiscoverModels } from './DialogDiscoverModels.svelte'; diff --git a/tools/ui/src/lib/components/app/forms/index.ts b/tools/ui/src/lib/components/app/forms/index.ts deleted file mode 100644 index 87594d7e351e..000000000000 --- a/tools/ui/src/lib/components/app/forms/index.ts +++ /dev/null @@ -1,52 +0,0 @@ -/** - * - * FORMS & INPUTS - * - * Form-related utility components. - * - */ - -/** - * **InputWithSuggestions** - Input field with autocomplete suggestions - * - * Text input with dropdown suggestions and keyboard navigation. - * Supports autocomplete functionality with suggestion loading. - * - * **Features:** - * - Autocomplete dropdown with suggestions - * - Keyboard navigation (arrow keys, enter) - * - Loading state for suggestions - * - Focus and blur handling - */ -export { default as InputWithSuggestions } from './InputWithSuggestions.svelte'; - -/** - * **KeyValuePairs** - Editable key-value list - * - * Dynamic list of key-value pairs with add/remove functionality. - * Used for HTTP headers, metadata, and configuration. - * - * **Features:** - * - Add new pairs with button - * - Remove individual pairs - * - Customizable placeholders and labels - * - Empty state message - * - Auto-resize value textarea - */ -export { default as KeyValuePairs } from './KeyValuePairs.svelte'; - -/** - * **SearchInput** - Search field with clear button - * - * Input field optimized for search with clear button and keyboard handling. - * Supports placeholder, autofocus, and change callbacks. - */ -export { default as SearchInput } from './SearchInput.svelte'; - -/** - * **HighlightedMatch** - Substring-match text highlight - * - * Renders `text` with each case-insensitive occurrence of `query` wrapped - * in ``. - */ -export { default as HighlightedMatch } from './HighlightedMatch.svelte'; diff --git a/tools/ui/src/lib/components/app/index.ts b/tools/ui/src/lib/components/app/index.ts deleted file mode 100644 index 4914c743a50d..000000000000 --- a/tools/ui/src/lib/components/app/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export * from './actions'; -export * from './badges'; -export * from './chat'; -export * from './content'; -export * from './dialogs'; -export * from './forms'; -export * from './mcp'; -export * from './misc'; -export * from './settings'; -export * from './models'; -export * from './navigation'; -export * from './server'; diff --git a/tools/ui/src/lib/components/app/mcp/McpCapabilitiesBadges.svelte b/tools/ui/src/lib/components/app/mcp/McpCapabilitiesBadges.svelte deleted file mode 100644 index 596954703652..000000000000 --- a/tools/ui/src/lib/components/app/mcp/McpCapabilitiesBadges.svelte +++ /dev/null @@ -1,84 +0,0 @@ - - -{#if capabilities} - {#if capabilities.server.tools} - - - - Tools - - {/if} - - {#if capabilities.server.resources} - { - if (e.key === 'Enter' || e.key === ' ') { - e.preventDefault(); - onBrowseResources?.(); - } - }} - role="button" - tabindex={0} - variant="outline" - > - - - Resources - - - - {/if} - - {#if capabilities.server.prompts} - - - - Prompts - - {/if} - - {#if capabilities.server.logging} - - - - Logging - - {/if} - - {#if capabilities.server.completions} - - - - Completions - - {/if} - - {#if capabilities.server.tasks} - - - - Tasks - - {/if} -{/if} diff --git a/tools/ui/src/lib/components/app/mcp/McpConnectionLogs.svelte b/tools/ui/src/lib/components/app/mcp/McpConnectionLogs.svelte deleted file mode 100644 index 168d11b12c0a..000000000000 --- a/tools/ui/src/lib/components/app/mcp/McpConnectionLogs.svelte +++ /dev/null @@ -1,81 +0,0 @@ - - -{#if logs.length > 0} - -
- - {#if isExpanded} - - {:else} - - {/if} - - Connection Log ({logs.length}) - - {#if connectionTimeMs !== undefined} - · Connected in {connectionTimeMs}ms - {/if} - -
- - -
- {#each logs as log (log.timestamp.getTime() + log.message)} - {@const IconComponent = getMcpLogLevelIcon(log.level)} - -
- - {formatTime(log.timestamp)} - - - - - {log.message} -
- - {#if log.details !== undefined} -
- details - -
-{formatLogDetails(log.details)}
-
- {/if} - {/each} -
-
-
-{/if} diff --git a/tools/ui/src/lib/components/app/mcp/McpResourcePreview.svelte b/tools/ui/src/lib/components/app/mcp/McpResourcePreview.svelte deleted file mode 100644 index eb84b2ab6948..000000000000 --- a/tools/ui/src/lib/components/app/mcp/McpResourcePreview.svelte +++ /dev/null @@ -1,178 +0,0 @@ - - -
- {#if !resource} -
- - - Select a resource to preview -
- {:else} -
-
-

{resource.title || resource.name}

- -

{resource.uri}

- - {#if resource.description} -

{resource.description}

- {/if} -
- -
- - - -
-
- -
- {#if isLoading} -
- -
- {:else if error} -
- - - {error} -
- {:else if content} - {@const textContent = getResourceTextContent(content)} - {@const blobContent = getResourceBlobContent(content)} - - {#if textContent} -
{textContent}
- {/if} - - {#each blobContent as blob (blob.uri)} - {#if isImageMimeType(blob.mimeType ?? MimeTypeApplication.OCTET_STREAM)} - Resource content - {:else} -
- - - Binary content ({blob.mimeType || 'unknown type'}) -
- {/if} - {/each} - - {#if !textContent && blobContent.length === 0} -
No content available
- {/if} - {/if} -
- - {#if resource.mimeType || resource.annotations} -
- {#if resource.mimeType} - {resource.mimeType} - {/if} - - {#if resource.annotations?.priority !== undefined} - - Priority: {resource.annotations.priority} - - {/if} - - - Server: {resource.serverName} - -
- {/if} - {/if} -
diff --git a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardActions.svelte b/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardActions.svelte deleted file mode 100644 index a327a02e488a..000000000000 --- a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardActions.svelte +++ /dev/null @@ -1,40 +0,0 @@ - - -
- - - - - -
diff --git a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardHeader.svelte b/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardHeader.svelte deleted file mode 100644 index 9baded678e08..000000000000 --- a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardHeader.svelte +++ /dev/null @@ -1,72 +0,0 @@ - - -
-
-
-
- -
- - {#if capabilities || transportType} -
- {#if transportType} - {@const TransportIcon = MCP_TRANSPORT_ICONS[transportType]} - - {#if TransportIcon} - - {/if} - - {MCP_TRANSPORT_LABELS[transportType] || transportType} - - {/if} - - {#if capabilities} - - {/if} -
- {/if} -
- -
- -
-
-
diff --git a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte b/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte deleted file mode 100644 index e4882bcb79a7..000000000000 --- a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte +++ /dev/null @@ -1,47 +0,0 @@ - - - - - {#if isExpanded} - - {:else} - - {/if} - - {toolsCount} tools available · Show details - - - -
- {#each tools as tool (tool.name)} -
- {tool.name} - - {#if tool.description} -

{tool.description}

- {/if} -
- {/each} -
-
-
diff --git a/tools/ui/src/lib/components/app/mcp/McpServerCardSkeleton.svelte b/tools/ui/src/lib/components/app/mcp/McpServerCardSkeleton.svelte deleted file mode 100644 index 52776ff6067f..000000000000 --- a/tools/ui/src/lib/components/app/mcp/McpServerCardSkeleton.svelte +++ /dev/null @@ -1,42 +0,0 @@ - - - -
-
- - - - - -
- - -
- -
- - - - - -
- -
- - - -
- - - -
- - - - - -
-
diff --git a/tools/ui/src/lib/components/app/mcp/McpServerIdentity.svelte b/tools/ui/src/lib/components/app/mcp/McpServerIdentity.svelte deleted file mode 100644 index 23f72b7ea58b..000000000000 --- a/tools/ui/src/lib/components/app/mcp/McpServerIdentity.svelte +++ /dev/null @@ -1,63 +0,0 @@ - - - - {#if faviconUrl} - - {:else} - - {/if} - - - - {#if showVersion && serverInfo?.version} - - - - {/if} - - {#if showWebsite && safeWebsiteUrl} - e.stopPropagation()} - rel="noopener noreferrer" - target="_blank" - > - - - {/if} - diff --git a/tools/ui/src/lib/components/app/mcp/McpServerInfo.svelte b/tools/ui/src/lib/components/app/mcp/McpServerInfo.svelte deleted file mode 100644 index fe0a45532ee0..000000000000 --- a/tools/ui/src/lib/components/app/mcp/McpServerInfo.svelte +++ /dev/null @@ -1,35 +0,0 @@ - - -{#if instructions} - - - {#if isExpanded} - - {:else} - - {/if} - - Server instructions - - - -

- {instructions} -

-
-
-{/if} diff --git a/tools/ui/src/lib/components/app/misc/TruncatedText.svelte b/tools/ui/src/lib/components/app/misc/TruncatedText.svelte deleted file mode 100644 index 8e621d301088..000000000000 --- a/tools/ui/src/lib/components/app/misc/TruncatedText.svelte +++ /dev/null @@ -1,50 +0,0 @@ - - -{#if isTruncated && showTooltip} - - - - {text} - - - - -

{text}

-
-
-{:else} - - {text} - -{/if} diff --git a/tools/ui/src/lib/components/app/misc/index.ts b/tools/ui/src/lib/components/app/misc/index.ts deleted file mode 100644 index 89a3c5313443..000000000000 --- a/tools/ui/src/lib/components/app/misc/index.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * - * MISC - * - * Miscellaneous utility components. - * - */ - -/** - * **ConversationSelection** - Multi-select conversation picker - * - * List of conversations with checkboxes for multi-selection. - * Used in import/export dialogs for selecting conversations. - * - * **Features:** - * - Search/filter conversations by name - * - Select all / deselect all controls - * - Shift-click for range selection - * - Message count display per conversation - * - Mode-specific UI (export vs import) - */ -export { default as ConversationSelection } from './ConversationSelection.svelte'; - -/** - * **TruncatedText** - Text with ellipsis and tooltip - * - * Displays text with automatic truncation and full content in tooltip. - * Useful for long names or paths in constrained spaces. - */ -export { default as TruncatedText } from './TruncatedText.svelte'; - -/** - * **KeyboardShortcutInfo** - Keyboard shortcut hint display - * - * Displays keyboard shortcut hints (e.g., "⌘ + Enter"). - * Supports special keys like shift, cmd, and custom text. - */ -export { default as KeyboardShortcutInfo } from './KeyboardShortcutInfo.svelte'; - -/** - * **ScrollCarousel** - Feature/carousel with center-aligned overflow controls - * - * Horizontal scrollable container with arrows that center the focused item. - */ -export { default as ScrollCarousel } from './ScrollCarousel.svelte'; - -/** - * **CodeBlockActions** - Actions bar for code blocks (copy, preview) - * - * Displays copy-to-clipboard and preview buttons for code blocks. - * Preview button is shown only for HTML code blocks. - */ -export { default as CodeBlockActions } from './CodeBlockActions.svelte'; - -/** - * **Logo** - Application brand mark - * - * Inline SVG of the application logo. Accepts styling via the standard - * `class` and `style` props and inherits color via `currentColor`. - */ -export { default as Logo } from './Logo.svelte'; - -/** Two-line menu glyph for the phone sidebar toggle, its lower line two thirds as long. */ -export { default as MenuIcon } from './MenuIcon.svelte'; - -/** Section with a trigger that expands in place. */ -export { default as CollapsibleSection } from './CollapsibleSection.svelte'; -export { - default as GroupedList, - type GroupedListGroup, - GroupedListUnit -} from './GroupedList.svelte'; -export { default as CollapsibleRegion } from './CollapsibleRegion.svelte'; diff --git a/tools/ui/src/lib/components/app/models/ModelCapabilities.svelte b/tools/ui/src/lib/components/app/models/ModelCapabilities.svelte deleted file mode 100644 index 4d158efbb178..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelCapabilities.svelte +++ /dev/null @@ -1,63 +0,0 @@ - - - (isNearViewport = true)} class={className}> - - diff --git a/tools/ui/src/lib/components/app/models/ModelCapabilityIcons.svelte b/tools/ui/src/lib/components/app/models/ModelCapabilityIcons.svelte deleted file mode 100644 index 3743a158fdca..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelCapabilityIcons.svelte +++ /dev/null @@ -1,87 +0,0 @@ - - -{#if hasIcons} - - {#if !hideCapabilities} - {#each capabilities as capability (capability)} - {@const Icon = CAPABILITY_ICONS[capability]} - - - - - - - -

{CAPABILITY_LABELS[capability]}

-
-
- {/each} - {/if} - - {#if shownModalities.length > 0 && !hideModalities} - - {#each shownModalities as modality (modality)} - {@const Icon = MODALITY_ICONS[modality]} - - - - - - - -

{MODALITY_LABELS[modality]}

-
-
- {/each} -
- {/if} -
-{/if} diff --git a/tools/ui/src/lib/components/app/models/ModelDraftSidecars.svelte b/tools/ui/src/lib/components/app/models/ModelDraftSidecars.svelte deleted file mode 100644 index 4e7b07156059..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelDraftSidecars.svelte +++ /dev/null @@ -1,40 +0,0 @@ - - -{#each badges as badge (badge.kind + (badge.quant ?? ''))} - - {badge.kind} - -{/each} diff --git a/tools/ui/src/lib/components/app/models/ModelDraftSubline.svelte b/tools/ui/src/lib/components/app/models/ModelDraftSubline.svelte deleted file mode 100644 index 101215d11138..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelDraftSubline.svelte +++ /dev/null @@ -1,53 +0,0 @@ - - - -
- - - Draft model - - {kind} - - {#if quant} - {quant} - {/if} - - {#if state === ModelRowDownloadState.DOWNLOADED} - - {:else} - - {#if percent !== null} - {percent}% - {:else if state === ModelRowDownloadState.PAUSED} - Paused - {/if} - - {/if} -
diff --git a/tools/ui/src/lib/components/app/models/ModelId.svelte b/tools/ui/src/lib/components/app/models/ModelId.svelte deleted file mode 100644 index 9a3464ab861b..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelId.svelte +++ /dev/null @@ -1,261 +0,0 @@ - - -{#if resolvedShowRaw} - -{:else} - {#snippet nameAndBadges()} - {#if !hideName} - - {#if !hideOrgName && parsed.orgName}{parsed.orgName}/{/if}{displayName} - - {/if} - - {#if hasBadges} - - - {#if parsed.sidecar} - - {parsed.sidecar} - - {/if} - - {#if parsed.params && !hideParameters} - - {parsed.params}{parsed.activatedParams ? `-${parsed.activatedParams}` : ''} - - {/if} - - {#if parsed.quantization && !resolvedHideQuantization} - - {parsed.quantization} - - {/if} - - {#each uniqueDraftKinds as kind (kind)} - - {kind} - - {/each} - - - - {#if primaryAlias} - {#if primaryAlias !== parsed.modelName} - - {parsed.modelName ?? modelId} - - {/if} - {:else if uniqueAliases.length > 1} - {#each uniqueAliases.slice(0, MAX_ALIAS_BADGES) as alias (alias)} - - {alias} - - {/each} - - {#if uniqueAliases.length > MAX_ALIAS_BADGES} - - +{uniqueAliases.length - MAX_ALIAS_BADGES} more - - {/if} - {/if} - - {#if uniqueTags.length > 0 && !resolvedHideTags} - {#each uniqueTags as tag (tag)} - {tag} - {/each} - {/if} - - {/if} - {/snippet} - - - - - {#if showRawTooltip} - - - {@render nameAndBadges()} - - - -

{modelId}

-
-
- {:else} - {@render nameAndBadges()} - {/if} - - {#if !iconsOnNewLine} - - {/if} -
- - {#if iconsOnNewLine || contextLength || sizeRange} - - {#if iconsOnNewLine} - - {/if} - - {#if contextLength} - - - - {formatParameters(contextLength)} - - {/if} - - {#if sizeRange} - - - - {HuggingFaceService.formatSizeRange(sizeRange.min, sizeRange.max)} - - {/if} - - {/if} -
-{/if} diff --git a/tools/ui/src/lib/components/app/models/ModelLoadControl.svelte b/tools/ui/src/lib/components/app/models/ModelLoadControl.svelte deleted file mode 100644 index 6d1ea5a93e60..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelLoadControl.svelte +++ /dev/null @@ -1,107 +0,0 @@ - - -
- {#if isLoading} - - {:else} - - {#if showAction && revealOnHover} - {#if isFailed} - - {:else} - - {/if} - {:else} - {#if isFailed} - - {:else} - - {/if} - {/if} - - -
- {#if isFailed} - modelsStore.status.load(option.model)} - stopPropagationOnClick - tooltip="Retry loading model" - tooltipAsTitle - /> - {:else if isLoaded || isSleeping} - modelsStore.status.unload(option.model)} - stopPropagationOnClick - tooltip="Unload model" - tooltipAsTitle - /> - {:else} - modelsStore.status.load(option.model)} - stopPropagationOnClick - tooltip="Load model" - tooltipAsTitle - /> - {/if} -
- {/if} -
diff --git a/tools/ui/src/lib/components/app/models/ModelOrgAvatar.svelte b/tools/ui/src/lib/components/app/models/ModelOrgAvatar.svelte deleted file mode 100644 index 5befb9306d07..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelOrgAvatar.svelte +++ /dev/null @@ -1,130 +0,0 @@ - - -{#if hubEnabled} - - {#if orgAvatarFailed} - - {:else} -
- - { - failedAvatarOrgs.set(org, Date.now()); - }} - src={HuggingFaceService.getAvatarUrl(org)} - /> -
- {/if} - - {#if quantOrg && quantOrg !== org} - - - {#if quantAvatarFailed} - - {:else} - { - failedAvatarOrgs.set(quantOrg ?? '', Date.now()); - }} - src={HuggingFaceService.getAvatarUrl(quantOrg)} - /> - {/if} - - {/if} -
-{/if} diff --git a/tools/ui/src/lib/components/app/models/ModelRowActions.svelte b/tools/ui/src/lib/components/app/models/ModelRowActions.svelte deleted file mode 100644 index 5c2f321bd2df..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelRowActions.svelte +++ /dev/null @@ -1,74 +0,0 @@ - - -
event.stopPropagation()} - onkeydown={(event) => event.stopPropagation()} - role="presentation" -> - - uiStore.openModelDetails(option.id)} - tooltip="Manage model" - tooltipAsTitle - /> - - - {#if isFav} - - - modelsStore.toggleFavorite(option.model)} - tooltip="Remove from favorites" - tooltipAsTitle - /> - - - - - {:else} - - modelsStore.toggleFavorite(option.model)} - tooltip="Add to favorites" - tooltipAsTitle - /> - - {/if} -
diff --git a/tools/ui/src/lib/components/app/models/ModelsManager/ModelsManagerDownloadControl.svelte b/tools/ui/src/lib/components/app/models/ModelsManager/ModelsManagerDownloadControl.svelte deleted file mode 100644 index 5e77caed06e8..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelsManager/ModelsManagerDownloadControl.svelte +++ /dev/null @@ -1,47 +0,0 @@ - - - -
- - {percent !== null ? `${percent}%` : isPaused ? 'Paused' : ''} - - - -
diff --git a/tools/ui/src/lib/components/app/models/ModelsManager/utils.ts b/tools/ui/src/lib/components/app/models/ModelsManager/utils.ts deleted file mode 100644 index 7241fc35583b..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelsManager/utils.ts +++ /dev/null @@ -1,219 +0,0 @@ -import { LOCAL_BACKEND_ID, type ModalityKey } from '$lib/constants'; -import { ModelCapability, ModelGroupKind, ModelsTableGroupKind } from '$lib/enums'; -import { HuggingFaceService, ModelsService } from '$lib/services'; -import { modelsStore } from '$lib/stores'; -import type { - ModelDownloadEntry, - ModelDownloadProgress, - ModelOption, - ModelSidecarBadge -} from '$lib/types/models'; -import { detectThinkingSupport, detectToolUseSupport, repoOf } from '$lib/utils'; - -/** One repo of the table, with the rows it ships as. */ -export interface ModelQuantGroup { - base: ModelOption; - key: string; - kind: ModelGroupKind; - quants: ModelOption[]; - /** Draft sidecars already on disk, shown as checked sub-lines. */ - sidecarBadges?: ModelSidecarBadge[]; -} - -/** True when any of the manager's filters narrows the table. */ -export function hasActiveFilters( - contextLimit: number, - modalities: ModalityKey[], - capabilities: ModelCapability[] -): boolean { - return contextLimit > 0 || modalities.length > 0 || capabilities.length > 0; -} - -/** Byte counts of a tracked download: live while it runs, frozen while paused. */ -export function downloadProgressFor(repoWithTag: string): ModelDownloadProgress | null { - return ( - modelsStore.status.getDownloadProgress(repoWithTag) ?? - modelsStore.status.getPausedDownloadProgress(repoWithTag) - ); -} - -/** - * One table row per tracked download, listed like any other model. A paused download - * is already in the router's listing, so its own option is reused; a fresh one is - * synthesized for its tag alone. - */ -export function downloadGroups( - entries: ModelDownloadEntry[], - models: ModelOption[], - sidecarsFor: (repo: string) => ModelSidecarBadge[] -): ModelQuantGroup[] { - return entries.map((entry) => { - const listed = models.find((candidate) => candidate.model === entry.repoWithTag); - // the synthesized option carries backendId, which ModelOption drops on - // assignment, so the callers spread it instead of typing this as one - const option = listed ?? { - backendId: LOCAL_BACKEND_ID, - capabilities: [], - id: entry.repoWithTag, - model: entry.repoWithTag, - name: entry.repoWithTag - }; - // a draft still coming down badges the id, an on-disk one keeps its sub-line - const sidecars = sidecarsFor(repoOf(entry.repoWithTag)); - const pending = sidecars.filter((badge) => badge.pending); - - return { - base: { ...option, draftSidecars: pending }, - key: `download::${entry.repoWithTag}`, - kind: ModelGroupKind.QUANTS, - quants: [{ ...option, draftSidecars: pending }], - sidecarBadges: sidecars.filter((badge) => !badge.pending) - }; - }); -} - -/** Model with this qualified id or raw name, from the listing or else the tracked downloads. */ -export function findModelOption( - key: string | null, - models: ModelOption[], - downloads: ModelQuantGroup[] -): ModelOption | null { - if (!key) return null; - - const matches = (candidate: ModelOption) => candidate.id === key || candidate.model === key; - - return models.find(matches) ?? downloads.find((group) => matches(group.base))?.base ?? null; -} - -/** One collapsible block of the manager's table. */ -export interface ModelsTableGroup { - /** One entry per repo, its quants hanging off it. */ - items: ModelQuantGroup[]; - key: string; - kind: ModelsTableGroupKind; - label: string; -} - -/** Controls in a model row that act on their own, so a row click passes them by. */ -const ROW_CONTROL_SELECTOR = 'button, a, input, [role="menuitem"]'; - -/** Whether a click on a model row landed on one of its own controls. */ -export function isRowControlClick(event: MouseEvent): boolean { - return event.target instanceof Element && event.target.closest(ROW_CONTROL_SELECTOR) !== null; -} - -/** Context the model runs with: what a loaded model reports. */ -export function configuredContext(option: ModelOption): number | null { - return modelsStore.isModelRunning(option.model) - ? modelsStore.props.getModelContextSize(option.model) - : null; -} - -/** - * Capability a model reports: true or false once its listing or its chat template - * answers, null while the Hub record that carries the template is not read yet. - */ -export function modelCapability(option: ModelOption, capability: ModelCapability): boolean | null { - if (option.capabilities.includes(capability)) return true; - - const details = HuggingFaceService.cachedDetails(option.model); - - // only the chat template answers this, and it arrives with the Hub record - if (details === undefined) return null; - - const template = details?.gguf?.chat_template ?? ''; - - return capability === ModelCapability.TOOL_USE - ? detectToolUseSupport(template) - : detectThinkingSupport(template); -} - -/** - * Context a model reports: the provider listing first, then the cached Hub record. - * Null while neither of them has answered. - */ -export function modelContextLength(option: ModelOption): number | null { - return ( - option.contextLength ?? - HuggingFaceService.cachedDetails(option.model)?.gguf?.context_length ?? - null - ); -} - -/** Fold the quants of one repo into a single entry, so the table shows one row per model. */ -export function groupModelQuants(models: ModelOption[]): ModelQuantGroup[] { - const groups = new Map(); - - for (const option of models) { - const key = repoOf(option.model); - const group = groups.get(key); - - if (group) { - group.quants.push(option); - - continue; - } - - groups.set(key, { base: option, key, kind: ModelGroupKind.QUANTS, quants: [option] }); - } - - return Array.from(groups.values()).flatMap((group) => { - const kind = groupKind(group.quants); - const modelIds = group.quants.map((option) => option.model); - - // the very same id twice is not a quant set; keep those rows apart - if (modelIds.length > 1 && modelIds.every((model) => model === modelIds[0])) { - return group.quants.map((option) => ({ - ...group, - base: option, - key: `${group.key}::${option.id}`, - kind: ModelGroupKind.VARIANTS, - quants: [option] - })); - } - - return [{ ...group, kind }]; - }); -} - -/** What a group folds: quants or variants of one repo. */ -function groupKind(quants: ModelOption[]): ModelGroupKind { - const isQuant = quants.every( - (option) => (option.parsedId ?? ModelsService.parseModelId(option.model)).quantization - ); - - return isQuant ? ModelGroupKind.QUANTS : ModelGroupKind.VARIANTS; -} - -/** - * Split the repos of a section into the quants that are hidden and the ones that - * are not, so a partly hidden repo lists in both blocks instead of dragging its - * visible quants into the hidden one. - */ -export function splitHiddenQuants( - entries: ModelQuantGroup[], - isHidden: (option: ModelOption) => boolean -): { hidden: ModelQuantGroup[]; local: ModelQuantGroup[] } { - const hidden: ModelQuantGroup[] = []; - const local: ModelQuantGroup[] = []; - - for (const entry of entries) { - const hiddenQuants = entry.quants.filter((quant) => isHidden(quant)); - const localQuants = entry.quants.filter((quant) => !isHidden(quant)); - - if (hiddenQuants.length > 0) { - hidden.push({ - ...entry, - base: hiddenQuants[0], - key: `${entry.key}::hidden`, - quants: hiddenQuants - }); - } - - if (localQuants.length > 0) { - local.push({ ...entry, base: localQuants[0], quants: localQuants }); - } - } - - return { hidden, local }; -} diff --git a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelector.svelte b/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelector.svelte deleted file mode 100644 index 4b53ef6a0265..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelector.svelte +++ /dev/null @@ -1,419 +0,0 @@ - - -{#snippet selectorTriggerInner()} - - - - {#if selectedOption} - - {:else} - Select model - {/if} - - - {#if ms.updating || ms.isLoadingModel || triggerLoading} - - {:else} - - {/if} - - {#if triggerLoading} - - {/if} -{/snippet} - -{#snippet modelOption(item: ModelItem, hideOrgName: boolean)} - {@const { option } = item} - {@const isSelected = ms.activeId === option.id} - {@const isHighlighted = option.id === highlightedId} - {@const isFav = ms.isFavorite(option.model)} - - { - if (event.key === KeyboardKey.ENTER || event.key === KeyboardKey.SPACE) { - event.preventDefault(); - void handleModelKeyAction(option.id, event.altKey); - } - }} - onMouseEnter={() => (highlightedId = option.id)} - onSelect={ms.handleSelect} - {option} - /> -{/snippet} - -{#snippet pickerList(listClass: string)} -
- {#if !ms.isCurrentModelInCache && displayModel} - - - {/if} - - {#if ms.isEmpty} -

{ms.emptyMessage}

- {/if} - - -
-{/snippet} - -{#if ms.loading && ms.options.length === 0 && ms.isMultiModel} -
- - - Loading models... -
-{:else if ms.options.length === 0 && ms.isMultiModel} - {#if displayModel} - - - - {:else} - No models yet. - {/if} -{:else if ms.isMultiModel} - {#if isMobile} - - - ms.setSearchTerm(v)} - onSearchKeyDown={handleSearchKeyDown} - searchTerm={ms.searchTerm} - > - {@render pickerList('px-2.5')} - - {:else} - (highlightedId = id)} - onModelKeyAction={(id, unload) => void handleModelKeyAction(id, unload)} - onSearchKeyDown={handleSearchKeyDown} - {showOrgName} - /> - {/if} -{:else if isMobile} - - - - ms.setSearchTerm(v)} - onSearchKeyDown={handleSearchKeyDown} - searchTerm={ms.searchTerm} - > - {@render pickerList('px-2.5')} - -{:else} - - - - - {#snippet child({ props })} - - {/snippet} - - -{/if} diff --git a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorDownloadItem.svelte b/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorDownloadItem.svelte deleted file mode 100644 index 995bfe6618fa..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorDownloadItem.svelte +++ /dev/null @@ -1,170 +0,0 @@ - - - -
-
- - - - - - - uiStore.openModelDetails(entry.repoWithTag)} - tooltip="Manage model" - tooltipAsTitle - /> - - onRequestCancel?.(entry.repoWithTag)} - /> -
- - - {#if onDiskDrafts.length} -
- {#each onDiskDrafts as badge (badge.repo + ':' + badge.kind + ':' + (badge.quant ?? ''))} - - {/each} -
- {/if} - - {#if entry.progress && entry.progress.totalBytes > 0} - - {/if} -
diff --git a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorDropdown.svelte b/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorDropdown.svelte deleted file mode 100644 index aeff24fd7b0d..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorDropdown.svelte +++ /dev/null @@ -1,267 +0,0 @@ - - -{#snippet selectorTriggerInner()} - - - - {#if selectedOption} - - {:else} - Select model - {/if} - - - {#if ms.updating || ms.isLoadingModel || triggerLoading} - - {:else} - - {/if} - - {#if triggerLoading} - - {/if} -{/snippet} - -{#snippet modelOption(item: ModelItem, hideOrgName: boolean)} - {@const { option } = item} - {@const isSelected = currentModel === option.model || ms.activeId === option.id} - {@const isHighlighted = option.id === highlightedId} - {@const isFav = ms.isFavorite(option.model)} - - { - if (event.key === KeyboardKey.ENTER || event.key === KeyboardKey.SPACE) { - event.preventDefault(); - onModelKeyAction?.(option.id, event.altKey); - } - }} - onMouseEnter={() => onHighlight?.(option.id)} - onSelect={ms.handleSelect} - {option} - /> -{/snippet} - - - - - - {#snippet child({ props })} - - {@render selectorTriggerInner()} - - {/snippet} - - - {#if selectedOption} - -

{triggerTooltipLabel(selectedOption)}

-
- {/if} -
- - - { - // bits-ui re-mounts the focus scope when the drawer opens or closes, so this runs with the menu still open; trigger focus would show its tooltip - if (open) event.preventDefault(); - }} - onFocusOutside={(event) => { - if (uiStore.isModelDetailsOpen) event.preventDefault(); - }} - onInteractOutside={(event) => { - if (uiStore.isModelDetailsOpen) event.preventDefault(); - }} - onOpenAutoFocus={(event) => event.preventDefault()} - > - ms.setSearchTerm(v)} - {onSearchKeyDown} - placeholder="Search models..." - searchClass="bg-transparent" - searchValue={ms.searchTerm} - > - - {@render pickerContent('px-1.5')} - - {#snippet footer()} - - - - - Manage models - - - {/snippet} - - -
- -{#snippet pickerContent(listClass: string)} -
- {#if !ms.isCurrentModelInCache && currentModel} - - - {/if} - - {#if ms.isEmpty} -

{ms.emptyMessage}

- {/if} - - -
-{/snippet} - - diff --git a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorTriggerIcon.svelte b/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorTriggerIcon.svelte deleted file mode 100644 index 6c9621cddcb2..000000000000 --- a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorTriggerIcon.svelte +++ /dev/null @@ -1,23 +0,0 @@ - - -{#if option} - - {#snippet fallback()} - - {/snippet} - -{:else} - -{/if} diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverChatTemplateDialog.svelte b/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverChatTemplateDialog.svelte deleted file mode 100644 index 11240a4a91e1..000000000000 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverChatTemplateDialog.svelte +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - - Chat template - - - - - - - - - - - diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsDraftDownloadButton.svelte b/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsDraftDownloadButton.svelte deleted file mode 100644 index d7cbd8becd84..000000000000 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsDraftDownloadButton.svelte +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - {#snippet child({ props })} - - {/snippet} - - - -

{tooltipText}

-
-
diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsQuantDownloadButton.svelte b/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsQuantDownloadButton.svelte deleted file mode 100644 index 5ccbd31d08c7..000000000000 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsDownloadOptions/ModelsDiscoverDetailsDownloadOptionsQuantDownloadButton.svelte +++ /dev/null @@ -1,272 +0,0 @@ - - -{#snippet chipBody(dividerClass: string)} - - {label} - - {#if showsCompanion && companion} - + - - - - {companion.kind}{companion.quant ? `:${companion.quant}` : ''} - - {#if companion.onDisk} - - {/if} - - {/if} - - -{/snippet} - - -{#snippet tooltipTrigger(tip: string, button: Snippet<[Record]>)} - - - {#snippet child({ props })} - {@render button(props)} - {/snippet} - - - -

{tip}

-
-
-{/snippet} - -{#snippet deleteChip(props: Record)} - - -{/snippet} - -{#snippet pauseResumeChip(props: Record)} - -{/snippet} - -{#snippet cancelChip(props: Record)} - - -{/snippet} - -{#snippet downloadChip(props: Record)} - - -{/snippet} - -{#if entry.isDownloaded} - {@render tooltipTrigger(tooltipText, deleteChip)} -{:else if entry.isDownloading || entry.isPaused} - -
- {@render tooltipTrigger(tooltipText, pauseResumeChip)} - - {@render tooltipTrigger('Cancel downloading', cancelChip)} - - {#if percent !== null} - - {/if} -
-{:else} - {@render tooltipTrigger(tooltipText, downloadChip)} -{/if} diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHeader.svelte b/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHeader.svelte deleted file mode 100644 index b2020fc31bf6..000000000000 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHeader.svelte +++ /dev/null @@ -1,105 +0,0 @@ - - -
-
-
- - -
-
-

{details.id ?? modelId}

- - -
- - {#if baseModels.length} -
- {baseModels.join(', ')} - - - - -
- {/if} -
-
- - -
- - - - -
diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHfHubStats.svelte b/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHfHubStats.svelte deleted file mode 100644 index b848a9bfeb35..000000000000 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHfHubStats.svelte +++ /dev/null @@ -1,31 +0,0 @@ - - -
- {#if typeof details.downloads === 'number'} - - - {HuggingFaceService.formatDownloads(details.downloads)} - - {/if} - - {#if typeof details.likes === 'number'} - - - {HuggingFaceService.formatLikes(details.likes)} - - {/if} - - {#if details.lastModified} - Updated {HuggingFaceService.formatRelativeTime(details.lastModified)} - {/if} -
diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsReadme.svelte b/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsReadme.svelte deleted file mode 100644 index fbf043b79712..000000000000 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsReadme.svelte +++ /dev/null @@ -1,17 +0,0 @@ - - -{#if readme} -
- -
-{/if} diff --git a/tools/ui/src/lib/components/app/models/index.ts b/tools/ui/src/lib/components/app/models/index.ts deleted file mode 100644 index c2736fb7741c..000000000000 --- a/tools/ui/src/lib/components/app/models/index.ts +++ /dev/null @@ -1,68 +0,0 @@ -/** - * - * MODELS - * - * Components for model selection and display. Supports two server modes: - * - **Single model mode**: Server runs with one model, selector shows model info - * - **Router mode**: Server runs with multiple models, selector enables switching - * - * Integrates with modelsStore for model data and serverStore for mode detection. - * - */ - -/** * **ModelBadge** - Model name display badge - * - * Compact badge showing current model name with package icon. - * Only visible in single model mode. Supports tooltip and copy functionality. - * - * **Architecture:** - * - Reads model name from modelsStore or prop - * - Checks server mode from serverStore - * - Uses BadgeInfo for consistent styling - * - * **Features:** - * - Optional copy to clipboard button - * - Optional tooltip with model details - * - Click handler for model info dialog - * - Only renders in model mode (not router) - * - * @example - * ```svelte - * showModelInfo = true} - * showTooltip - * showCopyIcon - * /> - * ``` - */ -export { default as ModelBadge } from './ModelBadge.svelte'; - -/** - * **ModelId** - Parsed model identifier display - * - * Displays a model ID with optional org name, parameter badges, quantization, - * aliases, and tags. Supports raw mode to show the unprocessed model name. - * Respects the user's `showRawModelNames` setting. - */ -export { default as ModelCapabilities } from './ModelCapabilities.svelte'; -export { default as ModelContext } from './ModelContext.svelte'; -export { default as ModelId } from './ModelId.svelte'; -export { default as ModelAvatar } from './ModelAvatar.svelte'; -export { default as ModelDownloadProgressBar } from './ModelDownloadProgressBar.svelte'; -export { default as ModelLoadControl } from './ModelLoadControl.svelte'; -export { default as ModelOrgAvatar } from './ModelOrgAvatar.svelte'; -export { default as ModelRowActions } from './ModelRowActions.svelte'; -export { default as ModelsSection } from './ModelsSection.svelte'; - -/** Capability and modality icon row, shared by every model-id surface. */ -export { default as ModelCapabilityIcons } from './ModelCapabilityIcons.svelte'; - -/** Draft sidecar badges, rendered as `+ [KIND] [QUANT]` per sidecar. */ -export { default as ModelDraftSidecars } from './ModelDraftSidecars.svelte'; - -/** Compact draft download line, embedded in the item it belongs to. */ -export { default as ModelDraftSubline } from './ModelDraftSubline.svelte'; -export * from './ModelsSelector'; - -/** Model details drawer, mounted once and opened over any page through `uiStore.openModelDetails`. */ -export { default as ModelsManagerModelDrawer } from './ModelsManager/ModelsManagerModelDrawer.svelte'; diff --git a/tools/ui/src/lib/components/app/navigation/DropdownMenuActions.svelte b/tools/ui/src/lib/components/app/navigation/DropdownMenuActions.svelte deleted file mode 100644 index 158c55858e03..000000000000 --- a/tools/ui/src/lib/components/app/navigation/DropdownMenuActions.svelte +++ /dev/null @@ -1,139 +0,0 @@ - - -{#if isMobile} - - - - - - {triggerTooltip ?? 'Actions'} - - -
- {#each actions as action, index (action.label)} - {#if action.separator && index > 0} - - {/if} - - - {/each} -
-
-
-{:else} - - - - - {#snippet child({ props })} - e.stopPropagation()} - > - {@render iconComponent(triggerIcon, 'h-3 w-3')} - - {#if triggerTooltip} - {triggerTooltip} - {/if} - - {/snippet} - - - {#if triggerTooltip} - -

{triggerTooltip}

-
- {/if} -
- - - (open = false)} /> - -
-{/if} - -{#snippet iconComponent(IconComponent: Component, className: string)} - -{/snippet} diff --git a/tools/ui/src/lib/components/app/navigation/DropdownMenuSearchable.svelte b/tools/ui/src/lib/components/app/navigation/DropdownMenuSearchable.svelte deleted file mode 100644 index 79336cf29d96..000000000000 --- a/tools/ui/src/lib/components/app/navigation/DropdownMenuSearchable.svelte +++ /dev/null @@ -1,79 +0,0 @@ - - -
- -
- -
- -
- {@render children()} - - {#if isEmpty} -
{emptyMessage}
- {/if} -
-
- -{#if footer} -
- - - {@render footer()} -
-{/if} diff --git a/tools/ui/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte b/tools/ui/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte deleted file mode 100644 index c642a3e359c8..000000000000 --- a/tools/ui/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte +++ /dev/null @@ -1,19 +0,0 @@ - - - - diff --git a/tools/ui/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationShowMore.svelte b/tools/ui/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationShowMore.svelte deleted file mode 100644 index 473779cf3ad8..000000000000 --- a/tools/ui/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationShowMore.svelte +++ /dev/null @@ -1,19 +0,0 @@ - - - - diff --git a/tools/ui/src/lib/components/app/server/ServerLoadingSplash.svelte b/tools/ui/src/lib/components/app/server/ServerLoadingSplash.svelte deleted file mode 100644 index f01d69aa2797..000000000000 --- a/tools/ui/src/lib/components/app/server/ServerLoadingSplash.svelte +++ /dev/null @@ -1,32 +0,0 @@ - - -
-
-
-
- -
- -

Connecting to Server

- -

- {message} -

-
- -
- -
-
-
diff --git a/tools/ui/src/lib/components/app/server/ServerStatus.svelte b/tools/ui/src/lib/components/app/server/ServerStatus.svelte deleted file mode 100644 index e06baf26874e..000000000000 --- a/tools/ui/src/lib/components/app/server/ServerStatus.svelte +++ /dev/null @@ -1,69 +0,0 @@ - - -
-
-
- - {getStatusText()} -
- - {#if serverData && !error} - - - - {model || 'Unknown Model'} - - - {#if serverData?.default_generation_settings?.n_ctx} - - ctx: {serverData.default_generation_settings.n_ctx.toLocaleString()} - - {/if} - {/if} - - {#if showActions && error} - - {/if} -
diff --git a/tools/ui/src/lib/components/app/server/index.ts b/tools/ui/src/lib/components/app/server/index.ts deleted file mode 100644 index 39ac5b482d23..000000000000 --- a/tools/ui/src/lib/components/app/server/index.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** - * - * SERVER - * - * Components for displaying server connection state and handling - * connection errors. Integrates with serverStore for state management. - * - */ - -/** - * **ServerStatus** - Server connection status indicator - * - * Compact status display showing connection state, model name, - * and context size. Used in headers and loading screens. - * - * **Architecture:** - * - Reads state from serverStore (props, loading, error) - * - Displays model name from modelsStore - * - * **Features:** - * - Status dot: green (connected), yellow (connecting), red (error), gray (unknown) - * - Status text label - * - Model name badge with icon - * - Context size badge - * - Optional error action button - * - * @example - * ```svelte - * - * ``` - */ -export { default as ServerStatus } from './ServerStatus.svelte'; - -/** - * **ServerErrorSplash** - Full-screen connection error display - * - * Blocking error screen shown when server connection fails. - * Provides retry options and API key input for authentication errors. - * - * **Architecture:** - * - Detects access denied errors for API key flow - * - Validates API key against server before saving - * - Integrates with settingsStore for API key persistence - * - * **Features:** - * - Error message display with icon - * - Retry connection button with loading state - * - API key input for authentication errors - * - API key validation with success/error feedback - * - Troubleshooting section with server start commands - * - Animated transitions for UI elements - * - * @example - * ```svelte - * - * ``` - */ -export { default as ServerErrorSplash } from './ServerErrorSplash.svelte'; - -/** - * **ServerLoadingSplash** - Full-screen loading display - * - * Shown during initial server connection. Displays loading animation - * with ServerStatus component for real-time connection state. - * - * **Features:** - * - Animated server icon - * - Customizable loading message - * - Embedded ServerStatus for live updates - * - * @example - * ```svelte - * - * ``` - */ -export { default as ServerLoadingSplash } from './ServerLoadingSplash.svelte'; diff --git a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatParameterSourceIndicator.svelte b/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatParameterSourceIndicator.svelte deleted file mode 100644 index 2efebfb263d1..000000000000 --- a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatParameterSourceIndicator.svelte +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - Custom - diff --git a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte b/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte deleted file mode 100644 index 987fcaeb9b4e..000000000000 --- a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte +++ /dev/null @@ -1,141 +0,0 @@ - - -{#if groups.length === 0} -
No tools available
-{:else} -
-

- Applies to new conversations. Tool picks inside a chat only affect that chat. -

- - {#each groups as group (group.key)} - {@const isExpanded = expandedGroups.has(group.key)} - toggleExpanded(group.key)} open={isExpanded}> - - {#if isExpanded} - - {:else} - - {/if} - - {@const groupToggleKey = - group.source === ToolSource.MCP && group.serverId - ? toolsStore.getMcpServerToolsKey(group.serverId) - : null} - - - groupToggleKey - ? toolsStore.toggleTool(groupToggleKey) - : toolsStore.toggleCategory(group.source)} - onclick={(e) => e.stopPropagation()} - /> - - {@const faviconUrl = group.serverId ? mcpStore.getServerFavicon(group.serverId) : null} - - - {#if group.source === 'mcp'} - - {:else} - - {/if} - - - - {group.tools.length} tool{group.tools.length !== 1 ? 's' : ''} - - - - -
- -
- Tool - - Enabled - - Always allow -
- - {#each group.tools as entry (entry.key)} - {@const toolName = entry.definition.function.name} - {@const toolUi = - entry.source === ToolSource.SERVER || entry.source === ToolSource.BROWSER - ? getToolUi(toolName) - : null} - {@const displayLabel = toolUi?.label ?? toolName} - {@const IconComponent = toolUi?.icon ?? null} - {@const isEnabled = toolsStore.isToolEnabled(entry.key)} - {@const permissionKey = entry.key} - {@const isAlwaysAllowed = permissionsStore.hasTool(permissionKey)} - -
- - {#if IconComponent} - - {/if} - - - - -
- toolsStore.toggleTool(entry.key)} - /> -
- -
- { - if (isAlwaysAllowed) { - permissionsStore.revokeTool(permissionKey); - } else { - permissionsStore.allowTool(permissionKey); - } - }} - /> -
-
- {/each} -
-
-
- {/each} -
-{/if} diff --git a/tools/ui/src/lib/components/app/settings/index.ts b/tools/ui/src/lib/components/app/settings/index.ts deleted file mode 100644 index 2d2aca5af17a..000000000000 --- a/tools/ui/src/lib/components/app/settings/index.ts +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Full chat settings page layout with sidebar, mobile header, and content area. - * Manages local configuration state, section navigation, and context setup. - * Accepts an optional `initialSection` prop to set the initial active section. - */ -export { default as SettingsChat } from './SettingsChat/SettingsChat.svelte'; - -/** - * Desktop sidebar navigation for chat settings. - * Displays a list of settings sections with icons and titles. - * Switches sections in-app via `onSectionChange`. - */ -export { default as SettingsChatDesktopSidebar } from './SettingsChatDesktopSidebar.svelte'; - -/** - * Mobile header with a horizontally scrollable section picker for chat settings. - * Shows chevron buttons for scroll navigation and highlights the active section. - * Switches sections in-app via `onSectionChange`. - */ -export { default as SettingsChatMobileHeader } from './SettingsChatMobileHeader.svelte'; - -/** - * Badge indicating parameter source for sampling settings. Shows one of: - * - **Custom**: User has explicitly set this value (orange badge) - * - **Server Props**: Using default from `/props` endpoint (blue badge) - * - **Default**: Using app default, server props unavailable (gray badge) - * Updates in real-time as user types to show immediate feedback. - */ -export { default as SettingsChatParameterSourceIndicator } from './SettingsChat/SettingsChatParameterSourceIndicator.svelte'; - -/** - * Section wrapper for settings panels. Displays a title heading with - * child content in a structured layout. - */ -export { default as SettingsGroup } from './SettingsGroup.svelte'; - -/** - * Sticky footer with the save button for settings panel, shown only when - * there are unsaved changes. Save commits form state to config store. - */ -export { default as SettingsFooter } from './SettingsFooter.svelte'; - -/** - * "Reset to default" button with confirmation dialog, shown only when the - * saved config differs from the defaults. - */ -export { default as SettingsResetButton } from './SettingsResetButton.svelte'; - -/** - * Settings Import/Export panel. - * Provides UI for importing and exporting chat conversations. - */ -export { default as SettingsChatImportExportTab } from './SettingsChat/SettingsChatImportExportTab.svelte'; - -/** - * Section wrapper for import/export sections. Displays a title, description, - * icon button, and optional summary of recent actions. - */ -export { default as SettingsChatImportExportSection } from './SettingsChat/SettingsChatImportExportSection.svelte'; - -/** - * MCP Servers configuration panel. - * Provides UI for managing Model Context Protocol (MCP) server connections. - */ -export { default as SettingsMcpServers } from './SettingsMcpServers.svelte'; - -/** - * Form fields renderer for individual settings. Generates appropriate input - * components based on field type (text, number, select, checkbox, textarea). - * Handles validation, help text display, and parameter source indicators. - */ -export { default as SettingsChatFields } from './SettingsChat/SettingsChatFields.svelte'; - -/** - * **SettingsChatToolsTab** - Tools configuration tab for chat settings - * - * Displays available tools grouped by source (server, browser, MCP, custom) with - * toggles to enable/disable individual tools and tool groups. Shows MCP - * server favicons and permission management controls. - */ -export { default as SettingsChatToolsTab } from './SettingsChat/SettingsChatToolsTab.svelte'; diff --git a/tools/ui/src/lib/components/pwa/PwaRefreshAlert.svelte b/tools/ui/src/lib/components/pwa/PwaRefreshAlert.svelte deleted file mode 100644 index 56a71406ff6b..000000000000 --- a/tools/ui/src/lib/components/pwa/PwaRefreshAlert.svelte +++ /dev/null @@ -1,35 +0,0 @@ - - -{#if needRefresh} - - - Update available - - - -

A new version is available. Reload to update.

- - -
-
-{/if} diff --git a/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-action.svelte b/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-action.svelte deleted file mode 100644 index fcf133becf4d..000000000000 --- a/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-action.svelte +++ /dev/null @@ -1,18 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-description.svelte b/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-description.svelte deleted file mode 100644 index 5bd7800c4827..000000000000 --- a/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-description.svelte +++ /dev/null @@ -1,17 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-overlay.svelte b/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-overlay.svelte deleted file mode 100644 index 418c643a2c3c..000000000000 --- a/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-overlay.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-title.svelte b/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-title.svelte deleted file mode 100644 index 204855c0b57b..000000000000 --- a/tools/ui/src/lib/components/ui/alert-dialog/alert-dialog-title.svelte +++ /dev/null @@ -1,17 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/alert/alert-description.svelte b/tools/ui/src/lib/components/ui/alert/alert-description.svelte deleted file mode 100644 index f812e9419c5b..000000000000 --- a/tools/ui/src/lib/components/ui/alert/alert-description.svelte +++ /dev/null @@ -1,23 +0,0 @@ - - -
- {@render children?.()} -
diff --git a/tools/ui/src/lib/components/ui/alert/alert.svelte b/tools/ui/src/lib/components/ui/alert/alert.svelte deleted file mode 100644 index 0078e30b54dd..000000000000 --- a/tools/ui/src/lib/components/ui/alert/alert.svelte +++ /dev/null @@ -1,44 +0,0 @@ - - - - - diff --git a/tools/ui/src/lib/components/ui/badge/badge.svelte b/tools/ui/src/lib/components/ui/badge/badge.svelte deleted file mode 100644 index 3210d25efcef..000000000000 --- a/tools/ui/src/lib/components/ui/badge/badge.svelte +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - {@render children?.()} - diff --git a/tools/ui/src/lib/components/ui/button-group/button-group-root.svelte b/tools/ui/src/lib/components/ui/button-group/button-group-root.svelte deleted file mode 100644 index 89afc3a8ed5c..000000000000 --- a/tools/ui/src/lib/components/ui/button-group/button-group-root.svelte +++ /dev/null @@ -1,21 +0,0 @@ - - -
*:first-child]:rounded-r-none [&>*:last-child]:rounded-l-none [&>*:not(:first-child):not(:last-child)]:rounded-none', - className - )} - {...restProps} -> - {@render children()} -
diff --git a/tools/ui/src/lib/components/ui/button-group/button-group-separator.svelte b/tools/ui/src/lib/components/ui/button-group/button-group-separator.svelte deleted file mode 100644 index d13c573c8e2f..000000000000 --- a/tools/ui/src/lib/components/ui/button-group/button-group-separator.svelte +++ /dev/null @@ -1,8 +0,0 @@ - - -
diff --git a/tools/ui/src/lib/components/ui/button/button.svelte b/tools/ui/src/lib/components/ui/button/button.svelte deleted file mode 100644 index b5642098f126..000000000000 --- a/tools/ui/src/lib/components/ui/button/button.svelte +++ /dev/null @@ -1,92 +0,0 @@ - - - - -{#if href} - - {@render children?.()} - -{:else} - -{/if} - - diff --git a/tools/ui/src/lib/components/ui/card/card-description.svelte b/tools/ui/src/lib/components/ui/card/card-description.svelte deleted file mode 100644 index e75f810d5c82..000000000000 --- a/tools/ui/src/lib/components/ui/card/card-description.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - -

- {@render children?.()} -

diff --git a/tools/ui/src/lib/components/ui/card/card.svelte b/tools/ui/src/lib/components/ui/card/card.svelte deleted file mode 100644 index 3dda1579acb0..000000000000 --- a/tools/ui/src/lib/components/ui/card/card.svelte +++ /dev/null @@ -1,25 +0,0 @@ - - -
- {@render children?.()} -
diff --git a/tools/ui/src/lib/components/ui/checkbox/checkbox.svelte b/tools/ui/src/lib/components/ui/checkbox/checkbox.svelte deleted file mode 100644 index 6f9cfe28e20b..000000000000 --- a/tools/ui/src/lib/components/ui/checkbox/checkbox.svelte +++ /dev/null @@ -1,36 +0,0 @@ - - - - {#snippet children({ checked, indeterminate })} -
- {#if indeterminate} - - {:else if checked} - - {/if} -
- {/snippet} -
diff --git a/tools/ui/src/lib/components/ui/context-menu/context-menu-content.svelte b/tools/ui/src/lib/components/ui/context-menu/context-menu-content.svelte deleted file mode 100644 index 28d82729cc35..000000000000 --- a/tools/ui/src/lib/components/ui/context-menu/context-menu-content.svelte +++ /dev/null @@ -1,25 +0,0 @@ - - - - - diff --git a/tools/ui/src/lib/components/ui/context-menu/context-menu-item.svelte b/tools/ui/src/lib/components/ui/context-menu/context-menu-item.svelte deleted file mode 100644 index cb7695111860..000000000000 --- a/tools/ui/src/lib/components/ui/context-menu/context-menu-item.svelte +++ /dev/null @@ -1,27 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/context-menu/context-menu-label.svelte b/tools/ui/src/lib/components/ui/context-menu/context-menu-label.svelte deleted file mode 100644 index 4366ec627497..000000000000 --- a/tools/ui/src/lib/components/ui/context-menu/context-menu-label.svelte +++ /dev/null @@ -1,24 +0,0 @@ - - -
- {@render children?.()} -
diff --git a/tools/ui/src/lib/components/ui/context-menu/context-menu-shortcut.svelte b/tools/ui/src/lib/components/ui/context-menu/context-menu-shortcut.svelte deleted file mode 100644 index 5974b06acf29..000000000000 --- a/tools/ui/src/lib/components/ui/context-menu/context-menu-shortcut.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - - {@render children?.()} - diff --git a/tools/ui/src/lib/components/ui/context-menu/context-menu-sub-content.svelte b/tools/ui/src/lib/components/ui/context-menu/context-menu-sub-content.svelte deleted file mode 100644 index 693a0a910d14..000000000000 --- a/tools/ui/src/lib/components/ui/context-menu/context-menu-sub-content.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/context-menu/context-menu-sub-trigger.svelte b/tools/ui/src/lib/components/ui/context-menu/context-menu-sub-trigger.svelte deleted file mode 100644 index 1249fb1e233e..000000000000 --- a/tools/ui/src/lib/components/ui/context-menu/context-menu-sub-trigger.svelte +++ /dev/null @@ -1,30 +0,0 @@ - - - - {@render children?.()} - - - diff --git a/tools/ui/src/lib/components/ui/dialog/dialog-description.svelte b/tools/ui/src/lib/components/ui/dialog/dialog-description.svelte deleted file mode 100644 index b7f2fc3a9894..000000000000 --- a/tools/ui/src/lib/components/ui/dialog/dialog-description.svelte +++ /dev/null @@ -1,17 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/dialog/dialog-overlay.svelte b/tools/ui/src/lib/components/ui/dialog/dialog-overlay.svelte deleted file mode 100644 index bb9a514c9df4..000000000000 --- a/tools/ui/src/lib/components/ui/dialog/dialog-overlay.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/dialog/dialog-title.svelte b/tools/ui/src/lib/components/ui/dialog/dialog-title.svelte deleted file mode 100644 index c2ad8b6e8ce6..000000000000 --- a/tools/ui/src/lib/components/ui/dialog/dialog-title.svelte +++ /dev/null @@ -1,17 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/drawer/drawer-content.svelte b/tools/ui/src/lib/components/ui/drawer/drawer-content.svelte deleted file mode 100644 index b4f85dd52a9b..000000000000 --- a/tools/ui/src/lib/components/ui/drawer/drawer-content.svelte +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - {@render children?.()} - - diff --git a/tools/ui/src/lib/components/ui/drawer/drawer-description.svelte b/tools/ui/src/lib/components/ui/drawer/drawer-description.svelte deleted file mode 100644 index ca95150a4880..000000000000 --- a/tools/ui/src/lib/components/ui/drawer/drawer-description.svelte +++ /dev/null @@ -1,17 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/drawer/drawer-title.svelte b/tools/ui/src/lib/components/ui/drawer/drawer-title.svelte deleted file mode 100644 index bfea79132712..000000000000 --- a/tools/ui/src/lib/components/ui/drawer/drawer-title.svelte +++ /dev/null @@ -1,17 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-content.svelte b/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-content.svelte deleted file mode 100644 index 44855b962a4a..000000000000 --- a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-content.svelte +++ /dev/null @@ -1,27 +0,0 @@ - - - - - diff --git a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelte b/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelte deleted file mode 100644 index 574089c283d1..000000000000 --- a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-item.svelte +++ /dev/null @@ -1,27 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-label.svelte b/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-label.svelte deleted file mode 100644 index cd574f27d061..000000000000 --- a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-label.svelte +++ /dev/null @@ -1,24 +0,0 @@ - - -
- {@render children?.()} -
diff --git a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-item.svelte b/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-item.svelte deleted file mode 100644 index a3b430011903..000000000000 --- a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-radio-item.svelte +++ /dev/null @@ -1,32 +0,0 @@ - - - - {#snippet children({ checked })} - - {#if checked} - - {/if} - - - {@render childrenProp?.({ checked })} - {/snippet} - diff --git a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-shortcut.svelte b/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-shortcut.svelte deleted file mode 100644 index 20d75e21d7f5..000000000000 --- a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-shortcut.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - - {@render children?.()} - diff --git a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte b/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte deleted file mode 100644 index 28c99086fdcc..000000000000 --- a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-content.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-trigger.svelte b/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-trigger.svelte deleted file mode 100644 index d7eb475deffa..000000000000 --- a/tools/ui/src/lib/components/ui/dropdown-menu/dropdown-menu-sub-trigger.svelte +++ /dev/null @@ -1,30 +0,0 @@ - - - - {@render children?.()} - - - diff --git a/tools/ui/src/lib/components/ui/dropdown-menu/index.ts b/tools/ui/src/lib/components/ui/dropdown-menu/index.ts deleted file mode 100644 index cf03db7f127d..000000000000 --- a/tools/ui/src/lib/components/ui/dropdown-menu/index.ts +++ /dev/null @@ -1,49 +0,0 @@ -import CheckboxItem from './dropdown-menu-checkbox-item.svelte'; -import Content from './dropdown-menu-content.svelte'; -import Group from './dropdown-menu-group.svelte'; -import GroupHeading from './dropdown-menu-group-heading.svelte'; -import Item from './dropdown-menu-item.svelte'; -import Label from './dropdown-menu-label.svelte'; -import RadioGroup from './dropdown-menu-radio-group.svelte'; -import RadioItem from './dropdown-menu-radio-item.svelte'; -import Separator from './dropdown-menu-separator.svelte'; -import Shortcut from './dropdown-menu-shortcut.svelte'; -import SubContent from './dropdown-menu-sub-content.svelte'; -import SubTrigger from './dropdown-menu-sub-trigger.svelte'; -import Trigger from './dropdown-menu-trigger.svelte'; -import { DropdownMenu as DropdownMenuPrimitive } from 'bits-ui'; -const Sub = DropdownMenuPrimitive.Sub; -const Root = DropdownMenuPrimitive.Root; - -export { - CheckboxItem, - Content, - Root as DropdownMenu, - CheckboxItem as DropdownMenuCheckboxItem, - Content as DropdownMenuContent, - Group as DropdownMenuGroup, - Item as DropdownMenuItem, - Label as DropdownMenuLabel, - RadioGroup as DropdownMenuRadioGroup, - RadioItem as DropdownMenuRadioItem, - Separator as DropdownMenuSeparator, - Shortcut as DropdownMenuShortcut, - Sub as DropdownMenuSub, - SubContent as DropdownMenuSubContent, - SubTrigger as DropdownMenuSubTrigger, - Trigger as DropdownMenuTrigger, - GroupHeading as DropdownMenuGroupHeading, - Group, - GroupHeading, - Item, - Label, - RadioGroup, - RadioItem, - Root, - Separator, - Shortcut, - Sub, - SubContent, - SubTrigger, - Trigger -}; diff --git a/tools/ui/src/lib/components/ui/empty/empty-content.svelte b/tools/ui/src/lib/components/ui/empty/empty-content.svelte deleted file mode 100644 index d902111dab60..000000000000 --- a/tools/ui/src/lib/components/ui/empty/empty-content.svelte +++ /dev/null @@ -1,23 +0,0 @@ - - -
- {@render children?.()} -
diff --git a/tools/ui/src/lib/components/ui/empty/empty-description.svelte b/tools/ui/src/lib/components/ui/empty/empty-description.svelte deleted file mode 100644 index e0119da89f5c..000000000000 --- a/tools/ui/src/lib/components/ui/empty/empty-description.svelte +++ /dev/null @@ -1,23 +0,0 @@ - - -
a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4', - className - )} - data-slot="empty-description" - {...restProps} -> - {@render children?.()} -
diff --git a/tools/ui/src/lib/components/ui/empty/empty-title.svelte b/tools/ui/src/lib/components/ui/empty/empty-title.svelte deleted file mode 100644 index d2c2af947af1..000000000000 --- a/tools/ui/src/lib/components/ui/empty/empty-title.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - -
- {@render children?.()} -
diff --git a/tools/ui/src/lib/components/ui/hover-card/hover-card-content.svelte b/tools/ui/src/lib/components/ui/hover-card/hover-card-content.svelte deleted file mode 100644 index d742bd836ecc..000000000000 --- a/tools/ui/src/lib/components/ui/hover-card/hover-card-content.svelte +++ /dev/null @@ -1,31 +0,0 @@ - - - - - diff --git a/tools/ui/src/lib/components/ui/input/input.svelte b/tools/ui/src/lib/components/ui/input/input.svelte deleted file mode 100644 index c5718e4d0d4d..000000000000 --- a/tools/ui/src/lib/components/ui/input/input.svelte +++ /dev/null @@ -1,52 +0,0 @@ - - -{#if type === 'file'} - -{:else} - -{/if} diff --git a/tools/ui/src/lib/components/ui/label/label.svelte b/tools/ui/src/lib/components/ui/label/label.svelte deleted file mode 100644 index 61456f0642a5..000000000000 --- a/tools/ui/src/lib/components/ui/label/label.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/popover/popover-content.svelte b/tools/ui/src/lib/components/ui/popover/popover-content.svelte deleted file mode 100644 index a3ed55420844..000000000000 --- a/tools/ui/src/lib/components/ui/popover/popover-content.svelte +++ /dev/null @@ -1,37 +0,0 @@ - - - - - diff --git a/tools/ui/src/lib/components/ui/select/select-item.svelte b/tools/ui/src/lib/components/ui/select/select-item.svelte deleted file mode 100644 index cfdfeab4ee0f..000000000000 --- a/tools/ui/src/lib/components/ui/select/select-item.svelte +++ /dev/null @@ -1,39 +0,0 @@ - - - - {#snippet children({ highlighted, selected })} - - {#if selected} - - {/if} - - - {#if childrenProp} - {@render childrenProp({ highlighted, selected })} - {:else} - {label || value} - {/if} - {/snippet} - diff --git a/tools/ui/src/lib/components/ui/select/select-label.svelte b/tools/ui/src/lib/components/ui/select/select-label.svelte deleted file mode 100644 index a23674f9189b..000000000000 --- a/tools/ui/src/lib/components/ui/select/select-label.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - -
- {@render children?.()} -
diff --git a/tools/ui/src/lib/components/ui/select/select-separator.svelte b/tools/ui/src/lib/components/ui/select/select-separator.svelte deleted file mode 100644 index c8a13d57e5cd..000000000000 --- a/tools/ui/src/lib/components/ui/select/select-separator.svelte +++ /dev/null @@ -1,18 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/select/select-trigger.svelte b/tools/ui/src/lib/components/ui/select/select-trigger.svelte deleted file mode 100644 index de3abcdf2125..000000000000 --- a/tools/ui/src/lib/components/ui/select/select-trigger.svelte +++ /dev/null @@ -1,47 +0,0 @@ - - - - {@render children?.()} - - - diff --git a/tools/ui/src/lib/components/ui/switch/switch.svelte b/tools/ui/src/lib/components/ui/switch/switch.svelte deleted file mode 100644 index 0be9e41940fe..000000000000 --- a/tools/ui/src/lib/components/ui/switch/switch.svelte +++ /dev/null @@ -1,29 +0,0 @@ - - - - - diff --git a/tools/ui/src/lib/components/ui/table/table-caption.svelte b/tools/ui/src/lib/components/ui/table/table-caption.svelte deleted file mode 100644 index e1a867d942f6..000000000000 --- a/tools/ui/src/lib/components/ui/table/table-caption.svelte +++ /dev/null @@ -1,20 +0,0 @@ - - - - {@render children?.()} - diff --git a/tools/ui/src/lib/components/ui/textarea/textarea.svelte b/tools/ui/src/lib/components/ui/textarea/textarea.svelte deleted file mode 100644 index 7b0511dee757..000000000000 --- a/tools/ui/src/lib/components/ui/textarea/textarea.svelte +++ /dev/null @@ -1,22 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/toggle-group/toggle-group-item.svelte b/tools/ui/src/lib/components/ui/toggle-group/toggle-group-item.svelte deleted file mode 100644 index e9474f61dc76..000000000000 --- a/tools/ui/src/lib/components/ui/toggle-group/toggle-group-item.svelte +++ /dev/null @@ -1,35 +0,0 @@ - - - diff --git a/tools/ui/src/lib/components/ui/toggle-group/toggle-group.svelte b/tools/ui/src/lib/components/ui/toggle-group/toggle-group.svelte deleted file mode 100644 index b8953761902c..000000000000 --- a/tools/ui/src/lib/components/ui/toggle-group/toggle-group.svelte +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - diff --git a/tools/ui/src/lib/components/ui/toggle/toggle.svelte b/tools/ui/src/lib/components/ui/toggle/toggle.svelte deleted file mode 100644 index 0d74d04d4f72..000000000000 --- a/tools/ui/src/lib/components/ui/toggle/toggle.svelte +++ /dev/null @@ -1,54 +0,0 @@ - - - - - diff --git a/tools/ui/src/lib/components/ui/tooltip/index.ts b/tools/ui/src/lib/components/ui/tooltip/index.ts deleted file mode 100644 index 48177b6affc3..000000000000 --- a/tools/ui/src/lib/components/ui/tooltip/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -import Content from './tooltip-content.svelte'; -import Trigger from './tooltip-trigger.svelte'; -import { Tooltip as TooltipPrimitive } from 'bits-ui'; - -const Root = TooltipPrimitive.Root; -const Provider = TooltipPrimitive.Provider; -const Portal = TooltipPrimitive.Portal; - -export { - Root, - Trigger, - Content, - Provider, - Portal, - // - Root as Tooltip, - Content as TooltipContent, - Trigger as TooltipTrigger, - Provider as TooltipProvider, - Portal as TooltipPortal -}; diff --git a/tools/ui/src/lib/components/ui/tooltip/tooltip-content.svelte b/tools/ui/src/lib/components/ui/tooltip/tooltip-content.svelte deleted file mode 100644 index 423fd1af3328..000000000000 --- a/tools/ui/src/lib/components/ui/tooltip/tooltip-content.svelte +++ /dev/null @@ -1,62 +0,0 @@ - - -{#snippet tooltipContent()} - - {@render children?.()} - - - {#snippet child({ props })} -
- {/snippet} -
-
-{/snippet} - -{#if noPortal} - {@render tooltipContent()} -{:else} - - {@render tooltipContent()} - -{/if} diff --git a/tools/ui/src/lib/components/ui/utils.ts b/tools/ui/src/lib/components/ui/utils.ts deleted file mode 100644 index 97525cc4290f..000000000000 --- a/tools/ui/src/lib/components/ui/utils.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { type ClassValue, clsx } from 'clsx'; -import { twMerge } from 'tailwind-merge'; - -export function cn(...inputs: ClassValue[]) { - return twMerge(clsx(inputs)); -} - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export type WithoutChild = T extends { child?: any } ? Omit : T; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export type WithoutChildren = T extends { children?: any } ? Omit : T; -export type WithoutChildrenOrChild = WithoutChildren>; -export type WithElementRef = T & { ref?: U | null }; diff --git a/tools/ui/src/lib/constants/browser-info.ts b/tools/ui/src/lib/constants/browser-info.ts deleted file mode 100644 index e99c324aa3ab..000000000000 --- a/tools/ui/src/lib/constants/browser-info.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { CLI_FLAGS } from './cli-flags.constants'; -import { BuiltInTool, JsonSchemaType, ToolCallType } from '$lib/enums'; -import type { OpenAIToolDefinition } from '$lib/types'; - -// get_info is served by the server, but the browser falls back to this -// implementation when the server does not provide it - same wire name. -export const BROWSER_INFO_TOOL_NAME = BuiltInTool.SERVER_GET_INFO; - -/** UA token to OS name, first match wins - Android and iOS UAs also carry the Linux / Mac OS X tokens */ -export const BROWSER_INFO_OS_UA_PATTERNS: readonly [RegExp, string][] = [ - [/Windows NT/, 'Windows'], - [/Android/, 'Android'], - [/iPhone|iPad|iPod/, 'iOS'], - [/CrOS/, 'ChromeOS'], - [/Mac OS X/, 'macOS'], - [/Linux/, 'Linux'] -]; - -export const BROWSER_INFO_OS_UNKNOWN = 'unknown'; - -/** Sent to the model as the `note` field of the tool result, next to the OS name */ -export const BROWSER_INFO_NOTE = `This environment is browser-only, it cannot read or modify local files, and it cannot run shell commands. To get local file access, tell user to launch llama-server with the ${CLI_FLAGS.AGENT} argument.`; - -export function buildBrowserInfoToolDefinition(): OpenAIToolDefinition { - return { - function: { - description: - 'Get runtime info (OS name), may call when user asks about local files or shell commands', - name: BROWSER_INFO_TOOL_NAME, - parameters: { - properties: {}, - required: [], - type: JsonSchemaType.OBJECT - } - }, - type: ToolCallType.FUNCTION - }; -} diff --git a/tools/ui/src/lib/constants/code-block.constants.ts b/tools/ui/src/lib/constants/code-block.constants.ts deleted file mode 100644 index 05db575f9ea5..000000000000 --- a/tools/ui/src/lib/constants/code-block.constants.ts +++ /dev/null @@ -1,50 +0,0 @@ -// Constants for the markdown code-block renderer: language/fence handling and CSS classes. - -/** Parsing and escaping helpers for the markdown code-block renderer. */ -export const CODE_BLOCK = { - AMPERSAND_REGEX: /&/g, - /** Language fallback used when no language is specified. */ - DEFAULT_LANGUAGE: 'text', - /** Matches opening/closing markdown code fences. */ - FENCE_PATTERN: /^```|\n```/g, - GT_REGEX: />/g, - /** Matches the language specifier at the start of a code fence. */ - LANG_PATTERN: /^(\w*)\n?/, - LT_REGEX: /, - keyof ModelModalities -> = { - [ModelModality.AUDIO]: 'audio', - [ModelModality.VIDEO]: 'video', - [ModelModality.VISION]: 'vision' -}; - -/** Modalities in the order the filters and the model cards list them. */ -export const MODALITY_ORDER: Exclude[] = [ - ModelModality.VISION, - ModelModality.VIDEO, - ModelModality.AUDIO -]; - -/** Boolean flag a modality drives on the ModelModalities type. */ -export type ModalityKey = (typeof MODALITY_FLAG_KEYS)[keyof typeof MODALITY_FLAG_KEYS]; - -/** Modality flags a model can carry, in display order. */ -export const MODALITY_KEYS: ModalityKey[] = MODALITY_ORDER.map( - (modality) => MODALITY_FLAG_KEYS[modality] -); - -export const CAPABILITY_ICONS: Record = { - [ModelCapability.REASONING]: ReasoningIcon, - [ModelCapability.TOOL_USE]: ToolUseIcon -} as const; - -export const CAPABILITY_LABELS: Record = { - [ModelCapability.REASONING]: 'Reasoning', - [ModelCapability.TOOL_USE]: 'Tool use' -} as const; - -/** Maps a ModelCapability to the boolean flag it drives on the ModelCapabilities type */ -export const CAPABILITY_FLAG_KEYS: Record = { - [ModelCapability.REASONING]: 'reasoning', - [ModelCapability.TOOL_USE]: 'tools' -}; - -/** Icons of the slash-command picker, one per chat-form command. */ -export const CHAT_FORM_COMMAND_ICONS: Record = { - [ChatFormCommandAction.COMPACT]: CompactCommandIcon, - [ChatFormCommandAction.CWD]: CwdCommandIcon, - [ChatFormCommandAction.MODEL]: MODEL_ICON, - [ChatFormCommandAction.PROMPT]: PromptCommandIcon -}; - -/** Icons of the download control a manager row shows while it downloads. */ -export const MODEL_DOWNLOAD_ICONS = { - pause: PauseDownloadIcon, - resume: ResumeDownloadIcon -} as const; - -/** Icons the model load control shows for its states and actions. */ -export const MODEL_LOAD_ICONS = { - failed: LoadFailedIcon, - load: LoadIcon, - loading: LoadingIcon, - retry: RetryIcon, - unload: UnloadIcon -} as const; - -// Shared SVG icon strings for copy and preview buttons -export const COPY_ICON_SVG = ``; - -export const PREVIEW_ICON_SVG = ``; - -export const CODE_ICON_SVG = ``; diff --git a/tools/ui/src/lib/constants/index.ts b/tools/ui/src/lib/constants/index.ts deleted file mode 100644 index 59504c094475..000000000000 --- a/tools/ui/src/lib/constants/index.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Central constants export file -// All constants should be imported from '$lib/constants' - -export * from './agentic.constants'; -export * from './api-endpoints.constants'; -export * from './app.constants'; -export * from './backend.constants'; -export * from './chat-tabs.constants'; -export * from './database.constants'; -export * from './reasoning-effort.constants'; -export * from './recommended-mcp-servers.constants'; -export * from './storage.constants'; -export * from './icons.constants'; -export * from './attachment-menu.constants'; -export * from './auto-scroll.constants'; -export * from './context-gauge-dial.constants'; -export * from './context-gauge-popup.constants'; -export * from './conversation-import.constants'; -export * from './binary-detection.constants'; -export * from './content-detection.constants'; -export * from './tool-call-args.constants'; -export * from './tool-ui.constants'; -export * from './cache.constants'; -export * from './chat-form.constants'; -export * from './cli-flags.constants'; -export * from './compaction.constants'; -export * from './code-block.constants'; -export * from './context-keys.constants'; -export * from './control-actions.constants'; -export * from './css-classes.constants'; -export * from './formatters.constants'; -export * from './groups.constants'; -export * from './headers.constants'; -export * from './key-value-pairs.constants'; -export * from './keyboard-shortcuts.constants'; -export * from './latex-protection.constants'; -export * from './literal-html.constants'; -export * from './markdown.constants'; -export * from './mermaid-blocks.constants'; -export * from './svg-blocks.constants'; -export * from './diagram-blocks.constants'; -export * from './max-bundle-size.constants'; -export * from './error.constants'; -export * from './image.constants'; -export * from './mcp.constants'; -export * from './mcp-form.constants'; -export * from './mcp-resource.constants'; -export * from './mention-badge.constants'; -export * from './message-export.constants'; -export * from './microphone.constants'; -export * from './path-display.constants'; -export * from './model-id.constants'; -export * from './model-loading.constants'; -export * from './models-manager.constants'; -export * from './models-discover.constants'; -export * from './models-discover-download.constants'; -export * from './model-compatibility.constants'; -export * from './huggingface.constants'; -export * from './precision.constants'; -export * from './pwa.constants'; -export * from './routes.constants'; -export * from './sandbox.constants'; -export * from './settings-keys.constants'; -export * from './settings.constants'; -export * from './special-characters.constants'; -export * from './stream.constants'; -export * from './supported-file-types.constants'; -export * from './table-html-restorer.constants'; -export * from './title-generation.constants'; -export * from './ui.constants'; -export * from './uri-template.constants'; -export * from './url.constants'; -export * from './working-directory.constants'; -export * from './read-media'; -export * from './get-datetime'; -export * from './browser-info'; -export * from './search-chats'; diff --git a/tools/ui/src/lib/constants/mermaid-blocks.constants.ts b/tools/ui/src/lib/constants/mermaid-blocks.constants.ts deleted file mode 100644 index cd9467fb6e63..000000000000 --- a/tools/ui/src/lib/constants/mermaid-blocks.constants.ts +++ /dev/null @@ -1,9 +0,0 @@ -export const MERMAID_WRAPPER_CLASS = 'mermaid-block-wrapper'; -export const MERMAID_SCROLL_CONTAINER_CLASS = 'mermaid-scroll-container'; -export const MERMAID_BLOCK_CLASS = 'mermaid'; - -export const MERMAID_LANGUAGE = 'mermaid'; - -export const MERMAID_SYNTAX_ATTR = 'data-mermaid-syntax'; -export const MERMAID_ID_ATTR = 'data-mermaid-id'; -export const MERMAID_RENDERED_ATTR = 'data-mermaid-rendered'; diff --git a/tools/ui/src/lib/constants/microphone.constants.ts b/tools/ui/src/lib/constants/microphone.constants.ts deleted file mode 100644 index 170299f9b875..000000000000 --- a/tools/ui/src/lib/constants/microphone.constants.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** Why the chat form's microphone can't record, as its button and toast tell the user. */ -export const MICROPHONE_UNAVAILABLE_MESSAGE = { - busy: 'The microphone is in use by another app.', - denied: "Microphone access was denied. Allow it in the browser's site settings to record.", - failed: "The microphone couldn't start.", - insecure: - 'The microphone only works over HTTPS or on localhost. Open this page over HTTPS to record.', - notFound: 'No microphone was found.', - unsupported: "This browser can't record audio." -} as const; diff --git a/tools/ui/src/lib/constants/model-compatibility.constants.ts b/tools/ui/src/lib/constants/model-compatibility.constants.ts deleted file mode 100644 index 5d65f8d62e0d..000000000000 --- a/tools/ui/src/lib/constants/model-compatibility.constants.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Model memory-fit constants. - * - * Mirrors the app's compatibility check (Model+Compatibility.swift): - * budget = RAM x RAM_BUDGET_RATIO - RAM_OVERHEAD_MB - * weightBytes = fileBytes x QUANT_WEIGHT - * a file fits when weightBytes <= budget. Kept here so the estimation util and - * any caller share one source. - */ - -/** Bytes in one mebibyte (MiB), used to convert a file size to MB. */ -export const MIB_BYTES = 1_048_576; - -/** MiB in one tier unit; the tiers below are binary sizes, i.e. GiB. */ -export const MB_PER_GB = 1024; - -/** Overhead multiplier applied to the file size when estimating weight memory. */ -export const QUANT_WEIGHT = 1.05; - -/** Share of RAM the app allows the model to occupy. */ -export const RAM_BUDGET_RATIO = 0.75; - -/** Fixed RAM overhead (MB) reserved for the system and KV cache. */ -export const RAM_OVERHEAD_MB = 2048; - -/** - * Memory tiers (GB) covering the RAM sizes common machines ship with, in - * small enough steps that the requirement reads honestly. Device-agnostic on - * purpose: the server exposes no host RAM, so the UI presents the tier and - * lets the user judge. - */ -export const MEM_TIERS = [4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024]; diff --git a/tools/ui/src/lib/constants/models-discover-download.constants.ts b/tools/ui/src/lib/constants/models-discover-download.constants.ts deleted file mode 100644 index 721d46db3a52..000000000000 --- a/tools/ui/src/lib/constants/models-discover-download.constants.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Models Discover - download options constants: the serve `--spec-type` mapping, - * the bit-depth buckets, and the standalone command builder. - */ - -import { ModelDraftSidecar } from '$lib/enums'; - -/** - * `--spec-type` value for each draft sidecar. - */ -export const SPEC_TYPE: Record = { - [ModelDraftSidecar.DFLASH]: 'draft-dflash', - [ModelDraftSidecar.DSPARK]: 'draft-dspark', - [ModelDraftSidecar.EAGLE3]: 'draft-eagle3', - [ModelDraftSidecar.MTP]: 'draft-mtp' -}; - -/** Bit-depth bucket for files that carry no quant token; rendered as "Other". */ -export const OTHER_BIT_DEPTH = 99; - -export const OTHER_BIT_DEPTH_LABEL = 'Other'; - -/** Suffix appended after a bit-depth number to label a row, e.g. `4-bit`. */ -export const BIT_DEPTH_LABEL_SUFFIX = '-bit'; - -/** - * Fixed tokens of the standalone `llama serve` command preview, so the command - * builder and its rendered spans share one source of the CLI spelling. - */ -export const SERVE_COMMAND = { - BIN: 'llama', - MODEL_FLAG: '-hf', - SPEC_TYPE_FLAG: '--spec-type', - SUBCOMMAND: 'serve' -} as const; - -/** Bit depth preferred for the command's default base quant. */ -export const DEFAULT_BASE_BIT_DEPTH = 4; - -/** Label shown for a draft-sidecar chip whose quant is unknown. */ -export const DRAFT_FILE_LABEL = 'draft'; diff --git a/tools/ui/src/lib/constants/pwa.constants.ts b/tools/ui/src/lib/constants/pwa.constants.ts deleted file mode 100644 index e8f3468176ec..000000000000 --- a/tools/ui/src/lib/constants/pwa.constants.ts +++ /dev/null @@ -1,354 +0,0 @@ -/** - * Centralized PWA constants to avoid magic strings, regexes, and duplicated - * definitions across the codebase. - */ - -import { APP_NAME } from './app.constants'; - -export const MEDIA_QUERIES = { - COARSE_POINTER: '(pointer: coarse)', - DISPLAY_MODE_STANDALONE: '(display-mode: standalone)', - PREFERS_DARK: '(prefers-color-scheme: dark)', - PREFERS_LIGHT: '(prefers-color-scheme: light)' -} as const; - -export const THEME_COLORS = { - ACCENT_BLUE: '#2563eb', - ACCENT_BLUE_HOVER: '#1d4ed8', - BACKGROUND_DARK: '#111111', - BACKGROUND_LIGHT: 'white', - DARK: '#0d0d0d', - LIGHT: '#ffffff', - TITLE_UPDATE_ALERT: { - BG_DARK: 'zinc-800', - BG_LIGHT: 'white', - BORDER_DARK: 'zinc-700', - BORDER_LIGHT: 'zinc-200', - TEXT_DARK: 'zinc-400', - TEXT_LIGHT: 'zinc-500' - } -} as const; - -export const FAVICON_PATHS = { - ICO_DARK: 'favicon-dark.ico', - ICO_LIGHT: 'favicon.ico', - SVG_DARK: 'favicon-dark.svg', - SVG_LIGHT: 'favicon.svg' -} as const; - -export const FAVICON_SELECTORS = { - ICO_48X48: 'link[rel="icon"][sizes="48x48"]', - SVG_ANY: 'link[rel="icon"][type="image/svg+xml"]' -} as const; - -export const APPLE_ASSETS = { - TOUCH_ICON: 'apple-touch-icon-180x180.png' -} as const; - -export const PWA_MANIFEST = { - background_color: THEME_COLORS.BACKGROUND_LIGHT, - description: 'Local AI chat interface powered by llama.cpp', - display: 'standalone' as const, - icons: [ - { sizes: '64x64', src: 'pwa-64x64.png', type: 'image/png' }, - { sizes: '192x192', src: 'pwa-192x192.png', type: 'image/png' }, - { purpose: 'any' as const, sizes: '512x512', src: 'pwa-512x512.png', type: 'image/png' }, - { - purpose: 'maskable' as const, - sizes: '512x512', - src: 'maskable-icon-512x512.png', - type: 'image/png' - } - ], - name: APP_NAME, - short_name: APP_NAME, - start_url: './', - theme_color: THEME_COLORS.BACKGROUND_LIGHT -}; - -export const PWA_ICON_PATHS = { - MASKABLE_512: '/maskable-icon-512x512.png', - PWA_64: '/pwa-64x64.png', - PWA_192: '/pwa-192x192.png', - PWA_512: '/pwa-512x512.png' -} as const; - -/** Apple device dimensions (logical points) and DPR, from Apple HIG. */ -export const APPLE_DEVICES = { - '640x1136': { dpr: 2, height: 568, width: 320 }, // iPhone 6/7/8 Plus - '744x1133': { dpr: 2, height: 573, width: 376 }, // iPad mini 8.3" - '750x1334': { dpr: 2, height: 667, width: 375 }, // iPhone 6/7/8, 14 - '1032x1376': { dpr: 2, height: 1376, width: 1032 }, // iPad Air 13" - // iPhones (DPR 3) - '1170x2532': { dpr: 3, height: 844, width: 390 }, // iPhone 13, 15 - '1179x2556': { dpr: 3, height: 852, width: 393 }, // iPhone 14, 15 Pro, 16 - '1206x2622': { dpr: 3, height: 874, width: 402 }, // iPhone 16 Plus, 16e - '1284x2778': { dpr: 3, height: 926, width: 428 }, // iPhone 15 Plus - '1290x2796': { dpr: 3, height: 932, width: 430 }, // iPhone 15 Pro Max, 16 Pro - '1320x2868': { dpr: 3, height: 956, width: 440 }, // iPhone 16 Pro Max - '1640x2360': { dpr: 2, height: 1180, width: 820 }, // iPad Air 10.9" - // iPads (DPR 2) - '1668x2388': { dpr: 2, height: 1194, width: 834 }, // iPad Air 11", iPad 11" - '2048x2732': { dpr: 2, height: 1366, width: 1024 } // iPad Pro 12.9" -} as const; - -export type AppleDeviceKey = keyof typeof APPLE_DEVICES; - -export const PWA_FILE_PATHS = { - MANIFEST: '/manifest.webmanifest', - SERVICE_WORKER: '/sw.js', - VERSION: '/version.json', - WORKBOX: '/workbox-.js' -} as const; - -// Used by the server middleware to skip API key validation. -// Keep in sync with tools/server/server-http.cpp public_endpoints list. - -export const PUBLIC_ENDPOINTS = [ - '/health', - '/v1/health', - '/models', - '/v1/models', - '/props', - '/metrics', - '/', - '/index.html', - - '/favicon.ico', - '/favicon-dark.ico', - '/favicon.svg', - '/favicon-dark.svg', - '/pwa-64x64.png', - '/pwa-192x192.png', - '/pwa-512x512.png', - '/maskable-icon-512x512.png', - '/apple-touch-icon-180x180.png', - '/apple-splash-portrait-640x1136.png', - '/apple-splash-landscape-640x1136.png', - '/apple-splash-portrait-750x1334.png', - '/apple-splash-landscape-750x1334.png', - '/apple-splash-portrait-1170x2532.png', - '/apple-splash-landscape-1170x2532.png', - '/apple-splash-portrait-1179x2556.png', - '/apple-splash-landscape-1179x2556.png', - '/apple-splash-portrait-1206x2622.png', - '/apple-splash-landscape-1206x2622.png', - '/apple-splash-portrait-1284x2778.png', - '/apple-splash-landscape-1284x2778.png', - '/apple-splash-portrait-1290x2796.png', - '/apple-splash-landscape-1290x2796.png', - '/apple-splash-portrait-1320x2868.png', - '/apple-splash-landscape-1320x2868.png', - '/apple-splash-portrait-1488x2266.png', - '/apple-splash-landscape-1488x2266.png', - '/apple-splash-portrait-1640x2360.png', - '/apple-splash-landscape-1640x2360.png', - '/apple-splash-portrait-1668x2388.png', - '/apple-splash-landscape-1668x2388.png', - '/apple-splash-portrait-2048x2732.png', - '/apple-splash-landscape-2048x2732.png', - '/apple-splash-portrait-dark-640x1136.png', - '/apple-splash-landscape-dark-640x1136.png', - '/apple-splash-portrait-dark-750x1334.png', - '/apple-splash-landscape-dark-750x1334.png', - '/apple-splash-portrait-dark-1170x2532.png', - '/apple-splash-landscape-dark-1170x2532.png', - '/apple-splash-portrait-dark-1179x2556.png', - '/apple-splash-landscape-dark-1179x2556.png', - '/apple-splash-portrait-dark-1206x2622.png', - '/apple-splash-landscape-dark-1206x2622.png', - '/apple-splash-portrait-dark-1284x2778.png', - '/apple-splash-landscape-dark-1284x2778.png', - '/apple-splash-portrait-dark-1290x2796.png', - '/apple-splash-landscape-dark-1290x2796.png', - '/apple-splash-portrait-dark-1320x2868.png', - '/apple-splash-landscape-dark-1320x2868.png', - '/apple-splash-portrait-dark-1488x2266.png', - '/apple-splash-landscape-dark-1488x2266.png', - '/apple-splash-portrait-dark-1640x2360.png', - '/apple-splash-landscape-dark-1640x2360.png', - '/apple-splash-portrait-dark-1668x2388.png', - '/apple-splash-landscape-dark-1668x2388.png', - '/apple-splash-portrait-dark-2048x2732.png', - '/apple-splash-landscape-dark-2048x2732.png', - '/manifest.webmanifest', - '/sw.js', - '/version.json', - '/workbox-.js' -] as const; -export const BUILD_CONFIG = { - GUIDE_COMMENT: ` - -`.trim(), - OUTPUT_DIR: './dist' -} as const; - -export const REGEX_PATTERNS = { - HEAD_CLOSE: /\t*<\/head>/, - SPLASH_FILE: /^apple-splash-(portrait|landscape)-(dark-)?(\d+)x(\d+)\.png$/ -} as const; - -// Device names used by @vite-pwa/assets-generator for splash screen generation. -// Keep in sync with pwa-assets.config.ts. -export const PWA_GENERATOR_DEVICES = [ - 'iPhone 13', - 'iPhone 13 Pro', - 'iPhone 13 Pro Max', - 'iPhone 14', - 'iPhone 14 Plus', - 'iPhone 14 Pro', - 'iPhone 14 Pro Max', - 'iPhone 15', - 'iPhone 15 Plus', - 'iPhone 15 Pro', - 'iPhone 15 Pro Max', - 'iPhone 16', - 'iPhone 16 Plus', - 'iPhone 16 Pro', - 'iPhone 16 Pro Max', - 'iPhone 16e', - 'iPhone SE 4"', - 'iPhone SE 4.7"', - 'iPad 11"', - 'iPad Air 10.9"', - 'iPad Air 11"', - 'iPad Air 13"', - 'iPad Pro 11"', - 'iPad Pro 12.9"', - 'iPad mini 8.3"' -] as const; - -// PWA assets generator configuration — used by pwa-assets.config.ts -// FAVICON_PADDING: fraction (0..1) of the icon reserved as equal margin on -// each side of the icon PNG/ICO outputs. 0, because llama-brand's favicons -// already carry their margin and optical centring. -export const PWA_ASSET_GENERATOR = { - ADD_MEDIA_SCREEN: true, - BASE_PATH: './', - DARK_PREFIX: 'dark-', - FAVICON_PADDING: 0, - FIT_MODE: 'contain', - LINK_PRESET: '2023', - PNG_COMPRESSION_LEVEL: 9, - PNG_QUALITY: 60, - SPLASH_PADDING: 0.75, - XHTML: false -} as const; - -export const CACHE_SETTINGS = { - API_CACHE_MAX_AGE_SECONDS: 60 * 60 * 24, - API_CACHE_MAX_ENTRIES: 50, - IMMUTABLE_MAX_AGE_SECONDS: 31536000, - MAX_FILE_SIZE_BYTES: 10 * 1024 * 1024 -} as const; - -export const GLOB_PATTERNS: string[] = [ - '**/*.{js,css,html,ico,svg,png,webp,woff,woff2,json,webmanifest}' -]; - -export const SW_CONFIG = { - CHECK_INTERVAL_MS: 60000, - UPDATE_FETCH_OPTIONS: { - CACHE: 'no-store', - HEADERS: { - CACHE: 'no-store', - CACHE_CONTROL: 'no-cache' - } - } -} as const; - -// Runtime caching configuration for Workbox -export const RUNTIME_CACHING = { - CACHE_NAME: 'api-cache', - HANDLER: 'NetworkFirst' -} as const; - -// Workbox runtime caching patterns -export const API_CACHING_PATTERNS = { - STATIC_API: /^\/(health|props|models|tools|slots|cors-proxy).*/, - V1_API: /^\/v1\/.*/ -} as const; - -// SvelteKit PWA plugin options -export const PWA_KIT_OPTIONS = {} as const; - -export const APPLE_META_TAGS = { - MOBILE_WEB_APP_CAPABLE: { content: 'yes', name: 'apple-mobile-web-app-capable' }, - MOBILE_WEB_APP_TITLE: { name: 'apple-mobile-web-app-title' }, - STATUS_BAR_STYLE: { content: 'black-translucent', name: 'apple-mobile-web-app-status-bar-style' } -} as const; - -// Splash screen HTML link tag prefix used by generateSplashScreenLinks -export const SPLASH_LINK = { - DARK_MEDIA_SUFFIX: ' and (prefers-color-scheme: dark)', - HTML: ' capture group 1 is `12345`. */ -export const READ_MEDIA_SIZE_REGEX = new RegExp(`^${PREFIX_SIZE}\\s*(\\d+)\\s*bytes`); - -/** Image extensions the tool accepts. The server decodes images with stb_image, which has no webp or tiff. */ -export const READ_MEDIA_IMAGE_MIME: Record = { - gif: MimeTypeImage.GIF, - jpeg: MimeTypeImage.JPEG, - jpg: MimeTypeImage.JPEG, - png: MimeTypeImage.PNG -} as const; - -/** Audio extensions the tool accepts. The `input_audio` API only takes wav and mp3. */ -export const READ_MEDIA_AUDIO_MIME: Record = { - mp3: MimeTypeAudio.MP3_MPEG, - wav: MimeTypeAudio.WAV -} as const; - -/** - * Build the read_media tool definition for the modalities the active model has. - * At least one of the two flags must be true, otherwise the tool is not offered - * at all - a model that cannot see or hear has nothing to do with the bytes. - */ -export function buildReadMediaToolDefinition( - supportsVision: boolean, - supportsAudio: boolean -): OpenAIToolDefinition { - const kinds: string[] = []; - - if (supportsVision) kinds.push(`images (${Object.keys(READ_MEDIA_IMAGE_MIME).join(', ')})`); - - if (supportsAudio) kinds.push(`audio (${Object.keys(READ_MEDIA_AUDIO_MIME).join(', ')})`); - - return { - function: { - description: `Read a media file and attach it to the conversation so it can be perceived directly. Supports ${kinds.join(' and ')}.`, - name: READ_MEDIA_TOOL_NAME, - parameters: { - properties: { - path: { - description: 'Path to the media file', - type: JsonSchemaType.STRING - } - }, - required: ['path'], - type: JsonSchemaType.OBJECT - } - }, - type: ToolCallType.FUNCTION - }; -} diff --git a/tools/ui/src/lib/constants/search-chats.ts b/tools/ui/src/lib/constants/search-chats.ts deleted file mode 100644 index 6ba1160e67c7..000000000000 --- a/tools/ui/src/lib/constants/search-chats.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { - BuiltInTool, - JsonSchemaType, - SearchChatsMessageSelection, - SearchChatsOrder, - ToolCallType, - ToolSource -} from '$lib/enums'; -import type { OpenAIToolDefinition } from '$lib/types'; - -export const SEARCH_CHATS_TOOL_NAME = BuiltInTool.BROWSER_SEARCH_CHATS; - -/** Key of the tool in the disabled tools lists, same format as toolsStore.toolKey */ -export const SEARCH_CHATS_TOOL_KEY = `${ToolSource.BROWSER}:${SEARCH_CHATS_TOOL_NAME}`; - -export const SEARCH_CHATS_OUTPUT_MAX_CHARS = 8192; - -export const SEARCH_CHATS_LIMIT_CHATS_DEFAULT = 10; -export const SEARCH_CHATS_LIMIT_CHATS_MAX = 1000; - -export const SEARCH_CHATS_LIMIT_MESSAGES_DEFAULT = 5; -export const SEARCH_CHATS_LIMIT_MESSAGES_MAX = 100; - -export const SEARCH_CHATS_MESSAGE_CHARS_DEFAULT = 600; -export const SEARCH_CHATS_MESSAGE_CHARS_MIN = 50; -export const SEARCH_CHATS_MESSAGE_CHARS_MAX = 4000; - -export const SEARCH_CHATS_MAX_PATTERNS = 10; -export const SEARCH_CHATS_MAX_IDS = 100; - -/** Matching cost grows with pattern length times text length, and runs on the main thread */ -export const SEARCH_CHATS_PATTERN_MAX_CHARS = 200; -export const SEARCH_CHATS_ID_MAX_CHARS = 200; - -/** A match past this share of the excerpt length moves the excerpt window to the match */ -export const SEARCH_CHATS_EXCERPT_RECENTER_RATIO = 0.6; - -/** Share of the excerpt shown before the match when the window is moved */ -export const SEARCH_CHATS_EXCERPT_LEAD_RATIO = 1 / 3; - -export const SEARCH_CHATS_ELLIPSIS = '...'; - -export const SEARCH_CHATS_FIELD_SEPARATOR = ' | '; - -export const SEARCH_CHATS_CUT_NOTICE = - '[messages cut to fit: lower limit_messages or max_message_chars]'; - -/** `2026-11-10`, read as local midnight */ -export const SEARCH_CHATS_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/; - -/** `2026-11-10T14:30`, optional seconds, fraction and offset; local time without an offset */ -export const SEARCH_CHATS_DATE_TIME_REGEX = - /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})?$/; - -const DESCRIPTION = `Find and read the user's other saved chats (read-only). The current chat is hidden, you already see it. -Returns chats, each with messages from what the user saw: user and assistant text only (tool output is skipped), numbered #1..#N in chat order. Dates are in the user's local time. -- List chats: limit_messages=0 gives one line per chat (title, conv_id, date); raise limit_chats and page with offset_chats. -- Find chats: by_matches=["%paris%", "%eiffel%"] matches the title or any message (case-insensitive, % = any text, _ = one char, no % means "contains"). A chat matches if any pattern does. For AND within a message use "%a%b%" (order matters, add "%b%a%" for either order). -- Read chats: by_conv_ids=[""] with message_selection "latest" (default) or "earliest". -- Time range: from_timestamp (inclusive) and to_timestamp (exclusive), ISO 8601 like 2026-11-10 or 2026-11-10T14:30, local time. Only messages in the range are searched and shown, and only chats with messages in it are returned. With from_timestamp, message_selection defaults to "earliest". -Example, "what was my last question in the chat about paris?": by_matches=["%paris%"], message_selection="latest", limit_messages=4, then answer from the last user message. -Example, "what did we talk about yesterday?": from_timestamp=, to_timestamp=, limit_messages=2.`; - -export function buildSearchChatsToolDefinition(): OpenAIToolDefinition { - return { - function: { - description: DESCRIPTION, - name: SEARCH_CHATS_TOOL_NAME, - parameters: { - properties: { - by_conv_ids: { - description: 'Only these chats, by conv_id', - items: { type: JsonSchemaType.STRING }, - type: JsonSchemaType.ARRAY - }, - by_matches: { - description: `LIKE patterns matched against titles and message text, any of them, max ${SEARCH_CHATS_PATTERN_MAX_CHARS} chars each`, - items: { type: JsonSchemaType.STRING }, - type: JsonSchemaType.ARRAY - }, - from_timestamp: { - description: - 'Only messages at or after this time, ISO 8601, local time unless an offset is given', - type: JsonSchemaType.STRING - }, - include_current: { - description: 'Also include the current chat, default false', - type: JsonSchemaType.BOOLEAN - }, - limit_chats: { - description: `Max chats, default ${SEARCH_CHATS_LIMIT_CHATS_DEFAULT}, max ${SEARCH_CHATS_LIMIT_CHATS_MAX}`, - type: JsonSchemaType.NUMBER - }, - limit_messages: { - description: `Messages per chat, default ${SEARCH_CHATS_LIMIT_MESSAGES_DEFAULT}, max ${SEARCH_CHATS_LIMIT_MESSAGES_MAX}; 0 lists chats only`, - type: JsonSchemaType.NUMBER - }, - max_message_chars: { - description: `Characters shown per message, default ${SEARCH_CHATS_MESSAGE_CHARS_DEFAULT}, max ${SEARCH_CHATS_MESSAGE_CHARS_MAX}`, - type: JsonSchemaType.NUMBER - }, - message_selection: { - description: `Which messages per chat; default "${SearchChatsMessageSelection.MATCHING}" with by_matches, else "${SearchChatsMessageSelection.EARLIEST}" with from_timestamp, else "${SearchChatsMessageSelection.LATEST}"`, - enum: Object.values(SearchChatsMessageSelection), - type: JsonSchemaType.STRING - }, - offset_chats: { - description: 'Skip this many chats, for paging', - type: JsonSchemaType.NUMBER - }, - order_timestamp: { - description: `Chat order by last activity, default "${SearchChatsOrder.DESC}" (newest first)`, - enum: Object.values(SearchChatsOrder), - type: JsonSchemaType.STRING - }, - to_timestamp: { - description: - 'Only messages before this time (exclusive), same format as from_timestamp', - type: JsonSchemaType.STRING - } - }, - type: JsonSchemaType.OBJECT - } - }, - type: ToolCallType.FUNCTION - }; -} diff --git a/tools/ui/src/lib/constants/tool-ui.constants.ts b/tools/ui/src/lib/constants/tool-ui.constants.ts deleted file mode 100644 index 1078ebfbee5c..000000000000 --- a/tools/ui/src/lib/constants/tool-ui.constants.ts +++ /dev/null @@ -1,66 +0,0 @@ -// Registry of server and browser tools whose renderer -// shows a recognizable icon and friendly label inline in the chat UI. -// -// To add a new tool, add an entry to TOOL_UI. To give a -// tool a custom title or body renderer, add a dedicated component under -// ChatMessageToolCall/ and route it in ChatMessageToolCallBlock.svelte -// (see ChatMessageToolCallBlockGetDatetime and -// ChatMessageToolCallBlockSearchResults for prior art). - -import { - Braces, - Clock, - Eye, - FilePen, - FilePlus, - FileSearch, - FileText, - Info, - MessagesSquare, - SearchCode, - Terminal -} from '@lucide/svelte'; -import { BuiltInTool, ToolSource } from '$lib/enums'; -import type { ToolUiEntry } from '$lib/types'; - -export const TOOL_UI: Readonly> = { - [BuiltInTool.BROWSER_GET_DATETIME]: { - icon: Clock, - label: 'Current time', - source: ToolSource.BROWSER - }, - [BuiltInTool.BROWSER_READ_MEDIA]: { icon: Eye, label: 'Read media', source: ToolSource.BROWSER }, - [BuiltInTool.BROWSER_RUN_JAVASCRIPT]: { - icon: Braces, - label: 'Run JavaScript', - source: ToolSource.BROWSER - }, - [BuiltInTool.BROWSER_SEARCH_CHATS]: { - icon: MessagesSquare, - label: 'Search chats', - source: ToolSource.BROWSER - }, - [BuiltInTool.SERVER_EDIT_FILE]: { icon: FilePen, label: 'Edit file', source: ToolSource.SERVER }, - [BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: { - icon: Terminal, - label: 'Run command', - source: ToolSource.SERVER - }, - [BuiltInTool.SERVER_FILE_GLOB_SEARCH]: { - icon: FileSearch, - label: 'Search files', - source: ToolSource.SERVER - }, - [BuiltInTool.SERVER_GET_INFO]: { icon: Info, label: 'Runtime info', source: ToolSource.SERVER }, - [BuiltInTool.SERVER_GREP_SEARCH]: { - icon: SearchCode, - label: 'Search in files', - source: ToolSource.SERVER - }, - [BuiltInTool.SERVER_READ_FILE]: { icon: FileText, label: 'Read file', source: ToolSource.SERVER }, - [BuiltInTool.SERVER_WRITE_FILE]: { - icon: FilePlus, - label: 'Write file', - source: ToolSource.SERVER - } -} as const; diff --git a/tools/ui/src/lib/constants/ui.constants.ts b/tools/ui/src/lib/constants/ui.constants.ts deleted file mode 100644 index d5098f5b98fc..000000000000 --- a/tools/ui/src/lib/constants/ui.constants.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { MODEL_ICON } from './icons.constants'; -import { - SHORTCUT_MODELS, - SHORTCUT_NEW_CHAT, - SHORTCUT_SEARCH, - SHORTCUT_SETTINGS -} from './keyboard-shortcuts.constants'; -import { MCP_SERVERS_ROUTE_ID, MODELS_ROUTE_ID, SETTINGS_ROUTE_ID } from './routes.constants'; -import { Search, Settings, SquarePen } from '@lucide/svelte'; -import McpLogo from '$lib/components/app/mcp/McpLogo.svelte'; -import { SidebarAction, ToolSource } from '$lib/enums'; -import type { DesktopIconStripItem } from '$lib/types'; - -/** Delay before a copied affordance resets from its check to the copy icon. */ -export const COPY_FEEDBACK_RESET_MS = 1500; - -/** How long a collapsible block's body takes to expand or collapse. */ -export const COLLAPSIBLE_TRANSITION_MS = 200; - -/** - * Parts of a message where right-click keeps the browser's own menu (open or - * copy a link, save an image, copy code or a field), not the message actions. - */ -export const NATIVE_CONTEXT_MENU_SELECTOR = - 'a, img, video, audio, pre, code, input, textarea, [contenteditable="true"]'; - -/** - * A sidebar section under a dragged chat, or one being moved: the faint tint - * of the sidebar's resize handle, edged like the handle while it is dragged. - */ -export const SIDEBAR_DRAG_HIGHLIGHT_CLASS = 'bg-foreground/6 ring-1 ring-foreground/15 ring-inset'; - -/** How long a sidebar chat row takes to slide out of a section, or into one. */ -export const SIDEBAR_ROW_SLIDE_MS = 200; - -/** Chats a sidebar section shows before its "Show more" row. */ -export const SIDEBAR_SECTION_PREVIEW_COUNT = 6; - -/** - * The "Show less" row of an opened section stays at the bottom of the sidebar - * while the section scrolls under it, with room below it and a fade above - * (see app.css). "Show more" is a plain row. - */ -export const SIDEBAR_SHOW_MORE_ROW_CLASS = 'sidebar-show-more sticky bottom-0 z-10 pb-2'; - -/** Ids of the sidebar's conversation sections, for their folded state. */ -export const SIDEBAR_SECTION_IDS = { - /** Followed by the group id: one section per group. */ - GROUP_PREFIX: 'group:', - PINNED: 'pinned', - RECENT: 'recent' -} as const; - -export const FORK_TREE_DEPTH_PADDING = 8; -export const SYSTEM_MESSAGE_PLACEHOLDER = 'System message'; - -/** Data attributes for app-level DOM contracts. */ -export const UI_DATA_ATTRS = { - ACTIVE: 'data-active', - ACTIVE_TAB: 'data-active-tab', - /** On while the main chat form is expanded (a full-screen sheet on a phone). */ - CHAT_FORM_SHEET: 'data-chat-form-sheet', - CONVERSATION_ROW: 'data-conversation-row', - HIGHLIGHT_THEME_PREVIEW: 'data-highlight-theme-preview', - PICKER_INDEX: 'data-picker-index', - RESULT_INDEX: 'data-result-index', - THUMBNAIL_INDEX: 'data-thumbnail-index' -} as const; - -export const TOOL_GROUP_LABELS = { - [ToolSource.BROWSER]: 'Browser', - [ToolSource.CUSTOM]: 'JSON Schema', - [ToolSource.SERVER]: 'Server' -} as const; - -export const TOOL_SERVER_LABELS = { - [ToolSource.BROWSER]: 'Browser Tools', - [ToolSource.CUSTOM]: 'Custom Tools', - [ToolSource.SERVER]: 'Server Tools' -} as const; - -export const TOOLTIP_DELAY_DURATION = 500; - -export const VIEWPORT_GUTTER = 8; -export const MENU_OFFSET = 6; - -export const PROCESSING_INFO_TIMEOUT = 2000; - -/** - * Statistics units labels - */ -export const STATS_UNITS = { - TOKENS_PER_SECOND: 't/s' -} as const; - -export const DEFAULT_MOBILE_BREAKPOINT = 768; - -/** Models listed per remote provider before the "+ X more" line; search covers the rest. */ -export const REMOTE_PROVIDER_MODEL_LIMIT = 12; - -/** Orgs whose avatar is dark and needs inverting in dark mode. */ -export const DARK_INVERT_AVATAR_ORGS = ['openai']; - -/** Model rows mounted before the list scrolls; a local catalog can hold hundreds. */ -export const MODEL_ROW_WINDOW = 50; - -/** Models of one family shown before the rest fold behind a "show more" row. */ -export const FAMILY_ROW_WINDOW = 6; - -/** Recently used models kept per browser, most recent first. */ -export const RECENT_MODEL_LIMIT = 20; - -export const ICON_STRIP_TRANSITION_DURATION = 150; -export const ICON_STRIP_TRANSITION_DELAY_MULTIPLIER = 50; - -/** Collapsed desktop sidebar strip width, matching its `md:w-12`. */ -export const SIDEBAR_COLLAPSED_WIDTH = '3rem'; -/** Bounds the expanded desktop sidebar can be dragged between. */ -export const SIDEBAR_MIN_WIDTH = '18rem'; -export const SIDEBAR_MAX_WIDTH = '32rem'; -/** Dragging the sidebar edge narrower than this snaps it to the pointer; letting go hides it. */ -export const SIDEBAR_COLLAPSE_WIDTH = '9rem'; -/** How far past its min or max width a drag can stretch the sidebar before it resists fully. */ -export const SIDEBAR_OVERSTRETCH_PX = 80; -/** Spring-back duration when a drag ends outside the width bounds. */ -export const SIDEBAR_SETTLE_MS = 300; -/** Duration of the sidebar's open and close slide, matching its `duration-200` transition. */ -export const SIDEBAR_TOGGLE_MS = 200; -/** The sidebar's contents fading out while a phone's full-screen search covers them, and back in. */ -export const SIDEBAR_CONTENT_FADE_MS = 200; - -/** Phone sidebar reveal: the page slides aside by this share of the screen, up to the max width. */ -export const SIDEBAR_REVEAL_RATIO = 0.8; -export const SIDEBAR_REVEAL_MAX_WIDTH = '20rem'; -/** Duration of the phone sidebar reveal, matching the page's `duration-300` slide. */ -export const SIDEBAR_REVEAL_MS = 300; -/** Wait after a tap in the phone sidebar closes it, before the tap's page or dialog appears. */ -export const SIDEBAR_REVEAL_ACTION_DELAY_MS = 180; -/** A swipe that starts this close to the left edge can open the phone sidebar. */ -export const SIDEBAR_REVEAL_EDGE_PX = 24; -/** Movement before a reveal swipe locks to a horizontal drag. */ -export const SIDEBAR_REVEAL_SLOP_PX = 8; -/** A rightward swipe this long from anywhere on the page opens the phone sidebar too. */ -export const SIDEBAR_REVEAL_SWIPE_PX = 16; -/** Share of the reveal a drag must cover to open or close the phone sidebar when let go slowly. */ -export const SIDEBAR_REVEAL_COMMIT_RATIO = 0.3; -/** Release speed past which a drag opens or closes the phone sidebar the way it was heading. */ -export const SIDEBAR_REVEAL_FLING_PX_PER_MS = 0.3; - -/** Hold time before a phone conversation row opens its action menu. */ -export const ROW_LONG_PRESS_MS = 450; -/** Drift that cancels a row hold, so scrolling still works. */ -export const ROW_LONG_PRESS_SLOP_PX = 8; - -/** Max height for tool-result code blocks (json / source / diff / streaming code). */ -export const MAX_HEIGHT_CODE_BLOCK = '22rem'; - -/** The sidebar's actions at its top: starting, finding and organizing chats. */ -export const SIDEBAR_ACTIONS_ITEMS: DesktopIconStripItem[] = [ - { - action: SidebarAction.NEW_CHAT, - icon: SquarePen, - keys: SHORTCUT_NEW_CHAT, - tooltip: 'New chat' - }, - { action: SidebarAction.SEARCH, icon: Search, keys: SHORTCUT_SEARCH, tooltip: 'Search' } -]; - -/** The sidebar's footer: managing the app around the chats. */ -export const SIDEBAR_FOOTER_ITEMS: DesktopIconStripItem[] = [ - { - action: SidebarAction.MANAGE_MODELS, - activeRouteId: MODELS_ROUTE_ID, - icon: MODEL_ICON, - keys: SHORTCUT_MODELS, - tooltip: 'Models' - }, - { - action: SidebarAction.MCP, - activeRouteId: MCP_SERVERS_ROUTE_ID, - icon: McpLogo, - tooltip: 'MCP' - }, - { - action: SidebarAction.SETTINGS, - activeRouteId: SETTINGS_ROUTE_ID, - icon: Settings, - keys: SHORTCUT_SETTINGS, - tooltip: 'Settings' - } -]; - -/** A light haptic tap's length where the browser vibrates (Android): a click, not a buzz. */ -export const HAPTIC_TAP_MS = 8; diff --git a/tools/ui/src/lib/contexts/chat-form-actions.context.ts b/tools/ui/src/lib/contexts/chat-form-actions.context.ts deleted file mode 100644 index a49f17447e44..000000000000 --- a/tools/ui/src/lib/contexts/chat-form-actions.context.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { CONTEXT_KEY_CHAT_FORM_ACTIONS } from '$lib/constants'; -import type { ChatFormActionsContext } from '$lib/types'; -import { getContext, setContext } from 'svelte'; - -const CHAT_FORM_ACTIONS_KEY = Symbol.for(CONTEXT_KEY_CHAT_FORM_ACTIONS); - -/** - * Sets the chat form actions context. Call in the parent component (ChatFormActions.svelte). - */ -export function setChatFormActionsContext(ctx: ChatFormActionsContext): ChatFormActionsContext { - return setContext(CHAT_FORM_ACTIONS_KEY, ctx); -} - -/** - * Gets the chat form actions context. Call in child components. - */ -export function getChatFormActionsContext(): ChatFormActionsContext { - return getContext(CHAT_FORM_ACTIONS_KEY); -} diff --git a/tools/ui/src/lib/contexts/chat-message-actions.context.ts b/tools/ui/src/lib/contexts/chat-message-actions.context.ts deleted file mode 100644 index fb075b3b0281..000000000000 --- a/tools/ui/src/lib/contexts/chat-message-actions.context.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { CONTEXT_KEY_CHAT_MESSAGE_ACTIONS } from '$lib/constants'; -import type { ChatMessageActionsContext } from '$lib/types'; -import { getContext, setContext } from 'svelte'; - -const CHAT_MESSAGE_ACTIONS_KEY = Symbol.for(CONTEXT_KEY_CHAT_MESSAGE_ACTIONS); - -/** - * Sets the per-message actions context. Call this in the parent component (ChatMessage.svelte). - */ -export function setChatMessageActionsContext( - ctx: ChatMessageActionsContext -): ChatMessageActionsContext { - return setContext(CHAT_MESSAGE_ACTIONS_KEY, ctx); -} - -/** - * Gets the per-message actions context. Call this in child components. - */ -export function getChatMessageActionsContext(): ChatMessageActionsContext { - return getContext(CHAT_MESSAGE_ACTIONS_KEY); -} diff --git a/tools/ui/src/lib/contexts/chat-message-edit.context.ts b/tools/ui/src/lib/contexts/chat-message-edit.context.ts deleted file mode 100644 index e9c053036e79..000000000000 --- a/tools/ui/src/lib/contexts/chat-message-edit.context.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { CONTEXT_KEY_CHAT_MESSAGE_EDIT } from '$lib/constants'; -import type { ChatMessageEditContext } from '$lib/types'; -import { getContext, setContext } from 'svelte'; - -const CHAT_MESSAGE_EDIT_KEY = Symbol.for(CONTEXT_KEY_CHAT_MESSAGE_EDIT); - -/** - * Sets the message edit context. Call this in the parent component (ChatMessage.svelte). - */ -export function setChatMessageEditContext(ctx: ChatMessageEditContext): ChatMessageEditContext { - return setContext(CHAT_MESSAGE_EDIT_KEY, ctx); -} - -/** - * Gets the message edit context. Call this in child components. - */ -export function getChatMessageEditContext(): ChatMessageEditContext { - return getContext(CHAT_MESSAGE_EDIT_KEY); -} diff --git a/tools/ui/src/lib/enums/index.ts b/tools/ui/src/lib/enums/index.ts deleted file mode 100644 index 134666eb5a62..000000000000 --- a/tools/ui/src/lib/enums/index.ts +++ /dev/null @@ -1,122 +0,0 @@ -export { - AttachmentLabel, - AttachmentType, - AttachmentMenuItemId, - AttachmentItemEnabledWhen, - AttachmentAction -} from './attachment.enums'; - -export { - AgenticSectionType, - ContinueIntentKind, - DiffLineKind, - ToolResultKind, - ToolCallType -} from './agentic.enums'; - -export { - ChatMessageStatsView, - ChatMessageStatisticsMode, - StreamConnectionState, - ContentPartType, - ConversationSelectionMode, - ErrorDialogType, - MessageRole, - MessageType, - PdfViewMode, - ReasoningFormat, - ChatFormCommandAction, - FileMentionEntryType -} from './chat.enums'; - -export { SessionRecordType } from './conversation-import.enums'; - -export { BooleanString } from './boolean-string.enums'; - -export { ReasoningEffort } from './reasoning-effort.enums'; - -export { - FileTypeCategory, - FileTypeImage, - FileTypeAudio, - FileTypePdf, - FileTypeText, - FileExtensionImage, - FileExtensionAudio, - FileExtensionPdf, - FileExtensionText, - MimeTypeApplication, - MimeTypeAudio, - MimeTypeVideo, - MimeTypeImage, - MimeTypePrefix, - MimeTypeIncludes, - UriPattern, - MimeTypeText, - SpecialFileType -} from './files.enums'; - -export { HfEntryType, HfModelSort, SidecarForm } from './huggingface.enums'; - -export { - MCPConnectionPhase, - MCPLogLevel, - MCPTransportType, - HealthCheckStatus, - MCPContentType, - MCPRefType, - JsonSchemaType -} from './mcp.enums'; - -export { - ModelAuxSidecar, - ModelCapability, - ModelDraftSidecar, - ModelModality, - ModelSelectableFileKind -} from './model.enums'; - -export { - ModelDownloadConfirmAction, - ModelDownloadStopRequest, - ModelGroupKind, - ModelRowDownloadState, - ModelsTableGroupKind, - ModelsTableSortKey -} from './model.enums'; - -export { - ServerRole, - ServerModelSource, - ServerModelStatus, - ServerModelsSseEventType -} from './server.enums'; - -export { ParameterSource, SyncableParameterType, SettingsFieldType } from './settings.enums'; - -export { - ColorLevel, - ColorMode, - HtmlInputType, - McpPromptVariant, - MenuKind, - ScrollCarouselVariant, - SidebarAction, - SidebarSectionKind, - TooltipSide, - UrlProtocol -} from './ui.enums'; - -export { KeyboardKey } from './keyboard.enums'; - -export { - BuiltInTool, - GlobSearchType, - SearchChatsMessageSelection, - SearchChatsOrder, - ToolSource, - ToolPermissionDecision, - ToolResponseField -} from './tools.enums'; - -export { SplashOrientation } from './splash.enums'; diff --git a/tools/ui/src/lib/enums/model.enums.ts b/tools/ui/src/lib/enums/model.enums.ts deleted file mode 100644 index 2f25c26f4f79..000000000000 --- a/tools/ui/src/lib/enums/model.enums.ts +++ /dev/null @@ -1,94 +0,0 @@ -export enum ModelModality { - AUDIO = 'AUDIO', - TEXT = 'TEXT', - VIDEO = 'VIDEO', - VISION = 'VISION' -} - -export enum ModelCapability { - REASONING = 'reasoning', - TOOL_USE = 'tools' -} - -/** - * Speculative-decoding draft sidecars (server spec-type draft-*). - * Filenames use the lowercase token, e.g. `mtp-.gguf` or `-mtp` suffix. - */ -export enum ModelDraftSidecar { - /** DFlash block-diffusion draft (spec-type draft-dflash). */ - DFLASH = 'dflash', - /** DSpark block-diffusion draft (spec-type draft-dspark). */ - DSPARK = 'dspark', - /** EAGLE-3 speculative draft (spec-type draft-eagle3). */ - EAGLE3 = 'eagle3', - /** Multi-token-prediction draft head (spec-type draft-mtp). */ - MTP = 'mtp' -} - -/** - * Non-draft sidecar file types. A sidecar is any auxiliary GGUF file - * accompanying the main model weights. - */ -export enum ModelAuxSidecar { - /** Importance-matrix data used to build imatrix quants; not loaded at serve time. */ - IMATRIX = 'imatrix', - /** Multimodal projector: unlocks vision and/or audio input modalities. */ - MMPROJ = 'mmproj' -} - -/** - * Role of a selectable GGUF in the download options: the main weights, a - * speculative-decoding draft sidecar, or an auxiliary sidecar (mmproj). - */ -export enum ModelSelectableFileKind { - AUX = 'aux', - DRAFT = 'draft', - MAIN = 'main' -} - -/** - * Why an in-flight download is being stopped, so the terminal `download_failed` feed - * event can be attributed: a user pause (resumable) or a user cancel (discard). - */ -export enum ModelDownloadStopRequest { - CANCEL = 'cancel', - PAUSE = 'pause' -} - -/** - * Destructive download action the user is asked to confirm: stop and discard an - * in-flight download, or delete an already-downloaded model from disk. Both - * resolve through the same store removal call, differing only in the copy. - */ -export enum ModelDownloadConfirmAction { - CANCEL = 'cancel', - DELETE = 'delete' -} - -/** What a table row group folds: the quants of one repo, or its variants. */ -export enum ModelGroupKind { - QUANTS = 'quants', - VARIANTS = 'variants' -} - -/** Kind of one collapsible block of the models manager table. */ -export enum ModelsTableGroupKind { - DOWNLOADING = 'downloading', - FAVORITES = 'favorites', - HIDDEN = 'hidden', - LOADED = 'loaded', - LOCAL = 'local' -} - -/** Download state a manager row reports in place of its load state. */ -export enum ModelRowDownloadState { - DOWNLOADED = 'downloaded', - DOWNLOADING = 'downloading', - PAUSED = 'paused' -} - -/** Column the models manager table can be ordered by. */ -export enum ModelsTableSortKey { - CONTEXT = 'context', - NAME = 'name' -} diff --git a/tools/ui/src/lib/enums/ui.enums.ts b/tools/ui/src/lib/enums/ui.enums.ts deleted file mode 100644 index c4c0156cc0f9..000000000000 --- a/tools/ui/src/lib/enums/ui.enums.ts +++ /dev/null @@ -1,80 +0,0 @@ -export enum ColorMode { - DARK = 'dark', - LIGHT = 'light', - SYSTEM = 'system' -} - -export enum TooltipSide { - BOTTOM = 'bottom', - LEFT = 'left', - RIGHT = 'right', - TOP = 'top' -} - -/** - * ScrollCarousel arrow placement. - */ -export enum ScrollCarouselVariant { - CENTER = 'center', - TOP = 'top' -} - -/** - * Sidebar icon strip actions handled directly by the sidebar. - */ -export enum SidebarAction { - MANAGE_MODELS = 'manage-models', - MCP = 'mcp', - NEW_CHAT = 'new-chat', - SEARCH = 'search', - SETTINGS = 'settings' -} - -/** Kind of a sidebar conversation section, which can be dragged into another order. */ -export enum SidebarSectionKind { - GROUP = 'group', - PINNED = 'pinned', - RECENT = 'recent' -} - -/** - * MCP prompt display variant - */ -export enum McpPromptVariant { - ATTACHMENT = 'attachment', - MESSAGE = 'message' -} - -/** - * URL prefixes for protocol detection - */ -export enum UrlProtocol { - DATA = 'data:', - FILE = 'file:', - HTTP = 'http:', - HTTPS = 'https:', - WEBSOCKET = 'ws:', - WEBSOCKET_SECURE = 'wss:' -} - -export enum HtmlInputType { - FILE = 'file' -} - -/** - * Alert level that drives the context gauge dial color. - */ -export enum ColorLevel { - CRITICAL = 'critical', - NEUTRAL = 'neutral', - OK = 'ok', - WARNING = 'warning' -} - -/** - * Which menu an item's actions render in. - */ -export enum MenuKind { - CONTEXT = 'context', - DROPDOWN = 'dropdown' -} diff --git a/tools/ui/src/lib/hooks/use-pwa.svelte.ts b/tools/ui/src/lib/hooks/use-pwa.svelte.ts deleted file mode 100644 index 8d2ca2b0b5c1..000000000000 --- a/tools/ui/src/lib/hooks/use-pwa.svelte.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { browser } from '$app/environment'; -import { BUILD_VERSION_LOCALSTORAGE_KEY, SW_CONFIG } from '$lib/constants'; -import { versionStore } from '$lib/stores'; -import { useRegisterSW } from 'virtual:pwa-register/svelte'; - -/** - * Hook for PWA service worker registration, update polling, and build version mismatch detection. - * - * Combines two concerns that always belong together: - * 1. SW registration with periodic polling for updates - * 2. localStorage-based version tracking for non-PWA users - */ -export function usePwa() { - let swCheckInterval: ReturnType | null = null; - let needRefreshByStorage = $state(false); - - const { - // offlineReady, // to do - add installation banners for iOS - needRefresh: pwaNeedRefresh, - updateServiceWorker - } = useRegisterSW({ - onRegisteredSW(swUrl: string, r: ServiceWorkerRegistration | undefined) { - if (swCheckInterval) { - clearInterval(swCheckInterval); - } - - swCheckInterval = setInterval(async () => { - if (!r || r.installing || !navigator?.onLine) return; - - try { - const resp = await fetch(swUrl, { - cache: SW_CONFIG.UPDATE_FETCH_OPTIONS.CACHE, - headers: { - cache: SW_CONFIG.UPDATE_FETCH_OPTIONS.HEADERS.CACHE, - 'cache-control': SW_CONFIG.UPDATE_FETCH_OPTIONS.HEADERS.CACHE_CONTROL - } - }); - - if (resp?.status === 200) { - await r.update(); - } - } catch (e) { - console.error(e); - } - }, SW_CONFIG.CHECK_INTERVAL_MS); - }, - onRegisterError(error: unknown) { - console.error('[PWA] SW registration error:', error); - } - }); - - // Detect version mismatch via localStorage. - // _app/version.json is SvelteKit's native version file for PWA cache invalidation. - // This comparison detects server upgrades for non-PWA users. - $effect(() => { - if (!browser) return; - - // PWA pages update via the service worker path; the storage check is the non-PWA fallback only - if (navigator.serviceWorker?.controller) return; - - const currentVersion = versionStore.frontend; - - if (!currentVersion) return; - - try { - const storedVersion = localStorage.getItem(BUILD_VERSION_LOCALSTORAGE_KEY); - - needRefreshByStorage = !!storedVersion && storedVersion !== currentVersion; - localStorage.setItem(BUILD_VERSION_LOCALSTORAGE_KEY, currentVersion); - } catch { - needRefreshByStorage = false; - } - }); - - return { - /** Writable that is true when a PWA service worker update is available */ - get needRefresh() { - return pwaNeedRefresh; - }, - /** Version mismatch detected via localStorage (non-PWA users) */ - get needRefreshByStorage() { - return needRefreshByStorage; - }, - updateServiceWorker - }; -} diff --git a/tools/ui/src/lib/services/index.ts b/tools/ui/src/lib/services/index.ts deleted file mode 100644 index 0e584520d35d..000000000000 --- a/tools/ui/src/lib/services/index.ts +++ /dev/null @@ -1,369 +0,0 @@ -/** - * - * SERVICES - * - * Stateless service layer for API communication and data operations. - * Services handle protocol-level concerns (HTTP, WebSocket, MCP, IndexedDB) - * without managing reactive state — that responsibility belongs to stores. - * - * **Design Principles:** - * - All methods are static — no instance state - * - Pure I/O operations (network requests, database queries) - * - No Svelte runes or reactive primitives - * - Error handling at the protocol level; business-level error handling in stores - * - * **Architecture (bottom to top):** - * - **Services** (this layer): Stateless protocol communication - * - **Stores**: Reactive state management consuming services - * - **Components**: UI consuming stores - * - */ - -/** - * **ChatService** - Chat Completions API communication layer - * - * Handles direct communication with the llama-server's `/v1/chat/completions` endpoint. - * Provides streaming and non-streaming response parsing, message format conversion - * (DatabaseMessage → API format), and request lifecycle management. - * - * **Terminology - Chat vs Conversation:** - * - **Chat**: The active interaction space with the Chat Completions API. Ephemeral and - * runtime-focused — sending messages, receiving streaming responses, managing request lifecycles. - * - **Conversation**: The persistent database entity storing all messages and metadata. - * Managed by conversationsStore, conversations persist across sessions. - * - * **Architecture & Relationships:** - * - **ChatService** (this class): Stateless API communication layer - * - Handles HTTP requests/responses with the llama-server - * - Manages streaming and non-streaming response parsing - * - Converts database messages to API format (multimodal, tool calls) - * - Handles error translation with user-friendly messages - * - * - **chatStore**: Primary consumer — uses ChatService for all AI model communication - * - **agenticStore**: Uses ChatService for multi-turn agentic loop streaming - * - **conversationsStore**: Provides message context for API requests - * - * **Key Responsibilities:** - * - Streaming response handling with real-time content/reasoning/tool-call callbacks - * - Non-streaming response parsing with complete response extraction - * - Database message to API format conversion (attachments, tool calls, multimodal) - * - Tool call delta merging for incremental streaming aggregation - * - Request parameter assembly (sampling, penalties, custom params) - * - File attachment processing (images, PDFs, audio, text, MCP prompts/resources) - * - Reasoning content stripping from prompt history to avoid KV cache pollution - * - Error translation (network, timeout, server errors → user-friendly messages) - * - * @see chatStore in stores/chat/index.svelte.ts — primary consumer for chat state management - * @see agenticStore in stores/agentic/index.svelte.ts — uses ChatService for agentic loop streaming - * @see conversationsStore in stores/conversations/index.svelte.ts — provides message context - */ -export { ChatService } from './chat.service'; - -/** - * **DatabaseService** - IndexedDB persistence layer via Dexie ORM - * - * Provides stateless data access for conversations and messages using IndexedDB. - * Handles all low-level storage operations including branching tree structures, - * cascade deletions, and transaction safety for multi-table operations. - * - * **Architecture & Relationships (bottom to top):** - * - **DatabaseService** (this class): Stateless IndexedDB operations - * - Lowest layer — direct Dexie/IndexedDB communication - * - Pure CRUD operations without business logic - * - Handles branching tree structure (parent-child relationships) - * - Provides transaction safety for multi-table operations - * - * - **conversationsStore**: Reactive state management layer - * - Uses DatabaseService for all persistence operations - * - Manages conversation list, active conversation, and messages in memory - * - * - **chatStore**: Active AI interaction management - * - Uses conversationsStore for conversation context - * - Directly uses DatabaseService for message CRUD during streaming - * - * **Key Responsibilities:** - * - Conversation CRUD (create, read, update, delete) - * - Message CRUD with branching support (parent-child relationships) - * - Root message and system prompt creation - * - Cascade deletion of message branches (descendants) - * - Transaction-safe multi-table operations - * - Conversation import with duplicate detection - * - * **Database Schema:** - * - `conversations`: id, lastModified, currNode, name - * - `messages`: id, convId, type, role, timestamp, parent, children - * - * **Branching Model:** - * Messages form a tree structure where each message can have multiple children, - * enabling conversation branching and alternative response paths. The conversation's - * `currNode` tracks the currently active branch endpoint. - * - * @see conversationsStore in stores/conversations/index.svelte.ts — reactive layer on top of DatabaseService - * @see chatStore in stores/chat/index.svelte.ts — uses DatabaseService directly for message CRUD during streaming - */ -export { DatabaseService } from './database.service'; - -/** - * **ConversationTransferService** - Conversation import/export format layer - * - * Owns the JSONL session format (SESSION header + MESSAGE records), ZIP - * archiving and browser downloads. Stateless; DB access and store refreshes - * stay in conversationsStore. - */ -export { ConversationTransferService } from './conversation-transfer.service'; - -/** - * **ModelsService** - Model management API communication - * - * Handles communication with model-related endpoints for both MODEL (single model) - * and ROUTER (multi-model) server modes. Provides model listing, loading/unloading, - * and status checking without managing any model state. - * - * **Architecture & Relationships:** - * - **ModelsService** (this class): Stateless HTTP communication - * - Sends requests to model endpoints - * - Parses and returns typed API responses - * - Provides model status utility methods - * - * - **modelsStore**: Primary consumer — manages reactive model state - * - Calls ModelsService for all model API operations - * - Handles polling, caching, and state updates - * - * **Key Responsibilities:** - * - List available models via OpenAI-compatible `/v1/models` endpoint - * - Load/unload models via `/models/load` and `/models/unload` (ROUTER mode) - * - Model status queries (loaded, loading) - * - * **Server Mode Behavior:** - * - **MODEL mode**: Only `list()` is relevant — single model always loaded - * - **ROUTER mode**: Full lifecycle - `list()`, `load()`, `unload()` - * - * **Endpoints:** - * - `GET /v1/models` — OpenAI-compatible model list (both modes) - * - `POST /models/load` — Load a model (ROUTER mode only) - * - `POST /models/unload` — Unload a model (ROUTER mode only) - * - * @see modelsStore in stores/models/index.svelte.ts — primary consumer for reactive model state - */ -export { ModelsService } from './models.service'; - -/** - * **HuggingFaceService** - Hugging Face Hub browsing and searching - * - * Stateless HTTP client for the HF REST API (`/api/models`, `/tree`, raw - * README) and the llama.app model catalog. Provides GGUF file analysis - * (quant metadata, shard collapsing, size formatting) used by the models - * discover UI. - */ -export { HuggingFaceService } from './huggingface.service'; - -/** - * **PropsService** - Server properties and capabilities retrieval - * - * Fetches server configuration, model information, and capabilities from the `/props` - * endpoint. Supports both global server props and per-model props (ROUTER mode). - * - * **Architecture & Relationships:** - * - **PropsService** (this class): Stateless HTTP communication - * - Fetches server properties from `/props` endpoint - * - Handles authentication and request parameters - * - Returns typed `ApiLlamaCppServerProps` responses - * - * - **serverStore**: Consumes global server properties (role detection, connection state) - * - **modelsStore**: Consumes per-model properties (modalities, context size) - * - **settingsStore**: Syncs default generation parameters from props response - * - * **Key Responsibilities:** - * - Fetch global server properties (default generation settings, modalities) - * - Fetch per-model properties in ROUTER mode via `?model=` parameter - * - Handle autoload control to prevent unintended model loading - * - * **API Behavior:** - * - `GET /props` → Global server props (MODEL mode: includes modalities) - * - `GET /props?model=` → Per-model props (ROUTER mode: model-specific modalities) - * - `&autoload=false` → Prevents model auto-loading when querying props - * - * @see serverStore in stores/server.svelte.ts — consumes global server props - * @see modelsStore in stores/models/index.svelte.ts — consumes per-model props for modalities - * @see settingsStore in stores/settings/index.svelte.ts — syncs default generation params from props - */ -export { PropsService } from './props.service'; - -/** - * **ParameterSyncService** - Server defaults and user settings synchronization - * - * Manages the complex logic of merging server-provided default parameters with - * user-configured overrides. Ensures the UI reflects the actual server state - * while preserving user customizations. Tracks parameter sources (server default - * vs user override) for display in the settings UI. - * - * **Architecture & Relationships:** - * - **ParameterSyncService** (this class): Stateless sync logic - * - Pure functions for parameter extraction, merging, and diffing - * - No side effects — receives data in, returns data out - * - Handles floating-point precision normalization - * - * - **settingsStore**: Primary consumer — calls sync methods during: - * - Initial load (`syncWithServerDefaults`) - * - Settings reset (`forceSyncWithServerDefaults`) - * - Parameter info queries (`getParameterInfo`) - * - * - **PropsService**: Provides raw server props that feed into extraction - * - * **Key Responsibilities:** - * - Extract syncable parameters from server `/props` response - * - Merge server defaults with user overrides (user wins) - * - Track parameter source (Custom vs Default) for UI badges - * - Validate server parameter values by type (number, string, boolean) - * - Create diffs between current settings and server defaults - * - Floating-point precision normalization for consistent comparisons - * - * **Parameter Source Priority:** - * 1. **User Override** (Custom badge) — explicitly set by user in settings - * 2. **Server Default** (Default badge) — from `/props` endpoint - * 3. **App Default** — hardcoded fallback when server props unavailable - * - * **Exports:** - * - `ParameterSyncService` class — static methods for sync logic - * - `SYNCABLE_PARAMETERS` — mapping of UI setting keys to server parameter keys - * - * @see settingsStore in stores/settings/index.svelte.ts — primary consumer for settings sync - * @see SettingsChatParameterSourceIndicator — displays parameter source badges in UI - */ -export { ParameterSyncService } from './parameter-sync.service'; - -/** - * **MCPService** - Low-level MCP protocol communication layer - * - * Implements the client-side MCP (Model Context Protocol) SDK operations for connecting - * to MCP servers, discovering capabilities, and executing protocol operations. - * Supports multiple transport types: WebSocket, StreamableHTTP, and SSE (legacy fallback). - * - * **Architecture & Relationships:** - * - **MCPService** (this class): Stateless protocol communication - * - Creates and manages transport connections (WebSocket, StreamableHTTP, SSE) - * - Wraps MCP SDK client operations with error handling - * - Formats tool results and extracts server info - * - Provides abort signal support for cancellable operations - * - * - **mcpStore**: Reactive business logic facade - * - Uses MCPService for all protocol-level operations - * - Manages connection lifecycle, health checks, reconnection - * - Handles tool name conflict resolution and server coordination - * - * - **mcpResourceStore** (composed as mcpStore.resources): Reactive resource state - * - Receives resource data fetched via MCPService - * - Manages resource caching, subscriptions, and attachments - * - * - **agenticStore**: Agentic loop orchestration - * - Executes tool calls via mcpStore → MCPService chain - * - * **Key Responsibilities:** - * - Transport creation with automatic fallback (StreamableHTTP → SSE) - * - Server connection with detailed phase tracking and progress callbacks - * - Tool discovery (`listTools`) and execution (`callTool`) with abort support - * - Prompt listing (`listPrompts`) and retrieval (`getPrompt`) with arguments - * - Resource operations: list, read, subscribe/unsubscribe, template support - * - Completion suggestions for prompt arguments and resource URI templates - * - CORS proxy routing via llama-server for cross-origin MCP servers - * - Tool result formatting (text, images, embedded resources) - * - * **Transport Hierarchy:** - * 1. **WebSocket** — bidirectional, no CORS proxy support - * 2. **StreamableHTTP** — modern HTTP-based, supports CORS proxy - * 3. **SSE** — legacy fallback, supports CORS proxy - * - * @see mcpStore in stores/mcp/index.svelte.ts — reactive business logic facade on top of MCPService - * @see mcpStore.resources in stores/mcp/resources.svelte.ts — reactive resource state management - * @see agenticStore in stores/agentic/index.svelte.ts — uses MCPService (via mcpStore) for tool execution - * @see MCP Protocol Specification: https://modelcontextprotocol.io/specification/2025-06-18 - */ -export { MCPService } from './mcp.service'; - -/** - * **SandboxService** - Browser JavaScript execution in a browser sandbox - * - * Stateless executor for the run_javascript browser tool. Model generated - * code runs in a Web Worker spawned inside a sandboxed iframe with an opaque - * origin: no access to the app origin, its storage or its API, and outgoing - * requests carry a null origin. The code never touches a main thread, so the - * parent enforces the timeout by removing the iframe, which terminates the - * worker at the browser level. - * - * **Architecture & Relationships:** - * - **SandboxService** (this class): Stateless sandbox execution - * - **toolsStore**: Exposes the tool definition when the sandbox is enabled - * - **agenticStore**: Dispatches ToolSource.BROWSER calls here - * - * @see buildSandboxToolDefinition in utils/sandbox-tool - tool schema sent to the LLM - * @see agenticStore in stores/agentic/index.svelte.ts - tool dispatch - */ -export { SandboxService } from './sandbox.service'; - -/** - * **SearchChatsService** - Read-only search over saved chats, executor of the search_chats browser tool - * - * @see buildSearchChatsToolDefinition in constants/search-chats - tool schema sent to the LLM - * @see utils/search-chats - parameter parsing, matching and formatting - */ -export { SearchChatsService } from './search-chats.service'; - -/** - * **RouterService** — Dynamic route URL construction utility - * - * Stateless utility for building dynamic route URLs from ROUTES base paths. - * Static routes (START, MCP_SERVERS) live in ROUTES constants; - * dynamic routes (CHAT, SETTINGS) are constructed here by appending parameters. - * - * **Architecture & Relationships:** - * - **RouterService** (this class): Stateless URL construction - * - Builds dynamic route URLs from ROUTES base paths - * - No side effects — receives route parameters, returns route strings - * - * - **ROUTES constant** (constants/routes.ts): Static route base paths - * - **All components/stores**: Call RouterService for dynamic route URLs - * - * **Key Responsibilities:** - * - Build chat URLs for specific conversations: `RouterService.chat(id)` → `#/chat/:id` - * - * @see ROUTES in constants/routes.ts — static route base paths - */ -export { RouterService } from './router.service'; - -/** - * **MigrationService** — Unified data migration hook - * - * Centralizes all data migrations (localStorage, IndexedDB, legacy formats) into a single - * initialization point. All migrations are NON-DESTRUCTIVE - legacy data is preserved - * for downgrade compatibility (no rollback needed). - * - * **Current Migrations:** - * 1. **localStorage prefix**: Copy LlamaCppWebui.* → LlamaUi.* (both preserved) - * 2. **IndexedDB database**: Copy LlamacppWebui → LlamaUi (both preserved) - * 3. **Legacy message format**: Marker-based → Structured format - * 4. **Theme key**: Copy standalone `theme` → config object (both preserved) - * - * **Usage:** - * ```typescript - * import { MigrationService } from '$lib/services'; - * - * // Run all migrations on app startup (non-destructive) - * await MigrationService.runAllMigrations(); - * - * // Check migration status - * const state = MigrationService.getState(); - * ``` - * - * @see migration.service.ts — full implementation (non-destructive) - */ -export { MigrationService } from './migration.service'; - -/** - * **SettingsService** - localStorage persistence layer for settings - * - * Stateless read/write of the settings config and user-override keys. Business - * logic (default merging, mobile defaults, theme migration) stays in the store. - * - * @see settingsStore in stores/settings/index.svelte.ts - reactive state + business logic - */ -export { SettingsService } from './settings.service'; diff --git a/tools/ui/src/lib/stores/agentic/index.svelte.ts b/tools/ui/src/lib/stores/agentic/index.svelte.ts deleted file mode 100644 index bc5d3890322f..000000000000 --- a/tools/ui/src/lib/stores/agentic/index.svelte.ts +++ /dev/null @@ -1,1111 +0,0 @@ -/** - * AgenticStore - Multi-turn agentic loop orchestration - * - * Drives the agentic loop over MCP tools: streams each LLM turn, detects - * tool calls, executes them via mcpStore, and enforces the turn limit. Each - * turn produces one assistant message (with tool_calls) and one tool result - * message per executed call, persisted as separate DB rows. - * - * Uses ChatService for streaming and mcpStore for tool execution; waits on - * the permission/continue/steering gates owned by {@link AgenticGates}. - */ - -import { DEFAULT_AGENTIC_CONFIG, NEWLINE } from '$lib/constants'; -import { - AUDIO_MIME_TO_EXTENSION, - DATA_URI_BASE64_REGEX, - DEFAULT_AUDIO_EXTENSION, - DEFAULT_IMAGE_EXTENSION, - IMAGE_MIME_TO_EXTENSION, - MCP_ATTACHMENT_NAME_PREFIX, - MIME_TYPE_PREFIXES -} from '$lib/constants'; -import { BuiltInTool, ToolPermissionDecision, ToolSource } from '$lib/enums'; -import { - AttachmentType, - ContentPartType, - MessageRole, - MimeTypePrefix, - ToolCallType -} from '$lib/enums'; -import { ChatService } from '$lib/services'; -import { ReadMediaService } from '$lib/services/read-media.service'; -import { SandboxService } from '$lib/services/sandbox.service'; -import { SearchChatsService } from '$lib/services/search-chats.service'; -import { ToolsService } from '$lib/services/tools.service'; -// direct imports between stores, not via the barrel, to avoid circular deps -import { AgenticGates } from '$lib/stores/agentic/gates.svelte'; -import { conversationsStore } from '$lib/stores/conversations/index.svelte'; -import { mcpStore } from '$lib/stores/mcp/index.svelte'; -import { modelsStore } from '$lib/stores/models/index.svelte'; -import { settingsStore } from '$lib/stores/settings/index.svelte'; -import { toolsStore } from '$lib/stores/tools.svelte'; -import type { - AgenticConfig, - AgenticFlowParams, - AgenticFlowResult, - AgenticSession, - MCPToolCall, - SettingsConfigType, - ToolExecutionResult -} from '$lib/types'; -import type { - AgenticFlowCallbacks, - AgenticFlowOptions, - AgenticMessage, - AgenticToolCallList, - AgenticToolPolicy, - SteeringMessage -} from '$lib/types/agentic'; -import type { - ApiChatCompletionToolCall, - ApiChatMessageContentPart, - ApiChatMessageData -} from '$lib/types/api'; -import type { - ChatMessageAgenticTimings, - ChatMessageAgenticTurnStats, - ChatMessagePromptProgress, - ChatMessageTimings, - ChatMessageToolCallTiming -} from '$lib/types/chat'; -import type { - DatabaseMessage, - DatabaseMessageExtra, - DatabaseMessageExtraAudioFile, - DatabaseMessageExtraImageFile -} from '$lib/types/database'; -import type { OpenAIToolDefinition } from '$lib/types/mcp'; -import { - executeBrowserInfoTool, - executeGetDatetimeTool, - getAudioInputFormat, - isAbortError -} from '$lib/utils'; -import { SvelteMap } from 'svelte/reactivity'; - -function createDefaultSession(): AgenticSession { - return { - currentTurn: 0, - executingToolCallId: null, - flowRootMessageId: null, - isRunning: false, - lastError: null, - liveLlm: null, - pendingPermissionRequest: null, - streamingToolCall: null, - totalToolCalls: 0 - }; -} - -function toAgenticMessages(messages: ApiChatMessageData[]): AgenticMessage[] { - return messages.map((message) => { - if ( - message.role === MessageRole.ASSISTANT && - message.tool_calls && - message.tool_calls.length > 0 - ) { - return { - content: message.content, - reasoning_content: message.reasoning_content, - role: MessageRole.ASSISTANT, - tool_calls: message.tool_calls.map((call, index) => ({ - function: { - arguments: call.function?.arguments ?? '', - name: call.function?.name ?? '' - }, - id: call.id ?? `call_${index}`, - type: (call.type as ToolCallType.FUNCTION) ?? ToolCallType.FUNCTION - })) - } satisfies AgenticMessage; - } - - if (message.role === MessageRole.ASSISTANT) { - return { - content: message.content, - reasoning_content: message.reasoning_content, - role: MessageRole.ASSISTANT - } satisfies AgenticMessage; - } - - if (message.role === MessageRole.TOOL && message.tool_call_id) { - return { - content: typeof message.content === 'string' ? message.content : '', - role: MessageRole.TOOL, - tool_call_id: message.tool_call_id - } satisfies AgenticMessage; - } - - return { - content: message.content, - role: message.role as MessageRole.SYSTEM | MessageRole.USER - } satisfies AgenticMessage; - }); -} - -class AgenticStore { - // permission, continue and steering gates the loop waits on between turns - private gates = new AgenticGates(); - private sessions = new SvelteMap(); - - get isAnyRunning(): boolean { - for (const session of this.sessions.values()) { - if (session.isRunning) return true; - } - - return false; - } - - get isReady(): boolean { - return true; - } - - clearError(conversationId: string): void { - this.updateSession(conversationId, { lastError: null }); - } - - clearSession(conversationId: string): void { - this.sessions.delete(conversationId); - } - - /** - * Clear the pending steering message without consuming it. - */ - clearSteeringMessage(conversationId: string): void { - this.gates.clearSteeringMessage(conversationId); - } - - constructor() { - // drop per-conversation session state when the conversation is deleted, - // otherwise every conversation that ever ran a flow leaks a session here - conversationsStore.onConversationsDeleted((convIds) => { - for (const convId of convIds) { - this.sessions.delete(convId); - } - }); - } - - /** - * Consume and return the pending steering message for re-sending. - * Called by chatStore after the agentic flow exits. - */ - consumePendingSteeringMessage(conversationId: string): SteeringMessage | null { - return this.gates.consumePendingSteeringMessage(conversationId); - } - - getActiveSessions(): Array<{ conversationId: string; session: AgenticSession }> { - const active: Array<{ conversationId: string; session: AgenticSession }> = []; - - for (const [conversationId, session] of this.sessions.entries()) { - if (session.isRunning) active.push({ conversationId, session }); - } - - return active; - } - - getConfig(settings: SettingsConfigType): AgenticConfig { - const maxTurns = Number(settings.agenticMaxTurns) || DEFAULT_AGENTIC_CONFIG.maxTurns; - const hasTools = - mcpStore.hasEnabledServers() || - toolsStore.serverTools.length > 0 || - toolsStore.browserTools.length > 0 || - toolsStore.customTools.length > 0; - - return { - enabled: hasTools && DEFAULT_AGENTIC_CONFIG.enabled, - maxTurns - }; - } - - getCurrentTurn(conversationId: string): number { - return this.sessions.get(conversationId)?.currentTurn ?? 0; - } - - getExecutingToolCallId(conversationId: string): string | null { - return this.sessions.get(conversationId)?.executingToolCallId ?? null; - } - - // read-only: safe to call from derivations, unlike getSession - getFlowRootMessageId(conversationId: string): string | null { - return this.sessions.get(conversationId)?.flowRootMessageId ?? null; - } - - getLastError(conversationId: string): Error | null { - return this.sessions.get(conversationId)?.lastError ?? null; - } - - // read-only: safe to call from derivations, unlike getSession - getLiveLlmTotals(conversationId: string): AgenticSession['liveLlm'] { - return this.sessions.get(conversationId)?.liveLlm ?? null; - } - - getPendingContinueRequest(conversationId: string): boolean { - return this.gates.getPendingContinueRequest(conversationId); - } - - getPendingPermissionRequest( - conversationId: string - ): { toolName: string; serverLabel: string } | null { - return this.gates.getPendingPermissionRequest(conversationId); - } - - getPendingSteeringMessageContent(conversationId: string): string | null { - return this.gates.getPendingSteeringMessageContent(conversationId); - } - - getPendingSteeringMessageExtras(conversationId: string): DatabaseMessageExtra[] | undefined { - return this.gates.getPendingSteeringMessageExtras(conversationId); - } - - getSession(conversationId: string): AgenticSession { - let session = this.sessions.get(conversationId); - - if (!session) { - session = createDefaultSession(); - this.sessions.set(conversationId, session); - } - - return session; - } - - getStreamingToolCall(conversationId: string): { name: string; arguments: string } | null { - return this.sessions.get(conversationId)?.streamingToolCall ?? null; - } - - getTotalToolCalls(conversationId: string): number { - return this.sessions.get(conversationId)?.totalToolCalls ?? 0; - } - - hasPendingSteeringMessage(conversationId: string): boolean { - return this.gates.hasPendingSteeringMessage(conversationId); - } - - /** - * Queue a steering message. When the current agentic turn completes, - * the flow exits and the caller re-sends the message as a normal chat message. - */ - injectSteeringMessage( - conversationId: string, - content: string, - extras?: DatabaseMessageExtra[] - ): void { - this.gates.injectSteeringMessage(conversationId, content, extras); - } - - isRunning(conversationId: string): boolean { - return this.sessions.get(conversationId)?.isRunning ?? false; - } - - /** - * What a request of the chat sends under this tool policy: its messages - * as the agentic flow shapes them, and the tools it offers, none when the - * flow does not run. A request built from it shares the prefix the server - * cached for the conversation. - */ - async requestFor( - messages: ApiChatMessageData[], - toolPolicy?: AgenticToolPolicy - ): Promise<{ messages: ApiChatMessageData[]; tools: OpenAIToolDefinition[] }> { - const tools = await this.toolsFor(toolPolicy); - - return { - messages: tools.length > 0 ? (toAgenticMessages(messages) as ApiChatMessageData[]) : messages, - tools - }; - } - - resolveContinue(conversationId: string, shouldContinue: boolean): void { - this.gates.resolveContinue(conversationId, shouldContinue); - } - - resolvePermission(conversationId: string, decision: ToolPermissionDecision): void { - this.gates.resolvePermission(conversationId, decision); - } - - async runAgenticFlow(params: AgenticFlowParams): Promise { - const { - callbacks, - conversationId, - flowRootMessageId, - messages, - options = {}, - signal, - toolPolicy - } = params; - - // Clear any pending permissions/continue requests for this conversation when starting a new flow - this.gates.clear(conversationId); - - const agenticConfig = this.getConfig(settingsStore.config); - const tools = await this.toolsFor(toolPolicy); - - if (tools.length === 0) { - return { handled: false }; - } - - const hasMcpServers = conversationsStore.preferences.policyEnabledServerIds().length > 0; - - console.log(`[AgenticStore] Starting agentic flow with ${tools.length} tools`); - - const normalizedMessages: ApiChatMessageData[] = - await ChatService.normalizeMessagesForApi(messages); - - this.updateSession(conversationId, { - currentTurn: 0, - flowRootMessageId: flowRootMessageId ?? null, - isRunning: true, - lastError: null, - liveLlm: null, - totalToolCalls: 0 - }); - - if (hasMcpServers) mcpStore.acquireConnection(); - - try { - await this.executeAgenticLoop({ - agenticConfig, - callbacks, - conversationId, - messages: normalizedMessages, - options, - signal, - tools - }); - - return { handled: true }; - } catch (error) { - const normalizedError = error instanceof Error ? error : new Error(String(error)); - - this.updateSession(conversationId, { lastError: normalizedError }); - callbacks.onError?.(normalizedError); - - return { error: normalizedError, handled: true }; - } finally { - this.updateSession(conversationId, { - flowRootMessageId: null, - isRunning: false, - liveLlm: null - }); - - if (hasMcpServers) { - await mcpStore - .releaseConnection() - .catch((err: unknown) => - console.warn('[AgenticStore] Failed to release MCP connection:', err) - ); - } - } - } - - private buildAttachmentName(mimeType: string, index: number): string { - const extension = mimeType.startsWith(MimeTypePrefix.AUDIO) - ? (AUDIO_MIME_TO_EXTENSION[mimeType] ?? DEFAULT_AUDIO_EXTENSION) - : (IMAGE_MIME_TO_EXTENSION[mimeType] ?? DEFAULT_IMAGE_EXTENSION); - - return `${MCP_ATTACHMENT_NAME_PREFIX}-${Date.now()}-${index}.${extension}`; - } - - private buildFinalTimings( - capturedTimings: ChatMessageTimings | undefined, - agenticTimings: ChatMessageAgenticTimings - ): ChatMessageTimings | undefined { - if (agenticTimings.toolCallsCount === 0) return capturedTimings; - - return { - agentic: agenticTimings, - cache_n: capturedTimings?.cache_n, - predicted_ms: capturedTimings?.predicted_ms, - predicted_n: capturedTimings?.predicted_n, - prompt_ms: capturedTimings?.prompt_ms, - prompt_n: capturedTimings?.prompt_n - }; - } - - private async executeAgenticLoop(params: { - conversationId: string; - messages: ApiChatMessageData[]; - options: AgenticFlowOptions; - tools: ReturnType; - agenticConfig: AgenticConfig; - callbacks: AgenticFlowCallbacks; - signal?: AbortSignal; - }): Promise { - const { agenticConfig, callbacks, conversationId, messages, options, signal, tools } = params; - const { - createAssistantMessage, - createToolResultMessage, - onAssistantTurnComplete, - onAttachments, - onChunk, - onCompletionId, - onFlowComplete, - onModel, - onReasoningChunk, - onTimings, - onToolCallsStreaming, - onTurnComplete, - updateToolResultMessage - } = callbacks; - const sessionMessages: AgenticMessage[] = toAgenticMessages(messages); - - let capturedTimings: ChatMessageTimings | undefined; - let totalToolCallCount = 0; - - const agenticTimings: ChatMessageAgenticTimings = { - llm: { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 }, - perTurn: [], - toolCalls: [], - toolCallsCount: 0, - toolsMs: 0, - turns: 0 - }; - const maxTurns = agenticConfig.maxTurns; - const effectiveModel = options.model || modelsStore.models[0]?.model || ''; - - let turn = 0; - - while (true) { - if (turn >= maxTurns) { - // Turn limit reached - ask user whether to continue - const shouldContinue = await this.gates.requestContinue(conversationId, signal); - - // Yield to allow Svelte to flush the UI update - await new Promise((r) => setTimeout(r, 0)); - - if (!shouldContinue || signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // User chose to continue - extend the limit - turn = 0; - } - - this.updateSession(conversationId, { currentTurn: turn + 1 }); - agenticTimings.turns = turn + 1; - - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // For turns > 0, create a new assistant message via callback - if (turn > 0 && createAssistantMessage) { - await createAssistantMessage(); - } - - let turnContent = ''; - let turnReasoningContent = ''; - let turnToolCalls: ApiChatCompletionToolCall[] = []; - let lastStreamingToolCallName = ''; - let lastStreamingToolCallArgsLength = 0; - let turnTimings: ChatMessageTimings | undefined; - - const turnStats: ChatMessageAgenticTurnStats = { - llm: { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 }, - toolCalls: [], - toolsMs: 0, - turn: turn + 1 - }; - - try { - await ChatService.sendMessage( - sessionMessages as ApiChatMessageData[], - { - ...options, - onChunk: (chunk: string) => { - turnContent += chunk; - onChunk?.(chunk); - }, - onComplete: () => { - /* Completion handled after sendMessage resolves */ - }, - onCompletionId, - onError: (error: Error) => { - throw error; - }, - onModel, - onReasoningChunk: (chunk: string) => { - turnReasoningContent += chunk; - onReasoningChunk?.(chunk); - }, - onTimings: (timings?: ChatMessageTimings, progress?: ChatMessagePromptProgress) => { - onTimings?.(timings, progress); - - if (timings) { - capturedTimings = timings; - turnTimings = timings; - - // completed turns + in-flight turn live counts - this.updateSession(conversationId, { - liveLlm: { - predicted_ms: agenticTimings.llm.predicted_ms + (timings.predicted_ms ?? 0), - predicted_n: agenticTimings.llm.predicted_n + (timings.predicted_n ?? 0), - prompt_ms: agenticTimings.llm.prompt_ms + (timings.prompt_ms ?? 0), - prompt_n: agenticTimings.llm.prompt_n + (timings.prompt_n ?? 0) - } - }); - } - }, - onToolCallChunk: (serialized: string) => { - try { - turnToolCalls = JSON.parse(serialized) as ApiChatCompletionToolCall[]; - - onToolCallsStreaming?.(turnToolCalls); - - if (turnToolCalls.length > 0 && turnToolCalls[0]?.function) { - const name = turnToolCalls[0].function.name || ''; - const args = turnToolCalls[0].function.arguments || ''; - const argsLengthBucket = Math.floor(args.length / 100); - - if ( - name !== lastStreamingToolCallName || - argsLengthBucket !== lastStreamingToolCallArgsLength - ) { - lastStreamingToolCallName = name; - lastStreamingToolCallArgsLength = argsLengthBucket; - this.updateSession(conversationId, { - streamingToolCall: { arguments: args, name } - }); - } - } - } catch { - /* Ignore parse errors during streaming */ - } - }, - stream: true, - tools: tools.length > 0 ? tools : undefined - }, - conversationId, - signal - ); - - this.updateSession(conversationId, { streamingToolCall: null }); - - if (turnTimings) { - agenticTimings.llm.predicted_n += turnTimings.predicted_n || 0; - agenticTimings.llm.predicted_ms += turnTimings.predicted_ms || 0; - agenticTimings.llm.prompt_n += turnTimings.prompt_n || 0; - agenticTimings.llm.prompt_ms += turnTimings.prompt_ms || 0; - turnStats.llm.predicted_n = turnTimings.predicted_n || 0; - turnStats.llm.predicted_ms = turnTimings.predicted_ms || 0; - turnStats.llm.prompt_n = turnTimings.prompt_n || 0; - turnStats.llm.prompt_ms = turnTimings.prompt_ms || 0; - } - } catch (error) { - if (signal?.aborted) { - // Save whatever we have for this turn before exiting - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - const normalizedError = error instanceof Error ? error : new Error('LLM stream error'); - - // preserve partial output as is, the outer error dialog informs the user separately - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - throw normalizedError; - } - - // If the abort landed while ChatService.sendMessage was still resolving, the - // outer catch above never fires because ChatService swallows the AbortError - // and returns normally. Bail out here so a half-received tool_call (truncated - // arguments JSON) is not persisted as if it were complete. - if (signal?.aborted) { - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // === Steering check: if a user message was queued during this turn, exit the flow. - // The caller (chatStore) will consume the pending message and re-send it normally. - if (this.gates.hasPendingSteeringMessage(conversationId)) { - console.log('[AgenticStore] Steering message detected after turn, exiting agentic flow'); - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - turnToolCalls.length > 0 ? this.normalizeToolCalls(turnToolCalls) : undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // No tool calls = final turn, save and complete - if (turnToolCalls.length === 0) { - agenticTimings.perTurn!.push(turnStats); - - const finalTimings = this.buildFinalTimings(capturedTimings, agenticTimings); - - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - finalTimings, - undefined - ); - - if (finalTimings) onTurnComplete?.(finalTimings); - - onFlowComplete?.(finalTimings); - - return; - } - - // Normalize and save assistant turn with tool calls - const normalizedCalls = this.normalizeToolCalls(turnToolCalls); - - if (normalizedCalls.length === 0) { - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - totalToolCallCount += normalizedCalls.length; - this.updateSession(conversationId, { totalToolCalls: totalToolCallCount }); - - // Save the assistant message with its tool calls - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - turnTimings, - normalizedCalls - ); - - // Add assistant message to session history - sessionMessages.push({ - content: turnContent || undefined, - reasoning_content: turnReasoningContent || undefined, - role: MessageRole.ASSISTANT, - tool_calls: normalizedCalls - }); - - // Execute each tool call and create result messages - for (let i = 0; i < normalizedCalls.length; i++) { - const toolCall = normalizedCalls[i]; - - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // Check for pending steering message - skip remaining tool calls - if (this.gates.hasPendingSteeringMessage(conversationId)) { - console.log( - `[AgenticStore] Steering message detected, skipping ${normalizedCalls.length - i} remaining tool call(s)` - ); - for (let j = i; j < normalizedCalls.length; j++) { - const remainingCall = normalizedCalls[j]; - const interruptedContent = 'Tool execution was interrupted by a new user message.'; - - if (createToolResultMessage) { - await createToolResultMessage(remainingCall.id, interruptedContent); - } - - sessionMessages.push({ - content: interruptedContent, - role: MessageRole.TOOL, - tool_call_id: remainingCall.id - }); - } - - break; - } - - const toolName = toolCall.function.name; - const serverLabel = toolsStore.getToolServerLabel(toolName); - // Ask for permission before executing the tool - const permission = await this.gates.requestPermission( - conversationId, - toolName, - serverLabel, - signal - ); - - // Yield to allow Svelte to flush the UI update (hide permission dialog) - await new Promise((r) => setTimeout(r, 0)); - - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - const toolStartTime = performance.now(); - const toolSource = toolsStore.getToolSource(toolName); - - let result = ''; - let toolSuccess = true; - let createdToolResultMessageId: string | null = null; - - // Streaming tools (currently only exec_shell_command): mark - // the session so the matching renderer can switch to live mode. - // Cleared unconditionally below. - this.updateSession(conversationId, { executingToolCallId: toolCall.id }); - - if (permission === ToolPermissionDecision.DENY) { - result = 'Tool execution was denied by the user.'; - toolSuccess = false; - } else { - try { - if ( - toolSource === ToolSource.SERVER && - toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND && - createToolResultMessage && - updateToolResultMessage - ) { - const args = this.parseToolArguments(toolCall.function.arguments); - const cwd = conversationsStore.activeConversation?.cwd; - const msg = await createToolResultMessage(toolCall.id, '', undefined, cwd); - - createdToolResultMessageId = msg.id; - - let accumulated = ''; - - for await (const ev of ToolsService.streamTool(toolName, args, signal, cwd)) { - if (ev.chunk !== null) { - accumulated += ev.chunk; - await updateToolResultMessage(msg.id, accumulated); - } - - if (ev.done) { - if (ev.error) { - accumulated = accumulated - ? `${accumulated}\nError: ${ev.error}` - : `Error: ${ev.error}`; - await updateToolResultMessage(msg.id, accumulated); - toolSuccess = false; - } - - break; - } - } - result = accumulated; - } else if (toolSource === ToolSource.SERVER) { - const args = this.parseToolArguments(toolCall.function.arguments); - const cwd = conversationsStore.activeConversation?.cwd; - const executionResult = await ToolsService.executeTool(toolName, args, signal, cwd); - - result = executionResult.content; - - if (executionResult.isError) toolSuccess = false; - } else if (toolSource === ToolSource.BROWSER) { - const args = this.parseToolArguments(toolCall.function.arguments); - - let executionResult: ToolExecutionResult; - - if (toolName === BuiltInTool.BROWSER_GET_DATETIME) { - executionResult = executeGetDatetimeTool(); - } else if (toolName === BuiltInTool.SERVER_GET_INFO) { - executionResult = executeBrowserInfoTool(); - } else if (toolName === BuiltInTool.BROWSER_SEARCH_CHATS) { - executionResult = await SearchChatsService.executeTool(args, conversationId); - } else if (toolName === BuiltInTool.BROWSER_READ_MEDIA) { - executionResult = await ReadMediaService.executeTool( - args, - { - audio: modelsStore.props.modelSupportsAudio(effectiveModel), - vision: modelsStore.props.modelSupportsVision(effectiveModel) - }, - signal, - conversationsStore.activeConversation?.cwd - ); - } else { - executionResult = await SandboxService.executeTool(toolName, args, signal); - } - - result = executionResult.content; - - if (executionResult.isError) toolSuccess = false; - } else { - const mcpCall: MCPToolCall = { - function: { arguments: toolCall.function.arguments, name: toolName }, - id: toolCall.id - }; - const executionResult = await mcpStore.executeTool(mcpCall, signal); - - result = executionResult.content; - } - } catch (error) { - if (isAbortError(error)) { - this.updateSession(conversationId, { executingToolCallId: null }); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // Carry the partial stream contents already mirrored to the UI - - // they show up as live output even if the stream broke off mid-run. - result = result - ? `${result}\nError: ${error instanceof Error ? error.message : String(error)}` - : `Error: ${error instanceof Error ? error.message : String(error)}`; - toolSuccess = false; - - if (createdToolResultMessageId && updateToolResultMessage) { - await updateToolResultMessage(createdToolResultMessageId, result); - } - } - } - - this.updateSession(conversationId, { executingToolCallId: null }); - - const toolDurationMs = performance.now() - toolStartTime; - const toolTiming: ChatMessageToolCallTiming = { - duration_ms: Math.round(toolDurationMs), - name: toolCall.function.name, - success: toolSuccess - }; - - agenticTimings.toolCalls!.push(toolTiming); - agenticTimings.toolCallsCount++; - agenticTimings.toolsMs += Math.round(toolDurationMs); - turnStats.toolCalls.push(toolTiming); - turnStats.toolsMs += Math.round(toolDurationMs); - - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - const { attachments, cleanedResult } = this.extractBase64Attachments(result); - - // For streaming tools the result message was created empty - // at the start of execution and updated in place as chunks - // arrived via updateToolResultMessage. Skip the second - // create call - just attach any base64 attachments found in - // the final accumulator (rare, since chunks usually don't - // carry image data URIs) and emit the attachments callback. - let toolResultMessage: DatabaseMessage | undefined; - - if (createdToolResultMessageId) { - toolResultMessage = { id: createdToolResultMessageId } as DatabaseMessage; - - if (attachments.length > 0 && updateToolResultMessage) { - await updateToolResultMessage(createdToolResultMessageId, cleanedResult, attachments); - } - } else if (createToolResultMessage) { - toolResultMessage = await createToolResultMessage( - toolCall.id, - cleanedResult, - attachments.length > 0 ? attachments : undefined - ); - } - - if (attachments.length > 0 && toolResultMessage) { - onAttachments?.(toolResultMessage.id, attachments); - } - - // Build content parts for session history (including images for vision models) - const contentParts: ApiChatMessageContentPart[] = [ - { text: cleanedResult, type: ContentPartType.TEXT } - ]; - - for (const attachment of attachments) { - if (attachment.type === AttachmentType.AUDIO) { - if (modelsStore.props.modelSupportsAudio(effectiveModel)) { - contentParts.push({ - input_audio: { - data: (attachment as DatabaseMessageExtraAudioFile).base64Data, - format: getAudioInputFormat( - (attachment as DatabaseMessageExtraAudioFile).mimeType - ) - }, - type: ContentPartType.INPUT_AUDIO - }); - } - } else if (attachment.type === AttachmentType.IMAGE) { - if (modelsStore.props.modelSupportsVision(effectiveModel)) { - contentParts.push({ - image_url: { - url: (attachment as DatabaseMessageExtraImageFile).base64Url - }, - type: ContentPartType.IMAGE_URL - }); - } else { - console.info( - `[AgenticStore] Skipping image attachment (model "${effectiveModel}" does not support vision)` - ); - } - } - } - - sessionMessages.push({ - content: contentParts.length === 1 ? cleanedResult : contentParts, - role: MessageRole.TOOL, - tool_call_id: toolCall.id - }); - } - - if (turnStats.toolCalls.length > 0) { - agenticTimings.perTurn!.push(turnStats); - - const intermediateTimings = this.buildFinalTimings(capturedTimings, agenticTimings); - - if (intermediateTimings) onTurnComplete?.(intermediateTimings); - } - - // If tools were interrupted by a steering message, exit now instead of starting another LLM turn - if (this.gates.hasPendingSteeringMessage(conversationId)) { - console.log( - '[AgenticStore] Steering message detected after tool execution, exiting agentic flow' - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - turn++; - } - } - - private extractBase64Attachments(result: string): { - cleanedResult: string; - attachments: DatabaseMessageExtra[]; - } { - if (!result.trim()) { - return { attachments: [], cleanedResult: result }; - } - - const lines = result.split(NEWLINE); - const attachments: DatabaseMessageExtra[] = []; - - let attachmentIndex = 0; - - const cleanedLines = lines.map((line) => { - const trimmedLine = line.trim(); - const match = trimmedLine.match(DATA_URI_BASE64_REGEX); - - if (!match) { - return line; - } - - const mimeType = match[1].toLowerCase(); - const base64Data = match[2]; - - if (!base64Data) { - return line; - } - - attachmentIndex += 1; - const name = this.buildAttachmentName(mimeType, attachmentIndex); - - if (mimeType.startsWith(MIME_TYPE_PREFIXES.IMAGE)) { - attachments.push({ base64Url: trimmedLine, name, type: AttachmentType.IMAGE }); - - return `[Attachment saved: ${name}]`; - } - - if (mimeType.startsWith(MimeTypePrefix.AUDIO)) { - // audio extras hold the bare base64, the input_audio part has no room for a data URI - attachments.push({ - base64Data, - mimeType, - name, - type: AttachmentType.AUDIO - }); - - return `[Attachment saved: ${name}]`; - } - - return line; - }); - - return { attachments, cleanedResult: cleanedLines.join(NEWLINE) }; - } - - private normalizeToolCalls(toolCalls: ApiChatCompletionToolCall[]): AgenticToolCallList { - if (!toolCalls) return []; - - return toolCalls.map((call, index) => ({ - function: { - arguments: call?.function?.arguments ?? '', - name: call?.function?.name ?? '' - }, - id: call?.id ?? `tool_${index}`, - type: (call?.type as ToolCallType.FUNCTION) ?? ToolCallType.FUNCTION - })); - } - - private parseToolArguments(args: string | Record): Record { - if (typeof args === 'object') return args; - - const trimmed = args.trim(); - - if (trimmed === '') return {}; - - return JSON.parse(trimmed) as Record; - } - - /** - * The tools a flow under this policy offers the model, none when agentic - * is off. Server tools are fetched first: a disabled /tools endpoint stays - * disabled for the life of the server, so the tools panel is the only - * place that probes it again. Every settings-enabled MCP server is - * initialized, and the collection filters by the policy, so switching - * policies never re-initializes connections; a caller without a policy - * falls back to the global defaults. - */ - private async toolsFor(toolPolicy?: AgenticToolPolicy): Promise { - if ( - toolsStore.serverTools.length === 0 && - !toolsStore.loading && - !toolsStore.isToolsEndpointUnreachable - ) { - await toolsStore.fetchServerTools(); - } - - if (!this.getConfig(settingsStore.config).enabled) return []; - - const disabledTools = new Set(toolPolicy?.disabledTools ?? toolsStore.disabledTools); - const disabledToolCategories = new Set( - toolPolicy?.disabledToolCategories ?? toolsStore.disabledToolCategories - ); - - if (conversationsStore.preferences.policyEnabledServerIds().length > 0) { - const initialized = await mcpStore.ensureInitialized(); - - if (!initialized) { - console.log('[AgenticStore] MCP not initialized'); - } - } - - return toolsStore.getEnabledToolsForLLM(disabledTools, disabledToolCategories); - } - - private updateSession(conversationId: string, update: Partial): void { - const session = this.getSession(conversationId); - - this.sessions.set(conversationId, { ...session, ...update }); - } -} - -export const agenticStore = new AgenticStore(); diff --git a/tools/ui/src/lib/stores/chat/index.svelte.ts b/tools/ui/src/lib/stores/chat/index.svelte.ts deleted file mode 100644 index ec20ecd34b06..000000000000 --- a/tools/ui/src/lib/stores/chat/index.svelte.ts +++ /dev/null @@ -1,1846 +0,0 @@ -/** - * chatStore - Chat lifecycle, streaming and message operations - * - * Owns the active conversation's chat state: sending messages, streaming - * responses, editing/regeneration flows and per-conversation processing - * activity. Composes the stream manager, message flows, activity ledger and - * processing snapshot; persists through conversationsStore. - * - * Uses ChatService for the API layer and conversationsStore for persistence. - */ - -import { - COMPACTION, - CWD_CLEARED_TEXT, - REASONING_EFFORT_TOKENS, - SYSTEM_MESSAGE_PLACEHOLDER, - TITLE_GENERATION -} from '$lib/constants'; -import { - ErrorDialogType, - MessageRole, - MessageType, - ReasoningEffort, - StreamConnectionState -} from '$lib/enums'; -import { ChatService } from '$lib/services/chat.service'; -import { DatabaseService } from '$lib/services/database.service'; -// direct imports between stores, not via the barrel, to avoid circular deps -import { agenticStore } from '$lib/stores/agentic/index.svelte'; -import { chatActivityStore } from '$lib/stores/chat/activity.svelte'; -import { type ChatFlowsHost, ChatMessageFlows } from '$lib/stores/chat/flows.svelte'; -import { chatProcessingStore } from '$lib/stores/chat/processing.svelte'; -import { type ChatStreamHost, ChatStreamManager } from '$lib/stores/chat/streams.svelte'; -import { conversationsStore } from '$lib/stores/conversations/index.svelte'; -import { mcpStore } from '$lib/stores/mcp/index.svelte'; -import { modelsStore } from '$lib/stores/models/index.svelte'; -import { serverStore } from '$lib/stores/server.svelte'; -import { settingsStore } from '$lib/stores/settings/index.svelte'; -import { toolsStore } from '$lib/stores/tools.svelte'; -import type { - ApiChatMessageData, - ChatMessageCompactionTimings, - ChatMessagePromptProgress, - ChatMessageTimings, - ChatStreamCallbacks, - DatabaseMessage, - DatabaseMessageExtra, - ErrorDialogState -} from '$lib/types'; -import type { AgenticToolPolicy } from '$lib/types/agentic'; -import { - canCompactMessages, - compactionCut, - filterByLeafNodeId, - findMessageById, - formatCwdMessage, - getConversationModel, - isAbortError, - normalizeModelName, - sliceAtLastCompaction -} from '$lib/utils'; -import { SvelteMap } from 'svelte/reactivity'; - -class ChatStore implements ChatStreamHost, ChatFlowsHost { - chatReasoningStates = new SvelteMap(); - chatStreamingStates = new SvelteMap< - string, - { response: string; messageId: string; model?: string | null } - >(); - errorDialogState = $state(null); - // true while the active conversation has a local pipe (send, attach or resume-wait) - isLoading = $derived(this.activity.isLocal(conversationsStore.activeConversation?.id ?? '')); - // true while the active conversation streams reasoning content but no visible content yet - isReasoning = $derived( - this.chatReasoningStates.get(conversationsStore.activeConversation?.id ?? '') ?? false - ); - pendingEditMessageId = $state(null); - // resumable stream connection state for the active conversation - // streaming -> bytes flowing normally, resuming -> waiting on /v1/stream reconnect, lost -> unrecoverable - streamConnectionState = $state(StreamConnectionState.STREAMING); - private abortControllers = new SvelteMap(); - private addFilesHandler: ((files: File[]) => void) | null = $state(null); - // message flows: edit, regenerate, continue, delete - private flows = new ChatMessageFlows(this); - private isEditModeActive = $state(false); - /** Reactive: queued pending messages for non-agentic streaming */ - private pendingMessages = new SvelteMap< - string, - { content: string; extras?: DatabaseMessageExtra[] } - >(); - private preEncodeAbortController: AbortController | null = null; - - // server-side stream sessions: discovery, attach/replay, resume retry, remote sync - private streams = new ChatStreamManager(this); - - /** Conv activity (local pipe / remote session), composed here. */ - get activity() { - return chatActivityStore; - } - - /** Processing state, composed here so consumers have a single chat scope. */ - get processing() { - return chatProcessingStore; - } - - /** - * Abort the current agentic flow signal without clearing loading state. - * Used by "Send immediately" to force the agentic loop to exit so that - * the pending steering message can be re-sent. - * - * Any tool calls captured mid-stream are dropped before the abort so the - * pending message (or a manual follow-up) does not re-send a half-received - * tool call with invalid JSON arguments to the server. Mirrors what the - * Stop button already does through stopGenerationForChat. - */ - async abortCurrentFlow(convId: string): Promise { - await this.savePartialResponseIfNeeded(convId); - const c = this.abortControllers.get(convId); - - if (c) { - c.abort(); - this.abortControllers.delete(convId); - } - } - - async addMessage( - role: MessageRole, - content: string, - type: MessageType = MessageType.TEXT, - parent: string = '-1', - extras?: DatabaseMessageExtra[], - isSynthetic?: boolean - ): Promise { - const activeConv = conversationsStore.activeConversation; - - if (!activeConv) throw new Error('No active conversation'); - - let parentId: string | null = null; - - if (parent === '-1') { - const am = conversationsStore.activeMessages; - - if (am.length > 0) parentId = am[am.length - 1].id; - else { - const all = await conversationsStore.getConversationMessages(activeConv.id); - const r = all.find((m) => m.parent === null && m.type === 'root'); - - parentId = r ? r.id : await DatabaseService.createRootMessage(activeConv.id); - } - } else parentId = parent; - - const message = await DatabaseService.createMessageBranch( - { - children: [], - content, - convId: activeConv.id, - extra: extras, - isSynthetic, - role, - timestamp: Date.now(), - toolCalls: '', - type - }, - parentId - ); - - conversationsStore.addMessageToActive(message); - await conversationsStore.updateCurrentNode(message.id); - conversationsStore.updateConversationTimestamp(); - - return message; - } - async addSystemPrompt(draft?: { message: string; files: ChatUploadedFile[] }): Promise { - let activeConv = conversationsStore.activeConversation; - - if (!activeConv) { - await conversationsStore.createConversation(undefined, draft); - activeConv = conversationsStore.activeConversation; - } - - if (!activeConv) return; - - try { - const allMessages = await conversationsStore.getConversationMessages(activeConv.id); - const rootMessage = allMessages.find((m) => m.type === 'root' && m.parent === null); - const rootId = rootMessage - ? rootMessage.id - : await DatabaseService.createRootMessage(activeConv.id); - const existingSystemMessage = allMessages.find( - (m) => m.role === MessageRole.SYSTEM && m.parent === rootId - ); - - if (existingSystemMessage) { - this.pendingEditMessageId = existingSystemMessage.id; - - if (!conversationsStore.activeMessages.some((m) => m.id === existingSystemMessage.id)) - conversationsStore.activeMessages.unshift(existingSystemMessage); - - return; - } - - const am = conversationsStore.activeMessages; - const firstActiveMessage = am.find((m) => m.parent === rootId); - const systemMessage = await DatabaseService.createSystemMessage( - activeConv.id, - SYSTEM_MESSAGE_PLACEHOLDER, - rootId - ); - - if (firstActiveMessage) { - await DatabaseService.updateMessage(firstActiveMessage.id, { - parent: systemMessage.id - }); - await DatabaseService.updateMessage(systemMessage.id, { - children: [firstActiveMessage.id] - }); - const updatedRootChildren = rootMessage - ? rootMessage.children.filter((id: string) => id !== firstActiveMessage.id) - : []; - - await DatabaseService.updateMessage(rootId, { - children: [ - ...updatedRootChildren.filter((id: string) => id !== systemMessage.id), - systemMessage.id - ] - }); - const firstMsgIndex = conversationsStore.findMessageIndex(firstActiveMessage.id); - - if (firstMsgIndex !== -1) - conversationsStore.updateMessageAtIndex(firstMsgIndex, { - parent: systemMessage.id - }); - } - - conversationsStore.activeMessages.unshift(systemMessage); - this.pendingEditMessageId = systemMessage.id; - conversationsStore.updateConversationTimestamp(); - } catch (error) { - console.error('Failed to add system prompt:', error); - } - } - cancelPreEncode(): void { - if (this.preEncodeAbortController) { - this.preEncodeAbortController.abort(); - this.preEncodeAbortController = null; - } - } - - /** - * Whether the branch holds a step to summarize before the steps a - * compaction preserves. - */ - canCompact(messages: DatabaseMessage[]): boolean { - return canCompactMessages(messages, this.compactionPreserve()); - } - - /** - * Resets the loading, streaming and processing state for a conversation - * after a generation ends or errors. Shared by the flows' exit paths. - */ - cleanupStreaming(convId: string): void { - this.setChatLoading(convId, false); - this.clearChatStreaming(convId); - this.processing.setState(convId, null); - } - clearChatStreaming(convId: string, messageId?: string): void { - // session aware: a stale generation must not wipe a newer one's streaming state on the - // same conversation, that would drop the frozen stop identity and stop the wrong session - if (messageId !== undefined) { - const cur = this.chatStreamingStates.get(convId); - - if (cur && cur.messageId !== messageId) return; - } - - this.chatStreamingStates.delete(convId); - } - clearEditMode(): void { - this.isEditModeActive = false; - this.addFilesHandler = null; - } - - clearPendingEditMessageId(): void { - this.pendingEditMessageId = null; - } - - clearPendingMessage(convId: string): void { - this.pendingMessages.delete(convId); - } - - /** - * Compacts the active branch: the model summarizes every turn since the - * last compaction boundary and the summary is stored in a new compaction - * node appended to the branch. Later requests slice the branch at that - * node, so the full history stays visible and navigable while the model - * context restarts from the summary. - */ - async compactConversation(): Promise { - const activeConv = conversationsStore.activeConversation; - - if (!activeConv) return; - - const convId = activeConv.id; - - if (this.isChatLoadingInternal(convId) || agenticStore.isRunning(convId)) return; - - // Snapshot of the reactive branch: the compaction node created below - // must not leak into the summarization request. - const source = sliceAtLastCompaction([...conversationsStore.activeMessages]); - const preserve = this.compactionPreserve(); - const cut = compactionCut(source, preserve); - - if (cut === null) return; - - this.showErrorDialog(null); - this.setChatLoading(convId, true); - - const node = await this.addMessage( - MessageRole.USER, - '', - MessageType.COMPACTION, - '-1', - undefined, - true - ); - - // An interrupted compaction leaves no summary behind, so the node goes - // along with the request instead of lingering empty in the branch. - await this.summarizeIntoNode(convId, node, source, async () => { - const idx = conversationsStore.findMessageIndex(node.id); - - if (idx >= 0) conversationsStore.removeMessageAtIndex(idx); - - await DatabaseService.deleteMessage(node.id); - - if (node.parent) await conversationsStore.updateCurrentNode(node.parent); - }); - - const pending = this.consumePendingMessage(convId); - - if (pending) await this.sendQueuedMessage(convId, pending); - } - - consumePendingMessage( - convId: string - ): { content: string; extras?: DatabaseMessageExtra[] } | null { - const msg = this.pendingMessages.get(convId); - - if (!msg) return null; - - this.pendingMessages.delete(convId); - - return msg; - } - - async continueAssistantMessage(messageId: string): Promise { - return this.flows.continueAssistantMessage(messageId); - } - - async createAssistantMessage(parentId?: string): Promise { - const activeConv = conversationsStore.activeConversation; - - if (!activeConv) throw new Error('No active conversation'); - - return await DatabaseService.createMessageBranch( - { - children: [], - content: '', - convId: activeConv.id, - model: null, - role: MessageRole.ASSISTANT, - timestamp: Date.now(), - toolCalls: '', - type: MessageType.TEXT - }, - parentId || null - ); - } - - async deleteMessage(messageId: string): Promise { - return this.flows.deleteMessage(messageId); - } - - /** - * Server-side stream sessions (discovery, attach/replay, resume retry, - * remote-running snapshot) live in ChatStreamManager. - */ - async discoverActiveStream(convId: string): Promise { - return this.streams.discoverActiveStream(convId); - } - - dismissErrorDialog(): void { - this.errorDialogState = null; - } - - async editAssistantMessage( - messageId: string, - newContent: string, - shouldBranch: boolean - ): Promise { - return this.flows.editAssistantMessage(messageId, newContent, shouldBranch); - } - - async editMessageWithBranching( - messageId: string, - newContent: string, - newExtras?: DatabaseMessageExtra[] - ): Promise { - return this.flows.editMessageWithBranching(messageId, newContent, newExtras); - } - - async editUserMessagePreserveResponses( - messageId: string, - newContent: string, - newExtras?: DatabaseMessageExtra[] - ): Promise { - return this.flows.editUserMessagePreserveResponses(messageId, newContent, newExtras); - } - - /** - * Send the message left queued for `convId` once that conversation is - * active and idle (e.g. after navigating back to it). - */ - async flushPendingMessage(convId: string): Promise { - if (conversationsStore.activeConversation?.id !== convId) return; - - if (this.isChatLoadingInternal(convId) || agenticStore.isRunning(convId)) return; - - const pending = this.consumePendingMessage(convId); - - if (pending) await this.sendMessage(pending.content, pending.extras); - } - - getAddFilesHandler(): ((files: File[]) => void) | null { - return this.addFilesHandler; - } - - /** Convs with any activity (local pipe or remote session), sidebar spinners. */ - getAllLoadingChats(): string[] { - return this.activity.loadingConvs; - } - - getApiOptions(): Record { - const currentConfig = settingsStore.config; - const hasValue = (value: unknown): boolean => - value !== undefined && value !== null && value !== ''; - const apiOptions: Record = { stream: true, timings_per_token: true }; - - if (serverStore.isRouterMode) { - const modelName = modelsStore.selectedModelName; - - if (modelName) apiOptions.model = modelName; - } - - if (currentConfig.systemMessage) apiOptions.systemMessage = currentConfig.systemMessage; - - if (currentConfig.disableReasoningParsing) apiOptions.disableReasoningParsing = true; - - if (currentConfig.excludeReasoningFromContext) apiOptions.excludeReasoningFromContext = true; - - // an explicit reasoning choice overrides the server default, DEFAULT sends nothing: - // a level the chat template honors goes as is, the others as a token budget - const modelId = modelsStore.selectedModelName ?? ''; - const effort = modelsStore.props.resolveReasoningEffort( - modelId, - conversationsStore.preferences.getReasoningEffort() - ); - const budgetTokens = REASONING_EFFORT_TOKENS[effort]; - - if (effort !== ReasoningEffort.DEFAULT) { - apiOptions.enableThinking = effort !== ReasoningEffort.OFF; - } - - if (modelsStore.props.getReasoningEfforts(modelId).includes(effort)) { - apiOptions.reasoningEffort = effort; - } else if (budgetTokens >= 0) { - apiOptions.thinkingBudgetTokens = budgetTokens; - } - - if (hasValue(currentConfig.temperature)) - apiOptions.temperature = Number(currentConfig.temperature); - - if (hasValue(currentConfig.max_tokens)) - apiOptions.max_tokens = Number(currentConfig.max_tokens); - - if (hasValue(currentConfig.dynatemp_range)) - apiOptions.dynatemp_range = Number(currentConfig.dynatemp_range); - - if (hasValue(currentConfig.dynatemp_exponent)) - apiOptions.dynatemp_exponent = Number(currentConfig.dynatemp_exponent); - - if (hasValue(currentConfig.top_k)) apiOptions.top_k = Number(currentConfig.top_k); - - if (hasValue(currentConfig.top_p)) apiOptions.top_p = Number(currentConfig.top_p); - - if (hasValue(currentConfig.min_p)) apiOptions.min_p = Number(currentConfig.min_p); - - if (hasValue(currentConfig.xtc_probability)) - apiOptions.xtc_probability = Number(currentConfig.xtc_probability); - - if (hasValue(currentConfig.xtc_threshold)) - apiOptions.xtc_threshold = Number(currentConfig.xtc_threshold); - - if (hasValue(currentConfig.typ_p)) apiOptions.typ_p = Number(currentConfig.typ_p); - - if (hasValue(currentConfig.repeat_last_n)) - apiOptions.repeat_last_n = Number(currentConfig.repeat_last_n); - - if (hasValue(currentConfig.repeat_penalty)) - apiOptions.repeat_penalty = Number(currentConfig.repeat_penalty); - - if (hasValue(currentConfig.presence_penalty)) - apiOptions.presence_penalty = Number(currentConfig.presence_penalty); - - if (hasValue(currentConfig.frequency_penalty)) - apiOptions.frequency_penalty = Number(currentConfig.frequency_penalty); - - if (hasValue(currentConfig.dry_multiplier)) - apiOptions.dry_multiplier = Number(currentConfig.dry_multiplier); - - if (hasValue(currentConfig.dry_base)) apiOptions.dry_base = Number(currentConfig.dry_base); - - if (hasValue(currentConfig.dry_allowed_length)) - apiOptions.dry_allowed_length = Number(currentConfig.dry_allowed_length); - - if (hasValue(currentConfig.dry_penalty_last_n)) - apiOptions.dry_penalty_last_n = Number(currentConfig.dry_penalty_last_n); - - if (currentConfig.samplers) apiOptions.samplers = currentConfig.samplers; - - if (hasValue(currentConfig.backend_sampling)) - apiOptions.backend_sampling = currentConfig.backend_sampling; - - if (currentConfig.customJson) apiOptions.custom = currentConfig.customJson; - - return apiOptions; - } - - getChatStreaming(convId: string): { response: string; messageId: string } | undefined { - return this.getChatStreamingState(convId); - } - - /** Node id of the summary running for the conv, or null when none runs. */ - getCompactingNodeId(convId: string): string | null { - return this.activity.getCompactingNodeId(convId); - } - - async getDeletionInfo(messageId: string): Promise<{ - totalCount: number; - userMessages: number; - assistantMessages: number; - messageTypes: string[]; - }> { - return this.flows.getDeletionInfo(messageId); - } - - getOrCreateAbortController(convId: string): AbortController { - let c = this.abortControllers.get(convId); - - if (!c || c.signal.aborted) { - c = new AbortController(); - this.abortControllers.set(convId, c); - } - - return c; - } - - getPendingMessageContent(convId: string): string | null { - return this.pendingMessages.get(convId)?.content ?? null; - } - - getPendingMessageExtras(convId: string): DatabaseMessageExtra[] | undefined { - return this.pendingMessages.get(convId)?.extras; - } - - getResumeModel(convId: string): string | null { - return this.streams.getResumeModel(convId); - } - - hasPendingMessage(convId: string): boolean { - return this.pendingMessages.has(convId); - } - - injectPendingMessage(convId: string, content: string, extras?: DatabaseMessageExtra[]): void { - this.pendingMessages.set(convId, { content, extras }); - } - - isChatLoading(convId: string): boolean { - return this.activity.isLocal(convId); - } - - isChatLoadingInternal(convId: string): boolean { - return this.activity.isLocal(convId) || this.chatStreamingStates.has(convId); - } - - /** - * True while the conv's in-flight run is a compaction summary, which reports - * its own progress on the compaction row. - */ - isCompacting(convId: string): boolean { - return this.activity.isCompacting(convId); - } - - isEditing(): boolean { - return this.isEditModeActive; - } - - /** True while the active conversation has a live streaming pipe. */ - isStreaming(): boolean { - return this.chatStreamingStates.has(conversationsStore.activeConversation?.id ?? ''); - } - - /** - * Record a working-directory change into chat history as a synthetic - * user message, so the model sees it on its next turn (the client - * sends the cwd itself via the x-tool-cwd header on tool calls). - * A plain user message is used because some chat templates reject - * tool messages without a preceding tool call. - */ - async recordCwdChange(cwd: string | null): Promise { - const content = cwd - ? formatCwdMessage(cwd, await toolsStore.resolveServerHome()) - : CWD_CLEARED_TEXT; - // Reuse the trailing cwd row when it is already the last message, so - // repeated picks update it in place instead of stacking another row. - const last = conversationsStore.activeMessages[conversationsStore.activeMessages.length - 1]; - - if (last && last.role === MessageRole.USER && last.isSynthetic === true) { - await DatabaseService.updateMessage(last.id, { content, isSynthetic: true }); - conversationsStore.updateMessageAtIndex(conversationsStore.activeMessages.length - 1, { - content, - isSynthetic: true - }); - - return; - } - - await this.addMessage(MessageRole.USER, content, MessageType.TEXT, '-1', undefined, true); - } - - /** - * Re-runs the summary of an existing compaction node in place. The node - * keeps its position in the branch, so the turns below it stay untouched - * while the summarized context is rewritten. - */ - async regenerateCompaction(messageId: string): Promise { - const activeConv = conversationsStore.activeConversation; - - if (!activeConv) return; - - const convId = activeConv.id; - - if (this.isChatLoadingInternal(convId) || agenticStore.isRunning(convId)) return; - - const allMessages = await conversationsStore.getConversationMessages(convId); - const node = findMessageById(allMessages, messageId); - - if (!node || node.type !== MessageType.COMPACTION) return; - - // The summary covers the branch above the node: walking the path up to - // its parent keeps the old summary from being folded into the new one. - const branchPath = node.parent ? [...filterByLeafNodeId(allMessages, node.parent, false)] : []; - const source = sliceAtLastCompaction(branchPath); - - if (!this.canCompact(source)) return; - - this.showErrorDialog(null); - this.setChatLoading(convId, true); - - const previous = { content: node.content, model: node.model }; - - await this.summarizeIntoNode(convId, node, source, async () => { - const idx = conversationsStore.findMessageIndex(node.id); - - if (idx >= 0) conversationsStore.updateMessageAtIndex(idx, previous); - - await DatabaseService.updateMessage(node.id, previous); - }); - } - - async regenerateMessage(messageId: string): Promise { - return this.flows.regenerateMessage(messageId); - } - - async regenerateMessageWithBranching(messageId: string, modelOverride?: string): Promise { - return this.flows.regenerateMessageWithBranching(messageId, modelOverride); - } - - async removeSystemPromptPlaceholder(messageId: string): Promise { - const activeConv = conversationsStore.activeConversation; - - if (!activeConv) return false; - - try { - const allMessages = await conversationsStore.getConversationMessages(activeConv.id); - const systemMessage = findMessageById(allMessages, messageId); - - if (!systemMessage || systemMessage.role !== MessageRole.SYSTEM) return false; - - const rootMessage = allMessages.find((m) => m.type === 'root' && m.parent === null); - - if (!rootMessage) return false; - - if (allMessages.length === 2 && systemMessage.children.length === 0) { - await conversationsStore.deleteConversation(activeConv.id); - - return true; - } - - for (const childId of systemMessage.children) { - await DatabaseService.updateMessage(childId, { parent: rootMessage.id }); - const childIndex = conversationsStore.findMessageIndex(childId); - - if (childIndex !== -1) - conversationsStore.updateMessageAtIndex(childIndex, { parent: rootMessage.id }); - } - await DatabaseService.updateMessage(rootMessage.id, { - children: [ - ...rootMessage.children.filter((id: string) => id !== messageId), - ...systemMessage.children - ] - }); - await DatabaseService.deleteMessage(messageId); - const systemIndex = conversationsStore.findMessageIndex(messageId); - - if (systemIndex !== -1) conversationsStore.activeMessages.splice(systemIndex, 1); - - conversationsStore.updateConversationTimestamp(); - - return false; - } catch (error) { - console.error('Failed to remove system prompt placeholder:', error); - - return false; - } - } - - async sendMessage(content: string, extras?: DatabaseMessageExtra[]): Promise { - if (!content.trim() && (!extras || extras.length === 0)) return; - - const activeConv = conversationsStore.activeConversation; - - // If agentic loop is running, inject as a steering message instead of starting a new flow - if (activeConv && agenticStore.isRunning(activeConv.id)) { - agenticStore.injectSteeringMessage(activeConv.id, content, extras); - - return; - } - - // If non-agentic streaming is active, queue as a pending message to send after completion - if (activeConv && this.isChatLoadingInternal(activeConv.id)) { - this.injectPendingMessage(activeConv.id, content, extras); - - return; - } - - // Cancel any in-flight pre-encode request - this.cancelPreEncode(); - - // Consume MCP resource attachments - converts them to extras and clears the live store - const resourceExtras = mcpStore.consumeResourceAttachmentsAsExtras(); - const allExtras = resourceExtras.length > 0 ? [...(extras || []), ...resourceExtras] : extras; - - let isNewConversation = false; - - if (!activeConv) { - await conversationsStore.createConversation(); - isNewConversation = true; - } - - const currentConv = conversationsStore.activeConversation; - - if (!currentConv) return; - - this.showErrorDialog(null); - this.setChatLoading(currentConv.id, true); - this.clearChatStreaming(currentConv.id); - try { - let parentIdForUserMessage: string | undefined; - - if (isNewConversation) { - const rootId = await DatabaseService.createRootMessage(currentConv.id); - const currentConfig = settingsStore.config; - const systemPrompt = currentConfig.systemMessage?.toString().trim(); - - let sysOrRootId = rootId; - - if (systemPrompt) { - const systemMessage = await DatabaseService.createSystemMessage( - currentConv.id, - systemPrompt, - rootId - ); - - conversationsStore.addMessageToActive(systemMessage); - sysOrRootId = systemMessage.id; - } - - // Reflect a working directory picked on the new-chat screen into - // chat history before the first user message, so the model sees - // it on its first turn. createConversation() has already threaded - // the pending pick onto the conversation. - if (currentConv.cwd) { - const cwdMessage = await this.addMessage( - MessageRole.USER, - formatCwdMessage(currentConv.cwd, await toolsStore.resolveServerHome()), - MessageType.TEXT, - sysOrRootId, - undefined, - true - ); - - parentIdForUserMessage = cwdMessage.id; - } else { - parentIdForUserMessage = sysOrRootId; - } - } - - const userMessage = await this.addMessage( - MessageRole.USER, - content, - MessageType.TEXT, - parentIdForUserMessage ?? '-1', - allExtras - ); - - if (isNewConversation && content) - await conversationsStore.applyTitleFromContent(currentConv.id, content); - - const assistantMessage = await this.createAssistantMessage(userMessage.id); - - conversationsStore.addMessageToActive(assistantMessage); - await this.streamChatCompletion( - conversationsStore.activeMessages.slice(0, -1), - assistantMessage, - undefined, - undefined, - undefined, - settingsStore.config.titleGenerationUseLLM && isNewConversation ? content : undefined - ); - } catch (error) { - if (isAbortError(error)) { - this.setChatLoading(currentConv.id, false); - - return; - } - - console.error('Failed to send message:', error); - this.setChatLoading(currentConv.id, false); - const dialogType = - error instanceof Error && error.name === 'TimeoutError' - ? ErrorDialogType.TIMEOUT - : ErrorDialogType.SERVER; - const contextInfo = ( - error as Error & { contextInfo?: { n_prompt_tokens: number; n_ctx: number } } - ).contextInfo; - - this.showErrorDialog({ - contextInfo, - message: error instanceof Error ? error.message : 'Unknown error', - type: dialogType - }); - } - } - setChatLoading(convId: string, loading: boolean): void { - if (loading) { - this.activity.markLocal(convId); - } else { - this.activity.localEnded(convId); - this.setChatReasoning(convId, false); - } - } - - setChatReasoning(convId: string, reasoning: boolean): void { - if (reasoning) this.chatReasoningStates.set(convId, true); - else this.chatReasoningStates.delete(convId); - } - - setChatStreaming( - convId: string, - response: string, - messageId: string, - model?: string | null - ): void { - this.chatStreamingStates.set(convId, { - messageId, - model: model ?? this.chatStreamingStates.get(convId)?.model, - response - }); - } - - setEditModeActive(handler: (files: File[]) => void): void { - this.isEditModeActive = true; - this.addFilesHandler = handler; - } - - showErrorDialog(state: ErrorDialogState | null): void { - this.errorDialogState = state; - } - - async stopGeneration(): Promise { - const activeConv = conversationsStore.activeConversation; - - if (!activeConv) return; - - await this.stopGenerationForChat(activeConv.id); - } - - async stopGenerationForChat(convId: string): Promise { - await this.savePartialResponseIfNeeded(convId); - // tell the server to stop the generation, not just drop the HTTP socket. without this the - // detached drain keeps producing tokens until eos or max_tokens. use the frozen identity - // captured when the session started, not the live dropdown - const streamStateForStop = this.chatStreamingStates.get(convId); - const modelForStop = streamStateForStop?.model ?? ChatService.getStreamState(convId)?.model; - - void ChatService.cancelServerStream(convId, modelForStop); - // an explicit stop leaves nothing to resume and kills a pending resume retry - ChatService.clearStreamState(convId); - this.streams.cancelResumeRetry(convId); - this.abortRequest(convId); - this.setChatLoading(convId, false); - this.clearChatStreaming(convId); - this.processing.setState(convId, null); - this.clearPendingMessage(convId); - } - - async streamChatCompletion( - allMessages: DatabaseMessage[], - assistantMessage: DatabaseMessage, - onComplete?: (content: string) => Promise, - onError?: (error: Error) => void, - modelOverride?: string | null, - firstUserMessageContent?: string - ): Promise { - // the ::model suffix in the stream identity is only for router mode, where it routes to the - // owning child. in single-model mode the identity stays the bare conv id so that attach, stop - // and reattach all agree, regardless of fresh send vs regenerate passing a resolved model - let effectiveModel: string | null | undefined = undefined; - - if (serverStore.isRouterMode) { - const conversationModel = getConversationModel(allMessages); - - effectiveModel = modelOverride || modelsStore.selectedModelName || conversationModel; - } - - // a router serves the props the request options read once the model is loaded, so the - // request waits for the load, and a stop during the wait aborts it - const abortController = this.getOrCreateAbortController(assistantMessage.convId); - - if (serverStore.isRouterMode && effectiveModel) { - await modelsStore.status.ensureLoaded(effectiveModel); - - if (abortController.signal.aborted) return; - - if (!modelsStore.props.getModelProps(effectiveModel)) - await modelsStore.props.fetchModelProps(effectiveModel); - } - - // Every request path funnels through here, so the compaction boundary - // applied once covers the plain send, the agentic flow, and the - // pre-encode that reuses this list from the closure. - allMessages = sliceAtLastCompaction(allMessages); - - // Mutable state for the current message being streamed - let currentMessageId = assistantMessage.id; - let streamedContent = ''; - let streamedReasoningContent = ''; - let resolvedModel: string | null = null; - let modelPersisted = false; - - const convId = assistantMessage.convId; - - // Tracks the last message created in this flow. Used as the parent for the next - // turn's assistant message so createAssistantMessage does not have to read - // conversationsStore.activeMessages, which may belong to a different conversation - // after the user navigates while the loop is still running. - let lastCreatedInFlow = currentMessageId; - - // freeze the POST identity from t0 so a stop cancels with the exact session key, - // never a stale or empty model resolved later - this.setChatStreaming(convId, streamedContent, currentMessageId, effectiveModel); - - const recordModel = (modelName: string | null | undefined, persistImmediately = true): void => { - if (!modelName) return; - - const n = normalizeModelName(modelName); - - if (!n || n === resolvedModel) return; - - resolvedModel = n; - const idx = conversationsStore.findMessageIndex(currentMessageId); - - conversationsStore.updateMessageAtIndex(idx, { model: n }); - - if (persistImmediately && !modelPersisted) { - modelPersisted = true; - DatabaseService.updateMessage(currentMessageId, { model: n }).catch(() => { - modelPersisted = false; - resolvedModel = null; - }); - } - }; - - let completionIdRecorded = false; - - const recordCompletionId = (id: string): void => { - if (!id || completionIdRecorded) return; - - completionIdRecorded = true; - const idx = conversationsStore.findMessageIndex(currentMessageId); - - conversationsStore.updateMessageAtIndex(idx, { completionId: id }); - DatabaseService.updateMessage(currentMessageId, { completionId: id }).catch(() => { - completionIdRecorded = false; - }); - }; - const updateStreamingUI = () => { - this.setChatStreaming(convId, streamedContent, currentMessageId, effectiveModel); - const idx = conversationsStore.findMessageIndex(currentMessageId); - - conversationsStore.updateMessageAtIndex(idx, { content: streamedContent }); - }; - const cleanupStreamingState = () => { - this.setChatLoading(convId, false); - this.clearChatStreaming(convId, currentMessageId); - this.processing.setState(convId, null); - }; - - this.processing.setActiveConversation(convId); - const streamCallbacks: ChatStreamCallbacks = { - createAssistantMessage: async () => { - // Reset streaming state for new message - streamedContent = ''; - streamedReasoningContent = ''; - - const msg = await DatabaseService.createMessageBranch( - { - children: [], - content: '', - convId, - model: resolvedModel, - role: MessageRole.ASSISTANT, - timestamp: Date.now(), - toolCalls: '', - type: MessageType.TEXT - }, - lastCreatedInFlow - ); - - if (conversationsStore.activeConversation?.id === convId) { - conversationsStore.addMessageToActive(msg); - } - - currentMessageId = msg.id; - lastCreatedInFlow = msg.id; - - return msg; - }, - createToolResultMessage: async ( - toolCallId: string, - content: string, - extras?: DatabaseMessageExtra[], - toolCwd?: string - ) => { - const msg = await DatabaseService.createMessageBranch( - { - children: [], - content, - convId, - extra: extras, - role: MessageRole.TOOL, - timestamp: Date.now(), - toolCallId, - toolCalls: '', - toolCwd, - type: MessageType.TEXT - }, - currentMessageId - ); - - // mirror into the active store and move the node pointer only when this - // conversation is displayed; otherwise persist the node move straight to - // the db for the owning conv so a foreign conv's currNode stays untouched - if (conversationsStore.activeConversation?.id === convId) { - conversationsStore.addMessageToActive(msg); - await conversationsStore.updateCurrentNode(msg.id); - } else { - await DatabaseService.updateCurrentNode(convId, msg.id); - } - - lastCreatedInFlow = msg.id; - - return msg; - }, - onAssistantTurnComplete: async ( - content: string, - reasoningContent: string | undefined, - timings: ChatMessageTimings | undefined, - toolCalls: import('$lib/types/api').ApiChatCompletionToolCall[] | undefined - ) => { - const updateData: Record = { - content, - reasoningContent: reasoningContent || undefined, - timings, - toolCalls: toolCalls ? JSON.stringify(toolCalls) : '' - }; - - if (resolvedModel && !modelPersisted) updateData.model = resolvedModel; - - await DatabaseService.updateMessage(currentMessageId, updateData); - const idx = conversationsStore.findMessageIndex(currentMessageId); - const uiUpdate: Partial = { - content, - reasoningContent: reasoningContent || undefined, - toolCalls: toolCalls ? JSON.stringify(toolCalls) : '' - }; - - if (timings) uiUpdate.timings = timings; - - if (resolvedModel) uiUpdate.model = resolvedModel; - - // touch the active ui array and node pointer only when this conversation - // is displayed; otherwise persist the node move straight to the db so a - // foreign conv's currNode stays untouched - if (conversationsStore.activeConversation?.id === convId) { - conversationsStore.updateMessageAtIndex(idx, uiUpdate); - await conversationsStore.updateCurrentNode(currentMessageId); - } else { - await DatabaseService.updateCurrentNode(convId, currentMessageId); - } - }, - onAttachments: (messageId: string, extras: DatabaseMessageExtra[]) => { - if (!extras.length) return; - - const idx = conversationsStore.findMessageIndex(messageId); - - if (idx === -1) return; - - const msg = conversationsStore.activeMessages[idx]; - const updatedExtras = [...(msg.extra || []), ...extras]; - - conversationsStore.updateMessageAtIndex(idx, { extra: updatedExtras }); - DatabaseService.updateMessage(messageId, { extra: updatedExtras }).catch(console.error); - }, - onChunk: (chunk: string) => { - streamedContent += chunk; - updateStreamingUI(); - this.setChatReasoning(convId, false); - }, - onCompletionId: (id: string) => recordCompletionId(id), - onError: async (error: Error) => { - if (isAbortError(error)) { - cleanupStreamingState(); - // If aborted with a pending message (e.g. "Send immediately"), re-send it - const pending = this.consumePendingMessage(convId); - - if (pending) { - void this.sendQueuedMessage(convId, pending); - } - - return; - } - - console.error('Streaming error:', error); - // keep whatever was streamed so far, the message stays in memory and in DB - await this.savePartialResponseIfNeeded(convId); - cleanupStreamingState(); - this.clearPendingMessage(convId); - - const contextInfo = ( - error as Error & { contextInfo?: { n_prompt_tokens: number; n_ctx: number } } - ).contextInfo; - - this.showErrorDialog({ - contextInfo, - message: error.message, - type: error.name === 'TimeoutError' ? ErrorDialogType.TIMEOUT : ErrorDialogType.SERVER - }); - - if (onError) onError(error); - }, - onFlowComplete: (finalTimings?: ChatMessageTimings) => { - if (finalTimings) { - const idx = conversationsStore.findMessageIndex(assistantMessage.id); - - conversationsStore.updateMessageAtIndex(idx, { timings: finalTimings }); - DatabaseService.updateMessage(assistantMessage.id, { - timings: finalTimings - }).catch(console.error); - } - - cleanupStreamingState(); - - if (onComplete) onComplete(streamedContent); - - if (serverStore.isRouterMode) modelsStore.fetchRouterModels().catch(console.error); - - // Pre-encode conversation in KV cache for faster next turn - if (settingsStore.config.preEncodeConversation) { - void this.triggerPreEncode(convId, lastCreatedInFlow, effectiveModel); - } - }, - onModel: (modelName: string) => recordModel(modelName), - onReasoningChunk: (chunk: string) => { - streamedReasoningContent += chunk; - // mark streaming state so a stop mid-thinking can persist the partial reasoning - this.setChatStreaming(convId, streamedContent, currentMessageId, effectiveModel); - const idx = conversationsStore.findMessageIndex(currentMessageId); - - conversationsStore.updateMessageAtIndex(idx, { - reasoningContent: streamedReasoningContent - }); - this.setChatReasoning(convId, true); - }, - onTimings: (timings?: ChatMessageTimings, promptProgress?: ChatMessagePromptProgress) => { - this.processing.applyStreamTimings(timings, promptProgress, convId); - }, - onToolCallsStreaming: (toolCalls) => { - const idx = conversationsStore.findMessageIndex(currentMessageId); - - conversationsStore.updateMessageAtIndex(idx, { - toolCalls: JSON.stringify(toolCalls) - }); - }, - onTurnComplete: (intermediateTimings: ChatMessageTimings) => { - // Update the first assistant message with cumulative agentic timings - const idx = conversationsStore.findMessageIndex(assistantMessage.id); - - conversationsStore.updateMessageAtIndex(idx, { timings: intermediateTimings }); - }, - updateToolResultMessage: async ( - messageId: string, - content: string, - extras?: DatabaseMessageExtra[] - ) => { - // Persist latest content + merged extras; mirror into the active - // store so the chat view sees live updates for streaming tools - // (e.g. exec_shell_command). The existing tool message node - // pointer stays put - the renderer is already scoped to it. - const updates: Partial = { content }; - - if (extras) { - const idx = conversationsStore.findMessageIndex(messageId); - const existing = idx >= 0 ? (conversationsStore.activeMessages[idx]?.extra ?? []) : []; - const merged = [...existing, ...extras]; - - updates.extra = merged; - } - - if (conversationsStore.activeConversation?.id === convId) { - const idx = conversationsStore.findMessageIndex(messageId); - - if (idx >= 0) conversationsStore.updateMessageAtIndex(idx, updates); - } - - await DatabaseService.updateMessage(messageId, updates); - } - }; - const toolPolicy = this.toolPolicy(); - - { - const agenticResult = await agenticStore.runAgenticFlow({ - callbacks: streamCallbacks, - conversationId: convId, - flowRootMessageId: assistantMessage.id, - messages: allMessages, - options: { - ...this.getApiOptions(), - ...(effectiveModel ? { model: effectiveModel } : {}) - }, - signal: abortController.signal, - toolPolicy - }); - - if (agenticResult.handled) { - // Generate LLM based title for new conversations after agentic flow completes - if (firstUserMessageContent) { - await this.generateTitleWithLLM(firstUserMessageContent, streamedContent, convId); - } - - // Check if there's a pending steering message to re-send - const pending = agenticStore.consumePendingSteeringMessage(convId); - - if (pending) { - await this.sendQueuedMessage(convId, pending); - } - - return; - } - } - - await ChatService.sendMessage( - allMessages, - { - ...this.getApiOptions(), - ...(effectiveModel ? { model: effectiveModel } : {}), - onChunk: streamCallbacks.onChunk, - onComplete: async ( - finalContent?: string, - reasoningContent?: string, - timings?: ChatMessageTimings, - toolCalls?: string - ) => { - const content = streamedContent || finalContent || ''; - const reasoning = streamedReasoningContent || reasoningContent; - const updateData: Record = { - content, - reasoningContent: reasoning || undefined, - timings, - toolCalls: toolCalls || '' - }; - - if (resolvedModel && !modelPersisted) updateData.model = resolvedModel; - - await DatabaseService.updateMessage(currentMessageId, updateData); - const idx = conversationsStore.findMessageIndex(currentMessageId); - const uiUpdate: Partial = { - content, - reasoningContent: reasoning || undefined, - toolCalls: toolCalls || '' - }; - - if (timings) uiUpdate.timings = timings; - - if (resolvedModel) uiUpdate.model = resolvedModel; - - conversationsStore.updateMessageAtIndex(idx, uiUpdate); - await conversationsStore.updateCurrentNode(currentMessageId); - cleanupStreamingState(); - - // Pre-encode conversation in KV cache for faster next turn - if (settingsStore.config.preEncodeConversation) { - void this.triggerPreEncode(convId, currentMessageId, effectiveModel); - } - - if (onComplete) await onComplete(content); - - if (serverStore.isRouterMode) modelsStore.fetchRouterModels().catch(console.error); - - // Generate LLM based title for new conversations (avoids stale reference - // issue when user switches conversations while streaming) - if (firstUserMessageContent) { - await this.generateTitleWithLLM(firstUserMessageContent, streamedContent, convId); - } - - // Check if there's a pending message queued during streaming - const pending = this.consumePendingMessage(convId); - - if (pending) { - await this.sendQueuedMessage(convId, pending); - } - }, - onCompletionId: streamCallbacks.onCompletionId, - onConnectionState: (state: StreamConnectionState) => { - if (convId === conversationsStore.activeConversation?.id) { - this.streamConnectionState = state; - } - }, - onError: streamCallbacks.onError, - onModel: streamCallbacks.onModel, - onReasoningChunk: streamCallbacks.onReasoningChunk, - onTimings: streamCallbacks.onTimings, - stream: true - }, - convId, - abortController.signal - ); - } - - syncLoadingStateForChat(convId: string): void { - const s = this.chatStreamingStates.get(convId); - - this.processing.setActiveConversation(convId); - - // Sync streaming content to activeMessages so UI displays current content - if (s?.response && s?.messageId) { - const idx = conversationsStore.findMessageIndex(s.messageId); - - if (idx !== -1) { - conversationsStore.updateMessageAtIndex(idx, { content: s.response }); - } - } - } - - async syncRemoteRunningStreams(): Promise { - return this.streams.syncRemoteRunningStreams(); - } - - /** - * Message flows (edit / regenerate / continue / delete) live in - * ChatMessageFlows; these delegate so consumers keep a single entry point. - */ - async updateMessage(messageId: string, newContent: string): Promise { - return this.flows.updateMessage(messageId, newContent); - } - - private abortRequest(convId?: string): void { - if (convId) { - const c = this.abortControllers.get(convId); - - if (c) { - c.abort(); - this.abortControllers.delete(convId); - } - } else { - for (const c of this.abortControllers.values()) c.abort(); - this.abortControllers.clear(); - } - } - - /** The steps a compaction keeps as written, as the settings set them. */ - private compactionPreserve(): number { - return Number(settingsStore.config.compactionPreservedSteps); - } - - private async generateTitleWithLLM( - userContent: string, - assistantContent: string, - convId: string - ): Promise { - const effectiveModel = - serverStore.isRouterMode && modelsStore.selectedModelName - ? modelsStore.selectedModelName - : undefined; - const configValue = settingsStore.config; - const titlePromptTemplate = - typeof configValue.titleGenerationPrompt === 'string' && - configValue.titleGenerationPrompt.trim() - ? configValue.titleGenerationPrompt - : TITLE_GENERATION.DEFAULT_PROMPT; - const titlePrompt = titlePromptTemplate - .replace('{{USER}}', String(userContent || '')) - .replace('{{ASSISTANT}}', String(assistantContent || '')); - const titleMessage: ApiChatMessageData = { - content: titlePrompt, - role: MessageRole.USER - }; - const titleResponse = await ChatService.generateTitle(titleMessage, effectiveModel); - - if (!titleResponse) { - return; - } - - let cleanTitle = titleResponse.trim(); - - cleanTitle = cleanTitle - .replace(TITLE_GENERATION.PREFIX_PATTERN, '') - .replace(TITLE_GENERATION.QUOTE_PATTERN, '') - .trim(); - - if (!cleanTitle || cleanTitle.length < TITLE_GENERATION.MIN_LENGTH) { - const firstLine = userContent.split('\n').find((l) => l.trim().length > 0); - - cleanTitle = firstLine ? firstLine.trim() : TITLE_GENERATION.FALLBACK; - } - - if (cleanTitle && cleanTitle.length >= TITLE_GENERATION.MIN_LENGTH) { - await conversationsStore.updateConversationName(convId, cleanTitle); - } - } - - private getChatStreamingState( - convId: string - ): { response: string; messageId: string } | undefined { - return this.chatStreamingStates.get(convId); - } - - /** - * Pre-encodes the branch ending at the leaf as the next turn reads it: the - * stored path cut at its last compaction, with the tools, message shaping - * and reasoning handling of the chat, so the server warms the very prefix - * that turn extends. Its prompt timings, or null when it returned none. - */ - private async preEncodeBranch( - convId: string, - leafId: string, - model: string | null | undefined, - signal: AbortSignal - ): Promise { - const allMessages = await conversationsStore.getConversationMessages(convId); - const branchPath = [...filterByLeafNodeId(allMessages, leafId, false)]; - const request = await agenticStore.requestFor( - await ChatService.normalizeMessagesForApi(sliceAtLastCompaction(branchPath)), - this.toolPolicy() - ); - - return ChatService.preEncode( - request.messages, - model, - Boolean(settingsStore.config.excludeReasoningFromContext), - signal, - request.tools - ); - } - - private async savePartialResponseIfNeeded(convId?: string): Promise { - const conversationId = convId || conversationsStore.activeConversation?.id; - - if (!conversationId) return; - - const streamingState = this.getChatStreamingState(conversationId); - - if (!streamingState) return; - - const messages = - conversationId === conversationsStore.activeConversation?.id - ? conversationsStore.activeMessages - : await conversationsStore.getConversationMessages(conversationId); - - if (!messages.length) return; - - const lastMessage = messages[messages.length - 1]; - - if (lastMessage?.role !== MessageRole.ASSISTANT) return; - - const partialContent = streamingState.response; - const partialReasoning = lastMessage.reasoningContent || ''; - // snapshot the streamed tool calls before clearing so we still know whether - // anything was captured when deciding to skip the DB write below - const hadPartialToolCalls = !!lastMessage.toolCalls?.trim(); - - // nothing to persist when content, reasoning, and streamed tool calls are all empty - // (e.g. stop before any token). otherwise drop the partial tool call and write whatever - // was streamed: incomplete arguments (truncated JSON, missing closing quote) would - // otherwise be re-sent to the server on the next turn and rejected. - if (!partialContent.trim() && !partialReasoning.trim() && !hadPartialToolCalls) return; - - try { - const updateData: { - content?: string; - reasoningContent?: string; - toolCalls?: string; - timings?: ChatMessageTimings; - } = { - toolCalls: '' - }; - - if (partialContent.trim()) updateData.content = partialContent; - - if (partialReasoning.trim()) updateData.reasoningContent = partialReasoning; - - const lastKnownState = this.processing.getState(conversationId); - - if (lastKnownState) { - updateData.timings = { - cache_n: lastKnownState.cacheTokens || 0, - predicted_ms: - lastKnownState.tokensPerSecond && lastKnownState.tokensDecoded - ? (lastKnownState.tokensDecoded / lastKnownState.tokensPerSecond) * 1000 - : undefined, - predicted_n: lastKnownState.tokensDecoded || 0, - prompt_ms: lastKnownState.promptMs, - prompt_n: lastKnownState.promptTokens || 0 - }; - } - - await DatabaseService.updateMessage(lastMessage.id, updateData); - lastMessage.content = partialContent; - // mirror the drop into the in-memory message so the next request sent via - // sendMessage (queued pending, Send immediately, or manual follow-up) reads - // the cleared value, not whatever the streaming widget had been showing - lastMessage.toolCalls = ''; - - if (updateData.timings) lastMessage.timings = updateData.timings; - } catch (error) { - lastMessage.content = partialContent; - lastMessage.toolCalls = ''; - console.error('Failed to save partial response:', error); - } - } - - /** - * Re-send a message queued while `convId` was busy. sendMessage targets the - * active conversation, so if the user navigated away the message stays - * queued on its own conversation until flushPendingMessage picks it up. - */ - private async sendQueuedMessage( - convId: string, - msg: { content: string; extras?: DatabaseMessageExtra[] } - ): Promise { - if (conversationsStore.activeConversation?.id !== convId) { - this.pendingMessages.set(convId, msg); - - return; - } - - await this.sendMessage(msg.content, msg.extras); - } - - /** - * Streams a fresh summary of `source` into the compaction node and re-stamps - * the reduced context afterwards. `rollback` restores the row when nothing - * usable came back, so an empty or aborted summary never replaces what the - * node already held. - */ - private async summarizeIntoNode( - convId: string, - node: DatabaseMessage, - source: DatabaseMessage[], - rollback: () => Promise - ): Promise { - const abortController = this.getOrCreateAbortController(convId); - const compactionStreamId = COMPACTION.STREAM_ID_PREFIX + convId; - // Model resolution mirrors the request funnel: the selected model - // first, then the model the branch was generated with, so router - // mode targets the child that owns this conversation's KV cache. - const effectiveModel = serverStore.isRouterMode - ? modelsStore.selectedModelName || getConversationModel(source) - : undefined; - - let summary = ''; - // a summary the output limit cut is no summary - let truncated = false; - let summaryModel = node.model; - let summaryTimings: ChatMessageCompactionTimings | undefined; - - const writeNode = (updates: Partial) => { - if (conversationsStore.activeConversation?.id !== convId) return; - - const idx = conversationsStore.findMessageIndex(node.id); - - if (idx >= 0) conversationsStore.updateMessageAtIndex(idx, updates); - }; - - // The node is the row that reports this run's progress, so the turns it - // summarizes stay quiet for as long as it runs. - this.activity.markCompacting(convId, node.id); - // Clearing the stored summary first hands the row over to the pending - // state, where it reports the prompt progress instead of the stale text. - writeNode({ content: '' }); - - // The steps the compaction keeps are part of the source the caller - // handed over; the summarization itself reads only what lies before - // them, so the summary describes the steps the model will still see. - const preserve = this.compactionPreserve(); - const cut = compactionCut(source, preserve); - - if (cut === null) { - await rollback(); - - return; - } - - try { - // The request is the one the chat sends, its options, tools and - // message shaping, cut before the preserved steps: the server - // reuses the prefix it cached and only the instruction is new. - const request = await agenticStore.requestFor( - await ChatService.normalizeMessagesForApi(source.slice(0, cut)), - this.toolPolicy() - ); - const configValue = settingsStore.config; - const compactionPrompt = - typeof configValue.compactionPrompt === 'string' && configValue.compactionPrompt.trim() - ? configValue.compactionPrompt - : COMPACTION.DEFAULT_PROMPT; - - await ChatService.sendMessage( - [...request.messages, { content: compactionPrompt, role: MessageRole.USER }], - { - ...this.getApiOptions(), - model: effectiveModel, - onChunk: (chunk: string) => { - summary += chunk; - writeNode({ content: summary }); - }, - onComplete: ( - _content: string, - _reasoning?: string, - _timings?: ChatMessageTimings, - _toolCalls?: string, - finishReason?: string - ) => { - truncated = finishReason === COMPACTION.FINISH_CUT; - }, - onModel: (modelName: string) => { - summaryModel = modelName; - writeNode({ model: modelName }); - }, - // The summary streams through the same pipe as a chat turn, which - // enables prompt progress on the wire; feeding it to the shared - // processing state lets the pending row show the percentage. The - // closing event carries the timings the row reports once done. - onTimings: (timings?: ChatMessageTimings, promptProgress?: ChatMessagePromptProgress) => { - if (timings) summaryTimings = timings; - - this.processing.applyStreamTimings(timings, promptProgress, convId); - }, - stream: true, - timings_per_token: true, - tools: request.tools - }, - // Registered under the prefixed identity: the visibility kick - // and byte-offset resume protect the summary through tab - // switches, while the reload probe for the bare conversation - // id never reattaches it as a chat turn. - compactionStreamId, - abortController.signal - ); - - if (truncated) throw new Error('The output limit cut the compaction summary'); - - if (!summary.trim()) { - await rollback(); - - return; - } - - const stored: Partial = { content: summary, kept: preserve }; - - if (summaryModel) stored.model = summaryModel; - - writeNode(stored); - await DatabaseService.updateMessage(node.id, stored); - - // Re-encoding the reduced prefix is part of the compaction - // itself: it rebuilds the server KV cache on the summary and - // stamps the true context size on the node for the gauge, - // independently of the per-turn pre-fill setting. - void this.triggerCompactionPreEncode(convId, node.id, effectiveModel, summaryTimings); - } catch (error) { - await rollback(); - - if (isAbortError(error)) { - // The server keeps generating a detached summary otherwise. - void ChatService.cancelServerStream(compactionStreamId, effectiveModel); - } else { - console.error('Failed to compact conversation:', error); - this.showErrorDialog({ - message: error instanceof Error ? error.message : 'Unknown error', - type: ErrorDialogType.SERVER - }); - } - } finally { - this.abortControllers.delete(convId); - // Nothing infers for this conversation anymore: the summarization - // progress reported above must not outlive the request, or a - // skipped pre-encode would leave the gauge on a live state that - // describes the pre-compaction prompt. - this.processing.setState(convId, null); - this.setChatLoading(convId, false); - // Released last: ending it after the loading flag keeps the chat - // turns from flashing their own indicator for a tick. - this.activity.endCompacting(convId); - } - } - - /** The tool policy of the active conversation, the one its requests run under. */ - private toolPolicy(): AgenticToolPolicy { - return { - disabledToolCategories: conversationsStore.preferences.getDisabledToolCategories(), - disabledTools: conversationsStore.preferences.getDisabledTools() - }; - } - - /** - * Pre-encodes the compacted branch and stamps the returned prompt - * timings on the compaction node, so the context gauge reflects the - * reduced context as soon as the compaction finishes instead of after - * the next turn. - */ - private async triggerCompactionPreEncode( - convId: string, - nodeId: string, - model?: string | null, - summaryTimings?: ChatMessageCompactionTimings - ): Promise { - this.cancelPreEncode(); - this.preEncodeAbortController = new AbortController(); - - const signal = this.preEncodeAbortController.signal; - - try { - const allIdle = await ChatService.areAllSlotsIdle(model, signal); - - if (!allIdle || signal.aborted) { - if (!signal.aborted) { - console.warn('[ChatStore] Compaction pre-encode skipped: slots busy'); - } - - return; - } - - const timings = await this.preEncodeBranch(convId, nodeId, model, signal); - - if (!timings || signal.aborted) { - if (!signal.aborted) { - console.warn('[ChatStore] Compaction pre-encode returned no timings'); - } - - return; - } - - // The row reports both what the summary cost (summaryTimings) and the - // size of the context it left behind (timings), so the second is - // nested under the first instead of overwriting it. - const stamped = summaryTimings ? { ...timings, compaction: summaryTimings } : timings; - - await DatabaseService.updateMessage(nodeId, { timings: stamped }); - - if (conversationsStore.activeConversation?.id === convId) { - const idx = conversationsStore.findMessageIndex(nodeId); - - if (idx >= 0) conversationsStore.updateMessageAtIndex(idx, { timings: stamped }); - } - - // Nothing is inferring anymore: clearing the live processing - // state hands the gauge over to the stamped node, which any - // later restore also picks as the context truth. - this.processing.setState(convId, null); - } catch (err) { - if (!isAbortError(err)) { - console.warn('[ChatStore] Compaction pre-encode failed:', err); - } - } - } - - /** - * Pre-encodes the branch ending at the leaf when every slot is idle, so - * the next turn finds its prefix already in the server KV cache. - */ - private async triggerPreEncode( - convId: string, - leafId: string, - model?: string | null - ): Promise { - this.cancelPreEncode(); - this.preEncodeAbortController = new AbortController(); - - const signal = this.preEncodeAbortController.signal; - - try { - const allIdle = await ChatService.areAllSlotsIdle(model, signal); - - if (!allIdle || signal.aborted) return; - - await this.preEncodeBranch(convId, leafId, model, signal); - } catch (err) { - if (!isAbortError(err)) { - console.warn('[ChatStore] Pre-encode failed:', err); - } - } - } -} - -export const chatStore = new ChatStore(); diff --git a/tools/ui/src/lib/stores/conversations/index.svelte.ts b/tools/ui/src/lib/stores/conversations/index.svelte.ts deleted file mode 100644 index f55f74c12208..000000000000 --- a/tools/ui/src/lib/stores/conversations/index.svelte.ts +++ /dev/null @@ -1,856 +0,0 @@ -/** - * conversationsStore - Conversation lifecycle, persistence and navigation - * - * Owns conversation CRUD, message tree navigation, import/export and title - * management, persisted through DatabaseService. Per-chat options (MCP - * overrides, reasoning effort, cwd) live in ConversationPreferences, - * composed as {@link ConversationsStore.preferences}. - */ - -import { browser } from '$app/environment'; -import { goto } from '$app/navigation'; -import { NEW_CHAT_TAB_ID, ROUTES } from '$lib/constants'; -import { MessageRole } from '$lib/enums'; -import { ConversationTransferService } from '$lib/services/conversation-transfer.service'; -import { DatabaseService } from '$lib/services/database.service'; -import { MigrationService } from '$lib/services/migration.service'; -import { RouterService } from '$lib/services/router.service'; -// direct imports between stores, not via the barrel, to avoid circular deps -import { draftMessagesStore } from '$lib/stores/chat/drafts.svelte'; -import { - ConversationPreferences, - type ConversationsPreferencesHost -} from '$lib/stores/conversations/preferences.svelte'; -import { settingsStore } from '$lib/stores/settings/index.svelte'; -import { tabsStore } from '$lib/stores/tabs.svelte'; -import { - collectForkFamily, - filterByLeafNodeId, - findLeafNode, - generateConversationTitle -} from '$lib/utils'; -import { withSearchChatsDisabled } from '$lib/utils/search-chats'; -import { SvelteSet } from 'svelte/reactivity'; -import { toast } from 'svelte-sonner'; - -class ConversationsStore implements ConversationsPreferencesHost { - /** Currently active conversation */ - activeConversation = $state(null); - - /** Messages in the active conversation (filtered by currNode path) */ - activeMessages = $state([]); - - /** List of all conversations */ - conversations = $state([]); - - /** Whether the store has been initialized */ - isInitialized = $state(false); - - /** Per-chat options (MCP overrides, reasoning effort, cwd), composed here. */ - private _preferences = new ConversationPreferences(this); - - /** - * Listeners notified with the ids of conversations that were deleted. - * Lets dependent stores (e.g. agenticStore) drop per-conversation state - * without introducing a circular import back into this store. - */ - private conversationDeletionListeners = new Set<(convIds: string[]) => void>(); - - /** In-flight init run; shared by concurrent callers, reset on failure to allow retry */ - private initPromise: Promise | null = null; - - /** - * Messages loadConversation just read, handed off once so the chat - * screen can reuse them for sibling info instead of re-fetching the - * whole conversation a second time. - */ - private lastLoadedMessages: { convId: string; messages: DatabaseMessage[] } | null = null; - - /** - * Memo of the last findMessageIndex() lookup. Streaming calls it once per - * chunk for the same message, so a validated cache hit keeps that O(1) - * instead of a linear scan of activeMessages on every token. - */ - private lastMessageIndex: { id: string; index: number } | null = null; - - get preferences() { - return this._preferences; - } - - /** - * Adds a message to the active messages array - */ - addMessageToActive(message: DatabaseMessage): void { - this.activeMessages.push(message); - } - - /** - * Applies a field update to a conversation row, mirroring it into both the - * conversations list and the active conversation when it is the target. - * Shared by the rename/pin/preferences flows so no caller can forget to - * mirror one side. - */ - applyConversationUpdate(id: string, updates: Partial): void { - const convIndex = this.conversations.findIndex((c) => c.id === id); - - if (convIndex !== -1) { - const target = this.conversations[convIndex] as unknown as Record; - - for (const [key, value] of Object.entries(updates)) { - if (target[key] !== value) target[key] = value; - } - } - - if (this.activeConversation?.id === id) { - // field-wise, not object replacement: effects that track the active - // conversation identity would otherwise refire on every rename or pin - const target = this.activeConversation as unknown as Record; - - for (const [key, value] of Object.entries(updates)) { - if (target[key] !== value) target[key] = value; - } - } - } - - /** - * Derives a conversation title from its first message content and applies - * it, honoring the title-generation setting. Shared by every flow that - * edits or creates the first user message. - */ - async applyTitleFromContent(convId: string, content: string): Promise { - await this.updateConversationName( - convId, - generateConversationTitle(content, Boolean(settingsStore.config.titleGenerationUseFirstLine)) - ); - } - - /** - * Puts the active conversation into a group, or out of one with null. - * With no active conversation the pick is buffered and the next created - * chat joins that group. - * - * @param groupId - Target group, null to leave the current one - */ - async assignActiveConversationGroup(groupId: string | null): Promise { - const active = this.activeConversation; - - if (active) { - await this.setConversationGroup(active.id, groupId); - } else { - this.preferences.pendingGroupId = groupId; - } - } - - /** - * Deletes multiple conversations in sequence. - * Mirrors deleteConversation() per-id; navigates to the new-chat screen only - * if the currently-open chat was among the deleted ones. - * @param convIds - Conversation IDs to delete - */ - async bulkDeleteConversations(convIds: string[]): Promise { - if (convIds.length === 0) return; - - try { - const idsToRemove = new SvelteSet(convIds); - // Collect all descendants recursively so the local cache stays consistent - // even when deleteWithForks is omitted. - const queue = [...convIds]; - - while (queue.length > 0) { - const parentId = queue.pop()!; - - for (const c of this.conversations) { - if (c.forkedFromConversationId === parentId && !idsToRemove.has(c.id)) { - idsToRemove.add(c.id); - queue.push(c.id); - } - } - } - - const activeWasDeleted = - this.activeConversation !== null && idsToRemove.has(this.activeConversation.id); - - await DatabaseService.bulkDeleteConversations([...idsToRemove]); - - this.conversations = this.conversations.filter((c) => !idsToRemove.has(c.id)); - this.notifyConversationsDeleted([...idsToRemove]); - - if (activeWasDeleted) { - const activeId = this.activeConversation!.id; - - tabsStore.removeTabs([...idsToRemove].filter((id) => id !== activeId)); - this.clearActiveConversation(); - await tabsStore.closeConversation(activeId); - } else { - tabsStore.removeTabs([...idsToRemove]); - } - - toast.success( - idsToRemove.size === 1 - ? 'Conversation deleted' - : `${idsToRemove.size} conversations deleted` - ); - } catch (error) { - console.error('Failed to bulk delete conversations:', error); - toast.error('Failed to delete conversations'); - } - } - - /** - * Bundles the given conversations into a single zip archive and triggers a - * browser download (one JSONL file per conversation). - * @param convIds - Conversation IDs to export - */ - async bulkExportConversations(convIds: string[]): Promise { - if (convIds.length === 0) return; - - try { - const exported = await this.getConversationsForExport(convIds); - - if (exported.length === 0) { - toast.error('No conversations to export'); - - return; - } - - ConversationTransferService.downloadConversationsArchive(exported); - - toast.success( - exported.length === 1 - ? 'Conversation exported' - : `${exported.length} conversations exported` - ); - } catch (error) { - console.error('Failed to bulk export conversations:', error); - toast.error('Failed to export conversations'); - } - } - - /** - * Toggles the pinned state of each conversation individually. - * Mixed-pin selections are intentionally not normalised here; the bulk - * action UI surfaces them as a disabled mixed-state instead. - * @param convIds - Conversation IDs to toggle - */ - async bulkToggleConversationPin(convIds: string[]): Promise { - if (convIds.length === 0) return; - - try { - const updates = await DatabaseService.bulkToggleConversationPins(convIds); - const activeId = this.activeConversation?.id; - - if (this.activeConversation && activeId && updates.has(activeId)) { - this.activeConversation.pinned = updates.get(activeId)!; - } - - for (let i = 0; i < this.conversations.length; i++) { - const newPinned = updates.get(this.conversations[i].id); - - if (newPinned !== undefined) this.conversations[i].pinned = newPinned; - } - - toast.success( - convIds.length === 1 - ? 'Conversation pin toggled' - : `Updated pin state for ${convIds.length} conversations` - ); - } catch (error) { - console.error('Failed to bulk toggle pin:', error); - toast.error('Failed to update pin state'); - } - } - - /** - * Clears the active conversation and messages. - */ - clearActiveConversation(): void { - this.activeConversation = null; - this.activeMessages = []; - // reload defaults so new chats inherit persisted state - this.preferences.resetPending(); - } - - /** One-shot handoff of the messages the last loadConversation read. */ - consumeLastLoadedMessages(convId: string): DatabaseMessage[] | null { - if (this.lastLoadedMessages?.convId !== convId) return null; - - const messages = this.lastLoadedMessages.messages; - - this.lastLoadedMessages = null; - - return messages; - } - - /** - * Creates a new conversation and navigates to it - * @param name - Optional name for the conversation - * @param draft - Optional input draft to carry over to the new conversation - * @returns The ID of the created conversation - */ - async createConversation( - name?: string, - draft?: { message: string; files: ChatUploadedFile[] } - ): Promise { - const conversationName = name || `Chat ${new Date().toLocaleString()}`; - // The tool policy is seeded from the current defaults: edits made inside - // the conversation afterwards live on its row and do not flow back into - // the defaults. Working directory picked on the new-chat screen gets - // threaded in here too, then cleared so it doesn't bleed onto subsequent - // new chats. - const conversation = await DatabaseService.createConversation(conversationName, { - cwd: this.preferences.pendingCwd ?? undefined, - groupId: this.preferences.pendingGroupId ?? undefined, - reasoningEffort: this.preferences.pendingReasoningEffort, - ...this.preferences.getToolPolicySnapshot() - }); - - this.preferences.pendingCwd = null; - this.preferences.pendingGroupId = null; - - this.conversations = [conversation, ...this.conversations]; - this.activeConversation = conversation; - this.activeMessages = []; - - if (draft) { - draftMessagesStore.saveDraftMessage(conversation.id, draft.message, draft.files); - } - - await goto(RouterService.chat(conversation.id)); - - // the draft moved to the new conversation, so drop the copy saved for the new-chat screen - if (draft) { - draftMessagesStore.clearDraftMessage(undefined); - } - - return conversation.id; - } - - /** - * Deletes all conversations and their messages - */ - async deleteAll(): Promise { - try { - const allConversations = await DatabaseService.getAllConversations(); - const allIds = allConversations.map((c) => c.id); - - await DatabaseService.bulkDeleteConversations(allIds); - - this.clearActiveConversation(); - this.conversations = []; - tabsStore.clear(); - this.notifyConversationsDeleted(allIds); - - toast.success('All conversations deleted'); - - await goto(ROUTES.START); - } catch (error) { - console.error('Failed to delete all conversations:', error); - toast.error('Failed to delete conversations'); - } - } - - /** - * Deletes a conversation and all its messages - * @param convId - The conversation ID to delete - */ - async deleteConversation(convId: string, options?: { deleteWithForks?: boolean }): Promise { - try { - await DatabaseService.deleteConversation(convId, options); - - if (options?.deleteWithForks) { - // Collect all descendants recursively - const idsToRemove = new SvelteSet([convId]); - const queue = [convId]; - - while (queue.length > 0) { - const parentId = queue.pop()!; - - for (const c of this.conversations) { - if (c.forkedFromConversationId === parentId && !idsToRemove.has(c.id)) { - idsToRemove.add(c.id); - queue.push(c.id); - } - } - } - this.conversations = this.conversations.filter((c) => !idsToRemove.has(c.id)); - - if (this.activeConversation && idsToRemove.has(this.activeConversation.id)) { - const activeId = this.activeConversation.id; - - tabsStore.removeTabs([...idsToRemove].filter((id) => id !== activeId)); - this.clearActiveConversation(); - await tabsStore.closeConversation(activeId); - } else { - tabsStore.removeTabs([...idsToRemove]); - } - - this.notifyConversationsDeleted([...idsToRemove]); - } else { - // Reparent direct children to deleted conv's parent (or promote to top-level) - const deletedConv = this.conversations.find((c) => c.id === convId); - const newParent = deletedConv?.forkedFromConversationId; - - this.conversations = this.conversations - .filter((c) => c.id !== convId) - .map((c) => - c.forkedFromConversationId === convId - ? { ...c, forkedFromConversationId: newParent } - : c - ); - - if (this.activeConversation?.id === convId) { - this.clearActiveConversation(); - await tabsStore.closeConversation(convId); - } else { - tabsStore.removeTabs([convId]); - } - - this.notifyConversationsDeleted([convId]); - } - } catch (error) { - console.error('Failed to delete conversation:', error); - } - } - - /** - * Downloads a single conversation as a JSONL file, serializing the full message tree. - * @param convId - The conversation ID to download - */ - async downloadConversation(convId: string): Promise { - const [exportedConversation] = await this.getConversationsForExport([convId]); - - if (!exportedConversation) return; - - ConversationTransferService.downloadConversationFile(exportedConversation); - } - - /** - * Finds the index of a message in active messages. - * - * The last lookup is memoized and reused when it still validates against - * the current array (same id at the same position), which covers the - * streaming hot path where the same message is looked up on every chunk - * while the array itself only mutates by field. Any structural change - * (splice, reassignment, reordering) fails validation and falls back to a - * full scan. - */ - findMessageIndex(messageId: string): number { - const last = this.lastMessageIndex; - const messages = this.activeMessages; - - if ( - last && - last.id === messageId && - last.index >= 0 && - last.index < messages.length && - messages[last.index]?.id === messageId - ) { - return last.index; - } - - const index = messages.findIndex((m) => m.id === messageId); - - this.lastMessageIndex = { id: messageId, index }; - - return index; - } - - /** - * Forks a conversation at a specific message, creating a new conversation - * containing messages from root up to the target message, then navigates to it. - * - * @param messageId - The message ID to fork at - * @param options - Fork options (name and whether to include attachments) - * @returns The new conversation ID, or null if fork failed - */ - async forkConversation( - messageId: string, - options: { name: string; includeAttachments: boolean } - ): Promise { - if (!this.activeConversation) return null; - - try { - const newConv = await DatabaseService.forkConversation( - this.activeConversation.id, - messageId, - options - ); - - this.conversations = [newConv, ...this.conversations]; - - await goto(RouterService.chat(newConv.id)); - - toast.success('Conversation forked'); - - return newConv.id; - } catch (error) { - console.error('Failed to fork conversation:', error); - toast.error('Failed to fork conversation'); - - return null; - } - } - - /** - * Gets all messages for a specific conversation - * @param convId - The conversation ID - * @returns Array of messages - */ - async getConversationMessages(convId: string): Promise { - return await DatabaseService.getConversationMessages(convId); - } - - /** - * Gets conversations and their messages from the database for export. - * @param convIds - Conversation IDs - * @returns List of conversations with messages, ordered by the input IDs - */ - async getConversationsForExport(convIds: string[]): Promise { - const [fetched, groups] = await Promise.all([ - DatabaseService.getConversationsWithMessages(convIds), - DatabaseService.getAllGroups() - ]); - const groupsById = new Map(groups.map((group) => [group.id, group])); - - return convIds - .map((id) => fetched.get(id)) - .filter((entry): entry is ExportedConversation => entry !== undefined) - .map((entry) => { - const group = entry.conv.groupId ? groupsById.get(entry.conv.groupId) : undefined; - - return group ? { ...entry, group: { id: group.id, name: group.name } } : entry; - }); - } - - /** - * Imports conversations from provided data (without file picker) - * @param data - Array of conversation data with messages - * @returns The conversations written to the database and the ones skipped - */ - async importConversationsData( - data: ExportedConversations - ): Promise<{ imported: DatabaseConversation[]; skipped: DatabaseConversation[] }> { - // exports can predate search_chats or come from another device, keep it off like for existing chats - const result = await DatabaseService.importConversations( - (Array.isArray(data) ? data : [data]).map(({ conv, messages }) => ({ - conv: { ...conv, disabledTools: withSearchChatsDisabled(conv.disabledTools) }, - messages - })) - ); - - await this.loadConversations(); - - return result; - } - - /** - * Initialize the store by loading conversations from database. - * Safe to call multiple times: concurrent callers share a single run, - * and a failed run can be retried by calling again. - */ - initialize(): Promise { - if (!browser) return Promise.resolve(); - - if (this.initPromise) return this.initPromise; - - this.initPromise = (async () => { - try { - await MigrationService.runAllMigrations(); - await this.loadConversations(); - this.isInitialized = true; - } catch (error) { - console.error('Failed to initialize conversations:', error); - this.initPromise = null; - } - })(); - - return this.initPromise; - } - - /** - * Loads a specific conversation and its messages - * @param convId - The conversation ID to load - * @returns True if conversation was loaded successfully - */ - async loadConversation(convId: string): Promise { - try { - const conversation = await DatabaseService.getConversation(convId); - - if (!conversation) { - return false; - } - - // Drop any cwd the user drafted on the empty new-chat screen - - // it doesn't belong to this conversation. - this.preferences.pendingCwd = null; - - const allMessages = await DatabaseService.getConversationMessages(convId); - - // set conversation and messages in one sync block so effects never see - // the new conversation with the previous conversation's messages - this.lastLoadedMessages = { convId, messages: allMessages }; - this.activeConversation = conversation; - this.activeMessages = conversation.currNode - ? (filterByLeafNodeId(allMessages, conversation.currNode, false) as DatabaseMessage[]) - : allMessages; - - return true; - } catch (error) { - console.error('Failed to load conversation:', error); - - return false; - } - } - - /** - * Loads all conversations from the database - */ - async loadConversations(): Promise { - const conversations = await DatabaseService.getAllConversations(); - - this.conversations = conversations; - } - - /** - * Navigates to a specific sibling branch by updating currNode and refreshing messages. - * @param siblingId - The sibling message ID to navigate to - */ - async navigateToSibling(siblingId: string): Promise { - if (!this.activeConversation) return; - - const allMessages = await DatabaseService.getConversationMessages(this.activeConversation.id); - const rootMessage = allMessages.find((m) => m.type === 'root' && m.parent === null); - const currentFirstUserMessage = this.activeMessages.find( - (m) => m.role === MessageRole.USER && m.parent === rootMessage?.id - ); - const currentLeafNodeId = findLeafNode(allMessages, siblingId); - - await DatabaseService.updateCurrentNode(this.activeConversation.id, currentLeafNodeId); - this.activeConversation.currNode = currentLeafNodeId; - await this.refreshActiveMessages(); - - if (rootMessage && this.activeMessages.length > 0) { - const newFirstUserMessage = this.activeMessages.find( - (m) => m.role === MessageRole.USER && m.parent === rootMessage.id - ); - - if ( - newFirstUserMessage && - newFirstUserMessage.content.trim() && - (!currentFirstUserMessage || - newFirstUserMessage.id !== currentFirstUserMessage.id || - newFirstUserMessage.content.trim() !== currentFirstUserMessage.content.trim()) - ) { - await this.applyTitleFromContent(this.activeConversation.id, newFirstUserMessage.content); - } - } - } - - /** - * Registers a listener invoked with the ids of deleted conversations. - * Returns an unsubscribe function. - */ - onConversationsDeleted(listener: (convIds: string[]) => void): () => void { - this.conversationDeletionListeners.add(listener); - - return () => this.conversationDeletionListeners.delete(listener); - } - - /** - * Start a fresh chat by navigating to the bare `#/` new-chat screen. - * - * @param options.inNewTab - With Conversation tabs on, open it in a tab of - * its own, like the tab bar's "+", so the open chat keeps its tab - */ - async openNewChat({ inNewTab = false } = {}): Promise { - if (inNewTab && settingsStore.config.conversationTabs) - await tabsStore.openInNewTab(NEW_CHAT_TAB_ID); - - this.clearActiveConversation(); - this.preferences.pendingGroupId = null; - await goto(ROUTES.START); - } - - /** - * Refreshes active messages based on currNode after branch navigation. - */ - async refreshActiveMessages(): Promise { - if (!this.activeConversation) return; - - const allMessages = await DatabaseService.getConversationMessages(this.activeConversation.id); - - if (allMessages.length === 0) { - this.activeMessages = []; - - return; - } - - const leafNodeId = - this.activeConversation.currNode || - allMessages.reduce((latest, msg) => (msg.timestamp > latest.timestamp ? msg : latest)).id; - const currentPath = filterByLeafNodeId(allMessages, leafNodeId, false) as DatabaseMessage[]; - - this.activeMessages = currentPath; - } - - /** - * Removes a message from active messages by index - */ - removeMessageAtIndex(index: number): DatabaseMessage | undefined { - if (index !== -1) { - return this.activeMessages.splice(index, 1)[0]; - } - - return undefined; - } - - /** - * Moves a conversation with its whole fork family into a group, or out of one - * when `groupId` is null: a family never splits across sections. A pinned chat - * that joins a group leaves Pinned, since group sections do not show pinned chats. - * - * @param convId - Conversation to move - * @param groupId - Target group, null to take the conversations out of their group - */ - async setConversationGroup(convId: string, groupId: string | null): Promise { - const ids = new Set(collectForkFamily(this.conversations, convId)); - - try { - await DatabaseService.setConversationsGroup([...ids], groupId); - - for (const conversation of this.conversations) { - if (!ids.has(conversation.id)) continue; - - this.applyConversationUpdate(conversation.id, { - groupId: groupId ?? undefined, - ...(groupId && conversation.pinned ? { pinned: false } : {}) - }); - } - } catch (error) { - console.error('Failed to move conversation to group:', error); - } - } - - /** - * Removes messages from active messages starting at an index - */ - sliceActiveMessages(startIndex: number): void { - this.activeMessages = this.activeMessages.slice(0, startIndex); - } - - /** - * Toggles the pinned status of a conversation. - * @param convId - The conversation ID to toggle - * @returns The new pinned status - */ - async toggleConversationPin(convId: string): Promise { - try { - const newPinnedState = await DatabaseService.toggleConversationPin(convId); - - this.applyConversationUpdate(convId, { pinned: newPinnedState }); - - return newPinnedState; - } catch (error) { - console.error('Failed to toggle conversation pin:', error); - - return false; - } - } - - /** - * Updates the name of a conversation. - * @param convId - The conversation ID to update - * @param name - The new name for the conversation - */ - async updateConversationName(convId: string, name: string): Promise { - try { - await DatabaseService.updateConversation(convId, { name }); - - this.applyConversationUpdate(convId, { name }); - } catch (error) { - console.error('Failed to update conversation name:', error); - } - } - - /** - * Marks a conversation as recently active: stamps lastModified (persisted) - * and moves it to the top of the list. Only message-activity flows call - * this; metadata updates (rename, pin, settings) do not. - * - * @param convId - Conversation that produced the activity, defaults to the active one - */ - updateConversationTimestamp(convId?: string): void { - const targetId = convId ?? this.activeConversation?.id; - - if (!targetId) return; - - const now = Date.now(); - const chatIndex = this.conversations.findIndex((c) => c.id === targetId); - - if (chatIndex !== -1) { - this.conversations[chatIndex].lastModified = now; - const updatedConv = this.conversations.splice(chatIndex, 1)[0]; - - this.conversations = [updatedConv, ...this.conversations]; - } - - if (this.activeConversation?.id === targetId) { - this.activeConversation.lastModified = now; - } - - DatabaseService.updateConversation(targetId, { lastModified: now }).catch((error) => - console.error('Failed to update conversation timestamp:', error) - ); - } - - /** - * Updates the current node of the active conversation - * @param nodeId - The new current node ID - */ - async updateCurrentNode(nodeId: string): Promise { - if (!this.activeConversation) return; - - await DatabaseService.updateCurrentNode(this.activeConversation.id, nodeId); - this.activeConversation.currNode = nodeId; - } - - /** - * Updates a message at a specific index in active messages - */ - updateMessageAtIndex(index: number, updates: Partial): void { - const message = index === -1 ? undefined : this.activeMessages[index]; - - if (!message) return; - - // Assign field by field rather than replacing the object. Replacing it - // changes the array slot, which invalidates every consumer that merely - // walks the list - notably ChatMessages.displayMessages, which rebuilds - // entries for every message in the conversation. Deep $state proxies make - // per-field writes fine-grained, so only readers of the changed field wake. - const target = message as unknown as Record; - - for (const [key, value] of Object.entries(updates)) { - if (target[key] !== value) { - target[key] = value; - } - } - } - - /** - * - * - * Import & Export - * - * - */ - - private notifyConversationsDeleted(convIds: string[]): void { - if (convIds.length === 0) return; - - for (const listener of this.conversationDeletionListeners) { - listener(convIds); - } - } -} - -export const conversationsStore = new ConversationsStore(); diff --git a/tools/ui/src/lib/stores/index.ts b/tools/ui/src/lib/stores/index.ts deleted file mode 100644 index 23eb809bd4ec..000000000000 --- a/tools/ui/src/lib/stores/index.ts +++ /dev/null @@ -1,67 +0,0 @@ -/** - * STORES - * - * Reactive Svelte runes state layer. Stores own application state and - * expose it as plain Svelte 5 runes (`$state`, `$derived`, `$effect`), - * consumed by components, routes, hooks and services. - * - * Import from this barrel in leaf consumers: - * - * ```ts - * import { chatStore, modelsStore } from '$lib/stores'; - * ``` - * - * Store modules keep direct imports between each other (and from services/ - * utils they depend on) to avoid circular dependency chains. - * - * Each store below documents its primary responsibility. - */ - -// CHAT / MESSAGING -export { chatStore } from './chat/index.svelte'; - -export { draftMessagesStore } from './chat/drafts.svelte'; - -// CONVERSATION TABS -export { tabsStore } from './tabs.svelte'; - -// CONTEXT STATS (active conversation context window usage) -export { contextStatsStore } from './chat/context-stats.svelte'; - -// AGENTIC (multi-turn tool orchestration) -export { agenticStore } from './agentic/index.svelte'; - -// CONVERSATIONS -export { sidebarDragStore } from './sidebar-drag.svelte'; -export { conversationsStore } from './conversations/index.svelte'; - -// MCP -export { mcpStore } from './mcp/index.svelte'; - -// GROUPS (named sidebar sections for chats) -export { groupsStore } from './groups.svelte'; - -// MODELS -export { modelsStore } from './models/index.svelte'; - -// MODELS DISCOVER (HuggingFace browse state for the discover dialog) -export { modelsDiscoverStore } from './models-discover/index.svelte'; - -// SERVER -export { serverStore } from './server.svelte'; - -// UI / LAYOUT -export { uiStore } from './ui.svelte'; - -// SETTINGS / UI PREFERENCES -export { settingsStore } from './settings/index.svelte'; - -export { permissionsStore } from './permissions.svelte'; - -// TOOLS -export { toolsStore } from './tools.svelte'; - -// ENVIRONMENT / META -export { versionStore } from './version.svelte'; - -export { deviceStore } from './device.svelte'; diff --git a/tools/ui/src/lib/stores/mcp/index.svelte.ts b/tools/ui/src/lib/stores/mcp/index.svelte.ts deleted file mode 100644 index 967288c90fa8..000000000000 --- a/tools/ui/src/lib/stores/mcp/index.svelte.ts +++ /dev/null @@ -1,1437 +0,0 @@ -/** - * mcpStore - MCP host: server connections and tool operations - * - * Implements the MCP "Host" role, coordinating multiple server connections - * and exposing a unified tool interface: lifecycle, name-conflict detection - * and automatic tool-to-server routing. Owns connection state and raw - * `Tool[]` per server; the OpenAI-compatible wire format is built in - * toolsStore. Composes the health-check manager; uses MCPService for the - * protocol layer. - */ - -import type { ListChangedHandlers } from '@modelcontextprotocol/sdk/types.js'; -import { browser } from '$app/environment'; -import { SETTINGS_KEYS } from '$lib/constants'; -import { CACHE, DEFAULT_MCP_CONFIG, MCP_RECONNECT, MCP_SERVER_ID_PREFIX } from '$lib/constants'; -import { ColorMode, HealthCheckStatus, MCPConnectionPhase, MCPRefType } from '$lib/enums'; -import { MCPService } from '$lib/services/mcp.service'; -// direct imports between stores, not via the barrel, to avoid circular deps -import { MCPHealthCheckManager, type McpHealthHost } from '$lib/stores/mcp/health.svelte'; -import { mcpResourceStore } from '$lib/stores/mcp/resources.svelte'; -import { serverStore } from '$lib/stores/server.svelte'; -import { settingsStore } from '$lib/stores/settings/index.svelte'; -import type { - GetPromptResult, - HealthCheckParams, - HealthCheckState, - MCPClientConfig, - MCPConnection, - MCPPromptInfo, - MCPResourceAttachment, - MCPResourceContent, - MCPServerConfig, - MCPServerDisplayInfo, - MCPServerSettingsEntry, - MCPToolCall, - ServerStatus, - Tool, - ToolExecutionResult -} from '$lib/types'; -import type { DatabaseMessageExtraMcpResource } from '$lib/types/database'; -import type { SettingsConfigType } from '$lib/types/settings'; -import { - buildProxiedIconUrl, - detectMcpTransportFromUrl, - getMcpIconUrl, - getMcpServerFaviconFallback, - getMcpServerLabel, - parseMcpServerSettings, - uuid -} from '$lib/utils'; -import { mode } from 'mode-watcher'; - -class MCPStore implements McpHealthHost { - private _error = $state(null); - private _isInitializing = $state(false); - private _toolCount = $state(0); - private activeFlowCount = 0; - - private configSignature: string | null = null; - private connectedServers = $state([]); - private connections = new Map(); - // health checks: per-server connectivity probes with optional promotion to active connections - private health = new MCPHealthCheckManager(this); - private initPromise: Promise | null = null; - private reconnectingServers = new Set(); // Guard against concurrent reconnections - private serverConfigs = new Map(); // Store configs for reconnection - private serversCache: { raw: unknown; servers: MCPServerSettingsEntry[] } | null = null; - private toolsIndex = new Map(); - - get availableTools(): string[] { - return Array.from(this.toolsIndex.keys()); - } - - get connectedServerCount(): number { - return this.connectedServers.length; - } - - get connectedServerNames(): string[] { - return this.connectedServers; - } - - get error(): string | null { - return this._error; - } - - get isEnabled(): boolean { - const mcpConfig = this.buildMcpClientConfig(settingsStore.config); - - return ( - mcpConfig !== null && mcpConfig !== undefined && Object.keys(mcpConfig.servers).length > 0 - ); - } - - get isInitialized(): boolean { - return this.connections.size > 0; - } - - get isInitializing(): boolean { - return this._isInitializing; - } - - get isProxyAvailable(): boolean { - return serverStore.props?.cors_proxy_enabled ?? false; - } - - /** Resource state, composed here so consumers have a single MCP scope. */ - get resources() { - return mcpResourceStore; - } - - get toolCount(): number { - return this._toolCount; - } - - acquireConnection(): void { - this.activeFlowCount++; - } - - addServer( - serverData: Omit & { id?: string } - ): MCPServerSettingsEntry { - const servers = this.getServers(); - const newServer: MCPServerSettingsEntry = { - displayName: serverData.displayName, - enabled: serverData.enabled, - headers: serverData.headers?.trim() || undefined, - id: serverData.id || (uuid() ?? `server-${Date.now()}`), - name: serverData.name, - url: serverData.url.trim(), - useProxy: serverData.useProxy - }; - - settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, JSON.stringify([...servers, newServer])); - - return newServer; - } - - /** - * Add a resource as attachment to chat context. - * Automatically fetches content if not cached. - */ - async attachResource(uri: string): Promise { - const resourceInfo = mcpResourceStore.findResourceByUri(uri); - - if (!resourceInfo) { - console.error(`[MCPStore] Resource not found: ${uri}`); - - return null; - } - - if (mcpResourceStore.isAttached(uri)) { - return null; - } - - const attachment = mcpResourceStore.addAttachment(resourceInfo); - - try { - const content = await this.readResource(uri); - - if (content) { - mcpResourceStore.updateAttachmentContent(attachment.id, content); - } else { - mcpResourceStore.updateAttachmentError(attachment.id, 'Failed to read resource'); - } - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - - mcpResourceStore.updateAttachmentError(attachment.id, message); - } - - return mcpResourceStore.getAttachment(attachment.id) ?? null; - } - - /** - * Auto-reconnect to a server with exponential backoff. - * Continues indefinitely until successful. - * - * Race-condition safety: when the phase callback fires a DISCONNECTED event - * while we are still inside this function (e.g., the server drops right after - * a successful connect()), a naive inner `autoReconnect()` call would be - * swallowed by the `reconnectingServers` guard, leaving the server - * permanently disconnected once the outer call exits. We solve this by - * deferring the new reconnection via the `needsReconnect` flag: the flag is - * set inside the phase callback and honoured in the `finally` block after - * the guard entry has been removed. - */ - async autoReconnect(serverName: string): Promise { - // Guard against concurrent reconnections - if (this.reconnectingServers.has(serverName)) { - console.log(`[MCPStore][${serverName}] Reconnection already in progress, skipping`); - - return; - } - - const serverConfig = this.serverConfigs.get(serverName); - - if (!serverConfig) { - console.error(`[MCPStore] No config found for ${serverName}, cannot reconnect`); - - return; - } - - this.reconnectingServers.add(serverName); - let backoff = MCP_RECONNECT.INITIAL_DELAY; - // Flag set by the phase callback when a DISCONNECTED event fires while - // reconnectingServers still holds this server (see JSDoc above). - let needsReconnect = false; - - try { - while (true) { - await new Promise((resolve) => setTimeout(resolve, backoff)); - - console.log(`[MCPStore][${serverName}] Auto-reconnecting...`); - - try { - // Per-attempt timeout: reject if the server doesn't respond in time, - // then fall through to backoff logic as with any other failure. - const timeoutPromise = new Promise((_, reject) => - setTimeout( - () => - reject( - new Error( - `Reconnect attempt timed out after ${MCP_RECONNECT.ATTEMPT_TIMEOUT_MS}ms` - ) - ), - MCP_RECONNECT.ATTEMPT_TIMEOUT_MS - ) - ); - - needsReconnect = false; - const listChangedHandlers = this.createListChangedHandlers(serverName); - const connectPromise = MCPService.connect( - serverName, - serverConfig, - DEFAULT_MCP_CONFIG.clientInfo, - DEFAULT_MCP_CONFIG.capabilities, - (phase) => { - if (phase === MCPConnectionPhase.DISCONNECTED) { - if (this.reconnectingServers.has(serverName)) { - // Reconnect loop is active; defer to after it exits. - needsReconnect = true; - } else { - console.log( - `[MCPStore][${serverName}] Connection lost, restarting auto-reconnect` - ); - this.autoReconnect(serverName); - } - } - }, - listChangedHandlers - ); - const connection = await Promise.race([connectPromise, timeoutPromise]); - - this.connections.set(serverName, connection); - - // Rebuild tool index for this server - this.indexServerTools(serverName, connection.tools); - - console.log(`[MCPStore][${serverName}] Reconnected successfully`); - - break; - } catch (error) { - console.warn(`[MCPStore][${serverName}] Reconnection failed:`, error); - backoff = Math.min(backoff * MCP_RECONNECT.BACKOFF_MULTIPLIER, MCP_RECONNECT.MAX_DELAY); - } - } - } finally { - this.reconnectingServers.delete(serverName); - - // If the phase callback signalled a disconnect while this function held - // the guard, kick off a fresh reconnect now that the guard is released. - if (needsReconnect) { - console.log( - `[MCPStore][${serverName}] Deferred disconnect detected, restarting auto-reconnect` - ); - this.autoReconnect(serverName); - } - } - } - - clearError(): void { - this._error = null; - } - - clearHealthCheck(serverId: string): void { - this.health.clear(serverId); - } - - /** - * Clear all resource attachments. - */ - clearResourceAttachments(): void { - mcpResourceStore.clearAttachments(); - } - - /** - * Convert current resource attachments to DatabaseMessageExtra[] and clear them. - * Called during message send to persist resources with the user message. - */ - consumeResourceAttachmentsAsExtras(): DatabaseMessageExtraMcpResource[] { - const extras = mcpResourceStore.toMessageExtras(); - - if (extras.length > 0) { - mcpResourceStore.clearAttachments(); - } - - return extras; - } - - /** - * Initialize every settings-enabled server. Policy filtering happens at tool - * collection time, so switching conversation policies never re-initializes. - */ - async ensureInitialized(): Promise { - if (!browser) { - return false; - } - - const mcpConfig = this.buildMcpClientConfig(settingsStore.config); - const signature = mcpConfig ? JSON.stringify(mcpConfig) : null; - - if (!signature) { - await this.shutdown(); - - return false; - } - - if (this.isInitialized && this.configSignature === signature) { - return true; - } - - if (this.initPromise && this.configSignature === signature) { - return this.initPromise; - } - - if (this.connections.size > 0 || this.initPromise) await this.shutdown(); - - return this.initialize(signature, mcpConfig!); - } - - async executeTool(toolCall: MCPToolCall, signal?: AbortSignal): Promise { - return this.executeToolByName( - toolCall.function.name, - this.parseToolArguments(toolCall.function.arguments), - signal - ); - } - - async executeToolByName( - toolName: string, - args: Record, - signal?: AbortSignal - ): Promise { - const serverName = this.toolsIndex.get(toolName); - - if (!serverName) throw new Error(`Unknown tool: ${toolName}`); - - const connection = this.connections.get(serverName); - - if (!connection) throw new Error(`Server "${serverName}" is not connected`); - - try { - return await MCPService.callTool(connection, { arguments: args, name: toolName }, signal); - } catch (error) { - if (MCPService.isSessionExpiredError(error)) { - await this.reconnectServer(serverName); - - const newConnection = this.connections.get(serverName); - - if (!newConnection) throw new Error(`Failed to reconnect to "${serverName}"`); - - return MCPService.callTool(newConnection, { arguments: args, name: toolName }, signal); - } - - throw error; - } - } - - /** - * Fetch resources from all connected servers that support them. - * Updates mcpResourceStore with the results. - * @param forceRefresh - If true, bypass cache and fetch fresh data - */ - async fetchAllResources(forceRefresh: boolean = false): Promise { - const serversWithResources = this.getServersWithResources(); - - if (serversWithResources.length === 0) { - return; - } - - // Check if we have cached resources and they're recent (unless force refresh) - if (!forceRefresh) { - const allServersCached = serversWithResources.every((serverName) => { - const serverRes = mcpResourceStore.getServerResources(serverName); - - if (!serverRes || !serverRes.lastFetched) { - return false; - } - - // Cache is valid for 5 minutes - const age = Date.now() - serverRes.lastFetched.getTime(); - - return age < CACHE.DEFAULT_TTL_MS; - }); - - if (allServersCached) { - console.log('[MCPStore] Using cached resources'); - - return; - } - } - - mcpResourceStore.setLoading(true); - - try { - await Promise.all( - serversWithResources.map((serverName) => this.fetchServerResources(serverName)) - ); - } finally { - mcpResourceStore.setLoading(false); - } - } - - /** - * Fetch resources from a specific server. - * Updates mcpResourceStore with the results. - */ - async fetchServerResources(serverName: string): Promise { - const connection = this.connections.get(serverName); - - if (!connection) { - console.warn(`[MCPStore] No connection found for server: ${serverName}`); - - return; - } - - if (!MCPService.supportsResources(connection)) { - return; - } - - mcpResourceStore.setServerLoading(serverName, true); - - try { - const [resources, templates] = await Promise.all([ - MCPService.listAllResources(connection), - MCPService.listAllResourceTemplates(connection) - ]); - - mcpResourceStore.setServerResources(serverName, resources, templates); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - - mcpResourceStore.setServerError(serverName, message); - console.error(`[MCPStore][${serverName}] Failed to fetch resources:`, error); - } - } - - /** - * Resolve which configured MCP server owns a given tool name. Looks at - * active connections first (fast path), then falls back to per-server - * health-check data so server-side MCP proxies (where llama-server - * executes MCP tools but the browser does not hold a direct connection) - * still resolve tool names to their owning server. - */ - findServerForTool(toolName: string): string | undefined { - const fromIndex = this.toolsIndex.get(toolName); - - if (fromIndex) return fromIndex; - - for (const server of this.getServers()) { - const health = this.health.checks[server.id]; - - if (!health || health.status !== HealthCheckStatus.SUCCESS) continue; - - if (health.tools.some((tool) => tool.name === toolName)) { - return server.id; - } - } - - return undefined; - } - getActiveFlowCount(): number { - return this.activeFlowCount; - } - - async getAllPrompts(): Promise { - const results: MCPPromptInfo[] = []; - - for (const [serverName, connection] of this.connections) { - if (!connection.serverCapabilities?.prompts) continue; - - const prompts = await MCPService.listPrompts(connection); - - for (const prompt of prompts) { - results.push({ - arguments: prompt.arguments?.map((arg) => ({ - description: arg.description, - name: arg.name, - required: arg.required - })), - description: prompt.description, - name: prompt.name, - serverName, - title: prompt.title - }); - } - } - - return results; - } - - /** - * Get all active MCP connections. - * @returns Map of server names to connections - */ - getConnections(): Map { - return this.connections; - } - - /** - * Check if a server already has an active connection that can be reused. - * Returns the existing connection if available. - */ - getExistingConnection(serverId: string): MCPConnection | undefined { - return this.connections.get(serverId); - } - - /** - * Get server instructions from health check results (for display before active connection). - * Useful for showing instructions in settings UI. - */ - getHealthCheckInstructions(): Array<{ - serverId: string; - serverTitle?: string; - instructions: string; - }> { - const results: Array<{ serverId: string; serverTitle?: string; instructions: string }> = []; - - for (const [serverId, state] of Object.entries(this.health.checks)) { - if (state.status === HealthCheckStatus.SUCCESS && state.instructions) { - results.push({ - instructions: state.instructions, - serverId, - serverTitle: state.serverInfo?.title || state.serverInfo?.name - }); - } - } - - return results; - } - - /** - * Health checks live in MCPHealthCheckManager; these delegate so - * consumers keep a single entry point. - */ - getHealthCheckState(serverId: string): HealthCheckState { - return this.health.getState(serverId); - } - - async getPrompt( - serverName: string, - promptName: string, - args?: Record - ): Promise { - const connection = this.connections.get(serverName); - - if (!connection) throw new Error(`Server "${serverName}" not found for prompt "${promptName}"`); - - return MCPService.getPrompt(connection, promptName, args); - } - - async getPromptCompletions( - serverName: string, - promptName: string, - argumentName: string, - argumentValue: string - ): Promise<{ values: string[]; total?: number; hasMore?: boolean } | null> { - const connection = this.connections.get(serverName); - - if (!connection) { - console.warn(`[MCPStore] Server "${serverName}" is not connected`); - - return null; - } - - if (!connection.serverCapabilities?.completions) { - return null; - } - - return MCPService.complete( - connection, - { name: promptName, type: MCPRefType.PROMPT }, - { name: argumentName, value: argumentValue } - ); - } - - /** - * Request timeout in milliseconds, read live from the global setting - * so a change in Settings applies to every server immediately. - */ - getRequestTimeoutMs(): number { - const seconds = - Number(settingsStore.config.mcpRequestTimeoutSeconds) || - DEFAULT_MCP_CONFIG.requestTimeoutSeconds; - - return Math.round(seconds * 1000); - } - - /** - * Get completions for a resource template argument. - * Uses the MCP Completion API with ref/resource. - */ - async getResourceCompletions( - serverName: string, - uriTemplate: string, - argumentName: string, - argumentValue: string - ): Promise<{ values: string[]; total?: number; hasMore?: boolean } | null> { - const connection = this.connections.get(serverName); - - if (!connection) { - console.warn(`[MCPStore] Server "${serverName}" is not connected`); - - return null; - } - - if (!connection.serverCapabilities?.completions) { - return null; - } - - return MCPService.complete( - connection, - { type: MCPRefType.RESOURCE, uri: uriTemplate }, - { name: argumentName, value: argumentValue } - ); - } - - /** - * Get formatted resource context for chat. - */ - getResourceContextForChat(): string { - return mcpResourceStore.formatAttachmentsForContext(); - } - - getServerById(serverId: string): MCPServerSettingsEntry | undefined { - return this.getServers().find((s) => s.id === serverId); - } - - /** - * Get display name for an MCP server by its ID. - * Falls back to the server ID if server is not found. - */ - getServerDisplayName(serverId: string): string { - const server = this.getServerById(serverId); - - return server ? this.getServerLabel(server) : serverId; - } - - /** - * Get icon URL for an MCP server by its ID. - * Returns the best icon from the MCP server's `icons` array - * (see MCP spec: spec.modelcontextprotocol.io). - * Returns null if no icon is available. - */ - getServerFavicon(serverId: string): string | null { - const server = this.getServerById(serverId); - - if (!server) { - return null; - } - - const isDark = mode.current === ColorMode.DARK; - const healthState = this.health.getState(serverId); - - if (healthState.status === HealthCheckStatus.SUCCESS && healthState.serverInfo?.icons) { - const mcpIconUrl = getMcpIconUrl(healthState.serverInfo.icons, isDark); - - if (mcpIconUrl) { - return this.toRenderableIconUrl(mcpIconUrl); - } - } - - return this.toRenderableIconUrl(getMcpServerFaviconFallback(server.url)); - } - - /** - * Resolve the favicon URL for an MCP server by one of its tool names. - * Returns `null` if the tool is not provided by any configured MCP server, - * or if the owning server has no icon to show. - * Pair with {@link getServerFavicon} for direct server-id lookup. - */ - getServerFaviconForTool(toolName: string | undefined): string | null { - if (!toolName) return null; - - const serverId = this.findServerForTool(toolName); - - if (!serverId) return null; - - return this.getServerFavicon(serverId); - } - - /** - * Get aggregated server instructions from all connected servers. - * Returns an array of { serverName, serverTitle, instructions } objects. - */ - getServerInstructions(): Array<{ - serverName: string; - serverTitle?: string; - instructions: string; - }> { - const results: Array<{ serverName: string; serverTitle?: string; instructions: string }> = []; - - for (const [serverName, connection] of this.connections) { - if (connection.instructions) { - results.push({ - instructions: connection.instructions, - serverName, - serverTitle: connection.serverInfo?.title || connection.serverInfo?.name - }); - } - } - - return results; - } - - getServerLabel(server: MCPServerDisplayInfo): string { - return getMcpServerLabel(server, this.getServers(), this.health.checks); - } - - getServers(): MCPServerSettingsEntry[] { - const raw = settingsStore.config.mcpServers; - - // cache the parse: the config string rarely changes and getServers is - // called from hot paths (per-tool display lookups, capability checks) - if (this.serversCache && this.serversCache.raw === raw) { - return this.serversCache.servers; - } - - const servers = parseMcpServerSettings(raw); - - this.serversCache = { raw, servers }; - - return servers; - } - - getServersStatus(): ServerStatus[] { - const statuses: ServerStatus[] = []; - - for (const [name, connection] of this.connections) { - statuses.push({ - error: undefined, - isConnected: true, - name, - toolCount: connection.tools.length - }); - } - - return statuses; - } - - /** - * Get list of enabled servers that support resources. - * Checks active connections first, then health check state as fallback. - */ - getServersWithResources(): string[] { - const enabledServerIds = new Set( - this.getServers() - .filter((s) => s.enabled) - .map((s) => s.id) - ); - const servers: string[] = []; - - for (const [name, connection] of this.connections) { - if (!enabledServerIds.has(name)) continue; - - if (MCPService.supportsResources(connection) && !servers.includes(name)) { - servers.push(name); - } - } - - // Also check health check states for servers not yet connected - for (const [serverId, state] of Object.entries(this.health.checks)) { - if (!enabledServerIds.has(serverId)) continue; - - if ( - !servers.includes(serverId) && - state.status === HealthCheckStatus.SUCCESS && - state.capabilities?.server?.resources !== undefined - ) { - servers.push(serverId); - } - } - - return servers; - } - - getToolNames(): string[] { - return Array.from(this.toolsIndex.keys()); - } - - getToolServer(toolName: string): string | undefined { - return this.toolsIndex.get(toolName); - } - - hasAvailableServers(): boolean { - return parseMcpServerSettings(settingsStore.config.mcpServers).some( - (s) => s.enabled && s.url.trim() - ); - } - - hasEnabledServers(): boolean { - return Boolean(this.buildMcpClientConfig(settingsStore.config)); - } - - /** - * Check if any connected server has instructions. - */ - hasServerInstructions(): boolean { - for (const connection of this.connections.values()) { - if (connection.instructions) { - return true; - } - } - - return false; - } - - hasTool(toolName: string): boolean { - return this.toolsIndex.has(toolName); - } - - /** - * Promote a health check connection to an active connection. - * This avoids the need to reconnect when the server is needed for agentic flows. - */ - promoteHealthCheckToConnection(serverId: string, connection: MCPConnection): void { - this.indexServerTools(serverId, connection.tools); - - this.connections.set(serverId, connection); - - this.updateState({ - connectedServers: Array.from(this.connections.keys()), - toolCount: this.toolsIndex.size - }); - } - - /** - * Read resource content from a server. - * Caches the result in mcpResourceStore. - */ - async readResource(uri: string): Promise { - const cached = mcpResourceStore.getCachedContent(uri); - - if (cached) { - return cached.content; - } - - // Find which server has this resource - const serverName = mcpResourceStore.findServerForUri(uri); - - if (!serverName) { - console.error(`[MCPStore] No server found for resource URI: ${uri}`); - - return null; - } - - const connection = this.connections.get(serverName); - - if (!connection) { - console.error(`[MCPStore] No connection found for server: ${serverName}`); - - return null; - } - - try { - const result = await MCPService.readResource(connection, uri); - const resourceInfo = mcpResourceStore.findResourceByUri(uri); - - if (resourceInfo) { - mcpResourceStore.cacheResourceContent(resourceInfo, result.contents); - } - - return result.contents; - } catch (error) { - console.error(`[MCPStore] Failed to read resource ${uri}:`, error); - - return null; - } - } - - /** - * Read a resource by an arbitrary URI (e.g., one expanded from a template). - * Unlike readResource(), this does not require the URI to be in the resources list. - */ - async readResourceByUri(serverName: string, uri: string): Promise { - const connection = this.connections.get(serverName); - - if (!connection) { - console.error(`[MCPStore] No connection found for server: ${serverName}`); - - return null; - } - - try { - const result = await MCPService.readResource(connection, uri); - - return result.contents; - } catch (error) { - console.error(`[MCPStore] Failed to read resource ${uri}:`, error); - - return null; - } - } - - /** Store a server config so auto-reconnect can rebuild the session. */ - registerServerConfig(name: string, config: MCPServerConfig): void { - this.serverConfigs.set(name, config); - } - - /** - * Release a connection reference. - * By default, keeps connections alive for reuse (shutdownIfUnused=false). - * MCP spec encourages long-lived sessions to avoid reconnection overhead. - */ - async releaseConnection(shutdownIfUnused = false): Promise { - this.activeFlowCount = Math.max(0, this.activeFlowCount - 1); - - if (shutdownIfUnused && this.activeFlowCount === 0) { - await this.shutdown(); - } - } - - /** - * Drop a connection without disconnecting, e.g. when a health check finds - * it stale and recreates it. - */ - removeConnection(serverId: string): void { - this.connections.delete(serverId); - } - - /** - * Remove a resource attachment from chat context. - */ - removeResourceAttachment(attachmentId: string): void { - mcpResourceStore.removeAttachment(attachmentId); - } - - removeServer(id: string): void { - const servers = this.getServers(); - - settingsStore.updateConfig( - SETTINGS_KEYS.MCP_SERVERS, - JSON.stringify(servers.filter((s) => s.id !== id)) - ); - this.clearHealthCheck(id); - } - - async runHealthCheck(server: HealthCheckParams, promoteToActive = false): Promise { - return this.health.run(server, promoteToActive); - } - - async runHealthChecksForServers( - servers: { - id: string; - enabled: boolean; - url: string; - headers?: string; - }[], - skipIfChecked = true, - promoteToActive = false - ): Promise { - return this.health.runForServers(servers, skipIfChecked, promoteToActive); - } - - async shutdown(): Promise { - if (this.initPromise) { - await this.initPromise.catch(() => {}); - this.initPromise = null; - } - - if (this.connections.size === 0) { - return; - } - - await Promise.all( - Array.from(this.connections.values()).map((conn) => - MCPService.disconnect(conn).catch((error) => - console.warn(`[MCPStore] Error disconnecting ${conn.serverName}:`, error) - ) - ) - ); - - this.connections.clear(); - this.toolsIndex.clear(); - this.serverConfigs.clear(); - this.configSignature = null; - this.updateState({ - connectedServers: [], - error: null, - isInitializing: false, - toolCount: 0 - }); - } - - /** - * Subscribe to resource updates. - */ - async subscribeToResource(uri: string): Promise { - const serverName = mcpResourceStore.findServerForUri(uri); - - if (!serverName) { - console.error(`[MCPStore] No server found for resource URI: ${uri}`); - - return false; - } - - const connection = this.connections.get(serverName); - - if (!connection) { - console.error(`[MCPStore] No connection found for server: ${serverName}`); - - return false; - } - - if (!MCPService.supportsResourceSubscriptions(connection)) { - return false; - } - - try { - await MCPService.subscribeResource(connection, uri); - mcpResourceStore.addSubscription(uri, serverName); - - return true; - } catch (error) { - console.error(`[MCPStore] Failed to subscribe to resource ${uri}:`, error); - - return false; - } - } - - /** - * Unsubscribe from resource updates. - */ - async unsubscribeFromResource(uri: string): Promise { - const serverName = mcpResourceStore.findServerForUri(uri); - - if (!serverName) { - console.error(`[MCPStore] No server found for resource URI: ${uri}`); - - return false; - } - - const connection = this.connections.get(serverName); - - if (!connection) { - console.error(`[MCPStore] No connection found for server: ${serverName}`); - - return false; - } - - try { - await MCPService.unsubscribeResource(connection, uri); - mcpResourceStore.removeSubscription(uri); - - return true; - } catch (error) { - console.error(`[MCPStore] Failed to unsubscribe from resource ${uri}:`, error); - - return false; - } - } - - updateServer(id: string, updates: Partial): void { - const servers = this.getServers(); - - settingsStore.updateConfig( - SETTINGS_KEYS.MCP_SERVERS, - JSON.stringify( - servers.map((server) => (server.id === id ? { ...server, ...updates } : server)) - ) - ); - } - - /** - * Builds MCP client configuration from settings. - */ - private buildMcpClientConfig(cfg: SettingsConfigType): MCPClientConfig | undefined { - const rawServers = parseMcpServerSettings(cfg.mcpServers); - - if (!rawServers.length) { - return undefined; - } - - const servers: Record = {}; - - for (const [index, entry] of rawServers.entries()) { - if (!entry.enabled) continue; - - const normalized = this.buildServerConfig(entry); - - if (normalized) servers[this.generateServerId(entry.id, index)] = normalized; - } - - if (Object.keys(servers).length === 0) { - return undefined; - } - - return { - capabilities: DEFAULT_MCP_CONFIG.capabilities, - clientInfo: DEFAULT_MCP_CONFIG.clientInfo, - protocolVersion: DEFAULT_MCP_CONFIG.protocolVersion, - requestTimeoutMs: this.getRequestTimeoutMs(), - servers - }; - } - - /** - * Builds server configuration from a settings entry. - */ - private buildServerConfig( - entry: MCPServerSettingsEntry, - connectionTimeoutMs = DEFAULT_MCP_CONFIG.connectionTimeoutMs - ): MCPServerConfig | undefined { - if (!entry?.url) { - return undefined; - } - - let headers: Record | undefined; - - if (entry.headers) { - try { - const parsed = JSON.parse(entry.headers); - - if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) - headers = parsed as Record; - } catch { - console.warn('[MCP] Failed to parse custom headers JSON:', entry.headers); - } - } - - return { - handshakeTimeoutMs: connectionTimeoutMs, - headers, - requestTimeoutMs: this.getRequestTimeoutMs(), - transport: detectMcpTransportFromUrl(entry.url), - url: entry.url, - useProxy: entry.useProxy - }; - } - - private createListChangedHandlers(serverName: string): ListChangedHandlers { - return { - prompts: { - onChanged: (error: Error | null) => { - if (error) { - console.warn(`[MCPStore][${serverName}] Prompts list changed error:`, error); - - return; - } - } - }, - tools: { - onChanged: (error: Error | null, tools: Tool[] | null) => { - if (error) { - console.warn(`[MCPStore][${serverName}] Tools list changed error:`, error); - - return; - } - - this.handleToolsListChanged(serverName, tools ?? []); - } - } - }; - } - - private async doInitialize( - signature: string, - mcpConfig: MCPClientConfig, - serverEntries: [string, MCPClientConfig['servers'][string]][] - ): Promise { - const clientInfo = mcpConfig.clientInfo ?? DEFAULT_MCP_CONFIG.clientInfo; - const capabilities = mcpConfig.capabilities ?? DEFAULT_MCP_CONFIG.capabilities; - const results = await Promise.allSettled( - serverEntries.map(async ([name, serverConfig]) => { - this.serverConfigs.set(name, serverConfig); - - const listChangedHandlers = this.createListChangedHandlers(name); - const connection = await MCPService.connect( - name, - serverConfig, - clientInfo, - capabilities, - (phase) => { - if (phase === MCPConnectionPhase.DISCONNECTED) { - console.log(`[MCPStore][${name}] Connection lost, starting auto-reconnect`); - this.autoReconnect(name); - } - }, - listChangedHandlers - ); - - return { connection, name }; - }) - ); - - if (this.configSignature !== signature) { - for (const result of results) { - if (result.status === 'fulfilled') - await MCPService.disconnect(result.value.connection).catch(console.warn); - } - - return false; - } - - for (const result of results) { - if (result.status === 'fulfilled') { - const { connection, name } = result.value; - - this.connections.set(name, connection); - - this.indexServerTools(name, connection.tools); - } else { - console.error(`[MCPStore] Failed to connect:`, result.reason); - } - } - - const successCount = this.connections.size; - - if (successCount === 0 && serverEntries.length > 0) { - this.updateState({ - connectedServers: [], - error: 'All MCP server connections failed', - isInitializing: false, - toolCount: 0 - }); - this.initPromise = null; - - return false; - } - - this.updateState({ - connectedServers: Array.from(this.connections.keys()), - error: null, - isInitializing: false, - toolCount: this.toolsIndex.size - }); - this.initPromise = null; - - return true; - } - - /** - * Generates a unique server ID from an optional ID string or index. - */ - private generateServerId(id: unknown, index: number): string { - if (typeof id === 'string' && id.trim()) { - return id.trim(); - } - - return `${MCP_SERVER_ID_PREFIX}-${index + 1}`; - } - - /** Server ids that are usable right now: globally enabled ones. */ - private globalEnabledServerIds(): Set { - return new Set( - this.getServers() - .filter((s) => s.enabled) - .map((s) => s.id) - ); - } - - private handleToolsListChanged(serverName: string, tools: Tool[]): void { - const connection = this.connections.get(serverName); - - if (!connection) { - return; - } - - for (const [toolName, ownerServer] of this.toolsIndex.entries()) { - if (ownerServer === serverName) this.toolsIndex.delete(toolName); - } - - connection.tools = tools; - - for (const tool of tools) { - if (this.toolsIndex.has(tool.name)) - console.warn( - `[MCPStore] Tool name conflict after list change: "${tool.name}" exists in "${this.toolsIndex.get(tool.name)}" and "${serverName}". Using tool from "${serverName}".` - ); - - this.toolsIndex.set(tool.name, serverName); - } - this.updateState({ toolCount: this.toolsIndex.size }); - } - - /** - * Registers the tools exposed by a server into the global name->server index, - * warning on conflicts. Shared by connect, reconnect and auto-reconnect. - */ - private indexServerTools(serverName: string, tools: Tool[]): void { - for (const tool of tools) { - if (this.toolsIndex.has(tool.name)) - console.warn( - `[MCPStore] Tool name conflict: "${tool.name}" exists in "${this.toolsIndex.get(tool.name)}" and "${serverName}". Using tool from "${serverName}".` - ); - - this.toolsIndex.set(tool.name, serverName); - } - } - - private async initialize(signature: string, mcpConfig: MCPClientConfig): Promise { - this.updateState({ error: null, isInitializing: true }); - this.configSignature = signature; - - const serverEntries = Object.entries(mcpConfig.servers); - - if (serverEntries.length === 0) { - this.updateState({ connectedServers: [], isInitializing: false, toolCount: 0 }); - - return false; - } - - this.initPromise = this.doInitialize(signature, mcpConfig, serverEntries); - - return this.initPromise; - } - - private parseToolArguments(args: string | Record): Record { - if (typeof args === 'string') { - const trimmed = args.trim(); - - if (trimmed === '') { - return {}; - } - - try { - const parsed = JSON.parse(trimmed); - - if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) - throw new Error( - `Tool arguments must be an object, got ${Array.isArray(parsed) ? 'array' : typeof parsed}` - ); - - return parsed as Record; - } catch (error) { - throw new Error(`Failed to parse tool arguments as JSON: ${(error as Error).message}`); - } - } - - if (typeof args === 'object' && args !== null && !Array.isArray(args)) { - return args; - } - - throw new Error(`Invalid tool arguments type: ${typeof args}`); - } - - /** - * Immediately reconnect to a server by creating a fresh transport and session. - * Used when a session-expired error (HTTP 404) is detected during tool execution. - * Per MCP spec 2025-11-25: client MUST discard session ID and re-initialize. - * - * Unlike autoReconnect (which uses exponential backoff for connectivity issues), - * this performs a single immediate reconnection attempt since the server is known - * to be reachable (it responded with 404). - */ - private async reconnectServer(serverName: string): Promise { - const serverConfig = this.serverConfigs.get(serverName); - - if (!serverConfig) { - throw new Error(`[MCPStore] No config found for ${serverName}, cannot reconnect`); - } - - // Disconnect stale connection (clears old transport + session ID) - const oldConnection = this.connections.get(serverName); - - if (oldConnection) { - await MCPService.disconnect(oldConnection).catch(console.warn); - this.connections.delete(serverName); - } - - console.log(`[MCPStore][${serverName}] Session expired, reconnecting with fresh session...`); - - const listChangedHandlers = this.createListChangedHandlers(serverName); - const connection = await MCPService.connect( - serverName, - serverConfig, - DEFAULT_MCP_CONFIG.clientInfo, - DEFAULT_MCP_CONFIG.capabilities, - (phase) => { - if (phase === MCPConnectionPhase.DISCONNECTED) { - console.log(`[MCPStore][${serverName}] Connection lost, starting auto-reconnect`); - this.autoReconnect(serverName); - } - }, - listChangedHandlers - ); - - this.connections.set(serverName, connection); - this.indexServerTools(serverName, connection.tools); - - console.log(`[MCPStore][${serverName}] Session recovered successfully`); - } - - /** - * Icons come from the MCP server's own origin, which the browser cannot load - * under the UI's cross-origin isolation. With the proxy enabled the server - * fetches them instead; data URLs need no help and stay as they are. - */ - private toRenderableIconUrl(iconUrl: string | null): string | null { - return buildProxiedIconUrl(iconUrl, this.isProxyAvailable); - } - - private updateState(state: { - isInitializing?: boolean; - error?: string | null; - toolCount?: number; - connectedServers?: string[]; - }): void { - if (state.isInitializing !== undefined) { - this._isInitializing = state.isInitializing; - } - - if (state.error !== undefined) { - this._error = state.error; - } - - if (state.toolCount !== undefined) { - this._toolCount = state.toolCount; - } - - if (state.connectedServers !== undefined) { - this.connectedServers = state.connectedServers; - } - } -} - -export const mcpStore = new MCPStore(); diff --git a/tools/ui/src/lib/stores/models-discover/index.svelte.ts b/tools/ui/src/lib/stores/models-discover/index.svelte.ts deleted file mode 100644 index 9742ab6498a7..000000000000 --- a/tools/ui/src/lib/stores/models-discover/index.svelte.ts +++ /dev/null @@ -1,284 +0,0 @@ -/** - * modelsDiscoverStore - Models Discover browse state - * - * Owns the HuggingFace GGUF list shown in the discover sidebar. The default list is - * the curated catalog set; a search replaces it with matches across all of HuggingFace. - * Both paths fetch the same fields, so a row renders the same either way. - */ - -import { MODELS_DISCOVER_CATALOG_BATCH } from '$lib/constants'; -import { HuggingFaceService } from '$lib/services'; -import type { - HfCatalogBuild, - HfCatalogEntry, - HfModelInfo, - HfModelSibling -} from '$lib/types/huggingface'; -import { isAuxSidecar, orgOf } from '$lib/utils'; -import { SvelteMap } from 'svelte/reactivity'; - -/** Min/max GGUF file size (bytes) across the quants of one repo. */ -export interface ModelsDiscoverSizeRange { - max: number; - min: number; -} - -class ModelsDiscoverStore { - error = $state(null); - models = $state([]); - /** First model in the list - discover auto-opens this one. */ - firstModel = $derived(this.models[0] ?? null); - - loading = $state(false); - /** True while a search is in flight; only the newest request owns this flag. */ - searching = $state(false); - - private catalog: HfCatalogEntry[] = []; - /** Repo id -> size range, for catalog rows and lazily measured search rows. */ - private catalogSizeRanges = new SvelteMap(); - private defaultModels: HfModelInfo[] = []; - private fetched = false; - private searchRequestId = 0; - /** In-flight `sizeRange()` lookups, keyed by repo id. */ - private sizeRangePending = new Map>(); - - /** - * Cached size range for a repo, without measuring: the synchronous part of - * `sizeRange()`, for rendering a row before its measurement resolves. - */ - cachedSizeRangeFor(modelId: string): ModelsDiscoverSizeRange | undefined { - return this.catalogSizeRanges.get(modelId); - } - - /** Catalog family description; undefined for a repo outside the curated catalog. */ - descriptionFor(modelId: string): string | undefined { - return this.catalog.find((entry) => - entry.sizes.some((size) => size.builds.some((build) => build.repo === modelId)) - )?.description; - } - - /** - * Fill the list from the llama.app catalog, one repo per catalog size. Every repo - * is fetched with its file tree, so a catalog row carries the same data a search - * result does. No-op when already loaded or in flight. - */ - async fetch(): Promise { - if (this.loading || this.fetched) return; - - this.loading = true; - this.error = null; - - try { - const catalog = await HuggingFaceService.getCatalog(); - - this.catalog = catalog; - - const builds = this.catalogBuilds(); - const failedBuilds: HfCatalogBuild[] = []; - - this.defaultModels = []; - - // fetch in small batches: not every repo hits the HF API at once, - // and the rows land as they arrive instead of all at the end - for (let i = 0; i < builds.length; i += MODELS_DISCOVER_CATALOG_BATCH) { - const batch = await Promise.all( - builds.slice(i, i + MODELS_DISCOVER_CATALOG_BATCH).map(async (build) => { - const [info, tree] = await Promise.all([ - HuggingFaceService.getDetails(build.repo), - HuggingFaceService.getTree(build.repo) - ]); - - return { build, info, tree }; - }) - ); - - for (const { build, info, tree } of batch) { - if (!info) { - failedBuilds.push(build); - - continue; - } - - this.catalogSizeRanges.set(build.repo, this.sizeRangeFor(build, tree)); - - // the catalog repo id, not the HF response `id`, drives selection - this.defaultModels.push({ ...info, id: build.repo, modelId: build.repo }); - } - - // show what has landed, unless a search owns the list right now - if (!this.searching) { - this.models = [...this.defaultModels]; - } - } - - // stay incomplete when some repos failed, so the next mount retries - // them; succeeded repos are served from the service cache for free - this.fetched = failedBuilds.length === 0; - } catch (err) { - this.error = err instanceof Error ? err.message : 'Failed to fetch models'; - } finally { - this.loading = false; - } - } - - /** Replace the list with search results; an empty query restores the default list. */ - async search(query: string): Promise { - const trimmed = query.trim(); - const requestId = ++this.searchRequestId; - - if (!trimmed) { - this.searching = false; - this.models = this.defaultModels; - this.error = null; - - return; - } - - this.searching = true; - - try { - const results = await HuggingFaceService.searchByQuery(trimmed, { limit: 50 }); - - if (requestId !== this.searchRequestId) return; - - this.models = this.baseOrgFirst(results); - this.error = null; - } catch (err) { - if (requestId !== this.searchRequestId) return; - - this.error = err instanceof Error ? err.message : 'Search failed'; - } finally { - if (requestId === this.searchRequestId) this.searching = false; - } - } - - /** - * Size range for a repo not measured yet, fetched once and cached: a search result - * never goes through fetch(), and a row can be remounted while scrolling. - */ - sizeRange(modelId: string): Promise { - const cached = this.catalogSizeRanges.get(modelId); - - if (cached) return Promise.resolve(cached); - - const pending = this.sizeRangePending.get(modelId); - - if (pending) return pending; - - const request = (async () => { - const tree = await HuggingFaceService.getTree(modelId); - const range = this.sizeRangeOfMainQuants(tree); - - if (range) this.catalogSizeRanges.set(modelId, range); - - return range; - })() - .catch(() => undefined) - .finally(() => this.sizeRangePending.delete(modelId)); - - this.sizeRangePending.set(modelId, request); - - return request; - } - - /** - * Repos published by their base model's own org first (e.g. `Qwen/Qwen3-8B-GGUF` - * ahead of third-party quants of `Qwen/Qwen3-8B`); the hub's order holds otherwise. - */ - private baseOrgFirst(models: HfModelInfo[]): HfModelInfo[] { - // org names are case-insensitive on the hub, and base_model tags are not always canonical - const isBaseOrg = (model: HfModelInfo) => { - const org = orgOf(model.id).toLowerCase(); - - return HuggingFaceService.getBaseModels(model).some( - (base) => orgOf(base).toLowerCase() === org - ); - }; - - return [...models.filter(isBaseOrg), ...models.filter((model) => !isBaseOrg(model))]; - } - - /** - * Sizes the catalog lists under this repo. Never empty: an entry with no parsable - * size contributes the build's own. - */ - private buildSizeBytes(build: HfCatalogBuild): number[] { - const sizes = this.catalog - .flatMap((entry) => entry.sizes) - .flatMap((size) => size.builds.filter((b) => b.repo === build.repo)) - .map((b) => b.sizeBytes ?? HuggingFaceService.parseSizeBytes(b.size)) - .filter((bytes): bytes is number => Boolean(bytes) && bytes > 0); - - return sizes.length > 0 ? sizes : [build.sizeBytes ?? 0]; - } - - /** - * One build per catalog size, newest family first. Prefers the official ggml-org - * repo, else the first build, so repos of other orgs are covered too. - */ - private catalogBuilds(): HfCatalogBuild[] { - return [...this.catalog] - .sort((a, b) => b.released.localeCompare(a.released)) - .flatMap((entry) => - entry.sizes.flatMap((size) => { - const build = size.builds.find((b) => b.repo.startsWith('ggml-org/')) ?? size.builds[0]; - - return build ? [build] : []; - }) - ); - } - - /** Byte sizes of every non-sidecar quant file in a tree, shards collapsed. */ - private quantSizesOf(tree: HfModelSibling[]): number[] { - return HuggingFaceService.collapseGgufShards( - HuggingFaceService.filterByExtension(tree, '.gguf') - ) - .filter((f) => { - const { quant, sidecar } = HuggingFaceService.extractQuantMeta(f.path) ?? {}; - - return Boolean(quant) && (sidecar === null || sidecar === undefined); - }) - .map((f) => f.size ?? 0) - .filter((size) => size > 0); - } - - /** - * Size range of one catalog build, draft sidecars included so the range covers what - * gets downloaded. Falls back to the catalog's own sizes when the tree yielded nothing. - */ - private sizeRangeFor(build: HfCatalogBuild, tree: HfModelSibling[]): ModelsDiscoverSizeRange { - const quantSizes = this.quantSizesOf(tree); - - if (quantSizes.length === 0) { - const listed = this.buildSizeBytes(build); - - return { max: Math.max(...listed), min: Math.min(...listed) }; - } - - const draftSizes = tree - .filter((f) => { - const sidecar = HuggingFaceService.extractQuantMeta(f.path)?.sidecar; - - return sidecar !== null && sidecar !== undefined && !isAuxSidecar(sidecar); - }) - .map((f) => f.size ?? 0) - .filter((size) => size > 0); - const extra = draftSizes.length > 0 ? Math.max(...draftSizes) : 0; - - return { - max: Math.max(...quantSizes) + extra, - min: Math.min(...quantSizes) + (draftSizes.length > 0 ? Math.min(...draftSizes) : 0) - }; - } - - /** Size range across the main-model quants of a tree, draft sidecars excluded. */ - private sizeRangeOfMainQuants(tree: HfModelSibling[]): ModelsDiscoverSizeRange | undefined { - const sizes = this.quantSizesOf(tree); - - if (sizes.length === 0) return undefined; - - return { max: Math.max(...sizes), min: Math.min(...sizes) }; - } -} - -export const modelsDiscoverStore = new ModelsDiscoverStore(); diff --git a/tools/ui/src/lib/stores/models/index.svelte.ts b/tools/ui/src/lib/stores/models/index.svelte.ts deleted file mode 100644 index 990bcf8e898b..000000000000 --- a/tools/ui/src/lib/stores/models/index.svelte.ts +++ /dev/null @@ -1,771 +0,0 @@ -/** - * modelsStore - Model management for MODEL and ROUTER modes - * - * Owns model lists, selection, favorites and load/unload state. Composes the - * per-model props cache (modalities, thinking detection) as - * {@link ModelsStore.props} and the /models/sse status feed as - * {@link ModelsStore.status}; tracks which conversations use which models. - */ - -import { browser } from '$app/environment'; -import { - FAVORITE_MODELS_LOCALSTORAGE_KEY, - HIDDEN_MODELS_LOCALSTORAGE_KEY, - MODEL_GROUP_OPEN_LOCALSTORAGE_KEY, - MODEL_REMOVE_BLOCKED_FALLBACK, - MODEL_REMOVE_BLOCKED_REASONS, - RECENT_MODEL_LIMIT, - RECENT_MODELS_LOCALSTORAGE_KEY -} from '$lib/constants'; -import { ReasoningEffort, ServerModelSource, ServerModelStatus } from '$lib/enums'; -import { HuggingFaceService } from '$lib/services/huggingface.service'; -import { ModelsService } from '$lib/services/models.service'; -// direct imports between stores, not via the barrel, to avoid circular deps -import { conversationsStore } from '$lib/stores/conversations/index.svelte'; -import { type ModelPropsHost, ModelPropsManager } from '$lib/stores/models/props.svelte'; -import { type ModelStatusHost, ModelStatusManager } from '$lib/stores/models/status.svelte'; -import { serverStore } from '$lib/stores/server.svelte'; -import type { ApiModelDataEntry } from '$lib/types'; -import type { ParsedModelId } from '$lib/types/models'; -import { getConversationModel } from '$lib/utils/conversation-utils'; -import { repoOf } from '$lib/utils/model-names'; -import { SvelteMap, SvelteSet } from 'svelte/reactivity'; -import { toast } from 'svelte-sonner'; - -/** Group open states kept before the oldest ones fall off; the map only ever grows. */ -const MAX_GROUP_OPEN_ENTRIES = 200; -/** - * Repos whose Hub details are prefetched on load. The Hub rate limits an - * unauthenticated client aggressively, so the warm slice stays far below the - * list window and the rest of the rows fetch as they scroll near the viewport. - */ -const HUB_WARM_LIMIT = 12; - -/** Models kept out of the selector. */ -function loadHiddenModels(): Set { - if (!browser) return new SvelteSet(); - - try { - const raw = localStorage.getItem(HIDDEN_MODELS_LOCALSTORAGE_KEY); - - return raw ? new SvelteSet(JSON.parse(raw) as string[]) : new SvelteSet(); - } catch { - return new SvelteSet(); - } -} - -/** Open state the user set for a section or family of the model lists. */ -function loadGroupOpenState(): SvelteMap { - if (!browser) return new SvelteMap(); - - try { - const raw = localStorage.getItem(MODEL_GROUP_OPEN_LOCALSTORAGE_KEY); - const parsed = raw ? (JSON.parse(raw) as unknown) : null; - const entries = - parsed && typeof parsed === 'object' ? Object.entries(parsed as Record) : []; - - return new SvelteMap( - entries.filter((entry): entry is [string, boolean] => typeof entry[1] === 'boolean') - ); - } catch { - return new SvelteMap(); - } -} - -/** Recently used backend-qualified ids, most recent first. */ -function loadRecentModels(): string[] { - if (!browser) return []; - - try { - const raw = localStorage.getItem(RECENT_MODELS_LOCALSTORAGE_KEY); - - if (!raw) return []; - - const parsed = JSON.parse(raw) as unknown; - - return Array.isArray(parsed) - ? parsed.filter((id): id is string => typeof id === 'string').slice(0, RECENT_MODEL_LIMIT) - : []; - } catch { - return []; - } -} - -class ModelsStore implements ModelPropsHost, ModelStatusHost { - error = $state(null); - favoriteModelIds = $state>(this.loadFavoritesFromStorage()); - groupOpenState = $state>(loadGroupOpenState()); - hiddenModelIds = $state>(loadHiddenModels()); - loading = $state(false); - models = $state([]); - recentModelIds = $state(loadRecentModels()); - routerModels = $state([]); - selectedModelId = $state(null); - selectedModelName = $state(null); - - updating = $state(false); - - /** Per-model props cache, modalities and thinking detection, composed here. */ - private _props = new ModelPropsManager(this); - - /** Load/unload operations and the /models/sse status feed, composed here. */ - private _status = new ModelStatusManager(this); - - // every caller awaits the same inflight promise - // Without this, ?model= URL handler races an in-progress fetch and sees an empty list. - private inflightFetch: Promise | null = null; - - /** - * Model the active conversation view resolves to. Router mode: the user's - * selection first, then the conversation's own model. Otherwise the single - * served model, from the models list or the server props as a fallback. - */ - get activeModelId(): string | null { - if (!serverStore.isRouterMode) { - return this.models.length > 0 ? this.models[0].model : this.singleModelName; - } - - if (this.selectedModelId) { - const selected = this.models.find((m) => m.id === this.selectedModelId); - - if (selected) return selected.model; - } - - const conversationModel = getConversationModel(conversationsStore.activeMessages); - - if (conversationModel) { - const model = this.models.find((m) => m.model === conversationModel); - - if (model) return model.model; - } - - return null; - } - - get loadedModelIds(): string[] { - return this.routerModels - .filter( - (m) => - m.status.value === ServerModelStatus.LOADED || - m.status.value === ServerModelStatus.SLEEPING - ) - .map((m) => m.id); - } - - get props() { - return this._props; - } - - get selectedModel(): ModelOption | null { - if (!this.selectedModelId) return null; - - return this.models.find((m) => m.id === this.selectedModelId) ?? null; - } - - get selectedModelContextSize(): number | null { - if (!this.selectedModelName) return null; - - return this.props.getModelContextSize(this.selectedModelName); - } - - /** - * Get model name in MODEL mode (single model). - * Extracts from model_path or model_alias from server props. - * In ROUTER mode, returns null (model is per-conversation). - */ - get singleModelName(): string | null { - if (serverStore.isRouterMode) return null; - - const props = serverStore.props; - - if (props?.model_alias) return props.model_alias; - - if (!props?.model_path) return null; - - return props.model_path.split(/(\\|\/)/).pop() || null; - } - - get status() { - return this._status; - } - - clearSelection(): void { - this.selectedModelId = null; - this.selectedModelName = null; - } - - /** Family keys folded away under one section, for a list that restores them. */ - collapsedGroupsUnder(prefix: string): string[] { - const head = `${prefix}-`; - - return [...this.groupOpenState] - .filter(([id, open]) => !open && id.startsWith(head)) - .map(([id]) => id.slice(head.length)); - } - - /** - * Auto-selects the first available model if none is selected. - * Prioritizes: - * 1. Model from active conversation's last assistant response (if loaded) - * 2. Model from active conversation's last assistant response (if not loaded) - * 3. A model that is loading - * 4. First loaded model (not from active conversation) - * 5. A favorite model - * 6. First available model - * - * A chat without a model of its own also trades an idle selection for a - * model that is loading. - */ - async ensureFirstModelSelected(): Promise { - if (this.selectedModelName) { - const loadingModel = this.getLoadingModelToPreselect(); - - if (loadingModel) await this.selectModelById(loadingModel.id); - - return; - } - - const availableModels = this.getVisibleModels(); - - if (availableModels.length === 0) return; - - // Try to select model from last assistant response first - const lastModel = this.getModelFromLastAssistantResponse(); - - if (lastModel) { - const lastModelOption = availableModels.find((m) => m.model === lastModel); - - if (lastModelOption) { - await this.selectModelById(lastModelOption.id); - - if (this.isModelLoaded(lastModel)) { - await this.props.fetchModelProps(lastModel); - } - - return; - } - } - - // a model that is loading is the one the user is waiting for - const loadingModel = availableModels.find((m) => this.isModelLoading(m.model)); - - if (loadingModel) { - await this.selectModelById(loadingModel.id); - - return; - } - - // Try a loaded model first - const loadedModel = availableModels.find((m) => this.isModelLoaded(m.model)); - - if (loadedModel) { - await this.selectModelById(loadedModel.id); - await this.props.fetchModelProps(loadedModel.model); - - return; - } - - // favorites are shared across backends, so a stored id may belong to another one - const favorite = this.favoriteModelIds.values().next()?.value; - const favoriteOption = favorite - ? availableModels.find((m) => m.id === favorite || m.model === favorite) - : undefined; - - if (favoriteOption) { - await this.selectModelById(favoriteOption.id); - - return; - } - - // Fall back to the first available model - await this.selectModelById(availableModels[0].id); - } - - /** - * Fetch list of models from server and detect server role. - * Also fetches modalities for MODEL mode (single model). - */ - async fetch(force = false): Promise { - if (this.inflightFetch) return this.inflightFetch; - - if (this.models.length > 0 && !force) return; - - this.inflightFetch = this.runFetch(); - try { - await this.inflightFetch; - } finally { - this.inflightFetch = null; - } - } - - /** - * Fetch models with full metadata (ROUTER mode only). - * No-op in MODEL mode - fetch() already calls list() internally. - * Kept for API compatibility (e.g. handleOpenChange dropdown open handler). - */ - async fetchRouterModels(): Promise { - if (!serverStore.isRouterMode) return; - - try { - const response = await ModelsService.list(); - - this.routerModels = response.data; - // a download an earlier run left unfinished is listed as incomplete, and - // is offered as paused until it is resumed - this._status.syncPausedDownloads(); - // keep the selector options in sync: a downloaded / deleted model shows - // up here too, not only in the router model rows - this.models = this.buildModelOptions(response); - this.warmHubDetails(); - await this.props.fetchModalitiesForLoadedModels(); - - const visible = this.getVisibleModels(); - - if (visible.length === 1 && this.isModelLoaded(visible[0].model)) { - this.selectModelById(visible[0].id); - } - } catch (error) { - console.warn('Failed to fetch router models:', error); - this.routerModels = []; - } - } - - findModelById(modelId: string): ModelOption | null { - return this.models.find((model) => model.id === modelId) ?? null; - } - - findModelByName(modelName: string): ModelOption | null { - return ( - this.models.find( - (model) => - model.model === modelName || model.id === modelName || model.aliases?.includes(modelName) - ) ?? null - ); - } - - /** - * The loading model a chat without a model of its own should switch to: none - * while the current selection is loaded or loading itself. - */ - getLoadingModelToPreselect(): ModelOption | null { - if (this.getModelFromLastAssistantResponse()) return null; - - const selected = this.selectedModelName; - - if (selected && (this.isModelLoaded(selected) || this.isModelLoading(selected))) return null; - - return this.getVisibleModels().find((m) => this.isModelLoading(m.model)) ?? null; - } - - /** - * Gets the model name from the last assistant message in the active conversation. - * Used by both the chat page and settings page to maintain model consistency. - */ - getModelFromLastAssistantResponse(): string | null { - const messages = conversationsStore.activeMessages; - - if (!messages || messages.length === 0) return null; - - for (let i = messages.length - 1; i >= 0; i--) { - if (messages[i].model) { - return messages[i].model; - } - } - - return null; - } - - getModelStatus(modelId: string): ServerModelStatus | null { - const model = this.routerModels.find((m) => m.id === modelId); - - return (model?.status?.value as ServerModelStatus) ?? null; - } - - /** - * Models the selector lists: not flagged out of the UI (ui === false) and not - * hidden by the user, so an automatic pick never lands on one it doesn't show. - */ - getVisibleModels(): ModelOption[] { - return this.models.filter( - (option) => this.props.getModelProps(option.model)?.ui !== false && !this.isHidden(option.id) - ); - } - - hasModel(modelName: string): boolean { - return this.models.some((model) => model.model === modelName); - } - - isFavorite(modelId: string): boolean { - return this.favoriteModelIds.has(modelId); - } - - isGroupOpen(id: string, fallbackOpen: boolean): boolean { - return this.groupOpenState.get(id) ?? fallbackOpen; - } - - isHidden(modelId: string): boolean { - return this.hiddenModelIds.has(modelId); - } - - isModelLoaded(modelId: string): boolean { - const status = this.getModelStatus(modelId); - - return status === ServerModelStatus.LOADED || status === ServerModelStatus.SLEEPING; - } - - /** Loading on the server, or a load this client started that has not finished yet. */ - isModelLoading(modelId: string): boolean { - // an unload raises the same in-progress flag, but the model stays loaded until it ends - return ( - this.getModelStatus(modelId) === ServerModelStatus.LOADING || - (this._status.isOperationInProgress(modelId) && !this.isModelLoaded(modelId)) - ); - } - - /** Loaded, or sleeping, and not mid-operation: what a row shows as running. */ - isModelRunning(modelId: string): boolean { - return this.isModelLoaded(modelId) && !this._status.isOperationInProgress(modelId); - } - - /** - * Why the router would refuse to delete a model from disk, or null when it can. - * Only a model from the HF cache is removable; a server that does not report - * `can_remove` is let through and answers for itself. - */ - removeBlockedReason(modelId: string): string | null { - const model = this.routerModels.find((m) => m.id === modelId); - - if (!model || model.can_remove !== false) return null; - - if (model.source && model.source !== ServerModelSource.CACHE) { - return MODEL_REMOVE_BLOCKED_REASONS[model.source]; - } - - return MODEL_REMOVE_BLOCKED_FALLBACK; - } - - /** - * Select a model. `recordRecent` keeps automatic picks out of the recency list. - */ - async selectModelById(modelId: string, options?: { recordRecent?: boolean }): Promise { - if (!modelId || this.updating) return; - - if (this.selectedModelId === modelId) { - if (options?.recordRecent) this.recordRecentModel(modelId); - - return; - } - - const option = this.models.find((model) => model.id === modelId); - - if (!option) throw new Error('Selected model is not available'); - - this.updating = true; - this.error = null; - - try { - this.selectedModelId = option.id; - this.selectedModelName = option.model; - - if (options?.recordRecent) this.recordRecentModel(modelId); - - // reasoning levels belong to the model that answered: another model in the chat starts at Default - const conversationModel = getConversationModel(conversationsStore.activeMessages); - - if (conversationModel && conversationModel !== option.model) { - void conversationsStore.preferences.setReasoningEffort(ReasoningEffort.DEFAULT); - } - } finally { - this.updating = false; - } - } - - /** - * Select a model by its model name (used for syncing with conversation model). - */ - selectModelByName(modelName: string): void { - const option = this.models.find((model) => model.model === modelName); - - if (option) { - // the updating guard inside selectModelById cannot refuse this call: that - // call is the only one that raises the flag, and it clears it before it returns - void this.selectModelById(option.id); - } - } - - /** - * Auto-selects the model from the last assistant response if available and loaded, - * or a loading model when the conversation has no model yet. - * Returns true if a model was selected, false otherwise. - */ - async selectModelFromLastAssistantResponse(): Promise { - const lastModel = this.getModelFromLastAssistantResponse(); - - if (!lastModel) { - const loadingModel = this.getLoadingModelToPreselect(); - - if (!loadingModel) return false; - - await this.selectModelById(loadingModel.id); - - return true; - } - - if (this.selectedModelName === lastModel) return false; - - const matchingModel = this.models.find((option) => option.model === lastModel); - - if (!matchingModel || !this.isModelLoaded(lastModel)) return false; - - try { - await this.selectModelById(matchingModel.id); - console.log(`[modelsStore] Automatically selected model: ${lastModel} from last message`); - - return true; - } catch (error) { - console.warn('[modelsStore] Failed to automatically select model from last message:', error); - - return false; - } - } - - /** Add or remove several models at once, e.g. every quant of a family. */ - setFavorites(modelIds: string[], favorite: boolean): void { - const next = new SvelteSet(this.favoriteModelIds); - - for (const modelId of modelIds) { - if (favorite) { - next.add(modelId); - } else { - next.delete(modelId); - } - } - - this.favoriteModelIds = next; - - try { - localStorage.setItem(FAVORITE_MODELS_LOCALSTORAGE_KEY, JSON.stringify([...next])); - } catch { - toast.error('Failed to save favorite models to local storage'); - } - } - - /** Persist one family of a section, e.g. a folded `Qwen` under the local models. */ - setGroupCollapsed(prefix: string, key: string, collapsed: boolean): void { - this.setGroupOpen(`${prefix}-${key}`, !collapsed); - } - - setGroupOpen(id: string, open: boolean): void { - const next = new SvelteMap(this.groupOpenState); - - // re-set moves the id to the end, so the oldest states fall off first - next.delete(id); - next.set(id, open); - - while (next.size > MAX_GROUP_OPEN_ENTRIES) { - const oldest = next.keys().next(); - - if (oldest.done) break; - - next.delete(oldest.value); - } - - this.groupOpenState = next; - - try { - localStorage.setItem( - MODEL_GROUP_OPEN_LOCALSTORAGE_KEY, - JSON.stringify(Object.fromEntries(next)) - ); - } catch { - toast.error('Failed to save the model list state to local storage'); - } - } - - toDisplayName(id: string): string { - const segments = id.split(/\\|\//); - const candidate = segments.pop(); - - return candidate && candidate.trim().length > 0 ? candidate : id; - } - - toggleFavorite(modelId: string): void { - this.setFavorites([modelId], !this.favoriteModelIds.has(modelId)); - } - - /** Models hidden from the selector stay in the manager, flagged and unhideable. */ - toggleHidden(modelId: string): void { - const next = new SvelteSet(this.hiddenModelIds); - - if (next.has(modelId)) { - next.delete(modelId); - } else { - next.add(modelId); - } - - this.hiddenModelIds = next; - - try { - localStorage.setItem(HIDDEN_MODELS_LOCALSTORAGE_KEY, JSON.stringify([...next])); - } catch { - toast.error('Failed to save hidden models to local storage'); - } - } - - /** - * Warm the Hub record of the local repos, so a list can read the context and size - * the server reports only once a model is loaded. - */ - warmHubDetails(): void { - if (!HuggingFaceService.isEnabled()) return; - - const repos: string[] = []; - - for (const option of this.models) { - const repo = repoOf(option.model); - - if (repo?.includes('/') && !repos.includes(repo)) repos.push(repo); - } - - // the Hub rate limits aggressively and an unauthenticated burst of requests - // leaves every detail uncached for a retry on the next mount, so warm only the - // rows the lists show at rest and let the rest arrive near the viewport - for (const repo of repos.slice(0, HUB_WARM_LIMIT)) { - void HuggingFaceService.getDetails(repo).catch(() => {}); - } - } - - /** - * Build ModelOption[] from an API response. - * Both MODEL and ROUTER modes share the same mapping logic; - * they differ only in which endpoint is called. - */ - private buildModelOptions(response: ApiModelsListResponse): ModelOption[] { - const entries: { - details?: ApiModelsListResponse['models'][number]; - item: ApiModelDataEntry; - parsed: ParsedModelId; - }[] = response.data.map((item: ApiModelDataEntry, index: number) => ({ - details: response.models?.[index], - item, - parsed: ModelsService.parseModelId(item.id) - })); - - return ( - entries - // a models dir can still name an entry after a projector file, which is - // no loadable model - .filter(({ parsed }) => !parsed.sidecar) - // in-flight and unfinished downloads are not usable models yet; the - // selector tracks them in its "Download in progress" section instead - .filter( - ({ item }) => - item.status?.value !== ServerModelStatus.DOWNLOADING && - item.status?.value !== ServerModelStatus.INCOMPLETE - ) - .map(({ details, item }) => { - const rawCapabilities = Array.isArray(details?.capabilities) ? details?.capabilities : []; - const displayNameSource = - details?.name && details.name.trim().length > 0 ? details.name : item.id; - const modelId = details?.model || item.id; - - return { - aliases: item.aliases ?? [], - capabilities: rawCapabilities.filter((value: unknown): value is string => - Boolean(value) - ), - // 0 is the server's way of leaving the trained context unknown; a - // model-mode listing reports it as meta.n_ctx_train instead - contextLength: - item.context_length || - (typeof item.meta?.n_ctx_train === 'number' && item.meta.n_ctx_train > 0 - ? item.meta.n_ctx_train - : undefined), - description: details?.description, - details: details?.details, - draftSidecars: this._status.getDraftSidecars(modelId), - id: item.id, - meta: item.meta ?? null, - modalities: this.props.buildArchitectureModalities(item.architecture), - model: modelId, - name: this.toDisplayName(displayNameSource), - parsedId: ModelsService.parseModelId(modelId), - tags: item.tags ?? [] - }; - }) - ); - } - /** Fetch models in MODEL mode (single model, standard OpenAI-compatible). */ - private async fetchModelModeInternal(): Promise { - const response = await ModelsService.list(); - - return this.buildModelOptions(response); - } - - private loadFavoritesFromStorage(): Set { - try { - const raw = localStorage.getItem(FAVORITE_MODELS_LOCALSTORAGE_KEY); - - return raw ? new Set(JSON.parse(raw) as string[]) : new Set(); - } catch { - toast.error('Failed to load favorite models from local storage'); - - return new Set(); - } - } - - /** Move a model to the front of the recently used list. */ - private recordRecentModel(qualifiedId: string): void { - this.recentModelIds = [ - qualifiedId, - ...this.recentModelIds.filter((id) => id !== qualifiedId) - ].slice(0, RECENT_MODEL_LIMIT); - - if (!browser) return; - - try { - localStorage.setItem(RECENT_MODELS_LOCALSTORAGE_KEY, JSON.stringify(this.recentModelIds)); - } catch { - console.warn('[ModelsStore] Failed to persist the recently used models'); - } - } - - private async runFetch(): Promise { - this.loading = true; - this.error = null; - - try { - if (!serverStore.props) { - await serverStore.fetch(); - } - - const router = serverStore.isRouterMode; - - if (router) { - const response = await ModelsService.list(); - - this.routerModels = response.data; - this.models = this.buildModelOptions(response); - - await this.props.fetchModalitiesForLoadedModels(); - - const visible = this.getVisibleModels(); - - if (visible.length === 1 && this.isModelLoaded(visible[0].model)) { - this.selectModelById(visible[0].id); - } - } else { - this.models = await this.fetchModelModeInternal(); - } - } catch (error) { - this.models = []; - this.error = error instanceof Error ? error.message : 'Failed to load models'; - - throw error; - } finally { - this.loading = false; - } - } -} - -export const modelsStore = new ModelsStore(); diff --git a/tools/ui/src/lib/stores/server.svelte.ts b/tools/ui/src/lib/stores/server.svelte.ts deleted file mode 100644 index e145e2891dd7..000000000000 --- a/tools/ui/src/lib/stores/server.svelte.ts +++ /dev/null @@ -1,131 +0,0 @@ -/** - * serverStore - Server connection state, configuration and role detection - * - * Owns the connection state and properties fetched from /props, plus MODEL - * vs ROUTER role detection and server-wide generation defaults. Uses - * PropsService for the /props fetch. - */ - -import { ServerRole } from '$lib/enums'; -import { PropsService } from '$lib/services/props.service'; -import { ApiError } from '$lib/utils'; - -const LOADING_RETRY_INTERVAL_MS = 1000; - -class ServerStore { - error = $state(null); - loading = $state(false); - props = $state(null); - role = $state(null); - status = $state(null); - private fetchPromise: Promise | null = null; - private retryTimer: ReturnType | null = null; - - get contextSize(): number | null { - const nCtx = this.props?.default_generation_settings?.n_ctx; - - return typeof nCtx === 'number' ? nCtx : null; - } - - get defaultParams(): ApiLlamaCppServerProps['default_generation_settings']['params'] | null { - return this.props?.default_generation_settings?.params || null; - } - - get isModelMode(): boolean { - return this.role === ServerRole.MODEL; - } - - get isRouterMode(): boolean { - return this.role === ServerRole.ROUTER; - } - - get uiSettings(): Record | undefined { - return this.props?.ui_settings ?? this.props?.webui_settings; - } - - clear(): void { - this.clearRetryTimer(); - this.props = null; - this.error = null; - this.status = null; - this.loading = false; - this.role = null; - this.fetchPromise = null; - } - - /** - * @param background - Set by the automatic "still loading" poll. Skips the - * `loading` flag flip so the UI doesn't bounce between the full loading - * splash and the chat screen every retry tick. - */ - async fetch({ background = false }: { background?: boolean } = {}): Promise { - if (this.fetchPromise) return this.fetchPromise; - - this.clearRetryTimer(); - - if (!background) { - this.loading = true; - } - - // Don't clear an existing "still loading" error before a retry - - // doing so would unmount/remount the error banner every second. - if (this.status !== 503) { - this.error = null; - } - - const fetchPromise = (async () => { - try { - const props = await PropsService.fetch(); - - this.props = props; - this.error = null; - this.status = null; - this.detectRole(props); - } catch (error: unknown) { - this.error = error instanceof Error ? error.message : String(error); - this.status = error instanceof ApiError ? error.status : null; - console.error('Error fetching server properties:', error); - - if (this.status === 503) { - this.scheduleRetry(); - } - } finally { - if (!background) { - this.loading = false; - } - - this.fetchPromise = null; - } - })(); - - this.fetchPromise = fetchPromise; - await fetchPromise; - } - - private clearRetryTimer(): void { - if (this.retryTimer) { - clearTimeout(this.retryTimer); - this.retryTimer = null; - } - } - - private detectRole(props: ApiLlamaCppServerProps): void { - const newRole = props?.role === ServerRole.ROUTER ? ServerRole.ROUTER : ServerRole.MODEL; - - if (this.role !== newRole) { - this.role = newRole; - console.info(`Server running in ${newRole === ServerRole.ROUTER ? 'ROUTER' : 'MODEL'} mode`); - } - } - - private scheduleRetry(): void { - if (this.retryTimer) return; - - this.retryTimer = setTimeout(() => { - this.retryTimer = null; - this.fetch({ background: true }); - }, LOADING_RETRY_INTERVAL_MS); - } -} - -export const serverStore = new ServerStore(); diff --git a/tools/ui/src/lib/stores/settings/index.svelte.ts b/tools/ui/src/lib/stores/settings/index.svelte.ts deleted file mode 100644 index 3adbb8e857c9..000000000000 --- a/tools/ui/src/lib/stores/settings/index.svelte.ts +++ /dev/null @@ -1,552 +0,0 @@ -/** - * settingsStore - Application configuration and theme management - * - * Owns generation parameters, UI preferences and theme, persisted to - * localStorage with Svelte 5 runes. Applies the admin's server ui_settings - * as defaults on first visit; sampling parameters sync with the server via - * ParameterSyncService. - */ - -import { browser } from '$app/environment'; -import { SETTING_CONFIG_DEFAULT, SETTINGS_KEYS } from '$lib/constants'; -import { ColorMode } from '$lib/enums'; -import { ParameterSyncService } from '$lib/services/parameter-sync.service'; -import { SettingsService } from '$lib/services/settings.service'; -import { deviceStore } from '$lib/stores/device.svelte'; -// direct imports between stores, not via the barrel, to avoid circular deps -import { serverStore } from '$lib/stores/server.svelte'; -import type { SettingsExportType } from '$lib/types'; -import { - configToParameterRecord, - getConfigValue, - normalizeFloatingPoint, - setConfigValue -} from '$lib/utils'; -import { setMode } from 'mode-watcher'; - -class SettingsStore { - config = $state({ ...SETTING_CONFIG_DEFAULT }); - isInitialized = $state(false); - userOverrides = $state>(new Set()); - - // True until a config exists in localStorage; gates the one-time - // application of server ui_settings defaults for new users. - private isFirstVisit = false; - - /** - * Whether the saved config differs from what "Reset to Default" would apply - */ - get hasCustomSettings(): boolean { - const propsDefaults = this.getServerDefaults(); - - for (const [key, value] of Object.entries(this.getResetValues())) { - const current = getConfigValue(this.config, key); - - // sampling params reset to '' (server decides); an explicit value equal to the server default is not custom - if (value === '' && propsDefaults[key] !== undefined) { - if ( - current !== '' && - current !== undefined && - normalizeFloatingPoint(current) !== normalizeFloatingPoint(propsDefaults[key]) - ) { - return true; - } - - continue; - } - - if (current !== value) { - return true; - } - } - - return false; - } - - canSyncParameter(key: string): boolean { - return ParameterSyncService.canSyncParameter(key); - } - - /** - * Clear all user overrides (for debugging) - */ - clearAllUserOverrides(): void { - this.userOverrides.clear(); - this.saveConfig(); - console.log('Cleared all user overrides'); - } - - /** - * Export all settings as a versioned JSON-compatible object. - * The export captures the full config (excluding sensitive values like API key) - * and user overrides. Sensitive fields are filtered out for security by default. - * @param includeSensitiveData - If true, include sensitive fields (apiKey, MCP server headers) in export - */ - exportSettings(includeSensitiveData: boolean = false): SettingsExportType { - // Build config excluding sensitive data unless user opts in - const configToExport: Record = - includeSensitiveData - ? { ...this.config } - : Object.fromEntries(Object.entries(this.config).filter(([key]) => key !== 'apiKey')); - - // Handle MCP servers: exclude custom headers unless user opts in - if ('mcpServers' in configToExport && !includeSensitiveData) { - try { - const mcpServers = JSON.parse(configToExport.mcpServers as string) as Array< - Record - >; - const safeServers = mcpServers.map((server) => { - delete server.headers; - - return server; - }); - - configToExport.mcpServers = JSON.stringify(safeServers); - } catch { - // If parsing fails, just exclude the entire mcpServers field - delete (configToExport as Record).mcpServers; - } - } - - return { - config: configToExport, - timestamp: Date.now(), - userOverrides: Array.from(this.userOverrides), - version: 1 - }; - } - - /** - * Reset all parameters to their default values (from props) - * This is used by the "Reset to Default" functionality - * Prioritizes Server defaults from /props, falls back to UI defaults - */ - forceSyncWithServerDefaults(): void { - for (const [key, value] of Object.entries(this.getResetValues())) { - setConfigValue(this.config, key, value); - - if (key === SETTINGS_KEYS.THEME) { - setMode(value as ColorMode); - } - - this.userOverrides.delete(key); - } - - for (const key of ParameterSyncService.getSyncableParameterKeys()) { - this.userOverrides.delete(key); - } - - this.saveConfig(); - } - - /** - * Get the entire configuration object - * @returns The complete configuration object - */ - getAllConfig(): SettingsConfigType { - return { ...this.config }; - } - - /** - * Get a specific configuration value - * @param key - The configuration key to get - * @returns The configuration value - */ - getConfig(key: K): SettingsConfigType[K] { - return this.config[key]; - } - - /** - * Get diff between current settings and server defaults - */ - getParameterDiff() { - const serverDefaults = this.getServerDefaults(); - - if (Object.keys(serverDefaults).length === 0) return {}; - - const configAsRecord = configToParameterRecord( - this.config, - ParameterSyncService.getSyncableParameterKeys() - ); - - return ParameterSyncService.createParameterDiff(configAsRecord, serverDefaults); - } - - /** - * Get parameter information including source for a specific parameter - */ - getParameterInfo(key: string) { - const propsDefaults = this.getServerDefaults(); - const currentValue = getConfigValue(this.config, key); - - return ParameterSyncService.getParameterInfo( - key, - currentValue ?? '', - propsDefaults, - this.userOverrides - ); - } - - /** - * Import settings from a previously exported object. - * Restores config (including theme) and user overrides. - * @param data - The exported settings object - */ - importSettings(data: SettingsExportType): void { - if (!browser) return; - - if (!data || !data.config) { - throw new Error('Invalid settings data: missing config'); - } - - // Restore config (theme is included in config) - this.config = { - ...SETTING_CONFIG_DEFAULT, - ...data.config - }; - - // Restore user overrides (derived state — may be stale if server defaults differ) - this.userOverrides = new Set(data.userOverrides ?? []); - - this.enforceDiscoverCoupling(); - - // Persist to localStorage - this.saveConfig(); - - // Apply theme for immediate visual feedback - setMode(this.config[SETTINGS_KEYS.THEME] as ColorMode); - - console.log('Settings imported successfully'); - } - - /** - * Initialize the settings store by loading from localStorage. - * Called by hydrateStores() after migrations have run. - */ - initialize() { - if (!browser) return; - - try { - this.loadConfig(); - this.migrateLegacyTheme(); - this.enforceDiscoverCoupling(); - // Apply the persisted theme from config on initial load - setMode(this.config[SETTINGS_KEYS.THEME] as ColorMode); - this.isInitialized = true; - } catch (error) { - console.error('Failed to initialize settings store:', error); - } - } - - /** - * Reset all settings to defaults. - */ - resetAll() { - this.resetConfig(); - - this.resetTheme(); - } - - /** - * Reset configuration to defaults - */ - resetConfig() { - this.config = { ...SETTING_CONFIG_DEFAULT }; - - this.enforceDiscoverCoupling(); - this.saveConfig(); - } - - /** - * Reset a parameter to Server default (or UI default if no Server default) - */ - resetParameterToServerDefault(key: string): void { - const serverDefaults = this.getServerDefaults(); - const uiSettings = serverStore.uiSettings; - - if (uiSettings && key in uiSettings) { - // UI setting from admin config: write actual value - setConfigValue(this.config, key, uiSettings[key]); - } else if (serverDefaults[key] !== undefined) { - // sampling param known by server: clear it, let server decide - setConfigValue(this.config, key, ''); - } else if (key in SETTING_CONFIG_DEFAULT) { - setConfigValue(this.config, key, getConfigValue(SETTING_CONFIG_DEFAULT, key)); - } - - this.userOverrides.delete(key); - this.saveConfig(); - } - - /** - * Reset theme to default value. - * Theme is now stored inside the config object. - */ - resetTheme() { - this.updateConfig(SETTINGS_KEYS.THEME, SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.THEME]); - - setMode(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.THEME] as ColorMode); - } - - /** - * Initialize settings with props defaults when server properties are first loaded - * This sets up the default values from /props endpoint - */ - syncWithServerDefaults(): void { - const propsDefaults = this.getServerDefaults(); - const uiSettings = serverStore.uiSettings; - - // a router main instance reports no sampling defaults, but its - // ui_settings still need the first visit pass below - if (Object.keys(propsDefaults).length === 0 && !(uiSettings && this.isFirstVisit)) return; - - const uiSettingsKeys = new Set(uiSettings ? Object.keys(uiSettings) : []); - - for (const [key, propsValue] of Object.entries(propsDefaults)) { - const currentValue = getConfigValue(this.config, key); - const normalizedCurrent = normalizeFloatingPoint(currentValue); - const normalizedDefault = normalizeFloatingPoint(propsValue); - - // if user value matches server, it's not a real override - if (normalizedCurrent === normalizedDefault) { - this.userOverrides.delete(key); - - if (!uiSettingsKeys.has(key) && getConfigValue(SETTING_CONFIG_DEFAULT, key) === undefined) { - setConfigValue(this.config, key, undefined); - } - } - } - - // UI settings are the admin's defaults for new users: applied once on - // the first visit, never on later loads, so the user's config can - // diverge. "Reset to Default" is the explicit way back to the baseline. - // A first visit config carries factory values only, so a key that - // already diverges here was set by the user before the baseline could - // be reached, through the API key splash, and stays theirs. - if (uiSettings && this.isFirstVisit) { - this.isFirstVisit = false; - - for (const [key, value] of Object.entries(uiSettings)) { - if (value === undefined || this.userOverrides.has(key)) continue; - - if (getConfigValue(this.config, key) !== getConfigValue(SETTING_CONFIG_DEFAULT, key)) { - continue; - } - - setConfigValue(this.config, key, value); - - // theme lives in mode-watcher, not just in config -> propagate - if (key === SETTINGS_KEYS.THEME) { - setMode(value as ColorMode); - } - } - } - - this.saveConfig(); - console.log('User overrides after sync:', Array.from(this.userOverrides)); - } - - /** - * Update a specific configuration setting - * @param key - The configuration key to update - * @param value - The new value for the configuration key - */ - updateConfig(key: K, value: SettingsConfigType[K]): void { - this.config[key] = value; - - if (ParameterSyncService.canSyncParameter(key as string)) { - const propsDefaults = this.getServerDefaults(); - const propsDefault = propsDefaults[key as string]; - - if (propsDefault !== undefined) { - const normalizedValue = normalizeFloatingPoint(value); - const normalizedDefault = normalizeFloatingPoint(propsDefault); - - if (normalizedValue === normalizedDefault) { - this.userOverrides.delete(key as string); - } else { - this.userOverrides.add(key as string); - } - } - } - - this.saveConfig(); - } - - /** - * Update multiple configuration settings at once - * @param updates - Object containing the configuration updates - */ - updateMultipleConfig(updates: Partial) { - Object.assign(this.config, updates); - - const propsDefaults = this.getServerDefaults(); - - for (const [key, value] of Object.entries(updates)) { - if (ParameterSyncService.canSyncParameter(key)) { - const propsDefault = propsDefaults[key]; - - if (propsDefault !== undefined) { - const normalizedValue = normalizeFloatingPoint(value); - const normalizedDefault = normalizeFloatingPoint(propsDefault); - - if (normalizedValue === normalizedDefault) { - this.userOverrides.delete(key); - } else { - this.userOverrides.add(key); - } - } - } - } - - this.saveConfig(); - } - - /** - * - * - * Import / Export - * - * - */ - - /** - * Update the theme setting. - * @param newTheme - The new theme value - */ - updateTheme(newTheme: string) { - this.updateConfig(SETTINGS_KEYS.THEME, newTheme); - - setMode(newTheme as ColorMode); - } - - /** - * Discover needs the hub metadata reads, so a checked Discover Models keeps - * the hub setting on; call wherever stored or reset state may disagree. - */ - private enforceDiscoverCoupling(): void { - if ( - this.config[SETTINGS_KEYS.ENABLE_DISCOVER_MODELS] && - !this.config[SETTINGS_KEYS.USE_HUGGING_FACE_HUB] - ) { - setConfigValue(this.config, SETTINGS_KEYS.USE_HUGGING_FACE_HUB, true); - this.saveConfig(); - } - } - - /** - * Values applied by "Reset to Default": admin ui_settings first, then server - * defaults from /props for sampling params, then the factory defaults - */ - private getResetValues(): Record { - const propsDefaults = this.getServerDefaults(); - const uiSettings = serverStore.uiSettings; - const values: Record = {}; - - for (const key of ParameterSyncService.getSyncableParameterKeys()) { - if (uiSettings && key in uiSettings) { - // UI setting from admin config: write actual value - values[key] = uiSettings[key]; - } else if (propsDefaults[key] !== undefined) { - // sampling param: clear it, let server decide - values[key] = ''; - } else if (key in SETTING_CONFIG_DEFAULT) { - values[key] = getConfigValue(SETTING_CONFIG_DEFAULT, key); - } - } - - // Non-syncable keys: reset is a full return to the instance state, the - // admin baseline value when defined, the factory default otherwise. - for (const key of Object.keys(SETTING_CONFIG_DEFAULT)) { - if (ParameterSyncService.canSyncParameter(key)) { - continue; - } - - values[key] = - uiSettings && key in uiSettings && uiSettings[key] !== undefined - ? uiSettings[key] - : getConfigValue(SETTING_CONFIG_DEFAULT, key); - } - - return values; - } - - /** - * - * - * Utilities (private helpers) - * - * - */ - - /** - * Helper method to get server defaults with null safety - * Centralizes the pattern of getting and extracting server defaults - */ - private getServerDefaults(): Record { - return ParameterSyncService.extractServerDefaults(serverStore.defaultParams); - } - - /** - * Load configuration from localStorage via the persistence service. - * Returns default values for missing keys to prevent breaking changes. - */ - private loadConfig() { - if (!browser) return; - - const { - config: savedVal, - isFirstVisit, - userOverrides: savedOverrides - } = SettingsService.loadConfig(); - - // First visit: no stored config yet. Server ui_settings apply once in - // this state, then the user's config diverges freely. - this.isFirstVisit = isFirstVisit; - - // Merge with defaults to prevent breaking changes - this.config = { - ...SETTING_CONFIG_DEFAULT, - ...savedVal - }; - - // Default sendOnEnter to false on mobile when the user has no saved preference - if (!(SETTINGS_KEYS.SEND_ON_ENTER in savedVal)) { - if (deviceStore.isMobile) { - this.config[SETTINGS_KEYS.SEND_ON_ENTER] = false; - } - } - - // Load user overrides - this.userOverrides = new Set(savedOverrides); - } - - /** - * Migrate the legacy un-namespaced "theme" localStorage key into config. - * Previously theme was stored separately in localStorage("theme") — now it lives - * inside the config object alongside all other settings. - * After migration the legacy key is removed. - */ - private migrateLegacyTheme() { - if (!browser) return; - - const legacyTheme = SettingsService.migrateLegacyTheme(); - - if (legacyTheme) { - this.config[SETTINGS_KEYS.THEME] = legacyTheme; - this.saveConfig(); - setMode(legacyTheme as ColorMode); - } - } - - /** - * Save the current configuration to localStorage via the persistence service. - */ - private saveConfig() { - if (!browser) return; - - SettingsService.saveConfig(this.config, Array.from(this.userOverrides)); - } -} - -export const settingsStore = new SettingsStore(); diff --git a/tools/ui/src/lib/stores/version.svelte.ts b/tools/ui/src/lib/stores/version.svelte.ts deleted file mode 100644 index 5a86a575bfb8..000000000000 --- a/tools/ui/src/lib/stores/version.svelte.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * versionStore - Build version information - * - * - `build`: llama.cpp build number from `build.json`, embedded at llama.cpp - * build time (LLAMA_BUILD_NUMBER). Shown in the UI when `showBuildVersion` - * is enabled. - * - `frontend`: frontend build version from SvelteKit's `_app/version.json`, - * generated by the @vite-pwa/sveltekit plugin. Changes on every build, so - * comparing it against localStorage reliably detects server upgrades. - * - * In dev mode both fall back to `'dev'`. - */ - -import { browser } from '$app/environment'; -import { base } from '$app/paths'; - -class VersionStore { - build = $state(''); - frontend = $state(''); - - /** - * Fetch the version files. Called by initStores(); order-independent, - * so it runs in the background. - */ - initialize(): void { - if (!browser) return; - - if (import.meta.env.DEV) { - this.build = 'dev'; - this.frontend = 'dev'; - - return; - } - - void this.load(); - } - - private async load(): Promise { - try { - const res = await fetch(`${base}/build.json`, { cache: 'no-store' }); - - if (res.ok) { - const data = await res.json(); - - this.build = data.version ?? ''; - } - } catch { - // build.json missing or unreachable - leave as empty string - } - - try { - const res = await fetch(`${base}/_app/version.json`, { cache: 'no-store' }); - - if (res.ok) { - const data = await res.json(); - - this.frontend = data.version ?? ''; - } - } catch { - // version.json missing or unreachable - leave as empty string - } - } -} - -export const versionStore = new VersionStore(); diff --git a/tools/ui/src/lib/types/index.ts b/tools/ui/src/lib/types/index.ts deleted file mode 100644 index 5c8c5e8b8b35..000000000000 --- a/tools/ui/src/lib/types/index.ts +++ /dev/null @@ -1,257 +0,0 @@ -/** - * Unified exports for all type definitions - * Import types from '$lib/types' for cleaner imports - */ - -// API types -export type { - ApiChatMessageContentPart, - ApiContextSizeError, - ApiErrorResponse, - ApiChatMessageData, - ApiModelStatus, - ApiModelDataEntry, - ApiModelLoadStage, - ApiModelsSseProgress, - ApiModelsSseData, - ApiModelsSseDownloadProgressData, - ApiModelsSseDownloadFailedData, - ApiModelsSseEvent, - ApiModelsDownloadRequest, - ApiModelsDownloadResponse, - ApiModelDetails, - ApiLlamaCppServerProps, - ApiChatCompletionRequest, - ApiChatCompletionToolCallFunctionDelta, - ApiChatCompletionToolCallDelta, - ApiChatCompletionToolCall, - ApiChatCompletionStreamChunk, - ApiChatCompletionResponse, - ApiSlotData, - ApiProcessingState, - ApiModelsLoadResponse, - ApiModelsListResponse, - ApiModelsUnloadResponse, - AudioInputFormat, - ApiStreamSession -} from './api'; - -// HuggingFace types -export type { - HfCatalogBuild, - HfCatalogEntry, - HfCatalogSize, - HfModelApiResponse, - HfModelCardData, - HfModelDetails, - HfModelDetailInfo, - HfModelGguf, - HfModelInfo, - HfModelSearchParams, - HfMmprojEncoders, - HfModelSibling, - HfModelSiblingRef -} from './huggingface'; - -// Chat types -export type { - AttachmentMenuItem, - ChatUploadedFile, - ChatAttachmentDisplayItem, - ChatMessageSiblingInfo, - ChatMessageActions, - ChatMessageActionsContext, - ChatMessageDeletionInfo, - ChatMessageEditContext, - ChatMessageEditState, - ChatMessageEditActions, - ChatMessageAssistantEditActions, - ChatFormActionsContext, - ChatMessagePromptProgress, - ChatMessageTimings, - ChatMessageAgenticTimings, - ChatMessageCompactionTimings, - ChatMessageAgenticTurnStats, - ChatMessageToolCallTiming, - ChatStreamCallbacks, - ErrorDialogState, - LiveProcessingStats, - LiveGenerationStats, - AttachmentDisplayItemsOptions, - FileProcessingResult, - FileMentionEntry, - ChatFormCommand, - ChatCommandsOptions, - ControlAction -} from './chat.d'; - -// Database types -export type { - McpServerOverride, - DatabaseConversation, - DatabaseMessageExtraAudioFile, - DatabaseMessageExtraVideoFile, - DatabaseMessageExtraImageFile, - DatabaseMessageExtraLegacyContext, - DatabaseMessageExtraMcpPrompt, - DatabaseMessageExtraMcpResource, - DatabaseMessageExtraPdfFile, - DatabaseMessageExtraTextFile, - DatabaseMessageExtra, - DatabaseMessage, - ExportedConversation, - ExportedConversations -} from './database'; - -// Model types -export type { - ModelCapabilities, - ModelModalities, - ModelOption, - ModelDownloadEntry, - ModelDownloadFileProgress, - ModelDownloadProgress, - ModelLoadProgress, - ModelSidecarBadge, - ModalityCapabilities -} from './models'; - -// Models discover types -export type { - ModelBitDepthRow, - ModelCompanionDraft, - ModelDownloadEntryState, - ModelQuantChip, - ModelQuantOption, - ModelSelectableFile -} from './models-discover'; - -// Settings types -export type { - SettingsConfigValue, - SettingsFieldConfig, - SettingsChatServiceOptions, - SettingsConfigType, - SettingsExportType, - ParameterValue, - ParameterRecord, - ParameterInfo, - SyncableParameter, - SettingsEntry, - SettingsSectionTitle, - SettingsSectionEntry, - SettingsSection -} from './settings'; - -// Common types -export type { - KeyValuePair, - BinaryDetectionOptions, - ClipboardTextAttachment, - ClipboardMcpPromptAttachment, - ClipboardAttachment, - ParsedClipboardContent -} from './common'; - -// MCP types -export type { - ClientCapabilities, - ServerCapabilities, - Implementation, - MCPConnectionLog, - MCPServerInfo, - MCPCapabilitiesInfo, - MCPToolInfo, - MCPPromptInfo, - MCPConnectionDetails, - MCPPhaseCallback, - MCPConnection, - HealthCheckState, - HealthCheckParams, - MCPServerConfig, - MCPClientConfig, - MCPServerSettingsEntry, - MCPServerDisplayInfo, - RecommendedMCPServer, - MCPToolCall, - OpenAIToolDefinition, - ServerStatus, - ToolCallParams, - ToolExecutionResult, - ServerToolInfo, - Tool, - Prompt, - GetPromptResult, - PromptMessage, - MCPProgressState, - MCPResourceAnnotations, - MCPResourceIcon, - MCPResource, - MCPResourceTemplate, - MCPTextResourceContent, - MCPBlobResourceContent, - MCPResourceContent, - MCPReadResourceResult, - MCPResourceInfo, - MCPResourceTemplateInfo, - MCPCachedResource, - MCPResourceAttachment, - MCPResourceSubscription, - MCPServerResources -} from './mcp'; - -// Group types -export type { Group } from './groups'; - -// Search result types -export type { SearchResult } from './search'; - -// Glob search types (working-directory / mention pickers) -export type { - GlobEntry, - GlobSearchArgs, - GlobSearchResult, - GlobEntryResult, - GlobSearchChildOptions, - GlobSearchChildResult -} from './glob'; - -// Agentic types -export type { - AgenticConfig, - AgenticToolCallPayload, - AgenticMessage, - AgenticAssistantMessage, - AgenticToolCallList, - AgenticChatCompletionRequest, - AgenticSession, - AgenticFlowCallbacks, - AgenticFlowOptions, - AgenticFlowParams, - AgenticFlowResult, - SteeringMessage, - AgenticSection, - ToolResultLine, - ContinueIntent -} from './agentic'; - -// Navigation types -export type { DesktopIconStripItem, MenuAction } from './navigation'; - -// Tools types -export type { - EditFileEdit, - EditFileMeta, - EditFileTitleMeta, - ToolEntry, - ToolGroup, - ToolUiEntry, - WriteFileMeta, - WriteFileTitleMeta -} from './tools'; - -// Reasoning -export type { ReasoningEffortLevel } from './reasoning'; - -// Splash -export type { SplashDimensions } from './splash'; diff --git a/tools/ui/src/lib/utils/audio-recording.ts b/tools/ui/src/lib/utils/audio-recording.ts deleted file mode 100644 index 2f3e4106b89a..000000000000 --- a/tools/ui/src/lib/utils/audio-recording.ts +++ /dev/null @@ -1,299 +0,0 @@ -import { MICROPHONE_UNAVAILABLE_MESSAGE } from '$lib/constants'; -import { MimeTypeAudio } from '$lib/enums'; - -/** - * AudioRecorder - Browser-based audio recording with MediaRecorder API - * - * This class provides a complete audio recording solution using the browser's MediaRecorder API. - * It handles microphone access, recording state management, and audio format optimization. - * - * **Features:** - * - Automatic microphone permission handling - * - Audio enhancement (echo cancellation, noise suppression, auto gain) - * - Multiple format support with fallback (WAV, WebM, MP4, AAC) - * - Real-time recording state tracking - * - Proper cleanup and resource management - */ -export class AudioRecorder { - private audioChunks: Blob[] = []; - private mediaRecorder: MediaRecorder | null = null; - private recordingState: boolean = false; - private stream: MediaStream | null = null; - - cancelRecording(): void { - const recorder = this.mediaRecorder; - const stream = this.stream; - - this.mediaRecorder = null; - this.audioChunks = []; - this.stream = null; - this.recordingState = false; - - if (recorder && recorder.state !== 'inactive') { - // Drop the original handlers so the pending stop event does not touch the instance - recorder.onstop = null; - recorder.onerror = null; - recorder.stop(); - } - - if (stream) { - for (const track of stream.getTracks()) { - track.stop(); - } - } - } - - isRecording(): boolean { - return this.recordingState; - } - - async startRecording(): Promise { - try { - this.stream = await navigator.mediaDevices.getUserMedia({ - audio: { - autoGainControl: true, - echoCancellation: true, - noiseSuppression: true - } - }); - - this.initializeRecorder(this.stream); - - this.audioChunks = []; - // Start recording with a small timeslice to ensure we get data - this.mediaRecorder!.start(100); - this.recordingState = true; - } catch (error) { - console.error('Failed to start recording:', error); - - // the browser's own error, which says why: see describeMicrophoneError - throw error; - } - } - - async stopRecording(): Promise { - return new Promise((resolve, reject) => { - const recorder = this.mediaRecorder; - const chunks = this.audioChunks; - const stream = this.stream; - - if (!recorder || recorder.state === 'inactive') { - reject(new Error('No active recording to stop')); - - return; - } - - // Detach instance state right away so a new startRecording can take over without race - this.mediaRecorder = null; - this.audioChunks = []; - this.stream = null; - this.recordingState = false; - - recorder.onstop = () => { - const audioBlob = new Blob(chunks, { - type: recorder.mimeType || MimeTypeAudio.WAV - }); - - if (stream) { - for (const track of stream.getTracks()) { - track.stop(); - } - } - - resolve(audioBlob); - }; - - recorder.onerror = (event) => { - console.error('Recording error:', event); - - if (stream) { - for (const track of stream.getTracks()) { - track.stop(); - } - } - - reject(new Error('Recording failed')); - }; - - recorder.stop(); - }); - } - - private initializeRecorder(stream: MediaStream): void { - const options: MediaRecorderOptions = {}; - - if (MediaRecorder.isTypeSupported(MimeTypeAudio.WAV)) { - options.mimeType = MimeTypeAudio.WAV; - } else if (MediaRecorder.isTypeSupported(MimeTypeAudio.WEBM_OPUS)) { - options.mimeType = MimeTypeAudio.WEBM_OPUS; - } else if (MediaRecorder.isTypeSupported(MimeTypeAudio.WEBM)) { - options.mimeType = MimeTypeAudio.WEBM; - } else if (MediaRecorder.isTypeSupported(MimeTypeAudio.MP4)) { - options.mimeType = MimeTypeAudio.MP4; - } else { - console.warn('No preferred audio format supported, using default'); - } - - this.mediaRecorder = new MediaRecorder(stream, options); - - this.mediaRecorder.ondataavailable = (event) => { - if (event.data.size > 0) { - this.audioChunks.push(event.data); - } - }; - - this.mediaRecorder.onstop = () => { - this.recordingState = false; - }; - - this.mediaRecorder.onerror = (event) => { - console.error('MediaRecorder error:', event); - this.recordingState = false; - }; - } -} - -export async function convertToWav(audioBlob: Blob): Promise { - try { - if (audioBlob.type.includes('wav')) { - return audioBlob; - } - - const arrayBuffer = await audioBlob.arrayBuffer(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)(); - - try { - const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); - - return audioBufferToWav(audioBuffer); - } finally { - audioContext.close(); - } - } catch (error) { - console.error('Failed to convert audio to WAV:', error); - - return audioBlob; - } -} - -function audioBufferToWav(buffer: AudioBuffer): Blob { - const length = buffer.length; - const numberOfChannels = buffer.numberOfChannels; - const sampleRate = buffer.sampleRate; - const bytesPerSample = 2; // 16-bit - const blockAlign = numberOfChannels * bytesPerSample; - const byteRate = sampleRate * blockAlign; - const dataSize = length * blockAlign; - const bufferSize = 44 + dataSize; - const arrayBuffer = new ArrayBuffer(bufferSize); - const view = new DataView(arrayBuffer); - const writeString = (offset: number, string: string) => { - for (let i = 0; i < string.length; i++) { - view.setUint8(offset + i, string.charCodeAt(i)); - } - }; - - writeString(0, 'RIFF'); // ChunkID - view.setUint32(4, bufferSize - 8, true); // ChunkSize - writeString(8, 'WAVE'); // Format - writeString(12, 'fmt '); // Subchunk1ID - view.setUint32(16, 16, true); // Subchunk1Size - view.setUint16(20, 1, true); // AudioFormat (PCM) - view.setUint16(22, numberOfChannels, true); // NumChannels - view.setUint32(24, sampleRate, true); // SampleRate - view.setUint32(28, byteRate, true); // ByteRate - view.setUint16(32, blockAlign, true); // BlockAlign - view.setUint16(34, 16, true); // BitsPerSample - writeString(36, 'data'); // Subchunk2ID - view.setUint32(40, dataSize, true); // Subchunk2Size - - // Cache channel arrays, write PCM via Int16Array (native little-endian, matches WAV) - const channels: Float32Array[] = new Array(numberOfChannels); - - for (let c = 0; c < numberOfChannels; c++) { - channels[c] = buffer.getChannelData(c); - } - - const pcm = new Int16Array(arrayBuffer, 44, length * numberOfChannels); - - let p = 0; - - for (let i = 0; i < length; i++) { - for (let c = 0; c < numberOfChannels; c++) { - let s = channels[c][i]; - - if (s > 1) s = 1; - else if (s < -1) s = -1; - - pcm[p++] = s * 0x7fff; - } - } - - return new Blob([arrayBuffer], { type: MimeTypeAudio.WAV }); -} - -/** - * Create a File object from audio blob with timestamp-based naming - * @param audioBlob - The audio blob to wrap - * @param filename - Optional custom filename - * @returns File object with appropriate name and metadata - */ -export function createAudioFile(audioBlob: Blob, filename?: string): File { - const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); - const extension = audioBlob.type.includes('wav') ? 'wav' : 'mp3'; - const defaultFilename = `recording-${timestamp}.${extension}`; - - return new File([audioBlob], filename || defaultFilename, { - lastModified: Date.now(), - type: audioBlob.type - }); -} - -/** - * Check if audio recording is supported in the current browser - * @returns True if MediaRecorder and getUserMedia are available - */ -export function isAudioRecordingSupported(): boolean { - return !!( - typeof navigator !== 'undefined' && - navigator.mediaDevices && - typeof navigator.mediaDevices.getUserMedia === 'function' && - typeof window !== 'undefined' && - window.MediaRecorder - ); -} - -/** - * Why this page can't record at all, or null when it can: a reason no tap will fix. Browsers - * only expose the microphone to a secure context, HTTPS or localhost, so a llama-server - * opened over plain HTTP on the local network or over Tailscale can't record. - */ -export function microphoneUnavailableReason(): string | null { - if (typeof window === 'undefined') return null; - - if (!window.isSecureContext) return MICROPHONE_UNAVAILABLE_MESSAGE.insecure; - - if (!isAudioRecordingSupported()) return MICROPHONE_UNAVAILABLE_MESSAGE.unsupported; - - return null; -} - -/** Why the microphone would not start, from the error the browser raised. */ -export function describeMicrophoneError(error: unknown): string { - switch (error instanceof DOMException ? error.name : '') { - case 'NotAllowedError': - case 'SecurityError': - return MICROPHONE_UNAVAILABLE_MESSAGE.denied; - case 'NotFoundError': - case 'OverconstrainedError': - return MICROPHONE_UNAVAILABLE_MESSAGE.notFound; - case 'AbortError': - case 'NotReadableError': - return MICROPHONE_UNAVAILABLE_MESSAGE.busy; - default: - return error instanceof Error && error.message - ? `${MICROPHONE_UNAVAILABLE_MESSAGE.failed} ${error.message}` - : MICROPHONE_UNAVAILABLE_MESSAGE.failed; - } -} diff --git a/tools/ui/src/lib/utils/browser-info.ts b/tools/ui/src/lib/utils/browser-info.ts deleted file mode 100644 index e313d42584bf..000000000000 --- a/tools/ui/src/lib/utils/browser-info.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Browser fallback for the server's `get_info` tool, offered only when the - * server does not serve one (llama-server without --agent). It tells the model - * which OS the browser runs on and that there is no local file or shell access, - * so it does not plan around tools that are not there. - * - * @see server_tool_get_info in tools/server/server-tools.cpp - the served variant - * @see buildBrowserInfoToolDefinition in constants/browser-info.ts - tool schema sent to the LLM - */ - -import { browser } from '$app/environment'; -import { - BROWSER_INFO_NOTE, - BROWSER_INFO_OS_UA_PATTERNS, - BROWSER_INFO_OS_UNKNOWN -} from '$lib/constants'; -import type { ToolExecutionResult } from '$lib/types'; - -export function detectOs(userAgent: string): string { - for (const [pattern, os] of BROWSER_INFO_OS_UA_PATTERNS) { - if (pattern.test(userAgent)) return os; - } - - return BROWSER_INFO_OS_UNKNOWN; -} - -/** - * Result shape mirrors the server tool's JSON so the `get_info` renderer reads - * `os` the same way, minus `cwd` - there is no working directory to report. - */ -export function executeBrowserInfoTool(): ToolExecutionResult { - return { - content: JSON.stringify({ - note: BROWSER_INFO_NOTE, - os: browser ? detectOs(navigator.userAgent) : BROWSER_INFO_OS_UNKNOWN - }), - isError: false - }; -} diff --git a/tools/ui/src/lib/utils/chat-commands.ts b/tools/ui/src/lib/utils/chat-commands.ts deleted file mode 100644 index 89e36e130bf4..000000000000 --- a/tools/ui/src/lib/utils/chat-commands.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { SET_WORKING_DIRECTORY_LABEL } from '$lib/constants'; -import { ChatFormCommandAction } from '$lib/enums'; -import type { ChatCommandsOptions, ChatFormCommand } from '$lib/types'; - -/** - * The slash commands surfaced by the `/` command picker, in display order. - * - * Availability is supplied as predicates rather than store imports: this - * module is re-exported through the `$lib/utils` barrel, and importing - * stores at module load would create a circular dependency (the stores - * themselves import from `$lib/utils`). - */ -export function getChatCommands(options: ChatCommandsOptions): ChatFormCommand[] { - return [ - { - action: ChatFormCommandAction.PROMPT, - description: 'Insert an MCP prompt', - disabled: !options.hasPrompts(), - name: 'prompt' - }, - { - action: ChatFormCommandAction.CWD, - description: SET_WORKING_DIRECTORY_LABEL, - disabled: !options.hasCwdTools(), - keywords: ['current working directory'], - name: 'cwd' - }, - { - action: ChatFormCommandAction.MODEL, - description: 'Select model', - disabled: !options.showModelSelector, - name: 'model' - }, - { - action: ChatFormCommandAction.COMPACT, - description: 'Summarize the conversation to free up context', - disabled: !options.canCompact(), - keywords: ['summarize', 'context'], - name: 'compact' - } - ]; -} diff --git a/tools/ui/src/lib/utils/code.ts b/tools/ui/src/lib/utils/code.ts deleted file mode 100644 index ab3e4b56f8f9..000000000000 --- a/tools/ui/src/lib/utils/code.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { CODE_BLOCK, NEWLINE } from '$lib/constants'; -import hljs from 'highlight.js'; - -export interface IncompleteCodeBlock { - language: string; - code: string; - openingIndex: number; -} - -// A fence line: up to 3 leading spaces (CommonMark), 3+ backticks, then -// whatever trails on the same line. -const FENCE_LINE_REGEX = /^ {0,3}(`{3,})(.*)$/; - -/** - * Splits text glued to a closing code fence onto its own line: - * - * ```ts - * let foo = 'bar'; - * ```create this file on ... - * - * A closing fence with trailing text is not a fence to the markdown - * parser, so the block would swallow the text as code. The chat form - * normally keeps the fence on its own line, but older messages and - * hand-pasted content can carry the glued form. - * - * Only trailing text containing whitespace is split: a single word - * after the backticks inside a fenced block is more likely nested - * markdown (a ```python example inside a ```md block) than glued prose. - */ -export function splitGluedClosingCodeFences(markdown: string): string { - if (!markdown.includes('```')) return markdown; - - const lines = markdown.split(NEWLINE); - - let inside = false; - let changed = false; - - for (let i = 0; i < lines.length; i++) { - const match = FENCE_LINE_REGEX.exec(lines[i]); - - if (!match) continue; - - if (!inside) { - inside = true; - - continue; - } - - inside = false; - - const trailing = match[2]; - - if (trailing.includes('`') || !/\s/.test(trailing)) continue; - - lines[i] = lines[i].slice(0, lines[i].length - trailing.length); - lines.splice(i + 1, 0, trailing.trim()); - i++; - changed = true; - } - - return changed ? lines.join(NEWLINE) : markdown; -} - -/** - * Strips empty lines (whitespace-only) from the start and end of code. - * - * Tool call payloads frequently arrive with surrounding whitespace from LLM - * formatting (`"\nfunction ...\n"`). Preserving those newlines makes hljs emit - * a leading/trailing empty line that `
` then renders as a phantom row,
- * pushing real content away from the box edge. The trim keeps the body intact
- * so internal blank lines are still rendered as such.
- */
-function trimCodePadding(code: string): string {
-	return code
-		.replace(CODE_BLOCK.TRIM_LEADING_PADDING_REGEX, '')
-		.replace(CODE_BLOCK.TRIM_TRAILING_PADDING_REGEX, '');
-}
-
-function escapeCode(code: string): string {
-	return code
-		.replace(CODE_BLOCK.AMPERSAND_REGEX, '&')
-		.replace(CODE_BLOCK.LT_REGEX, '<')
-		.replace(CODE_BLOCK.GT_REGEX, '>');
-}
-
-/** Bounded cache for highlightCode results. */
-const HIGHLIGHT_CACHE_MAX_SIZE = 64;
-const highlightCache = new Map();
-
-/**
- * Highlights code using highlight.js
- * @param code - The code to highlight
- * @param language - The programming language
- * @param autoDetect - Fall back to `highlightAuto` when `language` is unknown.
- *   Callers rendering a still-streaming block should pass false: auto-detection
- *   costs ~38ms per call and re-guesses on every chunk, so the language (and
- *   therefore the whole highlight) flickers as the block grows.
- * @returns HTML string with syntax highlighting
- */
-export function highlightCode(code: string, language: string, autoDetect = true): string {
-	if (!code) return '';
-
-	// Cache key includes language and autoDetect flag since results differ.
-	// During streaming, the same code string may be highlighted repeatedly
-	// (e.g., when text after a code block changes but the code itself doesn't).
-	const cacheKey = `${language}:${autoDetect}:${code}`;
-	const cached = highlightCache.get(cacheKey);
-
-	if (cached) return cached;
-
-	const trimmed = trimCodePadding(code);
-
-	let result: string;
-
-	try {
-		const lang = language.toLowerCase();
-		const isSupported = hljs.getLanguage(lang);
-
-		if (isSupported) {
-			result = hljs.highlight(trimmed, { language: lang }).value;
-		} else if (autoDetect) {
-			result = hljs.highlightAuto(trimmed).value;
-		} else {
-			result = escapeCode(trimmed);
-		}
-	} catch {
-		result = escapeCode(trimmed);
-	}
-
-	if (highlightCache.size >= HIGHLIGHT_CACHE_MAX_SIZE) {
-		highlightCache.delete(highlightCache.keys().next().value!);
-	}
-
-	highlightCache.set(cacheKey, result);
-
-	return result;
-}
-
-export { trimCodePadding };
-
-/**
- * Detects if markdown ends with an incomplete code block (opened but not closed).
- * Returns the code block info if found, null otherwise.
- * @param markdown - The raw markdown string to check
- * @returns IncompleteCodeBlock info or null
- */
-export function detectIncompleteCodeBlock(markdown: string): IncompleteCodeBlock | null {
-	// Count all code fences in the markdown
-	// A code block is incomplete if there's an odd number of ``` fences
-	const fencePattern = new RegExp(CODE_BLOCK.FENCE_PATTERN.source, CODE_BLOCK.FENCE_PATTERN.flags);
-	const fences: number[] = [];
-
-	let fenceMatch;
-
-	while ((fenceMatch = fencePattern.exec(markdown)) !== null) {
-		// Store the position after the ```
-		const pos = fenceMatch[0].startsWith(NEWLINE) ? fenceMatch.index + 1 : fenceMatch.index;
-
-		fences.push(pos);
-	}
-
-	// If even number of fences (including 0), all code blocks are closed
-	if (fences.length % 2 === 0) {
-		return null;
-	}
-
-	// Odd number means last code block is incomplete
-	// The last fence is the opening of the incomplete block
-	const openingIndex = fences[fences.length - 1];
-	const afterOpening = markdown.slice(openingIndex + 3);
-	// Extract language and code content
-	const langMatch = afterOpening.match(CODE_BLOCK.LANG_PATTERN);
-	const language = langMatch?.[1] || CODE_BLOCK.DEFAULT_LANGUAGE;
-	const codeStartIndex = openingIndex + 3 + (langMatch?.[0]?.length ?? 0);
-	const code = markdown.slice(codeStartIndex);
-
-	return {
-		code,
-		language,
-		openingIndex
-	};
-}
diff --git a/tools/ui/src/lib/utils/css.ts b/tools/ui/src/lib/utils/css.ts
deleted file mode 100644
index 99351a7f4493..000000000000
--- a/tools/ui/src/lib/utils/css.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * Converts a rem CSS value to pixels based on the document root font size.
- */
-export function remToPx(rem: string): number {
-	const val = parseFloat(rem);
-	const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
-
-	return val * fontSize;
-}
diff --git a/tools/ui/src/lib/utils/get-datetime.ts b/tools/ui/src/lib/utils/get-datetime.ts
deleted file mode 100644
index 69e41ce0fc0b..000000000000
--- a/tools/ui/src/lib/utils/get-datetime.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * Browser executor for the `get_datetime` tool. It runs in the browser, so it
- * reports the user's own clock and time zone instead of the server's UTC time -
- * a chat about "tomorrow" means the user's tomorrow, not the host's.
- *
- * @see buildGetDatetimeToolDefinition in constants/get-datetime.ts - tool schema sent to the LLM
- */
-
-import { formatLocalIso } from './formatters';
-import type { ToolExecutionResult } from '$lib/types';
-
-/** The `result` field keeps the shape the `get_datetime` renderer already reads. */
-export function executeGetDatetimeTool(): ToolExecutionResult {
-	const now = new Date();
-
-	return {
-		content: JSON.stringify({
-			result: formatLocalIso(now),
-			timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
-		}),
-		isError: false
-	};
-}
diff --git a/tools/ui/src/lib/utils/index.ts b/tools/ui/src/lib/utils/index.ts
deleted file mode 100644
index a7ed91bd8b2a..000000000000
--- a/tools/ui/src/lib/utils/index.ts
+++ /dev/null
@@ -1,385 +0,0 @@
-/**
- * Unified exports for all utility functions
- * Import utilities from '$lib/utils' for cleaner imports
- *
- * For browser-only utilities (pdf-processing, audio-recording, svg-to-png,
- * webp-to-png, process-uploaded-files, convert-files-to-extra), use:
- * import { ... } from '$lib/utils/browser-only'
- */
-
-// API utilities
-export { getAuthHeaders, getJsonHeaders, sanitizeHeaders } from './api-headers';
-export { ApiError, apiDelete, apiFetch, apiFetchWithParams, apiPost } from './api-fetch';
-export { validateApiKey } from './api-key-validation';
-
-// Attachment utilities
-export { getAttachmentDisplayItems, isMcpPrompt, isMcpResource } from './attachment-display';
-export { isTextFile, isImageFile, isPdfFile, isAudioFile, isVideoFile } from './attachment-type';
-
-// Textarea utilities
-export { default as autoResizeTextarea } from './autoresize-textarea';
-
-// Branching utilities
-export {
-	filterByLeafNodeId,
-	findMessageById,
-	findLeafNode,
-	findDescendantMessages,
-	getMessageSiblings,
-	buildSiblingInfoMap
-} from './branching';
-
-// Code
-export {
-	highlightCode,
-	detectIncompleteCodeBlock,
-	splitGluedClosingCodeFences,
-	trimCodePadding,
-	type IncompleteCodeBlock
-} from './code';
-
-// Config helpers
-export { setConfigValue, getConfigValue, configToParameterRecord } from './config-helpers';
-
-// CORS Proxy
-export { buildProxiedIconUrl, buildProxiedUrl, buildProxiedHeaders } from './cors-proxy';
-
-// URL utilities
-export { extractRootDomain, sanitizeExternalUrl, canonicalizeServerUrl } from './url';
-
-// Model list helpers
-export {
-	filterModelOptions,
-	groupFavoriteOptions,
-	groupModelOptions,
-	windowLocalGroups,
-	type GroupedModelOptions,
-	type ModelItem,
-	type OrgGroup
-} from './model-list';
-
-// Progress helpers
-export { modelLoadFraction, modelLoadProgressText } from './progress';
-
-// Conversation utilities
-export {
-	createMessageCountMap,
-	getMessageCount,
-	getConversationModel,
-	buildConversationTree,
-	collectForkFamily,
-	type ConversationTreeItem
-} from './conversation-utils';
-
-// Clipboard utilities
-export {
-	copyToClipboard,
-	copyCodeToClipboard,
-	formatMessageForClipboard,
-	parseClipboardContent,
-	hasClipboardAttachments
-} from './clipboard';
-
-// File preview utilities
-export { getFileTypeLabel } from './file-preview';
-export { getPreviewText, generateConversationTitle } from './text';
-
-// File type utilities
-export {
-	getFileTypeCategory,
-	getFileTypeCategoryByExtension,
-	getFileTypeByExtension,
-	isFileTypeSupported
-} from './file-type';
-
-// Formatting utilities
-export {
-	formatFileSize,
-	formatParameters,
-	formatNumber,
-	formatJsonPretty,
-	formatTime,
-	formatLocalIso,
-	formatPerformanceTime,
-	formatRelativeTime,
-	formatAttachmentText
-} from './formatters';
-
-// IME utilities
-export { isIMEComposing } from './is-ime-composing';
-
-// LaTeX utilities
-export { maskInlineLaTeX, preprocessLaTeX } from './latex-protection';
-
-// Modality file validation utilities
-export {
-	isFileTypeSupportedByModel,
-	filterFilesByModalities,
-	generateModalityErrorMessage
-} from './modality-file-validation';
-
-// Model name utilities
-export { isValidModelName, normalizeModelName, orgOf, repoOf } from './model-names';
-
-// Sidecar token utilities
-export {
-	directoryOf,
-	isAuxSidecar,
-	isDraftSidecar,
-	isServerSidecarFile,
-	sidecarFromFileToken,
-	sidecarFromTag
-} from './sidecars';
-
-// Portal utilities
-export { portalToBody } from './portal-to-body';
-
-// Haptic utilities
-export { hapticTap } from './haptics';
-
-// Precision utilities
-export { normalizeFloatingPoint, normalizeNumber } from './precision';
-
-// Syntax highlighting utilities
-export { loadHighlightTheme } from './highlight-theme';
-export { getLanguageFromFilename } from './syntax-highlight-language';
-
-// Text file utilities
-export { isTextFileByName, readFileAsText, isLikelyTextFile } from './text-files';
-
-// Debounce utilities
-export { debounce } from './debounce';
-
-// Sanitization utilities
-export { sanitizeKeyValuePairKey, sanitizeKeyValuePairValue } from './sanitize';
-
-// Image error fallback utilities
-export { getImageErrorFallbackHtml } from './image-error-fallback';
-
-// SSE-with-JSON stream iterator (used by server tool streaming, decoupled
-// from chat.service.ts which embeds its own SSE parser for resume support)
-export { extractSseDataPayload, parseSseJsonStream, splitSseRecords } from './sse';
-
-// Stream session identity (conversation-id based)
-export { streamIdentity } from './stream-identity';
-
-// MCP utilities
-export {
-	detectMcpTransportFromUrl,
-	parseMcpServerSettings,
-	getMcpLogLevelIcon,
-	getMcpLogLevelClass,
-	isImageMimeType,
-	parseResourcePath,
-	getDisplayName,
-	getResourceDisplayName,
-	isCodeResource,
-	isImageResource,
-	getResourceIcon,
-	getResourceTextContent,
-	getResourceBlobContent,
-	downloadResourceContent,
-	getMcpIconUrl,
-	getMcpServerFaviconFallback,
-	getMcpServerLabel
-} from './mcp';
-
-// URI Template utilities
-export {
-	extractTemplateVariables,
-	expandTemplate,
-	isTemplateComplete,
-	normalizeResourceUri,
-	type UriTemplateVariable
-} from './uri-template';
-
-// Data URL utilities
-export { createBase64DataUrl } from './data-url';
-
-// Header utilities
-export { parseHeadersToArray, serializeHeaders } from './headers';
-
-// Working-directory display helpers (HOME-style tilde abbreviation)
-export {
-	abbreviateWorkingDir,
-	abbreviateHome,
-	lastPathSegment,
-	formatCwdMessage,
-	parseCwdMessage,
-	CWD_CHANGED_PREFIX,
-	CWD_CLEARED_TEXT,
-	type CwdMessageInfo
-} from './path-display';
-
-// Working-directory picker search helpers
-export {
-	splitPathQuery,
-	buildCaseInsensitiveGlob,
-	buildGlobSearchArgs,
-	rankEntries,
-	joinPath,
-	highlightMatch,
-	type PathQuery
-} from './working-directory';
-
-export { resolveTabTarget, resolveTabView, type TabView } from './chat-tabs';
-
-// Shared `file_glob_search` runner with a short-lived result cache
-export { runGlobSearch, runGlobSearchWithChildren } from './glob-search';
-
-// Mention-token detection (for the `@`-triggered file/folder mention picker)
-export {
-	findMentionToken,
-	takeMentionDismissSnapshot,
-	type MentionDismissSnapshot
-} from './mention-token';
-
-// Slash-command token detection (for the `/`-triggered command picker)
-export {
-	findCommandToken,
-	takeCommandDismissSnapshot,
-	type CommandDismissSnapshot
-} from './command-token';
-
-// Mention-badge visual contract (used by the chat form input / rehype
-// DOM paths that build the same chip without a Svelte mount)
-export {
-	containsFileMentionLink,
-	fileMentionLinkRe,
-	encodeFileLinkPath,
-	decodeFileLinkPath,
-	MENTION_BADGE_CLASSNAME,
-	MENTION_BADGE_ICON_CLASSNAME,
-	MENTION_BADGE_SVG_ATTRIBUTES,
-	MENTION_BADGE_FILE_ICON_PATHS,
-	MENTION_BADGE_FOLDER_ICON_PATHS,
-	getMentionBadgeIconPaths,
-	getMentionBadgeLabel,
-	splitMentionSegments,
-	buildMentionInsertion
-} from './mention-badge';
-
-// Chat template utilities
-export {
-	detectThinkingSupport,
-	detectThinkingSupportWithReason
-} from './chat-template-thinking-detector';
-
-// Agentic content utilities (structured section derivation)
-export {
-	deriveAgenticSections,
-	buildAssistantRawOutput,
-	parseToolResultWithMedia,
-	splitSearchSummaryList,
-	hasAgenticContent,
-	isSectionExpandedByDefault,
-	classifyToolResult,
-	classifyContinueIntent
-} from './agentic';
-
-// Line-level unified diff for tool result rendering (`edit_file` block)
-export { computeLineDiff, prefixFor, renderUnifiedDiff, type DiffLine } from './compute-line-diff';
-
-// Partial-incremental JSON parser for streaming tool arguments
-export { parsePartialJsonArgs } from './parse-partial-json-args';
-
-// `exec_shell_command` result parsing
-export { parseExecShellCommandError } from './parse-exec-shell-error';
-export {
-	parseExecShellCommandExitStatus,
-	isExitCodeSummaryLine,
-	type ExecShellExitStatus
-} from './parse-exec-shell-status';
-
-// Search-result parsing (web-search / fetch MCP tools)
-export {
-	SUPPORTED_WEB_SEARCH_TOOL_NAMES,
-	extractSearchResults,
-	extractSearchQuery,
-	faviconForUrl,
-	isWebSearchToolName,
-	looksLikeSearchResult
-} from './search-results';
-
-// Cache utilities
-export { TTLCache, ReactiveTTLMap } from './cache-ttl';
-
-// Redaction utilities
-export { redactValue } from './redact';
-
-// Request inspection utilities
-export {
-	getRequestUrl,
-	getRequestMethod,
-	getRequestBody,
-	summarizeRequestBody,
-	formatDiagnosticErrorMessage,
-	extractJsonRpcMethods,
-	type RequestBodySummary
-} from './request-helpers';
-
-// Abort signal utilities
-export {
-	throwIfAborted,
-	isAbortError,
-	createLinkedController,
-	createTimeoutSignal,
-	withAbortSignal
-} from './abort';
-
-// Tool-call meta utilities. Parsers for each server tool live next to
-// their renderer family under
-// `src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/`.
-// This module only carries the helpers that genuinely cross tool
-// boundaries (currently: parsing the tool-result blob into a JSON
-// object).
-export { tryParseToolResultObject } from './tool-call-meta';
-
-// Per-tool UI metadata (label + icon) used by the tool-call chrome.
-// Re-exported through $lib/utils so renderer components can read the
-// label without depending on $lib/constants directly.
-export { getToolUi } from './tool-ui';
-
-// Chat command picker
-
-export { getChatCommands } from './chat-commands';
-export {
-	canCompactMessages,
-	compactionCut,
-	compactionTokensBefore,
-	lastContextBearingMessage,
-	sliceAtLastCompaction
-} from './compaction';
-
-// Sandbox tool definition
-// SANDBOX_TOOL_DEFINITION is deprecated; kept for backward compatibility.
-export { buildSandboxToolDefinition, SANDBOX_TOOL_DEFINITION } from './sandbox-tool';
-
-// Browser `get_datetime` executor (the browser clock, not the server's)
-export { executeGetDatetimeTool } from './get-datetime';
-
-// Browser fallback for the server's get_info tool
-export { detectOs, executeBrowserInfoTool } from './browser-info';
-
-// Tool-use support detection from a chat template
-export { detectToolUseSupport } from './chat-template-tool-detector';
-
-// Model memory estimation
-export { minMemoryTierGb } from './model-compatibility';
-
-// GGUF file metadata, e.g. which encoders an mmproj carries
-export { type GgufMetadata, type GgufValue, readGgufMetadata } from './gguf-metadata';
-
-// Cryptography utilities
-
-export { uuid } from './uuid';
-
-// CSS utilities
-export { remToPx } from './css';
-
-// Audio format helper (used by agentic store and chat service)
-export { getAudioInputFormat } from './audio-format';
-export { groupModelFamilies, modelFamilyKey, type ModelFamilyGroup } from './model-families';
-
-// Svelte actions
-export { nearViewport } from './near-viewport';
diff --git a/tools/ui/src/lib/utils/model-compatibility.ts b/tools/ui/src/lib/utils/model-compatibility.ts
deleted file mode 100644
index 4f7e32fe6765..000000000000
--- a/tools/ui/src/lib/utils/model-compatibility.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Model memory estimation.
- *
- * Mirrors the app's compatibility check (Model+Compatibility.swift): the
- * runtime budget is RAM x 0.75 minus a fixed overhead, and a file fits when
- * its size with headroom stays under that budget. The result is the smallest
- * memory tier that can run the model, so the UI presents an honest machine
- * requirement instead of a raw file size. Context length and
- * device-specific budgets are deliberately ignored - callers present the
- * requirement and let the user judge.
- */
-import {
-	MB_PER_GB,
-	MEM_TIERS,
-	MIB_BYTES,
-	QUANT_WEIGHT,
-	RAM_BUDGET_RATIO,
-	RAM_OVERHEAD_MB
-} from '$lib/constants';
-
-/**
- * Smallest memory tier (GB) that can run a model of the given file size,
- * or null if nothing fits even the largest tier.
- */
-export function minMemoryTierGb(sizeBytes: number): number | null {
-	if (!sizeBytes) return null;
-
-	const weightMb = (sizeBytes / MIB_BYTES) * QUANT_WEIGHT;
-
-	for (const tier of MEM_TIERS) {
-		const budgetMb = tier * MB_PER_GB * RAM_BUDGET_RATIO - RAM_OVERHEAD_MB;
-
-		if (weightMb <= budgetMb) return tier;
-	}
-
-	return null;
-}
diff --git a/tools/ui/src/lib/utils/near-viewport.ts b/tools/ui/src/lib/utils/near-viewport.ts
deleted file mode 100644
index 2af6a6bcfb26..000000000000
--- a/tools/ui/src/lib/utils/near-viewport.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type { ActionReturn } from 'svelte/action';
-
-/** Margin around the viewport that already counts as "near". */
-const NEAR_VIEWPORT_MARGIN = '200px';
-
-/**
- * Calls back once the element comes near the viewport, so per-row work that costs
- * a request (avatars, Hub details) does not fire on mount.
- */
-export function nearViewport(node: HTMLElement, onNear: () => void): ActionReturn {
-	if (typeof IntersectionObserver === 'undefined') {
-		onNear();
-
-		return {};
-	}
-
-	const observer = new IntersectionObserver(
-		(entries) => {
-			if (entries.some((entry) => entry.isIntersecting)) {
-				observer.disconnect();
-				onNear();
-			}
-		},
-		{ rootMargin: NEAR_VIEWPORT_MARGIN }
-	);
-
-	observer.observe(node);
-
-	return {
-		destroy() {
-			observer.disconnect();
-		}
-	};
-}
diff --git a/tools/ui/src/lib/utils/search-chats.ts b/tools/ui/src/lib/utils/search-chats.ts
deleted file mode 100644
index b9811bb415ff..000000000000
--- a/tools/ui/src/lib/utils/search-chats.ts
+++ /dev/null
@@ -1,665 +0,0 @@
-/**
- * search_chats core: parameter parsing, matching and formatting. Data comes through a loader, so this has no IndexedDB access.
- * Only user and assistant text on the visible branch is searched and shown, so tool output (e.g. older search results) cannot match.
- */
-
-import { filterByLeafNodeId } from './branching';
-import { formatLocalIso } from './formatters';
-import {
-	SEARCH_CHATS_CUT_NOTICE,
-	SEARCH_CHATS_DATE_REGEX,
-	SEARCH_CHATS_DATE_TIME_REGEX,
-	SEARCH_CHATS_ELLIPSIS,
-	SEARCH_CHATS_EXCERPT_LEAD_RATIO,
-	SEARCH_CHATS_EXCERPT_RECENTER_RATIO,
-	SEARCH_CHATS_FIELD_SEPARATOR,
-	SEARCH_CHATS_ID_MAX_CHARS,
-	SEARCH_CHATS_LIMIT_CHATS_DEFAULT,
-	SEARCH_CHATS_LIMIT_CHATS_MAX,
-	SEARCH_CHATS_LIMIT_MESSAGES_DEFAULT,
-	SEARCH_CHATS_LIMIT_MESSAGES_MAX,
-	SEARCH_CHATS_MAX_IDS,
-	SEARCH_CHATS_MAX_PATTERNS,
-	SEARCH_CHATS_MESSAGE_CHARS_DEFAULT,
-	SEARCH_CHATS_MESSAGE_CHARS_MAX,
-	SEARCH_CHATS_MESSAGE_CHARS_MIN,
-	SEARCH_CHATS_OUTPUT_MAX_CHARS,
-	SEARCH_CHATS_PATTERN_MAX_CHARS,
-	SEARCH_CHATS_TOOL_KEY
-} from '$lib/constants';
-import { MessageRole, SearchChatsMessageSelection, SearchChatsOrder } from '$lib/enums';
-import type { DatabaseConversation, DatabaseMessage } from '$lib/types/database';
-
-export class SearchChatsError extends Error {
-	constructor(message: string) {
-		super(message);
-		this.name = 'SearchChatsError';
-	}
-}
-
-export interface SearchChatsParams {
-	byConvIds?: string[];
-	byMatches?: string[];
-	/** Inclusive, ms since epoch */
-	fromTimestamp?: number;
-	/** Exclusive, ms since epoch */
-	toTimestamp?: number;
-	order: SearchChatsOrder;
-	limitChats: number;
-	offsetChats: number;
-	limitMessages: number;
-	messageSelection: SearchChatsMessageSelection;
-	maxMessageChars: number;
-	includeCurrent: boolean;
-}
-
-export interface SearchChatsTimeRange {
-	from?: number;
-	to?: number;
-}
-
-export interface SearchChatsLoader {
-	/** Messages of the given conversations (all for `null`); with `range`, only of conversations with a message in [from, to) */
-	messages(convIds: string[] | null, range?: SearchChatsTimeRange): Promise;
-}
-
-/** Tool policy with search_chats disabled, for rows that predate the tool */
-export function withSearchChatsDisabled(disabledTools: string[] = []): string[] {
-	return disabledTools.includes(SEARCH_CHATS_TOOL_KEY)
-		? disabledTools
-		: [...disabledTools, SEARCH_CHATS_TOOL_KEY];
-}
-
-/** `text.slice(start, end)` without cutting a surrogate pair in half */
-function sliceText(text: string, start: number, end: number = text.length): string {
-	const isHigh = (i: number) => {
-		const code = text.charCodeAt(i);
-
-		return code >= 0xd800 && code <= 0xdbff;
-	};
-
-	if (start > 0 && isHigh(start - 1)) start++;
-
-	if (end > start && end < text.length && isHigh(end - 1)) end--;
-
-	return text.slice(start, Math.max(start, end));
-}
-
-function isCalendarDate(year: number, month: number, day: number): boolean {
-	const date = new Date(Date.UTC(year, month - 1, day));
-
-	return date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
-}
-
-function stringList(
-	raw: unknown,
-	name: string,
-	maxEntries: number,
-	maxChars: number
-): string[] | undefined {
-	if (raw === undefined || raw === null) return undefined;
-
-	const list = typeof raw === 'string' ? [raw] : raw;
-
-	if (!Array.isArray(list) || !list.every((v) => typeof v === 'string' && v.trim() !== '')) {
-		throw new SearchChatsError(`${name} must be an array of non-empty strings`);
-	}
-
-	if (list.length === 0) return undefined;
-
-	if (list.length > maxEntries) {
-		throw new SearchChatsError(`${name} takes at most ${maxEntries} entries`);
-	}
-
-	if (list.some((v) => v.length > maxChars)) {
-		throw new SearchChatsError(`${name} entries must be at most ${maxChars} characters`);
-	}
-
-	return list.map((v) => v.trim());
-}
-
-function integer(raw: unknown, name: string, min: number, max: number, fallback: number): number {
-	if (raw === undefined || raw === null || raw === '') return fallback;
-
-	const n = Number(raw);
-
-	if (!Number.isInteger(n) || n < min || n > max) {
-		throw new SearchChatsError(`${name} must be an integer from ${min} to ${max}`);
-	}
-
-	return n;
-}
-
-function oneOf(raw: unknown, name: string, options: T[], fallback: T): T {
-	if (raw === undefined || raw === null || raw === '') return fallback;
-
-	const value = String(raw).toLowerCase() as T;
-
-	if (!options.includes(value)) {
-		throw new SearchChatsError(`${name} must be one of: ${options.join(', ')}`);
-	}
-
-	return value;
-}
-
-/** ISO 8601 date or date-time; without an offset it is the user's local time */
-function timestamp(raw: unknown, name: string): number | undefined {
-	if (raw === undefined || raw === null || raw === '') return undefined;
-
-	const error = new SearchChatsError(
-		`${name} must be an ISO 8601 date or date-time, e.g. 2026-11-10 or 2026-11-10T14:30 (local time unless an offset is given)`
-	);
-
-	if (typeof raw !== 'string') throw error;
-
-	const value = raw.trim().replace(' ', 'T');
-	const isDate = SEARCH_CHATS_DATE_REGEX.test(value);
-
-	if (!isDate && !SEARCH_CHATS_DATE_TIME_REGEX.test(value)) throw error;
-
-	const [year, month, day] = value.slice(0, 10).split('-').map(Number);
-
-	// Date.parse rolls 2026-02-30T10:00 over to March, it does not reject it
-	if (!isCalendarDate(year, month, day)) throw error;
-
-	let ms: number;
-
-	if (isDate) {
-		// Date.parse reads a date-only string as UTC midnight, the user means local midnight
-		ms = new Date(year, month - 1, day).getTime();
-	} else {
-		const [hours, minutes, seconds = 0] = value
-			.slice(11, 19)
-			.split(/[:.Z+-]/)
-			.map(Number);
-
-		if (hours > 23 || minutes > 59 || seconds > 59) throw error;
-
-		ms = Date.parse(value);
-	}
-
-	if (Number.isNaN(ms)) throw error;
-
-	return ms;
-}
-
-/** Throws SearchChatsError with a message for the model */
-export function parseSearchChatsParams(raw: Record): SearchChatsParams {
-	const byConvIds = stringList(
-		raw.by_conv_ids,
-		'by_conv_ids',
-		SEARCH_CHATS_MAX_IDS,
-		SEARCH_CHATS_ID_MAX_CHARS
-	);
-	const byMatches = stringList(
-		raw.by_matches,
-		'by_matches',
-		SEARCH_CHATS_MAX_PATTERNS,
-		SEARCH_CHATS_PATTERN_MAX_CHARS
-	);
-	const fromTimestamp = timestamp(raw.from_timestamp, 'from_timestamp');
-	const toTimestamp = timestamp(raw.to_timestamp, 'to_timestamp');
-
-	if (fromTimestamp !== undefined && toTimestamp !== undefined && toTimestamp <= fromTimestamp) {
-		throw new SearchChatsError('to_timestamp must be after from_timestamp');
-	}
-
-	const defaultSelection = byMatches
-		? SearchChatsMessageSelection.MATCHING
-		: fromTimestamp !== undefined
-			? SearchChatsMessageSelection.EARLIEST
-			: SearchChatsMessageSelection.LATEST;
-	const messageSelection = oneOf(
-		raw.message_selection,
-		'message_selection',
-		Object.values(SearchChatsMessageSelection),
-		defaultSelection
-	);
-
-	if (messageSelection === SearchChatsMessageSelection.MATCHING && !byMatches) {
-		throw new SearchChatsError(
-			`message_selection "${SearchChatsMessageSelection.MATCHING}" needs by_matches; use "${SearchChatsMessageSelection.LATEST}" or "${SearchChatsMessageSelection.EARLIEST}"`
-		);
-	}
-
-	return {
-		byConvIds,
-		byMatches,
-		fromTimestamp,
-		includeCurrent: raw.include_current === true || raw.include_current === 'true',
-		limitChats: integer(
-			raw.limit_chats,
-			'limit_chats',
-			1,
-			SEARCH_CHATS_LIMIT_CHATS_MAX,
-			SEARCH_CHATS_LIMIT_CHATS_DEFAULT
-		),
-		limitMessages: integer(
-			raw.limit_messages,
-			'limit_messages',
-			0,
-			SEARCH_CHATS_LIMIT_MESSAGES_MAX,
-			SEARCH_CHATS_LIMIT_MESSAGES_DEFAULT
-		),
-		maxMessageChars: integer(
-			raw.max_message_chars,
-			'max_message_chars',
-			SEARCH_CHATS_MESSAGE_CHARS_MIN,
-			SEARCH_CHATS_MESSAGE_CHARS_MAX,
-			SEARCH_CHATS_MESSAGE_CHARS_DEFAULT
-		),
-		messageSelection,
-		offsetChats: integer(raw.offset_chats, 'offset_chats', 0, Number.MAX_SAFE_INTEGER, 0),
-		order: oneOf(
-			raw.order_timestamp,
-			'order_timestamp',
-			Object.values(SearchChatsOrder),
-			SearchChatsOrder.DESC
-		),
-		toTimestamp
-	};
-}
-
-/** SQL LIKE (`%` any run, `_` one char) without regex, so a pattern cannot backtrack exponentially */
-function like(text: string, pattern: string): boolean {
-	let si = 0;
-	let pi = 0;
-	let star = -1;
-	let mark = 0;
-
-	while (si < text.length) {
-		if (
-			pi < pattern.length &&
-			(pattern[pi] === '_' || (pattern[pi] !== '%' && pattern[pi] === text[si]))
-		) {
-			si++;
-			pi++;
-		} else if (pi < pattern.length && pattern[pi] === '%') {
-			star = pi++;
-			mark = si;
-		} else if (star !== -1) {
-			pi = star + 1;
-			si = ++mark;
-		} else {
-			return false;
-		}
-	}
-
-	while (pi < pattern.length && pattern[pi] === '%') pi++;
-
-	return pi === pattern.length;
-}
-
-interface Matcher {
-	test(text: string): boolean;
-	/** Offset in `text` of the longest literal part of the first matching pattern, -1 if none */
-	locate(text: string): number;
-}
-
-function buildMatcher(patterns: string[]): Matcher {
-	// a pattern without % means "contains"
-	const compiled = patterns.map((p) => {
-		const lower = p.toLowerCase();
-		const pattern = lower.includes('%') ? lower : `%${lower}%`;
-		const needle = pattern
-			.split(/[%_]+/)
-			.reduce((best, part) => (part.length > best.length ? part : best), '');
-
-		return { needle, pattern };
-	});
-
-	return {
-		locate: (text) => {
-			const lower = text.toLowerCase();
-
-			// lowercasing can change the length (e.g. U+0130), then offsets do not map back
-			if (lower.length !== text.length) return -1;
-
-			const hit = compiled.find(({ pattern }) => like(lower, pattern));
-
-			if (!hit) return -1;
-
-			return hit.needle ? lower.indexOf(hit.needle) : 0;
-		},
-		test: (text) => {
-			const lower = text.toLowerCase();
-
-			return compiled.some(({ pattern }) => like(lower, pattern));
-		}
-	};
-}
-
-/** User and assistant text on the visible branch, in chat order */
-function visibleMessages(
-	conv: DatabaseConversation,
-	messages: DatabaseMessage[]
-): DatabaseMessage[] {
-	if (messages.length === 0) return [];
-
-	return filterByLeafNodeId(messages, conv.currNode ?? '').filter(
-		(m) =>
-			(m.role === MessageRole.USER || m.role === MessageRole.ASSISTANT) &&
-			!m.isSynthetic &&
-			typeof m.content === 'string' &&
-			m.content.trim() !== ''
-	);
-}
-
-function formatDate(ms: number): string {
-	const date = new Date(ms);
-
-	return Number.isNaN(date.getTime()) ? 'unknown' : formatLocalIso(date);
-}
-
-function excerpt(text: string, maxChars: number, matchAt: number): string {
-	if (text.length <= maxChars) return text;
-
-	if (matchAt > maxChars * SEARCH_CHATS_EXCERPT_RECENTER_RATIO) {
-		const lead = Math.floor(maxChars * SEARCH_CHATS_EXCERPT_LEAD_RATIO);
-		const start = Math.max(0, Math.min(matchAt - lead, text.length - maxChars));
-		const end = start + maxChars;
-		const before = start > 0 ? SEARCH_CHATS_ELLIPSIS : '';
-		const after = end < text.length ? `${SEARCH_CHATS_ELLIPSIS}[+${text.length - end} chars]` : '';
-
-		return `${before}${sliceText(text, start, end)}${after}`;
-	}
-
-	return `${sliceText(text, 0, maxChars)}${SEARCH_CHATS_ELLIPSIS}[+${text.length - maxChars} chars]`;
-}
-
-interface ChatHit {
-	conv: DatabaseConversation;
-	/** Visible messages of the whole chat, positions are counted on these */
-	messages: DatabaseMessage[];
-	/** Visible messages inside the time window (all of them without one) */
-	inRange: DatabaseMessage[];
-	titleMatched: boolean;
-	matched: DatabaseMessage[];
-}
-
-function formatMessage(
-	message: DatabaseMessage,
-	position: number,
-	params: SearchChatsParams,
-	matcher: Matcher | null
-): string {
-	const text = message.content.trim();
-	const matchAt = matcher ? matcher.locate(text) : -1;
-	const body = excerpt(text, params.maxMessageChars, matchAt).replace(/\n+/g, '\n  ');
-	const files = (message.extra ?? []).map((e) => e.name).filter(Boolean);
-	// names are user data, quote them so they cannot pass as result structure
-	const attachments =
-		files.length > 0 ? ` [attachments: ${files.map((f) => JSON.stringify(f)).join(', ')}]` : '';
-
-	return `#${position} ${message.role}${SEARCH_CHATS_FIELD_SEPARATOR}${formatDate(message.timestamp)}: ${body}${attachments}`;
-}
-
-interface ChatBlock {
-	head: string[];
-	/** Formatted messages, in chat order */
-	messages: string[];
-	/** On a cut, keep the last messages (latest / matching) instead of the first */
-	keepTail: boolean;
-}
-
-const blockText = ({ head, messages }: ChatBlock) => [...head, ...messages].join('\n');
-
-/** Fit a chat block into `room` chars by dropping whole messages from the less wanted end */
-function cutChat(block: ChatBlock, room: number): string {
-	const ordered = block.keepTail ? [...block.messages].reverse() : block.messages;
-	const kept: string[] = [];
-	const head = block.head.join('\n');
-
-	let size = head.length + 1 + SEARCH_CHATS_CUT_NOTICE.length;
-
-	for (const line of ordered) {
-		if (size + 1 + line.length > room) break;
-
-		kept.push(line);
-		size += 1 + line.length;
-	}
-
-	if (block.keepTail) kept.reverse();
-
-	const lines = block.keepTail
-		? [head, SEARCH_CHATS_CUT_NOTICE, ...kept]
-		: [head, ...kept, SEARCH_CHATS_CUT_NOTICE];
-	const text = lines.join('\n');
-
-	// even the head does not fit (very long title)
-	if (text.length > room) {
-		return `${sliceText(text, 0, Math.max(0, room - SEARCH_CHATS_CUT_NOTICE.length))}${SEARCH_CHATS_CUT_NOTICE}`;
-	}
-
-	return text;
-}
-
-function formatChat(
-	hit: ChatHit,
-	index: number,
-	params: SearchChatsParams,
-	matcher: Matcher | null,
-	timed: boolean
-): ChatBlock {
-	const { conv, inRange, matched, messages, titleMatched } = hit;
-	const summary = [`conv_id: ${conv.id}`, `updated ${formatDate(conv.lastModified)}`];
-	// titles are user data, JSON quoting escapes quotes and newlines
-	const title = JSON.stringify(conv.name ?? '');
-
-	if (params.limitMessages === 0) {
-		return {
-			head: [
-				`- ${title}${SEARCH_CHATS_FIELD_SEPARATOR}${summary.join(SEARCH_CHATS_FIELD_SEPARATOR)}`
-			],
-			keepTail: false,
-			messages: []
-		};
-	}
-
-	const counts = timed
-		? `${messages.length} messages, ${inRange.length} in the time range`
-		: `${messages.length} messages`;
-	const lines = [
-		`## Chat ${index}: ${title}`,
-		[...summary, counts].join(SEARCH_CHATS_FIELD_SEPARATOR)
-	];
-	const n = params.limitMessages;
-
-	let picked: DatabaseMessage[];
-
-	if (params.messageSelection === SearchChatsMessageSelection.MATCHING && matched.length > 0) {
-		const where = [titleMatched ? 'title' : '', `${matched.length} message(s)`]
-			.filter(Boolean)
-			.join(', ');
-
-		picked = matched.slice(-n);
-		lines.push(`matched in: ${where}${matched.length > n ? ` (showing the last ${n})` : ''}`);
-	} else {
-		if (params.messageSelection === SearchChatsMessageSelection.MATCHING) {
-			lines.push('matched in: title only, showing the latest messages');
-		}
-
-		picked =
-			params.messageSelection === SearchChatsMessageSelection.EARLIEST
-				? inRange.slice(0, n)
-				: inRange.slice(-n);
-	}
-
-	if (messages.length === 0) lines.push('(no messages)');
-
-	const position = new Map(messages.map((m, i) => [m.id, i + 1]));
-
-	return {
-		head: lines,
-		keepTail: params.messageSelection !== SearchChatsMessageSelection.EARLIEST,
-		messages: picked.map((m) => formatMessage(m, position.get(m.id)!, params, matcher))
-	};
-}
-
-function groupByConversation(messages: DatabaseMessage[]): Map {
-	const groups = new Map();
-
-	for (const m of messages) {
-		const group = groups.get(m.convId);
-
-		if (group) group.push(m);
-		else groups.set(m.convId, [m]);
-	}
-
-	return groups;
-}
-
-function describeQuery(params: SearchChatsParams): string {
-	const parts: string[] = [];
-
-	if (params.byMatches) parts.push(`matching ${JSON.stringify(params.byMatches)}`);
-
-	if (params.byConvIds) parts.push('by conv_id');
-
-	if (params.fromTimestamp !== undefined) parts.push(`from ${formatDate(params.fromTimestamp)}`);
-
-	if (params.toTimestamp !== undefined) parts.push(`before ${formatDate(params.toTimestamp)}`);
-
-	return parts.join(' ');
-}
-
-/**
- * Run a search and render the result as text for the model.
- * `conversations` holds the candidates: all conversations, or only those of by_conv_ids.
- */
-export async function searchChats(
-	conversations: DatabaseConversation[],
-	params: SearchChatsParams,
-	loader: SearchChatsLoader,
-	currentConversationId?: string
-): Promise {
-	const { byConvIds, fromTimestamp, toTimestamp } = params;
-	const timed = fromTimestamp !== undefined || toTimestamp !== undefined;
-	const notes: string[] = [];
-
-	let candidates = conversations;
-
-	if (byConvIds) {
-		const found = new Set(candidates.map((c) => c.id));
-		const missing = byConvIds.filter((id) => !found.has(id));
-
-		if (missing.length > 0) notes.push(`not found: ${missing.join(', ')}`);
-
-		candidates = candidates.filter((c) => byConvIds.includes(c.id));
-	}
-
-	if (currentConversationId && !params.includeCurrent) {
-		if (byConvIds?.includes(currentConversationId)) {
-			notes.push(
-				'the current chat is hidden (you already see it); set include_current=true to read it'
-			);
-		}
-
-		candidates = candidates.filter((c) => c.id !== currentConversationId);
-	}
-
-	const matcher = params.byMatches ? buildMatcher(params.byMatches) : null;
-	const isInRange = (m: DatabaseMessage) =>
-		(fromTimestamp === undefined || m.timestamp >= fromTimestamp) &&
-		(toTimestamp === undefined || m.timestamp < toTimestamp);
-	const toHit = (conv: DatabaseConversation, raw: DatabaseMessage[]): ChatHit => {
-		const messages = visibleMessages(conv, raw);
-		const inRange = timed ? messages.filter(isInRange) : messages;
-		const matched = matcher ? inRange.filter((m) => matcher.test(m.content)) : [];
-
-		return { conv, inRange, matched, messages, titleMatched: !!matcher?.test(conv.name ?? '') };
-	};
-
-	let hits: ChatHit[];
-
-	if (matcher || timed) {
-		// which chats qualify depends on their messages, so read them before paging
-		const ids = byConvIds ? candidates.map((c) => c.id) : null;
-		const range = timed ? { from: fromTimestamp, to: toTimestamp } : undefined;
-		const byConv = groupByConversation(await loader.messages(ids, range));
-
-		hits = [];
-
-		for (const conv of candidates) {
-			const raw = byConv.get(conv.id) ?? [];
-
-			// cheap check on all messages before building the visible branch
-			if (
-				matcher &&
-				!matcher.test(conv.name ?? '') &&
-				!raw.some((m) => typeof m.content === 'string' && matcher.test(m.content))
-			) {
-				continue;
-			}
-
-			const hit = toHit(conv, raw);
-
-			// with a time window, a chat needs visible messages inside it, a title match is not enough
-			if (timed && hit.inRange.length === 0) continue;
-
-			if (matcher && !hit.titleMatched && hit.matched.length === 0) continue;
-
-			hits.push(hit);
-		}
-	} else {
-		hits = candidates.map((conv) => toHit(conv, []));
-	}
-
-	const sign = params.order === SearchChatsOrder.ASC ? 1 : -1;
-
-	hits.sort((a, b) => sign * (a.conv.lastModified - b.conv.lastModified));
-
-	const total = hits.length;
-	const page = hits.slice(params.offsetChats, params.offsetChats + params.limitChats);
-
-	// plain listing or reading: only the chats on this page need their messages
-	if (!matcher && !timed && params.limitMessages > 0 && page.length > 0) {
-		const byConv = groupByConversation(await loader.messages(page.map((h) => h.conv.id)));
-
-		page.forEach((hit, i) => (page[i] = toHit(hit.conv, byConv.get(hit.conv.id) ?? [])));
-	}
-
-	const orderLabel = params.order === SearchChatsOrder.ASC ? 'oldest first' : 'newest first';
-	const range =
-		page.length === 0
-			? `showing none of ${total}`
-			: `showing ${params.offsetChats + 1}-${params.offsetChats + page.length} of ${total}`;
-	const header = [
-		`${`${total} chat(s) ${describeQuery(params)}`.trim()} (${orderLabel}, ${range})`,
-		...notes
-	].join('\n');
-	const headerSeparator = '\n\n';
-	const separator = params.limitMessages === 0 ? '\n' : '\n\n';
-	const moreNote = (hidden: number, nextOffset: number) =>
-		`[${hidden} more chat(s) on this page not shown: use offset_chats=${nextOffset}, or lower limit_messages]`;
-	// room for the note in its longest form: both numbers at their largest
-	const noteRoom =
-		separator.length + moreNote(page.length, params.offsetChats + page.length).length;
-	const blocks: string[] = [];
-
-	let size = header.length;
-
-	for (const [i, hit] of page.entries()) {
-		const block = formatChat(hit, params.offsetChats + i + 1, params, matcher, timed);
-		const text = blockText(block);
-		const gap = blocks.length === 0 ? headerSeparator.length : separator.length;
-		const isLast = i === page.length - 1;
-		const limit = SEARCH_CHATS_OUTPUT_MAX_CHARS - (isLast ? 0 : noteRoom);
-
-		if (size + gap + text.length > limit) {
-			// always show at least part of the first chat
-			if (blocks.length === 0) blocks.push(cutChat(block, limit - size - gap));
-
-			break;
-		}
-
-		blocks.push(text);
-		size += gap + text.length;
-	}
-
-	if (blocks.length < page.length) {
-		blocks.push(moreNote(page.length - blocks.length, params.offsetChats + blocks.length));
-	}
-
-	return blocks.length > 0 ? `${header}${headerSeparator}${blocks.join(separator)}` : header;
-}
diff --git a/tools/ui/src/routes/(chat)/+layout.svelte b/tools/ui/src/routes/(chat)/+layout.svelte
deleted file mode 100644
index 191614d2e438..000000000000
--- a/tools/ui/src/routes/(chat)/+layout.svelte
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-
- {#if showTabs} - - {/if} - - -
- -{@render children?.()} diff --git a/tools/ui/src/routes/(chat)/+page.svelte b/tools/ui/src/routes/(chat)/+page.svelte deleted file mode 100644 index 53975d7b3d7f..000000000000 --- a/tools/ui/src/routes/(chat)/+page.svelte +++ /dev/null @@ -1,99 +0,0 @@ - - - - {APP_NAME} - - - diff --git a/tools/ui/src/routes/(chat)/+page.ts b/tools/ui/src/routes/(chat)/+page.ts deleted file mode 100644 index 3be3d5a9567b..000000000000 --- a/tools/ui/src/routes/(chat)/+page.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { PageLoad } from './$types'; -import { loadAppRoute } from '$lib/stores/init'; - -export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); diff --git a/tools/ui/src/routes/(chat)/chat/[id]/+page.svelte b/tools/ui/src/routes/(chat)/chat/[id]/+page.svelte deleted file mode 100644 index ce6c88ba733a..000000000000 --- a/tools/ui/src/routes/(chat)/chat/[id]/+page.svelte +++ /dev/null @@ -1,146 +0,0 @@ - - - - {conversationsStore.activeConversation?.name || 'Chat'} - {APP_NAME} - - - diff --git a/tools/ui/src/routes/(chat)/chat/[id]/+page.ts b/tools/ui/src/routes/(chat)/chat/[id]/+page.ts deleted file mode 100644 index 3be3d5a9567b..000000000000 --- a/tools/ui/src/routes/(chat)/chat/[id]/+page.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { PageLoad } from './$types'; -import { loadAppRoute } from '$lib/stores/init'; - -export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); diff --git a/tools/ui/src/routes/+layout.svelte b/tools/ui/src/routes/+layout.svelte deleted file mode 100644 index b0d5ced314c2..000000000000 --- a/tools/ui/src/routes/+layout.svelte +++ /dev/null @@ -1,471 +0,0 @@ - - - - {#if pwaAssetsHead.themeColor} - - {/if} - - {#if settingsStore.config.customCss} - - {/if} - - {#each pwaAssetsHead.links as link (link.href)} - - {/each} - - - - - - - - - -
- - - - -
- - {#if deviceStore.isMobile && !uiStore.isComposerExpanded} - - - {#if deviceStore.isIOSSafari} - - - - - {/if} - - - - {/if} - - - {#if deviceStore.isMobile && !page.url.hash.includes(ROUTES.SEARCH) && !uiStore.isComposerExpanded} -
- -
- {/if} - - {@render children?.()} -
- - - {#if deviceStore.isMobile} - - - - - {/if} -
- - - - - - - {#if import.meta.env.DEV && import.meta.env.VITE_DEBUG} - {#await import('../../tests/debug/ViewportProbe.svelte') then { default: ViewportProbe }} - - {/await} - {/if} -
- - -
- {#if showBuildVersion && versionStore.build} - {versionStore.build} - {/if} - - -
diff --git a/tools/ui/src/routes/mcp-servers/+page.svelte b/tools/ui/src/routes/mcp-servers/+page.svelte deleted file mode 100644 index e155fa9baaba..000000000000 --- a/tools/ui/src/routes/mcp-servers/+page.svelte +++ /dev/null @@ -1,24 +0,0 @@ - - - - MCP Servers - {APP_NAME} - - - -
-
-

MCP Servers

- -

- Connect the servers whose tools, prompts and resources your chats can use. -

-
- - -
diff --git a/tools/ui/src/routes/mcp-servers/+page.ts b/tools/ui/src/routes/mcp-servers/+page.ts deleted file mode 100644 index 3be3d5a9567b..000000000000 --- a/tools/ui/src/routes/mcp-servers/+page.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { PageLoad } from './$types'; -import { loadAppRoute } from '$lib/stores/init'; - -export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); diff --git a/tools/ui/src/routes/models/+page.svelte b/tools/ui/src/routes/models/+page.svelte deleted file mode 100644 index 0a0da7c56347..000000000000 --- a/tools/ui/src/routes/models/+page.svelte +++ /dev/null @@ -1,53 +0,0 @@ - - - - Models - {APP_NAME} - - -
-
-
-

Models

- -

- Load, configure and remove the models this server can run. -

-
- - {#if uiStore.isDiscoverEnabled} - - {/if} -
- - -
diff --git a/tools/ui/src/routes/models/+page.ts b/tools/ui/src/routes/models/+page.ts deleted file mode 100644 index 3be3d5a9567b..000000000000 --- a/tools/ui/src/routes/models/+page.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { PageLoad } from './$types'; -import { loadAppRoute } from '$lib/stores/init'; - -export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); diff --git a/tools/ui/src/routes/search/+page.svelte b/tools/ui/src/routes/search/+page.svelte deleted file mode 100644 index cd462688179b..000000000000 --- a/tools/ui/src/routes/search/+page.svelte +++ /dev/null @@ -1,120 +0,0 @@ - - - - Search · llama.cpp - - -
- -
- -
- -
- - diff --git a/tools/ui/src/routes/settings/+page.svelte b/tools/ui/src/routes/settings/+page.svelte deleted file mode 100644 index 92da7e07029f..000000000000 --- a/tools/ui/src/routes/settings/+page.svelte +++ /dev/null @@ -1,28 +0,0 @@ - - - - Settings - {APP_NAME} - - - -
-
-

Settings

- -

How the app looks, chats and talks to the server.

-
- - toast.success('Settings saved')} - /> -
diff --git a/tools/ui/src/routes/settings/+page.ts b/tools/ui/src/routes/settings/+page.ts deleted file mode 100644 index 3be3d5a9567b..000000000000 --- a/tools/ui/src/routes/settings/+page.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { PageLoad } from './$types'; -import { loadAppRoute } from '$lib/stores/init'; - -export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); diff --git a/tools/ui/src/virtual-nerdamer.d.ts b/tools/ui/src/virtual-nerdamer.d.ts deleted file mode 100644 index 433fb2b3bd20..000000000000 --- a/tools/ui/src/virtual-nerdamer.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -declare module 'virtual:nerdamer' { - const code: string; - export default code; -} diff --git a/tools/ui/svelte.config.js b/tools/ui/svelte.config.js deleted file mode 100644 index 286a459973d9..000000000000 --- a/tools/ui/svelte.config.js +++ /dev/null @@ -1,38 +0,0 @@ -import adapter from '@sveltejs/adapter-static'; -import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; -import { mdsvex } from 'mdsvex'; - -// CMake sets LLAMA_UI_OUT_DIR to the staging dir under the build tree; manual -// `npm run build` runs without the env var default to ./dist. -const outDir = process.env.LLAMA_UI_OUT_DIR ?? './dist'; -/** @type {import('@sveltejs/kit').Config} */ -const config = { - extensions: ['.svelte', '.svx'], - - kit: { - adapter: adapter({ - assets: outDir, - fallback: 'index.html', - pages: outDir, - precompress: false, - strict: true - }), - output: { - bundleStrategy: 'single' - }, - paths: { - relative: true - }, - router: { type: 'hash' } - }, - - // Consult https://svelte.dev/docs/kit/integrations - // for more information about preprocessors - // mdsvex is for content pages we write ourselves (e.g. release notes reachable from the - // chat app): .svx files compiled to components at build time. No page uses it yet. - // It can't render chat input or messages, which are typed at runtime and go through - // the remark/rehype pipeline in MarkdownContent instead. - preprocess: [vitePreprocess(), mdsvex()] -}; - -export default config; diff --git a/tools/ui/tests/client/chat-form-input.svelte.test.ts b/tools/ui/tests/client/chat-form-input.svelte.test.ts deleted file mode 100644 index e16e9a15a13e..000000000000 --- a/tools/ui/tests/client/chat-form-input.svelte.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -// Guards the chat form input contract: a live-preview markdown editor whose value -// stays the exact markdown source, with mention links shown as badges while their -// block is edited and every block rendered once the editor loses focus. The form's -// key and paste handlers run first and win when they handle the event. - -import { EditorView } from '@codemirror/view'; -import ChatFormInput from '$lib/components/app/chat/ChatForm/ChatFormInput/ChatFormInput.svelte'; -import { SETTINGS_KEYS } from '$lib/constants'; -import { settingsStore } from '$lib/stores/settings/index.svelte'; -import { tick } from 'svelte'; -import { describe, expect, it, vi } from 'vitest'; -import { userEvent } from 'vitest/browser'; -import { render } from 'vitest-browser-svelte'; - -const MENTION = '[notes.md](file:///tmp/notes.md)'; - -function editorIn(container: HTMLElement): EditorView { - const el = container.querySelector('.cm-content'); - const view = el && EditorView.findFromDOM(el); - - if (!view) throw new Error('editor not rendered'); - - return view; -} - -async function settle() { - await tick(); - await new Promise((resolve) => requestAnimationFrame(() => resolve(null))); -} - -describe('ChatFormInput', () => { - it('keeps the typed markdown byte-exact in the value', async () => { - const screen = render(ChatFormInput, { value: '' }); - const editor = editorIn(screen.container); - - await userEvent.click(editor.contentDOM); - await userEvent.keyboard('## Title{Shift>}{Enter}{Enter}{/Shift}- **bold** `code`'); - await settle(); - - expect(editor.state.doc.toString()).toBe('## Title\n\n- **bold** `code`'); - }); - - it('shows a mention link as a badge in the block being edited', async () => { - const screen = render(ChatFormInput, { value: `see ${MENTION} ok` }); - const editor = editorIn(screen.container); - - editor.focus(); - editor.dispatch({ selection: { anchor: 0 } }); - await settle(); - - const line = screen.container.querySelector('.cm-line'); - - expect(line?.textContent).toContain('notes.md'); - expect(line?.textContent).not.toContain('file://'); - expect(editor.state.doc.toString()).toBe(`see ${MENTION} ok`); - }); - - it('leaves a mention link in a code block as text', async () => { - const screen = render(ChatFormInput, { value: `~~~\n${MENTION}\n~~~` }); - const editor = editorIn(screen.container); - - editor.focus(); - editor.dispatch({ selection: { anchor: 0 } }); - await settle(); - - expect(screen.container.querySelector('.cm-content')?.textContent).toContain('file://'); - }); - - it('steps over a mention badge as one unit', async () => { - const screen = render(ChatFormInput, { value: `a ${MENTION}` }); - const editor = editorIn(screen.container); - - editor.focus(); - editor.dispatch({ selection: { anchor: editor.state.doc.length } }); - await settle(); - - await userEvent.keyboard('{Backspace}'); - await settle(); - - expect(editor.state.doc.toString()).toBe('a '); - }); - - it('renders every block like a chat message once blurred', async () => { - const screen = render(ChatFormInput, { value: '# Title\n\nSome **bold** text' }); - const editor = editorIn(screen.container); - - editor.contentDOM.blur(); - await vi.waitFor(() => { - expect(screen.container.querySelector('.cm-md-block h1')?.textContent).toBe('Title'); - expect(screen.container.querySelector('.cm-md-block strong')?.textContent).toBe('bold'); - }); - }); - - it('shows the plain markdown, with mention badges, while the live preview setting is off', async () => { - settingsStore.updateConfig(SETTINGS_KEYS.LIVE_MARKDOWN_PREVIEW, false); - - try { - const screen = render(ChatFormInput, { value: `# Title\n\nsee ${MENTION}` }); - const editor = editorIn(screen.container); - - editor.contentDOM.blur(); - await settle(); - - const lines = [...screen.container.querySelectorAll('.cm-line')].map((l) => l.textContent); - - expect(screen.container.querySelector('.cm-md-block')).toBeNull(); - expect(lines[0]).toBe('# Title'); - expect(lines.at(-1)).toContain('notes.md'); - expect(lines.at(-1)).not.toContain('file://'); - - settingsStore.updateConfig(SETTINGS_KEYS.LIVE_MARKDOWN_PREVIEW, true); - - await vi.waitFor(() => - expect(screen.container.querySelector('.cm-md-block h1')?.textContent).toBe('Title') - ); - } finally { - settingsStore.updateConfig(SETTINGS_KEYS.LIVE_MARKDOWN_PREVIEW, true); - } - }); - - it('lets the form handle a key first and keeps it from the editor', async () => { - const onKeydown = vi.fn((event: KeyboardEvent) => { - if (event.key === 'Enter') event.preventDefault(); - }); - const screen = render(ChatFormInput, { onKeydown, value: 'hello' }); - const editor = editorIn(screen.container); - - editor.focus(); - editor.dispatch({ selection: { anchor: 5 } }); - await userEvent.keyboard('{Enter}'); - await settle(); - - expect(onKeydown).toHaveBeenCalled(); - expect(editor.state.doc.toString()).toBe('hello'); - }); - - it('leaves a paste the form handles out of the editor', async () => { - const onPaste = vi.fn((event: ClipboardEvent) => event.preventDefault()); - const screen = render(ChatFormInput, { onPaste, value: '' }); - const editor = editorIn(screen.container); - const clipboardData = new DataTransfer(); - - clipboardData.setData('text/plain', 'pasted'); - editor.focus(); - editor.contentDOM.dispatchEvent( - new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData }) - ); - await settle(); - - expect(onPaste).toHaveBeenCalled(); - expect(editor.state.doc.toString()).toBe(''); - }); -}); diff --git a/tools/ui/tests/client/components/ChatFormActionRecordWrapper.svelte b/tools/ui/tests/client/components/ChatFormActionRecordWrapper.svelte deleted file mode 100644 index 394bbe52b76a..000000000000 --- a/tools/ui/tests/client/components/ChatFormActionRecordWrapper.svelte +++ /dev/null @@ -1,14 +0,0 @@ - - - - - diff --git a/tools/ui/tests/client/components/ChatMessagesPerfWrapper.svelte b/tools/ui/tests/client/components/ChatMessagesPerfWrapper.svelte deleted file mode 100644 index ab5cc38bc96c..000000000000 --- a/tools/ui/tests/client/components/ChatMessagesPerfWrapper.svelte +++ /dev/null @@ -1,12 +0,0 @@ - - - - - diff --git a/tools/ui/tests/client/components/ChatScreenFormTestWrapper.svelte b/tools/ui/tests/client/components/ChatScreenFormTestWrapper.svelte deleted file mode 100644 index 3e780e80e98a..000000000000 --- a/tools/ui/tests/client/components/ChatScreenFormTestWrapper.svelte +++ /dev/null @@ -1,8 +0,0 @@ - - - - - diff --git a/tools/ui/tests/client/components/DialogPanelWrapper.svelte b/tools/ui/tests/client/components/DialogPanelWrapper.svelte deleted file mode 100644 index a851e37c0a99..000000000000 --- a/tools/ui/tests/client/components/DialogPanelWrapper.svelte +++ /dev/null @@ -1,12 +0,0 @@ - - -{#if panel === 'settings'} - -{:else} - -{/if} diff --git a/tools/ui/tests/client/components/ModelsManagerRowWrapper.svelte b/tools/ui/tests/client/components/ModelsManagerRowWrapper.svelte deleted file mode 100644 index d120a0b07156..000000000000 --- a/tools/ui/tests/client/components/ModelsManagerRowWrapper.svelte +++ /dev/null @@ -1,24 +0,0 @@ - - - - - false} - onDelete={() => {}} - {onSelect} - {option} - {selected} - /> - diff --git a/tools/ui/tests/client/components/ModelsManagerWrapper.svelte b/tools/ui/tests/client/components/ModelsManagerWrapper.svelte deleted file mode 100644 index 926648cb1f18..000000000000 --- a/tools/ui/tests/client/components/ModelsManagerWrapper.svelte +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - diff --git a/tools/ui/tests/client/components/SidebarNavigationHarness.svelte b/tools/ui/tests/client/components/SidebarNavigationHarness.svelte deleted file mode 100644 index 08721f21b383..000000000000 --- a/tools/ui/tests/client/components/SidebarNavigationHarness.svelte +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - diff --git a/tools/ui/tests/client/microphone-unavailable.svelte.test.ts b/tools/ui/tests/client/microphone-unavailable.svelte.test.ts deleted file mode 100644 index 7cccfbe80857..000000000000 --- a/tools/ui/tests/client/microphone-unavailable.svelte.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -// Guards how the chat form tells why its microphone can't record: a page without HTTPS (a -// llama-server opened over plain HTTP on the network or over Tailscale) can't reach the -// microphone at all, the browser's own errors are named, and the button shows the reason -// while staying tappable, so a tap on a phone, which shows no tooltip, can explain it. - -import ChatFormActionRecordWrapper from './components/ChatFormActionRecordWrapper.svelte'; -import { MICROPHONE_UNAVAILABLE_MESSAGE } from '$lib/constants'; -import { describeMicrophoneError, microphoneUnavailableReason } from '$lib/utils/browser-only'; -import { afterEach, describe, expect, it, vi } from 'vitest'; -import { render } from 'vitest-browser-svelte'; - -afterEach(() => { - vi.unstubAllGlobals(); -}); - -describe('microphoneUnavailableReason', () => { - it('names HTTPS when the page is not a secure context', () => { - vi.stubGlobal('isSecureContext', false); - - expect(microphoneUnavailableReason()).toBe(MICROPHONE_UNAVAILABLE_MESSAGE.insecure); - }); - - it('names the browser when it has no recorder', () => { - vi.stubGlobal('isSecureContext', true); - vi.stubGlobal('MediaRecorder', undefined); - - expect(microphoneUnavailableReason()).toBe(MICROPHONE_UNAVAILABLE_MESSAGE.unsupported); - }); - - it('has nothing to say when the page can record', () => { - vi.stubGlobal('isSecureContext', true); - - expect(microphoneUnavailableReason()).toBeNull(); - }); -}); - -describe('describeMicrophoneError', () => { - it.each([ - ['NotAllowedError', MICROPHONE_UNAVAILABLE_MESSAGE.denied], - ['SecurityError', MICROPHONE_UNAVAILABLE_MESSAGE.denied], - ['NotFoundError', MICROPHONE_UNAVAILABLE_MESSAGE.notFound], - ['NotReadableError', MICROPHONE_UNAVAILABLE_MESSAGE.busy] - ])('names a %s', (name, message) => { - expect(describeMicrophoneError(new DOMException('', name))).toBe(message); - }); - - it("keeps an unknown error's own message", () => { - expect(describeMicrophoneError(new Error('boom'))).toBe( - `${MICROPHONE_UNAVAILABLE_MESSAGE.failed} boom` - ); - }); -}); - -// the tooltip's trigger wraps the button and takes its name, so the button is the inner one -describe('the record button', () => { - it('shows the reason and stays tappable when the microphone cannot record', async () => { - const onMicClick = vi.fn(); - const screen = render(ChatFormActionRecordWrapper, { - micWarning: MICROPHONE_UNAVAILABLE_MESSAGE.insecure, - onMicClick - }); - const button = screen.getByRole('button', { name: /^Recording unavailable: / }).last(); - - await expect.element(button).toBeEnabled(); - await button.click(); - - expect(onMicClick).toHaveBeenCalledOnce(); - }); - - it('starts recording when nothing is wrong', async () => { - const screen = render(ChatFormActionRecordWrapper, {}); - - await expect - .element(screen.getByRole('button', { name: 'Start recording' }).last()) - .toBeEnabled(); - }); - - it('stays disabled for a model without audio, whatever the microphone', async () => { - const screen = render(ChatFormActionRecordWrapper, { - hasAudioModality: false, - micWarning: MICROPHONE_UNAVAILABLE_MESSAGE.insecure - }); - - await expect - .element(screen.getByRole('button', { name: 'Start recording' }).last()) - .toBeDisabled(); - }); -}); diff --git a/tools/ui/tests/e2e/pwa.e2e.ts b/tools/ui/tests/e2e/pwa.e2e.ts deleted file mode 100644 index 09442f42927f..000000000000 --- a/tools/ui/tests/e2e/pwa.e2e.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { expect, test } from '@playwright/test'; - -test.describe('PWA Service Worker', () => { - test('service worker is registered', async ({ page }) => { - await page.goto('/'); - - const swURL = await page.evaluate(async () => { - const registration = await Promise.race([ - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - type inference differs from browser runtime - navigator.serviceWorker.ready, - new Promise((_, reject) => - setTimeout(() => reject(new Error('Service worker registration failed: timeout')), 15000) - ) - ]); - - // @ts-expect-error registration is of type unknown - return registration.active?.scriptURL; - }); - - expect(swURL).toBeTruthy(); - expect(swURL).toContain('/sw.js'); - }); - - test('service worker has precache configured', async ({ page }) => { - await page.goto('/'); - - await page.evaluate(async () => { - await navigator.serviceWorker.ready; - }); - - const swActive = await page.evaluate(async () => { - const reg = await navigator.serviceWorker.ready; - - return reg.active?.scriptURL ?? null; - }); - - expect(swActive).toBeTruthy(); - - const swResponse = await page.request.get(swActive!); - const swContent = await swResponse.text(); - - // Precache contains SvelteKit content-hashed bundle paths - expect(swContent).toMatch(/"_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"/); - expect(swContent).toMatch(/"_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css"/); - expect(swContent).toMatch(/"manifest\.webmanifest"/); - expect(swContent).toMatch(/"_app\/version\.json"/); - // NavigationRoute is intentionally absent — server API endpoints - // (e.g. /slots, /models) must not be intercepted by the PWA and - // should return JSON directly from the server. - expect(swContent).not.toMatch(/NavigationRoute/); - expect(swContent).toMatch(/api-cache/); - }); - - test('offline mode - page loads when offline after caching', async ({ browser }) => { - const context = await browser.newContext(); - const offlinePage = await context.newPage(); - - await offlinePage.goto('/'); - await offlinePage.waitForLoadState('networkidle'); - - await offlinePage.evaluate(async () => { - await navigator.serviceWorker.ready; - }); - - await offlinePage.waitForTimeout(2000); - - await context.setOffline(true); - await offlinePage.goto('/'); - - const bodyText = await offlinePage.locator('body').textContent(); - - expect(bodyText).toBeTruthy(); - - await context.close(); - }); - - test('version.json is accessible and contains version', async ({ page }) => { - const versionResponse = await page.request.get('/_app/version.json'); - - expect(versionResponse.ok()).toBeTruthy(); - - const versionData = await versionResponse.json(); - - expect(versionData).toHaveProperty('version'); - expect(typeof versionData.version).toBe('string'); - expect(versionData.version.length).toBeGreaterThan(0); - }); - - test('manifest.webmanifest is accessible and valid', async ({ page }) => { - const response = await page.request.get('/manifest.webmanifest'); - - expect(response.ok()).toBeTruthy(); - - const manifest = await response.json(); - - expect(manifest).toHaveProperty('name', 'llama-ui'); - expect(manifest).toHaveProperty('short_name', 'llama-ui'); - expect(manifest).toHaveProperty('start_url', './'); - expect(manifest).toHaveProperty('display', 'standalone'); - expect(manifest.icons).toBeTruthy(); - expect(manifest.icons.length).toBeGreaterThan(0); - }); - - test('index.html contains content-hashed bundle references', async ({ page }) => { - const response = await page.request.get('/'); - - expect(response.ok()).toBeTruthy(); - - const html = await response.text(); - - // SvelteKit outputs content-hashed bundle names in _app/immutable/ - expect(html).toMatch(/href="(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"/); - expect(html).toMatch(/href="(\.\/|\/)_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css"/); - expect(html).toMatch(/import\("(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"\)/); - }); -}); diff --git a/tools/ui/tests/stories/ChatFormSingleRow.stories.svelte b/tools/ui/tests/stories/ChatFormSingleRow.stories.svelte deleted file mode 100644 index d2879c6fc2be..000000000000 --- a/tools/ui/tests/stories/ChatFormSingleRow.stories.svelte +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - -
- {#each RADII as [radius, label] (radius)} -
- {label} - - -
- {/each} -
-
diff --git a/tools/ui/tests/stories/ChatMessage.stories.svelte b/tools/ui/tests/stories/ChatMessage.stories.svelte deleted file mode 100644 index bec9cbcd3e18..000000000000 --- a/tools/ui/tests/stories/ChatMessage.stories.svelte +++ /dev/null @@ -1,416 +0,0 @@ - - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', true); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - const { conversationsStore } = await import('$lib/stores/conversations/index.svelte'); - - settingsStore.updateConfig('showMessageStats', true); - settingsStore.updateConfig('showRawOutputSwitch', false); - // The toggle reads the before size from the branch, so the story needs - // the summarized turn in the active message list. - conversationsStore.activeMessages = [preCompactionAssistant, compactionMessage]; - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - const { chatActivityStore } = await import('$lib/stores/chat/activity.svelte'); - const { chatStore } = await import('$lib/stores/chat/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - - // The summary request reports its prompt progress through the shared - // processing state; seed one so the story shows the prefill detail. - chatActivityStore.markCompacting('conv-1', compactionPendingMessage.id); - chatStore.processing.setActiveConversation('conv-1'); - chatStore.processing.setState('conv-1', { - contextTotal: 32768, - contextUsed: 10000, - hasNextToken: false, - outputTokensMax: -1, - outputTokensUsed: 0, - progressPercent: 42, - promptProgress: { cache: 0, processed: 4200, time_ms: 6000, total: 10000 }, - promptTokens: 0, - speculative: false, - status: 'preparing', - temperature: 0.8, - tokensDecoded: 0, - tokensPerSecond: 0, - tokensRemaining: -1, - topP: 0.95 - }); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - const { chatActivityStore } = await import('$lib/stores/chat/activity.svelte'); - const { chatStore } = await import('$lib/stores/chat/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - - // Prompt processing is over, so only the generated tokens are reported. - chatActivityStore.markCompacting('conv-1', compactionGeneratingMessage.id); - chatStore.processing.setActiveConversation('conv-1'); - chatStore.processing.setState('conv-1', { - contextTotal: 32768, - contextUsed: 45200, - hasNextToken: true, - outputTokensMax: -1, - outputTokensUsed: 128, - promptTokens: 42200, - speculative: false, - status: 'generating', - temperature: 0.8, - tokensDecoded: 128, - tokensPerSecond: 25, - tokensRemaining: -1, - topP: 0.95 - }); - }} -/> - - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - // Phase 1: Stream reasoning content in chunks - let reasoningText = - 'I need to think about this carefully. Let me break down the problem:\n\n1. The user is asking for help with something complex\n2. I should provide a thorough and helpful response\n3. I need to consider multiple approaches\n4. The best solution would be to explain step by step\n\nThis approach will ensure clarity and understanding.'; - let reasoningChunk = 'I'; - let i = 0; - - while (i < reasoningText.length) { - const chunkSize = Math.floor(Math.random() * 5) + 3; // Random 3-7 characters - const chunk = reasoningText.slice(i, i + chunkSize); - - reasoningChunk += chunk; - - // Update the reactive state directly - streamingMessage.thinking = reasoningChunk; - - i += chunkSize; - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - const regularText = - "Based on my analysis, here's the solution:\n\n**Step 1:** First, we need to understand the requirements clearly.\n\n**Step 2:** Then we can implement the solution systematically.\n\n**Step 3:** Finally, we test and validate the results.\n\nThis approach ensures we cover all aspects of the problem effectively."; - - let contentChunk = ''; - - i = 0; - - while (i < regularText.length) { - const chunkSize = Math.floor(Math.random() * 5) + 3; // Random 3-7 characters - const chunk = regularText.slice(i, i + chunkSize); - - contentChunk += chunk; - - // Update the reactive state directly - streamingMessage.content = contentChunk; - - i += chunkSize; - await new Promise((resolve) => setTimeout(resolve, 50)); - } - - streamingMessage.timestamp = Date.now(); - }} -> -
- -
-
- - { - const { settingsStore } = await import('$lib/stores/settings/index.svelte'); - - settingsStore.updateConfig('showRawOutputSwitch', false); - // Import the chat store to simulate loading state - const { chatStore } = await import('$lib/stores/chat/index.svelte'); - - // Set loading state to true to trigger the processing UI - chatStore.isLoading = true; - - // Simulate the processing state hook behavior - // This will show the "Generating..." text and parameter details - await new Promise((resolve) => setTimeout(resolve, 100)); - }} -/> diff --git a/tools/ui/tests/stories/ChatScreenForm.stories.svelte b/tools/ui/tests/stories/ChatScreenForm.stories.svelte deleted file mode 100644 index ab23974b6b9c..000000000000 --- a/tools/ui/tests/stories/ChatScreenForm.stories.svelte +++ /dev/null @@ -1,95 +0,0 @@ - - - { - const editor = await canvas.findByRole('textbox'); - const submitButton = await canvas.findByRole('button', { name: 'Send' }); - - // Expect the input to be focused after the component is mounted - await expect(editor).toHaveFocus(); - - // Expect the submit button to be disabled - await expect(submitButton).toBeDisabled(); - - const text = 'What is the meaning of life?'; - - await userEvent.clear(editor); - await userEvent.type(editor, text); - - await expect(editor).toHaveTextContent(text); - - const fileInput = document.querySelector('input[type="file"]'); - - await expect(fileInput).not.toHaveAttribute('accept'); - }} -/> - - - - { - const jpgAttachment = canvas.getByAltText('1.jpg'); - const svgAttachment = canvas.getByAltText('hf-logo.svg'); - const pdfFileExtension = canvas.getByText('PDF'); - const pdfAttachment = canvas.getByText('example.pdf'); - const pdfSize = canvas.getByText('342.82 KB'); - - await expect(jpgAttachment).toBeInTheDocument(); - await expect(jpgAttachment).toHaveAttribute('src', jpgAsset); - - await expect(svgAttachment).toBeInTheDocument(); - await expect(svgAttachment).toHaveAttribute('src', svgAsset); - - await expect(pdfFileExtension).toBeInTheDocument(); - await expect(pdfAttachment).toBeInTheDocument(); - await expect(pdfSize).toBeInTheDocument(); - }} -/> diff --git a/tools/ui/tests/stories/Introduction.mdx b/tools/ui/tests/stories/Introduction.mdx deleted file mode 100644 index d4c0c792164c..000000000000 --- a/tools/ui/tests/stories/Introduction.mdx +++ /dev/null @@ -1,44 +0,0 @@ -import { Meta } from '@storybook/addon-docs/blocks'; - - - -# llama.cpp Web UI - -Welcome to the **llama-ui** component library! This Storybook showcases the components used in the modern web interface for the llama-server. - -## 🚀 About This Project - -Llama UI is a modern web interface for the llama-server, built with SvelteKit and ShadCN UI. Features include: - -- **Real-time chat conversations** with AI assistants -- **Multi-conversation management** with persistent storage -- **Advanced parameter tuning** for model behavior -- **File upload support** for multimodal interactions -- **Responsive design** that works on desktop and mobile - -## 🎨 Design System - -The UI is built using: - -- **SvelteKit** - Modern web framework with excellent performance -- **Tailwind CSS** - Utility-first CSS framework for rapid styling -- **ShadCN/UI** - High-quality, accessible component library -- **Lucide Icons** - Beautiful, consistent icon set - -## 🔧 Development - -This Storybook serves as both documentation and a development environment for the UI components. Each story demonstrates: - -- **Component variations** - Different states and configurations -- **Interactive examples** - Live components you can interact with -- **Usage patterns** - How components work together -- **Styling consistency** - Unified design language - -## 🚀 Getting Started - -To explore the components: - -1. **Browse the sidebar** to see all available components -2. **Click on stories** to see different component states -3. **Use the controls panel** to interact with component props -4. **Check the docs tab** for detailed component information diff --git a/tools/ui/tests/stories/MarkdownContent.stories.svelte b/tools/ui/tests/stories/MarkdownContent.stories.svelte deleted file mode 100644 index b3203e335969..000000000000 --- a/tools/ui/tests/stories/MarkdownContent.stories.svelte +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - - - - - - - - - - - - { - const { canvasElement } = context; - - // Wait for component to render - await new Promise((resolve) => setTimeout(resolve, 100)); - - // Find all links in the rendered content - const links = (canvasElement as HTMLElement).querySelectorAll( - 'a[href]' - ) as NodeListOf; - const linkList = Array.from(links) as HTMLAnchorElement[]; - - // Test that we have the expected number of links - expect(links.length).toBeGreaterThan(0); - - // Test each link for proper attributes - links.forEach((link: HTMLAnchorElement) => { - const href = link.getAttribute('href'); - - // Test that external links have proper security attributes - if (href && (href.startsWith('http://') || href.startsWith('https://'))) { - expect(link.getAttribute('target')).toBe('_blank'); - expect(link.getAttribute('rel')).toBe('noopener noreferrer'); - } - }); - - // Test specific links exist - const hugginFaceLink = linkList.find( - (link) => link.getAttribute('href') === 'https://huggingface.co' - ); - - expect(hugginFaceLink).toBeTruthy(); - expect(hugginFaceLink?.textContent).toBe('Hugging Face Homepage'); - - const githubLink = linkList.find( - (link) => link.getAttribute('href') === 'https://github.com/ggml-org/llama.cpp' - ); - - expect(githubLink).toBeTruthy(); - expect(githubLink?.textContent).toBe('GitHub Repository'); - - const openaiLink = linkList.find((link) => link.getAttribute('href') === 'https://openai.com'); - - expect(openaiLink).toBeTruthy(); - expect(openaiLink?.textContent).toBe('OpenAI Website'); - - const googleLink = linkList.find( - (link) => link.getAttribute('href') === 'https://www.google.com' - ); - - expect(googleLink).toBeTruthy(); - expect(googleLink?.textContent).toBe('Google Search'); - - // Test inline links (auto-linked URLs) - const exampleLink = linkList.find( - (link) => link.getAttribute('href') === 'https://example.com' - ); - - expect(exampleLink).toBeTruthy(); - - const pythonDocsLink = linkList.find( - (link) => link.getAttribute('href') === 'https://docs.python.org' - ); - - expect(pythonDocsLink).toBeTruthy(); - - console.log(`✅ URL Links test passed - Found ${links.length} links with proper attributes`); - }} -/> diff --git a/tools/ui/tests/stories/ModelsManager.stories.svelte b/tools/ui/tests/stories/ModelsManager.stories.svelte deleted file mode 100644 index 77e53f8e3b1f..000000000000 --- a/tools/ui/tests/stories/ModelsManager.stories.svelte +++ /dev/null @@ -1,110 +0,0 @@ - - - - - -
- (selectedId = picked.id)} - {selectedId} - /> -
-
- - -
- (selectedId = picked.id)} - {selectedId} - /> -
-
- - -
- (selectedId = picked.id)} - {selectedId} - /> -
-
diff --git a/tools/ui/tests/stories/ModelsSelector.stories.svelte b/tools/ui/tests/stories/ModelsSelector.stories.svelte deleted file mode 100644 index 5c59b21a2052..000000000000 --- a/tools/ui/tests/stories/ModelsSelector.stories.svelte +++ /dev/null @@ -1,268 +0,0 @@ - - - - - -
- -
-
- - -
- -
-
- - -
- -
-
- - -
-
- Server model states -
- - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-idle', 'Model (idle)', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-loading', 'Model (loading)', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-loaded', 'Model (loaded)', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-sleeping', 'Model (sleeping)', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('model-failed', 'Model (failed)', 'meta')} - /> -
-
- - -
-
- Selection states -
- - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('normal-model', 'Normal Model', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('selected-model', 'Selected Model', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('highlighted-model', 'Highlighted Model', 'meta')} - /> - - {}} - onMouseEnter={() => {}} - onSelect={() => {}} - option={mockModel('fav-model', 'Favorite Model', 'Qwen')} - /> -
-
diff --git a/tools/ui/tests/stories/PwaRefreshAlert.stories.svelte b/tools/ui/tests/stories/PwaRefreshAlert.stories.svelte deleted file mode 100644 index 2a0a0b4bbf6a..000000000000 --- a/tools/ui/tests/stories/PwaRefreshAlert.stories.svelte +++ /dev/null @@ -1,64 +0,0 @@ - - - console.log('reload') }} - name="Default" - play={async ({ canvas }) => { - const title = canvas.getByText('Update available'); - - await expect(title).toBeInTheDocument(); - - const description = canvas.getByText(/A new version is available/); - - await expect(description).toBeInTheDocument(); - - const button = canvas.getByRole('button', { name: 'Reload' }); - - await expect(button).toBeInTheDocument(); - }} -/> - - console.log('reload') }} - name="Hidden" - play={async ({ canvas }) => { - const title = canvas.queryByText('Update available'); - - await expect(title).not.toBeInTheDocument(); - }} -/> - - console.log('reload') - }} - name="ClickReload" - play={async ({ canvas, userEvent }) => { - const button = canvas.getByRole('button', { name: 'Reload' }); - - await expect(button).toBeInTheDocument(); - - await userEvent.click(button); - - const title = canvas.queryByText('Update available'); - - await expect(title).not.toBeInTheDocument(); - - const reloadBtn = canvas.queryByRole('button', { name: 'Reload' }); - - await expect(reloadBtn).not.toBeInTheDocument(); - }} -/> diff --git a/tools/ui/tests/stories/SidebarNavigation.stories.svelte b/tools/ui/tests/stories/SidebarNavigation.stories.svelte deleted file mode 100644 index 1a638e6942f6..000000000000 --- a/tools/ui/tests/stories/SidebarNavigation.stories.svelte +++ /dev/null @@ -1,112 +0,0 @@ - - - - - { - const { conversationsStore } = await import('$lib/stores/conversations/index.svelte'); - - waitFor(() => - setTimeout(() => { - conversationsStore.conversations = mockConversations; - }, 0) - ); - }} -> -
- -
-
- - { - const { conversationsStore } = await import('$lib/stores/conversations/index.svelte'); - - waitFor(() => - setTimeout(() => { - conversationsStore.conversations = mockConversations; - }, 0) - ); - - // Expand sidebar first, then click Search in the expanded button list - const logoTrigger = screen.getByRole('button', { name: /expand navigation/i }); - - await userEvent.click(logoTrigger); - const searchTrigger = screen.getByText('Search'); - - await userEvent.click(searchTrigger); - - await expect(await screen.findByRole('combobox')).toHaveFocus(); - }} -> -
- -
-
- - { - // Mock empty conversations store - const { conversationsStore } = await import('$lib/stores/conversations/index.svelte'); - - conversationsStore.conversations = []; - }} -> -
- -
-
diff --git a/tools/ui/tests/stories/chat/screen/attachments/ChatAttachmentsPreview.stories.svelte b/tools/ui/tests/stories/chat/screen/attachments/ChatAttachmentsPreview.stories.svelte deleted file mode 100644 index f7f828f33f5c..000000000000 --- a/tools/ui/tests/stories/chat/screen/attachments/ChatAttachmentsPreview.stories.svelte +++ /dev/null @@ -1,47 +0,0 @@ - - - - { - await waitFor(() => expect(canvas.getByText('Failed to load PDF images')).toBeInTheDocument(), { - timeout: 5000 - }); - - // a retry loop would flip back to the loading state - await new Promise((resolve) => setTimeout(resolve, 500)); - await expect(canvas.queryByText('Converting PDF to images...')).not.toBeInTheDocument(); - await expect(canvas.getByText('Failed to load PDF images')).toBeInTheDocument(); - }} -> -
- -
-
diff --git a/tools/ui/tests/stories/fixtures/ChatFormSingleRowPreview.svelte b/tools/ui/tests/stories/fixtures/ChatFormSingleRowPreview.svelte deleted file mode 100644 index 6cfc54726fa4..000000000000 --- a/tools/ui/tests/stories/fixtures/ChatFormSingleRowPreview.svelte +++ /dev/null @@ -1,57 +0,0 @@ - - - - -
- -
diff --git a/tools/ui/tests/stories/fixtures/api-docs.ts b/tools/ui/tests/stories/fixtures/api-docs.ts deleted file mode 100644 index 7b499956f8bc..000000000000 --- a/tools/ui/tests/stories/fixtures/api-docs.ts +++ /dev/null @@ -1,160 +0,0 @@ -// API Documentation -export const API_DOCS_MD = String.raw` -# REST API Documentation - -## 🔐 Authentication - -All API requests require authentication using **Bearer tokens**. Include your API key in the Authorization header: - -${'```'}http -GET /api/v1/users -Host: api.example.com -Authorization: Bearer YOUR_API_KEY -Content-Type: application/json -${'```'} - -## 📍 Endpoints - -### Users API - -#### **GET** /api/v1/users - -Retrieve a paginated list of users. - -**Query Parameters:** - -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| page | integer | 1 | Page number | -| limit | integer | 20 | Items per page | -| sort | string | "created_at" | Sort field | -| order | string | "desc" | Sort order | - -**Response:** 200 OK - -${'```'}json -{ - "data": [ - { - "id": "usr_1234567890", - "email": "user@example.com", - "name": "John Doe", - "role": "admin", - "created_at": "2024-01-15T10:30:00Z" - } - ], - "pagination": { - "page": 1, - "limit": 20, - "total": 156, - "pages": 8 - } -} -${'```'} - -#### **POST** /api/v1/users - -Create a new user account. - -**Request Body:** - -${'```'}json -{ - "email": "newuser@example.com", - "password": "SecurePassword123!", - "name": "Jane Smith", - "role": "user" -} -${'```'} - -**Response:** 201 Created - -${'```'}json -{ - "id": "usr_9876543210", - "email": "newuser@example.com", - "name": "Jane Smith", - "role": "user", - "created_at": "2024-01-21T09:15:00Z" -} -${'```'} - -### Error Responses - -The API returns errors in a consistent format: - -${'```'}json -{ - "error": { - "code": "VALIDATION_ERROR", - "message": "Invalid request parameters", - "details": [ - { - "field": "email", - "message": "Email format is invalid" - } - ] - } -} -${'```'} - -### Rate Limiting - -| Tier | Requests/Hour | Burst | -|------|--------------|-------| -| **Free** | 1,000 | 100 | -| **Pro** | 10,000 | 500 | -| **Enterprise** | Unlimited | - | - -**Headers:** -- X-RateLimit-Limit -- X-RateLimit-Remaining -- X-RateLimit-Reset - -### Webhooks - -Configure webhooks to receive real-time events: - -${'```'}javascript -// Webhook payload -{ - "event": "user.created", - "timestamp": "2024-01-21T09:15:00Z", - "data": { - "id": "usr_9876543210", - "email": "newuser@example.com" - }, - "signature": "sha256=abcd1234..." -} -${'```'} - -### SDK Examples - -**JavaScript/TypeScript:** - -${'```'}typescript -import { ApiClient } from '@example/api-sdk'; - -const client = new ApiClient({ - apiKey: process.env.API_KEY -}); - -const users = await client.users.list({ - page: 1, - limit: 20 -}); -${'```'} - -**Python:** - -${'```'}python -from example_api import Client - -client = Client(api_key=os.environ['API_KEY']) -users = client.users.list(page=1, limit=20) -${'```'} - ---- - -📚 [Full API Reference](https://api.example.com/docs) | 💬 [Support](https://support.example.com) -`; diff --git a/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp b/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp deleted file mode 100644 index 6efcffc3b82b..000000000000 Binary files a/tools/ui/tests/stories/fixtures/assets/beautiful-flowers-lotus.webp and /dev/null differ diff --git a/tools/ui/tests/stories/fixtures/blog-post.ts b/tools/ui/tests/stories/fixtures/blog-post.ts deleted file mode 100644 index 3eb2ed7585f8..000000000000 --- a/tools/ui/tests/stories/fixtures/blog-post.ts +++ /dev/null @@ -1,125 +0,0 @@ -// Blog Post Content -export const BLOG_POST_MD = String.raw` -# Understanding Rust's Ownership System - -*Published on March 15, 2024 • 8 min read* - -Rust's ownership system is one of its most distinctive features, enabling memory safety without garbage collection. In this post, we'll explore how ownership works and why it's revolutionary for systems programming. - -## What is Ownership? - -Ownership is a set of rules that governs how Rust manages memory. These rules are checked at compile time, ensuring memory safety without runtime overhead. - -### The Three Rules of Ownership - -1. **Each value has a single owner** -2. **There can only be one owner at a time** -3. **When the owner goes out of scope, the value is dropped** - -## Memory Management Without GC - -Traditional approaches to memory management: - -- **Manual management** (C/C++): Error-prone, leads to bugs -- **Garbage collection** (Java, Python): Runtime overhead -- **Ownership** (Rust): Compile-time safety, zero runtime cost - -## Basic Examples - -### Variable Scope - -${'```'}rust -fn main() { - let s = String::from("hello"); // s comes into scope - - // s is valid here - println!("{}", s); - -} // s goes out of scope and is dropped -${'```'} - -### Move Semantics - -${'```'}rust -fn main() { - let s1 = String::from("hello"); - let s2 = s1; // s1 is moved to s2 - - // println!("{}", s1); // ❌ ERROR: s1 is no longer valid - println!("{}", s2); // ✅ OK: s2 owns the string -} -${'```'} - -## Borrowing and References - -Instead of transferring ownership, you can **borrow** values: - -### Immutable References - -${'```'}rust -fn calculate_length(s: &String) -> usize { - s.len() // s is a reference, doesn't own the String -} - -fn main() { - let s1 = String::from("hello"); - let len = calculate_length(&s1); // Borrow s1 - println!("Length of '{}' is {}", s1, len); // s1 still valid -} -${'```'} - -### Mutable References - -${'```'}rust -fn main() { - let mut s = String::from("hello"); - - let r1 = &mut s; - r1.push_str(", world"); - println!("{}", r1); - - // let r2 = &mut s; // ❌ ERROR: cannot borrow twice -} -${'```'} - -## Common Pitfalls - -### Dangling References - -${'```'}rust -fn dangle() -> &String { // ❌ ERROR: missing lifetime specifier - let s = String::from("hello"); - &s // s will be dropped, leaving a dangling reference -} -${'```'} - -### ✅ Solution - -${'```'}rust -fn no_dangle() -> String { - let s = String::from("hello"); - s // Ownership is moved out -} -${'```'} - -## Benefits - -- ✅ **No null pointer dereferences** -- ✅ **No data races** -- ✅ **No use-after-free** -- ✅ **No memory leaks** - -## Conclusion - -Rust's ownership system eliminates entire classes of bugs at compile time. While it has a learning curve, the benefits in safety and performance are worth it. - -## Further Reading - -- [The Rust Book - Ownership](https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html) -- [Rust by Example - Ownership](https://doc.rust-lang.org/rust-by-example/scope/move.html) -- [Rustlings Exercises](https://github.com/rust-lang/rustlings) - ---- - -*Questions? Reach out on [Twitter](https://twitter.com/rustlang) or join the [Rust Discord](https://discord.gg/rust-lang)* -`; diff --git a/tools/ui/tests/stories/fixtures/data-analysis.ts b/tools/ui/tests/stories/fixtures/data-analysis.ts deleted file mode 100644 index 6fec32dad637..000000000000 --- a/tools/ui/tests/stories/fixtures/data-analysis.ts +++ /dev/null @@ -1,124 +0,0 @@ -// Data Analysis Report -export const DATA_ANALYSIS_MD = String.raw` -# Q4 2024 Business Analytics Report - -*Executive Summary • Generated on January 15, 2025* - -## 📊 Key Performance Indicators - -${'```'} -Daily Active Users (DAU): 1.2M (+65% YoY) -Monthly Active Users (MAU): 4.5M (+48% YoY) -User Retention (Day 30): 68% (+12pp YoY) -Average Session Duration: 24min (+35% YoY) -${'```'} - -## 🎯 Product Performance - -### Feature Adoption Rates - -1. **AI Assistant**: 78% of users (↑ from 45%) -2. **Collaboration Tools**: 62% of users (↑ from 38%) -3. **Analytics Dashboard**: 54% of users (↑ from 31%) -4. **Mobile App**: 41% of users (↑ from 22%) - -### Customer Satisfaction - -| Metric | Q4 2024 | Q3 2024 | Change | -|--------|---------|---------|--------| -| **NPS Score** | 72 | 68 | +4 | -| **CSAT** | 4.6/5 | 4.4/5 | +0.2 | -| **Support Tickets** | 2,340 | 2,890 | -19% | -| **Resolution Time** | 4.2h | 5.1h | -18% | - -## 💰 Revenue Metrics - -### Monthly Recurring Revenue (MRR) - -- **Current MRR**: $2.8M (+42% YoY) -- **New MRR**: $340K -- **Expansion MRR**: $180K -- **Churned MRR**: $95K -- **Net New MRR**: $425K - -### Customer Acquisition - -${'```'} -Cost per Acquisition (CAC): $127 (-23% YoY) -Customer Lifetime Value: $1,840 (+31% YoY) -LTV:CAC Ratio: 14.5:1 -Payback Period: 3.2 months -${'```'} - -## 🌍 Geographic Performance - -### Revenue by Region - -1. **North America**: 45% ($1.26M) -2. **Europe**: 32% ($896K) -3. **Asia-Pacific**: 18% ($504K) -4. **Other**: 5% ($140K) - -### Growth Opportunities - -- **APAC**: 89% YoY growth potential -- **Latin America**: Emerging market entry -- **Middle East**: Enterprise expansion - -## 📱 Channel Performance - -### Traffic Sources - -| Channel | Sessions | Conversion | Revenue | -|---------|----------|------------|---------| -| **Organic Search** | 45% | 3.2% | $1.1M | -| **Direct** | 28% | 4.1% | $850K | -| **Social Media** | 15% | 2.8% | $420K | -| **Paid Ads** | 12% | 5.5% | $430K | - -### Marketing ROI - -- **Content Marketing**: 340% ROI -- **Email Campaigns**: 280% ROI -- **Social Media**: 190% ROI -- **Paid Search**: 220% ROI - -## 🔍 User Behavior Analysis - -### Session Patterns - -- **Peak Hours**: 9-11 AM, 2-4 PM EST -- **Mobile Usage**: 67% of sessions -- **Average Pages/Session**: 4.8 -- **Bounce Rate**: 23% (↓ from 31%) - -### Feature Usage Heatmap - -Most used features in order: -1. Dashboard (89% of users) -2. Search (76% of users) -3. Reports (64% of users) -4. Settings (45% of users) -5. Integrations (32% of users) - -## 💡 Recommendations - -1. **Invest** in AI capabilities (+$2M budget) -2. **Expand** sales team in APAC region -3. **Improve** onboarding to reduce churn -4. **Launch** enterprise security features - -## Appendix - -### Methodology - -Data collected from: -- Internal analytics (Amplitude) -- Customer surveys (n=2,450) -- Financial systems (NetSuite) -- Market research (Gartner) - ---- - -*Report prepared by Data Analytics Team • [View Interactive Dashboard](https://analytics.example.com)* -`; diff --git a/tools/ui/tests/stories/fixtures/empty.ts b/tools/ui/tests/stories/fixtures/empty.ts deleted file mode 100644 index 05286e7a783c..000000000000 --- a/tools/ui/tests/stories/fixtures/empty.ts +++ /dev/null @@ -1,2 +0,0 @@ -// Empty state -export const EMPTY_MD = ''; diff --git a/tools/ui/tests/stories/fixtures/math-formulas.ts b/tools/ui/tests/stories/fixtures/math-formulas.ts deleted file mode 100644 index 1355256b20ce..000000000000 --- a/tools/ui/tests/stories/fixtures/math-formulas.ts +++ /dev/null @@ -1,221 +0,0 @@ -/* eslint-disable no-irregular-whitespace */ -// Math Formulas Content -export const MATH_FORMULAS_MD = String.raw` -# Mathematical Formulas and Expressions - -This document demonstrates various mathematical notation and formulas that can be rendered using LaTeX syntax in markdown. - -## Basic Arithmetic - -### Addition and Summation -$$\sum_{i=1}^{n} i = \frac{n(n+1)}{2}$$ - -## Algebra - -### Quadratic Formula -The solutions to $ax^2 + bx + c = 0$ are: -$$x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$ - -### Binomial Theorem -$$(x + y)^n = \sum_{k=0}^{n} \binom{n}{k} x^{n-k} y^k$$ - -## Calculus - -### Derivatives -The derivative of $f(x) = x^n$ is: -$$f'(x) = nx^{n-1}$$ - -### Integration -$$\int_a^b f(x) \, dx = F(b) - F(a)$$ - -### Fundamental Theorem of Calculus -$$\frac{d}{dx} \int_a^x f(t) \, dt = f(x)$$ - -## Linear Algebra - -### Matrix Multiplication -If $A$ is an $m \times n$ matrix and $B$ is an $n \times p$ matrix, then: -$$C_{ij} = \sum_{k=1}^{n} A_{ik} B_{kj}$$ - -### Eigenvalues and Eigenvectors -For a square matrix $A$, if $Av = \lambda v$ for some non-zero vector $v$, then: -- $\lambda$ is an eigenvalue -- $v$ is an eigenvector - -## Statistics and Probability - -### Normal Distribution -The probability density function is: -$$f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2}$$ - -### Bayes' Theorem -$$P(A|B) = \frac{P(B|A) \cdot P(A)}{P(B)}$$ - -### Central Limit Theorem -For large $n$, the sample mean $\bar{X}$ is approximately: -$$\bar{X} \sim N\left(\mu, \frac{\sigma^2}{n}\right)$$ - -## Trigonometry - -### Pythagorean Identity -$$\sin^2\theta + \cos^2\theta = 1$$ - -### Euler's Formula -$$e^{i\theta} = \cos\theta + i\sin\theta$$ - -### Taylor Series for Sine -$$\sin x = \sum_{n=0}^{\infty} \frac{(-1)^n}{(2n+1)!} x^{2n+1} = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \cdots$$ - -## Complex Analysis - -### Complex Numbers -A complex number can be written as: -$$z = a + bi = r e^{i\theta}$$ - -where $r = |z| = \sqrt{a^2 + b^2}$ and $\theta = \arg(z)$ - -### Cauchy-Riemann Equations -For a function $f(z) = u(x,y) + iv(x,y)$ to be analytic: -$$\frac{\partial u}{\partial x} = \frac{\partial v}{\partial y}, \quad \frac{\partial u}{\partial y} = -\frac{\partial v}{\partial x}$$ - -## Differential Equations - -### First-order Linear ODE -$$\frac{dy}{dx} + P(x)y = Q(x)$$ - -Solution: $y = e^{-\int P(x)dx}\left[\int Q(x)e^{\int P(x)dx}dx + C\right]$ - -### Heat Equation -$$\frac{\partial u}{\partial t} = \alpha \frac{\partial^2 u}{\partial x^2}$$ - -## Number Theory - -### Prime Number Theorem -$$\pi(x) \sim \frac{x}{\ln x}$$ - -where $\pi(x)$ is the number of primes less than or equal to $x$. - -### Fermat's Last Theorem -For $n > 2$, there are no positive integers $a$, $b$, and $c$ such that: -$$a^n + b^n = c^n$$ - -## Set Theory - -### De Morgan's Laws -$$\overline{A \cup B} = \overline{A} \cap \overline{B}$$ -$$\overline{A \cap B} = \overline{A} \cup \overline{B}$$ - -## Advanced Topics - -### Riemann Zeta Function -$$\zeta(s) = \sum_{n=1}^{\infty} \frac{1}{n^s} = \prod_{p \text{ prime}} \frac{1}{1-p^{-s}}$$ - -### Maxwell's Equations -$$\nabla \cdot \mathbf{E} = \frac{\rho}{\epsilon_0}$$ -$$\nabla \cdot \mathbf{B} = 0$$ -$$\nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t}$$ -$$\nabla \times \mathbf{B} = \mu_0\mathbf{J} + \mu_0\epsilon_0\frac{\partial \mathbf{E}}{\partial t}$$ - -### Schrödinger Equation -$$i\hbar\frac{\partial}{\partial t}\Psi(\mathbf{r},t) = \hat{H}\Psi(\mathbf{r},t)$$ - -## Inline Math Examples - -Here are some inline mathematical expressions: - -- The golden ratio: $\phi = \frac{1 + \sqrt{5}}{2} \approx 1.618$ -- Euler's number: $e = \lim_{n \to \infty} \left(1 + \frac{1}{n}\right)^n$ -- Pi: $\pi = 4 \sum_{n=0}^{\infty} \frac{(-1)^n}{2n+1}$ -- Square root of 2: $\sqrt{2} = 1.41421356...$ - -## Fractions and Radicals - -Complex fraction: $\frac{\frac{a}{b} + \frac{c}{d}}{\frac{e}{f} - \frac{g}{h}}$ - -Nested radicals: $\sqrt{2 + \sqrt{3 + \sqrt{4 + \sqrt{5}}}}$ - -## Summations and Products - -### Geometric Series -$$\sum_{n=0}^{\infty} ar^n = \frac{a}{1-r} \quad \text{for } |r| < 1$$ - -### Product Notation -$$n! = \prod_{k=1}^{n} k$$ - -### Double Summation -$$\sum_{i=1}^{m} \sum_{j=1}^{n} a_{ij}$$ - -## Limits - -$$\lim_{x \to 0} \frac{\sin x}{x} = 1$$ - -$$\lim_{n \to \infty} \left(1 + \frac{x}{n}\right)^n = e^x$$ - -## Further Bracket Styles and Amounts - -- \( \mathrm{GL}_2(\mathbb{F}_7) \): Group of invertible matrices with entries in \(\mathbb{F}_7\). -- Some kernel of \(\mathrm{SL}_2(\mathbb{F}_7)\): - \[ - \left\{ \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}, \begin{pmatrix} -1 & 0 \\ 0 & -1 \end{pmatrix} \right\} = \{\pm I\} - \] -- Algebra: -\[ -x = \frac{-b \pm \sqrt{\,b^{2}-4ac\,}}{2a} -\] -- $100 and $12.99 are amounts, not LaTeX. -- I have $10, $3.99 and $x + y$ and $100x$. The amount is $2,000. -- Emma buys 2 cupcakes for $3 each and 1 cookie for $1.50. How much money does she spend in total? -- Maria has $20. She buys a notebook for $4.75 and a pack of pencils for $3.25. How much change does she receive? -- 1 kg の質量は - \[ - E = (1\ \text{kg}) \times (3.0 \times 10^8\ \text{m/s})^2 \approx 9.0 \times 10^{16}\ \text{J} - \] - というエネルギーに相当します。これは約 21 百万トンの TNT が爆発したときのエネルギーに匹敵します。 -- Algebra: \[ -x = \frac{-b \pm \sqrt{\,b^{2}-4ac\,}}{2a} -\] -- Algebraic topology, Homotopy Groups of $\mathbb{S}^3$: -$$\pi_n(\mathbb{S}^3) = \begin{cases} -\mathbb{Z} & n = 3 \\ -0 & n > 3, n \neq 4 \\ -\mathbb{Z}_2 & n = 4 \\ -\end{cases}$$ -- Spacer preceded by backslash: -\[ -\boxed{ -\begin{aligned} -N_{\text{att}}^{\text{(MHA)}} &= -h \bigl[\, d_{\text{model}}\;d_{k} + d_{\text{model}}\;d_{v}\, \bigr] && (\text{Q,K,V の重み})\\ -&\quad+ h(d_{k}+d_{k}+d_{v}) && (\text{バイアス Q,K,V)}\\[4pt] -&\quad+ (h d_{v})\, d_{\text{model}} && (\text{出力射影 }W^{O})\\ -&\quad+ d_{\text{model}} && (\text{バイアス }b^{O}) -\end{aligned}} -\] - -## Formulas in a Table - -| Area | Expression | Comment | -|------|------------|---------| -| **Algebra** | \[ -x = \frac{-b \pm \sqrt{\,b^{2}-4ac\,}}{2a} -\] | Quadratic formula | -| | \[ -(a+b)^{n} = \sum_{k=0}^{n}\binom{n}{k}\,a^{\,n-k}\,b^{\,k} -\] | Binomial theorem | -| | \(\displaystyle \prod_{k=1}^{n}k = n! \) | Factorial definition | -| **Geometry** | \( \mathbf{a}\cdot \mathbf{b} = \|\mathbf{a}\|\,\|\mathbf{b}\|\,\cos\theta \) | Dot product & angle | - -## No math (but chemical) - -Balanced chemical reaction with states: - -\[ -\ce{2H2(g) + O2(g) -> 2H2O(l)} -\] - -The standard enthalpy change for the reaction is: $\Delta H^\circ = \pu{-572 kJ mol^{-1}}$. - ---- - -*This document showcases various mathematical notation and formulas that can be rendered in markdown using LaTeX syntax.* -`; diff --git a/tools/ui/tests/stories/fixtures/mobile-tables.ts b/tools/ui/tests/stories/fixtures/mobile-tables.ts deleted file mode 100644 index 3e9cc3231db3..000000000000 --- a/tools/ui/tests/stories/fixtures/mobile-tables.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Table-heavy answers, to check the table layout at a phone width. -export const JOKES_TABLE_MD = String.raw` -Sure! Here are the jokes in a table: - -| No. | Joke | -|-----|------| -| 1 | Why don't scientists trust atoms? Because they make up everything. | -| 2 | I told my wife she was drawing her eyebrows too high. She looked surprised. | -| 3 | Why did the scarecrow win an award? Because he was outstanding in his field. | -| 4 | I'm reading a book about anti-gravity. It's impossible to put down. | -| 5 | Why don't skeletons fight each other? They don't have the guts. | -| 6 | I used to hate clowns, but they all have their fat-sies. | -| 7 | What do you call a fake noodle? An impasta. | -| 8 | Why did the bicycle fall over? Because it was two-tired. | -| 9 | I would tell you a chemistry joke, but I know I wouldn't get a reaction. | -| 10 | Why did the golfer bring two pairs of pants? In case he got a hole in one. | -`; - -export const WIDE_CELL_TABLE_MD = String.raw` -Some endpoints, in a table, for reference: - -| Name | Endpoint | Description | -|------|----------|-------------| -| Completions | https://huggingface.co/api/models/ggml-org/gpt-oss-20b-GGUF/summary | Long endpoint description | -| Models | ./v1/models | Lists the models loaded in the server slot | -| Props | ./props | Server capabilities and default sampling | -`; diff --git a/tools/ui/tests/stories/fixtures/readme.ts b/tools/ui/tests/stories/fixtures/readme.ts deleted file mode 100644 index e8b573d6c4e3..000000000000 --- a/tools/ui/tests/stories/fixtures/readme.ts +++ /dev/null @@ -1,136 +0,0 @@ -// README Content -export const README_MD = String.raw` -# 🚀 Awesome Web Framework - -[![npm version](https://img.shields.io/npm/v/awesome-framework.svg)](https://www.npmjs.com/package/awesome-framework) -[![Build Status](https://github.com/awesome/framework/workflows/CI/badge.svg)](https://github.com/awesome/framework/actions) -[![Coverage](https://codecov.io/gh/awesome/framework/branch/main/graph/badge.svg)](https://codecov.io/gh/awesome/framework) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) - -> A modern, fast, and flexible web framework for building scalable applications - -## ✨ Features - -- 🎯 **Type-Safe** - Full TypeScript support out of the box -- ⚡ **Lightning Fast** - Built on Vite for instant HMR -- 📦 **Zero Config** - Works out of the box for most use cases -- 🎨 **Flexible** - Unopinionated with sensible defaults -- 🔧 **Extensible** - Plugin system for custom functionality -- 📱 **Responsive** - Mobile-first approach -- 🌍 **i18n Ready** - Built-in internationalization -- 🔒 **Secure** - Security best practices by default - -## 📦 Installation - -${'```'}bash -npm install awesome-framework -# or -yarn add awesome-framework -# or -pnpm add awesome-framework -${'```'} - -## 🚀 Quick Start - -### Create a new project - -${'```'}bash -npx create-awesome-app my-app -cd my-app -npm run dev -${'```'} - -### Basic Example - -${'```'}javascript -import { createApp } from 'awesome-framework'; - -const app = createApp({ - port: 3000, - middleware: ['cors', 'helmet', 'compression'] -}); - -app.get('/', (req, res) => { - res.json({ message: 'Hello World!' }); -}); - -app.listen(() => { - console.log('Server running on http://localhost:3000'); -}); -${'```'} - -## 📖 Documentation - -### Core Concepts - -- [Getting Started](https://docs.awesome.dev/getting-started) -- [Configuration](https://docs.awesome.dev/configuration) -- [Routing](https://docs.awesome.dev/routing) -- [Middleware](https://docs.awesome.dev/middleware) -- [Database](https://docs.awesome.dev/database) -- [Authentication](https://docs.awesome.dev/authentication) - -### Advanced Topics - -- [Performance Optimization](https://docs.awesome.dev/performance) -- [Deployment](https://docs.awesome.dev/deployment) -- [Testing](https://docs.awesome.dev/testing) -- [Security](https://docs.awesome.dev/security) - -## 🛠️ Development - -### Prerequisites - -- Node.js >= 18 -- pnpm >= 8 - -### Setup - -${'```'}bash -git clone https://github.com/awesome/framework.git -cd framework -pnpm install -pnpm dev -${'```'} - -### Testing - -${'```'}bash -pnpm test # Run unit tests -pnpm test:e2e # Run end-to-end tests -pnpm test:watch # Run tests in watch mode -${'```'} - -## 🤝 Contributing - -We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details. - -### Contributors - - - - - -## 📊 Benchmarks - -| Framework | Requests/sec | Latency (ms) | Memory (MB) | -|-----------|-------------|--------------|-------------| -| **Awesome** | **45,230** | **2.1** | **42** | -| Express | 28,450 | 3.5 | 68 | -| Fastify | 41,200 | 2.3 | 48 | -| Koa | 32,100 | 3.1 | 52 | - -*Benchmarks performed on MacBook Pro M2, Node.js 20.x* - -## 📝 License - -MIT © [Awesome Team](https://github.com/awesome) - -## 🙏 Acknowledgments - -Special thanks to all our sponsors and contributors who make this project possible. - ---- - -**[Website](https://awesome.dev)** • **[Documentation](https://docs.awesome.dev)** • **[Discord](https://discord.gg/awesome)** • **[Twitter](https://twitter.com/awesomeframework)** -`; diff --git a/tools/ui/tests/stories/fixtures/storybook-mocks.ts b/tools/ui/tests/stories/fixtures/storybook-mocks.ts deleted file mode 100644 index ac9fb63cd077..000000000000 --- a/tools/ui/tests/stories/fixtures/storybook-mocks.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { modelsStore } from '$lib/stores/models/index.svelte'; -import { serverStore } from '$lib/stores/server.svelte'; - -/** - * Mock server properties for Storybook testing - * This utility allows setting mock server configurations without polluting production code - */ -export function mockServerProps(props: Partial): void { - // Reset any pointer-events from previous tests (dropdown cleanup) - const body = document.querySelector('body'); - - if (body) body.style.pointerEvents = ''; - - // Directly set the props for testing purposes - (serverStore as unknown as { props: ApiLlamaCppServerProps }).props = { - modalities: { - audio: props.modalities?.audio ?? false, - video: props.modalities?.video ?? false, - vision: props.modalities?.vision ?? false - }, - model_path: props.model_path || 'test-model', - ...props - } as ApiLlamaCppServerProps; - - // Set router mode role so activeModelId can be set - (serverStore as unknown as { props: ApiLlamaCppServerProps }).props.role = 'ROUTER'; - - // Also mock modelsStore methods for modality checking - const vision = props.modalities?.vision ?? false; - const audio = props.modalities?.audio ?? false; - const video = props.modalities?.video ?? false; - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).modelSupportsVision = () => vision; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).modelSupportsAudio = () => audio; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).modelSupportsVideo = () => video; - - // Mock models list with a test model so activeModelId can be resolved - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).models = [ - { - id: 'test-model', - model: 'test-model', - name: 'Test Model' - } - ]; - - // Mock selectedModelId - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (modelsStore as any).selectedModelId = 'test-model'; -} - -/** - * Reset server store to clean state for testing - */ -export function resetServerStore(): void { - (serverStore as unknown as { props: ApiLlamaCppServerProps }).props = { - modalities: { - audio: false, - video: false, - vision: false - }, - model_path: '' - } as ApiLlamaCppServerProps; - (serverStore as unknown as { error: string }).error = ''; - (serverStore as unknown as { loading: boolean }).loading = false; -} - -/** - * Common mock configurations for Storybook stories - */ -export const mockConfigs = { - audioOnly: { - modalities: { audio: true, vision: false } - }, - bothModalities: { - modalities: { audio: true, vision: true } - }, - noModalities: { - modalities: { audio: false, video: false, vision: false } - }, - visionOnly: { - modalities: { audio: false, vision: true } - } -} as const; diff --git a/tools/ui/tests/unit/conversations-store.test.ts b/tools/ui/tests/unit/conversations-store.test.ts deleted file mode 100644 index e06546597bbe..000000000000 --- a/tools/ui/tests/unit/conversations-store.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -// Field updates to the active conversation must keep the object identity -// stable: effects that track the identity ( the chat screen's sibling-info -// refresh ) refire on every identity change, which used to trigger a full -// message refetch on every send and tool result. - -import { beforeEach, describe, expect, it, vi } from 'vitest'; - -vi.mock('$lib/services/database.service', () => ({ - DatabaseService: { - getConversation: vi.fn(), - getConversationMessages: vi.fn(), - updateConversation: vi.fn(), - updateCurrentNode: vi.fn() - } -})); - -import { DatabaseService } from '$lib/services/database.service'; -import { conversationsStore } from '$lib/stores/conversations/index.svelte'; -import type { DatabaseConversation, DatabaseMessage } from '$lib/types/database'; - -const getConversationMock = vi.mocked(DatabaseService.getConversation); -const getMessagesMock = vi.mocked(DatabaseService.getConversationMessages); -const updateCurrentNodeMock = vi.mocked(DatabaseService.updateCurrentNode); - -function makeConversation(overrides: Partial = {}): DatabaseConversation { - return { - currNode: 'node-1', - id: 'conv-1', - lastModified: 1000, - name: 'conversation', - ...overrides - }; -} - -async function loadActive(conversation: DatabaseConversation, messages: DatabaseMessage[]) { - getConversationMock.mockResolvedValue(conversation); - getMessagesMock.mockResolvedValue(messages); - - expect(await conversationsStore.loadConversation(conversation.id)).toBe(true); -} - -beforeEach(() => { - getConversationMock.mockReset(); - getMessagesMock.mockReset(); - updateCurrentNodeMock.mockReset(); - updateCurrentNodeMock.mockResolvedValue(undefined); - vi.mocked(DatabaseService.updateConversation).mockReset(); - vi.mocked(DatabaseService.updateConversation).mockResolvedValue(undefined); -}); - -describe('active conversation identity', () => { - it('hands the load read off exactly once', async () => { - await loadActive(makeConversation(), []); - - expect(conversationsStore.consumeLastLoadedMessages('conv-1')).toEqual([]); - // a second consume is a miss: branch actions must fall back to a refetch - expect(conversationsStore.consumeLastLoadedMessages('conv-1')).toBeNull(); - }); - - it('writes currNode in place on updateCurrentNode', async () => { - await loadActive(makeConversation(), []); - const before = conversationsStore.activeConversation; - - await conversationsStore.updateCurrentNode('node-2'); - - expect(conversationsStore.activeConversation).toBe(before); - expect(conversationsStore.activeConversation?.currNode).toBe('node-2'); - }); - - it('writes renamed and pinned fields in place on applyConversationUpdate', async () => { - await loadActive(makeConversation(), []); - const before = conversationsStore.activeConversation; - - conversationsStore.applyConversationUpdate('conv-1', { name: 'renamed', pinned: true }); - - expect(conversationsStore.activeConversation).toBe(before); - expect(conversationsStore.activeConversation?.name).toBe('renamed'); - expect(conversationsStore.activeConversation?.pinned).toBe(true); - }); - - it('writes lastModified in place on updateConversationTimestamp', async () => { - await loadActive(makeConversation(), []); - const before = conversationsStore.activeConversation; - - conversationsStore.updateConversationTimestamp('conv-1'); - - expect(conversationsStore.activeConversation).toBe(before); - expect(conversationsStore.activeConversation?.lastModified).toBeGreaterThan(1000); - }); -}); diff --git a/tools/ui/tests/unit/pwa.spec.ts b/tools/ui/tests/unit/pwa.spec.ts deleted file mode 100644 index fc96e4ed9d35..000000000000 --- a/tools/ui/tests/unit/pwa.spec.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { existsSync, readdirSync, readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import { describe, expect, it } from 'vitest'; - -const DIST_DIR = resolve(__dirname, '../../dist'); -const distExists = existsSync(DIST_DIR); - -// PWA Build Output tests are integration tests that require a built dist/. -// CI builds first then runs these tests; local devs should run `npm run build` or use `npm run test:pwa`. -describe('PWA Build Output', () => { - if (!distExists) { - console.warn(`⚠ Skipping PWA Build Output tests - dist/ not found (run 'npm run build' first)`); - it('skipped - dist/ not found', () => {}); - - return; - } - - const swContent = readFileSync(resolve(DIST_DIR, 'sw.js'), 'utf-8'); - const indexContent = readFileSync(resolve(DIST_DIR, 'index.html'), 'utf-8'); - - describe('Core files exist', () => { - it('service worker (sw.js) exists', () => { - expect(existsSync(resolve(DIST_DIR, 'sw.js')), 'sw.js not found').toBeTruthy(); - }); - - it('workbox library exists (hashed filename)', () => { - // SvelteKit generates workbox-{hash}.js files - const files = readdirSync(DIST_DIR).filter((f) => f.match(/^workbox-[^.]+\.js$/)); - - expect(files.length).toBeGreaterThan(0); - }); - - it('manifest.webmanifest exists', () => { - expect( - existsSync(resolve(DIST_DIR, 'manifest.webmanifest')), - 'manifest.webmanifest not found' - ).toBeTruthy(); - }); - - it('SvelteKit bundle.js exists in _app/immutable/', () => { - // SvelteKit generates hashed bundle names in _app/immutable/ - const appDir = resolve(DIST_DIR, '_app', 'immutable'); - - expect(existsSync(appDir), '_app/immutable/ not found').toBeTruthy(); - const files = readdirSync(appDir).filter((f) => f.startsWith('bundle.') && f.endsWith('.js')); - - expect(files.length).toBeGreaterThan(0); - }); - - it('SvelteKit bundle.css exists in _app/immutable/assets/', () => { - // SvelteKit generates hashed CSS bundles in _app/immutable/assets/ - const cssDir = resolve(DIST_DIR, '_app', 'immutable', 'assets'); - - expect(existsSync(cssDir), '_app/immutable/assets/ not found').toBeTruthy(); - const files = readdirSync(cssDir).filter( - (f) => f.startsWith('bundle.') && f.endsWith('.css') - ); - - expect(files.length).toBeGreaterThan(0); - }); - - it('version.json exists in _app/', () => { - // SvelteKit stores version.json in _app directory - expect( - existsSync(resolve(DIST_DIR, '_app', 'version.json')), - '_app/version.json not found' - ).toBeTruthy(); - }); - }); - - describe('version.json content', () => { - it('has valid JSON with version field', () => { - const content = readFileSync(resolve(DIST_DIR, '_app', 'version.json'), 'utf-8'); - const parsed = JSON.parse(content); - - expect(parsed).toHaveProperty('version'); - expect(typeof parsed.version).toBe('string'); - expect(parsed.version.length).toBeGreaterThan(0); - }); - }); - - describe('Service worker content', () => { - it('service worker has minified self.define format', () => { - expect(swContent).toBeTruthy(); - // SvelteKit's workbox-plugin-sveltekit produces a minified SW with self.define - expect(swContent).toMatch(/if\(!self.define\)/); - }); - - it('references hashed workbox file (SvelteKit build output)', () => { - expect(swContent).toBeTruthy(); - // SvelteKit's workbox-plugin-sveltekit references hashed workbox files - expect(swContent).toMatch(/define\(\["\.\/workbox-[a-zA-Z0-9]+"\]/); - }); - - it('precache contains SvelteKit bundle.js with content hash', () => { - expect(swContent).toBeTruthy(); - // SvelteKit uses content-hashed bundle names in _app/immutable/ - expect(swContent).toMatch(/"_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"/); - }); - - it('precache contains SvelteKit bundle.css with content hash', () => { - expect(swContent).toBeTruthy(); - // SvelteKit uses content-hashed CSS bundle names in _app/immutable/assets/ - expect(swContent).toMatch(/"_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css"/); - }); - - it('precache contains _app/version.json', () => { - expect(swContent).toBeTruthy(); - // SvelteKit stores version.json in _app directory - expect(swContent).toMatch(/"_app\/version\.json"/); - }); - - it('precache contains manifest.webmanifest', () => { - expect(swContent).toBeTruthy(); - expect(swContent).toMatch(/"manifest\.webmanifest"/); - }); - - it('no navigation route — API endpoints bypass PWA', () => { - expect(swContent).toBeTruthy(); - // NavigationRoute is intentionally absent so direct browser - // navigation to server API endpoints returns JSON, not HTML. - expect(swContent).not.toMatch(/NavigationRoute/); - }); - - it('has runtime caching for API routes', () => { - expect(swContent).toBeTruthy(); - expect(swContent).toMatch(/api-cache/); - expect(swContent).toMatch(/NetworkFirst/); - }); - }); - - describe('index.html content', () => { - it('has modulepreload link for SvelteKit bundle with content hash', () => { - expect(indexContent).toBeTruthy(); - // SvelteKit generates hashed bundle names in _app/immutable/ - expect(indexContent).toMatch(/href="(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"/); - }); - - it('has stylesheet link for SvelteKit bundle.css with content hash', () => { - expect(indexContent).toBeTruthy(); - expect(indexContent).toMatch( - /href="(\.\/|\/)_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css"/ - ); - }); - - it('has dynamic import for SvelteKit bundle with content hash', () => { - expect(indexContent).toBeTruthy(); - expect(indexContent).toMatch( - /import\("(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"\)/ - ); - }); - - it('has __sveltekit__ variable (SvelteKit adds hash suffix)', () => { - expect(indexContent).toBeTruthy(); - // SvelteKit 2.x uses __sveltekit__ as base with random suffix - expect(indexContent).toMatch(/__sveltekit_[a-zA-Z0-9-]+/); - }); - - it('has PWA manifest link', () => { - expect(indexContent).toBeTruthy(); - expect(indexContent).toMatch(/rel="manifest" href="(\.?\/)?manifest\.webmanifest"/); - }); - - it('has apple-touch-icon link', () => { - expect(indexContent).toBeTruthy(); - expect(indexContent).toMatch(/rel="apple-touch-icon"/); - }); - - it('has _app paths for SvelteKit bundles', () => { - expect(indexContent).toBeTruthy(); - // SvelteKit uses _app paths for hashed assets - expect(indexContent).toMatch(/_app\//); - }); - }); - - describe('SvelteKit _app directory', () => { - it('_app directory exists (SvelteKit uses it for hashed assets)', () => { - expect(existsSync(resolve(DIST_DIR, '_app'))).toBeTruthy(); - }); - }); - - describe('Hashed workbox files', () => { - it('workbox-*.js files exist in dist root (SvelteKit build output)', () => { - const files = readdirSync(DIST_DIR).filter((f) => f.match(/^workbox-[^.]+\.js$/)); - - expect(files.length).toBeGreaterThan(0); - }); - }); - - describe('Static assets', () => { - it('has favicon.ico', () => { - expect(existsSync(resolve(DIST_DIR, 'favicon.ico'))).toBeTruthy(); - }); - - it('has PWA icons', () => { - expect(existsSync(resolve(DIST_DIR, 'pwa-64x64.png'))).toBeTruthy(); - expect(existsSync(resolve(DIST_DIR, 'pwa-192x192.png'))).toBeTruthy(); - expect(existsSync(resolve(DIST_DIR, 'pwa-512x512.png'))).toBeTruthy(); - }); - }); -}); diff --git a/tools/ui/tsconfig.json b/tools/ui/tsconfig.json deleted file mode 100644 index 60047e995be7..000000000000 --- a/tools/ui/tsconfig.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "extends": "./.svelte-kit/tsconfig.json", - "compilerOptions": { - "allowJs": true, - "checkJs": true, - "esModuleInterop": true, - "forceConsistentCasingInFileNames": true, - "resolveJsonModule": true, - "skipLibCheck": true, - "sourceMap": true, - "strict": true, - "moduleResolution": "bundler" - }, - "include": [ - ".svelte-kit/ambient.d.ts", - ".svelte-kit/non-ambient.d.ts", - ".svelte-kit/types/**/$types.d.ts", - "vite.config.js", - "vite.config.ts", - "src/**/*.js", - "src/**/*.ts", - "src/**/*.svelte", - "tests/**/*.ts", - "tests/**/*.svelte", - ".storybook/**/*.ts", - ".storybook/**/*.svelte" - ], - "exclude": ["src/lib/services/sandbox-worker.js", "src/lib/vendors/**"] - // Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias - // except $lib which is handled by https://svelte.dev/docs/kit/configuration#files - // - // If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes - // from the referenced tsconfig.json - TypeScript does not merge them in -} diff --git a/tools/ui/vite.config.ts b/tools/ui/vite.config.ts deleted file mode 100644 index b213ec8ab4ae..000000000000 --- a/tools/ui/vite.config.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { buildInfoPlugin } from './scripts/vite-plugin-build-info'; -import { nerdamerPlugin } from './scripts/vite-plugin-nerdamer'; -import { relativizeBasePlugin } from './scripts/vite-plugin-relativize-base'; -import { splashScreenPlugin } from './scripts/vite-plugin-splash-screen'; -import { SVELTEKIT_PWA_OPTIONS } from './src/lib/constants/pwa.constants'; -import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'; -import { sveltekit } from '@sveltejs/kit/vite'; -import tailwindcss from '@tailwindcss/vite'; -import { SvelteKitPWA } from '@vite-pwa/sveltekit'; -import { playwright } from '@vitest/browser-playwright'; -import { dirname, resolve } from 'path'; -import { fileURLToPath } from 'url'; -import { defineConfig, loadEnv, searchForWorkspaceRoot } from 'vite'; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const browserBaseConfig: any = { - enabled: true, - instances: [{ browser: 'chromium' }], - // CI runs the bundled Chromium without its sandbox, which the runners can't start; - // locally, the installed (auto-updated) Chrome with its sandbox on, see playwright.config.ts - provider: playwright({ - launchOptions: process.env.CI - ? { args: ['--no-sandbox'] } - : { channel: 'chrome', chromiumSandbox: true } - }) -}; - -export default defineConfig(({ mode }) => { - const env = loadEnv(mode, process.cwd(), 'VITE_PUBLIC_'); - const SERVER_ORIGIN = env.VITE_PUBLIC_SERVER_ORIGIN || 'http://localhost:9931'; - - return { - build: { - assetsInlineLimit: 32000, - chunkSizeWarningLimit: 3072, - minify: true - }, - - plugins: [ - tailwindcss(), - sveltekit(), - SvelteKitPWA(SVELTEKIT_PWA_OPTIONS), - splashScreenPlugin(), - buildInfoPlugin(), - nerdamerPlugin(), - relativizeBasePlugin() - ], - - resolve: { - alias: { - 'katex-fonts': resolve('node_modules/katex/dist/fonts') - } - }, - - server: { - fs: { - allow: [searchForWorkspaceRoot(process.cwd()), resolve(__dirname, 'tests')] - }, - headers: { - 'Cross-Origin-Embedder-Policy': 'require-corp', - 'Cross-Origin-Opener-Policy': 'same-origin' - }, - proxy: { - '/cors-proxy': SERVER_ORIGIN, - '/models': SERVER_ORIGIN, - '/props': SERVER_ORIGIN, - '/slots': SERVER_ORIGIN, - '/tools': SERVER_ORIGIN, - '/v1': SERVER_ORIGIN - } - }, - - test: { - projects: [ - { - extends: './vite.config.ts', - test: { - browser: browserBaseConfig, - include: ['tests/client/**/*.svelte.{test,spec}.{js,ts}'], - name: 'client', - setupFiles: ['./vitest-setup-client.ts'] - } - }, - - { - extends: './vite.config.ts', - test: { - environment: 'node', - include: ['tests/unit/**/*.{test,spec}.{js,ts}'], - name: 'unit' - } - }, - - { - extends: './vite.config.ts', - plugins: [ - storybookTest({ - storybookScript: 'pnpm run storybook --no-open' - }) - ], - test: { - browser: { ...browserBaseConfig, instances: [{ browser: 'chromium', headless: true }] }, - name: 'ui' - } - } - ] - } - }; -}); diff --git a/ty.toml b/ty.toml index 1a11151e67d9..2774cdbb8ed5 100644 --- a/ty.toml +++ b/ty.toml @@ -22,13 +22,3 @@ unresolved-reference = "ignore" import-not-found = "ignore" missing-attribute = "ignore" missing-union-attribute = "ignore" - -[[overrides]] -include = [ - "./examples/pydantic_models_to_grammar.py", -] - -[overrides.rules] -unsupported-operator = "ignore" -not-subscriptable = "ignore" -invalid-type-form = "ignore" diff --git a/ui/README.md b/ui/README.md new file mode 100644 index 000000000000..0f210a40c80c --- /dev/null +++ b/ui/README.md @@ -0,0 +1,41 @@ +# ui + +The UI of llama.cpp: the packages in `lib` and the apps built on them. + +```text +ui/ +├── lib/ +│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components +│ └── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation +└── apps/ + └── chat/ Llama Chat, the chat app that llama-server serves +``` + +- [`lib/ui`](lib/ui/README.md) draws the parts and handles interaction, with no business logic. It is built with + `@sveltejs/package` and published to npm as `@ggml-org/llama-ui`. Apps in this repo skip the package: they compile + its sources as part of their own build, so they hold no copy of a component, a token or a font. +- [`lib/voice`](lib/voice/README.md) records the microphone and turns speech into text through llama-server, with no + UI: Llama UI draws the voice parts. It is plain TypeScript built with `tsc`, plus a Svelte entry + (`@ggml-org/llama-voice/svelte`). Apps in this repo compile its sources too. It is not published to npm yet. +- [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop. CMake + builds it into llama-server (see `scripts/ui-assets.cmake`), and it is published to npm as `@ggml-org/llama-chat` + (with `llama-chat` as its short name), so `npx llama-chat` runs it against any llama-server. + +Each folder is its own npm package with its own `package-lock.json`: run `npm ci` in the one you work on. Building, +checking and testing `apps/chat` needs no install in `lib/ui` or `lib/voice`. + +## Releases + +The npm packages are versioned by hand, with semver, and published by CI: + +| Package | Version in | Published by | +| --- | --- | --- | +| `@ggml-org/llama-ui` | `lib/ui/package.json` | [`ui-lib-publish.yml`](../.github/workflows/ui-lib-publish.yml) | +| `@ggml-org/llama-chat` and `llama-chat` | `apps/chat/package.json` and `apps/chat/alias/package.json`, always the same | [`ui-chat-publish.yml`](../.github/workflows/ui-chat-publish.yml) | + +To release, bump the version in the PR that should ship the change: a patch for fixes, a minor for new or changed +features or API while the version is 0.x. When that PR reaches `master` with a version npm does not have yet, the +workflow builds the package and publishes it; any other commit publishes nothing. A version lower than the one on npm +fails the run. + +Llama Chat as bundled in llama-server is not versioned this way: it ships in every llama.cpp release, as `b`. diff --git a/tools/ui/.env.example b/ui/apps/chat/.env.example similarity index 94% rename from tools/ui/.env.example rename to ui/apps/chat/.env.example index a561a68a6560..ed46f9aded97 100644 --- a/tools/ui/.env.example +++ b/ui/apps/chat/.env.example @@ -13,7 +13,7 @@ VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033' # DEMO_TRACES_DATASET='/' # DEMO_GITHUB_REPO='ggml-org/llama.cpp' # DEMO_SERVER_ORIGIN='http://localhost:9931' -# DEMO_LLAMA_SERVER='../../build/bin/llama-server' +# DEMO_LLAMA_SERVER='../../../build/bin/llama-server' # DEMO_COLOR_SCHEME='light' # Device pixel ratio demos render and record at (1440x900 viewport) # DEMO_SCALE='2' diff --git a/tools/ui/.gitignore b/ui/apps/chat/.gitignore similarity index 100% rename from tools/ui/.gitignore rename to ui/apps/chat/.gitignore diff --git a/tools/ui/.npmrc b/ui/apps/chat/.npmrc similarity index 100% rename from tools/ui/.npmrc rename to ui/apps/chat/.npmrc diff --git a/tools/ui/.prettierignore b/ui/apps/chat/.prettierignore similarity index 100% rename from tools/ui/.prettierignore rename to ui/apps/chat/.prettierignore diff --git a/tools/ui/.prettierrc b/ui/apps/chat/.prettierrc similarity index 100% rename from tools/ui/.prettierrc rename to ui/apps/chat/.prettierrc diff --git a/ui/apps/chat/.storybook/color-scheme.ts b/ui/apps/chat/.storybook/color-scheme.ts new file mode 100644 index 000000000000..4ebfb46ee5cf --- /dev/null +++ b/ui/apps/chat/.storybook/color-scheme.ts @@ -0,0 +1,24 @@ +import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts'; +import { ColorMode } from '#lib/enums/ui.enums.ts'; +import { modeStorageKey } from 'mode-watcher'; + +/** The class on `` that turns the dark theme on, as mode-watcher sets it. */ +export const DARK_CLASS = ColorMode.DARK; + +/** Turns the dark theme on or off. */ +export function setDarkClass(isDark: boolean) { + document.documentElement.classList.toggle(DARK_CLASS, isDark); +} + +/** + * Sets the dark class from the saved mode-watcher mode, or the system preference + * when there is none. Docs pages render no story, so preview.ts calls this too. + */ +export function applyColorScheme() { + const mode = localStorage.getItem(modeStorageKey.current) || ColorMode.SYSTEM; + const isDark = + mode === ColorMode.DARK || + (mode === ColorMode.SYSTEM && window.matchMedia(MEDIA_QUERIES.PREFERS_DARK).matches); + + setDarkClass(isDark); +} diff --git a/ui/apps/chat/.storybook/decorators/ModeWatcherDecorator.svelte b/ui/apps/chat/.storybook/decorators/ModeWatcherDecorator.svelte new file mode 100644 index 000000000000..82fa0b10ac5c --- /dev/null +++ b/ui/apps/chat/.storybook/decorators/ModeWatcherDecorator.svelte @@ -0,0 +1,27 @@ + + +{#if !forced}{/if} + +{#if children} + {@const Component = children} + + +{/if} diff --git a/ui/apps/chat/.storybook/decorators/TooltipProviderDecorator.svelte b/ui/apps/chat/.storybook/decorators/TooltipProviderDecorator.svelte new file mode 100644 index 000000000000..76d15b48d6af --- /dev/null +++ b/ui/apps/chat/.storybook/decorators/TooltipProviderDecorator.svelte @@ -0,0 +1,13 @@ + + + + {@render children()} + diff --git a/ui/apps/chat/.storybook/main.ts b/ui/apps/chat/.storybook/main.ts new file mode 100644 index 000000000000..e2b8dad14377 --- /dev/null +++ b/ui/apps/chat/.storybook/main.ts @@ -0,0 +1,58 @@ +import type { StorybookConfig } from '@storybook/sveltekit'; +import { dirname, resolve } from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +// Llama UI's stories live with the library (ui/lib/ui/tests/stories), which runs and tests them in its own +// Storybook; this one shows them too, under Llama UI, next to Llama Chat's own. The library's front page stays its own. +// Llama Chat's stories take the helpers they share with the library's (the Editorial, the state gallery) from there +// too, as $llama-ui-stories/..., which tsconfig.json maps for TypeScript +const LLAMA_UI_STORIES = resolve(__dirname, '../../../lib/ui/tests/stories'); + +const config: StorybookConfig = { + stories: [ + '../tests/stories/**/*.mdx', + '../tests/stories/**/*.stories.@(js|ts|svelte)', + { + directory: '../../../lib/ui/tests/stories', + files: '{foundations,components,app,models,mockups,voice}/**/*.stories.svelte' + } + ], + addons: [ + '@storybook/addon-svelte-csf', + '@chromatic-com/storybook', + '@storybook/addon-vitest', + '@storybook/addon-a11y', + '@storybook/addon-docs', + '@storybook/addon-mcp' + ], + framework: '@storybook/sveltekit', + viteFinal: async (config) => { + config.server = config.server || {}; + config.server.fs = config.server.fs || {}; + config.server.fs.allow = [ + ...(config.server.fs.allow || []), + resolve(__dirname, '../tests'), + LLAMA_UI_STORIES + ]; + // the library's stories import Storybook from where they live, where only this app's packages are installed + config.resolve = config.resolve || {}; + config.resolve.alias = [ + ...(Array.isArray(config.resolve.alias) + ? config.resolve.alias + : Object.entries(config.resolve.alias || {}).map(([find, replacement]) => ({ + find, + replacement + }))), + { find: '$llama-ui-stories', replacement: LLAMA_UI_STORIES } + ]; + config.resolve.dedupe = [ + ...(config.resolve.dedupe || []), + '@storybook/addon-svelte-csf', + 'storybook' + ]; + return config; + } +}; +export default config; diff --git a/ui/apps/chat/.storybook/manager-head.html b/ui/apps/chat/.storybook/manager-head.html new file mode 100644 index 000000000000..5964c8fa3cb4 --- /dev/null +++ b/ui/apps/chat/.storybook/manager-head.html @@ -0,0 +1,86 @@ + + diff --git a/ui/apps/chat/.storybook/mockups/MacDock.svelte b/ui/apps/chat/.storybook/mockups/MacDock.svelte new file mode 100644 index 000000000000..0c2fdfad9bcf --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/MacDock.svelte @@ -0,0 +1,174 @@ + + + + + +{#snippet tile(app: DockApp)} + + {#if app.name === labelled}{app.name}{/if} + + {#if app.icon} + {app.name} + {:else} + {@const Glyph = app.glyph ?? Folder} + + + + + + + + + + + {/if} + + + +{/snippet} + + + + diff --git a/ui/apps/chat/.storybook/mockups/MacMenuBar.svelte b/ui/apps/chat/.storybook/mockups/MacMenuBar.svelte new file mode 100644 index 000000000000..5a524adb07ce --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/MacMenuBar.svelte @@ -0,0 +1,119 @@ + + + + + + diff --git a/ui/apps/chat/.storybook/mockups/MacStatusIcon.svelte b/ui/apps/chat/.storybook/mockups/MacStatusIcon.svelte new file mode 100644 index 000000000000..2b857aa5ad37 --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/MacStatusIcon.svelte @@ -0,0 +1,56 @@ + + + + + + + + diff --git a/ui/apps/chat/.storybook/mockups/MockDesktop.svelte b/ui/apps/chat/.storybook/mockups/MockDesktop.svelte new file mode 100644 index 000000000000..51facca5111d --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/MockDesktop.svelte @@ -0,0 +1,76 @@ + + + +
+
+ {@render children()} +
+
+ + diff --git a/ui/apps/chat/.storybook/mockups/WindowsTaskbar.svelte b/ui/apps/chat/.storybook/mockups/WindowsTaskbar.svelte new file mode 100644 index 000000000000..dc2e8afdf8bd --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/WindowsTaskbar.svelte @@ -0,0 +1,234 @@ + + + + + + + + diff --git a/ui/apps/chat/.storybook/mockups/index.ts b/ui/apps/chat/.storybook/mockups/index.ts new file mode 100644 index 000000000000..c4783bde1224 --- /dev/null +++ b/ui/apps/chat/.storybook/mockups/index.ts @@ -0,0 +1,15 @@ +// OS mockups for the stories: a desktop's wallpaper, and on it the macOS Dock and menu bar or the Windows taskbar, +// to picture the brand's icons where the apps put them +export { + default as MacDock, + PLACEHOLDERS as MAC_DOCK_PLACEHOLDERS, + type DockApp +} from './MacDock.svelte'; +export { default as MacMenuBar } from './MacMenuBar.svelte'; +export { default as MacStatusIcon } from './MacStatusIcon.svelte'; +export { default as MockDesktop } from './MockDesktop.svelte'; +export { + default as WindowsTaskbar, + PLACEHOLDERS as WINDOWS_TASKBAR_PLACEHOLDERS, + type TaskbarApp +} from './WindowsTaskbar.svelte'; diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts new file mode 100644 index 000000000000..7e7a58d167a8 --- /dev/null +++ b/ui/apps/chat/.storybook/preview.ts @@ -0,0 +1,142 @@ +import '../src/app.css'; +import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts'; +import { SurfaceTheme } from '#lib/enums/ui.enums.ts'; +import { applySurfaceTheme } from '#lib/utils/css.ts'; +// the docs pages' styles, shared with the library's Storybook +import '../../../lib/ui/.storybook/docs.css'; +import { applyColorScheme } from './color-scheme'; +import ModeWatcherDecorator from './decorators/ModeWatcherDecorator.svelte'; +import TooltipProviderDecorator from './decorators/TooltipProviderDecorator.svelte'; +import type { Preview } from '@storybook/sveltekit'; + +applyColorScheme(); +window.matchMedia(MEDIA_QUERIES.PREFERS_DARK).addEventListener('change', applyColorScheme); + +const preview: Preview = { + parameters: { + controls: { + matchers: { + color: /(background|color)$/i, + date: /Date$/i + } + }, + + backgrounds: { + disabled: true + }, + + options: { + // sidebar sections: the introduction and the guidelines for agents, then the two layers as the code has them. + // Llama UI is the library (ui/lib/ui): its foundations, base components, app components, Model UI and mockups. + // Llama Chat is the app (ui/apps/chat): its own foundations, then one folder per src/lib/components/app/, + // the full chat screen leading Chat. The brand and communications are in llama-brand's Storybook + storySort: { + order: [ + 'Introduction', + 'Agents', + ['Design guidelines'], + 'Llama UI', + [ + 'Foundations', + ['Colors', 'Typography', 'Sizing', 'Shapes', 'Elevation', 'Surfaces'], + 'Components', + ['Actions', 'Forms', 'Display', 'Overlays', 'Navigation'], + 'App components', + 'Models', + 'Mockups' + ], + 'Llama Chat', + [ + 'Foundations', + ['Safe areas', 'Brand'], + 'Chat', + [ + 'ChatScreen', + ['ChatScreen', '*'], + 'ChatForm', + 'ChatMessages', + 'ChatAttachments', + 'ChatTabs' + ], + 'Content', + 'Models', + 'MCP', + 'Navigation', + 'Settings', + ['DialogSettingsChat', 'Navigation', 'Sections'], + 'Dialogs', + 'Forms', + 'Actions', + 'Badges', + 'Misc', + 'Servers', + 'PWA' + ] + ] + } + }, + + a11y: { + // 'todo' shows violations in the Accessibility panel and the test UI without failing a test; 'error' would + // fail CI on them. Not yet 'error': about half the stories fail it, most on colour contrast (the muted + // foreground on the light surfaces, below 4.5:1) and nested interactive controls, which need design changes + // rather than story fixes. Switch once those are settled + test: 'todo' + } + }, + // read by tests/stories/pace.ts; the test runner always plays at full speed + globalTypes: { + interactionPace: { + description: 'Speed of the interactions a story plays', + toolbar: { + dynamicTitle: true, + icon: 'timer', + items: [ + { title: 'Human pace', value: 'human' }, + { title: 'Instant', value: 'instant' } + ], + title: 'Interaction pace' + } + }, + // the light surface theme: Paper (white panels on a grey page) or Matte (grey glass on white) + surface: { + description: 'Light surface theme', + toolbar: { + dynamicTitle: true, + icon: 'paintbrush', + items: [ + { title: 'Paper', value: SurfaceTheme.PAPER }, + { title: 'Matte', value: SurfaceTheme.MATTE } + ], + title: 'Surface' + } + } + }, + initialGlobals: { + interactionPace: 'human', + surface: SurfaceTheme.PAPER + }, + decorators: [ + (story, context) => { + applySurfaceTheme(context.globals.surface); + + return story(); + }, + // `parameters.colorScheme` fixes a story to light or dark, whatever the viewer chose (a scene in a store screenshot) + (story, context) => ({ + Component: ModeWatcherDecorator, + props: { + children: story, + forced: context.parameters.colorScheme + } + }), + (story) => ({ + Component: TooltipProviderDecorator, + props: { + children: story + } + }) + ] +}; + +export default preview; diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md new file mode 100644 index 000000000000..32e6a009a2c9 --- /dev/null +++ b/ui/apps/chat/AGENTS.md @@ -0,0 +1,23 @@ +# Instructions for ui/apps/chat + +These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. + +- **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual. Its token sections (`colors`, `typography`, `rounded`) are generated from the CSS with `npm run design:tokens`, and CI checks they are current; the rest is written by hand, and when it and the CSS disagree, the CSS wins and DESIGN.md is updated. +- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/`, one folder per `src/lib/components/app/` (`chat/` has one per Chat folder), titled `Llama Chat//`. An accessibility story sits next to its component's, as `.a11y.stories.svelte`, titled `...//Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here. +- **Releases:** `@ggml-org/llama-chat` and `@ggml-org/llama-ui` are versioned by hand and published by CI when a new version reaches `master` (see [Releases](../../README.md#releases)). Bump a version only when asked to release, never as a side effect of a change; Chat's version and its alias's (`alias/package.json`) always move together. +- **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions. + +## Content is Markdown, custom pieces are Svelte: .svx + +Anything that is mostly content (a doc, an overview, a showcase or a Storybook page with prose) is written in Markdown, and whatever Markdown cannot express (a live example, a diagram, a real component) is a Svelte component placed in it. Together that is a `.svx` page, compiled by [mdsvex](https://mdsvex.pngwk.com). + +- Write the prose as plain Markdown, so it reads well as source, for people and for agents alike. +- Put each custom piece in its own `.svelte` file and import it in the page's ` + + diff --git a/ui/apps/chat/src/lib/components/app/actions/GlassKey.svelte b/ui/apps/chat/src/lib/components/app/actions/GlassKey.svelte new file mode 100644 index 000000000000..d4a30779932e --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/actions/GlassKey.svelte @@ -0,0 +1,64 @@ + + +{#snippet key(props: Record = {})} + +{/snippet} + + +{#if tooltip && !deviceStore.isMobile} + + + {#snippet child({ props })} + {@render key(props)} + {/snippet} + + + +

{label}

+
+
+{:else} + {@render key()} +{/if} diff --git a/ui/apps/chat/src/lib/components/app/actions/index.ts b/ui/apps/chat/src/lib/components/app/actions/index.ts new file mode 100644 index 000000000000..8b0279d06216 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/actions/index.ts @@ -0,0 +1,16 @@ +/** + * + * ACTIONS + * + * Small interactive components for user actions. + * + */ + +/** Styled icon button for action triggers with tooltip. */ +export { ActionIcon } from '@ggml-org/llama-ui/app/actions'; + +/** Copy-to-clipboard icon button with clipboard logic. */ +export { default as ActionIconCopyToClipboard } from './ActionIconCopyToClipboard.svelte'; + +/** A round matte glass key: a phone's corner keys and the key back to a chat's bottom. */ +export { default as GlassKey } from './GlassKey.svelte'; diff --git a/tools/ui/src/lib/components/app/badges/BadgeInfo.svelte b/ui/apps/chat/src/lib/components/app/badges/BadgeInfo.svelte similarity index 100% rename from tools/ui/src/lib/components/app/badges/BadgeInfo.svelte rename to ui/apps/chat/src/lib/components/app/badges/BadgeInfo.svelte diff --git a/tools/ui/src/lib/components/app/badges/BadgesModality.svelte b/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte similarity index 75% rename from tools/ui/src/lib/components/app/badges/BadgesModality.svelte rename to ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte index 83b1b46affc6..87cc59093779 100644 --- a/tools/ui/src/lib/components/app/badges/BadgesModality.svelte +++ b/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte @@ -1,6 +1,6 @@ + + + + + + + +
+ {#if favicon} + {attachment.resource.serverName} { + (e.currentTarget as HTMLImageElement).style.display = 'none'; + }} + src={favicon} + /> + {/if} + + + {serverName} + +
+
+
diff --git a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailFile.svelte similarity index 83% rename from tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailFile.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailFile.svelte index 409a3a0f4a35..f7d96cd8a25d 100644 --- a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailFile.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailFile.svelte @@ -1,8 +1,8 @@ + +{#snippet image()} + {name} +{/snippet} + +
+ {#if onclick} + + {:else} + {@render image()} + {/if} + + {#if label} + + {label} + + {/if} + + {#if !readonly} +
+ onRemove?.(id)} + stopPropagationOnClick + tooltip="Remove" + /> +
+ {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemVoice.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemVoice.svelte new file mode 100644 index 000000000000..9da8a28db1f1 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemVoice.svelte @@ -0,0 +1,126 @@ + + + +
+ {#key collapsed} + + + + {/key} + + {#if !source.voice} +

{source.name}

+ {/if} + + {#if !readonly && onRemove} +
+ onRemove?.(item.id)} + stopPropagationOnClick + tooltip="Remove" + /> +
+ {/if} +
diff --git a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte similarity index 95% rename from tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte index 1193f0c6ddc8..de23eb85dd09 100644 --- a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreview.svelte @@ -4,9 +4,9 @@ ChatAttachmentsPreviewFileInfo, ChatAttachmentsPreviewNavButtons, ChatAttachmentsPreviewThumbnailStrip - } from '$lib/components/app'; - import { UI_DATA_ATTRS } from '$lib/constants'; - import { modelsStore } from '$lib/stores'; + } from '#lib/components/app/index.ts'; + import { UI_DATA_ATTRS } from '#lib/constants/index.ts'; + import { modelsStore } from '#lib/stores/index.ts'; import { createBase64DataUrl, formatFileSize, @@ -19,7 +19,7 @@ isPdfFile, isTextFile, isVideoFile - } from '$lib/utils'; + } from '#lib/utils/index.ts'; interface PreviewItem { id: string; @@ -189,7 +189,7 @@
1} /> -
+
{#if currentItem} diff --git a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItem.svelte similarity index 97% rename from tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItem.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItem.svelte index eabfe2f1aeeb..b7e7cb448323 100644 --- a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItem.svelte @@ -6,7 +6,7 @@ import ChatAttachmentsPreviewCurrentItemUnavailable from './ChatAttachmentsPreviewCurrentItemUnavailable.svelte'; import ChatAttachmentsPreviewCurrentItemVideo from './ChatAttachmentsPreviewCurrentItemVideo.svelte'; import { FileIcon, FileText, Image, Music, Video } from '@lucide/svelte'; - import type { ChatAttachmentDisplayItem } from '$lib/types'; + import type { ChatAttachmentDisplayItem } from '#lib/types/index.ts'; interface Props { currentItem: ChatAttachmentDisplayItem | null; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte new file mode 100644 index 000000000000..2d2ee228b19f --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte @@ -0,0 +1,50 @@ + + +
+
+ + + {#if audioSrc} + + {:else} +

Audio preview not available

+ {/if} + +

+ {source?.voice ? VOICE_MESSAGE_LABEL : currentItem?.name || 'Audio'} +

+ + {#if transcript} +

+ Transcript: {transcript} +

+ {:else if transcribing} +

Transcribing...

+ {/if} +
+
diff --git a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemImage.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemImage.svelte similarity index 93% rename from tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemImage.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemImage.svelte index 155fad87b4f6..65b670534812 100644 --- a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemImage.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemImage.svelte @@ -11,7 +11,7 @@
{currentItem?.name
diff --git a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte similarity index 87% rename from tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte index 2389a460cb47..07a08026ca40 100644 --- a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte @@ -1,13 +1,13 @@ + +
+

{displayName}

+ + {#if fileSize} +

{fileSize}

+ {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewNavButtons.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewNavButtons.svelte new file mode 100644 index 000000000000..fa1ffa709c43 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewNavButtons.svelte @@ -0,0 +1,34 @@ + + +{#if show} + + + +{/if} diff --git a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte similarity index 77% rename from tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte index e4ecd2357366..2fa421520d3a 100644 --- a/tools/ui/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte @@ -1,8 +1,8 @@ + +
{ event.preventDefault(); - - if (!canSubmit || disabled || hasLoadingAttachments) return; - - onSubmit?.(); + void submit(); }} > @@ -678,8 +731,7 @@
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte new file mode 100644 index 000000000000..e25bcb56f72c --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte @@ -0,0 +1,33 @@ + + + + + + + + +

{ATTACHMENT_TOOLTIP_TEXT}

+
+
diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte similarity index 80% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte index a3d3d1a19928..fe3bff7bdbc2 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte @@ -1,31 +1,30 @@
@@ -205,9 +204,9 @@ /> {/if} - {group.label} + {group.label} - + {enabledCount}/{group.tools.length} diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte similarity index 79% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte index f746a73cb72b..78153bfbdfbe 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte @@ -1,20 +1,22 @@ + + open && toolsPanel.handleOpen()}> + + + + {ATTACHMENT_MENU_TEXT.TOOLS} + + + + {#if toolsPanel.totalToolCount === 0} + {#if toolsStore.loading} +
+ + + Loading tools... +
+ {:else if toolsStore.isToolsEndpointUnreachable} +
+ + + + + Run llama-server with {CLI_FLAGS.TOOLS} flag to enable + + Server Tools. + + + + + {#if uiStore.isMcpShown} + + + + + {hasMcpServersAvailable ? 'Enable' : 'Add'} MCP Server(s) to access + + MCP Tools. + + + {/if} +
+ {:else if toolsStore.error} +
+ Failed to load tools +
+ {:else if toolsPanel.noToolsInfoMessage} +
+ + + {toolsPanel.noToolsInfoMessage} +
+ {:else} +
+ No tools available +
+ {/if} + {:else} +
+ {#each toolsPanel.categoryGroups as group (group.key)} + {@render groupRow(group)} + {/each} + + {#each toolsPanel.mcpGroups as group (group.key)} + {@render groupRow(group)} + {/each} +
+ {/if} +
+
+ +{#snippet groupRow(group: ToolGroup)} + {@const isExpanded = toolsPanel.expandedGroups.has(group.key)} + {@const checkState = toolsPanel.getGroupCheckState(group)} + {@const favicon = toolsPanel.getFavicon(group)} + {@const groupDisabled = toolsPanel.isGroupDisabled(group)} + + toolsPanel.toggleGroupExpanded(group.key)} + open={isExpanded} + > +
+ + {#if isExpanded} + + {:else} + + {/if} + + + {#if favicon} + { + (e.currentTarget as HTMLImageElement).style.display = 'none'; + }} + src={favicon} + /> + {/if} + + {group.label} + + + + {toolsPanel.getEnabledToolCount(group)}/{group.tools.length} + + + + + + {#snippet child({ props })} + toolsPanel.toggleGroupByKey(group.key)} + /> + {/snippet} + + + +

+ {checkState.checked ? 'Disable' : 'Enable'} + {group.tools.length} tool{group.tools.length !== 1 ? 's' : ''} +

+
+
+
+ + +
+ {#each group.tools as entry (entry.key)} + {@const enabled = toolsPanel.isToolEnabled(entry)} + {@const parentDisabled = toolsPanel.isToolParentDisabled(entry)} + + {/each} +
+
+
+{/snippet} diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionsAdd.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionsAdd.svelte similarity index 90% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionsAdd.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionsAdd.svelte index 50eb9be1c017..a63f0bd5c5a2 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionsAdd.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionsAdd.svelte @@ -2,7 +2,7 @@ import ChatFormActionAddButton from './ChatFormActionAddButton.svelte'; import ChatFormActionAddDrawer from './ChatFormActionAddDrawer.svelte'; import ChatFormActionAddDropdown from './ChatFormActionAddDropdown.svelte'; - import { deviceStore } from '$lib/stores'; + import { deviceStore } from '#lib/stores/index.ts'; {#if deviceStore.isMobile} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte new file mode 100644 index 000000000000..91d4b7de03cf --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte @@ -0,0 +1,147 @@ + + +{#snippet triggerLabel()} + + {#if reasoning.isOff} + + {:else} + + {/if} + + {#if !isDefault} + {REASONING_EFFORT_LABELS[reasoning.currentEffort]} + {/if} + +{/snippet} + +{#snippet levelRow(level: ReasoningEffortLevel)} + {@const tokenLabel = reasoning.tokenLabel(level)} + + +{/snippet} + + +{#if isMobile} + + + + + + Reasoning effort + + +
+ {#each reasoning.levels as level (level.value)} + {@render levelRow(level)} + {/each} +
+
+
+{:else} + + + {#snippet child({ props })} + + {/snippet} + + + + {#each reasoning.levels as level (level.value)} + {@const tokenLabel = reasoning.tokenLabel(level)} + + reasoning.select(level)}> + {#if reasoning.isSelected(level)} + + {:else} +
+ {/if} + + {level.label} + + {#if tokenLabel} + {tokenLabel} + {/if} + + {#if level.hasInfo} + + + + + + +

{MAX_EFFORT_HINT}

+
+
+ {/if} +
+ {/each} +
+
+{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte new file mode 100644 index 000000000000..33d52171d7e0 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionRecord.svelte @@ -0,0 +1,148 @@ + + +
+ + + + + + {#if tooltip} + +

{tooltip}

+
+ {/if} +
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte new file mode 100644 index 000000000000..fa26d6bbc10e --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte @@ -0,0 +1,59 @@ + + +{#snippet submitButton(props = {})} + +{/snippet} + +{#if tooltipLabel} + + + {@render submitButton()} + + + +

{tooltipLabel}

+
+
+{:else} + {@render submitButton()} +{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte new file mode 100644 index 000000000000..c895ef0c34b7 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte @@ -0,0 +1,259 @@ + + +
+ {#if showAddButton} +
+ +
+ {/if} + +
+ + {#if showContextGauge.current && !deviceStore.isMobile} + + {/if} + + {#if showModelSelector} + + + {/if} +
+ + {#if isVoiceRefining} + + + + {isSendWaiting ? VOICE_MODE_MESSAGE.sendAfterRefining : VOICE_MODE_MESSAGE.refining} + + {/if} + + {#if isReasoning && !canSend} + + {/if} + + {#snippet record(filled: boolean)} + + {/snippet} + + {#if showRecord && !showStop} + {@render record(false)} + {/if} + + {#if showStop} + + {:else} + + {/if} + + + {#if showRecord && showStop} + {@render record(true)} + {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionsRecording.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionsRecording.svelte new file mode 100644 index 000000000000..5e3d2bbba419 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionsRecording.svelte @@ -0,0 +1,63 @@ + + + + + {#snippet stop({ disabled })} + + {/snippet} + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte new file mode 100644 index 000000000000..221e7b5116d3 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte @@ -0,0 +1,88 @@ + + +{#snippet dial(size: 'sm' | 'md' | 'key')} + +{/snippet} + +{#if corner} + + + {@render dial('key')} + +{:else} +
+ + {@render dial(deviceStore.isMobile ? 'md' : 'sm')} +
+{/if} diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte similarity index 82% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte index 620bd874e952..8dc76858f157 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetailRow.svelte @@ -16,7 +16,7 @@
{#if subtitle} -
+
{subtitle}
{/if} diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte similarity index 86% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte index 34cf3d0bc484..34d22dfd6716 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDetails.svelte @@ -1,6 +1,6 @@
-

Token usage details

+

Token usage details

-
+
{#if hasCumulative}

Across all turns

@@ -68,7 +68,7 @@ {#if hasCurrent}

This turn · KV cache

diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDial.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDial.svelte similarity index 92% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDial.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDial.svelte index f9f2346af1bc..78ff58e58159 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDial.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDial.svelte @@ -1,7 +1,7 @@ + +{#if modelId !== null && !isLoading} +
+ Available context size is only visible once the model is loaded. + + +
+{:else if isLoading} +
+ + + Loading model... +
+{/if} diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte similarity index 87% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte index 8a2cb3c008a3..fbd645720665 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte @@ -8,12 +8,12 @@ gaugePopup, gaugePopupClose } from './gauge-popup.svelte'; + import { Button } from '@ggml-org/llama-ui/ui/button'; + import * as Drawer from '@ggml-org/llama-ui/ui/drawer'; import { FoldVertical, Loader2 } from '@lucide/svelte'; - import { Button } from '$lib/components/ui/button'; - import * as Drawer from '$lib/components/ui/drawer'; - import { useContextGauge } from '$lib/hooks/use-context-gauge.svelte'; - import { agenticStore, chatStore, conversationsStore, deviceStore } from '$lib/stores'; - import { formatParameters } from '$lib/utils/formatters'; + import { useContextGauge } from '#lib/hooks/use-context-gauge.svelte.ts'; + import { agenticStore, chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts'; + import { formatParameters } from '#lib/utils/formatters.ts'; const gauge = useContextGauge(); @@ -90,13 +90,13 @@ disabled={isCompactDisabled} onclick={handleCompact} size="sm" - variant="tertiary" + variant="secondary" > {#if isCompacting} - + Compacting... {:else} - + Compact conversation {/if} @@ -120,7 +120,7 @@ >
-
+
{gauge.contextPercent}% used @@ -130,7 +130,7 @@
{:else} -
No context info available
+
No context info available
{/if} {#if gauge.hasAnyUsage} @@ -172,7 +172,7 @@ {:else if gaugePopup.open}
| undefined; let lastPointerType = ''; diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte similarity index 90% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte index 59020eec2d96..2f9fe042eb48 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte @@ -1,18 +1,23 @@ + + +
+ + + {#if showTooltip && displayLabelTitle} + + + {#snippet child({ props })} + {displayLabel} + {/snippet} + + + +

{displayLabelTitle}

+
+
+ {:else} + {displayLabel} + {/if} +
+ + {#if directory} +
+ +
+ {/if} +
diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte similarity index 75% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte index db86a4ba49c6..bc368ac74a14 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte @@ -1,8 +1,8 @@
-
+
{#if faviconUrl} { (e.currentTarget as HTMLImageElement).style.display = 'none'; }} @@ -44,7 +44,7 @@
{#if description} -

+

{description}

{/if} diff --git a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerList.svelte similarity index 88% rename from tools/ui/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerList.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerList.svelte index 2b3d6167a618..abe0fec74626 100644 --- a/tools/ui/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerList.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerList.svelte @@ -1,8 +1,8 @@ + +{#if info} +
+ {#if info.path === null} + + + Working directory cleared + {:else} + + + Set working directory to  + + + {info.display} + + {/if} +
+{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte new file mode 100644 index 000000000000..2caaf6e4369a --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte @@ -0,0 +1,43 @@ + + +
+ {#if editCtx.isEditing} + + {:else} + + + {#if message.timestamp} +
+ +
+ {/if} + {/if} +
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte similarity index 81% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte index 1ed1cca9908e..d1303379a391 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte @@ -1,10 +1,10 @@ + +{#if isCwdChange} + +{:else} + {message.content} +{/if} diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte similarity index 79% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte index 3a7022227a4d..2770f96d83dc 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte @@ -1,13 +1,13 @@ + + + {#snippet children(_meta, ctx)} + {#if ctx.isStreamingCall} +
+ Input + + {#if ctx.isStreaming} + + {/if} +
+ + {#if section.toolArgs} + + {:else if ctx.isStreaming} +
+ Receiving arguments... +
+ {:else} +
+ Response was truncated +
+ {/if} + {:else} + {@const showInput = Boolean(section.toolArgs)} + {#if showInput} +
+ Input +
+ + + {/if} + +
+ Output + + {#if ctx.isPending} + + {/if} +
+ + {#if ctx.isPending} +
+ Waiting for result... +
+ {:else if section.toolResult} + {#if outputKind === ToolResultKind.JSON} + + {:else if outputKind === ToolResultKind.MARKDOWN} + + {:else} +
+ {#each parsedLines as line, i (i)} +
+ {line.text} +
+ + {#if line.media} + {#if line.media.type === AttachmentType.AUDIO} + {@const audioMimeType = line.media.mimeType ?? MimeTypeAudio.MP3_MPEG} +
+ +
+ {:else} + {line.media.name} + {/if} + {/if} + {/each} +
+ {/if} + {:else} +
+ No output +
+ {/if} + {/if} + {/snippet} +
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte similarity index 78% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte index f781cce49996..5e45d7c2c889 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockEditFile.svelte @@ -2,12 +2,17 @@ import { parseEditFileMeta, parseEditFileTitleMeta } from './parsers/edit-file'; import ToolCallBlock from './ToolCallBlock.svelte'; import { XCircle } from '@lucide/svelte'; - import { SyntaxHighlightedCode } from '$lib/components/app'; - import { MAX_HEIGHT_CODE_BLOCK, RESULT_STAT_SEPARATOR } from '$lib/constants'; - import { FileTypeText } from '$lib/enums'; - import { toolsStore } from '$lib/stores'; - import type { AgenticSection } from '$lib/types'; - import { abbreviateHome, computeLineDiff, formatJsonPretty, prefixFor } from '$lib/utils'; + import { SyntaxHighlightedCode } from '#lib/components/app/index.ts'; + import { MAX_HEIGHT_CODE_BLOCK, RESULT_STAT_SEPARATOR } from '#lib/constants/index.ts'; + import { FileTypeText } from '#lib/enums/index.ts'; + import { toolsStore } from '#lib/stores/index.ts'; + import type { AgenticSection } from '#lib/types/index.ts'; + import { + abbreviateHome, + computeLineDiff, + formatJsonPretty, + prefixFor + } from '#lib/utils/index.ts'; interface Props { section: AgenticSection; @@ -40,7 +45,7 @@ {#if editFileMeta?.errorMessage} - (failed) + (failed) {/if} @@ -49,16 +54,16 @@ {#snippet children(_meta, ctx)} {#if editFileBody?.errorMessage}
- + {editFileBody.errorMessage}
{:else if editFileBody?.edits.length} {#each editDiffs as diffLines, ei (ei)}
-
+
Edit {ei + 1} of {editFileBody.edits.length}
@@ -80,7 +85,7 @@
{/each} -
+
{#if editFileBody.resultMessage} {editFileBody.resultMessage}{editFileBody.editsApplied != null ? RESULT_STAT_SEPARATOR @@ -100,11 +105,13 @@ streaming={ctx.isCodeStreaming} /> {:else if ctx.isStreaming} -
+
Receiving arguments...
{:else} -
No edits
+
+ No edits +
{/if} {/snippet} @@ -114,13 +121,13 @@ overflow: auto; border-radius: 0.75rem; border-width: 1px; - border-color: color-mix(in oklch, var(--border) 30%, transparent); - background: var(--code-background); + border-color: color-mix(in oklch, var(--line-default) 30%, transparent); + background: var(--surface-code); box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); } :global(.dark) .diff-block { - border-color: color-mix(in oklch, var(--border) 20%, transparent); + border-color: color-mix(in oklch, var(--line-default) 20%, transparent); } /* Each row is a 4-column grid: old-line#, marker, new-line#, text. @@ -139,13 +146,13 @@ text-align: right; padding-right: 0.5rem; user-select: none; - color: color-mix(in oklch, var(--muted-foreground) 70%, transparent); + color: color-mix(in oklch, var(--fg-muted) 70%, transparent); font-variant-numeric: tabular-nums; } .diff-marker { text-align: center; - color: color-mix(in oklch, var(--muted-foreground) 70%, transparent); + color: color-mix(in oklch, var(--fg-muted) 70%, transparent); user-select: none; } diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte similarity index 82% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte index a67de857c6a7..06d417f7aa41 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte @@ -9,11 +9,14 @@ import { parseExecShellCommandMeta } from './parsers/exec-shell-command'; import ToolCallBlock from './ToolCallBlock.svelte'; import { AlertTriangle, Check, CircleStop, Loader2, XCircle } from '@lucide/svelte'; - import { CollapsibleTerminalBlock } from '$lib/components/app'; - import { SETTINGS_KEYS, TOOL_RUNTIME_SCROLL_AT_BOTTOM_THRESHOLD_PX } from '$lib/constants'; - import { AgenticSectionType, AttachmentType } from '$lib/enums'; - import { settingsStore, toolsStore } from '$lib/stores'; - import type { AgenticSection, DatabaseMessageExtra, ToolResultLine } from '$lib/types'; + import { CollapsibleTerminalBlock } from '#lib/components/app/index.ts'; + import { + SETTINGS_KEYS, + TOOL_RUNTIME_SCROLL_AT_BOTTOM_THRESHOLD_PX + } from '#lib/constants/index.ts'; + import { AgenticSectionType, AttachmentType } from '#lib/enums/index.ts'; + import { settingsStore, toolsStore } from '#lib/stores/index.ts'; + import type { AgenticSection, DatabaseMessageExtra, ToolResultLine } from '#lib/types/index.ts'; import { abbreviateHome, type ExecShellExitStatus, @@ -22,7 +25,7 @@ parseExecShellCommandError, parseExecShellCommandExitStatus, parseToolResultWithMedia - } from '$lib/utils'; + } from '#lib/utils/index.ts'; interface Props { section: AgenticSection; @@ -245,31 +248,30 @@ {#snippet children(_meta, ctx)} {#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)} -
- +
+ Executing command...
{:else if ctx.isInterrupted} -
+
Command interrupted before it returned output
{:else if execShellError} -
- +
+ {execShellError}
{:else if section.toolResult}
{#each outputLines as line, i (i)} -
{line.text}
+
{line.text}
{#if line.media?.type === AttachmentType.IMAGE} {#if execShellExitStatus.timedOut} - + timed out @@ -292,11 +294,11 @@ exit {execShellExitStatus.code} {:else if execShellExitStatus.code === 0} - + exit 0 {:else} - + exit {execShellExitStatus.code} {/if} @@ -314,13 +316,13 @@ .exec-wd { font-family: var(--font-mono); - color: var(--muted-foreground); + color: var(--fg-muted); margin-right: var(--exec-wd-margin); } .exec-prompt { font-family: var(--font-mono); - color: var(--muted-foreground); + color: var(--fg-muted); opacity: 0.55; margin-right: var(--exec-wd-margin); } @@ -331,7 +333,7 @@ height: 1.05em; margin-left: 0.15rem; vertical-align: text-bottom; - background: var(--foreground); + background: var(--fg-default); animation: exec-cursor-blink 1.1s steps(1) infinite; } @@ -362,34 +364,20 @@ line-height: 1; } + /* the status tokens, which follow the theme on their own */ .exit-badge.success { - background: color-mix(in oklch, var(--color-green-500, #22c55e) 14%, transparent); - color: var(--color-green-700, #15803d); - } - - :global(.dark) .exit-badge.success { - background: color-mix(in oklch, var(--color-green-400, #4ade80) 18%, transparent); - color: var(--color-green-300, #86efac); + background: var(--surface-success); + color: var(--fg-success); } .exit-badge.failure { - background: color-mix(in oklch, var(--color-red-500, #ef4444) 14%, transparent); - color: var(--color-red-700, #b91c1c); - } - - :global(.dark) .exit-badge.failure { - background: color-mix(in oklch, var(--color-red-400, #f87171) 18%, transparent); - color: var(--color-red-300, #fca5a5); + background: var(--surface-danger); + color: var(--fg-danger); } .exit-badge.warning { - background: color-mix(in oklch, var(--color-amber-500, #f59e0b) 14%, transparent); - color: var(--color-amber-700, #b45309); - } - - :global(.dark) .exit-badge.warning { - background: color-mix(in oklch, var(--color-amber-400, #fbbf24) 18%, transparent); - color: var(--color-amber-300, #fcd34d); + background: var(--surface-warning); + color: var(--fg-warning); } .exit-sep { diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte new file mode 100644 index 000000000000..67c5e15c348d --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte @@ -0,0 +1,72 @@ + + + + {#snippet titleSnippet()} + {#if fileGlobMeta} + {fileGlobMeta.include === '**' ? 'List files' : 'Search files'}  + + {#if fileGlobMeta.include !== '**'} + {fileGlobMeta.include} + {/if} + +  in  + + {abbreviateHome(fileGlobMeta.path, home)} + {/if} + {/snippet} + + {#snippet children(meta, ctx)} + {#if ctx.isPending} +
+ Searching... +
+ {:else if meta?.errorMessage} +
+ + + {meta.errorMessage} +
+ {:else if meta && meta.matches.length > 0} +
+ {#each meta.matches as match, i (i)} +
{match}
+ {/each} +
+ +
+ Total matches: {meta.totalMatches ?? meta.matches.length} +
+ {:else} +
No matches
+ +
+ Total matches: {meta?.totalMatches ?? 0} +
+ {/if} + {/snippet} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte new file mode 100644 index 000000000000..efcec2a3fced --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte @@ -0,0 +1,63 @@ + + +
+ + + {#if showSpinner} + Current time + + + {:else if dateMeta.errorMessage} + Current time  + + - {dateMeta.errorMessage} + {:else if dateMeta.dateString} + Current time is  + + {dateMeta.dateString} + {:else} + Current time + {/if} +
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte similarity index 75% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte index 225d9def90a4..3b68a2d85d05 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte @@ -1,9 +1,9 @@ + + + {#snippet titleSnippet()} + {#if grepMeta} + Search for  + + {grepMeta.pattern} + +  in  + + {abbreviateHome(grepMeta.path, home)} + {/if} + {/snippet} + + {#snippet children(meta, ctx)} + {#if ctx.isPending} +
+ Searching... +
+ {:else if meta?.errorMessage} +
+ + + {meta.errorMessage} +
+ {:else if meta && meta.matches.length > 0} +
+ {#each meta.matches as match, mi (mi)} +
+ {match.file} + + {#if meta.showLineNumbers && match.line != null} + :{match.line} + {/if} + + : + + {match.content} +
+ {/each} +
+ +
+ Total matches: {meta.totalMatches ?? meta.matches.length} + + {#if meta.showLineNumbers} +  (with line numbers) + {/if} +
+ {:else} +
No matches
+ +
+ Total matches: {meta?.totalMatches ?? 0} +
+ {/if} + {/snippet} +
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte similarity index 81% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte index 1134c8c0fecf..e8c424605b61 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte @@ -1,9 +1,9 @@ + + + {#snippet children(meta, ctx)} + {#if ctx.isPending} +
+ Running... +
+ {:else if meta?.errorMessage} +
+ + + {meta.errorMessage} +
+ +
+ +
+ {:else if meta} + + +
+ + + Console + + {#if meta.timeoutMs != null} + · timeout {meta.timeoutMs} ms + {/if} +
+ + {#if section.toolResult} +
+ +
+ {:else} +
+ No output +
+ {/if} + {/if} + {/snippet} +
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte similarity index 81% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte index 1f6f8df6876e..78fba40f98f8 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte @@ -1,18 +1,18 @@ + + + {#snippet titleSnippet()} + + Write file + + + + {abbreviateHome(writeFileMeta?.filePath ?? '', home)} + + + {#if writeFileMeta?.errorMessage} + (failed) + {/if} + + + {/snippet} + + {#snippet children(_meta, ctx)} + {#if writeFileBody?.errorMessage} +
+ + + {writeFileBody.errorMessage} +
+ {:else if writeFileBody?.content !== undefined} + + +
+ {#if writeFileBody.resultMessage} + {writeFileBody.resultMessage}{writeFileBody.bytesWritten != null + ? RESULT_STAT_SEPARATOR + : ''}{/if} + + {#if writeFileBody.bytesWritten != null} + {writeFileBody.bytesWritten} + bytes + {/if} +
+ {:else if section.toolArgs} + + + {:else if ctx.isStreaming} +
+ Receiving arguments... +
+ {:else} +
+ No content +
+ {/if} + {/snippet} +
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte similarity index 92% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte index 461ffe6f7663..cafb077e5366 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte @@ -10,12 +10,12 @@ // snippet - everything around them is this single source of truth. import { Loader2, Wrench } from '@lucide/svelte'; - import { CollapsibleContentBlock } from '$lib/components/app'; - import { ICON_CLASS_DEFAULT, ICON_CLASS_SPIN } from '$lib/constants'; - import { AgenticSectionType } from '$lib/enums'; - import { mcpStore } from '$lib/stores'; - import type { AgenticSection, ToolUiEntry } from '$lib/types'; - import { getToolUi } from '$lib/utils'; + import { CollapsibleContentBlock } from '#lib/components/app/index.ts'; + import { ICON_CLASS_DEFAULT, ICON_CLASS_SPIN } from '#lib/constants/index.ts'; + import { AgenticSectionType } from '#lib/enums/index.ts'; + import { mcpStore } from '#lib/stores/index.ts'; + import type { AgenticSection, ToolUiEntry } from '#lib/types/index.ts'; + import { getToolUi } from '#lib/utils/index.ts'; import type { Component, Snippet } from 'svelte'; type ToolCallBlockMetaWithError = TMeta & { errorMessage?: string }; diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts similarity index 94% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts index 039b2634a4dc..e11a1fa4d336 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts @@ -8,10 +8,10 @@ import { FILE_PATH_SEPARATOR_REGEX, TOOL_ARG_PATH_KEYS, TOOL_ARG_STRING_FIELD_PATTERN_TEMPLATE -} from '$lib/constants'; -import { BuiltInTool } from '$lib/enums'; -import type { AgenticSection } from '$lib/types/agentic'; -import { parsePartialJsonArgs } from '$lib/utils/parse-partial-json-args'; +} from '#lib/constants/index.ts'; +import { BuiltInTool } from '#lib/enums/index.ts'; +import type { AgenticSection } from '#lib/types/agentic.js'; +import { parsePartialJsonArgs } from '#lib/utils/parse-partial-json-args.ts'; /** * Strict (final-state) JSON parser for a tool-args blob. Mirrors the diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts similarity index 91% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts index 2bbb6bab52eb..006ea186f405 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts @@ -10,10 +10,15 @@ import { fileNameFromPath, parseToolArgs } from './_shared'; -import { TOOL_ARG_PATH_KEYS } from '$lib/constants'; -import { BuiltInTool } from '$lib/enums'; -import type { AgenticSection, EditFileEdit, EditFileMeta, EditFileTitleMeta } from '$lib/types'; -import { tryParseToolResultObject } from '$lib/utils'; +import { TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; +import { BuiltInTool } from '#lib/enums/index.ts'; +import type { + AgenticSection, + EditFileEdit, + EditFileMeta, + EditFileTitleMeta +} from '#lib/types/index.ts'; +import { tryParseToolResultObject } from '#lib/utils/index.ts'; export function parseEditFileMeta(section: AgenticSection): EditFileMeta | null { const args = parseToolArgs(BuiltInTool.SERVER_EDIT_FILE, section, { partial: true }); diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/exec-shell-command.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/exec-shell-command.ts similarity index 90% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/exec-shell-command.ts rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/exec-shell-command.ts index 2371c11e5a74..b171bab38d7b 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/exec-shell-command.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/exec-shell-command.ts @@ -8,8 +8,8 @@ // the error / exit status elide from call-section to result-section. import { parseToolArgs } from './_shared'; -import { BuiltInTool } from '$lib/enums'; -import type { AgenticSection } from '$lib/types'; +import { BuiltInTool } from '#lib/enums/index.ts'; +import type { AgenticSection } from '#lib/types/index.ts'; export type ExecShellCommandMeta = { command: string; diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/file-glob-search.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/file-glob-search.ts similarity index 91% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/file-glob-search.ts rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/file-glob-search.ts index 237afa599d21..cc5e391fc450 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/file-glob-search.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/file-glob-search.ts @@ -5,9 +5,9 @@ // emit unparseable output. import { parseToolArgs } from './_shared'; -import { BuiltInTool } from '$lib/enums'; -import type { AgenticSection } from '$lib/types'; -import { splitSearchSummaryList } from '$lib/utils'; +import { BuiltInTool } from '#lib/enums/index.ts'; +import type { AgenticSection } from '#lib/types/index.ts'; +import { splitSearchSummaryList } from '#lib/utils/index.ts'; export type FileGlobSearchMeta = { path: string; diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/grep-search.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/grep-search.ts similarity index 95% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/grep-search.ts rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/grep-search.ts index 90889ff2765e..a9efa8327f25 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/grep-search.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/grep-search.ts @@ -6,9 +6,9 @@ // surfaced. import { parseToolArgs } from './_shared'; -import { BuiltInTool } from '$lib/enums'; -import type { AgenticSection } from '$lib/types'; -import { splitSearchSummaryList } from '$lib/utils'; +import { BuiltInTool } from '#lib/enums/index.ts'; +import type { AgenticSection } from '#lib/types/index.ts'; +import { splitSearchSummaryList } from '#lib/utils/index.ts'; export type GrepSearchMatch = { file: string; diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/read-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/read-file.ts similarity index 88% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/read-file.ts rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/read-file.ts index af0f3d9252db..54465470145b 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/read-file.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/read-file.ts @@ -4,10 +4,10 @@ // can render incrementally as the file path streams in. import { parseToolArgs } from './_shared'; -import { CODE_BLOCK, FILE_PATH_SEPARATOR_REGEX } from '$lib/constants'; -import { BuiltInTool } from '$lib/enums'; -import type { AgenticSection } from '$lib/types'; -import { getFileTypeByExtension } from '$lib/utils'; +import { CODE_BLOCK, FILE_PATH_SEPARATOR_REGEX } from '#lib/constants/index.ts'; +import { BuiltInTool } from '#lib/enums/index.ts'; +import type { AgenticSection } from '#lib/types/index.ts'; +import { getFileTypeByExtension } from '#lib/utils/index.ts'; export type ReadFileMeta = { fileName: string; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/read-media.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/read-media.ts new file mode 100644 index 000000000000..aa2a03be39b8 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/read-media.ts @@ -0,0 +1,56 @@ +import { FILE_PATH_SEPARATOR_REGEX, NEWLINE } from '#lib/constants/index.ts'; +import { + PREFIX_FILE, + PREFIX_MIME, + PREFIX_SIZE, + READ_MEDIA_SIZE_REGEX +} from '#lib/constants/read-media.ts'; +import type { AgenticSection } from '#lib/types/index.ts'; + +export interface ReadMediaMeta { + fileName: string; + path: string; + sizeBytes?: number; + mimeType?: string; +} + +/** + * Parse read_media tool result to extract metadata. + * Expected format (after extractBase64Attachments processing): + * File: /path/to/file.png + * Size: 12345 bytes + * MIME: image/png + * [Attachment saved: mcp-attachment-xxx.png] + * + * The data URI line is replaced by the attachment marker by + * agenticStore.extractBase64Attachments before storage. + */ +export function parseReadMediaMeta(section: AgenticSection): ReadMediaMeta | null { + if (!section.toolResult) return null; + + const lines = section.toolResult.split(NEWLINE); + + let fileName = ''; + let path = ''; + let sizeBytes: number | undefined; + let mimeType: string | undefined; + + for (const line of lines) { + const trimmed = line.trim(); + + if (trimmed.startsWith(PREFIX_FILE)) { + path = trimmed.slice(PREFIX_FILE.length).trim(); + fileName = path.split(FILE_PATH_SEPARATOR_REGEX).pop() ?? path; + } else if (trimmed.startsWith(PREFIX_SIZE)) { + const match = trimmed.match(READ_MEDIA_SIZE_REGEX); + + if (match) sizeBytes = Number(match[1]); + } else if (trimmed.startsWith(PREFIX_MIME)) { + mimeType = trimmed.slice(PREFIX_MIME.length).trim(); + } + } + + if (!path) return null; + + return { fileName, mimeType, path, sizeBytes }; +} diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/run-javascript.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/run-javascript.ts similarity index 92% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/run-javascript.ts rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/run-javascript.ts index bd97cd2feb6d..33609efd3601 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/run-javascript.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/run-javascript.ts @@ -6,9 +6,9 @@ // are handled. import { parseToolArgs } from './_shared'; -import { JSON_ARRAY_OPEN, JSON_OBJECT_OPEN } from '$lib/constants'; -import { BuiltInTool } from '$lib/enums'; -import type { AgenticSection } from '$lib/types'; +import { JSON_ARRAY_OPEN, JSON_OBJECT_OPEN } from '#lib/constants/index.ts'; +import { BuiltInTool } from '#lib/enums/index.ts'; +import type { AgenticSection } from '#lib/types/index.ts'; export type RunJavascriptMeta = { code: string; diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts similarity index 94% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts index e8917845a739..3a88fb5f9f21 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts @@ -10,10 +10,10 @@ import { fileNameFromPath, parseToolArgs } from './_shared'; -import { CODE_BLOCK, TOOL_ARG_PATH_KEYS } from '$lib/constants'; -import { BuiltInTool } from '$lib/enums'; -import type { AgenticSection, WriteFileMeta, WriteFileTitleMeta } from '$lib/types'; -import { getFileTypeByExtension, tryParseToolResultObject } from '$lib/utils'; +import { CODE_BLOCK, TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; +import { BuiltInTool } from '#lib/enums/index.ts'; +import type { AgenticSection, WriteFileMeta, WriteFileTitleMeta } from '#lib/types/index.ts'; +import { getFileTypeByExtension, tryParseToolResultObject } from '#lib/utils/index.ts'; // Plain text when the call carries no path, or one with no known extension. function languageForPath(filePath: string | undefined): string { diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte similarity index 87% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte index bb0f10f3dcd5..1101287c767a 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte @@ -5,11 +5,11 @@ ChatMessageEditForm, ChatMessageStatistics, ChatMessageUserBubble - } from '$lib/components/app/chat'; - import { getChatMessageEditContext } from '$lib/contexts'; - import { ChatMessageStatisticsMode, MessageRole } from '$lib/enums'; - import { useProcessingState } from '$lib/hooks/use-processing-state.svelte'; - import { chatStore, settingsStore } from '$lib/stores'; + } from '#lib/components/app/chat/index.ts'; + import { getChatMessageEditContext } from '#lib/contexts/index.ts'; + import { ChatMessageStatisticsMode, MessageRole } from '#lib/enums/index.ts'; + import { useProcessingState } from '#lib/hooks/use-processing-state.svelte.ts'; + import { chatStore, settingsStore } from '#lib/stores/index.ts'; interface Props { class?: string; @@ -85,7 +85,7 @@
+
{/if} diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte similarity index 79% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte index 569737ac3b7b..c4f823886354 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte @@ -1,8 +1,8 @@ {#if attachments && attachments.length > 0} -
+
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte similarity index 87% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte index 40b299a83e80..73ef9091e361 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserPending.svelte @@ -1,7 +1,11 @@ + +
+
+ + + + {@render message()} + +
+ +
+ {@render actions()} +
+
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte similarity index 92% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte index f79d2604b1b1..68be708ed9cd 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardContinueRequest.svelte @@ -1,7 +1,7 @@ + + + {#snippet message()} + Allow use of {toolName}{#if serverLabel} +  from {serverLabel}{/if}? + {/snippet} + + {#snippet actions()} + + + + + + + + + + + + + onDecision(ToolPermissionDecision.ALWAYS)}> + Always allow
{toolName}
+ tool +
+ + {#if serverLabel} + onDecision(ToolPermissionDecision.ALWAYS_SERVER)}> + Always allow all tools from {serverLabel} + + {:else} + {@const source = toolsStore.getToolSource(toolName)} + {@const providerName = + source === ToolSource.SERVER + ? TOOL_SERVER_LABELS[ToolSource.SERVER] + : source === ToolSource.CUSTOM + ? TOOL_SERVER_LABELS[ToolSource.CUSTOM] + : 'MCP Tools'} + onDecision(ToolPermissionDecision.ALWAYS_SERVER)}> + Approve all tools from {providerName} + + {/if} +
+
+ + + {/snippet} +
diff --git a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte similarity index 90% rename from tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte index 1e6348c32821..a300da7363b8 100644 --- a/tools/ui/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte @@ -1,16 +1,16 @@ + + diff --git a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte similarity index 90% rename from tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte index d8ff0d2eee8c..5dc6107a0dde 100644 --- a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDialogsAndAlerts.svelte @@ -4,8 +4,8 @@ DialogConversationDelete, DialogEmptyFileAlert, DialogFileUploadError - } from '$lib/components/app'; - import { ErrorDialogType } from '$lib/enums'; + } from '#lib/components/app/index.ts'; + import { ErrorDialogType } from '#lib/enums/index.ts'; let { activeErrorDialog, diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDragOverlay.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDragOverlay.svelte new file mode 100644 index 000000000000..4e8a944a650d --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenDragOverlay.svelte @@ -0,0 +1,17 @@ + + +
+
+ + +

Attach a file

+ +

Drop your files here to upload

+
+
diff --git a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte similarity index 86% rename from tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte index fe382bd071f1..21bd62201f34 100644 --- a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte @@ -1,11 +1,11 @@ + +
- import { CHAT_FORM_RESIZE_MS, CHAT_GREETING_ENTER_DELAY_MS } from '$lib/constants'; - import { serverStore } from '$lib/stores'; + import { CHAT_FORM_RESIZE_MS, CHAT_GREETING_ENTER_DELAY_MS } from '#lib/constants/index.ts'; + import { serverStore } from '#lib/stores/index.ts'; interface Props { /** Transparent but still in place, e.g. behind the expanded chat form. */ @@ -32,7 +32,7 @@ }); let enterClass = $derived([ - 'transition-opacity duration-300 ease-[cubic-bezier(0.23,1,0.32,1)]', + 'transition-opacity duration-300 ease-out-quint', !hasEntered && !instant && 'opacity-0' ]); @@ -60,9 +60,9 @@ ]} >
-

Hello there

+

Hello there

-

+

{serverStore.props?.modalities?.audio ? 'Record audio, type a message ' : 'Type a message'} or upload files to get started

diff --git a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenMobileHeader.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenMobileHeader.svelte similarity index 76% rename from tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenMobileHeader.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenMobileHeader.svelte index 39f02504f9da..b3c2b83419d1 100644 --- a/tools/ui/src/lib/components/app/chat/ChatScreen/ChatScreenMobileHeader.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenMobileHeader.svelte @@ -1,7 +1,7 @@ + +{#if hasError || isLoadingModel} +
+ + {#if isLoadingModel} + + {:else} + + {/if} + + + {isLoadingModel ? 'Loading model' : 'Server unavailable'} + + {#if !isLoadingModel} + + {/if} + + + {#if !isLoadingModel} + {serverStore.error} + {/if} + +
+{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenStreamResumeStatus.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenStreamResumeStatus.svelte new file mode 100644 index 000000000000..e5887f626fc4 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenStreamResumeStatus.svelte @@ -0,0 +1,19 @@ + + +{#if state === StreamConnectionState.RESUMING} +
+ + + Reconnecting to the stream... +
+{/if} diff --git a/tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte similarity index 87% rename from tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte index 515bf4f78cf7..60f185e1b62f 100644 --- a/tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte @@ -2,8 +2,7 @@ import ChatTabsItem from './ChatTabsItem.svelte'; import ChatTabsNewChatButton from './ChatTabsNewChatButton.svelte'; import { ArrowRightToLine, ListX, Square, SquarePen, X } from '@lucide/svelte'; - import { page } from '$app/state'; - import { ContextMenuActions, ScrollCarousel } from '$lib/components/app'; + import { ContextMenuActions, ScrollCarousel } from '#lib/components/app/index.ts'; import { CHAT_TABS_MAX_WIDTH, NEW_CHAT_LABEL, @@ -11,11 +10,12 @@ SHORTCUT_CLOSE_TAB, UI_DATA_ATTRS, UNNAMED_CHAT_LABEL - } from '$lib/constants'; - import { useScrollCarousel } from '$lib/hooks/use-scroll-carousel.svelte'; - import { chatStore, conversationsStore, tabsStore, uiStore } from '$lib/stores'; - import type { MenuAction } from '$lib/types'; - import { resolveTabView } from '$lib/utils'; + } from '#lib/constants/index.ts'; + import { useScrollCarousel } from '#lib/hooks/use-scroll-carousel.svelte.ts'; + import { chatStore, conversationsStore, tabsStore, uiStore } from '#lib/stores/index.ts'; + import type { MenuAction } from '#lib/types/index.ts'; + import { resolveTabView } from '#lib/utils/index.ts'; + import { page } from '$app/state'; import { tick } from 'svelte'; const carousel = useScrollCarousel(); @@ -164,13 +164,13 @@
diff --git a/tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte similarity index 88% rename from tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte index d161f0f1d770..c01af20d6f4b 100644 --- a/tools/ui/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte @@ -1,7 +1,7 @@ + + + + +
+
+
+
+ + zoomBy(DIAGRAM_ZOOM_FACTOR)} + onZoomOut={() => zoomBy(1 / DIAGRAM_ZOOM_FACTOR)} + scale={view.scale} + {svgHtml} + /> +
diff --git a/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte b/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte new file mode 100644 index 000000000000..3c18771c826c --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte @@ -0,0 +1,82 @@ + + +
+
+ + + {Math.round(scale * 100)}% + + + +
+ + + +
+ + +
+
diff --git a/ui/apps/chat/src/lib/components/app/content/index.ts b/ui/apps/chat/src/lib/components/app/content/index.ts new file mode 100644 index 000000000000..62ad6978098f --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/content/index.ts @@ -0,0 +1,144 @@ +/** + * + * CONTENT RENDERING + * + * Components for rendering rich content: markdown, code, and previews. + * + */ + +/** + * **MarkdownContent** - Rich markdown renderer + * + * Renders markdown content with syntax highlighting, LaTeX math, + * tables, links, and code blocks. Optimized for streaming with + * incremental block-based rendering. + * + * **Features:** + * - GFM (GitHub Flavored Markdown): tables, task lists, strikethrough + * - LaTeX math via KaTeX (`$inline$` and `$$block$$`) + * - Syntax highlighting (highlight.js) with language detection + * - Code copy buttons with click feedback + * - External links open in new tab with security attrs + * - Image attachment resolution from message extras + * - Dark/light theme support (auto-switching) + * - Streaming-optimized incremental rendering + * - Code preview dialog for large blocks + * + * @example + * ```svelte + * + * ``` + */ +export { default as MarkdownContent } from './MarkdownContent/MarkdownContent.svelte'; + +/** + * **MarkdownEditor** - Live-preview markdown editor (CodeMirror) + * + * Edits markdown source in place: every block the cursor is not in renders + * exactly like MarkdownContent, and the block being edited shows its raw text + * in the same typography. The document is never rewritten, so the value stays + * byte-exact. Used by the chat form input. + * + * @example + * ```svelte + * (text = v)} placeholder="Write..." /> + * ``` + */ +export { default as MarkdownEditor } from './MarkdownEditor/MarkdownEditor.svelte'; + +/** + * **MentionText** - Plain text with file mention badges + * + * Renders a message verbatim, turning only `[name](file://path)` links + * into the same badge chips the markdown path draws. Nothing else is + * interpreted, so pasted code keeps its `#` comments and underscores. + * + * @example + * ```svelte + * + * ``` + */ +export { default as MentionText } from './MentionText.svelte'; + +/** + * **SyntaxHighlightedCode** - Code syntax highlighting + * + * Renders code with syntax highlighting using highlight.js. + * Supports theme switching and scrollable containers. + * + * **Features:** + * - Auto language detection with fallback + * - Dark/light theme auto-switching + * - Scrollable container with configurable max dimensions + * - Monospace font styling + * - Preserves whitespace and formatting + * + * @example + * ```svelte + * + * ``` + */ +export { SyntaxHighlightedCode } from '@ggml-org/llama-ui/app/content'; + +/** + * **CollapsibleContentBlock** - Expandable content card + * + * Reusable collapsible card with header, icon, and auto-scroll. + * Used for tool calls and reasoning blocks in chat messages. + * + * **Features:** + * - Collapsible content with smooth animation + * - Custom icon and title display + * - Optional subtitle/status text + * - Auto-scroll during streaming (pauses on user scroll) + * - Configurable max height with overflow scroll + * + * @example + * ```svelte + * + * {reasoningContent} + * + * ``` + */ +export { default as CollapsibleContentBlock } from './CollapsibleContentBlock.svelte'; + +/** + * **CollapsibleTerminalBlock** - Expandable content card with a terminal-style frame + * + * Same shape as CollapsibleContentBlock, but with a `code-background` + * fill, subtle border, and tightened padding suited for shell command + * output and similar dense / monospace content. + * + * @example + * ```svelte + * + *
{output}
+ *
+ * ``` + */ +export { default as CollapsibleTerminalBlock } from './CollapsibleTerminalBlock.svelte'; + +/** + * **MermaidPreview** - Pan and zoom viewer for a diagram's svg + * + * Shows a diagram (a Pele-drawn Mermaid block or an svg block) fitted to its box, with + * zoom, pan and download controls. + * + * **Features:** + * - Fits the diagram until the user pans or zooms, also as the box resizes + * - Wheel and trackpad pinch zoom around the pointer; zoom buttons and +/- keys zoom + * around the middle of the box, wherever the diagram has been panned to + * - Drag to pan, two-finger pinch on touch, double-click to zoom in, arrow keys to pan + * - Reset view (0) fits the diagram again + * - Download as SVG with the theme colors written in + * + * @example + * ```svelte + * + * ``` + */ +export { default as MermaidPreview } from './MermaidPreview.svelte'; diff --git a/tools/ui/src/lib/components/app/dialogs/DialogChatAttachmentsPreview.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogChatAttachmentsPreview.svelte similarity index 86% rename from tools/ui/src/lib/components/app/dialogs/DialogChatAttachmentsPreview.svelte rename to ui/apps/chat/src/lib/components/app/dialogs/DialogChatAttachmentsPreview.svelte index bac04d8174a4..119a9867e306 100644 --- a/tools/ui/src/lib/components/app/dialogs/DialogChatAttachmentsPreview.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogChatAttachmentsPreview.svelte @@ -1,8 +1,8 @@ + + + deviceStore.isMobile && event.preventDefault()} + > + + + + + MCP Servers + + + + + + diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogMermaidPreview.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogMermaidPreview.svelte new file mode 100644 index 000000000000..fedd84600b31 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogMermaidPreview.svelte @@ -0,0 +1,22 @@ + + + + + + + + diff --git a/tools/ui/src/lib/components/app/dialogs/DialogModelNotAvailable.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogModelNotAvailable.svelte similarity index 81% rename from tools/ui/src/lib/components/app/dialogs/DialogModelNotAvailable.svelte rename to ui/apps/chat/src/lib/components/app/dialogs/DialogModelNotAvailable.svelte index 5bbef292396d..5a7a6ba4d40a 100644 --- a/tools/ui/src/lib/components/app/dialogs/DialogModelNotAvailable.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogModelNotAvailable.svelte @@ -1,9 +1,9 @@ + +{#snippet hint(label: string, keys: (string | Component)[])} + + {label} + + + {#each keys as Key, index (index)} + + {#if typeof Key === 'string'} + {Key} + {:else} + + {/if} + + {/each} + + +{/snippet} + +{#snippet search()} +
+
+ 0 ? `search-result-${activeIndex}` : undefined} + aria-controls="search-results" + aria-expanded="true" + autocomplete="off" + class="h-10 min-w-0 flex-1 border-0 bg-transparent px-1 text-title font-normal outline-none placeholder:text-muted-foreground focus:outline-none focus-visible:ring-0" + oninput={() => (highlighted = 0)} + onkeydown={handleKeydown} + placeholder="Search" + role="combobox" + spellcheck={false} + /> + + handleOpenChange(false)} + /> +
+
+ +
+ {#each sections as section, sectionIndex (section.title)} + {@const offset = sections + .slice(0, sectionIndex) + .reduce((total, previous) => total + previous.entries.length, 0)} + +
+

+ {section.title} + + {#if section.loading} + + {/if} +

+ + {#each section.entries as entry, entryIndex (entry.id)} + {@const index = offset + entryIndex} + {@const isActive = index === activeIndex && !deviceStore.isMobile} + + + + {/each} +
+ {:else} +

{emptyMessage}

+ {/each} +
+ +
+ {@render hint('Close', ['Esc'])} + + {@render hint('Navigate', [ArrowUp, ArrowDown])} + + {@render hint('Open', [CornerDownLeft])} +
+{/snippet} + + + + { + event.preventDefault(); + inputRef?.focus(); + }} + > + Search + + {@render search()} + + diff --git a/tools/ui/src/lib/components/app/dialogs/DialogSettingsChat.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogSettingsChat.svelte similarity index 82% rename from tools/ui/src/lib/components/app/dialogs/DialogSettingsChat.svelte rename to ui/apps/chat/src/lib/components/app/dialogs/DialogSettingsChat.svelte index 82749a4e79b0..55092b90f594 100644 --- a/tools/ui/src/lib/components/app/dialogs/DialogSettingsChat.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSettingsChat.svelte @@ -1,9 +1,9 @@ + +{#if capabilities} + {#if capabilities.server.tools} + + + + Tools + + {/if} + + {#if capabilities.server.resources} + { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + onBrowseResources?.(); + } + }} + role="button" + tabindex={0} + variant="outline" + > + + + Resources + + + + {/if} + + {#if capabilities.server.prompts} + + + + Prompts + + {/if} + + {#if capabilities.server.logging} + + + + Logging + + {/if} + + {#if capabilities.server.completions} + + + + Completions + + {/if} + + {#if capabilities.server.tasks} + + + + Tasks + + {/if} +{/if} diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte new file mode 100644 index 000000000000..87efebf7a2e5 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte @@ -0,0 +1,83 @@ + + +{#if logs.length > 0} + +
+ + {#if isExpanded} + + {:else} + + {/if} + + Connection Log ({logs.length}) + + {#if connectionTimeMs !== undefined} + · Connected in {connectionTimeMs}ms + {/if} + +
+ + +
+ {#each logs as log (log.timestamp.getTime() + log.message)} + {@const IconComponent = getMcpLogLevelIcon(log.level)} + +
+ + {formatTime(log.timestamp)} + + + + + {log.message} +
+ + {#if log.details !== undefined} +
+ + details + + +
+{formatLogDetails(log.details)}
+
+ {/if} + {/each} +
+
+
+{/if} diff --git a/tools/ui/src/lib/components/app/mcp/McpLogo.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpLogo.svelte similarity index 100% rename from tools/ui/src/lib/components/app/mcp/McpLogo.svelte rename to ui/apps/chat/src/lib/components/app/mcp/McpLogo.svelte diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpResourcePreview.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpResourcePreview.svelte new file mode 100644 index 000000000000..abea49759d21 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/mcp/McpResourcePreview.svelte @@ -0,0 +1,182 @@ + + +
+ {#if !resource} +
+ + + Select a resource to preview +
+ {:else} +
+
+

{resource.title || resource.name}

+ +

{resource.uri}

+ + {#if resource.description} +

{resource.description}

+ {/if} +
+ +
+ + + +
+
+ +
+ {#if isLoading} +
+ +
+ {:else if error} +
+ + + {error} +
+ {:else if content} + {@const textContent = getResourceTextContent(content)} + {@const blobContent = getResourceBlobContent(content)} + + {#if textContent} +
{textContent}
+ {/if} + + {#each blobContent as blob (blob.uri)} + {#if isImageMimeType(blob.mimeType ?? MimeTypeApplication.OCTET_STREAM)} + Resource content + {:else} +
+ + + Binary content ({blob.mimeType || 'unknown type'}) +
+ {/if} + {/each} + + {#if !textContent && blobContent.length === 0} +
+ No content available +
+ {/if} + {/if} +
+ + {#if resource.mimeType || resource.annotations} +
+ {#if resource.mimeType} + {resource.mimeType} + {/if} + + {#if resource.annotations?.priority !== undefined} + + Priority: {resource.annotations.priority} + + {/if} + + + Server: {resource.serverName} + +
+ {/if} + {/if} +
diff --git a/tools/ui/src/lib/components/app/mcp/McpResourceTemplateForm.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpResourceTemplateForm.svelte similarity index 87% rename from tools/ui/src/lib/components/app/mcp/McpResourceTemplateForm.svelte rename to ui/apps/chat/src/lib/components/app/mcp/McpResourceTemplateForm.svelte index d471ae3381b0..a6800e442370 100644 --- a/tools/ui/src/lib/components/app/mcp/McpResourceTemplateForm.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpResourceTemplateForm.svelte @@ -1,16 +1,16 @@ -
+
{#if isLoading} Loading resources... {:else} diff --git a/tools/ui/src/lib/components/app/mcp/McpResourcesBrowser/McpResourcesBrowserHeader.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpResourcesBrowser/McpResourcesBrowserHeader.svelte similarity index 75% rename from tools/ui/src/lib/components/app/mcp/McpResourcesBrowser/McpResourcesBrowserHeader.svelte rename to ui/apps/chat/src/lib/components/app/mcp/McpResourcesBrowser/McpResourcesBrowserHeader.svelte index 37f91c226c2a..0945f3b47975 100644 --- a/tools/ui/src/lib/components/app/mcp/McpResourcesBrowser/McpResourcesBrowserHeader.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpResourcesBrowser/McpResourcesBrowserHeader.svelte @@ -1,8 +1,8 @@ + +
+ + + + + +
diff --git a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte similarity index 81% rename from tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte rename to ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte index da0ce1ffe75f..729590368f67 100644 --- a/tools/ui/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardCompact.svelte @@ -1,6 +1,6 @@ + +
+
+
+
+ +
+ + {#if capabilities || transportType} +
+ {#if transportType} + {@const TransportIcon = MCP_TRANSPORT_ICONS[transportType]} + + {#if TransportIcon} + + {/if} + + {MCP_TRANSPORT_LABELS[transportType] || transportType} + + {/if} + + {#if capabilities} + + {/if} +
+ {/if} +
+ +
+ +
+
+
diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte new file mode 100644 index 000000000000..bc3631ddf28e --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte @@ -0,0 +1,47 @@ + + + + + {#if isExpanded} + + {:else} + + {/if} + + {toolsCount} tools available · Show details + + + +
+ {#each tools as tool (tool.name)} +
+ {tool.name} + + {#if tool.description} +

{tool.description}

+ {/if} +
+ {/each} +
+
+
diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpServerCardSkeleton.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerCardSkeleton.svelte new file mode 100644 index 000000000000..1554dd4f2065 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerCardSkeleton.svelte @@ -0,0 +1,42 @@ + + + +
+
+ + + + + +
+ + +
+ +
+ + + + + +
+ +
+ + + +
+ + + +
+ + + + + +
+
diff --git a/tools/ui/src/lib/components/app/mcp/McpServerForm.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerForm.svelte similarity index 87% rename from tools/ui/src/lib/components/app/mcp/McpServerForm.svelte rename to ui/apps/chat/src/lib/components/app/mcp/McpServerForm.svelte index f9f07ad63d9e..97b3db3e86c3 100644 --- a/tools/ui/src/lib/components/app/mcp/McpServerForm.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerForm.svelte @@ -1,12 +1,12 @@ + + + {#if faviconUrl} + + {:else} + + {/if} + + + + {#if showVersion && serverInfo?.version} + + + + {/if} + + {#if showWebsite && safeWebsiteUrl} + e.stopPropagation()} + rel="noopener noreferrer" + target="_blank" + > + + + {/if} + diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte new file mode 100644 index 000000000000..220e6c6d954f --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte @@ -0,0 +1,35 @@ + + +{#if instructions} + + + {#if isExpanded} + + {:else} + + {/if} + + Server instructions + + + +

+ {instructions} +

+
+
+{/if} diff --git a/tools/ui/src/lib/components/app/mcp/index.ts b/ui/apps/chat/src/lib/components/app/mcp/index.ts similarity index 100% rename from tools/ui/src/lib/components/app/mcp/index.ts rename to ui/apps/chat/src/lib/components/app/mcp/index.ts diff --git a/tools/ui/src/lib/components/app/misc/CodeBlockActions.svelte b/ui/apps/chat/src/lib/components/app/misc/CodeBlockActions.svelte similarity index 83% rename from tools/ui/src/lib/components/app/misc/CodeBlockActions.svelte rename to ui/apps/chat/src/lib/components/app/misc/CodeBlockActions.svelte index f1865b886cbd..0f87bbdf9fdb 100644 --- a/tools/ui/src/lib/components/app/misc/CodeBlockActions.svelte +++ b/ui/apps/chat/src/lib/components/app/misc/CodeBlockActions.svelte @@ -1,7 +1,7 @@ + +{#if isTruncated && showTooltip} + + + + + {text} + + + + +

{text}

+
+
+{:else} + + {text} + +{/if} diff --git a/ui/apps/chat/src/lib/components/app/misc/index.ts b/ui/apps/chat/src/lib/components/app/misc/index.ts new file mode 100644 index 000000000000..8bb162917661 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/misc/index.ts @@ -0,0 +1,73 @@ +/** + * + * MISC + * + * Miscellaneous utility components. + * + */ + +/** + * **ConversationSelection** - Multi-select conversation picker + * + * List of conversations with checkboxes for multi-selection. + * Used in import/export dialogs for selecting conversations. + * + * **Features:** + * - Search/filter conversations by name + * - Select all / deselect all controls + * - Shift-click for range selection + * - Message count display per conversation + * - Mode-specific UI (export vs import) + */ +export { default as ConversationSelection } from './ConversationSelection.svelte'; + +/** + * **TruncatedText** - Text with ellipsis and tooltip + * + * Displays text with automatic truncation and full content in tooltip. + * Useful for long names or paths in constrained spaces. + */ +export { default as TruncatedText } from './TruncatedText.svelte'; + +/** + * **KeyboardShortcutInfo** - Keyboard shortcut hint display + * + * Displays keyboard shortcut hints (e.g., "⌘ + Enter"). + * Supports special keys like shift, cmd, and custom text. + */ +export { default as KeyboardShortcutInfo } from './KeyboardShortcutInfo.svelte'; + +/** + * **ScrollCarousel** - Feature/carousel with center-aligned overflow controls + * + * Horizontal scrollable container with arrows that center the focused item. + */ +export { default as ScrollCarousel } from './ScrollCarousel.svelte'; + +/** + * **CodeBlockActions** - Actions bar for code blocks (copy, preview) + * + * Displays copy-to-clipboard and preview buttons for code blocks. + * Preview button is shown only for HTML code blocks. + */ +export { default as CodeBlockActions } from './CodeBlockActions.svelte'; + +/** + * **Logo** - Application brand mark + * + * Inline SVG of the application logo. Accepts styling via the standard + * `class` and `style` props and inherits color via `currentColor`. + */ +export { Logo } from '@ggml-org/llama-ui/app/misc'; + +/** Two-line menu glyph for the phone sidebar toggle, its lower line two thirds as long. */ +export { default as MenuIcon } from './MenuIcon.svelte'; + +/** Section with a trigger that expands in place. */ +export { default as CollapsibleSection } from './CollapsibleSection.svelte'; +export { + default as GroupedList, + type GroupedListGroup, + GroupedListUnit +} from './GroupedList.svelte'; +export { default as CollapsibleRegion } from './CollapsibleRegion.svelte'; diff --git a/tools/ui/src/lib/components/app/models/ModelAvatar.svelte b/ui/apps/chat/src/lib/components/app/models/ModelAvatar.svelte similarity index 88% rename from tools/ui/src/lib/components/app/models/ModelAvatar.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelAvatar.svelte index 5e1234a27267..eb20342ce3cd 100644 --- a/tools/ui/src/lib/components/app/models/ModelAvatar.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelAvatar.svelte @@ -1,10 +1,10 @@ + + (isNearViewport = true))} class={className}> + + diff --git a/tools/ui/src/lib/components/app/models/ModelContext.svelte b/ui/apps/chat/src/lib/components/app/models/ModelContext.svelte similarity index 76% rename from tools/ui/src/lib/components/app/models/ModelContext.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelContext.svelte index 6d5395fc4497..f954d1014f51 100644 --- a/tools/ui/src/lib/components/app/models/ModelContext.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelContext.svelte @@ -1,9 +1,9 @@ (isNearViewport = true)} - class={['text-sm text-muted-foreground', className]} + {@attach nearViewport(() => (isNearViewport = true))} + class={['text-body-sm text-muted-foreground', className]} > {formatContextLength(values)} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelDraftSubline.svelte b/ui/apps/chat/src/lib/components/app/models/ModelDraftSubline.svelte new file mode 100644 index 000000000000..988bdf72d5ec --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelDraftSubline.svelte @@ -0,0 +1,53 @@ + + + +
+ + + Draft model + + {kind} + + {#if quant} + {quant} + {/if} + + {#if state === ModelRowDownloadState.DOWNLOADED} + + {:else} + + {#if percent !== null} + {percent}% + {:else if state === ModelRowDownloadState.PAUSED} + Paused + {/if} + + {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/models/ModelId.svelte b/ui/apps/chat/src/lib/components/app/models/ModelId.svelte new file mode 100644 index 000000000000..485ad5682e52 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelId.svelte @@ -0,0 +1,88 @@ + + + +{#if resolvedShowRaw} + +{:else} + !isAuxSidecar(badge.kind))} + name={parsed.modelName ?? modelId} + org={parsed.orgName ?? undefined} + params={hideParameters ? undefined : (parsed.params ?? undefined)} + quantization={resolvedHideQuantization ? undefined : (parsed.quantization ?? undefined)} + sidecar={parsed.sidecar ?? undefined} + tags={resolvedHideTags ? [] : [...(parsed.tags ?? []), ...(tags ?? [])]} + tooltip={showRawTooltip ? modelId : undefined} + /> +{/if} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte b/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte new file mode 100644 index 000000000000..0607ddcedcc2 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte @@ -0,0 +1,107 @@ + + +
+ {#if isLoading} + + {:else} + + {#if showAction && revealOnHover} + {#if isFailed} + + {:else} + + {/if} + {:else} + {#if isFailed} + + {:else} + + {/if} + {/if} + + +
+ {#if isFailed} + modelsStore.status.load(option.model)} + stopPropagationOnClick + tooltip="Retry loading model" + tooltipAsTitle + /> + {:else if isLoaded || isSleeping} + modelsStore.status.unload(option.model)} + stopPropagationOnClick + tooltip="Unload model" + tooltipAsTitle + /> + {:else} + modelsStore.status.load(option.model)} + stopPropagationOnClick + tooltip="Load model" + tooltipAsTitle + /> + {/if} +
+ {/if} +
diff --git a/tools/ui/src/lib/components/app/models/ModelLoadHighlight.svelte b/ui/apps/chat/src/lib/components/app/models/ModelLoadHighlight.svelte similarity index 100% rename from tools/ui/src/lib/components/app/models/ModelLoadHighlight.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelLoadHighlight.svelte diff --git a/ui/apps/chat/src/lib/components/app/models/ModelOrgAvatar.svelte b/ui/apps/chat/src/lib/components/app/models/ModelOrgAvatar.svelte new file mode 100644 index 000000000000..39b377b04a8d --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelOrgAvatar.svelte @@ -0,0 +1,18 @@ + + + +{#if hubEnabled} + +{/if} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte b/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte new file mode 100644 index 000000000000..071b71000e92 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelRowActions.svelte @@ -0,0 +1,107 @@ + + +
event.stopPropagation()} + onkeydown={(event) => event.stopPropagation()} + role="presentation" +> + + uiStore.openModelDetails(option.id)} + tooltip="Manage model" + tooltipAsTitle + /> + + + {#if canDictate} + + + voiceStore.toggleDictation(option.model)} + tooltip={dictationLabel} + tooltipAsTitle + /> + + {/if} + + {#if isFav} + + + modelsStore.toggleFavorite(option.model)} + tooltip="Remove from favorites" + tooltipAsTitle + /> + + + + + {:else} + + modelsStore.toggleFavorite(option.model)} + tooltip="Add to favorites" + tooltipAsTitle + /> + + {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/models/ModelVoiceRole.svelte b/ui/apps/chat/src/lib/components/app/models/ModelVoiceRole.svelte new file mode 100644 index 000000000000..cabc881390d4 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelVoiceRole.svelte @@ -0,0 +1,60 @@ + + + +{#if role} + {@const Icon = ICONS[role]} + + + + {#snippet child({ props })} + + + {/snippet} + + + +

{description}

+
+
+{/if} diff --git a/tools/ui/src/lib/components/app/models/ModelsManager/ModelsManager.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte similarity index 94% rename from tools/ui/src/lib/components/app/models/ModelsManager/ModelsManager.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte index a988b45b0bb1..4cdf3112bf7c 100644 --- a/tools/ui/src/lib/components/app/models/ModelsManager/ModelsManager.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte @@ -10,11 +10,15 @@ type ModelsTableGroup, splitHiddenQuants } from './utils'; - import { LOCAL_BACKEND_ID, type ModalityKey, MODELS_TABLE_GROUP_LABELS } from '$lib/constants'; - import { ModelCapability, ModelsTableGroupKind } from '$lib/enums'; - import { modelsStore, uiStore } from '$lib/stores'; - import type { ModelOption } from '$lib/types/models'; - import { filterModelOptions } from '$lib/utils'; + import { + LOCAL_BACKEND_ID, + type ModalityKey, + MODELS_TABLE_GROUP_LABELS + } from '#lib/constants/index.ts'; + import { ModelCapability, ModelsTableGroupKind } from '#lib/enums/index.ts'; + import { modelsStore, uiStore } from '#lib/stores/index.ts'; + import type { ModelOption } from '#lib/types/models.js'; + import { filterModelOptions } from '#lib/utils/index.ts'; import type { Snippet } from 'svelte'; import { SvelteMap } from 'svelte/reactivity'; diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerDownloadControl.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerDownloadControl.svelte new file mode 100644 index 000000000000..41418b729635 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerDownloadControl.svelte @@ -0,0 +1,47 @@ + + + +
+ + {percent !== null ? `${percent}%` : isPaused ? 'Paused' : ''} + + + +
diff --git a/tools/ui/src/lib/components/app/models/ModelsManager/ModelsManagerFilters.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerFilters.svelte similarity index 91% rename from tools/ui/src/lib/components/app/models/ModelsManager/ModelsManagerFilters.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerFilters.svelte index 99fe920725ff..27aaf8b2bdc0 100644 --- a/tools/ui/src/lib/components/app/models/ModelsManager/ModelsManagerFilters.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManagerFilters.svelte @@ -1,11 +1,10 @@ + + +
+
+ + + + + + + uiStore.openModelDetails(entry.repoWithTag)} + tooltip="Manage model" + tooltipAsTitle + /> + + onRequestCancel?.(entry.repoWithTag)} + /> +
+ + + {#if onDiskDrafts.length} +
+ {#each onDiskDrafts as badge (badge.repo + ':' + badge.kind + ':' + (badge.quant ?? ''))} + + {/each} +
+ {/if} + + {#if entry.progress && entry.progress.totalBytes > 0} + + {/if} +
diff --git a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorDrawer.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorDrawer.svelte similarity index 88% rename from tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorDrawer.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorDrawer.svelte index c5d5a1377fca..4a0f243604d4 100644 --- a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorDrawer.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorDrawer.svelte @@ -1,7 +1,7 @@ + +{#snippet selectorTriggerInner()} + + + + {#if selectedOption} + + + + {#if showReasoning} + + {/if} + {:else} + Select model + {/if} + + + {#if ms.updating || ms.isLoadingModel || triggerLoading} + + {:else} + + {/if} + + {#if triggerLoading} + + {/if} +{/snippet} + +{#snippet modelOption(item: ModelItem, hideOrgName: boolean)} + {@const { option } = item} + {@const isSelected = currentModel === option.model || ms.activeId === option.id} + {@const isHighlighted = option.id === highlightedId} + {@const isFav = ms.isFavorite(option.model)} + + { + if (event.key === KeyboardKey.ENTER || event.key === KeyboardKey.SPACE) { + event.preventDefault(); + onModelKeyAction?.(option.id, event.altKey); + } + }} + onMouseEnter={() => onHighlight?.(option.id)} + onSelect={ms.handleSelect} + {option} + /> +{/snippet} + + + + + + {#snippet child({ props })} + + {@render selectorTriggerInner()} + + {/snippet} + + + {#if selectedOption} + +

{triggerTooltipLabel(selectedOption)}

+
+ {/if} +
+ + + { + // bits-ui re-mounts the focus scope when the drawer opens or closes, so this runs with the menu still open; trigger focus would show its tooltip + if (open) event.preventDefault(); + }} + onFocusOutside={(event) => { + if (uiStore.isModelDetailsOpen) event.preventDefault(); + }} + onInteractOutside={(event) => { + if (uiStore.isModelDetailsOpen) event.preventDefault(); + }} + onOpenAutoFocus={(event) => event.preventDefault()} + > + ms.setSearchTerm(v)} + {onSearchKeyDown} + placeholder="Search models..." + scrollport + searchClass="bg-transparent" + searchValue={ms.searchTerm} + > + + {@render pickerContent('px-1.5')} + + +
+ + +{#snippet pickerFooter()} + {#if showReasoning} + + {:else} + + + + + Manage models + + + {/if} +{/snippet} + +{#snippet pickerContent(listClass: string)} +
+ {#if !ms.isCurrentModelInCache && currentModel} + + + {/if} + + {#if ms.isEmpty} +

{ms.emptyMessage}

+ {/if} + + +
+{/snippet} + + diff --git a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte similarity index 80% rename from tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte rename to ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte index 29adb3c0421e..d3e23c0a0077 100644 --- a/tools/ui/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorList.svelte @@ -1,22 +1,22 @@ + +{#snippet header()} + {#if reasoning.isOff} + + {:else} + + {/if} + + Reasoning + + {current} +{/snippet} + +{#snippet levelLabel(level: ReasoningEffortLevel)} + {@const tokenLabel = reasoning.tokenLabel(level)} + + {#if reasoning.isSelected(level)} + + {:else} +
+ {/if} + + {level.label} + + {#if tokenLabel} + {tokenLabel} + {/if} +{/snippet} + +{#if variant === 'menu'} + + + +
+ {#each reasoning.levels as level (level.value)} + reasoning.select(level)}> + {@render levelLabel(level)} + + {/each} +
+
+
+{:else} +
+ +
+ {#each reasoning.levels as level (level.value)} + + {/each} +
+
+
+{/if} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorReasoningBadge.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorReasoningBadge.svelte new file mode 100644 index 000000000000..fabc65c5425c --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorReasoningBadge.svelte @@ -0,0 +1,34 @@ + + + +{#if reasoning.isOff} + + +{:else if reasoning.currentEffort !== ReasoningEffort.DEFAULT} + + + + Reasoning {REASONING_EFFORT_LABELS[reasoning.currentEffort]} + +{/if} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorTriggerIcon.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorTriggerIcon.svelte new file mode 100644 index 000000000000..a7be8dc176f1 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorTriggerIcon.svelte @@ -0,0 +1,23 @@ + + +{#if option} + + {#snippet fallback()} + + {/snippet} + +{:else} + +{/if} diff --git a/tools/ui/src/lib/components/app/models/ModelsSelector/index.ts b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts similarity index 100% rename from tools/ui/src/lib/components/app/models/ModelsSelector/index.ts rename to ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscover.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscover.svelte similarity index 88% rename from tools/ui/src/lib/components/app/models/discover/ModelsDiscover.svelte rename to ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscover.svelte index 4bc1c38eb531..5cb8bcf54145 100644 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscover.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscover.svelte @@ -1,19 +1,19 @@ + + + + + + Chat template + + + + + + + + + + + diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte similarity index 90% rename from tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte rename to ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte index 7d957e983e10..8cbaac857889 100644 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte @@ -3,11 +3,11 @@ import ModelsDiscoverDetailsHeader from './ModelsDiscoverDetailsHeader.svelte'; import ModelsDiscoverDetailsReadme from './ModelsDiscoverDetailsReadme.svelte'; import ModelsDiscoverDetailsSkeleton from './ModelsDiscoverDetailsSkeleton.svelte'; - import { OTHER_BIT_DEPTH } from '$lib/constants'; - import { ModelAuxSidecar } from '$lib/enums'; - import { HuggingFaceService } from '$lib/services'; - import type { HfModelDetailInfo, HfModelSibling, ModelBitDepthRow } from '$lib/types'; - import { detectThinkingSupport, detectToolUseSupport } from '$lib/utils'; + import { OTHER_BIT_DEPTH } from '#lib/constants/index.ts'; + import { ModelAuxSidecar } from '#lib/enums/index.ts'; + import { HuggingFaceService } from '#lib/services/index.ts'; + import type { HfModelDetailInfo, HfModelSibling, ModelBitDepthRow } from '#lib/types/index.ts'; + import { detectThinkingSupport, detectToolUseSupport } from '#lib/utils/index.ts'; import { SvelteMap } from 'svelte/reactivity'; interface Props { @@ -80,7 +80,7 @@ {:else if error}
-

{error}

+

{error}

{:else if details}
diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsContainer.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsContainer.svelte similarity index 90% rename from tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsContainer.svelte rename to ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsContainer.svelte index 7d81ea8abab9..be6f1f1fe996 100644 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsContainer.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsContainer.svelte @@ -1,7 +1,7 @@ {#if bitDepthRows.length} -
+
@@ -211,7 +211,7 @@ readonly. --> {#if draftKinds.length}
diff --git a/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHfHubStats.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHfHubStats.svelte new file mode 100644 index 000000000000..2431b3bdbe27 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHfHubStats.svelte @@ -0,0 +1,31 @@ + + +
+ {#if typeof details.downloads === 'number'} + + + {HuggingFaceService.formatDownloads(details.downloads)} + + {/if} + + {#if typeof details.likes === 'number'} + + + {HuggingFaceService.formatLikes(details.likes)} + + {/if} + + {#if details.lastModified} + Updated {HuggingFaceService.formatRelativeTime(details.lastModified)} + {/if} +
diff --git a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte similarity index 78% rename from tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte rename to ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte index af7a38089390..c222d4ab0a29 100644 --- a/tools/ui/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte @@ -1,11 +1,11 @@ {#if description} -

{description}

+

{description}

{/if} @@ -51,10 +51,10 @@ {#if gguf?.chat_template} + + + + + {triggerTooltip ?? 'Actions'} + + +
+ {#each actions as action, index (action.label)} + {#if action.separator && index > 0} + + {/if} + + + {/each} +
+
+
+{:else} + + + + + {#snippet child({ props })} + e.stopPropagation()} + > + {@render iconComponent(triggerIcon, 'h-3 w-3')} + + {#if triggerTooltip} + {triggerTooltip} + {/if} + + {/snippet} + + + {#if triggerTooltip} + +

{triggerTooltip}

+
+ {/if} +
+ + + (open = false)} /> + +
+{/if} + +{#snippet iconComponent(IconComponent: Component, className: string)} + +{/snippet} diff --git a/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte b/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte new file mode 100644 index 000000000000..059af0e54e23 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte @@ -0,0 +1,98 @@ + + +{#snippet body()} +
+ +
+ +
+ +
+ {@render children()} + + {#if isEmpty} +
{emptyMessage}
+ {/if} +
+
+{/snippet} + +{#if scrollport} +
+ {@render body()} +
+{:else} + {@render body()} +{/if} + +{#if footer} +
+ + + {@render footer()} +
+{/if} diff --git a/tools/ui/src/lib/components/app/navigation/MenuActionsList.svelte b/ui/apps/chat/src/lib/components/app/navigation/MenuActionsList.svelte similarity index 78% rename from tools/ui/src/lib/components/app/navigation/MenuActionsList.svelte rename to ui/apps/chat/src/lib/components/app/navigation/MenuActionsList.svelte index 7a0ba8a4d4d8..a86d74ced7ea 100644 --- a/tools/ui/src/lib/components/app/navigation/MenuActionsList.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/MenuActionsList.svelte @@ -1,11 +1,11 @@ + + + diff --git a/tools/ui/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationGroupSection.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationGroupSection.svelte similarity index 92% rename from tools/ui/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationGroupSection.svelte rename to ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationGroupSection.svelte index 122a75ceae78..4a9ab73ed73c 100644 --- a/tools/ui/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationGroupSection.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationGroupSection.svelte @@ -9,22 +9,22 @@ ContextMenuActions, DialogConfirmation, DropdownMenuActions - } from '$lib/components/app'; + } from '#lib/components/app/index.ts'; import { SIDEBAR_ROW_SLIDE_MS, SIDEBAR_SECTION_IDS, SIDEBAR_SECTION_PREVIEW_COUNT, SIDEBAR_SHOW_MORE_ROW_CLASS - } from '$lib/constants'; + } from '#lib/constants/index.ts'; import { conversationsStore, deviceStore, groupsStore, sidebarDragStore, uiStore - } from '$lib/stores'; - import type { DatabaseConversation, Group, MenuAction } from '$lib/types'; - import type { ConversationTreeItem } from '$lib/utils'; + } from '#lib/stores/index.ts'; + import type { DatabaseConversation, Group, MenuAction } from '#lib/types/index.ts'; + import type { ConversationTreeItem } from '#lib/utils/index.ts'; import type { Snippet } from 'svelte'; import { slide } from 'svelte/transition'; @@ -143,7 +143,7 @@ {:else}
  • diff --git a/tools/ui/src/lib/components/app/navigation/index.ts b/ui/apps/chat/src/lib/components/app/navigation/index.ts similarity index 100% rename from tools/ui/src/lib/components/app/navigation/index.ts rename to ui/apps/chat/src/lib/components/app/navigation/index.ts diff --git a/tools/ui/src/lib/components/app/server/ServerErrorSplash.svelte b/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte similarity index 87% rename from tools/ui/src/lib/components/app/server/ServerErrorSplash.svelte rename to ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte index e8154e5ce22c..a527bcd2365c 100644 --- a/tools/ui/src/lib/components/app/server/ServerErrorSplash.svelte +++ b/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte @@ -1,13 +1,13 @@ + +
    +
    +
    +
    + +
    + +

    Connecting to Server

    + +

    + {message} +

    +
    + +
    + +
    +
    +
    diff --git a/ui/apps/chat/src/lib/components/app/servers/ServerStatus.svelte b/ui/apps/chat/src/lib/components/app/servers/ServerStatus.svelte new file mode 100644 index 000000000000..4077e0649831 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/servers/ServerStatus.svelte @@ -0,0 +1,69 @@ + + +
    +
    +
    + + {getStatusText()} +
    + + {#if serverData && !error} + + + + {model || 'Unknown Model'} + + + {#if serverData?.default_generation_settings?.n_ctx} + + ctx: {serverData.default_generation_settings.n_ctx.toLocaleString()} + + {/if} + {/if} + + {#if showActions && error} + + {/if} +
    diff --git a/ui/apps/chat/src/lib/components/app/servers/index.ts b/ui/apps/chat/src/lib/components/app/servers/index.ts new file mode 100644 index 000000000000..29394fddebb9 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/servers/index.ts @@ -0,0 +1,80 @@ +/** + * + * SERVERS + * + * Components for displaying server connection state and handling + * connection errors. Integrates with serverStore for state management. + * + */ + +/** + * **ServerStatus** - Server connection status indicator + * + * Compact status display showing connection state, model name, + * and context size. Used in headers and loading screens. + * + * **Architecture:** + * - Reads state from serverStore (props, loading, error) + * - Displays model name from modelsStore + * + * **Features:** + * - Status dot: green (connected), yellow (connecting), red (error), gray (unknown) + * - Status text label + * - Model name badge with icon + * - Context size badge + * - Optional error action button + * + * @example + * ```svelte + * + * ``` + */ +export { default as ServerStatus } from './ServerStatus.svelte'; + +/** + * **ServerErrorSplash** - Full-screen connection error display + * + * Blocking error screen shown when server connection fails. + * Provides retry options and API key input for authentication errors. + * + * **Architecture:** + * - Detects access denied errors for API key flow + * - Validates API key against server before saving + * - Integrates with settingsStore for API key persistence + * + * **Features:** + * - Error message display with icon + * - Retry connection button with loading state + * - API key input for authentication errors + * - API key validation with success/error feedback + * - Troubleshooting section with server start commands + * - Animated transitions for UI elements + * + * @example + * ```svelte + * + * ``` + */ +export { default as ServerErrorSplash } from './ServerErrorSplash.svelte'; + +/** + * **ServerLoadingSplash** - Full-screen loading display + * + * Shown during initial server connection. Displays loading animation + * with ServerStatus component for real-time connection state. + * + * **Features:** + * - Animated server icon + * - Customizable loading message + * - Embedded ServerStatus for live updates + * + * @example + * ```svelte + * + * ``` + */ +export { default as ServerLoadingSplash } from './ServerLoadingSplash.svelte'; diff --git a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte similarity index 81% rename from tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte rename to ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte index 6993e78732f5..d54d56a20017 100644 --- a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte @@ -1,4 +1,5 @@ -
    +
    section.slug === activeSlug} @@ -176,6 +186,12 @@ {:else if currentSection.slug === SETTINGS_SECTION_SLUGS.IMPORT_EXPORT} + {:else if currentSection.slug === SETTINGS_SECTION_SLUGS.VOICE && currentSection.fields} + {:else if currentSection.fields}
    @@ -200,7 +216,9 @@
    -

    Settings are saved in browser's localStorage

    +

    + Settings are saved in browser's localStorage +

    diff --git a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte similarity index 75% rename from tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte rename to ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte index 528654ee580e..2f66bd4fa835 100644 --- a/tools/ui/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte @@ -1,16 +1,21 @@
    -

    {title}

    +

    {title}

    -

    {description}

    +

    {description}

    + + +{/if} diff --git a/tools/ui/src/lib/components/pwa/index.ts b/ui/apps/chat/src/lib/components/pwa/index.ts similarity index 100% rename from tools/ui/src/lib/components/pwa/index.ts rename to ui/apps/chat/src/lib/components/pwa/index.ts diff --git a/tools/ui/src/lib/constants/agentic.constants.ts b/ui/apps/chat/src/lib/constants/agentic.constants.ts similarity index 97% rename from tools/ui/src/lib/constants/agentic.constants.ts rename to ui/apps/chat/src/lib/constants/agentic.constants.ts index 4b8463e1e3ab..2f83733a9771 100644 --- a/tools/ui/src/lib/constants/agentic.constants.ts +++ b/ui/apps/chat/src/lib/constants/agentic.constants.ts @@ -1,4 +1,4 @@ -import type { AgenticConfig } from '$lib/types/agentic'; +import type { AgenticConfig } from '#lib/types/agentic.js'; export const ATTACHMENT_SAVED_REGEX = /\[Attachment saved: ([^\]]+)\]/; diff --git a/tools/ui/src/lib/constants/api-endpoints.constants.ts b/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/api-endpoints.constants.ts rename to ui/apps/chat/src/lib/constants/api-endpoints.constants.ts diff --git a/tools/ui/src/lib/constants/app.constants.ts b/ui/apps/chat/src/lib/constants/app.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/app.constants.ts rename to ui/apps/chat/src/lib/constants/app.constants.ts diff --git a/tools/ui/src/lib/constants/attachment-menu.constants.ts b/ui/apps/chat/src/lib/constants/attachment-menu.constants.ts similarity index 91% rename from tools/ui/src/lib/constants/attachment-menu.constants.ts rename to ui/apps/chat/src/lib/constants/attachment-menu.constants.ts index dc9db7478fee..2888457765d5 100644 --- a/tools/ui/src/lib/constants/attachment-menu.constants.ts +++ b/ui/apps/chat/src/lib/constants/attachment-menu.constants.ts @@ -1,6 +1,10 @@ -import { FILE_TYPE_ICONS } from '$lib/constants'; -import { AttachmentAction, AttachmentItemEnabledWhen, AttachmentMenuItemId } from '$lib/enums'; -import type { AttachmentMenuItem } from '$lib/types'; +import { FILE_TYPE_ICONS } from '#lib/constants/index.ts'; +import { + AttachmentAction, + AttachmentItemEnabledWhen, + AttachmentMenuItemId +} from '#lib/enums/index.ts'; +import type { AttachmentMenuItem } from '#lib/types/index.ts'; /** * File attachment menu items shown in both the desktop dropdown and mobile sheet. diff --git a/tools/ui/src/lib/constants/auto-scroll.constants.ts b/ui/apps/chat/src/lib/constants/auto-scroll.constants.ts similarity index 79% rename from tools/ui/src/lib/constants/auto-scroll.constants.ts rename to ui/apps/chat/src/lib/constants/auto-scroll.constants.ts index 61a0ae27460c..932cd1104c9c 100644 --- a/tools/ui/src/lib/constants/auto-scroll.constants.ts +++ b/ui/apps/chat/src/lib/constants/auto-scroll.constants.ts @@ -6,10 +6,6 @@ export const LANDING_EAGER_ROWS = 8; // Reasoning block: stickier because reasoning fires many small // incremental DOM writes that easily drift a few pixels off bottom. export const REASONING_SCROLL_AT_BOTTOM_THRESHOLD_PX = 64; -// Syntax-highlighted code: stickier than the chat main view because line -// wrap reflows while the highlight.js pass settles can drift a few pixels -// off bottom. -export const SYNTAX_CODE_SCROLL_AT_BOTTOM_THRESHOLD_PX = 32; // Streaming tool output (e.g. exec_shell_command): shell commands produce // lots of small line writes and the exit-code line appended at the tail // past the last user-visible frame is what triggers DOM drift, so use a diff --git a/tools/ui/src/lib/constants/backend.constants.ts b/ui/apps/chat/src/lib/constants/backend.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/backend.constants.ts rename to ui/apps/chat/src/lib/constants/backend.constants.ts diff --git a/tools/ui/src/lib/constants/binary-detection.constants.ts b/ui/apps/chat/src/lib/constants/binary-detection.constants.ts similarity index 78% rename from tools/ui/src/lib/constants/binary-detection.constants.ts rename to ui/apps/chat/src/lib/constants/binary-detection.constants.ts index 69bd4d48e371..75c7c43879b5 100644 --- a/tools/ui/src/lib/constants/binary-detection.constants.ts +++ b/ui/apps/chat/src/lib/constants/binary-detection.constants.ts @@ -1,4 +1,4 @@ -import type { BinaryDetectionOptions } from '$lib/types'; +import type { BinaryDetectionOptions } from '#lib/types/index.ts'; export const DEFAULT_BINARY_DETECTION_OPTIONS: BinaryDetectionOptions = { maxAbsoluteNullBytes: 2, diff --git a/ui/apps/chat/src/lib/constants/browser-info.ts b/ui/apps/chat/src/lib/constants/browser-info.ts new file mode 100644 index 000000000000..b63583ffb496 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/browser-info.ts @@ -0,0 +1,38 @@ +import { CLI_FLAGS } from './cli-flags.constants'; +import { BuiltInTool, JsonSchemaType, ToolCallType } from '#lib/enums/index.ts'; +import type { OpenAIToolDefinition } from '#lib/types/index.ts'; + +// get_info is served by the server, but the browser falls back to this +// implementation when the server does not provide it - same wire name. +export const BROWSER_INFO_TOOL_NAME = BuiltInTool.SERVER_GET_INFO; + +/** UA token to OS name, first match wins - Android and iOS UAs also carry the Linux / Mac OS X tokens */ +export const BROWSER_INFO_OS_UA_PATTERNS: readonly [RegExp, string][] = [ + [/Windows NT/, 'Windows'], + [/Android/, 'Android'], + [/iPhone|iPad|iPod/, 'iOS'], + [/CrOS/, 'ChromeOS'], + [/Mac OS X/, 'macOS'], + [/Linux/, 'Linux'] +]; + +export const BROWSER_INFO_OS_UNKNOWN = 'unknown'; + +/** Sent to the model as the `note` field of the tool result, next to the OS name */ +export const BROWSER_INFO_NOTE = `This environment is browser-only, it cannot read or modify local files, and it cannot run shell commands. To get local file access, tell user to launch llama-server with the ${CLI_FLAGS.AGENT} argument.`; + +export function buildBrowserInfoToolDefinition(): OpenAIToolDefinition { + return { + function: { + description: + 'Get runtime info (OS name), may call when user asks about local files or shell commands', + name: BROWSER_INFO_TOOL_NAME, + parameters: { + properties: {}, + required: [], + type: JsonSchemaType.OBJECT + } + }, + type: ToolCallType.FUNCTION + }; +} diff --git a/tools/ui/src/lib/constants/cache.constants.ts b/ui/apps/chat/src/lib/constants/cache.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/cache.constants.ts rename to ui/apps/chat/src/lib/constants/cache.constants.ts diff --git a/tools/ui/src/lib/constants/chat-form.constants.ts b/ui/apps/chat/src/lib/constants/chat-form.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/chat-form.constants.ts rename to ui/apps/chat/src/lib/constants/chat-form.constants.ts diff --git a/tools/ui/src/lib/constants/chat-tabs.constants.ts b/ui/apps/chat/src/lib/constants/chat-tabs.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/chat-tabs.constants.ts rename to ui/apps/chat/src/lib/constants/chat-tabs.constants.ts diff --git a/tools/ui/src/lib/constants/cli-flags.constants.ts b/ui/apps/chat/src/lib/constants/cli-flags.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/cli-flags.constants.ts rename to ui/apps/chat/src/lib/constants/cli-flags.constants.ts diff --git a/ui/apps/chat/src/lib/constants/code-block.constants.ts b/ui/apps/chat/src/lib/constants/code-block.constants.ts new file mode 100644 index 000000000000..c3ae149a0d10 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/code-block.constants.ts @@ -0,0 +1,9 @@ +export { + CODE_BLOCK, + CODE_BLOCK_CLASS, + FILE_EXTENSION_SEPARATOR, + FILE_PATH_SEPARATOR_REGEX, + TEXT_LANGUAGE_PREFIX_REGEX +} from '@ggml-org/llama-ui/constants'; + +// Constants for the markdown code-block renderer: language/fence handling and CSS classes. diff --git a/tools/ui/src/lib/constants/compaction.constants.ts b/ui/apps/chat/src/lib/constants/compaction.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/compaction.constants.ts rename to ui/apps/chat/src/lib/constants/compaction.constants.ts diff --git a/tools/ui/src/lib/constants/content-detection.constants.ts b/ui/apps/chat/src/lib/constants/content-detection.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/content-detection.constants.ts rename to ui/apps/chat/src/lib/constants/content-detection.constants.ts diff --git a/tools/ui/src/lib/constants/context-gauge-dial.constants.ts b/ui/apps/chat/src/lib/constants/context-gauge-dial.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/context-gauge-dial.constants.ts rename to ui/apps/chat/src/lib/constants/context-gauge-dial.constants.ts diff --git a/tools/ui/src/lib/constants/context-gauge-popup.constants.ts b/ui/apps/chat/src/lib/constants/context-gauge-popup.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/context-gauge-popup.constants.ts rename to ui/apps/chat/src/lib/constants/context-gauge-popup.constants.ts diff --git a/tools/ui/src/lib/constants/control-actions.constants.ts b/ui/apps/chat/src/lib/constants/control-actions.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/control-actions.constants.ts rename to ui/apps/chat/src/lib/constants/control-actions.constants.ts diff --git a/tools/ui/src/lib/constants/conversation-import.constants.ts b/ui/apps/chat/src/lib/constants/conversation-import.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/conversation-import.constants.ts rename to ui/apps/chat/src/lib/constants/conversation-import.constants.ts diff --git a/ui/apps/chat/src/lib/constants/conversation-search.constants.ts b/ui/apps/chat/src/lib/constants/conversation-search.constants.ts new file mode 100644 index 000000000000..ab988cd285b0 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/conversation-search.constants.ts @@ -0,0 +1,28 @@ +/** + * Search dialog constants: how many results each section keeps and how long typing settles + * before the slower searches (message content, Hugging Face) run. + */ + +/** Recent chats shown before typing, so the actions stay in view below them. */ +export const CONVERSATION_SEARCH_RECENT_LIMIT = 5; + +/** Title matches kept while typing; the rest stays reachable by typing more. */ +export const CONVERSATION_SEARCH_MATCH_LIMIT = 50; + +/** Chats matched by their messages; the scan stops once this many are found, newest first. */ +export const CONVERSATION_SEARCH_CONTENT_LIMIT = 20; + +/** Pause after typing before the messages are scanned. */ +export const CONVERSATION_SEARCH_CONTENT_DEBOUNCE_MS = 150; + +/** Characters kept before the match in a snippet. */ +export const CONVERSATION_SEARCH_SNIPPET_LEAD = 24; + +/** Snippet length, the match included. */ +export const CONVERSATION_SEARCH_SNIPPET_MAX_CHARS = 120; + +/** Hugging Face matches kept: Discover lists the rest. */ +export const CONVERSATION_SEARCH_HUB_LIMIT = 8; + +/** Pause after typing before Hugging Face is asked, as long as the Discover search waits. */ +export const CONVERSATION_SEARCH_HUB_DEBOUNCE_MS = 300; diff --git a/ui/apps/chat/src/lib/constants/css-classes.constants.ts b/ui/apps/chat/src/lib/constants/css-classes.constants.ts new file mode 100644 index 000000000000..12de5176bd6d --- /dev/null +++ b/ui/apps/chat/src/lib/constants/css-classes.constants.ts @@ -0,0 +1,71 @@ +export { + BOX_BORDER, + FILTER_TOGGLE_ITEM_CLASS, + FILTER_TRIGGER_CLASS, + ICON_CLASS_DEFAULT, + INPUT_CLASSES, + PANEL_CLOSE_MOBILE_CLASS +} from '@ggml-org/llama-ui/constants'; +export { MODEL_BADGE_CLASS, MODEL_VARIANT_BADGE_CLASS } from '@ggml-org/llama-ui/models'; + +export const PANEL_CLASSES = ` + bg-background + elevated-control backdrop-blur-lg! + rounded-t-lg! +`; + +export const CHAT_FORM_POPOVER_MAX_HEIGHT = 'max-h-80'; +export const DIALOG_SUBMENU_CONTENT = 'w-60'; + +/** Shape of a chat tab, shared with the breadcrumb items next to the project tabs. */ +export const TAB_SURFACE_CLASS = + 'flex h-8 items-center rounded-lg border text-body-sm whitespace-nowrap backdrop-blur-xl'; + +/** Tab surface at rest: invisible until hovered. */ +export const TAB_SURFACE_IDLE_CLASS = + 'border-transparent hover:bg-primary/10 hover:border-border/10 hover:shadow-(--elevation-control)'; + +/** A round matte glass key (see GlassKey): white glass over the page, a faint hairline, and + * matte-key's blur and saturation with its small shadow, so what scrolls under it softens. */ +export const GLASS_KEY_CLASS = + 'matte-key flex shrink-0 cursor-pointer items-center justify-center rounded-full border border-border/20 bg-(--surface-glass) text-accent-foreground outline-none transition-colors focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50'; + +/** Tab surface of the open tab. */ +export const TAB_SURFACE_ACTIVE_CLASS = + 'matte-key bg-muted/60 border-border/10 text-accent-foreground hover:bg-primary/15'; + +/** Selects the focused chat-form input (either renderer) to restore focus after model actions. */ +export const CHAT_INPUT_FOCUS_SELECTOR = + '[data-slot="input-area"] textarea, [data-slot="input-area"] [contenteditable="true"]'; + +/** Search input of an open dropdown-menu, focused after the menu mounts. */ +export const DROPDOWN_MENU_CONTENT_SEARCH_SELECTOR = '[data-slot="dropdown-menu-content"] input'; + +/** + * Sticky offset of a model-list group heading under the dropdown's search block: + * the search header exposes its height as `--dropdown-sticky-height`, and one + * section-header row (`py-2` over `text-body-sm` line height) minus the header's + * bottom border stacks the two sticky rows without a gap or an overlap. + */ +export const SELECTOR_GROUP_STICKY_OFFSET = + 'top: calc(var(--dropdown-sticky-height, 0px) + 2.25rem - 1px)'; + +/** Column grid shared by every row of the models manager table. Below md the context, + * status and actions columns are dropped, so a phone gives the whole width to the + * model id and floats the row's last cell at the row's end. */ +export const MODEL_ROW_GRID_CLASS = + 'grid grid-cols-[minmax(0,1fr)] items-center gap-3 md:grid-cols-[minmax(0,1fr)_11rem_3rem_4.5rem] md:gap-4'; + +/** Last cell of a row: its actions menu, or its fold control. A phone floats it at the + * row's end, inside the clearance the first cell leaves in front of it. */ +export const MODEL_ROW_TRAILING_CELL_CLASS = + 'max-md:absolute max-md:top-1/2 max-md:right-3 max-md:-translate-y-1/2'; + +/** Small Tailwind size class for inline icons. */ +export const ICON_CLASS_SM = 'size-icon-sm'; + +/** Extra-small Tailwind size class for inline icons. */ +export const ICON_CLASS_XS = 'size-icon-xs'; + +/** Icon size + spinning animation; used for live-streaming tool indicators. */ +export const ICON_CLASS_SPIN = 'size-icon-md animate-spin'; diff --git a/tools/ui/src/lib/constants/database.constants.ts b/ui/apps/chat/src/lib/constants/database.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/database.constants.ts rename to ui/apps/chat/src/lib/constants/database.constants.ts diff --git a/tools/ui/src/lib/constants/diagram-blocks.constants.ts b/ui/apps/chat/src/lib/constants/diagram-blocks.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/diagram-blocks.constants.ts rename to ui/apps/chat/src/lib/constants/diagram-blocks.constants.ts diff --git a/tools/ui/src/lib/constants/error.constants.ts b/ui/apps/chat/src/lib/constants/error.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/error.constants.ts rename to ui/apps/chat/src/lib/constants/error.constants.ts diff --git a/tools/ui/src/lib/constants/formatters.constants.ts b/ui/apps/chat/src/lib/constants/formatters.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/formatters.constants.ts rename to ui/apps/chat/src/lib/constants/formatters.constants.ts diff --git a/ui/apps/chat/src/lib/constants/get-datetime.ts b/ui/apps/chat/src/lib/constants/get-datetime.ts new file mode 100644 index 000000000000..13c08beffc6f --- /dev/null +++ b/ui/apps/chat/src/lib/constants/get-datetime.ts @@ -0,0 +1,20 @@ +import { BuiltInTool, JsonSchemaType, ToolCallType } from '#lib/enums/index.ts'; +import type { OpenAIToolDefinition } from '#lib/types/index.ts'; + +export const GET_DATETIME_TOOL_NAME = BuiltInTool.BROWSER_GET_DATETIME; + +export function buildGetDatetimeToolDefinition(): OpenAIToolDefinition { + return { + function: { + description: + 'Returns the current local date and time in ISO 8601 format, with the IANA time zone name', + name: GET_DATETIME_TOOL_NAME, + parameters: { + properties: {}, + required: [], + type: JsonSchemaType.OBJECT + } + }, + type: ToolCallType.FUNCTION + }; +} diff --git a/tools/ui/src/lib/constants/groups.constants.ts b/ui/apps/chat/src/lib/constants/groups.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/groups.constants.ts rename to ui/apps/chat/src/lib/constants/groups.constants.ts diff --git a/tools/ui/src/lib/constants/headers.constants.ts b/ui/apps/chat/src/lib/constants/headers.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/headers.constants.ts rename to ui/apps/chat/src/lib/constants/headers.constants.ts diff --git a/tools/ui/src/lib/constants/huggingface.constants.ts b/ui/apps/chat/src/lib/constants/huggingface.constants.ts similarity index 96% rename from tools/ui/src/lib/constants/huggingface.constants.ts rename to ui/apps/chat/src/lib/constants/huggingface.constants.ts index 9a9ce6885923..ca444b0162c0 100644 --- a/tools/ui/src/lib/constants/huggingface.constants.ts +++ b/ui/apps/chat/src/lib/constants/huggingface.constants.ts @@ -5,11 +5,22 @@ * Reference: https://huggingface.co/docs/huggingface_hub/package_reference/hf_api */ +import { GIGABYTE, KILOBYTE, MEGABYTE } from '@ggml-org/llama-ui/models'; +export { + BYTE_LABEL, + GIGABYTE, + GIGABYTE_LABEL, + HF_AVATARS_URL, + KILOBYTE, + KILOBYTE_LABEL, + MEGABYTE, + MEGABYTE_LABEL +} from '@ggml-org/llama-ui/models'; + // API endpoints export const HF_BASE_URL = 'https://huggingface.co'; export const HF_API_MODELS_URL = `${HF_BASE_URL}/api/models`; -export const HF_AVATARS_URL = `${HF_BASE_URL}/api/avatars`; // Query params @@ -176,9 +187,6 @@ export const HF_TASK_TAGS: readonly string[] = [ // Formatting export const BYTE = 1; -export const KILOBYTE = 1_000; -export const MEGABYTE = 1_000_000; -export const GIGABYTE = 1_000_000_000; export const TERABYTE = 1_000_000_000_000; /** @@ -199,11 +207,6 @@ export const HF_SIZE_SUFFIX_BYTES: Readonly> = { t: TERABYTE }; -export const BYTE_LABEL = 'B'; -export const KILOBYTE_LABEL = 'KB'; -export const MEGABYTE_LABEL = 'MB'; -export const GIGABYTE_LABEL = 'GB'; - /** Count suffixes for compact number formatting, e.g. `1.5K`, `2.0M`. */ export const KILO_LABEL = 'K'; export const MEGA_LABEL = 'M'; diff --git a/ui/apps/chat/src/lib/constants/icons.constants.ts b/ui/apps/chat/src/lib/constants/icons.constants.ts new file mode 100644 index 000000000000..c096e9a69285 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/icons.constants.ts @@ -0,0 +1,95 @@ +/** + * Icon and modality mappings for file types and models + * Centralized configuration to ensure consistent icon usage across the app + */ + +import { MODALITY_FLAG_KEYS, MODALITY_ORDER } from '@ggml-org/llama-ui/models'; +import LoadFailedIcon from '@lucide/svelte/icons/circle-alert'; +import DiscoverIcon from '@lucide/svelte/icons/compass'; +import UnloadIcon from '@lucide/svelte/icons/eject'; +import FileIcon from '@lucide/svelte/icons/file'; +// not a microphone: that one is for recording and dictation +import AudioIcon from '@lucide/svelte/icons/file-headphone'; +import FileTextIcon from '@lucide/svelte/icons/file-text'; +import CompactCommandIcon from '@lucide/svelte/icons/fold-vertical'; +import CwdCommandIcon from '@lucide/svelte/icons/folder-open'; +import ImageIcon from '@lucide/svelte/icons/image'; +import LoadingIcon from '@lucide/svelte/icons/loader-2'; +import ModelIcon from '@lucide/svelte/icons/package'; +import PauseDownloadIcon from '@lucide/svelte/icons/pause'; +import ResumeDownloadIcon from '@lucide/svelte/icons/play'; +import LoadIcon from '@lucide/svelte/icons/power'; +import RetryIcon from '@lucide/svelte/icons/rotate-cw'; +import PromptCommandIcon from '@lucide/svelte/icons/sparkles'; +import VideoIcon from '@lucide/svelte/icons/video'; +import { ChatFormCommandAction, FileTypeCategory, ModelCapability } from '#lib/enums/index.ts'; +import type { ModelCapabilities } from '#lib/types/models.js'; +import type { Component } from 'svelte'; +export { + CAPABILITY_ICONS, + CAPABILITY_LABELS, + MODALITY_FLAG_KEYS, + MODALITY_ICONS, + MODALITY_LABELS, + MODALITY_ORDER +} from '@ggml-org/llama-ui/models'; + +export const FILE_TYPE_ICONS = { + [FileTypeCategory.AUDIO]: AudioIcon, + [FileTypeCategory.IMAGE]: ImageIcon, + [FileTypeCategory.PDF]: FileIcon, + [FileTypeCategory.TEXT]: FileTextIcon, + [FileTypeCategory.VIDEO]: VideoIcon +} as const; + +export const DEFAULT_FILE_ICON = FileIcon; + +/** The mark for a model, wherever one is listed. */ +export const MODEL_ICON = ModelIcon; + +/** The mark for the Discover Models surface and its entry points. */ +export const DISCOVER_ICON = DiscoverIcon; + +/** Boolean flag a modality drives on the ModelModalities type. */ +export type ModalityKey = (typeof MODALITY_FLAG_KEYS)[keyof typeof MODALITY_FLAG_KEYS]; + +/** Modality flags a model can carry, in display order. */ +export const MODALITY_KEYS: ModalityKey[] = MODALITY_ORDER.map( + (modality) => MODALITY_FLAG_KEYS[modality] +); + +/** Maps a ModelCapability to the boolean flag it drives on the ModelCapabilities type */ +export const CAPABILITY_FLAG_KEYS: Record = { + [ModelCapability.REASONING]: 'reasoning', + [ModelCapability.TOOL_USE]: 'tools' +}; + +/** Icons of the slash-command picker, one per chat-form command. */ +export const CHAT_FORM_COMMAND_ICONS: Record = { + [ChatFormCommandAction.COMPACT]: CompactCommandIcon, + [ChatFormCommandAction.CWD]: CwdCommandIcon, + [ChatFormCommandAction.MODEL]: MODEL_ICON, + [ChatFormCommandAction.PROMPT]: PromptCommandIcon +}; + +/** Icons of the download control a manager row shows while it downloads. */ +export const MODEL_DOWNLOAD_ICONS = { + pause: PauseDownloadIcon, + resume: ResumeDownloadIcon +} as const; + +/** Icons the model load control shows for its states and actions. */ +export const MODEL_LOAD_ICONS = { + failed: LoadFailedIcon, + load: LoadIcon, + loading: LoadingIcon, + retry: RetryIcon, + unload: UnloadIcon +} as const; + +// Shared SVG icon strings for copy and preview buttons +export const COPY_ICON_SVG = ``; + +export const PREVIEW_ICON_SVG = ``; + +export const CODE_ICON_SVG = ``; diff --git a/tools/ui/src/lib/constants/image.constants.ts b/ui/apps/chat/src/lib/constants/image.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/image.constants.ts rename to ui/apps/chat/src/lib/constants/image.constants.ts diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts new file mode 100644 index 000000000000..6f6ac5a10c20 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/index.ts @@ -0,0 +1,77 @@ +// Central constants export file +// All constants should be imported from '#lib/constants/index.ts' + +export * from './agentic.constants'; +export * from './api-endpoints.constants'; +export * from './app.constants'; +export * from './backend.constants'; +export * from './chat-tabs.constants'; +export * from './database.constants'; +export * from './reasoning-effort.constants'; +export * from './recommended-mcp-servers.constants'; +export * from './storage.constants'; +export * from './icons.constants'; +export * from './attachment-menu.constants'; +export * from './auto-scroll.constants'; +export * from './context-gauge-dial.constants'; +export * from './context-gauge-popup.constants'; +export * from './conversation-import.constants'; +export * from './conversation-search.constants'; +export * from './binary-detection.constants'; +export * from './content-detection.constants'; +export * from './tool-call-args.constants'; +export * from './tool-ui.constants'; +export * from './cache.constants'; +export * from './chat-form.constants'; +export * from './cli-flags.constants'; +export * from './compaction.constants'; +export * from './code-block.constants'; +export * from './control-actions.constants'; +export * from './css-classes.constants'; +export * from './formatters.constants'; +export * from './groups.constants'; +export * from './headers.constants'; +export * from './key-value-pairs.constants'; +export * from './keyboard-shortcuts.constants'; +export * from './latex-protection.constants'; +export * from './literal-html.constants'; +export * from './markdown.constants'; +export * from './mermaid-blocks.constants'; +export * from './svg-blocks.constants'; +export * from './diagram-blocks.constants'; +export * from './max-bundle-size.constants'; +export * from './error.constants'; +export * from './image.constants'; +export * from './mcp.constants'; +export * from './mcp-form.constants'; +export * from './mcp-resource.constants'; +export * from './mention-badge.constants'; +export * from './message-export.constants'; +export * from './path-display.constants'; +export * from './model-id.constants'; +export * from './model-loading.constants'; +export * from './models-manager.constants'; +export * from './models-discover.constants'; +export * from './models-discover-download.constants'; +export * from './model-compatibility.constants'; +export * from './huggingface.constants'; +export * from './precision.constants'; +export * from './pwa.constants'; +export * from './routes.constants'; +export * from './sandbox.constants'; +export * from './settings-keys.constants'; +export * from './settings.constants'; +export * from './special-characters.constants'; +export * from './stream.constants'; +export * from './supported-file-types.constants'; +export * from './table-html-restorer.constants'; +export * from './title-generation.constants'; +export * from './ui.constants'; +export * from './uri-template.constants'; +export * from './url.constants'; +export * from './working-directory.constants'; +export * from './read-media'; +export * from './get-datetime'; +export * from './browser-info'; +export * from './search-chats'; +export * from './voice.constants'; diff --git a/tools/ui/src/lib/constants/key-value-pairs.constants.ts b/ui/apps/chat/src/lib/constants/key-value-pairs.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/key-value-pairs.constants.ts rename to ui/apps/chat/src/lib/constants/key-value-pairs.constants.ts diff --git a/tools/ui/src/lib/constants/keyboard-shortcuts.constants.ts b/ui/apps/chat/src/lib/constants/keyboard-shortcuts.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/keyboard-shortcuts.constants.ts rename to ui/apps/chat/src/lib/constants/keyboard-shortcuts.constants.ts diff --git a/tools/ui/src/lib/constants/latex-protection.constants.ts b/ui/apps/chat/src/lib/constants/latex-protection.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/latex-protection.constants.ts rename to ui/apps/chat/src/lib/constants/latex-protection.constants.ts diff --git a/tools/ui/src/lib/constants/literal-html.constants.ts b/ui/apps/chat/src/lib/constants/literal-html.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/literal-html.constants.ts rename to ui/apps/chat/src/lib/constants/literal-html.constants.ts diff --git a/tools/ui/src/lib/constants/markdown.constants.ts b/ui/apps/chat/src/lib/constants/markdown.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/markdown.constants.ts rename to ui/apps/chat/src/lib/constants/markdown.constants.ts diff --git a/tools/ui/src/lib/constants/max-bundle-size.constants.ts b/ui/apps/chat/src/lib/constants/max-bundle-size.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/max-bundle-size.constants.ts rename to ui/apps/chat/src/lib/constants/max-bundle-size.constants.ts diff --git a/tools/ui/src/lib/constants/mcp-form.constants.ts b/ui/apps/chat/src/lib/constants/mcp-form.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/mcp-form.constants.ts rename to ui/apps/chat/src/lib/constants/mcp-form.constants.ts diff --git a/tools/ui/src/lib/constants/mcp-resource.constants.ts b/ui/apps/chat/src/lib/constants/mcp-resource.constants.ts similarity index 97% rename from tools/ui/src/lib/constants/mcp-resource.constants.ts rename to ui/apps/chat/src/lib/constants/mcp-resource.constants.ts index c2639daa12d5..557d9efa30dd 100644 --- a/tools/ui/src/lib/constants/mcp-resource.constants.ts +++ b/ui/apps/chat/src/lib/constants/mcp-resource.constants.ts @@ -1,4 +1,4 @@ -import { MimeTypeAudio, MimeTypeImage } from '$lib/enums'; +import { MimeTypeAudio, MimeTypeImage } from '#lib/enums/index.ts'; // File extension patterns for resource type detection export const IMAGE_FILE_EXTENSION_REGEX = /\.(png|jpg|jpeg|gif|svg|webp)$/i; diff --git a/tools/ui/src/lib/constants/mcp.constants.ts b/ui/apps/chat/src/lib/constants/mcp.constants.ts similarity index 88% rename from tools/ui/src/lib/constants/mcp.constants.ts rename to ui/apps/chat/src/lib/constants/mcp.constants.ts index 11013d2cb15e..fffbdc9de96e 100644 --- a/tools/ui/src/lib/constants/mcp.constants.ts +++ b/ui/apps/chat/src/lib/constants/mcp.constants.ts @@ -1,7 +1,9 @@ -import { Globe, Radio, Zap } from '@lucide/svelte'; -import { MCPTransportType } from '$lib/enums'; -import { MimeTypeImage } from '$lib/enums/files.enums'; -import type { ClientCapabilities, Implementation } from '$lib/types'; +import Globe from '@lucide/svelte/icons/globe'; +import Radio from '@lucide/svelte/icons/radio'; +import Zap from '@lucide/svelte/icons/zap'; +import { MimeTypeImage } from '#lib/enums/files.enums.ts'; +import { MCPTransportType } from '#lib/enums/index.ts'; +import type { ClientCapabilities, Implementation } from '#lib/types/index.ts'; import type { Component } from 'svelte'; export const DEFAULT_CLIENT_VERSION = '1.0.0'; diff --git a/tools/ui/src/lib/constants/mention-badge.constants.ts b/ui/apps/chat/src/lib/constants/mention-badge.constants.ts similarity index 90% rename from tools/ui/src/lib/constants/mention-badge.constants.ts rename to ui/apps/chat/src/lib/constants/mention-badge.constants.ts index f0873dc4a16b..e3534d008de3 100644 --- a/tools/ui/src/lib/constants/mention-badge.constants.ts +++ b/ui/apps/chat/src/lib/constants/mention-badge.constants.ts @@ -6,9 +6,9 @@ * scanner picks it up in both sources. */ export const MENTION_BADGE_CLASSNAME = - 'inline-flex w-fit shrink-0 items-center gap-1 whitespace-nowrap rounded-md border border-border/50 bg-foreground/5 px-1.5 py-0.5 text-xs font-mono text-foreground hover:bg-foreground/10 dark:bg-foreground/10 dark:text-secondary-foreground'; + 'inline-flex w-fit shrink-0 items-center gap-1 whitespace-nowrap rounded-md border border-border/50 bg-foreground/5 px-1.5 py-0.5 text-caption font-mono text-foreground hover:bg-foreground/10 dark:bg-foreground/10 dark:text-secondary-foreground'; -export const MENTION_BADGE_ICON_CLASSNAME = 'h-3 w-3 shrink-0'; +export const MENTION_BADGE_ICON_CLASSNAME = 'size-icon-xs shrink-0'; /** Regex flag that makes the mention scanner walk every link in a message instead of the first. */ export const MENTION_LINK_SCAN_FLAGS = 'g'; diff --git a/ui/apps/chat/src/lib/constants/mermaid-blocks.constants.ts b/ui/apps/chat/src/lib/constants/mermaid-blocks.constants.ts new file mode 100644 index 000000000000..379e85c77304 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/mermaid-blocks.constants.ts @@ -0,0 +1,28 @@ +export const MERMAID_WRAPPER_CLASS = 'mermaid-block-wrapper'; +export const MERMAID_SCROLL_CONTAINER_CLASS = 'mermaid-scroll-container'; +export const MERMAID_BLOCK_CLASS = 'mermaid'; +export const MERMAID_ERROR_CLASS = 'mermaid-error'; +// left plus right padding of a diagram's svg, see `pre.mermaid svg` in markdown-content.css +export const MERMAID_SVG_PADDING_X_REM = 2; + +// class Pele puts on the root of every diagram it draws +export const PELE_SVG_CLASS = 'pele'; +// the Pele colors app.css maps to the theme, written into a downloaded diagram +export const PELE_THEME_VARIABLES = [ + '--pele-bg', + '--pele-fg', + '--pele-muted', + '--pele-line', + '--pele-surface', + '--pele-surface-alt', + '--pele-border', + '--pele-accent', + '--pele-critical', + '--pele-radius' +] as const; + +export const MERMAID_LANGUAGE = 'mermaid'; + +export const MERMAID_SYNTAX_ATTR = 'data-mermaid-syntax'; +export const MERMAID_ID_ATTR = 'data-mermaid-id'; +export const MERMAID_RENDERED_ATTR = 'data-mermaid-rendered'; diff --git a/tools/ui/src/lib/constants/message-export.constants.ts b/ui/apps/chat/src/lib/constants/message-export.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/message-export.constants.ts rename to ui/apps/chat/src/lib/constants/message-export.constants.ts diff --git a/ui/apps/chat/src/lib/constants/model-compatibility.constants.ts b/ui/apps/chat/src/lib/constants/model-compatibility.constants.ts new file mode 100644 index 000000000000..e9ce54c4d8a7 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/model-compatibility.constants.ts @@ -0,0 +1,18 @@ +/** + * Model memory-fit constants. + * + * Mirrors the app's compatibility check (Model+Compatibility.swift): + * budget = RAM x RAM_BUDGET_RATIO - RAM_OVERHEAD_MB + * weightBytes = fileBytes x QUANT_WEIGHT + * a file fits when weightBytes <= budget. Kept here so the estimation util and + * any caller share one source. + */ + +export { + MB_PER_GB, + MEM_TIERS, + MIB_BYTES, + QUANT_WEIGHT, + RAM_BUDGET_RATIO, + RAM_OVERHEAD_MB +} from '@ggml-org/llama-ui/models'; diff --git a/tools/ui/src/lib/constants/model-id.constants.ts b/ui/apps/chat/src/lib/constants/model-id.constants.ts similarity index 98% rename from tools/ui/src/lib/constants/model-id.constants.ts rename to ui/apps/chat/src/lib/constants/model-id.constants.ts index d4ffc8b0ff0b..d40fe39d78aa 100644 --- a/tools/ui/src/lib/constants/model-id.constants.ts +++ b/ui/apps/chat/src/lib/constants/model-id.constants.ts @@ -2,7 +2,7 @@ * Parsing of `org/ModelName[-tag][:quant]` style model IDs. */ -import { ModelAuxSidecar, ModelDraftSidecar } from '$lib/enums'; +import { ModelAuxSidecar, ModelDraftSidecar } from '#lib/enums/index.ts'; /** Any sidecar file type: a draft variant or an auxiliary sidecar like mmproj. */ export type ModelSidecar = ModelDraftSidecar | ModelAuxSidecar; diff --git a/tools/ui/src/lib/constants/model-loading.constants.ts b/ui/apps/chat/src/lib/constants/model-loading.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/model-loading.constants.ts rename to ui/apps/chat/src/lib/constants/model-loading.constants.ts diff --git a/ui/apps/chat/src/lib/constants/models-discover-download.constants.ts b/ui/apps/chat/src/lib/constants/models-discover-download.constants.ts new file mode 100644 index 000000000000..dff1a29590e5 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/models-discover-download.constants.ts @@ -0,0 +1,39 @@ +/** + * Models Discover - download options constants: the serve `--spec-type` mapping, + * the bit-depth buckets, and the standalone command builder. + */ + +import { ModelDraftSidecar } from '#lib/enums/index.ts'; + +export { + BIT_DEPTH_LABEL_SUFFIX, + OTHER_BIT_DEPTH, + OTHER_BIT_DEPTH_LABEL +} from '@ggml-org/llama-ui/models'; + +/** + * `--spec-type` value for each draft sidecar. + */ +export const SPEC_TYPE: Record = { + [ModelDraftSidecar.DFLASH]: 'draft-dflash', + [ModelDraftSidecar.DSPARK]: 'draft-dspark', + [ModelDraftSidecar.EAGLE3]: 'draft-eagle3', + [ModelDraftSidecar.MTP]: 'draft-mtp' +}; + +/** + * Fixed tokens of the standalone `llama serve` command preview, so the command + * builder and its rendered spans share one source of the CLI spelling. + */ +export const SERVE_COMMAND = { + BIN: 'llama', + MODEL_FLAG: '-hf', + SPEC_TYPE_FLAG: '--spec-type', + SUBCOMMAND: 'serve' +} as const; + +/** Bit depth preferred for the command's default base quant. */ +export const DEFAULT_BASE_BIT_DEPTH = 4; + +/** Label shown for a draft-sidecar chip whose quant is unknown. */ +export const DRAFT_FILE_LABEL = 'draft'; diff --git a/tools/ui/src/lib/constants/models-discover.constants.ts b/ui/apps/chat/src/lib/constants/models-discover.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/models-discover.constants.ts rename to ui/apps/chat/src/lib/constants/models-discover.constants.ts diff --git a/tools/ui/src/lib/constants/models-manager.constants.ts b/ui/apps/chat/src/lib/constants/models-manager.constants.ts similarity index 89% rename from tools/ui/src/lib/constants/models-manager.constants.ts rename to ui/apps/chat/src/lib/constants/models-manager.constants.ts index e6165f8423f6..56a7788bf22e 100644 --- a/tools/ui/src/lib/constants/models-manager.constants.ts +++ b/ui/apps/chat/src/lib/constants/models-manager.constants.ts @@ -1,6 +1,6 @@ /** Labels of the models manager table sections. */ -import { ModelsTableGroupKind, ServerModelSource } from '$lib/enums'; +import { ModelsTableGroupKind, ServerModelSource } from '#lib/enums/index.ts'; export const MODELS_TABLE_GROUP_LABELS: Record = { [ModelsTableGroupKind.DOWNLOADING]: 'Downloading', @@ -12,7 +12,7 @@ export const MODELS_TABLE_GROUP_LABELS: Record = { /** * Sticky offset of a group heading under its section header: one section-header - * row (`py-2` over `text-[13px]` line height) minus the header's bottom border, + * row (`py-2` over `text-body-sm` line height) minus the header's bottom border, * so the two stacked sticky rows do not show a gap or overlap by a pixel. */ export const MODELS_TABLE_GROUP_STICKY_OFFSET = 'top: calc(2.25rem - 1px)'; diff --git a/tools/ui/src/lib/constants/path-display.constants.ts b/ui/apps/chat/src/lib/constants/path-display.constants.ts similarity index 95% rename from tools/ui/src/lib/constants/path-display.constants.ts rename to ui/apps/chat/src/lib/constants/path-display.constants.ts index fd10017613a6..486a672c1467 100644 --- a/tools/ui/src/lib/constants/path-display.constants.ts +++ b/ui/apps/chat/src/lib/constants/path-display.constants.ts @@ -7,7 +7,7 @@ * `[file:///abs/path](display)` payload back out on the UI side. */ -import { UrlProtocol } from '$lib/enums'; +import { UrlProtocol } from '#lib/enums/index.ts'; export const CWD_CHANGED_PREFIX = 'Set working directory to '; export const CWD_CLEARED_TEXT = 'Working directory cleared'; diff --git a/tools/ui/src/lib/constants/precision.constants.ts b/ui/apps/chat/src/lib/constants/precision.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/precision.constants.ts rename to ui/apps/chat/src/lib/constants/precision.constants.ts diff --git a/ui/apps/chat/src/lib/constants/pwa.constants.ts b/ui/apps/chat/src/lib/constants/pwa.constants.ts new file mode 100644 index 000000000000..734356fb72bc --- /dev/null +++ b/ui/apps/chat/src/lib/constants/pwa.constants.ts @@ -0,0 +1,277 @@ +/** + * Centralized PWA constants to avoid magic strings, regexes, and duplicated + * definitions across the codebase. + */ + +import { APP_NAME } from './app.constants'; + +export const MEDIA_QUERIES = { + COARSE_POINTER: '(pointer: coarse)', + DISPLAY_MODE_STANDALONE: '(display-mode: standalone)', + PREFERS_DARK: '(prefers-color-scheme: dark)', + PREFERS_LIGHT: '(prefers-color-scheme: light)' +} as const; + +export const THEME_COLORS = { + ACCENT_BLUE: '#2563eb', + ACCENT_BLUE_HOVER: '#1d4ed8', + BACKGROUND_DARK: '#111111', + BACKGROUND_LIGHT: 'white', + DARK: '#0d0d0d', + LIGHT: '#ffffff', + TITLE_UPDATE_ALERT: { + BG_DARK: 'zinc-800', + BG_LIGHT: 'white', + BORDER_DARK: 'zinc-700', + BORDER_LIGHT: 'zinc-200', + TEXT_DARK: 'zinc-400', + TEXT_LIGHT: 'zinc-500' + } +} as const; + +export const FAVICON_PATHS = { + ICO_DARK: 'favicon-dark.ico', + ICO_LIGHT: 'favicon.ico', + SVG_DARK: 'favicon-dark.svg', + SVG_LIGHT: 'favicon.svg' +} as const; + +export const FAVICON_SELECTORS = { + ICO_48X48: 'link[rel="icon"][sizes="48x48"]', + SVG_ANY: 'link[rel="icon"][type="image/svg+xml"]' +} as const; + +export const APPLE_ASSETS = { + TOUCH_ICON: 'apple-touch-icon-180x180.png' +} as const; + +export const PWA_MANIFEST = { + background_color: THEME_COLORS.BACKGROUND_LIGHT, + description: 'Local AI chat interface powered by llama.cpp', + display: 'standalone' as const, + icons: [ + { sizes: '64x64', src: 'pwa-64x64.png', type: 'image/png' }, + { sizes: '192x192', src: 'pwa-192x192.png', type: 'image/png' }, + { purpose: 'any' as const, sizes: '512x512', src: 'pwa-512x512.png', type: 'image/png' }, + { + purpose: 'maskable' as const, + sizes: '512x512', + src: 'maskable-icon-512x512.png', + type: 'image/png' + } + ], + lang: 'en', + name: APP_NAME, + scope: './', + short_name: APP_NAME, + start_url: './', + theme_color: THEME_COLORS.BACKGROUND_LIGHT +}; + +export const PWA_ICON_PATHS = { + MASKABLE_512: '/maskable-icon-512x512.png', + PWA_64: '/pwa-64x64.png', + PWA_192: '/pwa-192x192.png', + PWA_512: '/pwa-512x512.png' +} as const; + +/** Apple device dimensions (logical points) and DPR, from Apple HIG. */ +export const APPLE_DEVICES = { + '640x1136': { dpr: 2, height: 568, width: 320 }, // iPhone 6/7/8 Plus + '744x1133': { dpr: 2, height: 573, width: 376 }, // iPad mini 8.3" + '750x1334': { dpr: 2, height: 667, width: 375 }, // iPhone 6/7/8, 14 + '1032x1376': { dpr: 2, height: 1376, width: 1032 }, // iPad Air 13" + // iPhones (DPR 3) + '1170x2532': { dpr: 3, height: 844, width: 390 }, // iPhone 13, 15 + '1179x2556': { dpr: 3, height: 852, width: 393 }, // iPhone 14, 15 Pro, 16 + '1206x2622': { dpr: 3, height: 874, width: 402 }, // iPhone 16 Plus, 16e + '1284x2778': { dpr: 3, height: 926, width: 428 }, // iPhone 15 Plus + '1290x2796': { dpr: 3, height: 932, width: 430 }, // iPhone 15 Pro Max, 16 Pro + '1320x2868': { dpr: 3, height: 956, width: 440 }, // iPhone 16 Pro Max + '1640x2360': { dpr: 2, height: 1180, width: 820 }, // iPad Air 10.9" + // iPads (DPR 2) + '1668x2388': { dpr: 2, height: 1194, width: 834 }, // iPad Air 11", iPad 11" + '2048x2732': { dpr: 2, height: 1366, width: 1024 } // iPad Pro 12.9" +} as const; + +export type AppleDeviceKey = keyof typeof APPLE_DEVICES; + +export const PWA_FILE_PATHS = { + LEGACY_SERVICE_WORKER: '/sw.js', + MANIFEST: '/manifest.webmanifest', + SERVICE_WORKER: '/service-worker.js' +} as const; + +/** The Vite plugin that serves manifest.webmanifest in dev and emits it with the build */ +export const PWA_MANIFEST_PLUGIN = { + /** Media type of a web app manifest (W3C Web App Manifest) */ + CONTENT_TYPE: 'application/manifest+json', + /** Vite environment that builds the browser bundle, the one the manifest goes with */ + ENVIRONMENT: 'client', + NAME: 'llamacpp:pwa-manifest' +} as const; + +// Used by the server middleware to skip API key validation. +// Keep in sync with tools/server/server-http.cpp public_endpoints list. + +export const PUBLIC_ENDPOINTS = [ + '/health', + '/v1/health', + '/models', + '/v1/models', + '/props', + '/metrics', + '/', + '/index.html', + + '/favicon.ico', + '/favicon-dark.ico', + '/favicon.svg', + '/favicon-dark.svg', + '/pwa-64x64.png', + '/pwa-192x192.png', + '/pwa-512x512.png', + '/maskable-icon-512x512.png', + '/apple-touch-icon-180x180.png', + '/apple-splash-portrait-640x1136.png', + '/apple-splash-landscape-640x1136.png', + '/apple-splash-portrait-750x1334.png', + '/apple-splash-landscape-750x1334.png', + '/apple-splash-portrait-1170x2532.png', + '/apple-splash-landscape-1170x2532.png', + '/apple-splash-portrait-1179x2556.png', + '/apple-splash-landscape-1179x2556.png', + '/apple-splash-portrait-1206x2622.png', + '/apple-splash-landscape-1206x2622.png', + '/apple-splash-portrait-1284x2778.png', + '/apple-splash-landscape-1284x2778.png', + '/apple-splash-portrait-1290x2796.png', + '/apple-splash-landscape-1290x2796.png', + '/apple-splash-portrait-1320x2868.png', + '/apple-splash-landscape-1320x2868.png', + '/apple-splash-portrait-1488x2266.png', + '/apple-splash-landscape-1488x2266.png', + '/apple-splash-portrait-1640x2360.png', + '/apple-splash-landscape-1640x2360.png', + '/apple-splash-portrait-1668x2388.png', + '/apple-splash-landscape-1668x2388.png', + '/apple-splash-portrait-2048x2732.png', + '/apple-splash-landscape-2048x2732.png', + '/apple-splash-portrait-dark-640x1136.png', + '/apple-splash-landscape-dark-640x1136.png', + '/apple-splash-portrait-dark-750x1334.png', + '/apple-splash-landscape-dark-750x1334.png', + '/apple-splash-portrait-dark-1170x2532.png', + '/apple-splash-landscape-dark-1170x2532.png', + '/apple-splash-portrait-dark-1179x2556.png', + '/apple-splash-landscape-dark-1179x2556.png', + '/apple-splash-portrait-dark-1206x2622.png', + '/apple-splash-landscape-dark-1206x2622.png', + '/apple-splash-portrait-dark-1284x2778.png', + '/apple-splash-landscape-dark-1284x2778.png', + '/apple-splash-portrait-dark-1290x2796.png', + '/apple-splash-landscape-dark-1290x2796.png', + '/apple-splash-portrait-dark-1320x2868.png', + '/apple-splash-landscape-dark-1320x2868.png', + '/apple-splash-portrait-dark-1488x2266.png', + '/apple-splash-landscape-dark-1488x2266.png', + '/apple-splash-portrait-dark-1640x2360.png', + '/apple-splash-landscape-dark-1640x2360.png', + '/apple-splash-portrait-dark-1668x2388.png', + '/apple-splash-landscape-dark-1668x2388.png', + '/apple-splash-portrait-dark-2048x2732.png', + '/apple-splash-landscape-dark-2048x2732.png', + '/manifest.webmanifest', + '/service-worker.js', + '/sw.js', + '/version.json' +] as const; + +export const BUILD_CONFIG = { + GUIDE_COMMENT: ` + +`.trim(), + OUTPUT_DIR: './dist' +} as const; + +export const REGEX_PATTERNS = { + HEAD_CLOSE: /\t*<\/head>/, + SPLASH_FILE: /^apple-splash-(portrait|landscape)-(dark-)?(\d+)x(\d+)\.png$/ +} as const; + +// Device names used by @vite-pwa/assets-generator for splash screen generation. +// Keep in sync with pwa-assets.config.ts. +export const PWA_GENERATOR_DEVICES = [ + 'iPhone 13', + 'iPhone 13 Pro', + 'iPhone 13 Pro Max', + 'iPhone 14', + 'iPhone 14 Plus', + 'iPhone 14 Pro', + 'iPhone 14 Pro Max', + 'iPhone 15', + 'iPhone 15 Plus', + 'iPhone 15 Pro', + 'iPhone 15 Pro Max', + 'iPhone 16', + 'iPhone 16 Plus', + 'iPhone 16 Pro', + 'iPhone 16 Pro Max', + 'iPhone 16e', + 'iPhone SE 4"', + 'iPhone SE 4.7"', + 'iPad 11"', + 'iPad Air 10.9"', + 'iPad Air 11"', + 'iPad Air 13"', + 'iPad Pro 11"', + 'iPad Pro 12.9"', + 'iPad mini 8.3"' +] as const; + +// PWA assets generator configuration — used by pwa-assets.config.ts +// FAVICON_PADDING: fraction (0..1) of the icon reserved as equal margin on +// each side of the icon PNG/ICO outputs. 0, because llama-brand's favicons +// already carry their margin and optical centring. +export const PWA_ASSET_GENERATOR = { + ADD_MEDIA_SCREEN: true, + BASE_PATH: './', + DARK_PREFIX: 'dark-', + FAVICON_PADDING: 0, + FIT_MODE: 'contain', + LINK_PRESET: '2023', + PNG_COMPRESSION_LEVEL: 9, + PNG_QUALITY: 60, + SPLASH_PADDING: 0.75, + XHTML: false +} as const; + +export const SW_CONFIG = { + /** How long the update waits for the new worker to install and activate before reloading */ + ACTIVATE_TIMEOUT_MS: 10000, + CHECK_INTERVAL_MS: 60000, + UPDATE_FETCH_OPTIONS: { + CACHE: 'no-store', + HEADERS: { + CACHE: 'no-store', + CACHE_CONTROL: 'no-cache' + } + } +} as const; + +export const APPLE_META_TAGS = { + MOBILE_WEB_APP_CAPABLE: { content: 'yes', name: 'apple-mobile-web-app-capable' }, + MOBILE_WEB_APP_TITLE: { name: 'apple-mobile-web-app-title' }, + STATUS_BAR_STYLE: { content: 'black-translucent', name: 'apple-mobile-web-app-status-bar-style' } +} as const; + +// Splash screen HTML link tag prefix used by generateSplashScreenLinks +export const SPLASH_LINK = { + DARK_MEDIA_SUFFIX: ' and (prefers-color-scheme: dark)', + HTML: ' capture group 1 is `12345`. */ +export const READ_MEDIA_SIZE_REGEX = new RegExp(`^${PREFIX_SIZE}\\s*(\\d+)\\s*bytes`); + +/** Image extensions the tool accepts. The server decodes images with stb_image, which has no webp or tiff. */ +export const READ_MEDIA_IMAGE_MIME: Record = { + gif: MimeTypeImage.GIF, + jpeg: MimeTypeImage.JPEG, + jpg: MimeTypeImage.JPEG, + png: MimeTypeImage.PNG +} as const; + +/** Audio extensions the tool accepts. The `input_audio` API only takes wav and mp3. */ +export const READ_MEDIA_AUDIO_MIME: Record = { + mp3: MimeTypeAudio.MP3_MPEG, + wav: MimeTypeAudio.WAV +} as const; + +/** + * Build the read_media tool definition for the modalities the active model has. + * At least one of the two flags must be true, otherwise the tool is not offered + * at all - a model that cannot see or hear has nothing to do with the bytes. + */ +export function buildReadMediaToolDefinition( + supportsVision: boolean, + supportsAudio: boolean +): OpenAIToolDefinition { + const kinds: string[] = []; + + if (supportsVision) kinds.push(`images (${Object.keys(READ_MEDIA_IMAGE_MIME).join(', ')})`); + + if (supportsAudio) kinds.push(`audio (${Object.keys(READ_MEDIA_AUDIO_MIME).join(', ')})`); + + return { + function: { + description: `Read a media file and attach it to the conversation so it can be perceived directly. Supports ${kinds.join(' and ')}.`, + name: READ_MEDIA_TOOL_NAME, + parameters: { + properties: { + path: { + description: 'Path to the media file', + type: JsonSchemaType.STRING + } + }, + required: ['path'], + type: JsonSchemaType.OBJECT + } + }, + type: ToolCallType.FUNCTION + }; +} diff --git a/tools/ui/src/lib/constants/reasoning-effort.constants.ts b/ui/apps/chat/src/lib/constants/reasoning-effort.constants.ts similarity index 92% rename from tools/ui/src/lib/constants/reasoning-effort.constants.ts rename to ui/apps/chat/src/lib/constants/reasoning-effort.constants.ts index 8d3c23f630d7..bafda1a69c15 100644 --- a/tools/ui/src/lib/constants/reasoning-effort.constants.ts +++ b/ui/apps/chat/src/lib/constants/reasoning-effort.constants.ts @@ -1,5 +1,5 @@ -import { ReasoningEffort } from '$lib/enums'; -import type { ReasoningEffortLevel } from '$lib/types'; +import { ReasoningEffort } from '#lib/enums/index.ts'; +import type { ReasoningEffortLevel } from '#lib/types/index.ts'; /** * Reasoning effort UI labels. diff --git a/tools/ui/src/lib/constants/recommended-mcp-servers.constants.ts b/ui/apps/chat/src/lib/constants/recommended-mcp-servers.constants.ts similarity index 95% rename from tools/ui/src/lib/constants/recommended-mcp-servers.constants.ts rename to ui/apps/chat/src/lib/constants/recommended-mcp-servers.constants.ts index 6a550ee96930..990aff2ac819 100644 --- a/tools/ui/src/lib/constants/recommended-mcp-servers.constants.ts +++ b/ui/apps/chat/src/lib/constants/recommended-mcp-servers.constants.ts @@ -1,4 +1,4 @@ -import type { RecommendedMCPServer } from '$lib/types'; +import type { RecommendedMCPServer } from '#lib/types/index.ts'; // Suggested MCP servers shown as opt-in cards in the "Add New Server" dialog. // Rendering these cards never reaches the upstream domain - favicons come diff --git a/tools/ui/src/lib/constants/routes.constants.ts b/ui/apps/chat/src/lib/constants/routes.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/routes.constants.ts rename to ui/apps/chat/src/lib/constants/routes.constants.ts diff --git a/tools/ui/src/lib/constants/sandbox.constants.ts b/ui/apps/chat/src/lib/constants/sandbox.constants.ts similarity index 86% rename from tools/ui/src/lib/constants/sandbox.constants.ts rename to ui/apps/chat/src/lib/constants/sandbox.constants.ts index 68462a23d7a4..bca3905b6be4 100644 --- a/tools/ui/src/lib/constants/sandbox.constants.ts +++ b/ui/apps/chat/src/lib/constants/sandbox.constants.ts @@ -1,4 +1,4 @@ -import { BuiltInTool } from '$lib/enums'; +import { BuiltInTool } from '#lib/enums/index.ts'; export const SANDBOX_TOOL_NAME = BuiltInTool.BROWSER_RUN_JAVASCRIPT; diff --git a/ui/apps/chat/src/lib/constants/search-chats.ts b/ui/apps/chat/src/lib/constants/search-chats.ts new file mode 100644 index 000000000000..2d958eafe70e --- /dev/null +++ b/ui/apps/chat/src/lib/constants/search-chats.ts @@ -0,0 +1,127 @@ +import { + BuiltInTool, + JsonSchemaType, + SearchChatsMessageSelection, + SearchChatsOrder, + ToolCallType, + ToolSource +} from '#lib/enums/index.ts'; +import type { OpenAIToolDefinition } from '#lib/types/index.ts'; + +export const SEARCH_CHATS_TOOL_NAME = BuiltInTool.BROWSER_SEARCH_CHATS; + +/** Key of the tool in the disabled tools lists, same format as toolsStore.toolKey */ +export const SEARCH_CHATS_TOOL_KEY = `${ToolSource.BROWSER}:${SEARCH_CHATS_TOOL_NAME}`; + +export const SEARCH_CHATS_OUTPUT_MAX_CHARS = 8192; + +export const SEARCH_CHATS_LIMIT_CHATS_DEFAULT = 10; +export const SEARCH_CHATS_LIMIT_CHATS_MAX = 1000; + +export const SEARCH_CHATS_LIMIT_MESSAGES_DEFAULT = 5; +export const SEARCH_CHATS_LIMIT_MESSAGES_MAX = 100; + +export const SEARCH_CHATS_MESSAGE_CHARS_DEFAULT = 600; +export const SEARCH_CHATS_MESSAGE_CHARS_MIN = 50; +export const SEARCH_CHATS_MESSAGE_CHARS_MAX = 4000; + +export const SEARCH_CHATS_MAX_PATTERNS = 10; +export const SEARCH_CHATS_MAX_IDS = 100; + +/** Matching cost grows with pattern length times text length, and runs on the main thread */ +export const SEARCH_CHATS_PATTERN_MAX_CHARS = 200; +export const SEARCH_CHATS_ID_MAX_CHARS = 200; + +/** A match past this share of the excerpt length moves the excerpt window to the match */ +export const SEARCH_CHATS_EXCERPT_RECENTER_RATIO = 0.6; + +/** Share of the excerpt shown before the match when the window is moved */ +export const SEARCH_CHATS_EXCERPT_LEAD_RATIO = 1 / 3; + +export const SEARCH_CHATS_ELLIPSIS = '...'; + +export const SEARCH_CHATS_FIELD_SEPARATOR = ' | '; + +export const SEARCH_CHATS_CUT_NOTICE = + '[messages cut to fit: lower limit_messages or max_message_chars]'; + +/** `2026-11-10`, read as local midnight */ +export const SEARCH_CHATS_DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/; + +/** `2026-11-10T14:30`, optional seconds, fraction and offset; local time without an offset */ +export const SEARCH_CHATS_DATE_TIME_REGEX = + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})?$/; + +const DESCRIPTION = `Find and read the user's other saved chats (read-only). The current chat is hidden, you already see it. +Returns chats, each with messages from what the user saw: user and assistant text only (tool output is skipped), numbered #1..#N in chat order. Dates are in the user's local time. +- List chats: limit_messages=0 gives one line per chat (title, conv_id, date); raise limit_chats and page with offset_chats. +- Find chats: by_matches=["%paris%", "%eiffel%"] matches the title or any message (case-insensitive, % = any text, _ = one char, no % means "contains"). A chat matches if any pattern does. For AND within a message use "%a%b%" (order matters, add "%b%a%" for either order). +- Read chats: by_conv_ids=[""] with message_selection "latest" (default) or "earliest". +- Time range: from_timestamp (inclusive) and to_timestamp (exclusive), ISO 8601 like 2026-11-10 or 2026-11-10T14:30, local time. Only messages in the range are searched and shown, and only chats with messages in it are returned. With from_timestamp, message_selection defaults to "earliest". +Example, "what was my last question in the chat about paris?": by_matches=["%paris%"], message_selection="latest", limit_messages=4, then answer from the last user message. +Example, "what did we talk about yesterday?": from_timestamp=, to_timestamp=, limit_messages=2.`; + +export function buildSearchChatsToolDefinition(): OpenAIToolDefinition { + return { + function: { + description: DESCRIPTION, + name: SEARCH_CHATS_TOOL_NAME, + parameters: { + properties: { + by_conv_ids: { + description: 'Only these chats, by conv_id', + items: { type: JsonSchemaType.STRING }, + type: JsonSchemaType.ARRAY + }, + by_matches: { + description: `LIKE patterns matched against titles and message text, any of them, max ${SEARCH_CHATS_PATTERN_MAX_CHARS} chars each`, + items: { type: JsonSchemaType.STRING }, + type: JsonSchemaType.ARRAY + }, + from_timestamp: { + description: + 'Only messages at or after this time, ISO 8601, local time unless an offset is given', + type: JsonSchemaType.STRING + }, + include_current: { + description: 'Also include the current chat, default false', + type: JsonSchemaType.BOOLEAN + }, + limit_chats: { + description: `Max chats, default ${SEARCH_CHATS_LIMIT_CHATS_DEFAULT}, max ${SEARCH_CHATS_LIMIT_CHATS_MAX}`, + type: JsonSchemaType.NUMBER + }, + limit_messages: { + description: `Messages per chat, default ${SEARCH_CHATS_LIMIT_MESSAGES_DEFAULT}, max ${SEARCH_CHATS_LIMIT_MESSAGES_MAX}; 0 lists chats only`, + type: JsonSchemaType.NUMBER + }, + max_message_chars: { + description: `Characters shown per message, default ${SEARCH_CHATS_MESSAGE_CHARS_DEFAULT}, max ${SEARCH_CHATS_MESSAGE_CHARS_MAX}`, + type: JsonSchemaType.NUMBER + }, + message_selection: { + description: `Which messages per chat; default "${SearchChatsMessageSelection.MATCHING}" with by_matches, else "${SearchChatsMessageSelection.EARLIEST}" with from_timestamp, else "${SearchChatsMessageSelection.LATEST}"`, + enum: Object.values(SearchChatsMessageSelection), + type: JsonSchemaType.STRING + }, + offset_chats: { + description: 'Skip this many chats, for paging', + type: JsonSchemaType.NUMBER + }, + order_timestamp: { + description: `Chat order by last activity, default "${SearchChatsOrder.DESC}" (newest first)`, + enum: Object.values(SearchChatsOrder), + type: JsonSchemaType.STRING + }, + to_timestamp: { + description: + 'Only messages before this time (exclusive), same format as from_timestamp', + type: JsonSchemaType.STRING + } + }, + type: JsonSchemaType.OBJECT + } + }, + type: ToolCallType.FUNCTION + }; +} diff --git a/tools/ui/src/lib/constants/settings-keys.constants.ts b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts similarity index 85% rename from tools/ui/src/lib/constants/settings-keys.constants.ts rename to ui/apps/chat/src/lib/constants/settings-keys.constants.ts index 910f492a386d..5bb1bb4ec12e 100644 --- a/tools/ui/src/lib/constants/settings-keys.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts @@ -57,6 +57,7 @@ export const SETTINGS_KEYS = { SHOW_AGENTIC_TURN_STATS: 'showAgenticTurnStats', SHOW_BUILD_VERSION: 'showBuildVersion', SHOW_FULL_PATH_IN_MENTIONS: 'showFullPathInMentions', + SHOW_MCP: 'showMcp', // Display SHOW_MESSAGE_STATS: 'showMessageStats', SHOW_MODEL_CAPABILITIES_IN_SELECTOR: 'showModelCapabilitiesInSelector', @@ -64,12 +65,14 @@ export const SETTINGS_KEYS = { SHOW_MODEL_ORG_NAME_ON_MOBILE: 'showModelOrgNameOnMobile', SHOW_MODEL_QUANTIZATION: 'showModelQuantization', SHOW_MODEL_TAGS: 'showModelTags', + SHOW_MODELS_MANAGER: 'showModelsManager', SHOW_RAW_MODEL_NAMES: 'showRawModelNames', SHOW_RAW_OUTPUT_SWITCH: 'showRawOutputSwitch', SHOW_SYSTEM_MESSAGE: 'showSystemMessage', SHOW_THOUGHT_IN_PROGRESS: 'showThoughtInProgress', SHOW_TOOL_CALL_IN_PROGRESS: 'showToolCallInProgress', SINGLE_ROW_CHAT_FORM: 'singleRowChatForm', + SURFACE_THEME: 'surfaceTheme', SYMBOLIC_MATH_ENABLED: 'symbolicMathEnabled', SYSTEM_MESSAGE: 'systemMessage', // Sampling @@ -84,6 +87,17 @@ export const SETTINGS_KEYS = { TYP_P: 'typ_p', // General USE_HUGGING_FACE_HUB: 'useHuggingFaceHub', + // Voice + VOICE_AUTO_GAIN: 'voiceAutoGain', + VOICE_BOOST: 'voiceBoost', + VOICE_COLLAPSE_TRANSCRIPTS: 'voiceCollapseTranscripts', + VOICE_ECHO_CANCELLATION: 'voiceEchoCancellation', + VOICE_INPUT_MODE: 'voiceInputMode', + VOICE_MICROPHONE: 'voiceMicrophone', + VOICE_NOISE_SUPPRESSION: 'voiceNoiseSuppression', + VOICE_TRANSCRIBE_MESSAGES: 'voiceTranscribeMessages', + VOICE_TRANSCRIPTION_LANGUAGE: 'voiceTranscriptionLanguage', + VOICE_TRANSCRIPTION_MODEL: 'voiceTranscriptionModel', XTC_PROBABILITY: 'xtc_probability', XTC_THRESHOLD: 'xtc_threshold' } as const; diff --git a/tools/ui/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts similarity index 80% rename from tools/ui/src/lib/constants/settings.constants.ts rename to ui/apps/chat/src/lib/constants/settings.constants.ts index 9fd0832e10a2..4df67abefb18 100644 --- a/tools/ui/src/lib/constants/settings.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings.constants.ts @@ -4,28 +4,33 @@ import { COMPACTION } from './compaction.constants'; import { DEFAULT_MCP_CONFIG } from './mcp.constants'; import { SETTINGS_KEYS } from './settings-keys.constants'; import { TITLE_GENERATION } from './title-generation.constants'; +import { VOICE_TRANSCRIPTION_MODEL_AUTO } from './voice.constants'; import { FILE_GLOB_SEARCH_PICKERS } from './working-directory.constants'; -import { - Code, - Database, - Funnel, - ListRestart, - Monitor, - Moon, - PencilRuler, - SlidersVertical, - Sun -} from '@lucide/svelte'; -import { SyncableParameterType } from '$lib/enums'; -import { SettingsFieldType } from '$lib/enums/settings.enums'; -import { ColorMode } from '$lib/enums/ui.enums'; +import { VOICE_MICROPHONE_AUTO } from '@ggml-org/llama-voice'; +import AudioLines from '@lucide/svelte/icons/audio-lines'; +import Code from '@lucide/svelte/icons/code'; +import Database from '@lucide/svelte/icons/database'; +import File from '@lucide/svelte/icons/file'; +import Funnel from '@lucide/svelte/icons/funnel'; +import GlassWater from '@lucide/svelte/icons/glass-water'; +import ListRestart from '@lucide/svelte/icons/list-restart'; +import Mic from '@lucide/svelte/icons/mic'; +import Monitor from '@lucide/svelte/icons/monitor'; +import Moon from '@lucide/svelte/icons/moon'; +import PencilRuler from '@lucide/svelte/icons/pencil-ruler'; +import SlidersVertical from '@lucide/svelte/icons/sliders-vertical'; +import Sun from '@lucide/svelte/icons/sun'; +import TextCursorInput from '@lucide/svelte/icons/text-cursor-input'; +import { SurfaceTheme, SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts'; +import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; +import { ColorMode } from '#lib/enums/ui.enums.ts'; import type { SettingsConfigValue, SettingsEntry, SettingsFieldConfig, SettingsSection, SettingsSectionEntry -} from '$lib/types'; +} from '#lib/types/index.ts'; /** Settings sections — slug is the routing identity, title is the display label. */ export const SETTINGS_SECTIONS = { @@ -35,7 +40,8 @@ export const SETTINGS_SECTIONS = { GENERAL: { slug: 'general', title: 'General' }, IMPORT_EXPORT: { slug: 'import-export', title: 'Import/Export' }, SAMPLING_PENALTIES: { slug: 'sampling-penalties', title: 'Sampling & Penalties' }, - TOOLS: { slug: 'tools', title: 'Tools' } + TOOLS: { slug: 'tools', title: 'Tools' }, + VOICE: { slug: 'voice', title: 'Voice' } } as const; export const SETTINGS_SECTION_SLUGS = { @@ -45,7 +51,8 @@ export const SETTINGS_SECTION_SLUGS = { GENERAL: SETTINGS_SECTIONS.GENERAL.slug, IMPORT_EXPORT: SETTINGS_SECTIONS.IMPORT_EXPORT.slug, SAMPLING_PENALTIES: SETTINGS_SECTIONS.SAMPLING_PENALTIES.slug, - TOOLS: SETTINGS_SECTIONS.TOOLS.slug + TOOLS: SETTINGS_SECTIONS.TOOLS.slug, + VOICE: SETTINGS_SECTIONS.VOICE.slug } as const; export const SETTINGS_SECTION_TITLES = { @@ -55,7 +62,8 @@ export const SETTINGS_SECTION_TITLES = { GENERAL: SETTINGS_SECTIONS.GENERAL.title, IMPORT_EXPORT: SETTINGS_SECTIONS.IMPORT_EXPORT.title, SAMPLING_PENALTIES: SETTINGS_SECTIONS.SAMPLING_PENALTIES.title, - TOOLS: SETTINGS_SECTIONS.TOOLS.title + TOOLS: SETTINGS_SECTIONS.TOOLS.title, + VOICE: SETTINGS_SECTIONS.VOICE.title } as const; export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ @@ -75,6 +83,17 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ ], type: SettingsFieldType.SELECT }, + { + defaultValue: SurfaceTheme.PAPER, + help: 'Choose how the light theme draws its surfaces: Paper puts white panels, fields and buttons on a faint grey page; Matte puts grey glass on a white page. Dark mode is the same for both.', + key: SETTINGS_KEYS.SURFACE_THEME, + label: 'Light surfaces', + options: [ + { icon: File, label: 'Paper', value: SurfaceTheme.PAPER }, + { icon: GlassWater, label: 'Matte', value: SurfaceTheme.MATTE } + ], + type: SettingsFieldType.SELECT + }, { defaultValue: '', help: `Set the API Key if you are using ${CLI_FLAGS.API_KEY} option for the server.`, @@ -113,7 +132,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ type: SettingsFieldType.CHECKBOX }, { - defaultValue: true, + defaultValue: false, help: 'Render the markdown in the message input as you write it: every line but the one you are on shows as it will look in the conversation. When disabled, the input shows the plain markdown text.', key: SETTINGS_KEYS.LIVE_MARKDOWN_PREVIEW, label: 'Live markdown preview in the message input', @@ -121,7 +140,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ }, { defaultValue: true, - help: 'Automatically show microphone button instead of send button when textarea is empty for models with audio modality support.', + help: 'Show the microphone beside the send button while the message is empty, whenever voice input is available (see Voice).', key: SETTINGS_KEYS.AUTO_MIC_ON_EMPTY, label: 'Show microphone on empty input', type: SettingsFieldType.CHECKBOX @@ -136,7 +155,14 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ }, { defaultValue: false, - help: 'Show the Discover Models sidebar action to browse and download HuggingFace GGUF models. Turns the Hugging Face Hub API on while it is enabled. Only available in router mode.', + help: 'Show Models in the sidebar and "Manage models" in the model selector, to see, load and configure the models on the server.', + key: SETTINGS_KEYS.SHOW_MODELS_MANAGER, + label: 'Show Models', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: false, + help: 'Show Discover Models on the Models page, to browse and download HuggingFace GGUF models. Turns Models and the Hugging Face Hub API on while it is enabled. Only available in router mode.', key: SETTINGS_KEYS.ENABLE_DISCOVER_MODELS, label: 'Enable Discover Models', type: SettingsFieldType.CHECKBOX @@ -148,6 +174,13 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ label: 'Use the Hugging Face Hub API', type: SettingsFieldType.CHECKBOX }, + { + defaultValue: false, + help: 'Show MCP in the sidebar, to add and manage MCP servers. Servers already added keep working while it is hidden.', + key: SETTINGS_KEYS.SHOW_MCP, + label: 'Show MCP', + type: SettingsFieldType.CHECKBOX + }, { defaultValue: true, help: 'Choose how conversation titles are generated. The first non-empty line uses a fast deterministic rule; the LLM option uses a model-generated title from the first message exchange.', @@ -307,7 +340,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ type: SettingsFieldType.CHECKBOX }, { - defaultValue: true, + defaultValue: false, help: 'Show open chats as browser-style tabs above the conversation, one per open chat. When disabled, only one chat is shown at a time.', key: SETTINGS_KEYS.CONVERSATION_TABS, label: 'Conversation tabs', @@ -380,6 +413,91 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ slug: SETTINGS_SECTION_SLUGS.DISPLAY, title: SETTINGS_SECTION_TITLES.DISPLAY }, + // Voice: the transcription model picker lists the server's models (SettingsChatVoiceTab) + { + icon: Mic, + settings: [ + { + defaultValue: VoiceInputMode.AUTO, + help: 'Automatic sends your voice to a model that understands audio, as a voice message with its transcript, and turns it into text in the message input for any other model. Always dictate turns it into text for every model, so only the text reaches the chat.', + key: SETTINGS_KEYS.VOICE_INPUT_MODE, + label: 'Voice input', + options: [ + { icon: AudioLines, label: 'Automatic', value: VoiceInputMode.AUTO }, + { icon: TextCursorInput, label: 'Always dictate', value: VoiceInputMode.DICTATION } + ], + type: SettingsFieldType.SELECT + }, + { + defaultValue: VOICE_TRANSCRIPTION_MODEL_AUTO, + help: 'The model that turns speech into text when the chat model has no audio input. Automatic uses a model with audio input that is already loaded, so dictating loads nothing.', + key: SETTINGS_KEYS.VOICE_TRANSCRIPTION_MODEL, + label: 'Transcription model', + standaloneField: false, + type: SettingsFieldType.SELECT + }, + { + defaultValue: VOICE_MICROPHONE_AUTO, + help: "The microphone you record from. Automatic takes the system's default one, unless that is a Bluetooth headset's: recording from it switches the headset to its call mode, which plays music in low quality, so the built-in microphone is used instead.", + key: SETTINGS_KEYS.VOICE_MICROPHONE, + label: 'Microphone', + standaloneField: false, + type: SettingsFieldType.SELECT + }, + { + defaultValue: true, + help: 'Write down what was said in each voice message, to read under its waveform. The chat model writes it, and a model without audio input gets it in place of the audio.', + key: SETTINGS_KEYS.VOICE_TRANSCRIBE_MESSAGES, + label: 'Transcribe voice messages', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: false, + help: 'Show the transcript of a voice message folded under its waveform, to open on hover or with a tap, instead of open.', + key: SETTINGS_KEYS.VOICE_COLLAPSE_TRANSCRIPTS, + label: 'Collapse transcripts', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: true, + help: 'Raise quiet speech to a level the model hears well, up to eight times louder, so a quiet microphone or a voice from afar is still understood. Only speech is measured, never the silence around it, and loud speech is left as it is.', + key: SETTINGS_KEYS.VOICE_BOOST, + label: 'Boost quiet speech', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: false, + help: 'Let the browser filter background noise out of what the microphone records. Off, the model gets the raw signal, which speech models take well.', + key: SETTINGS_KEYS.VOICE_NOISE_SUPPRESSION, + label: 'Noise suppression', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: false, + help: 'Let the browser remove what your speakers play from the recording. It makes the system treat a recording as a call, which can lower or pause music and other sound while you record.', + key: SETTINGS_KEYS.VOICE_ECHO_CANCELLATION, + label: 'Echo cancellation', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: false, + help: 'Let the browser even out how loud you sound. It fades the microphone in, so the first words of a recording can come out quiet.', + key: SETTINGS_KEYS.VOICE_AUTO_GAIN, + label: 'Automatic gain', + type: SettingsFieldType.CHECKBOX + }, + { + defaultValue: '', + help: 'The language you speak, as a two-letter code such as en or de, passed to the transcription. Leave it empty to let the model tell.', + key: SETTINGS_KEYS.VOICE_TRANSCRIPTION_LANGUAGE, + label: 'Transcription language', + placeholder: 'Automatic', + type: SettingsFieldType.INPUT + } + ], + slug: SETTINGS_SECTION_SLUGS.VOICE, + title: SETTINGS_SECTION_TITLES.VOICE + }, // MCP Servers (non-UI config object) { icon: PencilRuler, diff --git a/tools/ui/src/lib/constants/special-characters.constants.ts b/ui/apps/chat/src/lib/constants/special-characters.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/special-characters.constants.ts rename to ui/apps/chat/src/lib/constants/special-characters.constants.ts diff --git a/tools/ui/src/lib/constants/storage.constants.ts b/ui/apps/chat/src/lib/constants/storage.constants.ts similarity index 96% rename from tools/ui/src/lib/constants/storage.constants.ts rename to ui/apps/chat/src/lib/constants/storage.constants.ts index 463f0a68b8e5..1b10507dd491 100644 --- a/tools/ui/src/lib/constants/storage.constants.ts +++ b/ui/apps/chat/src/lib/constants/storage.constants.ts @@ -60,9 +60,6 @@ export const DEPRECATED_FAVORITE_MODELS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME_D /** @deprecated Use {@link USER_OVERRIDES_LOCALSTORAGE_KEY} instead */ export const DEPRECATED_USER_OVERRIDES_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME_DEPRECATED}.userOverrides`; -/** Build version stored in localStorage for non-PWA update detection */ -export const BUILD_VERSION_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.buildVersion`; - /** Maps new keys to their deprecated fallback keys */ export const NEW_TO_DEPRECATED_MAP: Record = { [ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY]: DEPRECATED_ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY, diff --git a/tools/ui/src/lib/constants/stream.constants.ts b/ui/apps/chat/src/lib/constants/stream.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/stream.constants.ts rename to ui/apps/chat/src/lib/constants/stream.constants.ts diff --git a/tools/ui/src/lib/constants/supported-file-types.constants.ts b/ui/apps/chat/src/lib/constants/supported-file-types.constants.ts similarity index 98% rename from tools/ui/src/lib/constants/supported-file-types.constants.ts rename to ui/apps/chat/src/lib/constants/supported-file-types.constants.ts index 255b762ff3e4..88ca4145f3f3 100644 --- a/tools/ui/src/lib/constants/supported-file-types.constants.ts +++ b/ui/apps/chat/src/lib/constants/supported-file-types.constants.ts @@ -3,6 +3,7 @@ * Organized by category with TypeScript enums for better type safety */ +import { FileExtensionVideo, FileTypeVideo } from '#lib/enums/files.enums.ts'; import { FileExtensionAudio, FileExtensionImage, @@ -17,8 +18,7 @@ import { MimeTypeImage, MimeTypeText, MimeTypeVideo -} from '$lib/enums'; -import { FileExtensionVideo, FileTypeVideo } from '$lib/enums/files.enums'; +} from '#lib/enums/index.ts'; // File type configuration using enums export const AUDIO_FILE_TYPES = { diff --git a/tools/ui/src/lib/constants/svg-blocks.constants.ts b/ui/apps/chat/src/lib/constants/svg-blocks.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/svg-blocks.constants.ts rename to ui/apps/chat/src/lib/constants/svg-blocks.constants.ts diff --git a/tools/ui/src/lib/constants/table-html-restorer.constants.ts b/ui/apps/chat/src/lib/constants/table-html-restorer.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/table-html-restorer.constants.ts rename to ui/apps/chat/src/lib/constants/table-html-restorer.constants.ts diff --git a/tools/ui/src/lib/constants/title-generation.constants.ts b/ui/apps/chat/src/lib/constants/title-generation.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/title-generation.constants.ts rename to ui/apps/chat/src/lib/constants/title-generation.constants.ts diff --git a/tools/ui/src/lib/constants/tool-call-args.constants.ts b/ui/apps/chat/src/lib/constants/tool-call-args.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/tool-call-args.constants.ts rename to ui/apps/chat/src/lib/constants/tool-call-args.constants.ts diff --git a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts new file mode 100644 index 000000000000..dce125262e3e --- /dev/null +++ b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts @@ -0,0 +1,64 @@ +// Registry of server and browser tools whose renderer +// shows a recognizable icon and friendly label inline in the chat UI. +// +// To add a new tool, add an entry to TOOL_UI. To give a +// tool a custom title or body renderer, add a dedicated component under +// ChatMessageToolCall/ and route it in ChatMessageToolCallBlock.svelte +// (see ChatMessageToolCallBlockGetDatetime and +// ChatMessageToolCallBlockSearchResults for prior art). + +import Braces from '@lucide/svelte/icons/braces'; +import Clock from '@lucide/svelte/icons/clock'; +import Eye from '@lucide/svelte/icons/eye'; +import FilePen from '@lucide/svelte/icons/file-pen'; +import FilePlus from '@lucide/svelte/icons/file-plus'; +import FileSearch from '@lucide/svelte/icons/file-search'; +import FileText from '@lucide/svelte/icons/file-text'; +import Info from '@lucide/svelte/icons/info'; +import MessagesSquare from '@lucide/svelte/icons/messages-square'; +import SearchCode from '@lucide/svelte/icons/search-code'; +import Terminal from '@lucide/svelte/icons/terminal'; +import { BuiltInTool, ToolSource } from '#lib/enums/index.ts'; +import type { ToolUiEntry } from '#lib/types/index.ts'; + +export const TOOL_UI: Readonly> = { + [BuiltInTool.BROWSER_GET_DATETIME]: { + icon: Clock, + label: 'Current time', + source: ToolSource.BROWSER + }, + [BuiltInTool.BROWSER_READ_MEDIA]: { icon: Eye, label: 'Read media', source: ToolSource.BROWSER }, + [BuiltInTool.BROWSER_RUN_JAVASCRIPT]: { + icon: Braces, + label: 'Run JavaScript', + source: ToolSource.BROWSER + }, + [BuiltInTool.BROWSER_SEARCH_CHATS]: { + icon: MessagesSquare, + label: 'Search chats', + source: ToolSource.BROWSER + }, + [BuiltInTool.SERVER_EDIT_FILE]: { icon: FilePen, label: 'Edit file', source: ToolSource.SERVER }, + [BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: { + icon: Terminal, + label: 'Run command', + source: ToolSource.SERVER + }, + [BuiltInTool.SERVER_FILE_GLOB_SEARCH]: { + icon: FileSearch, + label: 'Search files', + source: ToolSource.SERVER + }, + [BuiltInTool.SERVER_GET_INFO]: { icon: Info, label: 'Runtime info', source: ToolSource.SERVER }, + [BuiltInTool.SERVER_GREP_SEARCH]: { + icon: SearchCode, + label: 'Search in files', + source: ToolSource.SERVER + }, + [BuiltInTool.SERVER_READ_FILE]: { icon: FileText, label: 'Read file', source: ToolSource.SERVER }, + [BuiltInTool.SERVER_WRITE_FILE]: { + icon: FilePlus, + label: 'Write file', + source: ToolSource.SERVER + } +} as const; diff --git a/ui/apps/chat/src/lib/constants/ui.constants.ts b/ui/apps/chat/src/lib/constants/ui.constants.ts new file mode 100644 index 000000000000..5ac2adfbb247 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/ui.constants.ts @@ -0,0 +1,193 @@ +import { MODEL_ICON } from './icons.constants'; +import { + SHORTCUT_MODELS, + SHORTCUT_NEW_CHAT, + SHORTCUT_SEARCH, + SHORTCUT_SETTINGS +} from './keyboard-shortcuts.constants'; +import { MCP_SERVERS_ROUTE_ID, MODELS_ROUTE_ID, SETTINGS_ROUTE_ID } from './routes.constants'; +import Search from '@lucide/svelte/icons/search'; +import Settings from '@lucide/svelte/icons/settings'; +import SquarePen from '@lucide/svelte/icons/square-pen'; +import McpLogo from '#lib/components/app/mcp/McpLogo.svelte'; +import { SidebarAction, ToolSource } from '#lib/enums/index.ts'; +import type { DesktopIconStripItem } from '#lib/types/index.ts'; + +/** Delay before a copied affordance resets from its check to the copy icon. */ +export const COPY_FEEDBACK_RESET_MS = 1500; + +/** How long a collapsible block's body takes to expand or collapse. */ +export const COLLAPSIBLE_TRANSITION_MS = 200; + +/** + * Parts of a message where right-click keeps the browser's own menu (open or + * copy a link, save an image, copy code or a field), not the message actions. + */ +export const NATIVE_CONTEXT_MENU_SELECTOR = + 'a, img, video, audio, pre, code, input, textarea, [contenteditable="true"]'; + +/** + * A sidebar section under a dragged chat, or one being moved: the faint tint + * of the sidebar's resize handle, edged like the handle while it is dragged. + */ +export const SIDEBAR_DRAG_HIGHLIGHT_CLASS = 'bg-foreground/6 ring-1 ring-foreground/15 ring-inset'; + +/** How long a sidebar chat row takes to slide out of a section, or into one. */ +export const SIDEBAR_ROW_SLIDE_MS = 200; + +/** Chats a sidebar section shows before its "Show more" row. */ +export const SIDEBAR_SECTION_PREVIEW_COUNT = 6; + +/** + * The "Show less" row of an opened section stays at the bottom of the sidebar + * while the section scrolls under it, with room below it and a fade above + * (see app.css). "Show more" is a plain row. + */ +export const SIDEBAR_SHOW_MORE_ROW_CLASS = 'sidebar-show-more sticky bottom-0 z-10 pb-2'; + +/** Ids of the sidebar's conversation sections, for their folded state. */ +export const SIDEBAR_SECTION_IDS = { + /** Followed by the group id: one section per group. */ + GROUP_PREFIX: 'group:', + PINNED: 'pinned', + RECENT: 'recent' +} as const; + +export const FORK_TREE_DEPTH_PADDING = 8; +export const SYSTEM_MESSAGE_PLACEHOLDER = 'System message'; + +/** Data attributes for app-level DOM contracts. */ +export const UI_DATA_ATTRS = { + ACTIVE: 'data-active', + ACTIVE_TAB: 'data-active-tab', + /** On while the main chat form is expanded (a full-screen sheet on a phone). */ + CHAT_FORM_SHEET: 'data-chat-form-sheet', + CONVERSATION_ROW: 'data-conversation-row', + HIGHLIGHT_THEME_PREVIEW: 'data-highlight-theme-preview', + PICKER_INDEX: 'data-picker-index', + RESULT_INDEX: 'data-result-index', + THUMBNAIL_INDEX: 'data-thumbnail-index' +} as const; + +export const TOOL_GROUP_LABELS = { + [ToolSource.BROWSER]: 'Browser', + [ToolSource.CUSTOM]: 'JSON Schema', + [ToolSource.SERVER]: 'Server' +} as const; + +export const TOOL_SERVER_LABELS = { + [ToolSource.BROWSER]: 'Browser Tools', + [ToolSource.CUSTOM]: 'Custom Tools', + [ToolSource.SERVER]: 'Server Tools' +} as const; + +export const TOOLTIP_DELAY_DURATION = 500; + +export const VIEWPORT_GUTTER = 8; +export const MENU_OFFSET = 6; + +export const PROCESSING_INFO_TIMEOUT = 2000; + +/** + * Statistics units labels + */ +export const STATS_UNITS = { + TOKENS_PER_SECOND: 't/s' +} as const; + +export const DEFAULT_MOBILE_BREAKPOINT = 768; + +/** Models listed per remote provider before the "+ X more" line; search covers the rest. */ +export const REMOTE_PROVIDER_MODEL_LIMIT = 12; + +/** Model rows mounted before the list scrolls; a local catalog can hold hundreds. */ +export const MODEL_ROW_WINDOW = 50; + +/** Models of one family shown before the rest fold behind a "show more" row. */ +export const FAMILY_ROW_WINDOW = 6; + +/** Recently used models kept per browser, most recent first. */ +export const RECENT_MODEL_LIMIT = 20; + +export const ICON_STRIP_TRANSITION_DURATION = 150; +export const ICON_STRIP_TRANSITION_DELAY_MULTIPLIER = 50; + +/** Collapsed desktop sidebar strip width, matching its `md:w-12`. */ +export const SIDEBAR_COLLAPSED_WIDTH = '3rem'; +/** Bounds the expanded desktop sidebar can be dragged between. */ +export const SIDEBAR_MIN_WIDTH = '18rem'; +export const SIDEBAR_MAX_WIDTH = '32rem'; +/** Dragging the sidebar edge narrower than this snaps it to the pointer; letting go hides it. */ +export const SIDEBAR_COLLAPSE_WIDTH = '9rem'; +/** How far past its min or max width a drag can stretch the sidebar before it resists fully. */ +export const SIDEBAR_OVERSTRETCH_PX = 80; +/** Spring-back duration when a drag ends outside the width bounds. */ +export const SIDEBAR_SETTLE_MS = 300; +/** Duration of the sidebar's open and close slide, matching its `duration-200` transition. */ +export const SIDEBAR_TOGGLE_MS = 200; +/** The sidebar's contents fading out while a phone's full-screen search covers them, and back in. */ +export const SIDEBAR_CONTENT_FADE_MS = 200; + +/** Phone sidebar reveal: the page slides aside by this share of the screen, up to the max width. */ +export const SIDEBAR_REVEAL_RATIO = 0.8; +export const SIDEBAR_REVEAL_MAX_WIDTH = '20rem'; +/** Duration of the phone sidebar reveal, matching the page's `duration-300` slide. */ +export const SIDEBAR_REVEAL_MS = 300; +/** Wait after a tap in the phone sidebar closes it, before the tap's page or dialog appears. */ +export const SIDEBAR_REVEAL_ACTION_DELAY_MS = 180; +/** A swipe that starts this close to the left edge can open the phone sidebar. */ +export const SIDEBAR_REVEAL_EDGE_PX = 24; +/** Movement before a reveal swipe locks to a horizontal drag. */ +export const SIDEBAR_REVEAL_SLOP_PX = 8; +/** A rightward swipe this long from anywhere on the page opens the phone sidebar too. */ +export const SIDEBAR_REVEAL_SWIPE_PX = 16; +/** Share of the reveal a drag must cover to open or close the phone sidebar when let go slowly. */ +export const SIDEBAR_REVEAL_COMMIT_RATIO = 0.3; +/** Release speed past which a drag opens or closes the phone sidebar the way it was heading. */ +export const SIDEBAR_REVEAL_FLING_PX_PER_MS = 0.3; + +/** Hold time before a phone conversation row opens its action menu. */ +export const ROW_LONG_PRESS_MS = 450; +/** Drift that cancels a row hold, so scrolling still works. */ +export const ROW_LONG_PRESS_SLOP_PX = 8; + +/** Max height for tool-result code blocks (json / source / diff / streaming code). */ +export const MAX_HEIGHT_CODE_BLOCK = '22rem'; + +/** The sidebar's actions at its top: starting, finding and organizing chats. */ +export const SIDEBAR_ACTIONS_ITEMS: DesktopIconStripItem[] = [ + { + action: SidebarAction.NEW_CHAT, + icon: SquarePen, + keys: SHORTCUT_NEW_CHAT, + tooltip: 'New chat' + }, + { action: SidebarAction.SEARCH, icon: Search, keys: SHORTCUT_SEARCH, tooltip: 'Search' } +]; + +/** The sidebar's footer: managing the app around the chats. */ +export const SIDEBAR_FOOTER_ITEMS: DesktopIconStripItem[] = [ + { + action: SidebarAction.MANAGE_MODELS, + activeRouteId: MODELS_ROUTE_ID, + icon: MODEL_ICON, + keys: SHORTCUT_MODELS, + tooltip: 'Models' + }, + { + action: SidebarAction.MCP, + activeRouteId: MCP_SERVERS_ROUTE_ID, + icon: McpLogo, + tooltip: 'MCP' + }, + { + action: SidebarAction.SETTINGS, + activeRouteId: SETTINGS_ROUTE_ID, + icon: Settings, + keys: SHORTCUT_SETTINGS, + tooltip: 'Settings' + } +]; + +/** A light haptic tap's length where the browser vibrates (Android): a click, not a buzz. */ +export const HAPTIC_TAP_MS = 8; diff --git a/tools/ui/src/lib/constants/uri-template.constants.ts b/ui/apps/chat/src/lib/constants/uri-template.constants.ts similarity index 100% rename from tools/ui/src/lib/constants/uri-template.constants.ts rename to ui/apps/chat/src/lib/constants/uri-template.constants.ts diff --git a/tools/ui/src/lib/constants/url.constants.ts b/ui/apps/chat/src/lib/constants/url.constants.ts similarity index 98% rename from tools/ui/src/lib/constants/url.constants.ts rename to ui/apps/chat/src/lib/constants/url.constants.ts index 8df442934688..83178544dad5 100644 --- a/tools/ui/src/lib/constants/url.constants.ts +++ b/ui/apps/chat/src/lib/constants/url.constants.ts @@ -1,4 +1,4 @@ -import { UrlProtocol } from '$lib/enums'; +import { UrlProtocol } from '#lib/enums/index.ts'; const STD = ['com', 'net', 'org', 'gov', 'edu'] as const; const STD_MIL = [...STD, 'mil'] as const; diff --git a/ui/apps/chat/src/lib/constants/voice.constants.ts b/ui/apps/chat/src/lib/constants/voice.constants.ts new file mode 100644 index 000000000000..d897a1c73938 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/voice.constants.ts @@ -0,0 +1,130 @@ +import { STORAGE_APP_NAME } from './storage.constants'; +import { VoiceRecordingBarStatus } from '@ggml-org/llama-ui/voice'; +import { ChatFormVoiceState } from '#lib/enums/voice.enums.ts'; + +/** What the chat form's microphone says it will do, or why it can't, on its button. */ +export const VOICE_MODE_MESSAGE = { + dictate: 'Dictate', + dictating: 'Dictating', + realtimeOnlyBehindKey: + 'This model only transcribes live, over a connection a browser cannot open on a server with an API key.', + recording: 'Recording a voice message', + refining: 'Refining transcript...', + sendAfterRefining: 'Sending once the transcript is refined', + separateModelHint: + 'The transcription model is loaded on the server alongside the chat model, which a server that keeps one model at a time unloads.', + starting: 'Starting...', + tooQuiet: + 'Your microphone sounds quiet. Move closer, or turn its input level up in your system settings.', + transcribing: 'Transcribing...', + transcriptionFailed: 'Transcription failed', + unavailable: + 'No model with audio input is available. In router mode, load one or pick a transcription model in Settings > Voice.', + voiceMessage: 'Send a voice message' +} as const; + +/** The status of a server that has no such route for the model, e.g. a live-only model asked over HTTP. */ +export const VOICE_NOT_SUPPORTED_STATUS = 501; + +/** Where the chat form remembers that it showed the hint about a separate transcription model. */ +export const VOICE_SEPARATE_MODEL_HINT_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.voiceSeparateModelHintSeen`; + +/** Name prefix of a voice message's WAV file; the rest makes it unique per recording. */ +export const VOICE_CLIP_NAME_PREFIX = 'voice-'; + +/** File extension of a voice message. */ +export const VOICE_CLIP_EXTENSION = '.wav'; + +/** Characters of a random id in a voice message's file name, after its time. */ +export const VOICE_CLIP_ID_LENGTH = 8; + +/** How often the recording's elapsed time is updated. */ +export const VOICE_ELAPSED_TICK_MS = 200; + +/** + * A mouse starts recording on press, so the click that ends that press comes within this + * long and is not another tap. + */ +export const VOICE_PRESS_CLICK_MS = 1000; + +/** How long a transcript that came back keeps looking for the message it belongs to. */ +export const VOICE_TRANSCRIPT_APPLY_RETRY_DELAYS_MS = [500, 1500, 4000] as const; + +/** A string that is already a URL (data, blob, http...), which an