diff --git a/.devops/cann.Dockerfile b/.devops/cann.Dockerfile index 83df409506fd..d76bfa69978b 100644 --- a/.devops/cann.Dockerfile +++ b/.devops/cann.Dockerfile @@ -25,9 +25,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and the harness 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/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${CANN_BASE_IMAGE} AS build diff --git a/.devops/cpu.Dockerfile b/.devops/cpu.Dockerfile index e195b5ac8b53..19a6a93b78c0 100644 --- a/.devops/cpu.Dockerfile +++ b/.devops/cpu.Dockerfile @@ -15,9 +15,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and the harness 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/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.devops/cuda.Dockerfile b/.devops/cuda.Dockerfile index 20501c1beac2..b4cad90c95c5 100644 --- a/.devops/cuda.Dockerfile +++ b/.devops/cuda.Dockerfile @@ -23,9 +23,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and the harness 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/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_CUDA_DEV_CONTAINER} AS build diff --git a/.devops/intel.Dockerfile b/.devops/intel.Dockerfile index 16326ebbdea5..9e0025920602 100644 --- a/.devops/intel.Dockerfile +++ b/.devops/intel.Dockerfile @@ -17,9 +17,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and the harness 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/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build diff --git a/.devops/musa.Dockerfile b/.devops/musa.Dockerfile index dbf9e0b41122..dcfe3a22080f 100644 --- a/.devops/musa.Dockerfile +++ b/.devops/musa.Dockerfile @@ -21,9 +21,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and the harness 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/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_MUSA_DEV_CONTAINER} AS build diff --git a/.devops/nix/package.nix b/.devops/nix/package.nix index 4ac844ff959d..887270fb23bd 100644 --- a/.devops/nix/package.nix +++ b/.devops/nix/package.nix @@ -182,7 +182,7 @@ effectiveStdenv.mkDerivation (finalAttrs: { webui = stdenvNoCC.mkDerivation { pname = "webui"; version = llamaVersion; - # the app compiles Llama UI from its source in ../../lib/ui, so the source is ui/ as a whole + # the app compiles Llama UI and the harness from their sources in ../../lib, so the source is ui/ as a whole src = lib.cleanSource ../../ui; sourceRoot = "source/apps/chat"; diff --git a/.devops/openvino.Dockerfile b/.devops/openvino.Dockerfile index c88cc2bbb5f9..f7461f2eee7f 100644 --- a/.devops/openvino.Dockerfile +++ b/.devops/openvino.Dockerfile @@ -34,9 +34,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and the harness 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/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ## Build Image diff --git a/.devops/rocm.Dockerfile b/.devops/rocm.Dockerfile index 9e667660f00e..78a30ef47ae4 100644 --- a/.devops/rocm.Dockerfile +++ b/.devops/rocm.Dockerfile @@ -23,9 +23,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and the harness 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/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ### Build image diff --git a/.devops/vulkan.Dockerfile b/.devops/vulkan.Dockerfile index dc8a87667205..740cd3b9cced 100644 --- a/.devops/vulkan.Dockerfile +++ b/.devops/vulkan.Dockerfile @@ -15,9 +15,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and the harness 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/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.devops/zendnn.Dockerfile b/.devops/zendnn.Dockerfile index cbc3696ed643..75b2da5a4dd5 100644 --- a/.devops/zendnn.Dockerfile +++ b/.devops/zendnn.Dockerfile @@ -15,9 +15,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and the harness 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/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.github/workflows/ui-self-hosted.yml b/.github/workflows/ui-self-hosted.yml index 346f1cfb4b12..e19c4234b827 100644 --- a/.github/workflows/ui-self-hosted.yml +++ b/.github/workflows/ui-self-hosted.yml @@ -19,6 +19,7 @@ on: '.github/workflows/ui-build-self-hosted.yml', 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', + 'ui/lib/harness/**.*', 'tools/server/tests/**.*' ] pull_request: @@ -28,6 +29,7 @@ on: '.github/workflows/ui-build-self-hosted.yml', 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', + 'ui/lib/harness/**.*', 'tools/server/tests/**.*' ] diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 10d7ed0ed5e4..11875ba53c5c 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -150,6 +150,37 @@ jobs: run: npm run prepack working-directory: ui/lib/ui + harness-checks: + name: Harness 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/harness + + - name: Run type checking + run: npm run check + working-directory: ui/lib/harness + + - name: Run tests + run: npm test + working-directory: ui/lib/harness + + - name: Build the package + run: npm run prepack + working-directory: ui/lib/harness + e2e-tests: name: E2E Tests needs: ui-build diff --git a/common/arg.cpp b/common/arg.cpp index 192f70607f1e..4503b19bc7d4 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -3426,6 +3426,22 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.ui_mcp_proxy = value; } ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_MCP_PROXY")); + add_opt(common_arg( + {"--ui-storage"}, + {"--no-ui-storage"}, + "experimental: keep UI conversations and settings on disk instead of only in the browser - anyone who can reach the server can read them (default: disabled)", + [](common_params & params, bool value) { + params.ui_storage = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_STORAGE")); + add_opt(common_arg( + {"--ui-storage-dir"}, "PATH", + "directory for UI storage, implies --ui-storage (default: llama.cpp/ui in the user data directory)", + [](common_params & params, const std::string & value) { + params.ui_storage = true; + params.ui_storage_dir = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_STORAGE_DIR")); 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" diff --git a/common/common.cpp b/common/common.cpp index b009d460d697..80cf1f157a88 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1014,6 +1014,24 @@ std::filesystem::path fs_get_config_directory() { return config_directory / "llama.cpp"; } +std::filesystem::path fs_get_data_directory() { + std::filesystem::path data_directory; +#if defined(_WIN32) + data_directory = common_get_path_from_env("APPDATA"); + if (data_directory.empty()) { + throw std::runtime_error("Failed to find %APPDATA% directory"); + } +#elif defined(__APPLE__) + data_directory = get_home_directory() / "Library/Application Support"; +#else + data_directory = common_get_path_from_env("XDG_DATA_HOME"); + if (data_directory.empty()) { + data_directory = get_home_directory() / ".local/share"; + } +#endif + return data_directory / "llama.cpp"; +} + std::filesystem::path fs_get_cache_file(const std::string & filename) { GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos); const std::filesystem::path cache_directory = fs_get_cache_directory(); diff --git a/common/common.h b/common/common.h index e16bee7c1629..48f9ef99572a 100644 --- a/common/common.h +++ b/common/common.h @@ -703,6 +703,8 @@ struct common_params { bool ui = true; bool ui_mcp_proxy = false; std::string ui_config_json; + bool ui_storage = false; // keep UI conversations and settings on disk + std::string ui_storage_dir; // empty: fs_get_data_directory() / "ui" // "advanced" endpoints are disabled by default for better security bool endpoint_slots = true; @@ -960,6 +962,7 @@ inline bool common_create_directories(const std::filesystem::path & path, std::e std::filesystem::path fs_get_cache_directory(); std::filesystem::path fs_get_cache_file(const std::string & filename); std::filesystem::path fs_get_config_directory(); +std::filesystem::path fs_get_data_directory(); void fs_write_atomic(const std::filesystem::path & path, const std::string & data); diff --git a/scripts/ui-assets.cmake b/scripts/ui-assets.cmake index 90d0bdf338b8..12b5f068d513 100644 --- a/scripts/ui-assets.cmake +++ b/scripts/ui-assets.cmake @@ -20,10 +20,12 @@ set(LLAMA_UI_GZIP "" CACHE STRING "Apply gzip compress to assets to save ban set(DIST_DIR "${UI_BINARY_DIR}/dist") set(SRC_DIST_DIR "${UI_SOURCE_DIR}/dist") # The stage keeps the layout of ui/: the app in apps/chat, with the sources of -# Llama UI that it compiles next to it in lib/ui (see ui/apps/chat/scripts/llama-ui.js). +# Llama UI and the harness that it compiles next to it in lib/ (see +# ui/apps/chat/scripts/llama-ui.js and svelte.config.js). set(STAGE_DIR "${UI_BINARY_DIR}/ui-src") set(WORK_DIR "${STAGE_DIR}/apps/chat") set(UI_LIB_DIR "${UI_SOURCE_DIR}/../../lib/ui") +set(HARNESS_DIR "${UI_SOURCE_DIR}/../../lib/harness") set(STAMP_FILE "${UI_BINARY_DIR}/.ui-stamp") set(EMBED_STAMP "${UI_BINARY_DIR}/.ui-embed.sha256") set(UI_CPP "${UI_BINARY_DIR}/ui.cpp") @@ -323,7 +325,7 @@ function(npm_build_should_skip out_var) endfunction() function(stage_sources) - # everything but the app goes: the library, restaged below, and what a stage + # everything but the app goes: the packages, restaged below, and what a stage # from before this layout left at the top, its node_modules included if(EXISTS "${STAGE_DIR}") file(GLOB staged RELATIVE "${STAGE_DIR}" "${STAGE_DIR}/*") @@ -347,7 +349,8 @@ function(stage_sources) PATTERN "node_modules" EXCLUDE ) - # what the app reads of the library: its sources and the dependency list + # what the app reads of the packages: Llama UI's sources and dependency list, + # and the harness's sources file(COPY "${UI_LIB_DIR}/package.json" DESTINATION "${STAGE_DIR}/lib/ui" NO_SOURCE_PERMISSIONS @@ -356,6 +359,10 @@ function(stage_sources) DESTINATION "${STAGE_DIR}/lib/ui/src" NO_SOURCE_PERMISSIONS ) + file(COPY "${HARNESS_DIR}/src" + DESTINATION "${STAGE_DIR}/lib/harness" + NO_SOURCE_PERMISSIONS + ) endfunction() function(npm_build out_var) diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt index 9f9393f98384..7403ce5aa0cd 100644 --- a/tools/server/CMakeLists.txt +++ b/tools/server/CMakeLists.txt @@ -23,6 +23,8 @@ add_library(${TARGET} STATIC server-stream.h server-tools.cpp server-tools.h + server-storage.cpp + server-storage.h server-mcp.cpp server-mcp.h server-schema.cpp diff --git a/tools/server/README-dev.md b/tools/server/README-dev.md index 997b8137d61f..f7ec63b7f44f 100644 --- a/tools/server/README-dev.md +++ b/tools/server/README-dev.md @@ -190,6 +190,7 @@ Get a list of tools, each tool has these fields: - `tool` (string): the ID name of the tool, to be used in POST call. Example: `read_file` - `display_name` (string): the name to be displayed on UI. Example: `Read file` - `type` (string): `"server"` for a server tool, or `"mcp"` for a tool exposed by an MCP server +- `mcp_server` (string, only when `type` is `"mcp"`): the name of the MCP server the tool comes from, as declared in `--mcp-servers-config`. Example: `imcp` - `permissions` (object): a mapping string --> boolean that indicates the permission required by this tool. This is useful for the UI to ask the user before calling the tool. For now, the only permission supported is `"write"` - `definition` (object): the OAI-compat definition of this tool diff --git a/tools/server/README.md b/tools/server/README.md index 278518dce75c..abb425cf3b57 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -203,6 +203,8 @@ For the full list of features, please refer to [server's changelog](https://gith | `--ui-config, --webui-config JSON` | JSON that provides default UI settings (overrides UI defaults)
(env: LLAMA_ARG_UI_CONFIG) | | `--ui-config-file, --webui-config-file PATH` | JSON file that provides default UI settings (overrides UI defaults)
(env: LLAMA_ARG_UI_CONFIG_FILE) | | `--ui-mcp-proxy, --webui-mcp-proxy, --no-ui-mcp-proxy, --no-webui-mcp-proxy` | experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused - do not enable in untrusted environments (default: disabled)
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_UI_MCP_PROXY) | +| `--ui-storage, --no-ui-storage` | experimental: keep UI conversations and settings on disk instead of only in the browser - anyone who can reach the server can read them (default: disabled)
(env: LLAMA_ARG_UI_STORAGE) | +| `--ui-storage-dir PATH` | directory for UI storage, implies --ui-storage (default: llama.cpp/ui in the user data directory)
(env: LLAMA_ARG_UI_STORAGE_DIR) | | `--tools TOOL1,TOOL2,...` | experimental: whether to enable built-in tools for AI agents - do not enable in untrusted environments (default: no tools)
specify "all" to enable all tools
available tools: read_file, file_glob_search, grep_search, exec_shell_command, write_file, edit_file, get_info
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_TOOLS) | | `--tools-runtime OPTION` | experimental: run tools in a separate runtime environment (default: none, use host environment)
available options:
'docker:', 'podman:': spin up a new container and reuse it for all invocations, clean up on server exit
'docker-container:', 'podman-container:': use an existing container by ID, won't stop on server exit
'ssh:': run tools on a remote POSIX host over SSH, key-based auth and a trusted host key are required

(env: LLAMA_ARG_TOOLS_RUNTIME) | | `--allow-unauthenticated-tools` | allow server tools, MCP servers or MCP proxy on a non-loopback address without an API key - only for trusted networks (default: disabled)
(env: LLAMA_ARG_ALLOW_UNAUTHENTICATED_TOOLS) | @@ -389,7 +391,7 @@ The same JSON can be passed inline with `--mcp-servers-json`. Each entry under ` | `cwd` | working directory of the child process | | `timeout_ms` | per-tool-call timeout (default: 30000) | -Every server is spawned once at startup to list its tools, then stopped, and respawned on demand when one of its tools is called. Tools are exposed as `_` alongside the built-in ones: they show up in Llama Chat and in `GET /tools`, and the model calls them like any other tool. A name colliding with an already registered tool is skipped. This is independent of `--tools`, MCP servers can be the only tools available. +Every server is spawned once at startup to list its tools, then stopped, and respawned on demand when one of its tools is called. Tools are exposed as `_` alongside the built-in ones: they show up in Llama Chat, which lists each of these servers on its MCP servers page, and in `GET /tools`, with `"type": "mcp"` and the server's name in `mcp_server`. The model calls them like any other tool. A name colliding with an already registered tool is skipped. This is independent of `--tools`, MCP servers can be the only tools available. The child process runs with the same privileges as the server, so only declare commands you trust. As with `--tools`, `--cors-origins` then defaults to `localhost`. diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 36082df89d7a..e8c09724fa62 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -5663,6 +5663,7 @@ static json get_res_props(const server_context_meta & meta, const common_params { "build_info", meta.build_info }, { "is_sleeping", is_sleeping }, { "cors_proxy_enabled", params.ui_mcp_proxy }, + { "ui_storage", params.ui_storage }, }; if (!params.server_connect_code.empty()) { diff --git a/tools/server/server-models.cpp b/tools/server/server-models.cpp index 5d5992c08d3a..60bd889b5539 100644 --- a/tools/server/server-models.cpp +++ b/tools/server/server-models.cpp @@ -296,6 +296,9 @@ static void unset_reserved_args(common_preset & preset, bool unset_model_args) { preset.unset_option("LLAMA_ARG_CONNECT_CODE"); preset.unset_option("LLAMA_ARG_MCP_SERVERS_CONFIG"); preset.unset_option("LLAMA_ARG_MCP_SERVERS_JSON"); + // UI storage is served by the router only + preset.unset_option("LLAMA_ARG_UI_STORAGE"); + preset.unset_option("LLAMA_ARG_UI_STORAGE_DIR"); if (unset_model_args) { preset.unset_option("LLAMA_ARG_MODEL"); preset.unset_option("LLAMA_ARG_SHARD"); @@ -2073,6 +2076,7 @@ void server_models_routes::init_routes() { {"ui_settings", ui_settings}, {"build_info", std::string(llama_build_info())}, {"cors_proxy_enabled", params.ui_mcp_proxy}, + {"ui_storage", params.ui_storage}, }; if (!params.server_connect_code.empty()) { props["connect_code"] = params.server_connect_code; diff --git a/tools/server/server-storage.cpp b/tools/server/server-storage.cpp new file mode 100644 index 000000000000..2239e57c965a --- /dev/null +++ b/tools/server/server-storage.cpp @@ -0,0 +1,227 @@ +#include "server-storage.h" + +#include +#include + +namespace fs = std::filesystem; + +static json read_json_file(const fs::path & path) { + std::ifstream f(path, std::ios::binary); + if (!f) { + throw std::runtime_error("failed to open file: " + path.string()); + } + std::stringstream ss; + ss << f.rdbuf(); + return json::parse(ss.str()); +} + +// ids and record kinds come from the UI (uuids, table names), anything else could escape the storage directory +static void validate_id(const std::string & id, const char * what = "conversation id") { + if (id.empty() || id.size() > 64) { + throw std::invalid_argument(std::string("invalid ") + what); + } + for (char c : id) { + if (!std::isalnum((unsigned char) c) && c != '-' && c != '_') { + throw std::invalid_argument(std::string("invalid ") + what); + } + } +} + +static server_http_res_ptr res_json(int status, const json & data) { + auto res = std::make_unique(); + res->status = status; + res->data = safe_json_to_str(data); + return res; +} + +fs::path server_storage::conversation_path(const std::string & id) const { + return dir / "conversations" / fs::u8path(id + ".json"); +} + +fs::path server_storage::records_path(const std::string & kind) const { + return dir / "records" / fs::u8path(kind + ".json"); +} + +void server_storage::load_index() { + const fs::path index_path = dir / "index.json"; + + if (fs::exists(index_path)) { + try { + index = read_json_file(index_path); + if (index.is_object()) { + return; + } + } catch (const std::exception & e) { + SRV_WRN("failed to read %s, rebuilding it: %s\n", index_path.string().c_str(), e.what()); + } + } + + index = json::object(); + for (const auto & entry : fs::directory_iterator(dir / "conversations")) { + if (!entry.is_regular_file() || entry.path().extension() != ".json") { + continue; + } + try { + const json doc = read_json_file(entry.path()); + const std::string id = doc.at("conv").at("id").get(); + index[id] = { { "rev", doc.value("rev", 0) }, { "conv", doc.at("conv") } }; + } catch (const std::exception & e) { + SRV_WRN("skipping unreadable conversation %s: %s\n", entry.path().string().c_str(), e.what()); + } + } + save_index(); +} + +void server_storage::save_index() const { + fs_write_atomic(dir / "index.json", safe_json_to_str(index)); +} + +void server_storage::setup(const fs::path & storage_dir) { + dir = storage_dir; + + std::error_code ec; + common_create_directories(dir / "conversations", ec); + if (!ec) { + common_create_directories(dir / "records", ec); + } + if (ec) { + throw std::runtime_error("failed to create UI storage directory: " + dir.string()); + } + load_index(); + + SRV_INF("UI storage in %s (%zu conversations)\n", dir.string().c_str(), index.size()); + + handle_list = [this](const server_http_req &) { + std::lock_guard lock(mtx); + json list = json::array(); + for (const auto & [id, entry] : index.items()) { + list.push_back(entry); + } + return res_json(200, list); + }; + + handle_get = [this](const server_http_req & req) { + const std::string id = req.get_param("id"); + validate_id(id); + + std::lock_guard lock(mtx); + if (!index.contains(id)) { + return res_json(404, { { "error", format_error_response("conversation not found", ERROR_TYPE_NOT_FOUND) } }); + } + return res_json(200, read_json_file(conversation_path(id))); + }; + + // the body carries the revision it was based on, 0 for a new conversation + handle_put = [this](const server_http_req & req) { + const std::string id = req.get_param("id"); + validate_id(id); + + const json body = json::parse(req.body); + const int rev = body.at("rev").get(); + const json & conv = body.at("conv"); + const json & messages = body.at("messages"); + if (!conv.is_object() || conv.value("id", "") != id || !messages.is_array()) { + throw std::invalid_argument("expected { rev, conv, messages } with conv.id matching the path"); + } + + std::lock_guard lock(mtx); + const int current = index.contains(id) ? index[id].value("rev", 0) : 0; + if (rev != current) { + json error = { { "code", 409 }, { "message", "conversation was modified by another client" }, { "type", "conflict_error" } }; + return res_json(409, { { "error", error }, { "rev", current } }); + } + + const json doc = { { "rev", current + 1 }, { "conv", conv }, { "messages", messages } }; + fs_write_atomic(conversation_path(id), safe_json_to_str(doc)); + index[id] = { { "rev", current + 1 }, { "conv", conv } }; + save_index(); + + return res_json(200, { { "rev", current + 1 } }); + }; + + handle_delete = [this](const server_http_req & req) { + const std::string id = req.get_param("id"); + validate_id(id); + + std::lock_guard lock(mtx); + std::error_code ec; + fs::remove(conversation_path(id), ec); + if (index.contains(id)) { + index.erase(id); + save_index(); + } + return res_json(200, json::object()); + }; + + handle_get_settings = [this](const server_http_req &) { + std::lock_guard lock(mtx); + const fs::path path = dir / "settings.json"; + return res_json(200, fs::exists(path) ? read_json_file(path) : json::object()); + }; + + // merges per key, so two clients changing different settings do not overwrite each other + handle_put_settings = [this](const server_http_req & req) { + const json body = json::parse(req.body); + const json set = body.value("set", json::object()); + const json remove = body.value("remove", json::array()); + if (!set.is_object() || !remove.is_array()) { + throw std::invalid_argument("expected { set: { key: value }, remove: [key] }"); + } + + std::lock_guard lock(mtx); + const fs::path path = dir / "settings.json"; + json settings = fs::exists(path) ? read_json_file(path) : json::object(); + for (const auto & [key, value] : set.items()) { + if (!value.is_string()) { + throw std::invalid_argument("setting values must be strings"); + } + settings[key] = value; + } + for (const auto & key : remove) { + settings.erase(key.get()); + } + fs_write_atomic(path, safe_json_to_str(settings)); + + return res_json(200, settings); + }; + + handle_get_records = [this](const server_http_req & req) { + const std::string kind = req.get_param("kind"); + validate_id(kind, "record kind"); + + std::lock_guard lock(mtx); + const fs::path path = records_path(kind); + return res_json(200, fs::exists(path) ? read_json_file(path) : json::object()); + }; + + // records are small and written whole, merged per id like settings + handle_put_records = [this](const server_http_req & req) { + const std::string kind = req.get_param("kind"); + validate_id(kind, "record kind"); + + const json body = json::parse(req.body); + const json set = body.value("set", json::object()); + const json remove = body.value("remove", json::array()); + if (!set.is_object() || !remove.is_array()) { + throw std::invalid_argument("expected { set: { id: record }, remove: [id] }"); + } + for (const auto & [id, record] : set.items()) { + if (!record.is_object() || record.value("id", "") != id) { + throw std::invalid_argument("records must be objects whose id matches their key"); + } + } + + std::lock_guard lock(mtx); + const fs::path path = records_path(kind); + json records = fs::exists(path) ? read_json_file(path) : json::object(); + for (const auto & [id, record] : set.items()) { + records[id] = record; + } + for (const auto & id : remove) { + records.erase(id.get()); + } + fs_write_atomic(path, safe_json_to_str(records)); + + return res_json(200, json::object()); + }; +} diff --git a/tools/server/server-storage.h b/tools/server/server-storage.h new file mode 100644 index 000000000000..ee2c24bb1dd0 --- /dev/null +++ b/tools/server/server-storage.h @@ -0,0 +1,39 @@ +#pragma once + +#include "server-common.h" +#include "server-http.h" + +#include +#include + +// UI storage (--ui-storage): the Web UI's conversations and settings kept as JSON files on disk +// the server does not interpret the documents, it only tracks a revision per conversation so +// concurrent writers (tabs, browsers) get a 409 instead of silently overwriting each other +// +// layout: +// /conversations/.json { "rev": n, "conv": {...}, "messages": [...] } +// /index.json { "": { "rev": n, "conv": {...} } }, rebuilt when missing +// /settings.json { "": "" } +// /records/.json { "": {...} }, groups, projects, prompts, ... +struct server_storage { + void setup(const std::filesystem::path & dir); + + server_http_context::handler_t handle_list; // GET /storage/conversations + server_http_context::handler_t handle_get; // GET /storage/conversations/:id + server_http_context::handler_t handle_put; // POST /storage/conversations/:id + server_http_context::handler_t handle_delete; // DELETE /storage/conversations/:id + server_http_context::handler_t handle_get_settings; // GET /storage/settings + server_http_context::handler_t handle_put_settings; // POST /storage/settings + server_http_context::handler_t handle_get_records; // GET /storage/records/:kind + server_http_context::handler_t handle_put_records; // POST /storage/records/:kind + +private: + std::filesystem::path dir; + std::mutex mtx; + json index = json::object(); + + std::filesystem::path conversation_path(const std::string & id) const; + std::filesystem::path records_path(const std::string & kind) const; + void load_index(); + void save_index() const; +}; diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp index 63626ddcc3df..633d0a5a51e6 100644 --- a/tools/server/server-tools.cpp +++ b/tools/server/server-tools.cpp @@ -89,7 +89,7 @@ static std::string console_output_to_utf8(const std::string & text) { } json server_tool::to_json() const { - return { + json res = { {"display_name", display_name}, {"tool", name}, {"type", type()}, @@ -99,6 +99,10 @@ json server_tool::to_json() const { {"uses_cwd", uses_cwd}, {"definition", get_definition()}, }; + if (!mcp_server.empty()) { + res["mcp_server"] = mcp_server; + } + return res; } static constexpr size_t SERVER_TOOL_GIT_LS_FILES_MAX_OUTPUT = 8 * 1024 * 1024; // 8 MB @@ -1814,6 +1818,7 @@ struct server_mcp_tool : server_tool { { name = server_name + "_" + tool_name; display_name = name; + mcp_server = server_name; permission_write = false; support_stream = false; } diff --git a/tools/server/server-tools.h b/tools/server/server-tools.h index 5a63ee973bef..1dc1d6e1e60b 100644 --- a/tools/server/server-tools.h +++ b/tools/server/server-tools.h @@ -15,6 +15,7 @@ struct server_tool { bool permission_write = false; bool support_stream = false; // if true, output can be streamed bool uses_cwd = false; // if true, the tool resolves paths and runs against the working directory + std::string mcp_server; // the MCP server the tool comes from, empty for a built-in tool virtual ~server_tool() = default; virtual json get_definition() const = 0; diff --git a/tools/server/server.cpp b/tools/server/server.cpp index d14978286224..1acdd56c7290 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -5,6 +5,7 @@ #include "server-cors-proxy.h" #include "server-stream.h" #include "server-tools.h" +#include "server-storage.h" #include "arg.h" #include "build-info.h" @@ -241,6 +242,7 @@ static bool server_setup_features( const common_params & params, server_mcp & mcp_mgr, server_tools & tools, + server_storage & storage, server_role_type role_type) { // return 403 for disabled features server_http_context::handler_t res_403 = [](const server_http_req &) { @@ -319,6 +321,33 @@ static bool server_setup_features( ctx_http.post("/tools", ex_wrapper(res_403)); } + if (params.ui_storage) { + try { + storage.setup(params.ui_storage_dir.empty() ? fs_get_data_directory() / "ui" : std::filesystem::u8path(params.ui_storage_dir)); + } catch (const std::exception & e) { + SRV_ERR("UI storage setup failed: %s\n", e.what()); + return false; + } + ctx_http.get ("/storage/conversations", ex_wrapper(storage.handle_list)); + ctx_http.get ("/storage/conversations/:id", ex_wrapper(storage.handle_get)); + ctx_http.post("/storage/conversations/:id", ex_wrapper(storage.handle_put)); + ctx_http.del ("/storage/conversations/:id", ex_wrapper(storage.handle_delete)); + ctx_http.get ("/storage/settings", ex_wrapper(storage.handle_get_settings)); + ctx_http.post("/storage/settings", ex_wrapper(storage.handle_put_settings)); + ctx_http.get ("/storage/records/:kind", ex_wrapper(storage.handle_get_records)); + ctx_http.post("/storage/records/:kind", ex_wrapper(storage.handle_put_records)); + warn_names.push_back("UI storage (experimental)"); + } else { + ctx_http.get ("/storage/conversations", ex_wrapper(res_403)); + ctx_http.get ("/storage/conversations/:id", ex_wrapper(res_403)); + ctx_http.post("/storage/conversations/:id", ex_wrapper(res_403)); + ctx_http.del ("/storage/conversations/:id", ex_wrapper(res_403)); + ctx_http.get ("/storage/settings", ex_wrapper(res_403)); + ctx_http.post("/storage/settings", ex_wrapper(res_403)); + ctx_http.get ("/storage/records/:kind", ex_wrapper(res_403)); + ctx_http.post("/storage/records/:kind", ex_wrapper(res_403)); + } + if (!warn_names.empty()) { std::string features; for (const auto & name : warn_names) { @@ -502,6 +531,7 @@ static int server_run_router(common_params & params, int argc, char ** argv, con server_context ctx_server; server_routes routes(params, ctx_server); server_tools tools; + server_storage storage; server_http_context ctx_http; if (!ctx_http.init(params)) { @@ -564,7 +594,7 @@ static int server_run_router(common_params & params, int argc, char ** argv, con models_routes->router_streams_lookup, models_routes->router_stream_delete); - if (!server_setup_features(ctx_http, params, mcp_mgr, tools, SERVER_ROLE_ROUTER)) { + if (!server_setup_features(ctx_http, params, mcp_mgr, tools, storage, SERVER_ROLE_ROUTER)) { return 1; } @@ -653,6 +683,7 @@ static int server_run_instance(common_params & params, server_role & role, commo server_context ctx_server; server_routes routes(params, ctx_server); server_tools tools; + server_storage storage; server_http_context ctx_http; if (!ctx_http.init(params)) { @@ -666,7 +697,7 @@ static int server_run_instance(common_params & params, server_role & role, commo server_stream_make_lookup_handler(), server_stream_make_delete_handler()); - if (!server_setup_features(ctx_http, params, mcp_mgr, tools, SERVER_ROLE_INSTANCE)) { + if (!server_setup_features(ctx_http, params, mcp_mgr, tools, storage, SERVER_ROLE_INSTANCE)) { return 1; } diff --git a/tools/server/tests/unit/test_mcp_servers.py b/tools/server/tests/unit/test_mcp_servers.py index 7a9f0bea57b3..6500d432485e 100644 --- a/tools/server/tests/unit/test_mcp_servers.py +++ b/tools/server/tests/unit/test_mcp_servers.py @@ -77,6 +77,9 @@ def get_tool_name(t): # Verify tool structure echo_tool = next(t for t in mcp_tools if get_tool_name(t) == "echo_echo") assert "description" in echo_tool or "definition" in echo_tool + assert echo_tool["type"] == "mcp" + assert echo_tool["mcp_server"] == "echo" + assert all("mcp_server" not in t for t in tools if t["type"] != "mcp") finally: server.stop() diff --git a/ui/README.md b/ui/README.md index b70228d0de7c..55fab208f41d 100644 --- a/ui/README.md +++ b/ui/README.md @@ -5,20 +5,27 @@ 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 +│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components +│ └── harness/ @ggml-org/llama-harness: the agentic loop, headless └── apps/ - └── chat/ Llama Chat, the chat app that llama-server serves + └── 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. -- [`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. +- [`lib/harness`](lib/harness/README.md) is the agentic loop: plain TypeScript with no UI and no dependencies. An app + gives it an inference client and tools, and reads its events. +- [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop through the + harness. 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`. +checking and testing `apps/chat` needs no install in `lib/ui` or `lib/harness`. + +The split between library and app is not finished. Llama Chat takes its tokens, fonts, surfaces and base components +from `lib/ui`, but still has its own versions of what the library holds above those (ActionIcon, SearchInput, Logo, +SyntaxHighlightedCode and the Model UI), and `DESIGN.md`, `BRAND.md` and the full Storybook still sit beside the app. ## Releases diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts index 7e7a58d167a8..035a5d097f12 100644 --- a/ui/apps/chat/.storybook/preview.ts +++ b/ui/apps/chat/.storybook/preview.ts @@ -4,6 +4,7 @@ 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 { activateBuiltInExtensions } from '../tests/stories/helpers/extensions'; import { applyColorScheme } from './color-scheme'; import ModeWatcherDecorator from './decorators/ModeWatcherDecorator.svelte'; import TooltipProviderDecorator from './decorators/TooltipProviderDecorator.svelte'; @@ -13,6 +14,8 @@ applyColorScheme(); window.matchMedia(MEDIA_QUERIES.PREFERS_DARK).addEventListener('change', applyColorScheme); const preview: Preview = { + // the app switches its extensions on at startup; the stories get them the same way, once + beforeAll: activateBuiltInExtensions, parameters: { controls: { matchers: { diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md index 32e6a009a2c9..0b4884de3167 100644 --- a/ui/apps/chat/AGENTS.md +++ b/ui/apps/chat/AGENTS.md @@ -1,6 +1,6 @@ # 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. +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. The agentic loop is `ui/lib/harness` (`@ggml-org/llama-harness`). - **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. diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index 5fa37286aadf..2a6c5ac44b72 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -19,21 +19,22 @@ It works with a llama-server in either mode: **MODEL** (one model) or **ROUTER** Llama Chat is published to npm as [`@ggml-org/llama-chat`](https://www.npmjs.com/package/@ggml-org/llama-chat), with [`llama-chat`](https://www.npmjs.com/package/llama-chat) as its short name. It serves the prebuilt app as static files on localhost, or writes them to a folder for any static file server (see [Self-hosting](#self-hosting)); it brings no server and no models of its own. It needs Node.js 20 or later. ```bash -npx @ggml-org/llama-chat # serve it on http://127.0.0.1:3000 and open the browser -npx llama-chat --host 0.0.0.0 --no-open # the same, by its short name, reachable from other devices -npx llama-chat build # write the static app to ./llama-chat instead +npx @ggml-org/llama-chat --server http://127.0.0.1:9931 # serve it on http://127.0.0.1:3000 with that server added +npx llama-chat --host 0.0.0.0 --no-open # the same, by its short name, reachable from other devices +npx llama-chat build --server https://llm.example.com # write the static app to ./llama-chat instead ``` | Flag | Default | What it does | | --------------------------------- | ----------- | ------------------------------------------------------------------------------------------- | +| `--server ` | | A llama-server the app adds on startup, once; repeatable. Its API key goes in the app | | `--port ` | `3000` | Fixed, so the origin, and the chats the browser stores under it, stay the same between runs | | `--host ` | `127.0.0.1` | `0.0.0.0` to open it to the LAN | | `--open` / `--no-open` | open | Opens the default browser once it listens | | `-v`, `--version`, `-h`, `--help` | | As usual | -The bare command is the documented form; `start` is accepted as an alias for it. `build` takes `--out ` (default `./llama-chat`) and `--force`, which lets it write into a folder that is not empty. +The bare command is the documented form; `start` is accepted as an alias for it. `build` takes `--out ` (default `./llama-chat`), `--force`, which lets it write into a folder that is not empty, and `--server`. -How it works: the CLI only serves the files of `dist`, with llama-server's headers for the UI (`index.html` cross-origin isolated, the PWA files revalidated, hashed assets cached for good), and forwards nothing. The browser talks to each llama-server you add in the app by URL directly, so llama-server's own rules apply: start it with `--cors-origins http://127.0.0.1:3000` (the address you open) when it restricts origins, as it does with tools or MCP enabled, and with `--api-key` when it is reachable from the LAN. An `http://` page like this one can reach a plain `http://` llama-server on the LAN, which an `https://` page cannot. +How it works: the CLI only serves the files of `dist`, with llama-server's headers for the UI (`index.html` cross-origin isolated, the PWA files revalidated, hashed assets cached for good), and forwards nothing. `--server` only puts the address in `llama-chat.json` next to `index.html`, which the app reads at startup to add the server; one you remove in the app stays removed. The CLI marks `index.html` with ``, and only a page with that tag asks for the file (`build --server` writes both). The browser talks to each llama-server directly, so llama-server's own rules apply: start it with `--cors-origins http://127.0.0.1:3000` (the address you open) when it restricts origins, as it does with tools or MCP enabled, and with `--api-key` when it is reachable from the LAN. An `http://` page like this one can reach a plain `http://` llama-server on the LAN, which an `https://` page cannot. ## Self-hosting @@ -84,15 +85,17 @@ Llama Chat is the first app on Llama UI, and the reference for the line between The app imports the library as `@ggml-org/llama-ui/ui/` and compiles its sources in its own build, with no install of the library (see `scripts/vite-plugin-llama-ui.ts`). Data flows one way, through these layers: -| Layer | Lives in | What it holds | -| -------------- | ------------------------- | --------------------------------------------------------------------------------------------------- | -| Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` | -| App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area | -| UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI | -| Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard | -| Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings | -| Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox | -| Storage + API | the browser, llama-server | IndexedDB and localStorage; llama-server's `/v1`, `/props`, `/models`, `/tools`, `/slots` | +| Layer | Lives in | What it holds | +| -------------- | ------------------------- | ---------------------------------------------------------------------------------------------------- | +| Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` | +| App components | `src/lib/components/app` | Chat, navigation, models, settings and dialogs, grouped by area | +| UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI | +| Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard | +| Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings | +| Agentic loop | `ui/lib/harness` | Llama Harness: streams a turn, runs the tools the model called, repeats until it answers without one | +| Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, the Hugging Face Hub, the tool sandbox | +| Extensions | `src/lib/extensions` | Features that can be switched off, MCP first: what they add to the app's extension points | +| Storage + API | the browser, llama-server | IndexedDB and localStorage; llama-server's `/v1`, `/props`, `/models`, `/tools`, `/slots` | ```mermaid flowchart LR @@ -104,6 +107,7 @@ flowchart LR Services --> DB[("IndexedDB, localStorage")] Services --> API["llama-server"] Components -. "imports" .-> UI["Llama UI"] + Ext["Extensions, such as MCP"] -. "extension points" .-> Stores Stores -. "reactive state" .-> Components ``` @@ -140,7 +144,32 @@ sequenceDiagram - **Messages form a tree**: each message knows its parent and children, and a conversation points at the branch tip it shows, so editing or regenerating branches without losing history. - **Server role**: one codebase serves MODEL and ROUTER mode; `serverStore` reads the role from `/props`, and ROUTER-only UI shows only there. - **Modalities**: attachments a model cannot read (images for a text-only model, say) are refused before sending, from the model's `/props`. -- **Storage**: conversations and messages in IndexedDB (Dexie), settings and model preferences in localStorage, server state and Hub details in memory only. +- **Storage**: conversations and messages in IndexedDB (idb), settings and model preferences in localStorage, server state and Hub details in memory only. + +### Extensions (`src/lib/extensions/`) + +An extension is a feature the app is composed with and that can be switched off. The registry (`registry.svelte.ts`) knows the built-in extensions (`builtin.ts`), activates the ones that are on at startup, and holds what they add to each extension point (`points/`): tools, flow hooks, sidebar entries, pages, slash commands, pickers, pending attachments, message and attachment renderers, and prompts offered as system messages. + +The core never imports an extension's own code; an extension may import the core. ESLint enforces this: a file outside `src/lib/extensions//` cannot import from that folder. + +Extensions are switched on and off in Settings, in the Extensions section. A switch takes effect at once: the extension's contributions go away and its cleanups run (MCP closes its connections). The choice is kept in localStorage and read at startup. + +MCP is the first extension. All of its code is in `src/lib/extensions/mcp/`: + +| Part | Responsibility | +| -------------------------- | ------------------------------------------------------------------------------------------------- | +| `index.ts` and glue | The extension: what MCP adds to each extension point (`tools.ts`, `composer.ts`, `pages.ts`, ...) | +| `stores/` (`mcpStore`) | MCP host role: multi-server lifecycle, tool routing, server icons; composes `health`, `resources` | +| `services/` (`MCPService`) | MCP protocol: transports, connect, list/execute tools, prompts, resources | +| `components/` | Server cards and forms, resource browser, dialogs, the prompt picker and the chat renderers | + +MCP's shared data stays in the core: types, enums, constants, `utils/mcp.ts`, settings keys and the stored message formats. + +MCP servers come two ways. A remote server (Streamable HTTP, SSE or WebSocket) is one the browser connects to by URL, added on the MCP servers page. A local server that runs as a command (stdio) is one llama-server starts from `--mcp-servers-config`, since a page cannot start a process: llama-server lists its tools in `/tools` with the type `mcp` and the server's name in `mcp_server`, and runs them on `POST /tools`. The MCP extension takes those tools over from the core's server tools (`serverToolType` on its tool provider, see `llama-server.ts`), so both kinds show up the same way, one group per server, on the MCP servers page and in the tools menu. With the extension off, the core lists them as server tools again. + +A setting can name the extension it belongs to (`extension` in `SETTINGS_REGISTRY`): its field shows only while that extension is on, and the stored value stays either way. + +llama-server embeds the app as a single bundle, so an extension's code ships whether it is on or off; nothing of it runs while it is off. ### Cross-origin isolation diff --git a/ui/apps/chat/cli/server.js b/ui/apps/chat/cli/server.js index 8ef0f557c3a4..70a7a33c80cd 100644 --- a/ui/apps/chat/cli/server.js +++ b/ui/apps/chat/cli/server.js @@ -6,12 +6,15 @@ * * It only serves files and forwards nothing: the browser calls each llama-server the app is * pointed at directly, so llama-server's own rules (--cors-origins, --api-key) apply as they do - * to any other page. + * to any other page. `--server` only tells the app which servers to add: the CLI serves them in + * `llama-chat.json` next to index.html, and `build` writes that file, which the app reads at + * startup. index.html carries a marker for it, so a page served any other way, such as by + * llama-server or the dev server, does not ask for a file that is not there. */ import { spawn } from 'node:child_process'; import { createReadStream, readFileSync } from 'node:fs'; -import { cp, readdir, stat } from 'node:fs/promises'; +import { cp, readdir, readFile, stat, writeFile } from 'node:fs/promises'; import http from 'node:http'; import { extname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -28,6 +31,15 @@ export const DEFAULTS = Object.freeze({ port: 3000 }); +/** The file next to index.html that lists the servers the app adds at startup. */ +export const PRESET_FILE = 'llama-chat.json'; + +/** + * The marker in index.html that sends the app to `llama-chat.json`. It names the file rather + * than the servers: the service worker keeps index.html, so servers in it would outlive a run. + */ +export const PRESET_META = ``; + // The same caching llama-server applies to the UI it embeds (tools/server/server-http.cpp): // index.html and the PWA's update checks are revalidated, hashed assets are cached for good. const NO_CACHE = new Set([ @@ -36,7 +48,8 @@ const NO_CACHE = new Set([ '/sw.js', '/manifest.webmanifest', '/_app/version.json', - '/build.json' + '/build.json', + `/${PRESET_FILE}` ]); const CACHE_IMMUTABLE = 'public, max-age=31536000, immutable'; const CACHE_REVALIDATE = 'no-cache'; @@ -65,13 +78,15 @@ const SERVE_OPTIONS = ['host', 'open', 'port']; const BUILD_OPTIONS = ['force', 'out']; export const USAGE = `Usage: llama-chat [options] - llama-chat build [--out ] [--force] + llama-chat build [--out ] [--force] [--server ] Serves Llama Chat on localhost as static files, or, with build, writes them to a folder for any HTTP server. The browser talks to llama-server directly: start it with --cors-origins set to this page's address when it restricts origins. Options: + --server a llama-server the app adds on startup, repeatable; the API + key, if it needs one, goes in the app --port port to listen on (default: ${DEFAULTS.port}) --host address to listen on, 0.0.0.0 for the LAN (default: ${DEFAULTS.host}) --open open the browser once it listens (default) @@ -82,11 +97,12 @@ Options: Build options: --out folder to write to (default: ./${DEFAULTS.out}) --force write into a folder that is not empty + --server as above, written to ${PRESET_FILE} in the folder Examples: - npx @ggml-org/llama-chat + npx @ggml-org/llama-chat --server http://127.0.0.1:9931 npx @ggml-org/llama-chat --host 0.0.0.0 --port 3000 --no-open - npx @ggml-org/llama-chat build --out ./public`; + npx @ggml-org/llama-chat build --out ./public --server https://llm.example.com`; /** The version in this package's package.json. */ export function packageVersion() { @@ -97,7 +113,7 @@ export function packageVersion() { * Reads the command line. No verb serves the app, `start` means the same, and `build` writes it * to a folder. * @param {string[]} argv the arguments after the command - * @returns {{ command: 'build' | 'serve', force: boolean, help: boolean, host: string, open: boolean, out: string, port: number, version: boolean }} + * @returns {{ command: 'build' | 'serve', force: boolean, help: boolean, host: string, open: boolean, out: string, port: number, servers: string[], version: boolean }} */ export function parseCliArgs(argv) { const { positionals, values } = parseArgs({ @@ -111,6 +127,7 @@ export function parseCliArgs(argv) { open: { type: 'boolean' }, out: { type: 'string' }, port: { type: 'string' }, + server: { multiple: true, type: 'string' }, version: { short: 'v', type: 'boolean' } }, strict: true @@ -146,10 +163,54 @@ export function parseCliArgs(argv) { open: values.open ?? true, out: values.out ?? DEFAULTS.out, port, + servers: (values.server ?? []).map(parseServerUrl), version: values.version ?? false }; } +/** + * A llama-server address for the app, with or without `http://`, as the app stores it: no + * trailing slash, a path kept (for `--api-prefix`). + * @param {string} value + */ +export function parseServerUrl(value) { + let url; + + try { + url = new URL(/^[a-z][a-z\d+.-]*:\/\//i.test(value) ? value : `http://${value}`); + } catch { + throw new Error(`invalid --server: ${value}`); + } + + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new Error(`invalid --server: ${value} (use an http:// or https:// address)`); + } + + if (url.search || url.hash || url.username || url.password) { + throw new Error(`invalid --server: ${value} (no query, fragment or credentials)`); + } + + return url.href.replace(/\/+$/, ''); +} + +/** + * index.html with the marker for `llama-chat.json` at the end of its head, once. + * @param {string} html + */ +export function withPresetMeta(html) { + if (html.includes('name="llama-chat-servers"')) return html; + + return html.replace('', `\t${PRESET_META}\n\t`); +} + +/** + * The contents of `llama-chat.json`. + * @param {string[]} servers + */ +export function presetFile(servers) { + return `${JSON.stringify({ servers: servers.map((url) => ({ url })) }, null, '\t')}\n`; +} + /** * Maps a request path to a file under `root`, or null when it falls outside it. * @param {string} root @@ -181,7 +242,10 @@ function resolveStatic(root, pathname) { */ function sendFile(req, res, file, pathname, stats) { const name = pathname === '/' ? '/index.html' : pathname; - const etag = `W/"${stats.size.toString(16)}-${Math.floor(stats.mtimeMs).toString(16)}"`; + // index.html goes out with the marker for llama-chat.json, and an ETag of its own + const body = + name === '/index.html' ? Buffer.from(withPresetMeta(readFileSync(file, 'utf8'))) : null; + const etag = `W/"${(body?.length ?? stats.size).toString(16)}-${Math.floor(stats.mtimeMs).toString(16)}"`; res.setHeader('ETag', etag); res.setHeader('Cache-Control', NO_CACHE.has(name) ? CACHE_REVALIDATE : CACHE_IMMUTABLE); @@ -201,7 +265,7 @@ function sendFile(req, res, file, pathname, stats) { 'Content-Type', MIME_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream' ); - res.setHeader('Content-Length', stats.size); + res.setHeader('Content-Length', body?.length ?? stats.size); res.writeHead(200); if (req.method === 'HEAD') { @@ -210,6 +274,12 @@ function sendFile(req, res, file, pathname, stats) { return; } + if (body) { + res.end(body); + + return; + } + createReadStream(file).pipe(res); } @@ -224,11 +294,13 @@ function sendError(res, status, message) { } /** - * The HTTP server: the files of `dist`, read-only. - * @param {{ distDir?: string }} [options] + * The HTTP server: the files of `dist`, read-only, and `llama-chat.json` with the servers given, + * if any: index.html always points the app at it. + * @param {{ distDir?: string, servers?: string[] }} [options] */ -export function createChatServer({ distDir = DIST_DIR } = {}) { +export function createChatServer({ distDir = DIST_DIR, servers = [] } = {}) { const root = normalize(distDir); + const preset = Buffer.from(presetFile(servers)); return http.createServer(async (req, res) => { const { pathname } = new URL(req.url ?? '/', 'http://localhost'); @@ -240,6 +312,17 @@ export function createChatServer({ distDir = DIST_DIR } = {}) { return; } + if (pathname === `/${PRESET_FILE}`) { + res.writeHead(200, { + 'Cache-Control': CACHE_REVALIDATE, + 'Content-Length': preset.length, + 'Content-Type': MIME_TYPES['.json'] + }); + res.end(req.method === 'HEAD' ? undefined : preset); + + return; + } + const file = resolveStatic(root, pathname); const stats = file ? await stat(file).catch(() => null) : null; @@ -255,11 +338,12 @@ export function createChatServer({ distDir = DIST_DIR } = {}) { /** * Writes the app to a folder: the files of `dist` without source maps, ready for any static - * file server. Refuses a folder that is not empty unless `force` is set, and a folder in `dist`. - * @param {{ distDir?: string, force?: boolean, out: string }} options + * file server, and `llama-chat.json` when servers are given, with the marker in index.html. Refuses a folder that is not empty + * unless `force` is set, and a folder in `dist`. + * @param {{ distDir?: string, force?: boolean, out: string, servers?: string[] }} options * @returns {Promise} the absolute path of the folder */ -export async function buildStatic({ distDir = DIST_DIR, force = false, out }) { +export async function buildStatic({ distDir = DIST_DIR, force = false, out, servers = [] }) { const source = resolve(distDir); const target = resolve(out); const inside = relative(source, target); @@ -276,6 +360,13 @@ export async function buildStatic({ distDir = DIST_DIR, force = false, out }) { await cp(source, target, { filter: (file) => !file.endsWith('.map'), recursive: true }); + if (servers.length > 0) { + const index = join(target, 'index.html'); + + await writeFile(join(target, PRESET_FILE), presetFile(servers)); + await writeFile(index, withPresetMeta(await readFile(index, 'utf8'))); + } + return target; } @@ -339,10 +430,17 @@ export async function main(argv) { if (options.command === 'build') { try { - const target = await buildStatic({ force: options.force, out: options.out }); + const target = await buildStatic({ + force: options.force, + out: options.out, + servers: options.servers + }); const shown = relative(process.cwd(), target) || '.'; console.log(`Llama Chat ${packageVersion()} written to ${target}`); + + for (const server of options.servers) console.log(`Adds the llama-server at ${server}`); + console.log(`Serve it with any static file server, e.g.: npx http-server ${shown}`); } catch (error) { console.error(`llama-chat: ${error instanceof Error ? error.message : error}`); @@ -352,7 +450,7 @@ export async function main(argv) { return; } - const server = createChatServer(); + const server = createChatServer({ servers: options.servers }); return new Promise((resolve) => { server.on('error', (error) => { @@ -373,6 +471,9 @@ export async function main(argv) { const url = `http://${shown.includes(':') ? `[${shown}]` : shown}:${address.port}/`; console.log(`Llama Chat ${packageVersion()} on ${url}`); + + for (const server of options.servers) console.log(`Adds the llama-server at ${server}`); + console.log( `If llama-server restricts origins (tools or MCP on), start it with --cors-origins ${url.slice(0, -1)}` ); diff --git a/ui/apps/chat/demo/fixtures/mcp-servers.ts b/ui/apps/chat/demo/fixtures/mcp-servers.ts index 15529e4a314e..46b637c670da 100644 --- a/ui/apps/chat/demo/fixtures/mcp-servers.ts +++ b/ui/apps/chat/demo/fixtures/mcp-servers.ts @@ -8,8 +8,8 @@ */ import { DEMO_MCP_PORT, DEMO_MCP_SERVERS, type DemoMcpServer } from './demo-config.ts'; -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; -import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; +import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node'; +import { McpServer } from '@modelcontextprotocol/server'; import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; import { z } from 'zod'; @@ -19,7 +19,7 @@ function buildServer(fixture: DemoMcpServer): McpServer { for (const tool of fixture.tools) { server.registerTool( tool.name, - { description: tool.description, inputSchema: { query: z.string().optional() } }, + { description: tool.description, inputSchema: z.object({ query: z.string().optional() }) }, async () => ({ content: [{ text: tool.result, type: 'text' }] }) ); } @@ -72,7 +72,7 @@ const httpServer = createServer(async (req, res) => { } const server = buildServer(fixture); - const transport = new StreamableHTTPServerTransport({ + const transport = new NodeStreamableHTTPServerTransport({ enableJsonResponse: true, sessionIdGenerator: undefined }); diff --git a/ui/apps/chat/docs/storage-adapters.md b/ui/apps/chat/docs/storage-adapters.md new file mode 100644 index 000000000000..37e2e27fc0ab --- /dev/null +++ b/ui/apps/chat/docs/storage-adapters.md @@ -0,0 +1,115 @@ +# Storage adapters + +By default the UI keeps conversations, groups, projects, prompts and settings in the browser (IndexedDB and localStorage). A storage adapter keeps them somewhere else instead. The built-in one is llama-server's own JSON document store (`llama-server --ui-storage`). You can add your own for Postgres (Supabase, Neon), PocketBase or any other database. + +```mermaid +flowchart LR + stores[Stores] --> db[DatabaseService
tree rules] + db --> backend{StorageBackend} + backend --> idb[IdbBackend
this browser] + backend --> dsb[DocumentStoreBackend
cache, batching, conflict replay] + dsb --> adapter{StorageAdapter} + adapter --> ls[llama-server
/storage routes] + adapter --> pg[your adapter
Postgres, PocketBase, ...] +``` + +## The contract + +An adapter stores one **document per conversation**: `{ rev, conv, messages }`. It doesn't need to understand the document. It only stores it as a whole and enforces one rule: + +- **Compare and swap on `rev`.** `putConversation(doc)` writes only if the store still holds revision `doc.rev`, where `0` means the document must not exist yet. It returns the new revision. Otherwise it throws `StorageConflictError` and writes nothing. This check and the write must be atomic. + +`DocumentStoreBackend` uses that rule to merge edits from two tabs or browsers: on a conflict it fetches the fresh document, replays its own edits and retries. + +Settings are plain string key/value pairs, merged per key: `updateSettings(set, remove)` must leave other keys untouched. The API key never reaches an adapter; it stays in the browser. + +Records are the small standalone objects next to conversations, one kind per table: `groups`, `projects` and `prompts`. Each has an `id`. `listRecords(kind)` returns all of a kind, and `updateRecords(kind, set, remove)` writes `set` whole and deletes `remove` by id, leaving the other records untouched. Last write wins per record. New kinds the UI adds later go through the same two methods, so a store keyed by kind and id needs no change for them. + +See `StorageAdapter` in `src/lib/types/storage.d.ts` for the full interface (eight methods). + +## Adding one + +1. Implement `StorageAdapter` in `src/lib/storage-adapters/.adapter.ts`, next to `llama-server.adapter.ts`. +2. Export a `StorageAdapterDefinition` (`id`, `name`, `description`, `isAvailable`, `create`) and add it to `STORAGE_ADAPTERS` in `src/lib/storage-adapters/index.ts`. +3. Build the UI. Settings → Import/Export → Storage then offers "Store on " wherever `isAvailable` returns true, and copies the browser's data over when the user picks it. + +Configuration such as a URL or a public key usually comes from build-time env vars (`import.meta.env.VITE_*`). Make `isAvailable` return false when they are missing. + +The in-memory adapter in `tests/unit/document-store-backend.test.ts` is the smallest working example. + +## Postgres: Supabase, Neon + +Store the document as JSON columns, and do the compare and swap in one SQL function: + +```sql +create table llama_ui_conversations ( + id text primary key, + rev integer not null, + conv jsonb not null, + messages jsonb not null +); + +create table llama_ui_settings ( + key text primary key, + value text not null +); + +create table llama_ui_records ( + kind text not null, + id text not null, + record jsonb not null, + primary key (kind, id) +); + +-- returns the new revision, or null when `doc.rev` is stale +create function llama_ui_put_conversation(doc jsonb) returns integer +language plpgsql as $$ +declare + base integer := (doc->>'rev')::integer; + new_rev integer; +begin + if base = 0 then + insert into llama_ui_conversations (id, rev, conv, messages) + values (doc->'conv'->>'id', 1, doc->'conv', doc->'messages') + on conflict (id) do nothing + returning rev into new_rev; + else + update llama_ui_conversations + set rev = rev + 1, conv = doc->'conv', messages = doc->'messages' + where id = doc->'conv'->>'id' and rev = base + returning rev into new_rev; + end if; + return new_rev; +end $$; +``` + +Supabase and Neon (Data API) both expose this over PostgREST, so the adapter is a thin wrapper around `fetch`: + +| Method | Request | +| -------------------- | --------------------------------------------------------------------------------------------------- | +| `listConversations` | `GET /llama_ui_conversations?select=rev,conv` | +| `getConversation` | `GET /llama_ui_conversations?id=eq.&select=rev,conv,messages`, first row or null | +| `putConversation` | `POST /rpc/llama_ui_put_conversation` with `{ "doc": ... }`; a null result → `StorageConflictError` | +| `deleteConversation` | `DELETE /llama_ui_conversations?id=eq.` | +| `getSettings` | `GET /llama_ui_settings`, rows into an object | +| `updateSettings` | upsert with `Prefer: resolution=merge-duplicates`, then `DELETE ?key=in.(...)` | +| `listRecords` | `GET /llama_ui_records?kind=eq.&select=record` | +| `updateRecords` | upsert `{ kind, id, record }` rows, then `DELETE ?kind=eq.&id=in.(...)` | + +Whatever key the adapter sends is in the built UI bundle, readable by anyone who loads the page. Protect the tables with row level security tied to a signed-in user (for example Supabase Auth), not with a key alone. + +Add a `user_id` column to every table if several people share the database. + +## PocketBase + +Create three collections: + +- `conversations`, with `conv_id` (text, unique), `rev` (number), `conv` (json) and `messages` (json). +- `settings`, with `key` (text, unique) and `value` (text). +- `records`, with `kind` (text), `record_id` (text) and `record` (json), unique on `kind` + `record_id`. + +PocketBase's record API has no conditional update, so do the compare and swap in a custom route in `pb_hooks`. Inside `$app.runInTransaction`, read the record, compare `rev`, then save it with `rev + 1`. Answer 409 on a mismatch, and have the adapter turn that 409 into `StorageConflictError`. + +## Going lower level + +If you'd rather store messages as rows, for example as normalized Postgres tables, implement `StorageBackend` (`src/lib/types/database.d.ts`) directly, the way `IdbBackend` does. Then pass it to `DatabaseService.useBackend`. Your backend then has to provide transactions across conversations, messages and records itself; the document model above exists to avoid that requirement. diff --git a/ui/apps/chat/eslint.config.js b/ui/apps/chat/eslint.config.js index 330551d9d8d1..8b03c8098097 100644 --- a/ui/apps/chat/eslint.config.js +++ b/ui/apps/chat/eslint.config.js @@ -8,6 +8,7 @@ import simpleImportSort from 'eslint-plugin-simple-import-sort'; import storybook from 'eslint-plugin-storybook'; import svelte from 'eslint-plugin-svelte'; import globals from 'globals'; +import path from 'node:path'; import { fileURLToPath } from 'node:url'; import ts from 'typescript-eslint'; @@ -157,6 +158,86 @@ const blankLineBetweenAccessors = { type: 'layout' } }; +// The core never imports an extension's own code; an extension may import the +// core. A module under src/lib/extensions// can only be imported by a file +// in that same folder. The registry's own files (the index, builtin, +// registry.svelte, types and points/*) stay importable from anywhere, and +// builtin.ts loads each extension's entry with a dynamic import. +const LIB_DIR = fileURLToPath(new URL('./src/lib', import.meta.url)); +const EXTENSIONS_DIR = path.join(LIB_DIR, 'extensions'); +const EXTENSIONS_PUBLIC_FILES = new Set(['builtin', 'index', 'registry.svelte', 'types']); +const noExtensionInternals = { + create(context) { + // path of a file inside src/lib/extensions as segments, or null for a file outside it + function extensionSegments(file) { + const relative = path.relative(EXTENSIONS_DIR, file); + + if (relative.startsWith('..') || path.isAbsolute(relative)) return null; + + return relative === '' ? [] : relative.split(path.sep); + } + + function check(node, source, isDynamic) { + if (typeof source !== 'string') return; + + let target; + + if (source.startsWith('#lib/')) { + target = path.join(LIB_DIR, source.slice('#lib'.length)); + } else if (source.startsWith('.')) { + target = path.resolve(path.dirname(context.filename), source); + } else { + return; + } + + const segments = extensionSegments(target); + + if (!segments || segments.length === 0 || segments[0] === 'points') return; + + const id = segments[0]; + + if (segments.length === 1 && EXTENSIONS_PUBLIC_FILES.has(id.replace(/\.[jt]s$/, ''))) return; + + const importer = extensionSegments(context.filename); + + if (importer && importer.length > 1 && importer[0] === id) return; + + const isEntry = + segments.length === 1 || (segments.length === 2 && /^index(\.[jt]s)?$/.test(segments[1])); + + // the one place that names the extensions: it loads the entry of each, lazily + if (isDynamic && isEntry && importer?.length === 1 && importer[0] === 'builtin.ts') return; + + context.report({ data: { id, source }, messageId: 'internal', node }); + } + + return { + ExportAllDeclaration(node) { + check(node, node.source.value, false); + }, + ExportNamedDeclaration(node) { + if (node.source) check(node, node.source.value, false); + }, + ImportDeclaration(node) { + check(node, node.source.value, false); + }, + ImportExpression(node) { + if (node.source.type === 'Literal') check(node, node.source.value, true); + } + }; + }, + meta: { + docs: { + description: "Keep an extension's own code out of the rest of the app." + }, + messages: { + internal: + '"{{source}}" is the own code of the "{{id}}" extension. Only files in src/lib/extensions/{{id}}/ can import it; the rest of the app uses the extension points.' + }, + schema: [], + type: 'problem' + } +}; export default ts.config( includeIgnoreFile(gitignorePath), @@ -171,6 +252,7 @@ export default ts.config( local: { rules: { 'blank-line-between-accessors': blankLineBetweenAccessors, + 'no-extension-internals': noExtensionInternals, 'padding-line-between-elements': paddingLineBetweenElements } }, @@ -189,6 +271,8 @@ export default ts.config( 'eol-last': 'error', // Enforce a blank line between consecutive get/set accessors 'local/blank-line-between-accessors': 'error', + // The core does not import an extension's own code + 'local/no-extension-internals': 'error', // Require a blank line between sibling elements in a Svelte template 'local/padding-line-between-elements': 'error', // typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects. @@ -266,7 +350,6 @@ export default ts.config( 'simple-import-sort/imports': ['error', { groups: [['.*']] }], 'svelte/no-at-html-tags': 'off', // This app uses hash-based routing (#/) where resolve() from $app/paths does not apply - 'svelte/no-navigation-without-resolve': 'off', // Sort HTML attributes alphabetically in the markup. The Svelte directives // (bind:/use:/animate:/style:/in:/out:/transition:/class:) sort first, @@ -321,6 +404,17 @@ export default ts.config( } } }, + { + // type information for the app's own modules too, so svelte/no-navigation-without-resolve + // accepts a URL typed as ResolvedPathname, such as RouterService.chat(id) + files: ['src/**/*.ts'], + languageOptions: { parserOptions: { projectService: true } } + }, + { + // Tests and stories exercise an extension's code directly + files: ['tests/**'], + rules: { 'local/no-extension-internals': 'off' } + }, { // Exclude generated build output and Storybook files from ESLint ignores: [ diff --git a/ui/apps/chat/package-lock.json b/ui/apps/chat/package-lock.json index ef7891ba3e38..d29105211fe6 100644 --- a/ui/apps/chat/package-lock.json +++ b/ui/apps/chat/package-lock.json @@ -24,7 +24,9 @@ "@internationalized/date": "3.12.2", "@lezer/highlight": "1.2.5", "@lucide/svelte": "1.46.0", - "@modelcontextprotocol/sdk": "1.32.1", + "@modelcontextprotocol/client": "2.4.0", + "@modelcontextprotocol/node": "2.1.2", + "@modelcontextprotocol/server": "2.4.0", "@playwright/test": "1.56.1", "@storybook/addon-a11y": "10.6.6", "@storybook/addon-docs": "10.6.6", @@ -47,7 +49,6 @@ "@vitest/coverage-v8": "4.1.12", "bits-ui": "2.18.1", "clsx": "2.1.1", - "dexie": "4.4.3", "dompurify": "3.4.17", "eslint": "10.14.0", "eslint-config-prettier": "10.1.8", @@ -59,6 +60,7 @@ "globals": "16.5.0", "highlight.js": "11.11.1", "http-server": "14.1.1", + "idb": "8.0.4", "mdsvex": "0.12.7", "mode-watcher": "1.1.0", "pdfjs-dist": "5.4.54", @@ -89,6 +91,7 @@ "typescript-eslint": "8.72.1", "unified": "11.0.5", "unist-util-visit": "5.1.0", + "uqr": "0.1.3", "uuid": "13.0.2", "vaul-svelte": "1.0.0-next.7", "vite": "8.3.6", @@ -1937,45 +1940,67 @@ "react": ">=16" } }, - "node_modules/@modelcontextprotocol/sdk": { - "version": "1.32.1", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz", - "integrity": "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==", + "node_modules/@modelcontextprotocol/client": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz", + "integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==", "dev": true, - "license": "MIT", + "license": "Apache-2.0", "dependencies": { - "@hono/node-server": "^1.19.9 || ^2.0.5", - "ajv": "^8.17.1", - "ajv-formats": "^3.0.1", - "content-type": "^1.0.5", - "cors": "^2.8.5", + "@modelcontextprotocol/core": "2.4.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", - "eventsource-parser": "^3.0.0", - "express": "^5.2.1", - "express-rate-limit": "^8.2.1", - "hono": "^4.11.4", + "eventsource-parser": "^3.0.8", "jose": "^6.1.3", - "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", - "raw-body": "^3.0.0", - "zod": "^3.25 || ^4.0", - "zod-to-json-schema": "^3.25.1" + "zod": "^4.2.0" }, "engines": { - "node": ">=18" + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz", + "integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/node": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.1.2.tgz", + "integrity": "sha512-IIcIqBpr6NCQQs5DgJTgvbSOAw+3iaR/uquqg+e0nXCdudfjPg/80x0TseUnQx14AUAtE4fsJCEpJKPyb6WPVA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@hono/node-server": "^1.19.9 || ^2.1.3", + "hono": "^4.11.4" + }, + "engines": { + "node": ">=20" }, "peerDependencies": { - "@cfworker/json-schema": "^4.1.1", - "zod": "^3.25 || ^4.0" + "@modelcontextprotocol/server": "^2.4.0" + } + }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.4.0.tgz", + "integrity": "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/core": "2.4.0", + "zod": "^4.2.0" }, - "peerDependenciesMeta": { - "@cfworker/json-schema": { - "optional": true - }, - "zod": { - "optional": false - } + "engines": { + "node": ">=20" } }, "node_modules/@napi-rs/canvas": { @@ -5230,20 +5255,6 @@ "dev": true, "license": "MIT" }, - "node_modules/accepts": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", - "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-types": "^3.0.0", - "negotiator": "^1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, "node_modules/acorn": { "version": "8.19.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", @@ -5267,41 +5278,6 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, - "node_modules/ajv": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", - "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ajv-formats": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", - "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^8.0.0" - }, - "peerDependencies": { - "ajv": "^8.0.0" - }, - "peerDependenciesMeta": { - "ajv": { - "optional": true - } - } - }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -5484,45 +5460,6 @@ } } }, - "node_modules/body-parser": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", - "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "bytes": "^3.1.2", - "content-type": "^2.1.0", - "debug": "^4.4.3", - "http-errors": "^2.0.1", - "iconv-lite": "^0.7.3", - "on-finished": "^2.4.1", - "qs": "^6.16.1", - "raw-body": "^3.0.2", - "type-is": "^2.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/body-parser/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/brace-expansion": { "version": "5.0.12", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", @@ -5552,16 +5489,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/cac": { "version": "6.7.14", "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", @@ -5813,30 +5740,6 @@ "node": "^14.18.0 || >=16.10.0" } }, - "node_modules/content-disposition": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", - "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -5858,34 +5761,6 @@ "url": "https://opencollective.com/express" } }, - "node_modules/cookie-signature": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", - "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.6.0" - } - }, - "node_modules/cors": { - "version": "2.8.6", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", - "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", - "dev": true, - "license": "MIT", - "dependencies": { - "object-assign": "^4", - "vary": "^1" - }, - "engines": { - "node": ">= 0.10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/corser": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", @@ -6106,16 +5981,6 @@ "dev": true, "license": "MIT" }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -6157,13 +6022,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/dexie": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/dexie/-/dexie-4.4.3.tgz", - "integrity": "sha512-N+3IGQ3HPlyO2YAkntGAwitm42BpBGV86MttzUMiRzWLa4NGh0pltVRcUVF4ybL/OnXjCrr9k7SDPIKkFYP2Lg==", - "dev": true, - "license": "Apache-2.0" - }, "node_modules/dom-accessibility-api": { "version": "0.5.16", "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", @@ -6196,27 +6054,6 @@ "node": ">= 0.4" } }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "dev": true, - "license": "MIT" - }, - "node_modules/encodeurl": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.1.tgz", - "integrity": "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/enhanced-resolve": { "version": "5.26.1", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.1.tgz", @@ -6339,13 +6176,6 @@ "@esbuild/win32-x64": "0.28.2" } }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "dev": true, - "license": "MIT" - }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -6724,16 +6554,6 @@ "node": ">=0.10.0" } }, - "node_modules/etag": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", - "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/eventemitter3": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", @@ -6774,84 +6594,6 @@ "node": ">=12.0.0" } }, - "node_modules/express": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", - "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", - "dev": true, - "license": "MIT", - "dependencies": { - "accepts": "^2.0.0", - "body-parser": "^2.3.0", - "content-disposition": "^2.0.1", - "content-type": "^2.0.0", - "cookie": "^0.7.1", - "cookie-signature": "^1.2.1", - "debug": "^4.4.0", - "depd": "^2.0.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "finalhandler": "^2.1.0", - "fresh": "^2.0.0", - "http-errors": "^2.0.0", - "merge-descriptors": "^2.0.0", - "mime-types": "^3.0.0", - "on-finished": "^2.4.1", - "once": "^1.4.0", - "parseurl": "^1.3.3", - "proxy-addr": "^2.0.8", - "qs": "^6.16.0", - "range-parser": "^1.2.1", - "router": "^2.2.0", - "send": "^1.1.0", - "serve-static": "^2.2.0", - "statuses": "^2.0.1", - "type-is": "^2.1.0", - "vary": "^1.1.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/express-rate-limit": { - "version": "8.7.3", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.3.tgz", - "integrity": "sha512-zPLqDI2f0gV2WmGnacLf9XSSqn4VldRyP5LCzOwx0BKH40mO6+2PCFkoSsRO2jePx87/Kf6NUF6P2QOTKXHbQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.3", - "ip-address": "^10.2.0" - }, - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://github.com/sponsors/express-rate-limit" - }, - "peerDependencies": { - "express": ">= 4.11" - } - }, - "node_modules/express/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", @@ -6880,23 +6622,6 @@ "dev": true, "license": "MIT" }, - "node_modules/fast-uri": { - "version": "3.1.9", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", - "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -6932,28 +6657,6 @@ "flat-cache": "^6.1.23" } }, - "node_modules/finalhandler": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", - "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.0", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "on-finished": "^2.4.1", - "parseurl": "^1.3.3", - "statuses": "^2.0.1" - }, - "engines": { - "node": ">= 18.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -7011,26 +6714,6 @@ } } }, - "node_modules/forwarded": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", - "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fresh": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", - "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", @@ -7446,27 +7129,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/http-errors": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", - "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "depd": "~2.0.0", - "inherits": "~2.0.4", - "setprototypeof": "~1.2.0", - "statuses": "~2.0.2", - "toidentifier": "~1.0.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/http-proxy": { "version": "1.18.1", "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", @@ -7517,22 +7179,12 @@ "dev": true, "license": "MPL-2.0" }, - "node_modules/iconv-lite": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", - "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "node_modules/idb": { + "version": "8.0.4", + "resolved": "https://registry.npmjs.org/idb/-/idb-8.0.4.tgz", + "integrity": "sha512-jd0ITCrN+Zah4J7R/Z2jnR3W7A4BXDAjmo62MwWuSjxCiueUAf7X5rbodEdidWzeknwXHmLpdZkoiiCppNi30Q==", "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } + "license": "ISC" }, "node_modules/ignore": { "version": "5.3.2", @@ -7571,13 +7223,6 @@ "node": ">=8" } }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, - "license": "ISC" - }, "node_modules/inline-style-parser": { "version": "0.2.7", "resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz", @@ -7585,26 +7230,6 @@ "dev": true, "license": "MIT" }, - "node_modules/ip-address": { - "version": "10.7.6", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", - "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, - "node_modules/ipaddr.js": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", - "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, "node_modules/is-docker": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", @@ -7676,13 +7301,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/is-promise": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", - "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", - "dev": true, - "license": "MIT" - }, "node_modules/is-reference": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", @@ -7789,20 +7407,6 @@ "dev": true, "license": "MIT" }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-schema-typed": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz", - "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==", - "dev": true, - "license": "BSD-2-Clause" - }, "node_modules/json-stable-stringify-without-jsonify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", @@ -8638,33 +8242,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/media-typer": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", - "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/merge-descriptors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", - "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/micromark": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", @@ -9311,33 +8888,6 @@ "node": ">=4" } }, - "node_modules/mime-db": { - "version": "1.54.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", - "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", - "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-db": "^1.54.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/min-indent": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", @@ -9499,37 +9049,6 @@ "node": ">=18" } }, - "node_modules/negotiator": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", - "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", - "dev": true, - "license": "MIT", - "dependencies": { - "content-type": "^2.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/negotiator/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/node-addon-api": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", @@ -9538,16 +9057,6 @@ "license": "MIT", "optional": true }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -9575,33 +9084,6 @@ "node": ">=12.20.0" } }, - "node_modules/on-finished": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", - "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, "node_modules/open": { "version": "10.2.0", "resolved": "https://registry.npmjs.org/open/-/open-10.2.0.tgz", @@ -9763,16 +9245,6 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -9793,17 +9265,6 @@ "node": ">=8" } }, - "node_modules/path-to-regexp": { - "version": "8.4.2", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", - "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", - "dev": true, - "license": "MIT", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -10242,24 +9703,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/proxy-addr": { - "version": "2.0.8", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", - "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "forwarded": "0.2.0", - "ipaddr.js": "1.9.1" - }, - "engines": { - "node": ">= 0.10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -10324,36 +9767,6 @@ ], "license": "MIT" }, - "node_modules/range-parser": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", - "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/raw-body": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", - "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "bytes": "~3.1.2", - "http-errors": "~2.0.1", - "iconv-lite": "~0.7.0", - "unpipe": "~1.0.0" - }, - "engines": { - "node": ">= 0.10" - } - }, "node_modules/react": { "version": "19.3.1", "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", @@ -10621,16 +10034,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", @@ -10682,23 +10085,6 @@ "url": "https://github.com/sponsors/oxc-project" } }, - "node_modules/router": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", - "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.0", - "depd": "^2.0.0", - "is-promise": "^4.0.0", - "parseurl": "^1.3.3", - "path-to-regexp": "^8.0.0" - }, - "engines": { - "node": ">= 18" - } - }, "node_modules/run-applescript": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz", @@ -10748,13 +10134,6 @@ "dev": true, "license": "MIT" }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true, - "license": "MIT" - }, "node_modules/sass": { "version": "1.100.0", "resolved": "https://registry.npmjs.org/sass/-/sass-1.100.0.tgz", @@ -10810,60 +10189,6 @@ "node": ">=10" } }, - "node_modules/send": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", - "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.4.3", - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "etag": "^1.8.1", - "fresh": "^2.0.0", - "http-errors": "^2.0.1", - "mime-types": "^3.0.2", - "ms": "^2.1.3", - "on-finished": "^2.4.1", - "range-parser": "^1.2.1", - "statuses": "^2.0.2" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/serve-static": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", - "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", - "dev": true, - "license": "MIT", - "dependencies": { - "encodeurl": "^2.0.0", - "escape-html": "^1.0.3", - "parseurl": "^1.3.3", - "send": "^1.2.0" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "dev": true, - "license": "ISC" - }, "node_modules/sharp": { "version": "0.35.5", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", @@ -11092,16 +10417,6 @@ "dev": true, "license": "MIT" }, - "node_modules/statuses": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", - "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/std-env": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", @@ -11693,16 +11008,6 @@ "dev": true, "license": "MIT" }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.6" - } - }, "node_modules/totalist": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz", @@ -11801,39 +11106,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/type-is": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", - "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", - "dev": true, - "license": "MIT", - "dependencies": { - "content-type": "^2.0.0", - "media-typer": "^1.1.0", - "mime-types": "^3.0.0" - }, - "engines": { - "node": ">= 18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/type-is/node_modules/content-type": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", - "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, "node_modules/typescript": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", @@ -12040,16 +11312,6 @@ "node": ">= 10.0.0" } }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/unplugin": { "version": "2.3.11", "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-2.3.11.tgz", @@ -12066,6 +11328,13 @@ "node": ">=18.12.0" } }, + "node_modules/uqr": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.3.tgz", + "integrity": "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==", + "dev": true, + "license": "MIT" + }, "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", @@ -12136,16 +11405,6 @@ } } }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/vaul-svelte": { "version": "1.0.0-next.7", "resolved": "https://registry.npmjs.org/vaul-svelte/-/vaul-svelte-1.0.0-next.7.tgz", @@ -12625,13 +11884,6 @@ "node": ">=0.10.0" } }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC" - }, "node_modules/ws": { "version": "8.22.2", "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", @@ -12700,16 +11952,6 @@ "url": "https://github.com/sponsors/colinhacks" } }, - "node_modules/zod-to-json-schema": { - "version": "3.25.2", - "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", - "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", - "dev": true, - "license": "ISC", - "peerDependencies": { - "zod": "^3.25.28 || ^4" - } - }, "node_modules/zwitch": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json index bc3f0d3315d1..223afabc19e2 100644 --- a/ui/apps/chat/package.json +++ b/ui/apps/chat/package.json @@ -83,7 +83,9 @@ "@internationalized/date": "3.12.2", "@lezer/highlight": "1.2.5", "@lucide/svelte": "1.46.0", - "@modelcontextprotocol/sdk": "1.32.1", + "@modelcontextprotocol/client": "2.4.0", + "@modelcontextprotocol/node": "2.1.2", + "@modelcontextprotocol/server": "2.4.0", "@playwright/test": "1.56.1", "@storybook/addon-a11y": "10.6.6", "@storybook/addon-docs": "10.6.6", @@ -106,7 +108,7 @@ "@vitest/coverage-v8": "4.1.12", "bits-ui": "2.18.1", "clsx": "2.1.1", - "dexie": "4.4.3", + "idb": "8.0.4", "dompurify": "3.4.17", "eslint": "10.14.0", "eslint-config-prettier": "10.1.8", @@ -149,6 +151,7 @@ "typescript-eslint": "8.72.1", "unified": "11.0.5", "unist-util-visit": "5.1.0", + "uqr": "0.1.3", "uuid": "13.0.2", "vaul-svelte": "1.0.0-next.7", "vite": "8.3.6", diff --git a/ui/apps/chat/sources.cmake b/ui/apps/chat/sources.cmake index 7e506c0eccf9..817bb9a22918 100644 --- a/ui/apps/chat/sources.cmake +++ b/ui/apps/chat/sources.cmake @@ -3,8 +3,9 @@ set(UI_SOURCE_GLOBS src/* static/* - # Llama UI, which the app compiles from source + # Llama UI and the harness, which the app compiles from source ../../lib/ui/src/lib/* + ../../lib/harness/src/* ) set(UI_SOURCE_FILES diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css index cca440844162..df5c707dd0d7 100644 --- a/ui/apps/chat/src/app.css +++ b/ui/apps/chat/src/app.css @@ -23,6 +23,11 @@ --safe-area-bottom: env(safe-area-inset-bottom, 0px); /* where the phone's corner controls (menu toggle, context gauge, sidebar logo) sit */ --corner-control-top: calc(1rem + var(--safe-area-top)); + /* where the phone's bottom corner actions (a page's floating key) sit: as far in from + the side as up from the bottom, which keeps a 56px key about concentric with an + iPhone's rounded screen corner */ + --corner-control-side: 1.75rem; + --corner-control-bottom: calc(var(--corner-control-side) + var(--safe-area-bottom)); /* where a phone page's title starts: a row below the corner controls */ --page-top: calc(var(--corner-control-top) + 3.75rem); /* expanded desktop sidebar width, overridden once the user drags its edge */ @@ -75,6 +80,9 @@ /* the installed app's status bar already sets them apart from the screen's edge */ :root { --corner-control-top: calc(0.25rem + var(--safe-area-top)); + /* the home indicator is a short bar in the middle, so the corners beside it are + free: a corner action ignores its inset and keeps the same gap as from the side */ + --corner-control-bottom: var(--corner-control-side); } html { @@ -295,11 +303,15 @@ } /* While something is dragged, what it passes over takes no hover: only the - sections themselves stay targets, for the drop */ + sections themselves, and the projects in them, stay targets, for the drop */ body[data-sidebar-dragging] [data-sidebar-section] * { pointer-events: none; } + body[data-sidebar-dragging] [data-sidebar-section] [data-sidebar-section] { + pointer-events: auto; + } + .sidebar-drag-overlay { position: fixed; z-index: 1000; @@ -354,6 +366,21 @@ animation: none; } } + + /* A page's entrance, for pages that remount on every navigation into them: + * the whole page fades in at once. A plain ease over 350ms spreads the + * fade evenly instead of front-loading it, so it reads as a calm arrival. + * Opacity only, so it runs on the compositor and stays for reduced motion + * too: a fade does not move anything. */ + .page-enter { + animation: page-enter 350ms ease; + } + + @keyframes page-enter { + from { + opacity: 0; + } + } } /* diff --git a/ui/apps/chat/src/app.d.ts b/ui/apps/chat/src/app.d.ts index 006a37a8cfaa..7b9e60c457f0 100644 --- a/ui/apps/chat/src/app.d.ts +++ b/ui/apps/chat/src/app.d.ts @@ -10,6 +10,7 @@ import type { ApiChatCompletionStreamChunk, ApiChatCompletionToolCall, ApiChatCompletionToolCallDelta, + ApiChatCompletionUsage, ApiChatMessageContentPart, ApiChatMessageData, ApiContextSizeError, @@ -72,6 +73,7 @@ declare global { ApiChatCompletionResponse, ApiChatCompletionStreamChunk, ApiChatCompletionToolCall, + ApiChatCompletionUsage, ApiChatCompletionToolCallDelta, ApiChatMessageData, ApiChatMessageContentPart, diff --git a/ui/apps/chat/src/lib/components/app/actions/FloatingActionButton.svelte b/ui/apps/chat/src/lib/components/app/actions/FloatingActionButton.svelte new file mode 100644 index 000000000000..0689c01a6dbe --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/actions/FloatingActionButton.svelte @@ -0,0 +1,30 @@ + + + + + + diff --git a/ui/apps/chat/src/lib/components/app/actions/index.ts b/ui/apps/chat/src/lib/components/app/actions/index.ts index 8b0279d06216..7a1db73a293a 100644 --- a/ui/apps/chat/src/lib/components/app/actions/index.ts +++ b/ui/apps/chat/src/lib/components/app/actions/index.ts @@ -14,3 +14,6 @@ export { default as ActionIconCopyToClipboard } from './ActionIconCopyToClipboar /** 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'; + +/** A page's main action on a phone: a round key pinned to the bottom-right corner. */ +export { default as FloatingActionButton } from './FloatingActionButton.svelte'; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte index cc9b940df6de..aafbd3ad47bc 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte @@ -2,12 +2,11 @@ import { ChatAttachmentsListItem, DialogChatAttachmentsPreview, - DialogMcpResourcePreview, ScrollCarousel } from '#lib/components/app/index.ts'; import { ScrollCarouselVariant } from '#lib/enums/index.ts'; - import type { DatabaseMessageExtraMcpResource } from '#lib/types/index.ts'; - import { getAttachmentDisplayItems, isMcpPrompt, isMcpResource } from '#lib/utils/index.ts'; + import { extensions, findAttachmentRenderer } from '#lib/extensions/index.ts'; + import { getAttachmentDisplayItems } from '#lib/utils/index.ts'; interface Props { class?: string; @@ -44,8 +43,6 @@ }: Props = $props(); let carouselRef: ScrollCarousel | undefined = $state(); - let mcpResourcePreviewOpen = $state(false); - let mcpResourcePreviewExtra = $state(null); let previewFocusIndex = $state(0); let viewAllDialogOpen = $state(false); @@ -55,19 +52,15 @@ event?.stopPropagation(); event?.preventDefault(); - // Find the index of the clicked item among non-MCP attachments - const nonMcpItems = displayItems.filter((i) => !isMcpPrompt(i) && !isMcpResource(i)); - const index = nonMcpItems.findIndex((i) => i.id === item.id); + // items an extension draws stay out of the built-in preview, so they do not count + const renderers = extensions.contributions('attachmentRenderers'); + const previewItems = displayItems.filter((i) => !findAttachmentRenderer(renderers, i)); + const index = previewItems.findIndex((i) => i.id === item.id); previewFocusIndex = index >= 0 ? index : 0; viewAllDialogOpen = true; } - function openMcpResourcePreview(extra: DatabaseMessageExtraMcpResource) { - mcpResourcePreviewExtra = extra; - mcpResourcePreviewOpen = true; - } - $effect(() => { if (carouselRef && displayItems.length) { carouselRef.resetScroll(); @@ -83,7 +76,6 @@ {item} {limitToSingleRow} {onFileRemove} - onMcpResourcePreview={openMcpResourcePreview} onPreview={(i: ChatAttachmentDisplayItem, event?: MouseEvent) => openPreview(i, event)} {readonly} /> @@ -114,7 +106,3 @@ {previewFocusIndex} {uploadedFiles} /> - -{#if mcpResourcePreviewExtra} - -{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte index 5bb7a47d71ea..e405100199e4 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte @@ -1,18 +1,12 @@ -{#if isMcpPrompt(item)} - {@const mcpPrompt = - item.attachment?.type === AttachmentType.MCP_PROMPT - ? (item.attachment as DatabaseMessageExtraMcpPrompt) - : item.uploadedFile?.mcpPrompt - ? { - arguments: item.uploadedFile.mcpPrompt.arguments, - content: item.textContent ?? '', - name: item.name, - promptName: item.uploadedFile.mcpPrompt.promptName, - serverName: item.uploadedFile.mcpPrompt.serverName, - type: AttachmentType.MCP_PROMPT as const - } - : null} - {#if mcpPrompt} - onFileRemove(item.id) : undefined} - prompt={mcpPrompt} - {readonly} - /> - {/if} -{:else if isMcpResource(item)} - {@const mcpResource = item.attachment as DatabaseMessageExtraMcpResource} - - onMcpResourcePreview?.(mcpResource)} +{#if renderer} + onFileRemove(item.id) : undefined} + {readonly} /> {:else if item.isImage && item.preview} !isMcpPrompt(item) && !isMcpResource(item)) + .filter((item) => !findAttachmentRenderer(attachmentRenderers, item)) .map( (item): PreviewItem => ({ ...item, diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index 0c44d125fb9c..d4a5f905477b 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -8,46 +8,41 @@ ChatFormCurrentWorkingDirectory, ChatFormInput, ChatFormInputFileInputInvisible, - ChatFormMcpResourcesList, ChatFormPickers, - DialogMcpResourcesBrowser + ChatFormProjectChip } from '#lib/components/app/index.ts'; import { CHAT_FORM_SINGLE_ROW_MAX_TEXT_PX, CLIPBOARD_CONTENT_QUOTE_PREFIX, ICON_CLASS_DEFAULT, - INITIAL_FILE_SIZE, - PROMPT_CONTENT_SEPARATOR, SETTING_CONFIG_DEFAULT } from '#lib/constants/index.ts'; import { - ContentPartType, FileExtensionText, KeyboardKey, MimeTypeText, - SpecialFileType, - ToolSource + SpecialFileType } from '#lib/enums/index.ts'; + import { + type ComposerHandle, + extensions, + type SystemPromptEntry, + type SystemPromptSource + } from '#lib/extensions/index.ts'; import { useChatFormExpansion } from '#lib/hooks/use-chat-form-expansion.svelte.ts'; import { useChatFormPickers } from '#lib/hooks/use-chat-form-pickers.svelte.ts'; import { chatStore, conversationsStore, deviceStore, - mcpStore, modelsStore, + projectsStore, serverStore, settingsStore, toolsStore, uiStore } from '#lib/stores/index.ts'; - import type { - FileMentionEntry, - GetPromptResult, - MCPPromptInfo, - MCPResourceInfo, - PromptMessage - } from '#lib/types/index.ts'; + import type { FileMentionEntry } from '#lib/types/index.ts'; import { AudioRecorder, convertToWav, @@ -93,6 +88,7 @@ onStop?: () => void; onSubmit?: () => void; onSystemPromptClick?: (draft: { message: string; files: ChatUploadedFile[] }) => void; + onSystemPromptWithContent?: (content: string, promptId: string, title: string) => void; onUploadedFileRemove?: (fileId: string) => void; onUploadedFilesChange?: (files: ChatUploadedFile[]) => void; onValueChange?: (value: string) => void; @@ -109,6 +105,7 @@ onStop, onSubmit, onSystemPromptClick, + onSystemPromptWithContent, onUploadedFileRemove, onUploadedFilesChange, onValueChange, @@ -146,6 +143,14 @@ conversationsStore.activeConversation?.cwd ?? conversationsStore.preferences.pendingCwd ); + // the project the chat is in, or the one picked for the chat about to start + let project = $derived.by(() => { + const active = conversationsStore.activeConversation; + const projectId = active ? active.projectId : conversationsStore.preferences.pendingProjectId; + + return projectId ? projectsStore.get(projectId) : undefined; + }); + let showWorkingDirectory = $derived(conversationsStore.preferences.hasEnabledCwdTools()); // On a desktop the chip under the form shows a directory once one is set, and the + menu // sets one until then. A phone has no chip: a chat shows it in its header (see @@ -155,27 +160,38 @@ showWorkingDirectory && (deviceStore.isMobile ? !conversationsStore.activeConversation : !cwd) ); + // what extensions add to the form: slash commands, the pickers they open, and + // attachments that wait outside the form's files + let contributedCommands = $derived(extensions.contributions('composerCommands')); + let contributedPickers = $derived(extensions.contributions('composerPickers')); + let contributedAttachments = $derived(extensions.contributions('composerAttachments')); + + const composer: ComposerHandle = { + addUploadedFile(file) { + uploadedFiles = [...uploadedFiles, file]; + onUploadedFilesChange?.(uploadedFiles); + }, + closePicker: () => pickers.closePicker(), + focusInput: () => inputRef?.focus(), + openPicker: (id, query) => pickers.openPicker(id, query), + updateUploadedFile(id, update) { + uploadedFiles = uploadedFiles.map((f) => (f.id === id ? update(f) : f)); + onUploadedFilesChange?.(uploadedFiles); + } + }; + const pickers = useChatFormPickers({ canCompact: () => chatStore.canCompact(conversationsStore.activeMessages), focusInput: refocusInput, getCaretOffset: () => inputRef?.getCaretOffset(), + getComposer: () => composer, + getContributedCommands: () => contributedCommands, getCwd: () => cwd, getPickersRef: () => pickersRef, getServerHome: () => toolsStore.serverHome ?? null, getShowModelSelector: () => showModelSelector, getValue: () => value, hasCwdTools: () => conversationsStore.preferences.hasEnabledCwdTools(), - // policy-aware, same rule as the agentic flow: MCP category on and at - // least one globally-enabled server whose group key is not disabled - hasPrompts: () => { - const prefs = conversationsStore.preferences; - - if (!prefs.isCategoryEnabled(ToolSource.MCP)) return false; - - return mcpStore - .getServers() - .some((s) => s.enabled && prefs.isServerToolsEnabled(s.id) && s.url.trim()); - }, onCompact: () => chatStore.compactConversation(), openModelSelector: () => chatFormActionsRef?.openModelSelector(), // TODO: no typed pickers with an on-screen keyboard for now: each mobile browser moves @@ -206,12 +222,6 @@ } } - // Resource Dialog State - let isResourceDialogOpen = $state(false); - let preSelectedResourceUri = $state(undefined); - - // MCP Servers Dialog State - let currentConfig = $derived(settingsStore.config); let pasteLongTextToFileLength = $derived.by(() => { @@ -264,7 +274,7 @@ !deviceStore.isMobile && !isExpanded && !hasAttachments && - !mcpStore.resources.hasAttachments && + !contributedAttachments.some((source) => source.hasPending()) && !value.includes('\n') ); // starts as it will settle, so a phone never draws a frame of the single row @@ -293,7 +303,7 @@ let isPickerOpen = $derived( pickers.isCommandPickerOpen || pickers.isMentionPickerOpen || - pickers.isPromptPickerOpen || + pickers.openPickerId !== null || pickers.isWorkingDirectoryPickerOpen ); @@ -488,70 +498,9 @@ } } - function handlePromptLoadStart( - placeholderId: string, - promptInfo: MCPPromptInfo, - args?: Record - ) { - pickers.closePromptPicker(); - - const promptName = promptInfo.title || promptInfo.name; - const placeholder: ChatUploadedFile = { - file: new File([], 'loading'), - id: placeholderId, - isLoading: true, - mcpPrompt: { - arguments: args ? { ...args } : undefined, - promptName: promptInfo.name, - serverName: promptInfo.serverName - }, - name: promptName, - size: INITIAL_FILE_SIZE, - type: SpecialFileType.MCP_PROMPT - }; - - uploadedFiles = [...uploadedFiles, placeholder]; - onUploadedFilesChange?.(uploadedFiles); - inputRef?.focus(); - } - - function handlePromptLoadComplete(placeholderId: string, result: GetPromptResult) { - const promptText = result.messages - ?.map((msg: PromptMessage) => { - if (typeof msg.content === 'string') { - return msg.content; - } - - if (msg.content.type === ContentPartType.TEXT) { - return msg.content.text; - } - - return ''; - }) - .filter(Boolean) - .join(PROMPT_CONTENT_SEPARATOR); - - uploadedFiles = uploadedFiles.map((f) => - f.id === placeholderId - ? { - ...f, - file: new File([promptText], `${f.name}${FileExtensionText.TXT}`, { - type: MimeTypeText.PLAIN - }), - isLoading: false, - size: promptText.length, - textContent: promptText - } - : f - ); - onUploadedFilesChange?.(uploadedFiles); - } - - function handlePromptLoadError(placeholderId: string, error: string) { - uploadedFiles = uploadedFiles.map((f) => - f.id === placeholderId ? { ...f, isLoading: false, loadError: error } : f - ); - onUploadedFilesChange?.(uploadedFiles); + /** A prompt of the System message list that needs arguments: its source asks for them in the form. */ + function handlePromptArguments(source: SystemPromptSource, entry: SystemPromptEntry) { + source.openArguments(entry, composer); } // Deferred so the closing popover's focus scope tears down first - @@ -656,20 +605,19 @@ anchor={activePickerAnchor} commandQuery={pickers.commandQuery} commands={pickers.availableCommands} + {composer} isCommandPickerOpen={pickers.isCommandPickerOpen} isMentionPickerOpen={pickers.isMentionPickerOpen} - isPromptPickerOpen={pickers.isPromptPickerOpen} mentionQuery={pickers.mentionQuery} onCommandPickerClose={pickers.handleCommandPickerClose} onCommandSelect={pickers.handleCommandSelect} onMentionOpened={() => inputRef?.focus()} onMentionPickerClose={pickers.handleMentionPickerClose} onMentionSelect={handleMentionSelect} - onPromptLoadComplete={handlePromptLoadComplete} - onPromptLoadError={handlePromptLoadError} - onPromptLoadStart={handlePromptLoadStart} - onPromptPickerClose={pickers.handlePromptPickerClose} - promptSearchQuery={pickers.promptSearchQuery} + onPickerClose={pickers.handlePickerClose} + openPickerId={pickers.openPickerId} + pickerQuery={pickers.pickerQuery} + pickers={contributedPickers} scopePath={pickers.mentionScopePath} /> @@ -764,15 +712,9 @@ {placeholder} /> - {#if mcpStore.resources.hasAttachments} - { - preSelectedResourceUri = uri; - isResourceDialogOpen = true; - }} - /> - {/if} + {#each contributedAttachments as source (source)} + + {/each}
@@ -788,9 +730,11 @@ micWarning={micUnavailableReason ?? micError} onFileUpload={handleFileUpload} onMicClick={handleMicClick} + onPromptArguments={handlePromptArguments} {onStop} onSystemPromptClick={() => onSystemPromptClick?.({ files: uploadedFiles, message: value })} + {onSystemPromptWithContent} onWorkingDirectoryClick={isWorkingDirectoryInAddMenu ? pickers.handleWorkingDirectoryOpen : undefined} @@ -817,7 +761,37 @@ >
{/if} - {#if showWorkingDirectory} + {#if project} + +
+ + + {#if showWorkingDirectoryChip} + + {/if} + + {#if showWorkingDirectory} + + {/if} +
+ {:else if showWorkingDirectory} {/if} - - { - mcpStore.attachResource(resource.uri); - }} - onOpenChange={(newOpen: boolean) => { - if (!newOpen) { - preSelectedResourceUri = undefined; - } - }} - preSelectedUri={preSelectedResourceUri} -/> diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte index b777b7c00117..53a5f51bf097 100644 --- a/ui/apps/chat/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,4 +1,5 @@ + + + + + + System message + + + + {#if prompts.hasPrompts} +
+ +
+ {/if} + + onWriteNew?.()}> + + + Write new + + + {#if prompts.libraryPrompts.length > 0} + + + Your prompts + + {#each prompts.libraryPrompts as prompt (prompt.id)} + prompts.selectLibraryPrompt(prompt.id)} + > + {prompt.name} + + {#if prompt.description} + + {prompt.description} + + {/if} + + + {prompt.content} + + + {/each} + {/if} + + {#each prompts.sourceGroups as group (group.source.id)} + + + {group.source.label} + + {#each group.entries as entry (entry.id)} + prompts.selectSourcePrompt(group.source, entry)} + > +
+ {#if entry.iconUrl} + { + (e.currentTarget as HTMLImageElement).style.display = 'none'; + }} + src={entry.iconUrl} + /> + {:else} + + {/if} + + {entry.origin} + + {#if entry.argumentCount > 0} + + {entry.argumentCount} arg{entry.argumentCount > 1 ? 's' : ''} + + {/if} +
+ + + {entry.title} + + + {#if entry.description} + + {entry.description} + + {/if} +
+ {/each} + {/each} + + {#if prompts.hasNoMatches} +
No matches
+ {/if} +
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte index ce32bdf3113e..a55c259a8f11 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte @@ -6,11 +6,10 @@ import { Check, ChevronDown, ChevronRight, Info, Loader2, PencilRuler } from '@lucide/svelte'; import { ATTACHMENT_MENU_TEXT, CLI_FLAGS, ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; import { useToolsPanel } from '#lib/hooks/use-tools-panel.svelte.ts'; - import { mcpStore, toolsStore, uiStore } from '#lib/stores/index.ts'; + import { toolsStore } from '#lib/stores/index.ts'; import type { ToolGroup } from '#lib/types/index.ts'; const toolsPanel = useToolsPanel(); - const hasMcpServersAvailable = $derived(mcpStore.getServers().length > 0); open && toolsPanel.handleOpen()}> @@ -40,18 +39,17 @@ - - {#if uiStore.isMcpShown} + {#each toolsPanel.providerHints as hint (hint.toolsLabel)} - {hasMcpServersAvailable ? 'Enable' : 'Add'} MCP Server(s) to access + {hint.action} - MCP Tools. + {hint.toolsLabel}. - {/if} + {/each} {:else if toolsStore.error}
Failed to load tools
@@ -70,7 +68,7 @@ {@render groupRow(group)} {/each} - {#each toolsPanel.mcpGroups as group (group.key)} + {#each toolsPanel.providerGroups as group (group.key)} {@render groupRow(group)} {/each} 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 index 987c5a350cac..562343baf354 100644 --- 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 @@ -12,6 +12,7 @@ import { ICON_CLASS_DEFAULT, SET_WORKING_DIRECTORY_LABEL } from '#lib/constants/index.ts'; import { setChatFormActionsContext } from '#lib/contexts/index.ts'; import { FileTypeCategory } from '#lib/enums/index.ts'; + import type { SystemPromptEntry, SystemPromptSource } from '#lib/extensions/index.ts'; import { useChatFormModel } from '#lib/hooks/use-chat-form-model.svelte.ts'; import { useShowContextGauge } from '#lib/hooks/use-context-gauge.svelte.ts'; import { ChatService } from '#lib/services/index.ts'; @@ -37,7 +38,9 @@ onFileUpload?: () => void; onMicClick?: () => void; onStop?: () => void; + onPromptArguments?: (source: SystemPromptSource, entry: SystemPromptEntry) => void; onSystemPromptClick?: () => void; + onSystemPromptWithContent?: (content: string, promptId: string, title: string) => void; onWorkingDirectoryClick?: () => void; } @@ -52,8 +55,10 @@ micWarning = null, onFileUpload, onMicClick, + onPromptArguments, onStop, onSystemPromptClick, + onSystemPromptWithContent, onWorkingDirectoryClick, showAddButton = true, showModelSelector = true, @@ -114,9 +119,15 @@ get onFileUpload() { return onFileUpload; }, + get onPromptArguments() { + return onPromptArguments; + }, get onSystemPromptClick() { return onSystemPromptClick; }, + get onSystemPromptWithContent() { + return onSystemPromptWithContent; + }, get onWorkingDirectoryClick() { return onWorkingDirectoryClick; }, diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte index 802dd7e8d081..53c0820e1896 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte @@ -104,7 +104,7 @@ {/snippet} {#snippet body()} - {#if gauge.activeModelId !== null && !gauge.isActiveModelLoaded} + {#if gauge.canLoadActiveModel && gauge.activeModelId !== null && !gauge.isActiveModelLoaded} {#snippet item(command, index, isSelected)} - {@const Icon = CHAT_FORM_COMMAND_ICONS[command.action]} + {@const Icon = 'action' in command ? CHAT_FORM_COMMAND_ICONS[command.action] : command.icon} void; @@ -43,8 +47,9 @@ onClose, onOpened, onSelect, - query, - scopePath = null + query = $bindable(''), + scopePath = null, + showSearchInput = false }: Props = $props(); const nav = usePickerNavigation({ @@ -226,14 +231,16 @@ sideOffset={12} > entry.type + ':' + entry.path} items={displayedItems} + onSearchClose={onClose} scrollTrigger={nav.scrollTrigger} - searchQuery={query ?? ''} + searchPlaceholder="Search files" selectedIndex={nav.hoveredIndex} - showSearchInput={false} + {showSearchInput} > {#snippet item(entry, index, isSelected)} import ChatFormPickerCommand from './ChatFormPickerCommand.svelte'; - import ChatFormPickerMcpPrompts from './ChatFormPickerMcpPrompts/ChatFormPickerMcpPrompts.svelte'; import ChatFormPickerMention from './ChatFormPickerMention.svelte'; import type { - ChatFormCommand, - FileMentionEntry, - GetPromptResult, - MCPPromptInfo - } from '#lib/types/index.ts'; + ComposerHandle, + ComposerPicker, + ComposerPickerExports + } from '#lib/extensions/index.ts'; + import type { ChatFormCommand, FileMentionEntry } from '#lib/types/index.ts'; interface Props { /** What every picker's popover floats by. */ @@ -15,49 +14,46 @@ isCommandPickerOpen?: boolean; commandQuery?: string; commands?: ChatFormCommand[]; - isPromptPickerOpen?: boolean; - promptSearchQuery?: string; + /** Handed to the pickers extensions contribute. */ + composer: ComposerHandle; + /** The pickers extensions contribute. */ + pickers?: ComposerPicker[]; + /** The contributed picker that is open, if any. */ + openPickerId?: string | null; + pickerQuery?: string; isMentionPickerOpen?: boolean; mentionQuery?: string; scopePath?: string | null; onCommandPickerClose?: () => void; onCommandSelect?: (command: ChatFormCommand) => void; - onPromptPickerClose?: () => void; + onPickerClose?: () => void; onMentionPickerClose?: () => void; onMentionOpened?: () => void; onMentionSelect?: (entry: FileMentionEntry) => void; - onPromptLoadStart?: ( - placeholderId: string, - promptInfo: MCPPromptInfo, - args?: Record - ) => void; - onPromptLoadComplete?: (placeholderId: string, result: GetPromptResult) => void; - onPromptLoadError?: (placeholderId: string, error: string) => void; } let { anchor, commandQuery, commands = [], + composer, isCommandPickerOpen, isMentionPickerOpen, - isPromptPickerOpen, mentionQuery, onCommandPickerClose, onCommandSelect, onMentionOpened, onMentionPickerClose, onMentionSelect, - onPromptLoadComplete, - onPromptLoadError, - onPromptLoadStart, - onPromptPickerClose, - promptSearchQuery, + onPickerClose, + openPickerId = null, + pickerQuery, + pickers = [], scopePath }: Props = $props(); let commandPickerRef: ChatFormPickerCommand | undefined = $state(undefined); - let promptPickerRef: ChatFormPickerMcpPrompts | undefined = $state(undefined); + let contributedPickerRefs: Record = $state({}); let mentionPickerRef: ChatFormPickerMention | undefined = $state(undefined); /** Delegate keyboard events to the active picker child; true if handled. */ @@ -66,7 +62,7 @@ return true; } - if (isPromptPickerOpen && promptPickerRef?.handleKeydown(event)) { + if (openPickerId !== null && contributedPickerRefs[openPickerId]?.handleKeydown(event)) { return true; } @@ -88,16 +84,18 @@ query={commandQuery ?? ''} /> - +{#each pickers as picker (picker.id)} + {@const isOpen = openPickerId === picker.id} + + {})} + query={isOpen ? (pickerQuery ?? '') : ''} + /> +{/each} + import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip'; + import { X } from '@lucide/svelte'; + import { ActionIcon } from '#lib/components/app/actions/index.ts'; + import { conversationsStore, projectsStore, uiStore } from '#lib/stores/index.ts'; + import type { Project } from '#lib/types/index.ts'; + + interface Props { + disabled?: boolean; + project: Project; + } + + let { disabled = false, project }: Props = $props(); + + function pickProject() { + uiStore.openProjectPicker({ + currentProjectId: project.id, + onSelect: (projectId) => + void conversationsStore.assignActiveConversationProject( + projectsStore.get(projectId) ?? null + ) + }); + } + + + +
+ + + {#snippet child({ props })} + + {/snippet} + + + +

Change project

+
+
+ +
+ void conversationsStore.assignActiveConversationProject(null)} + tooltip="Remove from project" + /> +
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessage.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessage.svelte index 0086107eed80..ffcfada3b83b 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessage.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessage.svelte @@ -2,7 +2,6 @@ import { ChatMessageAssistant, ChatMessageCompaction, - ChatMessageMcpPrompt, ChatMessageSynthetic, ChatMessageSystem, ChatMessageUser @@ -14,22 +13,15 @@ SYSTEM_MESSAGE_PLACEHOLDER } from '#lib/constants/index.ts'; import { setChatMessageActionsContext, setChatMessageEditContext } from '#lib/contexts/index.ts'; - import { - AgenticSectionType, - AttachmentType, - MessageRole, - MessageType - } from '#lib/enums/index.ts'; + import { AgenticSectionType, MessageRole, MessageType } from '#lib/enums/index.ts'; + import { extensions, findMessageRenderer } from '#lib/extensions/index.ts'; import { DatabaseService } from '#lib/services/database.service.ts'; import { chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts'; - import type { - ChatMessageActions, - ChatMessageDeletionInfo, - DatabaseMessageExtraMcpPrompt - } from '#lib/types/index.ts'; + import type { ChatMessageActions, ChatMessageDeletionInfo } from '#lib/types/index.ts'; import { parseFilesToMessageExtras } from '#lib/utils/browser-only.ts'; import { deriveAgenticSections } from '#lib/utils/index.ts'; import { goto } from '$app/navigation'; + import { resolve } from '$app/paths'; interface Props { class?: string; @@ -185,9 +177,10 @@ return deletionInfo; }, get forkConversation() { - const isForkableUser = message.role === MessageRole.USER && !mcpPromptExtra; + const isForkableRole = + message.role === MessageRole.USER || message.role === MessageRole.ASSISTANT; - return isForkableUser || message.role === MessageRole.ASSISTANT + return isForkableRole && messageRenderer?.forkable !== false ? handleForkConversation : undefined; }, @@ -208,21 +201,10 @@ } }); - let mcpPromptExtra = $derived.by(() => { - if (message.role !== MessageRole.USER) return null; - - if (message.content.trim()) return null; - - if (!message.extra || message.extra.length !== 1) return null; - - const extra = message.extra[0]; - - if (extra.type === AttachmentType.MCP_PROMPT) { - return extra as DatabaseMessageExtraMcpPrompt; - } - - return null; - }); + // an extension can claim a message and draw it in place of the default + let messageRenderer = $derived( + findMessageRenderer(extensions.contributions('messageRenderers'), message) + ); $effect(() => { const pendingId = chatStore.pendingEditMessageId; @@ -241,7 +223,7 @@ const conversationDeleted = await chatStore.removeSystemPromptPlaceholder(message.id); if (conversationDeleted) { - goto(ROUTES.START); + goto(resolve(ROUTES.START)); } return; @@ -282,7 +264,7 @@ const conversationDeleted = await chatStore.removeSystemPromptPlaceholder(message.id); if (conversationDeleted) { - goto(ROUTES.START); + goto(resolve(ROUTES.START)); } } else { chatActions.delete(message); @@ -362,7 +344,7 @@ isEditing = false; if (conversationDeleted) { - goto(ROUTES.START); + goto(resolve(ROUTES.START)); } else { focusMainChatForm(); } @@ -425,8 +407,8 @@
{#if message.role === MessageRole.SYSTEM} - {:else if mcpPromptExtra} - + {:else if messageRenderer} + {:else if isCompaction} {:else if isSynthetic} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte index c37b0447fd29..7e0e0e4c036d 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte @@ -235,7 +235,8 @@ --assistant-min-height-offset: calc( var(--last-user-message-height, 19rem) + var(--chat-form-height, 6rem) + var(--chat-form-bottom-position, 0.5rem) + var(--chat-form-padding-top, 6rem) + - var(--assistant-margin-top, 3rem) + var(--chat-tabs-offset, 0px) + var(--assistant-margin-top, 3rem) + var(--chat-tabs-offset, 0px) + + var(--chat-header-height, 0px) ); min-height: calc(100dvh - var(--assistant-min-height-offset)); @@ -243,7 +244,8 @@ --assistant-min-height-offset: calc( var(--last-user-message-height, 18rem) + var(--chat-form-height, 6rem) + var(--chat-form-bottom-position, 1rem) + var(--chat-form-padding-top, 6rem) + - var(--assistant-margin-top, 3rem) + var(--chat-tabs-offset, 0px) + var(--assistant-margin-top, 3rem) + var(--chat-tabs-offset, 0px) + + var(--chat-header-height, 0px) ); } } diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte index 959016a26538..515dca042fa9 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte @@ -1,5 +1,6 @@ {#if info} -
- {#if info.path === null} + {#if info.path === null} +
Working directory cleared - {:else} - - - Set working directory to  - - - {info.display} - - {/if} -
+
+ {:else} + + {/if} {/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChangeRow.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChangeRow.svelte new file mode 100644 index 000000000000..999f000279e4 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChangeRow.svelte @@ -0,0 +1,21 @@ + + +
+ + + Set working directory to  + + {display} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessagePrompt/ChatMessagePromptContent.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessagePrompt/ChatMessagePromptContent.svelte new file mode 100644 index 000000000000..8b1e21b9cb28 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessagePrompt/ChatMessagePromptContent.svelte @@ -0,0 +1,43 @@ + + + +
+
+
+ + + +
+ + {@render status?.()} +
+ + {#if content.trim()} + +
+ {content} +
+
+ {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte index df2097b5a7d9..7988ec4f7bb8 100644 --- a/ui/apps/chat/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,28 @@ {#snippet pill(result: SearchResult)} - {@const faviconUrl = buildProxiedIconUrl(faviconForUrl(result.url), mcpStore.isProxyAvailable)} + {@const faviconUrl = buildProxiedIconUrl(faviconForUrl(result.url), isProxyAvailable)} {@const safeUrl = sanitizeExternalUrl(result.url)} {@const showHoverCard = safeUrl !== null && hasDetails(result)} {#if safeUrl} @@ -91,7 +93,7 @@ {#if faviconUrl} @@ -116,7 +118,7 @@ {result.title} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte index cafb077e5366..278eef10ff23 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte @@ -4,7 +4,7 @@ // - the collapsible wrapper (defaults to CollapsibleContentBlock; // `exec_shell_command` swaps in CollapsibleTerminalBlock via the // `wrapper` prop); - // - the icon, spinner state, and MCP favicon fallback chain; + // - the icon, spinner state, and tool provider icon fallback chain; // - the status subtitle pill. // Components supply only their `meta`, a title snippet, and a body // snippet - everything around them is this single source of truth. @@ -13,7 +13,7 @@ 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 { toolsStore } 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'; @@ -104,13 +104,11 @@ const toolIconClass = $derived( spinIconWhenActive && showSpinner ? ICON_CLASS_SPIN : ICON_CLASS_DEFAULT ); - // Drop the MCP favicon while the spinner is on so the title row + // Drop the provider's icon while the spinner is on so the title row // signals "in flight" without being overwritten by server branding. - const mcpServerFavicon = $derived( - showSpinner ? null : mcpStore.getServerFaviconForTool(section.toolName) - ); + const providerIcon = $derived(showSpinner ? null : toolsStore.getToolIcon(section.toolName)); const iconUrl = $derived( - showSpinner || (toolUi?.icon ?? null) || !mcpServerFavicon ? null : mcpServerFavicon + showSpinner || (toolUi?.icon ?? null) || !providerIcon ? null : providerIcon ); // No subtitle while the call is in flight - the spinner already diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte index 214f9dea2304..d425b172e982 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte @@ -56,14 +56,14 @@ {:else} {@const source = toolsStore.getToolSource(toolName)} - {@const providerName = + {@const serverName = 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} + Approve all tools from {serverName} {/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte index 911f0743487c..9d59d5947b53 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte @@ -23,9 +23,9 @@ CHAT_FORM_MOVE_OUT_MS, CHAT_FORM_MOVE_SHIFT_PX, CHAT_FORM_MOVE_TO_BOTTOM_IN_MS, - CHAT_FORM_MOVE_TO_BOTTOM_OUT_MS, - ROUTES + CHAT_FORM_MOVE_TO_BOTTOM_OUT_MS } from '#lib/constants/index.ts'; + import { useBackendAvailability } from '#lib/hooks/use-backend-availability.svelte.ts'; import { useChatScreenActiveModel } from '#lib/hooks/use-chat-screen-active-model.svelte.ts'; import { useChatScreenDragAndDrop } from '#lib/hooks/use-chat-screen-drag-and-drop.svelte.ts'; import { useChatScreenFileUpload } from '#lib/hooks/use-chat-screen-file-upload.svelte.ts'; @@ -43,12 +43,25 @@ import { parseFilesToMessageExtras } from '#lib/utils/browser-only.ts'; import { disableScrollHandling, onNavigate } from '$app/navigation'; import { page } from '$app/state'; - import { tick, untrack } from 'svelte'; + import { type Snippet, tick, untrack } from 'svelte'; import { fade } from 'svelte/transition'; - let { showCenteredEmpty = false } = $props(); + interface Props { + /** Sits above the messages. */ + header?: Snippet; + /** Scrolls away under the header, e.g. a title. */ + intro?: Snippet; + /** Takes the place of the messages, with the form at the bottom. */ + overview?: Snippet; + /** Sit between the intro and the overview, e.g. a project's instructions and context. */ + panels?: Snippet; + showCenteredEmpty?: boolean; + } + + let { header, intro, overview, panels, showCenteredEmpty = false }: Props = $props(); let emptyFileNames = $state([]); + let headerHeight = $state(0); let showDeleteDialog = $state(false); let showEmptyFileDialog = $state(false); let isEmpty = $derived( @@ -64,8 +77,10 @@ let formWrapper: HTMLElement | undefined = $state(); let chatScreenForm: ChatScreenForm | undefined = $state(); let activeErrorDialog = $derived(chatStore.errorDialogState); - let isServerLoading = $derived(serverStore.loading); - let hasPropsError = $derived(!!serverStore.error); + // no local server in this deployment: never block on its probe + let isServerLoading = $derived(serverStore.loading && !serverStore.localServerMissing); + const availability = useBackendAvailability(); + let hasPropsError = $derived(availability.isOffline); let isCurrentConversationLoading = $derived(chatStore.isLoading || chatStore.isStreaming()); let chatFormBottomPosition = $derived.by(() => { if (!deviceStore.isMobile) return CHAT_FORM_BOTTOM_OFFSET.desktop; @@ -261,6 +276,10 @@ await chatStore.addSystemPrompt(draft); } + async function handleSystemPromptWithContent(content: string, promptId: string, title: string) { + await chatStore.addSystemPromptFromPrompt(content, { promptId, title }); + } + $effect(() => { stick.setEnabled(!settingsStore.config.disableAutoScroll); }); @@ -290,6 +309,7 @@
0 ? `${headerHeight}px` : undefined} class="chat-screen flex grow flex-col min-h-[calc(100dvh-1rem)] md:min-h-[calc(100dvh-var(--chat-tabs-offset,0px))] px-4 md:py-0 pt-(--page-top) pb-48 md:pb-4" ondragenter={dragAndDrop.dragHandlers.dragenter} ondragleave={dragAndDrop.dragHandlers.dragleave} @@ -319,7 +339,31 @@
{/if} - {#if !isEmpty} + {#if header} + +
+
+ {@render header()} +
+
+ {/if} + + {#if panels} + +
+ {@render intro?.()} + + {@render panels()} + + {@render overview?.()} +
+ {:else if overview} +
+ {@render overview()} +
+ {:else if !isEmpty} - {#if stick.farFromBottom && page.url.hash.includes(ROUTES.CHAT) && page.params.id} + {#if stick.farFromBottom && page.params.id} stick.scrollToBottom('smooth')} /> {/if}
@@ -387,6 +431,7 @@ onSend={handleSendMessage} onStop={() => chatStore.stopGeneration()} onSystemPromptAdd={handleSystemPromptAdd} + onSystemPromptWithContent={handleSystemPromptWithContent} /> diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte index 309cb722289a..1bfd3f2ab134 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte @@ -17,6 +17,7 @@ onSend?: (message: string, files?: ChatUploadedFile[]) => Promise; onStop?: () => void; onSystemPromptAdd?: (draft: { message: string; files: ChatUploadedFile[] }) => void; + onSystemPromptWithContent?: (content: string, promptId: string, title: string) => void; uploadedFiles?: ChatUploadedFile[]; } @@ -29,6 +30,7 @@ onSend, onStop, onSystemPromptAdd, + onSystemPromptWithContent, uploadedFiles = $bindable([]) }: Props = $props(); @@ -161,6 +163,7 @@ {onStop} onSubmit={handleSubmit} onSystemPromptClick={handleSystemPromptClick} + {onSystemPromptWithContent} onUploadedFileRemove={handleUploadedFileRemove} singleRow={settingsStore.config[SETTINGS_KEYS.SINGLE_ROW_CHAT_FORM] !== false} /> diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenGreeting.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenGreeting.svelte index 22bde59ce057..720e397368ca 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenGreeting.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenGreeting.svelte @@ -63,8 +63,9 @@

Hello there

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

diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenServerError.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenServerError.svelte index 497c1efc2c14..4d8d60e8fb39 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenServerError.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenServerError.svelte @@ -1,11 +1,18 @@ {#if hasError || isLoadingModel} @@ -33,7 +40,19 @@ {#if !isLoadingModel} - {serverStore.error} + + {serverStore.error} + + + + {/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte index c4a68a2dbfc8..bf9a4d586a06 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabs.svelte @@ -14,31 +14,45 @@ 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 { projectNewChatTabId, projectOfNewChatTab, resolveTabView } from '#lib/utils/index.ts'; + import { goto } from '$app/navigation'; import { page } from '$app/state'; - import { tick } from 'svelte'; + import { type Snippet, tick } from 'svelte'; + + interface Props { + /** Sits before the tabs, e.g. the breadcrumb of a project view. */ + leading?: Snippet; + } + + let { leading }: Props = $props(); const carousel = useScrollCarousel(); - let view = $derived(resolveTabView(page, tabsStore.openTabs)); + let view = $derived(resolveTabView(page, tabsStore.openTabs, conversationsStore.conversations)); let activeId = $derived(view.activeId); let tabs = $derived( - view.ids.map((id) => - id === NEW_CHAT_TAB_ID - ? { href: view.hrefFor(id), icon: SquarePen, id, name: NEW_CHAT_LABEL } - : { - href: view.hrefFor(id), - id, - name: - conversationsStore.conversations.find((c) => c.id === id)?.name ?? UNNAMED_CHAT_LABEL - } - ) + view.ids.map((id) => { + if (id === NEW_CHAT_TAB_ID || projectOfNewChatTab(id)) { + return { href: view.hrefFor(id), icon: SquarePen, id, name: NEW_CHAT_LABEL }; + } + + return { + href: view.hrefFor(id), + id, + name: conversationsStore.conversations.find((c) => c.id === id)?.name ?? UNNAMED_CHAT_LABEL + }; + }) ); - // hide the New chat button while a new-chat tab is already open - let showNewChatButton = $derived(!view.ids.includes(NEW_CHAT_TAB_ID)); + // the new-chat tab of the view: the regular one, or the project's own + let newChatTabId = $derived( + view.projectId ? projectNewChatTabId(view.projectId) : NEW_CHAT_TAB_ID + ); + + // hide the New chat button while that tab is already open + let showNewChatButton = $derived(!view.ids.includes(newChatTabId)); let loadingIds = $derived(new Set(chatStore.getAllLoadingChats())); @@ -46,6 +60,11 @@ void tabsStore.close(id, id === activeId, view); } + function openNewChat() { + void tabsStore.openInNewTab(newChatTabId); + void goto(view.hrefFor(newChatTabId)); + } + function handleStop(id: string, event: MouseEvent) { event.stopPropagation(); void chatStore.stopGenerationForChat(id); @@ -135,44 +154,48 @@ : CHAT_TABS_MAX_WIDTH.COLLAPSED_SIDEBAR ]} > -
- - {#each tabs as tab (tab.id)} - - tabsStore.activate(id)} - onAuxClick={handleAuxClick} - onClose={handleClose} - onStop={handleStop} - {tab} - /> - - {/each} - - {#if showNewChatButton} - void tabsStore.openInNewTab(NEW_CHAT_TAB_ID, { activate: true })} - /> - {/if} - - -
- -
+
+ {#if leading} +
{@render leading()}
+ {/if} + +
+ + {#each tabs as tab (tab.id)} + + void goto(view.hrefFor(id))} + onAuxClick={handleAuxClick} + onClose={handleClose} + onStop={handleStop} + {tab} + /> + + {/each} + + {#if showNewChatButton} + + {/if} + + +
+ +
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte index c01af20d6f4b..d5c5509568c2 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsItem.svelte @@ -10,10 +10,11 @@ TAB_SURFACE_IDLE_CLASS, UI_DATA_ATTRS } from '#lib/constants/index.ts'; + import type { ResolvedPathname } from '$app/types'; import type { Component } from 'svelte'; interface Tab { - href: string; + href: ResolvedPathname; /** Marks the new-chat tab. */ icon?: Component; id: string; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsNewChatButton.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsNewChatButton.svelte index a3a8f1439bbb..35affb808ba1 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsNewChatButton.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatTabs/ChatTabsNewChatButton.svelte @@ -4,10 +4,11 @@ import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; interface Props { + label?: string; onclick?: () => void; } - let { onclick }: Props = $props(); + let { label = 'New chat', onclick }: Props = $props(); @@ -15,8 +16,8 @@ {#snippet child({ props })} + + {#if projects.length > 0} + + +
+ {#each projects as project (project.id)} + + {/each} +
+ {/if} + + diff --git a/ui/apps/chat/src/lib/components/app/projects/index.ts b/ui/apps/chat/src/lib/components/app/projects/index.ts new file mode 100644 index 000000000000..a1955d81bb29 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/projects/index.ts @@ -0,0 +1,88 @@ +/** + * + * PROJECTS + * + * A project groups chats under shared instructions, context and a working + * directory. It is configured in one dialog and shown as a sidebar section. + * + */ + +/** + * **DialogProject** - Create or edit a project + * + * Name, goal, working directory, instructions and context in one form. When + * editing, the footer also deletes the project. Opened through + * `uiStore.openProjectDialog`. + */ +export { default as DialogProject } from './DialogProject.svelte'; + +/** + * **DialogProjectPicker** - Pick a project for a chat on a phone + * + * The phone's stand-in for `ProjectSubmenu`: a searchable list that can also + * create a project by name. Opened through `uiStore.openProjectPicker`. + */ +export { default as DialogProjectPicker } from './DialogProjectPicker.svelte'; + +/** + * **ProjectCard** - One project on the Projects page + * + * Opens the project dialog on click; its right-click menu and "more actions" + * dropdown edit, pin or delete the project. + */ +export { default as ProjectCard } from './ProjectCard.svelte'; + +/** + * **ProjectContextList** - Context items of a project draft + * + * Uploads files, references server files or MCP resources, and removes items. + */ +export { default as ProjectContextList } from './ProjectContextList.svelte'; + +/** + * **ProjectFolderPicker** - Working directory row of a project draft + */ +export { default as ProjectFolderPicker } from './ProjectFolderPicker.svelte'; + +/** + * **ProjectPrefix** - Project icon, name and slash before a chat title + */ +export { default as ProjectPrefix } from './ProjectPrefix.svelte'; + +/** + * **ProjectSubmenu** - "Add to project" flyout of a chat menu + * + * Searchable project list inside a dropdown or context menu, with a New + * project entry that opens the project dialog and joins the project it creates. + */ +export { default as ProjectSubmenu } from './ProjectSubmenu.svelte'; + +/** **ProjectActions** - Pin and menu of the project page's title */ +export { default as ProjectActions } from './ProjectActions.svelte'; + +/** **ProjectBreadcrumb** - Part of the project page */ +export { default as ProjectBreadcrumb } from './ProjectBreadcrumb.svelte'; + +/** **ProjectContext** - Part of the project page */ +export { default as ProjectContext } from './ProjectContext.svelte'; + +/** **ProjectConversations** - Part of the project page */ +export { default as ProjectConversations } from './ProjectConversations.svelte'; + +/** **ProjectHeader** - Part of the project page */ +export { default as ProjectHeader } from './ProjectHeader.svelte'; + +/** **ProjectInstructions** - Part of the project page */ +export { default as ProjectInstructions } from './ProjectInstructions.svelte'; + +/** **ProjectIntro** - Part of the project page */ +export { default as ProjectIntro } from './ProjectIntro.svelte'; + +/** **ProjectOverview** - Part of the project page */ +export { default as ProjectOverview } from './ProjectOverview.svelte'; + +/** **ProjectPanels** - Part of the project page */ +export { default as ProjectPanels } from './ProjectPanels.svelte'; + +/** **ProjectSection** - Part of the project page */ +export { default as ProjectSection } from './ProjectSection.svelte'; diff --git a/ui/apps/chat/src/lib/components/app/servers/DialogServerCodeScanner.svelte b/ui/apps/chat/src/lib/components/app/servers/DialogServerCodeScanner.svelte new file mode 100644 index 000000000000..4cd18b033479 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/servers/DialogServerCodeScanner.svelte @@ -0,0 +1,120 @@ + + + + + + Scan the access code + + + Point the camera at the QR code llama-server prints with --connect. + + + + {#if error} +
+ + +

{error}

+
+ {:else} + + {/if} + +
+

+ + + Checked every {SCAN_INTERVAL_MS / 1000}s +

+ + +
+
+
diff --git a/ui/apps/chat/src/lib/components/app/servers/DialogServerForm.svelte b/ui/apps/chat/src/lib/components/app/servers/DialogServerForm.svelte new file mode 100644 index 000000000000..9b98f64ebb4b --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/servers/DialogServerForm.svelte @@ -0,0 +1,417 @@ + + +{#snippet fields()} +
+ (showScanner = true)} + server={draft} + {urlError} + /> +
+ + handleChange({ code: scanned })} + /> + + +
+ {#if pairing} + + +
+

Pairing

+ +

Opening the tunnel to that server.

+
+ {:else if testing} + + +
+

Testing connection

+ +

+ Asking {hostOf(draft.baseUrl)} for the models it serves. +

+
+ {:else if pairError} + + +
+

Pairing failed

+ +

{pairError}

+ +

The server is saved; retry from its card.

+
+ {:else if testResult?.ok} + + +
+

Connected

+ +

+ {testResult.modelCount ?? 0} + model{(testResult.modelCount ?? 0) === 1 ? '' : 's'} available. +

+
+ {:else if testResult} + + +
+

Connection failed

+ +

+ {testResult.error ?? 'The endpoint did not answer.'}{testResult.status + ? ` (HTTP ${testResult.status})` + : ''} +

+
+ {:else} + {#if isRemote} + + {:else} + + {/if} + +
+

+ {isRemote ? 'Not paired yet' : 'Connection not tested'} +

+ +

+ {isRemote + ? 'Pairing saves the server and connects to it.' + : 'Test it to list the models this server serves.'} +

+
+ {/if} +
+{/snippet} + +{#snippet actions()} + + + {#if isRemote} + + {:else} + + + + {/if} +{/snippet} + +{#if deviceStore.isMobile} + + + + + {title} + + {description} + + + +
+ {@render fields()} +
+ + {@render actions()} + +
+
+{:else} + + + + {title} + + {description} + + +
+ {@render fields()} + + {@render actions()} +
+
+
+{/if} diff --git a/ui/apps/chat/src/lib/components/app/servers/DialogServers.svelte b/ui/apps/chat/src/lib/components/app/servers/DialogServers.svelte new file mode 100644 index 000000000000..1939343a4d2f --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/servers/DialogServers.svelte @@ -0,0 +1,48 @@ + + + + + deviceStore.isMobile && event.preventDefault()} + > + + + + + Servers + + + + {remoteAccessStore.isEnabled + ? 'Pair a remote server by its access code, or point at one by its URL.' + : 'Point at a llama-server by its URL.'} + + + +
+ +
+
+
diff --git a/ui/apps/chat/src/lib/components/app/servers/ServerCard.svelte b/ui/apps/chat/src/lib/components/app/servers/ServerCard.svelte new file mode 100644 index 000000000000..56aa0452875e --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/servers/ServerCard.svelte @@ -0,0 +1,334 @@ + + + +
+
+ + {#snippet fallback()} + {#if isLocal} + + {:else if remote} + + {:else} + + {/if} + {/snippet} + + +
+

{server.name}

+ + {#if remote} +
+ + + +
+ {:else} +

{displayUrl}

+ {/if} +
+
+ + {#if remote} + + + {#snippet child({ props })} + onToggle?.(value)} + /> + {/snippet} + + + +

Disabling also closes this server's tunnel.

+
+
+ {:else} + onToggle?.(value)} + /> + {/if} +
+ + {#if hostCode} +
+
+
+

Remote access: on

+ +

+ This server can be reached through its access code. +

+
+ +
+ + + + + {#if onPair} + + {/if} +
+
+ + {#if showHostQr && hostQr} +
+ Access code QR code + +

Scan it with the other device.

+
+ {/if} +
+ {/if} + + {#if status.detail} +

+ {status.detail} +

+ {/if} + +
+
+ {#if isConnecting || isChecking} + + {:else if isOnline} + + {:else if isOffline} + + {:else if isIdle} + + {/if} + + {#if hasStatus} + {status.label} + + {#if isOffline} + + {/if} + + · + {/if} + + {metaText} +
+ +
+ {#if isIdle} + + {/if} + + {#if remote && tunnel !== TunnelStatus.IDLE} + + {/if} + + {#if !isLocal} + + + + {/if} +
+
+
+ + (showDelete = false)} + onConfirm={() => { + showDelete = false; + onDelete?.(); + }} + title={remote ? 'Forget this server?' : 'Delete server?'} + variant="destructive" +/> diff --git a/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte b/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte index fab3edba4090..5d712ce491c7 100644 --- a/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte +++ b/ui/apps/chat/src/lib/components/app/servers/ServerErrorSplash.svelte @@ -3,11 +3,18 @@ import { Input } from '@ggml-org/llama-ui/ui/input'; import { Label } from '@ggml-org/llama-ui/ui/label'; import { AlertTriangle, CheckCircle, Key, RefreshCw, XCircle } from '@lucide/svelte'; - import { HEADERS, ICON_CLASS_DEFAULT, ROUTES, SETTINGS_KEYS } from '#lib/constants/index.ts'; + import { + HEADERS, + ICON_CLASS_DEFAULT, + LOCAL_BACKEND_ID, + ROUTES, + SETTINGS_KEYS + } from '#lib/constants/index.ts'; import { KeyboardKey } from '#lib/enums/index.ts'; import { serverStore, settingsStore } from '#lib/stores/index.ts'; - import { withBase } from '#lib/utils/base-path.ts'; + import { apiUrl } from '#lib/utils/api-base.ts'; import { goto } from '$app/navigation'; + import { resolve } from '$app/paths'; import { fade, fly, scale } from 'svelte/transition'; interface Props { @@ -67,7 +74,7 @@ settingsStore.updateConfig(SETTINGS_KEYS.API_KEY, apiKeyInput.trim()); // Test the API key by making a real request to the server - const response = await fetch(withBase('/props'), { + const response = await fetch(apiUrl('/props', LOCAL_BACKEND_ID), { headers: { 'Content-Type': 'application/json', [HEADERS.AUTHORIZATION]: `${HEADERS.BEARER}${apiKeyInput.trim()}` @@ -80,7 +87,7 @@ // Show success state briefly, then navigate to home setTimeout(() => { - goto(ROUTES.START); + goto(resolve(ROUTES.START)); }, 1000); } else { // API key is invalid - User Story A diff --git a/ui/apps/chat/src/lib/components/app/servers/ServerForm.svelte b/ui/apps/chat/src/lib/components/app/servers/ServerForm.svelte new file mode 100644 index 000000000000..79f01c3513cc --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/servers/ServerForm.svelte @@ -0,0 +1,188 @@ + + +
+ + + {#if kinds.length > 1} + onChange({ kind: value as ServerKind })} + value={server.kind} + > + + {#each kinds as kind (kind)} + + {kind === ServerKind.REMOTE ? 'Remote server' : 'Server URL'} + + {#if kind === ServerKind.REMOTE} + + {/if} + + {/each} + + + {/if} + + {#if isRemote} +
+ + +

+ Experimental. The pass code is currently sent + to whichever peer answers on the public tracker, so someone watching it could capture the code. + Mutual authentication, where neither side sends it, is planned. +

+
+ {/if} + + {#if isRemote} +
+ + +
+ onChange({ code: e.currentTarget.value })} + placeholder="Paste the {CODE_LENGTHS.SHARE}-character code" + spellcheck="false" + type="text" + value={server.code ?? ''} + /> + + {#if canScan} + + {/if} +
+ + {#if codeError} +

{codeError}

+ {:else} +

+ Printed by llama-server --connect. It is a credential: + anyone who has it can use that server. +

+ {/if} +
+ {:else} +
+ + + onChange({ baseUrl: e.currentTarget.value })} + placeholder="https://api.example.com" + type="url" + value={server.baseUrl} + /> + + {#if urlError} +

{urlError}

+ {:else if endpointError} +

{endpointError}

+ {/if} +
+ {/if} + +
+
+ + + onChange({ name: e.currentTarget.value })} + placeholder="Name shown in the model selector" + type="text" + value={server.name} + /> +
+ +
+ + + onChange({ apiKey: e.currentTarget.value || undefined })} + placeholder="Optional" + type="password" + value={server.apiKey ?? ''} + /> + +

+ {#if apiKeyRequired} + Required by this endpoint. + {:else} + Sent as a Bearer token. + {/if} +

+
+
+
diff --git a/ui/apps/chat/src/lib/components/app/servers/ServerIcon.svelte b/ui/apps/chat/src/lib/components/app/servers/ServerIcon.svelte new file mode 100644 index 000000000000..c3e1bcdae466 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/servers/ServerIcon.svelte @@ -0,0 +1,33 @@ + + +{#if faviconUrl && !failedFavicons.has(faviconUrl)} + failedFavicons.add(faviconUrl)} + src={faviconUrl} + /> +{:else} + {@render fallback?.()} +{/if} diff --git a/ui/apps/chat/src/lib/components/app/servers/ServerStatus.svelte b/ui/apps/chat/src/lib/components/app/servers/ServerStatus.svelte index 630079fd9a73..590fcc66067f 100644 --- a/ui/apps/chat/src/lib/components/app/servers/ServerStatus.svelte +++ b/ui/apps/chat/src/lib/components/app/servers/ServerStatus.svelte @@ -15,7 +15,7 @@ let error = $derived(serverStore.error); let loading = $derived(serverStore.loading); let model = $derived(modelsStore.singleModelName); - let serverData = $derived(serverStore.props); + let serverData = $derived(serverStore.localProps); function getStatusColor() { if (loading) return 'status-lamp orb-warning'; diff --git a/ui/apps/chat/src/lib/components/app/servers/index.ts b/ui/apps/chat/src/lib/components/app/servers/index.ts index 29394fddebb9..c4afc9a28e73 100644 --- a/ui/apps/chat/src/lib/components/app/servers/index.ts +++ b/ui/apps/chat/src/lib/components/app/servers/index.ts @@ -78,3 +78,10 @@ export { default as ServerErrorSplash } from './ServerErrorSplash.svelte'; * ``` */ export { default as ServerLoadingSplash } from './ServerLoadingSplash.svelte'; + +export { default as ServerCard } from './ServerCard.svelte'; +export { default as ServerForm } from './ServerForm.svelte'; +export { default as ServerIcon } from './ServerIcon.svelte'; +export { default as DialogServerCodeScanner } from './DialogServerCodeScanner.svelte'; +export { default as DialogServerForm } from './DialogServerForm.svelte'; +export { default as DialogServers } from './DialogServers.svelte'; diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte index 38452cbb951e..cd64d8ff0458 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte @@ -3,6 +3,7 @@ import { RefreshCw } from '@lucide/svelte'; import { SettingsChatDesktopSidebar, + SettingsChatExtensionsTab, SettingsChatFields, SettingsChatImportExportTab, SettingsChatMobileHeader, @@ -18,6 +19,7 @@ SETTINGS_SECTION_SLUGS } from '#lib/constants/index.ts'; import { ColorMode } from '#lib/enums/ui.enums.ts'; + import { StorageModeService } from '#lib/services/index.ts'; import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts'; import type { SettingsSection, SettingsSectionTitle } from '#lib/types/index.ts'; import { applySurfaceTheme } from '#lib/utils/index.ts'; @@ -66,12 +68,17 @@ return false; }); + // Snapshot used to persist only the fields edited in this dialog. Config keys + // that other surfaces write directly (servers, MCP servers) must not be + // clobbered by the dialog's save. + let baseline: SettingsConfigType = $state({ ...settingsStore.config }); + let mobileHeader: { updateCarousel: () => void } | undefined; let fetchInitiated = false; $effect(() => { - if (serverStore.isRouterMode && currentSection.fields?.length && !fetchInitiated) { + if (serverStore.localIsRouter && currentSection.fields?.length && !fetchInitiated) { fetchInitiated = true; void modelsStore @@ -106,6 +113,7 @@ function handleReset() { localConfig = { ...settingsStore.config }; + baseline = { ...settingsStore.config }; setMode(localConfig.theme as ColorMode); applySurfaceTheme(localConfig[SETTINGS_KEYS.SURFACE_THEME]); mobileHeader?.updateCarousel(); @@ -127,7 +135,13 @@ } } - const processedConfig = { ...localConfig }; + const processedConfig: SettingsConfigType = {}; + + for (const [key, value] of Object.entries(localConfig)) { + if (value !== baseline[key]) { + processedConfig[key] = value; + } + } for (const field of NUMERIC_FIELDS) { if (processedConfig[field] !== undefined && processedConfig[field] !== '') { @@ -159,6 +173,7 @@ export function reset() { localConfig = { ...settingsStore.config }; + baseline = { ...settingsStore.config }; } @@ -183,6 +198,8 @@
{#if currentSection.slug === SETTINGS_SECTION_SLUGS.TOOLS} + {:else if currentSection.slug === SETTINGS_SECTION_SLUGS.EXTENSIONS} + {:else if currentSection.slug === SETTINGS_SECTION_SLUGS.IMPORT_EXPORT} {:else if currentSection.fields} @@ -209,7 +226,11 @@
-

Settings are saved in browser's localStorage

+

+ {StorageModeService.activeAdapter + ? `Settings are saved on ${StorageModeService.activeAdapter.name}` + : "Settings are saved in browser's localStorage"} +

diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatExtensionsTab.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatExtensionsTab.svelte new file mode 100644 index 000000000000..ed17efb754b3 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatExtensionsTab.svelte @@ -0,0 +1,64 @@ + + +
+

+ Features you can switch off. An extension that is off does not run. +

+ + {#if registry.extensions.length === 0} +
No extensions available
+ {:else} +
    + {#each registry.extensions as extension (extension.id)} + {@const switchId = `extension-${extension.id}`} + {@const descriptionId = `${switchId}-description`} + +
  • +
    + + +

    + {extension.description} +

    + + {#if extension.state === 'failed'} + + {/if} +
    + + void registry.setEnabled(extension.id, checked)} + /> +
  • + {/each} +
+ {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte index 4dc97756d7fa..a6ff5355bf12 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte @@ -5,7 +5,7 @@ import * as RadioGroup from '@ggml-org/llama-ui/ui/radio-group'; import * as Select from '@ggml-org/llama-ui/ui/select'; import { Textarea } from '@ggml-org/llama-ui/ui/textarea'; - import { FlaskConical, RotateCcw } from '@lucide/svelte'; + import { FlaskConical, RotateCcw, ShieldAlert } from '@lucide/svelte'; import { SettingsChatParameterSourceIndicator } from '#lib/components/app/settings/index.ts'; import { ICON_CLASS_DEFAULT, @@ -14,6 +14,7 @@ SETTINGS_KEYS } from '#lib/constants/index.ts'; import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; + import { extensions } from '#lib/extensions/index.ts'; import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts'; import { normalizeFloatingPoint } from '#lib/utils/precision.ts'; import type { Component } from 'svelte'; @@ -31,6 +32,11 @@ // are read-only while discover is on let discoverOn = $derived(Boolean(localConfig[SETTINGS_KEYS.ENABLE_DISCOVER_MODELS])); + // a field that belongs to an extension shows only while that extension is on + let visibleFields = $derived( + fields.filter((field) => !field.extension || extensions.isActive(field.extension)) + ); + function isLockedField(key: string): boolean { return ( discoverOn && @@ -41,7 +47,7 @@ let currentModelParams = $derived.by(() => { void modelsStore.props.cacheVersion; - if (serverStore.isRouterMode) { + if (serverStore.localIsRouter) { const currentModelName = modelsStore.selectedModelName; if (currentModelName) { @@ -58,7 +64,7 @@ }); -{#each fields as field (field.key)} +{#each visibleFields as field (field.key)} {#if !field.dependsOn || Boolean(localConfig[field.dependsOn])}
{#if field.type === SettingsFieldType.INPUT} @@ -343,6 +349,14 @@ {field.help || SETTING_CONFIG_INFO[field.key]}

{/if} + + {#if field.note} +

+ + + {field.note} +

+ {/if}
{/if} diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportExportTab.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportExportTab.svelte index 9f95d5e44cea..d6b6eca455f8 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportExportTab.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportExportTab.svelte @@ -1,6 +1,6 @@
+ {#if activeStorage} + + openStorageDialog(null)} + title="Stored on {activeStorage.name}" + /> + + {:else if offeredStorage.length > 0} + + {#each offeredStorage as adapter (adapter.id)} + openStorageDialog(adapter)} + title="Stored in this browser" + /> + {/each} + + {/if} + + (showStorageDialog = false)} + onConfirm={handleStorageConfirm} + title={storageTarget ? `Store on ${storageTarget.name}` : 'Store in this browser'} +/> + e.stopPropagation()} /> - {@const faviconUrl = group.serverId ? mcpStore.getServerFavicon(group.serverId) : null} + {@const GroupIdentity = toolsStore.getGroupIdentity(group)} - {#if group.source === 'mcp'} - + {#if GroupIdentity && group.serverId} + {:else} {/if} diff --git a/ui/apps/chat/src/lib/components/app/settings/index.ts b/ui/apps/chat/src/lib/components/app/settings/index.ts index 2d2aca5af17a..1f0da690670f 100644 --- a/ui/apps/chat/src/lib/components/app/settings/index.ts +++ b/ui/apps/chat/src/lib/components/app/settings/index.ts @@ -53,16 +53,19 @@ export { default as SettingsResetButton } from './SettingsResetButton.svelte'; 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. + * **SettingsChatExtensionsTab** - Extensions section of the settings + * + * Lists the extensions the app knows (name, description) with a switch for + * each. A switch takes effect at once and the choice is remembered. An + * extension that failed to load or activate shows why. */ -export { default as SettingsChatImportExportSection } from './SettingsChat/SettingsChatImportExportSection.svelte'; +export { default as SettingsChatExtensionsTab } from './SettingsChat/SettingsChatExtensionsTab.svelte'; /** - * MCP Servers configuration panel. - * Provides UI for managing Model Context Protocol (MCP) server connections. + * Section wrapper for import/export sections. Displays a title, description, + * icon button, and optional summary of recent actions. */ -export { default as SettingsMcpServers } from './SettingsMcpServers.svelte'; +export { default as SettingsChatImportExportSection } from './SettingsChat/SettingsChatImportExportSection.svelte'; /** * Form fields renderer for individual settings. Generates appropriate input @@ -79,3 +82,8 @@ export { default as SettingsChatFields } from './SettingsChat/SettingsChatFields * server favicons and permission management controls. */ export { default as SettingsChatToolsTab } from './SettingsChat/SettingsChatToolsTab.svelte'; + +/** + * Servers panel for chat settings. Switches between the llama.cpp and + * OpenAI-compatible protocols and lists the endpoints configured for each. + */ diff --git a/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts b/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts index 2f6efb94cba3..b03173f55d3b 100644 --- a/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts +++ b/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts @@ -19,6 +19,13 @@ export const API_SLOTS = { LIST: './slots' }; +// conversations and settings kept on the server, requires the --ui-storage flag +export const API_STORAGE = { + CONVERSATIONS: './storage/conversations', + RECORDS: './storage/records', + SETTINGS: './storage/settings' +}; + export const API_TOOLS = { EXECUTE: '/tools', LIST: '/tools' diff --git a/ui/apps/chat/src/lib/constants/attachment-menu.constants.ts b/ui/apps/chat/src/lib/constants/attachment-menu.constants.ts index 2888457765d5..65a66bad15f6 100644 --- a/ui/apps/chat/src/lib/constants/attachment-menu.constants.ts +++ b/ui/apps/chat/src/lib/constants/attachment-menu.constants.ts @@ -62,6 +62,7 @@ export const ATTACHMENT_TOOLTIP_TEXT = 'Add files, prompts, tools or MCP Servers export const ATTACHMENT_MENU_TEXT = { ADD_FILES: 'Add files', ADD_TO_CHAT: 'Add to chat', + ADD_TO_PROJECT: 'Add to project', DESCRIPTION: 'Add files, system prompt or pick the tools the model may call', SYSTEM_MESSAGE: 'System Message', TOOLS: 'Tools' diff --git a/ui/apps/chat/src/lib/constants/backend.constants.ts b/ui/apps/chat/src/lib/constants/backend.constants.ts deleted file mode 100644 index 57f5c4213220..000000000000 --- a/ui/apps/chat/src/lib/constants/backend.constants.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Marks the built-in local llama.cpp backend. */ -export const LOCAL_BACKEND_ID = 'local'; diff --git a/ui/apps/chat/src/lib/constants/chat-tabs.constants.ts b/ui/apps/chat/src/lib/constants/chat-tabs.constants.ts index cc3f97b83079..ff00d451ac17 100644 --- a/ui/apps/chat/src/lib/constants/chat-tabs.constants.ts +++ b/ui/apps/chat/src/lib/constants/chat-tabs.constants.ts @@ -1,6 +1,9 @@ /** Sentinel tab id for the bare `#/` new-chat screen */ export const NEW_CHAT_TAB_ID = 'new-chat'; +/** Route target of a project's home page, which never gets a tab */ +export const PROJECT_HOME_TAB_ID = 'project-home'; + /** Label shown for the new-chat sentinel tab. */ export const NEW_CHAT_LABEL = 'New chat'; diff --git a/ui/apps/chat/src/lib/constants/css-classes.constants.ts b/ui/apps/chat/src/lib/constants/css-classes.constants.ts index 4ef04f9a61fb..aade305d2ab1 100644 --- a/ui/apps/chat/src/lib/constants/css-classes.constants.ts +++ b/ui/apps/chat/src/lib/constants/css-classes.constants.ts @@ -34,6 +34,11 @@ export const GLASS_KEY_CLASS = export const TAB_SURFACE_ACTIVE_CLASS = 'matte-key bg-muted/60 border-border/10 text-accent-foreground hover:bg-primary/15'; +/** Trailing control of a panel section header: the trigger of a section menu takes the flat + * look of a solo action icon, so both read as the same control. */ +export const SECTION_ACTION_CLASS = + 'hover:bg-transparent focus:bg-transparent dark:hover:bg-transparent data-[state=open]:bg-transparent focus-visible:ring-[3px] focus-visible:ring-ring/50'; + /** 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"]'; diff --git a/ui/apps/chat/src/lib/constants/database.constants.ts b/ui/apps/chat/src/lib/constants/database.constants.ts index fb77d117a954..fde99e2ed81a 100644 --- a/ui/apps/chat/src/lib/constants/database.constants.ts +++ b/ui/apps/chat/src/lib/constants/database.constants.ts @@ -1,5 +1,5 @@ /** - * Database-related constants (IndexedDB, Dexie). + * Database-related constants (IndexedDB). * * Centralized to ensure consistency across the app and simplify future * naming changes. @@ -14,28 +14,30 @@ export const DB_NAME = STORAGE_APP_NAME; export const IDXDB_TABLES = { conversations: 'conversations', groups: 'groups', - messages: 'messages' + messages: 'messages', + projects: 'projects', + prompts: 'prompts' } as const; -/** IndexedDB store schemas */ -export const IDXDB_STORE_SCHEMAS = { - conversations: 'id, lastModified, currNode, name', - groups: 'id, updatedAt, name', - messages: 'id, convId, type, role, timestamp, parent, children' -} as const; - -/** Combined Dexie stores definition — keys are table names, values are schemas */ -export const IDXDB_STORES = { - [IDXDB_TABLES.conversations]: IDXDB_STORE_SCHEMAS.conversations, - [IDXDB_TABLES.groups]: IDXDB_STORE_SCHEMAS.groups, - [IDXDB_TABLES.messages]: IDXDB_STORE_SCHEMAS.messages -} as const; +/** + * Indexes of each store, every one keyed by `id`. Each index is named after + * the field it covers and is neither unique nor multi-entry: the layout Dexie + * created from its `'id, lastModified, ...'` schemas, kept so existing + * databases open unchanged. + */ +export const IDXDB_STORE_INDEXES = { + conversations: ['lastModified', 'currNode', 'name'], + groups: ['updatedAt', 'name'], + messages: ['convId', 'type', 'role', 'timestamp', 'parent', 'children'], + projects: ['updatedAt', 'name'], + prompts: ['lastModified', 'name'] +} as const satisfies Record; -/** Stores of schema version 1, before the groups table existed. */ -export const IDXDB_STORES_V1 = { - [IDXDB_TABLES.conversations]: IDXDB_STORE_SCHEMAS.conversations, - [IDXDB_TABLES.messages]: IDXDB_STORE_SCHEMAS.messages -} as const; +/** Primary key path of every store */ +export const IDXDB_KEY_PATH = 'id'; -/** Schema version new Dexie instances open the database at; bump with a new version block. */ -export const IDXDB_VERSION = 2; +/** + * IndexedDB version the database is opened at. Dexie stored its schema + * version 4 (prompts added) as 4 * 10; a new store or index bumps this. + */ +export const IDXDB_VERSION = 40; diff --git a/ui/apps/chat/src/lib/constants/icons.constants.ts b/ui/apps/chat/src/lib/constants/icons.constants.ts index ff2918ee2e7e..fb413b83e87b 100644 --- a/ui/apps/chat/src/lib/constants/icons.constants.ts +++ b/ui/apps/chat/src/lib/constants/icons.constants.ts @@ -10,7 +10,8 @@ import UnloadIcon from '@lucide/svelte/icons/eject'; import FileIcon from '@lucide/svelte/icons/file'; 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 CwdCommandIcon from '@lucide/svelte/icons/folder'; +import ProjectIcon from '@lucide/svelte/icons/folder-open'; import ImageIcon from '@lucide/svelte/icons/image'; import LoadingIcon from '@lucide/svelte/icons/loader-2'; import AudioIcon from '@lucide/svelte/icons/mic'; @@ -19,7 +20,6 @@ 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'; @@ -46,6 +46,12 @@ export const DEFAULT_FILE_ICON = FileIcon; /** The mark for a model, wherever one is listed. */ export const MODEL_ICON = ModelIcon; +/** + * The mark for a project, wherever one is listed: an open folder. The working + * directory, which a project may have, is the closed folder. + */ +export const PROJECT_ICON = ProjectIcon; + /** The mark for the Discover Models surface and its entry points. */ export const DISCOVER_ICON = DiscoverIcon; @@ -63,12 +69,11 @@ export const CAPABILITY_FLAG_KEYS: Record = { [ChatFormCommandAction.COMPACT]: CompactCommandIcon, [ChatFormCommandAction.CWD]: CwdCommandIcon, - [ChatFormCommandAction.MODEL]: MODEL_ICON, - [ChatFormCommandAction.PROMPT]: PromptCommandIcon + [ChatFormCommandAction.MODEL]: MODEL_ICON }; /** Icons of the download control a manager row shows while it downloads. */ diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts index 46feb4a6dd4a..8905f88c1bf9 100644 --- a/ui/apps/chat/src/lib/constants/index.ts +++ b/ui/apps/chat/src/lib/constants/index.ts @@ -4,7 +4,8 @@ export * from './agentic.constants'; export * from './api-endpoints.constants'; export * from './app.constants'; -export * from './backend.constants'; +export * from './servers.constants'; +export * from './webrtc.constants'; export * from './chat-tabs.constants'; export * from './database.constants'; export * from './reasoning-effort.constants'; @@ -68,9 +69,12 @@ export * from './table-html-restorer.constants'; export * from './title-generation.constants'; export * from './ui.constants'; export * from './uri-template.constants'; +export * from './projects.constants'; export * from './url.constants'; export * from './working-directory.constants'; export * from './read-media'; export * from './get-datetime'; +export * from './project-tools'; export * from './browser-info'; export * from './search-chats'; +export * from './library.constants'; diff --git a/ui/apps/chat/src/lib/constants/library.constants.ts b/ui/apps/chat/src/lib/constants/library.constants.ts new file mode 100644 index 000000000000..fe23c5153f36 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/library.constants.ts @@ -0,0 +1,17 @@ +import AudioLines from '@lucide/svelte/icons/audio-lines'; +import Film from '@lucide/svelte/icons/film'; +import Image from '@lucide/svelte/icons/image'; +import { LibraryItemKind, LibraryTab } from '#lib/enums/index.ts'; +import type { Component } from 'svelte'; + +/** The mark of each kind of media item. */ +export const LIBRARY_KIND_ICONS: Record = { + [LibraryItemKind.AUDIO]: AudioLines, + [LibraryItemKind.IMAGE]: Image, + [LibraryItemKind.VIDEO]: Film +}; + +export const LIBRARY_TABS: { label: string; value: LibraryTab }[] = [ + { label: 'Prompts', value: LibraryTab.PROMPTS }, + { label: 'Media', value: LibraryTab.MEDIA } +]; diff --git a/ui/apps/chat/src/lib/constants/mcp.constants.ts b/ui/apps/chat/src/lib/constants/mcp.constants.ts index fffbdc9de96e..2b9591d65c67 100644 --- a/ui/apps/chat/src/lib/constants/mcp.constants.ts +++ b/ui/apps/chat/src/lib/constants/mcp.constants.ts @@ -21,23 +21,18 @@ export const MCP_ALLOWED_ICON_MIME_TYPES = new Set([ MimeTypeImage.ICO_MICROSOFT ]); -/** - * MCP specification version this client targets. - * Update when the upstream MCP spec introduces a new stable version: - * https://spec.modelcontextprotocol.io/ - */ -export const MCP_PROTOCOL_VERSION = '2025-06-18'; - export const DEFAULT_MCP_CONFIG = { capabilities: { tools: { listChanged: true } } as ClientCapabilities, clientInfo: { name: MCP_CLIENT_NAME, version: DEFAULT_CLIENT_VERSION } as Implementation, connectionTimeoutMs: 10_000, // 10 seconds for connection establishment - protocolVersion: MCP_PROTOCOL_VERSION, requestTimeoutSeconds: 300 // 5 minutes for long-running tools } as const; export const MCP_SERVER_ID_PREFIX = 'LlamaUI-MCP-Server'; +/** Prefix of MCP prompt ids, so they never match a library prompt id. */ +export const MCP_PROMPT_ID_PREFIX = 'mcp:'; + /** Backoff policy for reconnecting to a dropped MCP server. */ export const MCP_RECONNECT = { /** Per-attempt timeout for a single reconnection attempt before giving up and backing off. */ diff --git a/ui/apps/chat/src/lib/constants/message-export.constants.ts b/ui/apps/chat/src/lib/constants/message-export.constants.ts index f6c576d792b6..671e6d7c9a06 100644 --- a/ui/apps/chat/src/lib/constants/message-export.constants.ts +++ b/ui/apps/chat/src/lib/constants/message-export.constants.ts @@ -22,3 +22,11 @@ export const EXPORT_CONV = { NON_ALPHANUMERIC_REGEX: /[^a-z0-9]/gi, NONALNUM_REPLACEMENT: '_' } as const; + +/** Archive layout of a project export. */ +export const EXPORT_PROJECT = { + /** Folder holding one .jsonl per conversation of the project. */ + CONVERSATIONS_DIR: 'conversations/', + /** Project row, at the archive root. */ + PROJECT_ENTRY: 'project.json' +} as const; diff --git a/ui/apps/chat/src/lib/constants/project-tools.ts b/ui/apps/chat/src/lib/constants/project-tools.ts new file mode 100644 index 000000000000..f6eae79e330a --- /dev/null +++ b/ui/apps/chat/src/lib/constants/project-tools.ts @@ -0,0 +1,80 @@ +import { BuiltInTool, JsonSchemaType, ToolCallType } from '#lib/enums/index.ts'; +import type { OpenAIToolDefinition } from '#lib/types/index.ts'; + +/** Browser tools that read and edit the user's projects, offered once a project exists. */ +export const PROJECT_TOOL_NAMES: readonly string[] = [ + BuiltInTool.BROWSER_LIST_PROJECTS, + BuiltInTool.BROWSER_GET_PROJECT, + BuiltInTool.BROWSER_UPDATE_PROJECT, + BuiltInTool.BROWSER_ADD_PROJECT_CONTEXT +]; + +const PROJECT_ID_PROPERTY = { + description: + "Id of the project, from list_projects. Defaults to the current chat's project when the chat is in one.", + type: JsonSchemaType.STRING +}; + +function tool( + name: string, + description: string, + properties: Record +): OpenAIToolDefinition { + return { + function: { + description, + name, + parameters: { properties, required: [], type: JsonSchemaType.OBJECT } + }, + type: ToolCallType.FUNCTION + }; +} + +export function buildProjectToolDefinitions(): OpenAIToolDefinition[] { + return [ + tool( + BuiltInTool.BROWSER_LIST_PROJECTS, + "Lists the user's projects with their id, name, goal and number of chats. Projects group chats that share instructions and context files.", + {} + ), + tool( + BuiltInTool.BROWSER_GET_PROJECT, + "Returns a project's name, goal, instructions, context items and working directory.", + { project_id: PROJECT_ID_PROPERTY } + ), + tool( + BuiltInTool.BROWSER_UPDATE_PROJECT, + "Updates the current chat's project: renames it, sets its goal, and replaces or extends its instructions. Instructions are added to every new chat in the project. Only the given fields change.", + { + append_instructions: { + description: 'Text added after the current instructions, on a new line.', + type: JsonSchemaType.STRING + }, + goal: { + description: 'What the project is trying to achieve, in a sentence.', + type: JsonSchemaType.STRING + }, + instructions: { + description: 'Replaces all of the instructions. Use append_instructions to keep them.', + type: JsonSchemaType.STRING + }, + name: { description: 'New name of the project.', type: JsonSchemaType.STRING } + } + ), + tool( + BuiltInTool.BROWSER_ADD_PROJECT_CONTEXT, + "Adds context to the current chat's project, which new chats in it start with: either a file on the server, referenced by its absolute path, or a text note saved with the project. Give either path, or note_name with note_content.", + { + note_content: { description: 'Text of the note.', type: JsonSchemaType.STRING }, + note_name: { + description: 'File name for the note, e.g. "decisions.md".', + type: JsonSchemaType.STRING + }, + path: { + description: 'Absolute path of a server file to reference.', + type: JsonSchemaType.STRING + } + } + ) + ]; +} diff --git a/ui/apps/chat/src/lib/constants/projects.constants.ts b/ui/apps/chat/src/lib/constants/projects.constants.ts new file mode 100644 index 000000000000..595ceda685f8 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/projects.constants.ts @@ -0,0 +1,2 @@ +/** Longest project name, also the name field's `maxlength`. */ +export const PROJECT_NAME_MAX_LENGTH = 200; diff --git a/ui/apps/chat/src/lib/constants/routes.constants.ts b/ui/apps/chat/src/lib/constants/routes.constants.ts index a5d4ad35fc70..80955488a96e 100644 --- a/ui/apps/chat/src/lib/constants/routes.constants.ts +++ b/ui/apps/chat/src/lib/constants/routes.constants.ts @@ -1,3 +1,5 @@ +import type { RouteId } from '$app/types'; + /** Query params the chat routes read from the URL. */ export const URL_PARAMS = { /** Load the selected model instead of waiting for the first message. */ @@ -8,26 +10,34 @@ export const URL_PARAMS = { QUERY: 'q' } as const; +/** + * Route ids of the app's pages, as `page.route.id` reports them. Navigate with + * `resolve(ROUTES.MODELS)` from `$app/paths`, which checks the route exists and returns its URL + * (`#/models` with the hash router); URLs with ids come from RouterService. + */ export const ROUTES = { - /** Chat base — for dynamic chat URLs use RouterService. */ - CHAT: '#/chat', - /** MCP servers - a page on a phone, a dialog elsewhere. */ - MCP_SERVERS: '#/mcp-servers', + /** A conversation outside any project. */ + CHAT: '/(chat)/chat/[id]', + /** A page an extension contributes, see RouterService.extensionPage(). */ + EXTENSION_PAGE: '/[extensionPage]', + /** Library. */ + LIBRARY: '/library', /** Models manager. */ - MODELS: '#/models', + MODELS: '/models', + /** A project's overview. */ + PROJECT: '/(chat)/projects/[projectId]', + /** A chat opened inside its project. */ + PROJECT_CHAT: '/(chat)/projects/[projectId]/chat/[id]', + /** The new-chat screen of a project. */ + PROJECT_NEW_CHAT: '/(chat)/projects/[projectId]/chat/new', + /** Projects list. */ + PROJECTS: '/projects', /** Search — mobile-only full-page conversation search. */ - SEARCH: '#/search', + SEARCH: '/search', + /** Servers - a page on a phone, a dialog elsewhere. */ + SERVERS: '/servers', /** Settings - a page on a phone, a dialog elsewhere. */ - SETTINGS: '#/settings', + SETTINGS: '/settings', /** Root — start of the app. */ - START: '#/' -} as const; - -/** SvelteKit route id of the models manager, as `page.route.id` reports it. */ -export const MODELS_ROUTE_ID = '/models'; - -/** SvelteKit route id of the MCP servers page, as `page.route.id` reports it. */ -export const MCP_SERVERS_ROUTE_ID = '/mcp-servers'; - -/** SvelteKit route id of the settings page, as `page.route.id` reports it. */ -export const SETTINGS_ROUTE_ID = '/settings'; + START: '/(chat)' +} as const satisfies Record; diff --git a/ui/apps/chat/src/lib/constants/servers.constants.ts b/ui/apps/chat/src/lib/constants/servers.constants.ts new file mode 100644 index 000000000000..3234bdbe8fa9 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/servers.constants.ts @@ -0,0 +1,27 @@ +/** Prefix for generated ids of user-added servers. */ +export const SERVER_ID_PREFIX = 'server'; + +/** Chat completions path every server serves. */ +export const DEFAULT_SERVER_CHAT_PATH = '/v1/chat/completions'; + +/** Models listing path every server serves. */ +export const DEFAULT_SERVER_MODELS_PATH = '/v1/models'; + +/** Id of the built-in backend that points at the server serving this UI. */ +export const LOCAL_BACKEND_ID = 'local'; + +/** Favicon extract keyed by domain, for servers with no bundled mark. */ +export const FAVICON_SERVICE_URL = 'https://www.google.com/s2/favicons?domain='; + +/** + * File next to index.html listing servers the app adds on startup, as + * `{ "servers": [{ "url": "http://127.0.0.1:9931" }] }`. `llama-chat --server` + * serves it, and `llama-chat build --server` writes it. + */ +export const PRESET_SERVERS_FILE = 'llama-chat.json'; + +/** + * Name of the meta tag in index.html that says {@link PRESET_SERVERS_FILE} is + * there: pages served any other way, such as by llama-server, never ask for it. + */ +export const PRESET_SERVERS_META = 'llama-chat-servers'; diff --git a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts index 03e9a39d54c6..f1b86f30787d 100644 --- a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts @@ -10,6 +10,7 @@ export const SETTINGS_KEYS = { ALWAYS_SHOW_TOOL_CALL_CONTENT: 'alwaysShowToolCallContent', API_KEY: 'apiKey', AUTO_MIC_ON_EMPTY: 'autoMicOnEmpty', + // llama.cpp's own flag: "backend" here is the compute backend, not a server BACKEND_SAMPLING: 'backend_sampling', COMPACTION_PRESERVED_STEPS: 'compactionPreservedSteps', COMPACTION_PROMPT: 'compactionPrompt', @@ -29,11 +30,13 @@ export const SETTINGS_KEYS = { DYNATEMP_RANGE: 'dynatemp_range', ENABLE_CONTINUE_GENERATION: 'enableContinueGeneration', ENABLE_DISCOVER_MODELS: 'enableDiscoverModels', + ENABLE_REMOTE_PAIRING: 'enableRemotePairing', EXCLUDE_REASONING_FROM_CONTEXT: 'excludeReasoningFromContext', FREQUENCY_PENALTY: 'frequency_penalty', FULL_HEIGHT_CODE_BLOCKS: 'fullHeightCodeBlocks', GROUP_MODELS_BY_FAMILY: 'groupModelsByFamily', LIVE_MARKDOWN_PREVIEW: 'liveMarkdownPreview', + LOCAL_BACKEND_ENABLED: 'localBackendEnabled', MAX_IMAGE_RESOLUTION: 'maxImageMPixels', MAX_TOKENS: 'max_tokens', MCP_REQUEST_TIMEOUT_SECONDS: 'mcpRequestTimeoutSeconds', @@ -54,6 +57,8 @@ export const SETTINGS_KEYS = { REPEAT_PENALTY: 'repeat_penalty', SAMPLERS: 'samplers', SEND_ON_ENTER: 'sendOnEnter', + // the server list is stored under the key it shipped with, so the value is not its name + SERVERS: 'backends', SHOW_AGENTIC_TURN_STATS: 'showAgenticTurnStats', SHOW_BUILD_VERSION: 'showBuildVersion', SHOW_FULL_PATH_IN_MENTIONS: 'showFullPathInMentions', diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts index 4f1f77237a6e..90155ce64d51 100644 --- a/ui/apps/chat/src/lib/constants/settings.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings.constants.ts @@ -14,6 +14,7 @@ import ListRestart from '@lucide/svelte/icons/list-restart'; import Monitor from '@lucide/svelte/icons/monitor'; import Moon from '@lucide/svelte/icons/moon'; import PencilRuler from '@lucide/svelte/icons/pencil-ruler'; +import Puzzle from '@lucide/svelte/icons/puzzle'; import SlidersVertical from '@lucide/svelte/icons/sliders-vertical'; import Sun from '@lucide/svelte/icons/sun'; import { SurfaceTheme, SyncableParameterType } from '#lib/enums/index.ts'; @@ -32,6 +33,7 @@ export const SETTINGS_SECTIONS = { AGENTIC: { slug: 'agentic', title: 'Agentic' }, DEVELOPER: { slug: 'developer', title: 'Developer' }, DISPLAY: { slug: 'display', title: 'Display' }, + EXTENSIONS: { slug: 'extensions', title: 'Extensions' }, GENERAL: { slug: 'general', title: 'General' }, IMPORT_EXPORT: { slug: 'import-export', title: 'Import/Export' }, SAMPLING_PENALTIES: { slug: 'sampling-penalties', title: 'Sampling & Penalties' }, @@ -42,6 +44,7 @@ export const SETTINGS_SECTION_SLUGS = { AGENTIC: SETTINGS_SECTIONS.AGENTIC.slug, DEVELOPER: SETTINGS_SECTIONS.DEVELOPER.slug, DISPLAY: SETTINGS_SECTIONS.DISPLAY.slug, + EXTENSIONS: SETTINGS_SECTIONS.EXTENSIONS.slug, GENERAL: SETTINGS_SECTIONS.GENERAL.slug, IMPORT_EXPORT: SETTINGS_SECTIONS.IMPORT_EXPORT.slug, SAMPLING_PENALTIES: SETTINGS_SECTIONS.SAMPLING_PENALTIES.slug, @@ -52,6 +55,7 @@ export const SETTINGS_SECTION_TITLES = { AGENTIC: SETTINGS_SECTIONS.AGENTIC.title, DEVELOPER: SETTINGS_SECTIONS.DEVELOPER.title, DISPLAY: SETTINGS_SECTIONS.DISPLAY.title, + EXTENSIONS: SETTINGS_SECTIONS.EXTENSIONS.title, GENERAL: SETTINGS_SECTIONS.GENERAL.title, IMPORT_EXPORT: SETTINGS_SECTIONS.IMPORT_EXPORT.title, SAMPLING_PENALTIES: SETTINGS_SECTIONS.SAMPLING_PENALTIES.title, @@ -173,6 +177,15 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ label: 'Show MCP', type: SettingsFieldType.CHECKBOX }, + { + defaultValue: false, + help: 'Experimental: pair a llama-server started with --connect by its access code or QR code, and reach it peer-to-peer over WebRTC from any network. Servers added by URL work either way.', + isExperimental: true, + key: SETTINGS_KEYS.ENABLE_REMOTE_PAIRING, + label: 'Enable remote server pairing', + note: 'Known security gap: the pass code in the access code is sent to whichever peer answers on the public WebTorrent tracker, so someone watching that tracker could capture it. A mutual challenge-response, where both sides prove they know the code without ever sending it, is the planned fix.', + 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.', @@ -435,6 +448,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ }, { defaultValue: DEFAULT_MCP_CONFIG.requestTimeoutSeconds, + extension: 'mcp', help: 'Timeout for individual MCP tool calls.', isPositiveInteger: true, key: SETTINGS_KEYS.MCP_REQUEST_TIMEOUT_SECONDS, @@ -456,6 +470,13 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ slug: SETTINGS_SECTION_SLUGS.AGENTIC, title: SETTINGS_SECTION_TITLES.AGENTIC }, + // Extensions: the list comes from the extension registry, not from settings + { + icon: Puzzle, + settings: [], + slug: SETTINGS_SECTION_SLUGS.EXTENSIONS, + title: SETTINGS_SECTION_TITLES.EXTENSIONS + }, // Import/Export { icon: Database, @@ -755,6 +776,7 @@ function toSettingsSection(section: SettingsSectionEntry): SettingsSection { .filter((s) => s.standaloneField !== false) .map((s) => ({ dependsOn: s.dependsOn, + extension: s.extension, help: s.help, isExperimental: s.isExperimental, isPositiveInteger: s.isPositiveInteger, @@ -763,6 +785,7 @@ function toSettingsSection(section: SettingsSectionEntry): SettingsSection { label: s.label, max: s.max, min: s.min, + note: s.note, options: s.options as SettingsFieldConfig['options'], placeholder: s.placeholder, radioOptions: s.radioOptions, diff --git a/ui/apps/chat/src/lib/constants/storage.constants.ts b/ui/apps/chat/src/lib/constants/storage.constants.ts index 1b10507dd491..b1d50ecef2fe 100644 --- a/ui/apps/chat/src/lib/constants/storage.constants.ts +++ b/ui/apps/chat/src/lib/constants/storage.constants.ts @@ -16,6 +16,13 @@ export const DB_APP_NAME_DEPRECATED = 'LlamacppWebui'; export const ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.alwaysAllowedTools`; +/** Id of the server the selector and new requests target, restored on page load. */ +/* Kept under the name it was first stored under; only the constant was renamed. */ +export const ACTIVE_SERVER_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.activeBackend`; + +/** Base URLs of the preset servers already added once, so one the user removed stays removed. */ +export const PRESET_SERVERS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.presetServers`; + export const CONFIG_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.config`; export const DISABLED_TOOLS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.disabledTools`; @@ -24,15 +31,24 @@ export const DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.disabled /** Default disabled tool categories, seeded into newly created conversations */ export const DISABLED_TOOL_CATEGORIES_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.disabledToolCategories`; + +/** The user's on/off choice per extension, by extension id */ +export const EXTENSIONS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.extensions`; export const FAVORITE_MODELS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.favoriteModels`; /** Open state the user set for a model list section or one of its families, by id. */ export const MODEL_GROUP_OPEN_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.modelGroupOpen`; -/** Recently used model ids, most recent first, backend-qualified. */ +/** Per-model load and inference overrides, keyed by server-qualified model id. */ +export const MODEL_OVERRIDES_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.modelOverrides`; + +/** Model the user picked last, kept across reloads. Stores `{ id, model }`. */ +export const SELECTED_MODEL_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.selectedModel`; + +/** Recently used model ids, most recent first, server-qualified. */ export const RECENT_MODELS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.recentModels`; -/** Model ids kept out of the selector, backend-qualified. */ +/** Model ids kept out of the selector, server-qualified. */ export const HIDDEN_MODELS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.hiddenModels`; export const REASONING_EFFORT_DEFAULT_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.reasoningEffortDefault`; /** Sidebar conversation sections the user folded. */ @@ -44,11 +60,32 @@ export const SIDEBAR_EXPANDED_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.sidebarExp export const SIDEBAR_WIDTH_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.sidebarWidth`; export const USER_OVERRIDES_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.userOverrides`; export const DISMISSED_RECOMMENDED_MCP_SERVERS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.dismissedRecommendedMcpServers`; +/* Likewise: the value is the key already written, the name is the one the list now has. */ +export const DISMISSED_RECOMMENDED_SERVERS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.dismissedRecommendedBackends`; /** Key prefix for per-conversation resumable stream state, conversationId is appended */ export const STREAM_RESUME_LOCALSTORAGE_KEY_PREFIX = `${STORAGE_APP_NAME}.streamResume.`; +/** Preference keys holding the user's own data; every other key is device-local UI state */ +export const USER_PREFERENCE_KEYS: ReadonlySet = new Set([ + ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY, + CONFIG_LOCALSTORAGE_KEY, + DISABLED_TOOL_CATEGORIES_LOCALSTORAGE_KEY, + DISABLED_TOOL_KEYS_LOCALSTORAGE_KEY, + DISMISSED_RECOMMENDED_MCP_SERVERS_LOCALSTORAGE_KEY, + DISMISSED_RECOMMENDED_SERVERS_LOCALSTORAGE_KEY, + EXTENSIONS_LOCALSTORAGE_KEY, + FAVORITE_MODELS_LOCALSTORAGE_KEY, + HIDDEN_MODELS_LOCALSTORAGE_KEY, + MODEL_OVERRIDES_LOCALSTORAGE_KEY, + REASONING_EFFORT_DEFAULT_LOCALSTORAGE_KEY, + RECENT_MODELS_LOCALSTORAGE_KEY, + USER_OVERRIDES_LOCALSTORAGE_KEY +]); + // Deprecated old key names (kept for backward compat while users migrate) +/** @deprecated Remote servers are settings-backed now; the demo build kept them here */ +export const LEGACY_TUNNEL_SERVERS_LOCALSTORAGE_KEY = 'llama_servers'; /** @deprecated Use {@link ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY} instead */ export const DEPRECATED_ALWAYS_ALLOWED_TOOLS_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME_DEPRECATED}.alwaysAllowedTools`; /** @deprecated Use {@link CONFIG_LOCALSTORAGE_KEY} instead */ @@ -60,6 +97,12 @@ 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`; +/** Storage adapter id this browser keeps conversations and user settings in, unset: this browser */ +export const STORAGE_ADAPTER_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.storageAdapter`; + +/** API key kept in this browser while the rest of the config lives on the server */ +export const API_KEY_LOCALSTORAGE_KEY = `${STORAGE_APP_NAME}.apiKey`; + /** 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/ui/apps/chat/src/lib/constants/stream.constants.ts b/ui/apps/chat/src/lib/constants/stream.constants.ts index 64f67243c266..b590996c045c 100644 --- a/ui/apps/chat/src/lib/constants/stream.constants.ts +++ b/ui/apps/chat/src/lib/constants/stream.constants.ts @@ -2,6 +2,10 @@ // while the tab was hidden. covers brief background pauses without thrashing live streams export const STREAM_VISIBILITY_KICK_MS = 3000; +// minimum gap between synthesized live timing updates for servers that do not +// stream their own, keeps the per-chunk state updates cheap +export const STREAM_LIVE_TIMINGS_INTERVAL_MS = 500; + // separator joining a conversation id and its per-model stream identity // suffix (conv::model) used by the server side replay buffer export const CONVERSATION_ID_SEPARATOR = '::'; diff --git a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts index dce125262e3e..ab7aa6c6cab5 100644 --- a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts +++ b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts @@ -7,6 +7,7 @@ // (see ChatMessageToolCallBlockGetDatetime and // ChatMessageToolCallBlockSearchResults for prior art). +import { PROJECT_ICON } from './icons.constants'; import Braces from '@lucide/svelte/icons/braces'; import Clock from '@lucide/svelte/icons/clock'; import Eye from '@lucide/svelte/icons/eye'; @@ -15,18 +16,35 @@ 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 List from '@lucide/svelte/icons/list'; import MessagesSquare from '@lucide/svelte/icons/messages-square'; +import Paperclip from '@lucide/svelte/icons/paperclip'; 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_ADD_PROJECT_CONTEXT]: { + icon: Paperclip, + label: 'Add project context', + source: ToolSource.BROWSER + }, [BuiltInTool.BROWSER_GET_DATETIME]: { icon: Clock, label: 'Current time', source: ToolSource.BROWSER }, + [BuiltInTool.BROWSER_GET_PROJECT]: { + icon: PROJECT_ICON, + label: 'Read project', + source: ToolSource.BROWSER + }, + [BuiltInTool.BROWSER_LIST_PROJECTS]: { + icon: List, + label: 'List projects', + source: ToolSource.BROWSER + }, [BuiltInTool.BROWSER_READ_MEDIA]: { icon: Eye, label: 'Read media', source: ToolSource.BROWSER }, [BuiltInTool.BROWSER_RUN_JAVASCRIPT]: { icon: Braces, @@ -38,6 +56,11 @@ export const TOOL_UI: Readonly> = { label: 'Search chats', source: ToolSource.BROWSER }, + [BuiltInTool.BROWSER_UPDATE_PROJECT]: { + icon: FilePen, + label: 'Update project', + source: ToolSource.BROWSER + }, [BuiltInTool.SERVER_EDIT_FILE]: { icon: FilePen, label: 'Edit file', source: ToolSource.SERVER }, [BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: { icon: Terminal, diff --git a/ui/apps/chat/src/lib/constants/ui.constants.ts b/ui/apps/chat/src/lib/constants/ui.constants.ts index 5ac2adfbb247..69dfa221cd54 100644 --- a/ui/apps/chat/src/lib/constants/ui.constants.ts +++ b/ui/apps/chat/src/lib/constants/ui.constants.ts @@ -1,17 +1,19 @@ -import { MODEL_ICON } from './icons.constants'; +import { MODEL_ICON, PROJECT_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 { ROUTES } from './routes.constants'; +import Library from '@lucide/svelte/icons/library'; import Search from '@lucide/svelte/icons/search'; +import Server from '@lucide/svelte/icons/server'; 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'; +import { resolve } from '$app/paths'; /** Delay before a copied affordance resets from its check to the copy icon. */ export const COPY_FEEDBACK_RESET_MS = 1500; @@ -50,6 +52,8 @@ export const SIDEBAR_SECTION_IDS = { /** Followed by the group id: one section per group. */ GROUP_PREFIX: 'group:', PINNED: 'pinned', + /** Followed by the project id: one section per project. */ + PROJECT_PREFIX: 'project:', RECENT: 'recent' } as const; @@ -97,8 +101,8 @@ export const STATS_UNITS = { 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; +/** Models listed per remote server before the "+ X more" line; search covers the rest. */ +export const REMOTE_SERVER_MODEL_LIMIT = 12; /** Model rows mounted before the list scrolls; a local catalog can hold hundreds. */ export const MODEL_ROW_WINDOW = 50; @@ -162,27 +166,42 @@ export const SIDEBAR_ACTIONS_ITEMS: DesktopIconStripItem[] = [ keys: SHORTCUT_NEW_CHAT, tooltip: 'New chat' }, - { action: SidebarAction.SEARCH, icon: Search, keys: SHORTCUT_SEARCH, tooltip: 'Search' } + { action: SidebarAction.SEARCH, icon: Search, keys: SHORTCUT_SEARCH, tooltip: 'Search' }, + { + action: SidebarAction.PROJECTS, + activeRouteId: ROUTES.PROJECTS, + icon: PROJECT_ICON, + tooltip: 'Projects' + }, + { + activeRoutePrefix: '/library', + icon: Library, + route: resolve(ROUTES.LIBRARY), + tooltip: 'Library' + } ]; -/** The sidebar's footer: managing the app around the chats. */ +/** + * The sidebar's footer: managing the app around the chats. Extensions add their + * items right after Models, which opens it (see `sidebarFooterItems`). + */ export const SIDEBAR_FOOTER_ITEMS: DesktopIconStripItem[] = [ { action: SidebarAction.MANAGE_MODELS, - activeRouteId: MODELS_ROUTE_ID, + activeRouteId: ROUTES.MODELS, icon: MODEL_ICON, keys: SHORTCUT_MODELS, tooltip: 'Models' }, { - action: SidebarAction.MCP, - activeRouteId: MCP_SERVERS_ROUTE_ID, - icon: McpLogo, - tooltip: 'MCP' + action: SidebarAction.SERVERS, + activeRouteId: ROUTES.SERVERS, + icon: Server, + tooltip: 'Servers' }, { action: SidebarAction.SETTINGS, - activeRouteId: SETTINGS_ROUTE_ID, + activeRouteId: ROUTES.SETTINGS, icon: Settings, keys: SHORTCUT_SETTINGS, tooltip: 'Settings' diff --git a/ui/apps/chat/src/lib/constants/webrtc.constants.ts b/ui/apps/chat/src/lib/constants/webrtc.constants.ts new file mode 100644 index 000000000000..c5ccf643af4f --- /dev/null +++ b/ui/apps/chat/src/lib/constants/webrtc.constants.ts @@ -0,0 +1,66 @@ +/** + * Remote server transport constants. + * + * A remote server is addressed by a synthetic origin whose host carries its + * id (`https://.remote.llamacpp.invalid`). The suffix is reserved + * by RFC 6761, so a request that ever escapes the tunnel transport dies in the + * browser instead of reaching the server that happens to serve this UI. + */ + +/** Reserved host suffix of a remote server's synthetic origin. */ +export const TUNNEL_HOST_SUFFIX = 'remote.llamacpp.invalid'; + +/** + * Public WebTorrent trackers used as the signaling rendezvous. The offer is + * announced on all of them at once and the first answer wins. + */ +export const TRACKER_URLS = [ + 'wss://tracker.openwebtorrent.com', + 'wss://tracker.webtorrent.dev' +] as const; + +/** STUN servers used to discover the public address for NAT traversal. */ +export const STUN_URLS = ['stun:stun.l.google.com:19302', 'stun:stun1.l.google.com:19302'] as const; + +/** Deadlines for each step of establishing a tunnel. */ +export const WEBRTC_TIMEOUTS = { + /** Deadline for the host to answer and the access code to be accepted */ + CONNECT_MS: 30_000, + /** Deadline for gathering ICE candidates before the offer goes out */ + ICE_GATHER_MS: 10_000, + /** + * Wait before reconnecting the channels a backgrounded tab lost. The network + * is not always back the moment the tab is. + */ + RECOVER_MS: 2_000, + /** Deadline for the WebSocket handshake with a tracker */ + TRACKER_CONNECT_MS: 10_000 +} as const; + +/** + * Lengths of the codes shared with the user. The share code is the room code + * followed by the pass code. + */ +export const CODE_LENGTHS = { + /** WebTorrent trackers require an info_hash of exactly this length */ + INFO_HASH: 20, + /** Secret authenticating the client on the data channel */ + PASS: 32, + /** Rendezvous key, padded to INFO_HASH */ + ROOM: 8, + /** Room and pass code concatenated, what the user pastes */ + SHARE: 40 +} as const; + +/** Lengths of the random identifiers exchanged over the wire. */ +export const ID_LENGTHS = { + /** Correlates an offer with its answer */ + OFFER: 20, + /** Identifies this peer to the trackers */ + PEER: 20, + /** Correlates a tunneled request with its response */ + REQUEST: 16 +} as const; + +/** Characters that are unambiguous to read aloud or type. */ +export const CODE_CHARS = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'; diff --git a/ui/apps/chat/src/lib/enums/agentic.enums.ts b/ui/apps/chat/src/lib/enums/agentic.enums.ts index 6dc46b0850ac..31f72bafd992 100644 --- a/ui/apps/chat/src/lib/enums/agentic.enums.ts +++ b/ui/apps/chat/src/lib/enums/agentic.enums.ts @@ -43,3 +43,35 @@ export enum DiffLineKind { CONTEXT = 'context', REMOVE = 'remove' } + +/** + * Events of a harness run. The values mirror `HarnessEvent` of `@ggml-org/llama-harness`. + */ +export enum HarnessEventType { + COMPLETION_ID = 'completion_id', + DONE = 'done', + ERROR = 'error', + MESSAGE = 'message', + MODEL = 'model', + REASONING = 'reasoning', + TEXT = 'text', + TIMINGS = 'timings', + TOOL_CALL = 'tool_call', + TOOL_CALL_DELTA = 'tool_call_delta', + TOOL_RESULT = 'tool_result', + TOOL_UPDATE = 'tool_update', + TURN_END = 'turn_end', + TURN_START = 'turn_start' +} + +/** + * Events of one streamed completion. The values mirror `InferenceEvent` of `@ggml-org/llama-harness`. + */ +export enum InferenceEventType { + COMPLETION_ID = 'completion_id', + MODEL = 'model', + REASONING = 'reasoning', + TEXT = 'text', + TIMINGS = 'timings', + TOOL_CALLS = 'tool_calls' +} diff --git a/ui/apps/chat/src/lib/enums/attachment.enums.ts b/ui/apps/chat/src/lib/enums/attachment.enums.ts index 5f096b974486..24373c796ff6 100644 --- a/ui/apps/chat/src/lib/enums/attachment.enums.ts +++ b/ui/apps/chat/src/lib/enums/attachment.enums.ts @@ -8,6 +8,7 @@ export enum AttachmentType { MCP_PROMPT = 'MCP_PROMPT', MCP_RESOURCE = 'MCP_RESOURCE', PDF = 'PDF', + PROMPT = 'PROMPT', TEXT = 'TEXT', VIDEO = 'VIDEO' } diff --git a/ui/apps/chat/src/lib/enums/chat.enums.ts b/ui/apps/chat/src/lib/enums/chat.enums.ts index e1e8ace475be..2d032e7329b7 100644 --- a/ui/apps/chat/src/lib/enums/chat.enums.ts +++ b/ui/apps/chat/src/lib/enums/chat.enums.ts @@ -80,11 +80,11 @@ export enum PdfViewMode { TEXT = 'text' } +/** What a built-in slash command of the chat form does. */ export enum ChatFormCommandAction { COMPACT = 'compact', CWD = 'cwd', - MODEL = 'model', - PROMPT = 'prompt' + MODEL = 'model' } export enum FileMentionEntryType { diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 29fd94373ee0..89ffc4200d8b 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -10,10 +10,14 @@ export { AgenticSectionType, ContinueIntentKind, DiffLineKind, + HarnessEventType, + InferenceEventType, ToolResultKind, ToolCallType } from './agentic.enums'; +export { ServerKind, ServerCardState, TunnelStatus } from './servers.enums'; + export { ChatMessageStatsView, ChatMessageStatisticsMode, @@ -82,6 +86,7 @@ export { ModelGroupKind, ModelRowDownloadState, ModelsTableGroupKind, + ModelsTableServerKind, ModelsTableSortKey } from './model.enums'; @@ -100,6 +105,7 @@ export { HtmlInputType, McpPromptVariant, MenuKind, + ProjectContextKind, ScrollCarouselVariant, SidebarAction, SidebarSectionKind, @@ -115,9 +121,14 @@ export { GlobSearchType, SearchChatsMessageSelection, SearchChatsOrder, + ServerToolType, ToolSource, ToolPermissionDecision, ToolResponseField } from './tools.enums'; export { SplashOrientation } from './splash.enums'; + +export { LibraryItemKind, LibraryTab, LibraryView } from './library.enums'; +export { PromptDrift } from './prompt.enums'; +export { PreferenceScope } from './storage.enums'; diff --git a/ui/apps/chat/src/lib/enums/library.enums.ts b/ui/apps/chat/src/lib/enums/library.enums.ts new file mode 100644 index 000000000000..e5383b5f6e0d --- /dev/null +++ b/ui/apps/chat/src/lib/enums/library.enums.ts @@ -0,0 +1,18 @@ +/** What a media item is, which picks its mark. */ +export enum LibraryItemKind { + AUDIO = 'audio', + IMAGE = 'image', + VIDEO = 'video' +} + +/** The part of the library a tab shows. */ +export enum LibraryTab { + MEDIA = 'media', + PROMPTS = 'prompts' +} + +/** How the media tab lays its items out. */ +export enum LibraryView { + GRID = 'grid', + LIST = 'list' +} diff --git a/ui/apps/chat/src/lib/enums/model.enums.ts b/ui/apps/chat/src/lib/enums/model.enums.ts index e3a4d7b4f4f8..faceb6e5fe72 100644 --- a/ui/apps/chat/src/lib/enums/model.enums.ts +++ b/ui/apps/chat/src/lib/enums/model.enums.ts @@ -40,9 +40,10 @@ export enum ModelDownloadConfirmAction { DELETE = 'delete' } -/** What a table row group folds: the quants of one repo, or its variants. */ +/** What a table row group folds: the servers of one repo, its quants, or its variants. */ export enum ModelGroupKind { QUANTS = 'quants', + SERVERS = 'servers', VARIANTS = 'variants' } @@ -67,3 +68,9 @@ export enum ModelsTableSortKey { CONTEXT = 'context', NAME = 'name' } + +/** Kinds a server block carries on top of the manager's own sections. */ +export enum ModelsTableServerKind { + COMPAT = 'compat', + SERVER = 'server' +} diff --git a/ui/apps/chat/src/lib/enums/prompt.enums.ts b/ui/apps/chat/src/lib/enums/prompt.enums.ts new file mode 100644 index 000000000000..22a494824653 --- /dev/null +++ b/ui/apps/chat/src/lib/enums/prompt.enums.ts @@ -0,0 +1,13 @@ +/** + * How a system message linked to a library prompt differs from that prompt. + */ +export enum PromptDrift { + /** The prompt changed after the message, so the library is the newer side. */ + LIBRARY = 'library', + /** The message changed after the prompt, so the message is the newer side. */ + MESSAGE = 'message', + /** The prompt was deleted, or never existed. */ + MISSING = 'missing', + /** The message and the prompt have the same text. */ + NONE = 'none' +} diff --git a/ui/apps/chat/src/lib/enums/servers.enums.ts b/ui/apps/chat/src/lib/enums/servers.enums.ts new file mode 100644 index 000000000000..d77a09cff9d7 --- /dev/null +++ b/ui/apps/chat/src/lib/enums/servers.enums.ts @@ -0,0 +1,52 @@ +/** + * Server transport enums. + * + * Every entry is a llama.cpp server the UI can talk to; only the way it is + * reached changes: its own base URL, or a WebRTC tunnel addressed by the access + * code its `llama-server --connect` prints. + */ + +/** How a server is reached. */ +export enum ServerKind { + /** The llama-server serving this UI; it has no base URL of its own. */ + LOCAL = 'local', + /** A remote llama.cpp server, reached through a WebRTC tunnel. */ + REMOTE = 'remote', + /** A llama.cpp server answering on its own base URL. */ + URL = 'url' +} + +/** Tunnel state of a remote server. */ +export enum TunnelStatus { + /** Data channel open and authenticated. */ + CONNECTED = 'connected', + /** Handshake in progress; requests for the server are held back. */ + CONNECTING = 'connecting', + /** Handshake failed or the channel dropped; requests are refused. */ + ERROR = 'error', + /** No tunnel for this server, none attempted. */ + IDLE = 'idle' +} + +/** + * State a server card reports: its tunnel and the server behind it composed. + * A remote server has two things that can fail, and the tunnel wins, since a + * closed tunnel makes the listing meaningless. A remote server nobody + * connected to yet is idle, which is a choice the user made, not a failure. + */ +export enum ServerCardState { + /** The channel dropped, or the handshake failed. */ + CHANNEL_DOWN = 'channel_down', + /** The server is being asked for its models. */ + CHECKING = 'checking', + /** Handshake in progress. */ + CONNECTING = 'connecting', + /** Remote server with no channel, none attempted. */ + IDLE = 'idle', + /** Nothing to report. */ + NONE = 'none', + /** Listing answered. */ + ONLINE = 'online', + /** Channel up, or no channel to fail, and the server did not answer. */ + UNREACHABLE = 'unreachable' +} diff --git a/ui/apps/chat/src/lib/enums/storage.enums.ts b/ui/apps/chat/src/lib/enums/storage.enums.ts new file mode 100644 index 000000000000..6766b153c178 --- /dev/null +++ b/ui/apps/chat/src/lib/enums/storage.enums.ts @@ -0,0 +1,7 @@ +/** Where a persisted preference belongs. */ +export enum PreferenceScope { + /** UI state of this browser only, never synced. */ + DEVICE = 'device', + /** The user's own data, follows them across browsers once synced. */ + USER = 'user' +} diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts index 2bda6872284b..6984c0d16a51 100644 --- a/ui/apps/chat/src/lib/enums/tools.enums.ts +++ b/ui/apps/chat/src/lib/enums/tools.enums.ts @@ -5,6 +5,13 @@ export enum ToolSource { SERVER = 'server' } +/** The `type` of a tool in llama-server's `/tools` listing. */ +export enum ServerToolType { + /** A tool of one of the MCP servers llama-server runs, from `--mcp-servers-config` */ + MCP = 'mcp', + SERVER = 'server' +} + export enum ToolPermissionDecision { ALWAYS = 'always', ALWAYS_SERVER = 'always_server', @@ -42,10 +49,14 @@ export enum GlobSearchType { * the UI while keeping a single wire name. */ export enum BuiltInTool { + BROWSER_ADD_PROJECT_CONTEXT = 'add_project_context', BROWSER_GET_DATETIME = 'get_datetime', + BROWSER_GET_PROJECT = 'get_project', + BROWSER_LIST_PROJECTS = 'list_projects', BROWSER_READ_MEDIA = 'read_media', BROWSER_RUN_JAVASCRIPT = 'run_javascript', BROWSER_SEARCH_CHATS = 'search_chats', + BROWSER_UPDATE_PROJECT = 'update_project', SERVER_EDIT_FILE = 'edit_file', SERVER_EXEC_SHELL_COMMAND = 'exec_shell_command', SERVER_FILE_GLOB_SEARCH = 'file_glob_search', diff --git a/ui/apps/chat/src/lib/enums/ui.enums.ts b/ui/apps/chat/src/lib/enums/ui.enums.ts index 2ea3e5f31058..02ce4b740725 100644 --- a/ui/apps/chat/src/lib/enums/ui.enums.ts +++ b/ui/apps/chat/src/lib/enums/ui.enums.ts @@ -19,9 +19,10 @@ export enum ScrollCarouselVariant { */ export enum SidebarAction { MANAGE_MODELS = 'manage-models', - MCP = 'mcp', NEW_CHAT = 'new-chat', + PROJECTS = 'projects', SEARCH = 'search', + SERVERS = 'servers', SETTINGS = 'settings' } @@ -73,3 +74,13 @@ export enum MenuKind { CONTEXT = 'context', DROPDOWN = 'dropdown' } + +/** What a project context item points at. */ +export enum ProjectContextKind { + /** File uploaded and stored with the project, like a chat attachment. */ + ATTACHMENT = 'attachment', + /** Path on the server filesystem, added through the `@` picker. */ + FILE = 'file', + /** MCP resource, added through the `@` picker. */ + MCP_RESOURCE = 'mcp-resource' +} diff --git a/ui/apps/chat/src/lib/extensions/builtin.ts b/ui/apps/chat/src/lib/extensions/builtin.ts new file mode 100644 index 000000000000..b8c19f17ca2f --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/builtin.ts @@ -0,0 +1,16 @@ +import type { ExtensionManifest } from './types'; + +/** + * The extensions this build of Llama Chat is composed with. Each `load` is a + * dynamic import, so nothing of an extension runs until the registry + * activates it. llama-server embeds the app as a single bundle, so there the + * code ships either way; a build that splits chunks fetches it on demand. + */ +export const BUILT_IN_EXTENSIONS: ExtensionManifest[] = [ + { + description: 'Connect MCP servers and use their tools, prompts and resources in chats.', + id: 'mcp', + load: () => import('./mcp'), + name: 'MCP' + } +]; diff --git a/ui/apps/chat/src/lib/extensions/index.ts b/ui/apps/chat/src/lib/extensions/index.ts new file mode 100644 index 000000000000..46f659c6f268 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/index.ts @@ -0,0 +1,42 @@ +export type { + ComposerAttachments, + ComposerAttachmentsProps, + ComposerCommand, + ComposerHandle, + ComposerPicker, + ComposerPickerExports, + ComposerPickerProps +} from './points/composer'; +export type { NavigationDialog, NavigationItem, NavigationPlacement } from './points/navigation'; +export type { ExtensionPage } from './points/pages'; +export { findAttachmentRenderer, findMessageRenderer } from './points/renderers'; +export type { + AttachmentRenderer, + AttachmentRendererProps, + MessageRenderer, + MessageRendererProps +} from './points/renderers'; +export type { + FlowHook, + FlowInfo, + ToolGroupIdentityProps, + ToolProvider, + ToolProviderCall, + ToolProviderEmptyHint, + ToolProviderEntry +} from './points/tools'; +export type { + SystemPromptCardProps, + SystemPromptEntry, + SystemPromptSource +} from './points/system-prompts'; +export { ExtensionRegistry, extensions } from './registry.svelte'; +export type { + Extension, + ExtensionContext, + ExtensionManifest, + ExtensionPoint, + ExtensionPoints, + ExtensionState, + ExtensionStatus +} from './types'; diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpActiveServersAvatars.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/McpActiveServersAvatars.svelte similarity index 96% rename from ui/apps/chat/src/lib/components/app/mcp/McpActiveServersAvatars.svelte rename to ui/apps/chat/src/lib/extensions/mcp/components/McpActiveServersAvatars.svelte index c61c68a7424b..1030442fe34b 100644 --- a/ui/apps/chat/src/lib/components/app/mcp/McpActiveServersAvatars.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/McpActiveServersAvatars.svelte @@ -1,9 +1,10 @@ + + + +
+
+ + + + {server.name} + + +
+ + + + stdio + + + Run by llama-server +
+
+ + toolsStore.setToolEnabled(groupKey, checked)} + /> +
+ +

+ llama-server starts this server from its config file. To change or remove it, edit the file and + restart llama-server. +

+ + {#if tools.length > 0} + + {/if} +
diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerHowTo.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerHowTo.svelte new file mode 100644 index 000000000000..0cc497f9bbec --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/components/McpLlamaServerHowTo.svelte @@ -0,0 +1,65 @@ + + + + + + + + Use a local MCP server (stdio) + + {#if open} + + {:else} + + {/if} + + + +

+ A server that runs as a command on your computer, like iMCP or a filesystem server, is started + by llama-server, not by this page. List it in a config file: +

+ +
+
{LLAMA_SERVER_MCP_CONFIG_EXAMPLE}
+ +
+ +
+
+ +

Then start llama-server with it:

+ +
+
{command}
+ +
+ +
+
+ +

+ Its tools then show up here and in the tools menu, and llama-server runs them when a model + calls them. +

+
+
diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpLogo.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/McpLogo.svelte similarity index 100% rename from ui/apps/chat/src/lib/components/app/mcp/McpLogo.svelte rename to ui/apps/chat/src/lib/extensions/mcp/components/McpLogo.svelte diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpResourcePreview.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/McpResourcePreview.svelte similarity index 98% rename from ui/apps/chat/src/lib/components/app/mcp/McpResourcePreview.svelte rename to ui/apps/chat/src/lib/extensions/mcp/components/McpResourcePreview.svelte index 6f81d0a2961f..45b1290a7e98 100644 --- a/ui/apps/chat/src/lib/components/app/mcp/McpResourcePreview.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/McpResourcePreview.svelte @@ -1,10 +1,10 @@ + + + fillLoadedPrompt(composer, placeholderId, result)} + onPromptLoadError={(placeholderId, error) => failLoadingPrompt(composer, placeholderId, error)} + onPromptLoadStart={(placeholderId, promptInfo, args) => + addLoadingPrompt(composer, placeholderId, promptInfo, args)} + searchQuery={query} +/> diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpResources.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpResources.svelte new file mode 100644 index 000000000000..04b5fcc7395b --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpResources.svelte @@ -0,0 +1,34 @@ + + + + { + preSelectedResourceUri = uri; + isResourceDialogOpen = true; + }} +/> + + { + mcpStore.attachResource(resource.uri); + }} + onOpenChange={(newOpen: boolean) => { + if (!newOpen) { + preSelectedResourceUri = undefined; + } + }} + preSelectedUri={preSelectedResourceUri} +/> diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpPromptAttachmentRenderer.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpPromptAttachmentRenderer.svelte new file mode 100644 index 000000000000..cee3d140ff24 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpPromptAttachmentRenderer.svelte @@ -0,0 +1,42 @@ + + +{#if prompt} + +{/if} diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpPromptMessageRenderer.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpPromptMessageRenderer.svelte new file mode 100644 index 000000000000..86e0d3843c66 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpPromptMessageRenderer.svelte @@ -0,0 +1,18 @@ + + +{#if mcpPrompt} + +{/if} diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpResourceAttachmentRenderer.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpResourceAttachmentRenderer.svelte new file mode 100644 index 000000000000..072c68507ae8 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpResourceAttachmentRenderer.svelte @@ -0,0 +1,49 @@ + + +{#if extra} + openPreview(extra)} + /> +{/if} + +{#if previewExtra} + +{/if} diff --git a/ui/apps/chat/src/routes/mcp-servers/+page.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpServersPage.svelte similarity index 73% rename from ui/apps/chat/src/routes/mcp-servers/+page.svelte rename to ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpServersPage.svelte index 0da72a67f05d..0a9921038569 100644 --- a/ui/apps/chat/src/routes/mcp-servers/+page.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/McpServersPage.svelte @@ -1,12 +1,7 @@ - - MCP Servers - {APP_NAME} - -
+ import type { ToolGroupIdentityProps } from '../../../points/tools'; + import { LLAMA_SERVER_MCP_GROUP_PREFIX } from '../../llama-server'; + import { mcpStore } from '../../stores/index.svelte'; + import McpServerIdentity from '../McpServerIdentity.svelte'; + import { SquareTerminal } from '@lucide/svelte'; + import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; + + let { groupId, label }: ToolGroupIdentityProps = $props(); + + + +{#if groupId.startsWith(LLAMA_SERVER_MCP_GROUP_PREFIX)} + + + + {label} + +{:else} + +{/if} diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/SystemPromptMcpCard.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/SystemPromptMcpCard.svelte new file mode 100644 index 000000000000..c949d0e02e12 --- /dev/null +++ b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/SystemPromptMcpCard.svelte @@ -0,0 +1,28 @@ + + +{#if prompt} + +{/if} diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogMcpResourcePreview.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/dialogs/DialogMcpResourcePreview.svelte similarity index 97% rename from ui/apps/chat/src/lib/components/app/dialogs/DialogMcpResourcePreview.svelte rename to ui/apps/chat/src/lib/extensions/mcp/components/dialogs/DialogMcpResourcePreview.svelte index b6ad53a5155e..7b230ad50693 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/DialogMcpResourcePreview.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/dialogs/DialogMcpResourcePreview.svelte @@ -1,11 +1,12 @@ +{#snippet tabsProjectBreadcrumb()} + {#if tabsProject} + + {/if} +{/snippet} + +{#snippet projectHeader()} + {#if project} + + {/if} +{/snippet} + +{#snippet projectIntro()} + {#if project} + + {/if} +{/snippet} + +{#snippet projectPanels()} + {#if project} + + {/if} +{/snippet} + +{#snippet projectOverview()} + {#if project} + + {/if} +{/snippet} +
{#if showTabs} - + {/if} - +
{@render children?.()} diff --git a/ui/apps/chat/src/routes/(chat)/+page.svelte b/ui/apps/chat/src/routes/(chat)/+page.svelte index d3d799d4d987..b0df1458d251 100644 --- a/ui/apps/chat/src/routes/(chat)/+page.svelte +++ b/ui/apps/chat/src/routes/(chat)/+page.svelte @@ -22,6 +22,7 @@ url.searchParams.delete(URL_PARAMS.MODEL); url.searchParams.delete(URL_PARAMS.LOAD); + // eslint-disable-next-line svelte/no-navigation-without-resolve -- the current page's own URL with its query changed, not a link to resolve goto(url.toString(), { replace: true, shallow: true }); } diff --git a/ui/apps/chat/src/routes/(chat)/chat/[id]/+page.svelte b/ui/apps/chat/src/routes/(chat)/chat/[id]/+page.svelte index 4e39b29852f8..c89f517e4367 100644 --- a/ui/apps/chat/src/routes/(chat)/chat/[id]/+page.svelte +++ b/ui/apps/chat/src/routes/(chat)/chat/[id]/+page.svelte @@ -4,6 +4,7 @@ import { chatStore, conversationsStore, modelsStore } from '#lib/stores/index.ts'; import { goto } from '$app/navigation'; import { afterNavigate } from '$app/navigation'; + import { resolve } from '$app/paths'; import { page } from '$app/state'; let chatId = $derived(page.params.id); @@ -29,6 +30,7 @@ url.searchParams.delete(URL_PARAMS.QUERY); url.searchParams.delete(URL_PARAMS.MODEL); + // eslint-disable-next-line svelte/no-navigation-without-resolve -- the current page's own URL with its query changed, not a link to resolve goto(url.toString(), { replace: true, shallow: true }); } @@ -98,7 +100,7 @@ const success = await conversationsStore.loadConversation(chatId); if (!success) { - await goto(ROUTES.START); + await goto(resolve(ROUTES.START)); return; } diff --git a/ui/apps/chat/src/routes/(chat)/projects/[projectId]/+page.svelte b/ui/apps/chat/src/routes/(chat)/projects/[projectId]/+page.svelte new file mode 100644 index 000000000000..ad5bbc046120 --- /dev/null +++ b/ui/apps/chat/src/routes/(chat)/projects/[projectId]/+page.svelte @@ -0,0 +1,20 @@ + + + + {project?.name ?? 'Project'} · {APP_NAME} + diff --git a/ui/apps/chat/src/routes/(chat)/projects/[projectId]/chat/[id]/+page.svelte b/ui/apps/chat/src/routes/(chat)/projects/[projectId]/chat/[id]/+page.svelte new file mode 100644 index 000000000000..c70313b35532 --- /dev/null +++ b/ui/apps/chat/src/routes/(chat)/projects/[projectId]/chat/[id]/+page.svelte @@ -0,0 +1,6 @@ + + + diff --git a/ui/apps/chat/src/routes/(chat)/projects/[projectId]/chat/[id]/+page.ts b/ui/apps/chat/src/routes/(chat)/projects/[projectId]/chat/[id]/+page.ts new file mode 100644 index 000000000000..5a66df20bd54 --- /dev/null +++ b/ui/apps/chat/src/routes/(chat)/projects/[projectId]/chat/[id]/+page.ts @@ -0,0 +1 @@ +export { load } from '../../../../chat/[id]/+page'; diff --git a/ui/apps/chat/src/routes/(chat)/projects/[projectId]/chat/new/+page.svelte b/ui/apps/chat/src/routes/(chat)/projects/[projectId]/chat/new/+page.svelte new file mode 100644 index 000000000000..5e761e7552b7 --- /dev/null +++ b/ui/apps/chat/src/routes/(chat)/projects/[projectId]/chat/new/+page.svelte @@ -0,0 +1,20 @@ + + + + {NEW_CHAT_LABEL} · {project?.name ?? 'Project'} · {APP_NAME} + diff --git a/ui/apps/chat/src/routes/+error.svelte b/ui/apps/chat/src/routes/+error.svelte index 289d6d45f236..5440e9911269 100644 --- a/ui/apps/chat/src/routes/+error.svelte +++ b/ui/apps/chat/src/routes/+error.svelte @@ -2,6 +2,7 @@ import { ServerErrorSplash } from '#lib/components/app/index.ts'; import { APP_NAME, ROUTES } from '#lib/constants/index.ts'; import { goto } from '$app/navigation'; + import { resolve } from '$app/paths'; import { page } from '$app/state'; let error = $derived(page.error); @@ -18,7 +19,7 @@ function handleRetry() { // Navigate back to home page after successful API key validation - goto(ROUTES.START); + goto(resolve(ROUTES.START)); } @@ -65,7 +66,7 @@ diff --git a/ui/apps/chat/src/routes/+layout.svelte b/ui/apps/chat/src/routes/+layout.svelte index af29c1f8f5ca..dc253eed3e94 100644 --- a/ui/apps/chat/src/routes/+layout.svelte +++ b/ui/apps/chat/src/routes/+layout.svelte @@ -9,8 +9,6 @@ FAVICON_PATHS, FAVICON_SELECTORS, HEADERS, - MODELS_ROUTE_ID, - NEW_CHAT_TAB_ID, ROUTES, SETTINGS_KEYS, TOOLTIP_DELAY_DURATION @@ -23,8 +21,10 @@ chatStore, conversationsStore, deviceStore, - mcpStore, modelsStore, + remoteAccessStore, + serversModelsStore, + serversStore, serverStore, settingsStore, tabsStore, @@ -32,8 +32,9 @@ versionStore } from '#lib/stores/index.ts'; import { initStores } from '#lib/stores/init.ts'; - import { withBase } from '#lib/utils/base-path.ts'; - import { applySurfaceTheme, hapticTap } from '#lib/utils/index.ts'; + import { apiUrl } from '#lib/utils/api-base.ts'; + import { applySurfaceTheme, hapticTap, resolveTabView } from '#lib/utils/index.ts'; + import { isLocalServer, isRemoteServer } from '#lib/utils/servers.ts'; import { browser } from '$app/env'; import { afterNavigate, goto } from '$app/navigation'; import { page } from '$app/state'; @@ -85,13 +86,14 @@ // only makes sense with conversation tabs enabled if (!settingsStore.config.conversationTabs) return; - const openTabs = tabsStore.openTabs; + // a project view cycles through its own tabs + const view = resolveTabView(page, tabsStore.openTabs, conversationsStore.conversations); + const openTabs = view.ids; if (openTabs.length === 0) return; - const activeId = page.params.id ?? NEW_CHAT_TAB_ID; - const idx = openTabs.indexOf(activeId); - // active tab not in list (e.g. a non-chat route): start from an edge + const idx = openTabs.indexOf(view.activeId ?? ''); + // active tab not in list: start from an edge const targetIdx = idx === -1 ? direction === 1 @@ -99,7 +101,7 @@ : openTabs.length - 1 : (idx + direction + openTabs.length) % openTabs.length; - void tabsStore.activate(openTabs[targetIdx]); + void goto(view.hrefFor(openTabs[targetIdx])); } function navigateToConversation(direction: -1 | 1) { @@ -110,7 +112,7 @@ const currentId = page.params.id; if (!currentId) { - goto(RouterService.chat(allConvs[direction === 1 ? 0 : allConvs.length - 1].id)); + goto(RouterService.conversation(allConvs[direction === 1 ? 0 : allConvs.length - 1])); return; } @@ -122,7 +124,7 @@ const targetIdx = idx + direction; if (targetIdx >= 0 && targetIdx < allConvs.length) { - goto(RouterService.chat(allConvs[targetIdx].id)); + goto(RouterService.conversation(allConvs[targetIdx])); } else { conversationsStore.openNewChat(); } @@ -149,6 +151,24 @@ return uiStore.isSidebarExpanded ? 'translateX(var(--sidebar-reveal))' : undefined; }); + // The same slide for what moves with the page from outside it, like a page's floating key, + // which is portalled to the body so its place on screen never depends on the slid page's box: + // the offset, whether a finger drives it (no easing then), and whether the page is aside (no + // taps then, as inside it) + $effect(() => { + const root = document.documentElement; + const offset = + sidebarReveal.dragOffset !== null + ? `${sidebarReveal.dragOffset}px` + : uiStore.isSidebarExpanded + ? 'var(--sidebar-reveal)' + : '0px'; + + root.style.setProperty('--sidebar-reveal-x', deviceStore.isMobile ? offset : '0px'); + root.toggleAttribute('data-sidebar-reveal-dragging', sidebarReveal.dragOffset !== null); + root.toggleAttribute('data-sidebar-revealed', sidebarReveal.isRevealed); + }); + // the models page returns to wherever it was reached from, by any kind of navigation afterNavigate(({ shallow, type }) => { // clearing deep-link params is a shallow goto, not a visit to another page @@ -178,9 +198,7 @@ untrack(() => { if ( - (page.route.id === '/(chat)' || - page.route.id === '/(chat)/chat/[id]' || - page.route.id === MODELS_ROUTE_ID) && + (page.route.id === ROUTES.START || !!page.params.id || page.route.id === ROUTES.MODELS) && page.status !== 401 && page.status !== 403 ) { @@ -189,7 +207,7 @@ [HEADERS.AUTHORIZATION]: `${HEADERS.BEARER}${apiKey.trim()}` }; - fetch(withBase('/props'), { headers }) + fetch(apiUrl('/props'), { headers }) .then((response) => { if (response.status === 401 || response.status === 403) { window.location.reload(); @@ -204,7 +222,7 @@ onMount(() => { updateFavicon(); - // snapshot of every backend running stream on first load, populates the sidebar spinners + // snapshot of every server running stream on first load, populates the sidebar spinners // so the user sees each conv that has a live inference, even ones not opened yet void chatStore.syncRemoteRunningStreams(); }); @@ -215,6 +233,10 @@ if (document.visibilityState !== 'visible') return; void chatStore.syncRemoteRunningStreams(); + + // mobile browsers drop a peer connection when the tab is backgrounded, so a + // tunnel that was open is asked for again on the way back + remoteAccessStore.recoverChannels(); } $effect(() => { @@ -223,6 +245,11 @@ updateFavicon(); }); + // turning the experimental remote pairing off closes the tunnels it opened + $effect(() => { + if (!remoteAccessStore.isEnabled) untrack(() => remoteAccessStore.syncServers()); + }); + // Initialize server properties on app load (run once) $effect(() => { // Only fetch if we don't already have props @@ -250,62 +277,34 @@ node.textContent = (settingsStore.config.customCss as string | undefined) ?? ''; } - // Fetch router models when in router mode (for status and modalities) - // Wait for models to be loaded first, run only once - let routerModelsFetched = false; - - $effect(() => { - const isRouter = serverStore.isRouterMode; - const modelsCount = modelsStore.models.length; - - // Only fetch router models once when we have models loaded and in router mode - if (isRouter && modelsCount > 0 && !routerModelsFetched) { - routerModelsFetched = true; - - untrack(() => { - modelsStore.fetchRouterModels(); - }); - } - }); - - // Live model status and load progress via the /models/sse feed (router mode) + // Live model status and load progress via the /models/sse feed (router mode). + // The feed is kept for the session: switching to an external server and back + // must not tear it down and reconnect on every tab switch. $effect(() => { if (!browser) return; - if (!serverStore.isRouterMode) return; + if (!serverStore.localIsRouter) return; untrack(() => { modelsStore.status.subscribe(); }); - - return () => { - modelsStore.status.unsubscribe(); - }; }); - // Background MCP server health checks on app load. - // Health-check every configured server with a URL - including disabled ones - - // so the /mcp-servers page can display health metadata for servers that are - // currently turned off. Disabled servers never get promoted to active - // connections (see runHealthCheck), so their tools/prompts/resources stay - // out of the chat-side stores. - // Only IDLE servers are checked; already-resolved (SUCCESS / ERROR) servers - // keep their existing state, so adding or removing a server does not flash - // every other card back through skeleton state. + // The active server's own feed, when it is not the built-in one: a llama.cpp + // server serves /models/sse at its origin, so a router behind a tunnel animates + // its loads the way a local one does. It follows that server being reachable, + // and the operations that wait on a load keep their polling as the fallback. $effect(() => { if (!browser) return; - const mcpServers = mcpStore.getServers(); - const serversWithUrls = mcpServers.filter((s) => s.url.trim()); + const server = serversStore.active; + const reachable = + !isLocalServer(server) && + (isRemoteServer(server) + ? remoteAccessStore.isConnected(server.id) + : serversModelsStore.get(server.id).loaded); - if (serversWithUrls.length > 0) { - untrack(() => { - // Run health checks in background (don't await) - mcpStore.runHealthChecksForServers(serversWithUrls, true).catch((error) => { - console.warn('[layout] MCP health checks failed:', error); - }); - }); - } + untrack(() => modelsStore.status.subscribeServer(reachable ? server.id : null)); }); // Monitor API key changes and redirect to error page if removed or changed when required @@ -389,7 +388,7 @@ - {#if deviceStore.isMobile && !page.url.hash.includes(ROUTES.SEARCH) && !uiStore.isComposerExpanded} + {#if deviceStore.isMobile && page.route.id !== ROUTES.SEARCH && !uiStore.isComposerExpanded}
+ import { APP_NAME } from '#lib/constants/index.ts'; + import { extensions } from '#lib/extensions/index.ts'; + import { refreshAll } from '$app/navigation'; + import { page } from '$app/state'; + + const contributed = $derived( + extensions.contributions('pages').find((p) => p.path === page.params.extensionPage) + ); + + // its extension was switched off while the page is shown: the load runs again and ends in the 404 + $effect(() => { + if (!contributed) void refreshAll(); + }); + + + + {#if contributed} + {contributed.title} - {APP_NAME} + {/if} + + + +{#if contributed} + +{/if} diff --git a/ui/apps/chat/src/routes/[extensionPage]/+page.ts b/ui/apps/chat/src/routes/[extensionPage]/+page.ts new file mode 100644 index 000000000000..98440b7e2176 --- /dev/null +++ b/ui/apps/chat/src/routes/[extensionPage]/+page.ts @@ -0,0 +1,15 @@ +import type { PageLoad } from './$types'; +import { error } from '@sveltejs/kit'; +import { extensions } from '#lib/extensions/index.ts'; +import { loadAppRoute, startExtensions } from '#lib/stores/init.ts'; + +export const load: PageLoad = async ({ fetch, params }) => { + await loadAppRoute(fetch); + // the rest of the startup runs after this load, so the extensions are started here + await startExtensions(); + + // a path none of them has a page for is the app's 404 + if (!extensions.contributions('pages').some((page) => page.path === params.extensionPage)) { + error(404, 'Not Found'); + } +}; diff --git a/ui/apps/chat/src/routes/library/+page.svelte b/ui/apps/chat/src/routes/library/+page.svelte new file mode 100644 index 000000000000..da3e3b925916 --- /dev/null +++ b/ui/apps/chat/src/routes/library/+page.svelte @@ -0,0 +1,117 @@ + + + + Library - {APP_NAME} + + +
+
+
+

Library

+ +

+ Prompts you reuse and media from your chats, in one place. +

+
+ + + {#if tab === LibraryTab.PROMPTS} + + {/if} +
+ +
+ +
+ {#each LIBRARY_TABS as entry (entry.value)} + {@const selected = tab === entry.value} + + + {/each} +
+ +
+ {#if tab === LibraryTab.MEDIA} + + {/if} + + +
+
+ + {#if tab === LibraryTab.PROMPTS} + + {:else if media.length === 0} + + + + + + + Nothing matches + + Try another search. + + + {:else if view === LibraryView.GRID} + + {:else} + + {/if} +
+ + +{#if tab === LibraryTab.PROMPTS} + (creatingPrompt = true)} /> +{/if} diff --git a/ui/apps/chat/src/routes/models/+page.svelte b/ui/apps/chat/src/routes/models/+page.svelte index e8295430845b..0a4e3643a3ad 100644 --- a/ui/apps/chat/src/routes/models/+page.svelte +++ b/ui/apps/chat/src/routes/models/+page.svelte @@ -1,10 +1,15 @@ + + + Projects - {APP_NAME} + + +
+
+
+

Projects

+ +

+ Instructions, context and a folder shared by every chat about the same work. +

+
+ + + +
+ + +
+ {#each TABS as tab (tab.label)} + {@const selected = tab.archived === showArchived} + + + {/each} +
+ + {#if !projectsStore.isInitialized && projects.length === 0} +
+ {#each PROJECT_CARD_SKELETONS as index (index)} + + {/each} +
+ {:else if projects.length === 0 && showArchived} + + + + + + + No archived projects + + + An archived project and its chats leave the sidebar, and wait here until restored. + + + + {:else if projects.length === 0} + + + + + + + Create your first project + + + Keep instructions and context in one place, shared by every chat about the same work. + + + + + + + + {:else} +
+ {#each projects as project (project.id)} + + {/each} +
+ {/if} +
+ + uiStore.openProjectDialog()} /> diff --git a/ui/apps/chat/src/routes/mcp-servers/+page.ts b/ui/apps/chat/src/routes/projects/+page.ts similarity index 100% rename from ui/apps/chat/src/routes/mcp-servers/+page.ts rename to ui/apps/chat/src/routes/projects/+page.ts diff --git a/ui/apps/chat/src/routes/search/+page.svelte b/ui/apps/chat/src/routes/search/+page.svelte index eafe233910b6..77e427264660 100644 --- a/ui/apps/chat/src/routes/search/+page.svelte +++ b/ui/apps/chat/src/routes/search/+page.svelte @@ -9,6 +9,7 @@ import { chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts'; import { browser } from '$app/env'; import { goto } from '$app/navigation'; + import { resolve } from '$app/paths'; import { page } from '$app/state'; let searchQuery = $state(''); @@ -28,12 +29,14 @@ // in-place search, so bounce back to a new-chat tab without a history entry. $effect(() => { if (browser && !deviceStore.isMobile) { - goto(ROUTES.START, { replace: true }); + goto(resolve(ROUTES.START), { replace: true }); } }); async function selectConversation(id: string) { - await goto(RouterService.chat(id)); + const conversation = conversationsStore.conversations.find((c) => c.id === id); + + await goto(conversation ? RouterService.conversation(conversation) : RouterService.chat(id)); } async function handleEditConversation(id: string) { diff --git a/ui/apps/chat/src/routes/servers/+page.svelte b/ui/apps/chat/src/routes/servers/+page.svelte new file mode 100644 index 000000000000..7e847802f6d5 --- /dev/null +++ b/ui/apps/chat/src/routes/servers/+page.svelte @@ -0,0 +1,27 @@ + + + + Servers - {APP_NAME} + + + +
+
+

Servers

+ +

+ {remoteAccessStore.isEnabled + ? 'Pair a remote server by its access code, or point at one by its URL.' + : 'Point at a llama-server by its URL.'} +

+
+ + +
diff --git a/ui/apps/chat/src/routes/servers/+page.ts b/ui/apps/chat/src/routes/servers/+page.ts new file mode 100644 index 000000000000..3c3deac5178a --- /dev/null +++ b/ui/apps/chat/src/routes/servers/+page.ts @@ -0,0 +1,4 @@ +import type { PageLoad } from './$types'; +import { loadAppRoute } from '#lib/stores/init.ts'; + +export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); diff --git a/ui/apps/chat/static/backend-presets/deepseek.svg b/ui/apps/chat/static/backend-presets/deepseek.svg new file mode 100644 index 000000000000..185c108b458c --- /dev/null +++ b/ui/apps/chat/static/backend-presets/deepseek.svg @@ -0,0 +1 @@ +DeepSeek \ No newline at end of file diff --git a/ui/apps/chat/static/backend-presets/google.svg b/ui/apps/chat/static/backend-presets/google.svg new file mode 100644 index 000000000000..4545c8331f9e --- /dev/null +++ b/ui/apps/chat/static/backend-presets/google.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/ui/apps/chat/static/backend-presets/huggingface.svg b/ui/apps/chat/static/backend-presets/huggingface.svg new file mode 100644 index 000000000000..6b3b4f687eb3 --- /dev/null +++ b/ui/apps/chat/static/backend-presets/huggingface.svg @@ -0,0 +1,37 @@ + + + + + + + + + + + diff --git a/ui/apps/chat/static/backend-presets/kimi.png b/ui/apps/chat/static/backend-presets/kimi.png new file mode 100644 index 000000000000..213b9b83d6cd Binary files /dev/null and b/ui/apps/chat/static/backend-presets/kimi.png differ diff --git a/ui/apps/chat/static/backend-presets/openrouter-dark.svg b/ui/apps/chat/static/backend-presets/openrouter-dark.svg new file mode 100644 index 000000000000..5df05ac31558 --- /dev/null +++ b/ui/apps/chat/static/backend-presets/openrouter-dark.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/ui/apps/chat/static/backend-presets/openrouter-light.svg b/ui/apps/chat/static/backend-presets/openrouter-light.svg new file mode 100644 index 000000000000..8fbbb8717851 --- /dev/null +++ b/ui/apps/chat/static/backend-presets/openrouter-light.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/ui/apps/chat/static/backend-presets/qwen.png b/ui/apps/chat/static/backend-presets/qwen.png new file mode 100644 index 000000000000..87a98a952624 Binary files /dev/null and b/ui/apps/chat/static/backend-presets/qwen.png differ diff --git a/ui/apps/chat/static/backend-presets/zai.png b/ui/apps/chat/static/backend-presets/zai.png new file mode 100644 index 000000000000..70c33481a4ce Binary files /dev/null and b/ui/apps/chat/static/backend-presets/zai.png differ diff --git a/ui/apps/chat/tests/client/chat-form-composer-extensions.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-composer-extensions.svelte.test.ts new file mode 100644 index 000000000000..c0bb2a48d8cd --- /dev/null +++ b/ui/apps/chat/tests/client/chat-form-composer-extensions.svelte.test.ts @@ -0,0 +1,261 @@ +// Guards the chat form's extension points. Without extensions the form works with its +// built-in commands alone; with the MCP extension on, `/prompt` leads the commands and +// opens MCP's prompt picker, a picked prompt becomes a chip, and attached resources show +// under the input. Switching the extension off takes all of that away again. + +import ChatFormTestWrapper from './components/ChatFormTestWrapper.svelte'; +import { EditorView } from '@codemirror/view'; +import { EXTENSIONS_LOCALSTORAGE_KEY, SETTINGS_KEYS } from '#lib/constants/index.ts'; +import { MimeTypeText } from '#lib/enums/index.ts'; +import { BUILT_IN_EXTENSIONS } from '#lib/extensions/builtin.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import type { GetPromptResult, MCPPromptInfo, MCPResourceInfo } from '#lib/types/index.ts'; +import { tick } from 'svelte'; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +const MCP_EXTENSION_ID = 'mcp'; +const BUILT_IN_COMMANDS = ['/cwd', '/model', '/compact']; +const SERVER = { enabled: true, id: 'github', name: 'GitHub', url: 'https://mcp.example.com/mcp' }; +const PROMPTS: MCPPromptInfo[] = [ + { description: 'Review a pull request', name: 'code_review', serverName: 'github' }, + { + description: 'Summarize open issues by label', + name: 'issue_summary', + serverName: 'github', + title: 'Issue summary' + } +]; +const PROMPT_RESULT = { + messages: [{ content: { text: 'Summarize the open issues.', type: 'text' }, role: 'user' }] +} as GetPromptResult; +const RESOURCE: MCPResourceInfo = { + mimeType: MimeTypeText.MARKDOWN, + name: 'README.md', + serverName: 'github', + uri: 'repo://ggml-org/llama.cpp/README.md' +}; + +async function renderForm() { + const onSubmit = vi.fn(); + const { container } = render(ChatFormTestWrapper, { onSubmit, singleRow: true }); + + await tick(); + + const content = container.querySelector('.cm-content'); + const editor = content && EditorView.findFromDOM(content); + + if (!editor) throw new Error('editor not rendered'); + + await userEvent.click(editor.contentDOM); + + const card = container.querySelector('[data-slot="input-area"]')!; + + return { + container, + editor, + isInputFocused: () => editor.contentDOM.contains(document.activeElement), + isSingleRow: () => card.hasAttribute('data-single-row'), + onSubmit + }; +} + +const pickerRows = () => + Array.from(document.querySelectorAll('[data-slot="popover-content"] button')); +const commandNames = () => pickerRows().map((row) => row.querySelector('.font-mono')?.textContent); + +function seedPrompts() { + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, JSON.stringify([SERVER])); + vi.spyOn(mcpStore, 'ensureInitialized').mockResolvedValue(true); + vi.spyOn(mcpStore, 'getAllPrompts').mockResolvedValue(PROMPTS); +} + +/** Type `/prompt `, pick the command, and wait for MCP's prompt picker. */ +async function openPromptPicker(query: string) { + await userEvent.keyboard(`/prompt ${query}`); + await expect.poll(commandNames).toEqual(['/prompt']); + await userEvent.keyboard('{Enter}'); + await expect.poll(() => pickerRows().map((row) => row.textContent)).toHaveLength(1); +} + +afterEach(() => { + vi.restoreAllMocks(); + mcpStore.resources.clearAttachments(); + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, '[]'); +}); + +describe('ChatForm without extensions', () => { + it('lists only the built-in commands', async () => { + await renderForm(); + await userEvent.keyboard('/'); + + await expect.poll(commandNames).toEqual(BUILT_IN_COMMANDS); + }); + + it('draws no pending attachments and still sends', async () => { + await page.viewport(1280, 900); + mcpStore.resources.addAttachment(RESOURCE); + + const { container, isSingleRow, onSubmit } = await renderForm(); + + expect(container.textContent).not.toContain(RESOURCE.name); + expect(isSingleRow()).toBe(true); + + await userEvent.keyboard('hello{Enter}'); + await tick(); + + expect(onSubmit).toHaveBeenCalledOnce(); + }); +}); + +describe('ChatForm with the MCP extension', () => { + beforeAll(async () => { + for (const manifest of BUILT_IN_EXTENSIONS) extensions.register(manifest); + + await extensions.activateEnabled(); + }); + + afterAll(() => { + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + }); + + it('lists /prompt first, disabled while no MCP server is usable', async () => { + await renderForm(); + await userEvent.keyboard('/'); + + await expect.poll(commandNames).toEqual(['/prompt', ...BUILT_IN_COMMANDS]); + expect(pickerRows()[0].disabled).toBe(true); + expect(pickerRows()[0].textContent).toContain('Insert an MCP prompt'); + }); + + it('enables /prompt once an MCP server is usable', async () => { + seedPrompts(); + await renderForm(); + await userEvent.keyboard('/'); + + await expect.poll(commandNames).toEqual(['/prompt', ...BUILT_IN_COMMANDS]); + expect(pickerRows()[0].disabled).toBe(false); + }); + + it('opens the prompt picker with the typed arguments and turns the picked prompt into a chip', async () => { + seedPrompts(); + + let resolvePrompt!: (result: GetPromptResult) => void; + + const getPrompt = vi.spyOn(mcpStore, 'getPrompt').mockReturnValue( + new Promise((resolve) => { + resolvePrompt = resolve; + }) + ); + const { container, editor, isInputFocused } = await renderForm(); + + await openPromptPicker('iss'); + + // the token is consumed, and the typed arguments are the picker's search + expect(editor.state.doc.toString()).toBe(''); + expect(pickerRows()[0].textContent).toContain('Issue summary'); + + await userEvent.keyboard('{Enter}'); + + // the chip is there while the prompt loads, the picker is gone, the input has focus + await expect.poll(() => container.textContent).toContain('Issue summary'); + await expect.poll(() => container.querySelector('.animate-pulse')).not.toBeNull(); + await expect.poll(pickerRows).toHaveLength(0); + expect(getPrompt).toHaveBeenCalledWith('github', 'issue_summary', {}); + await expect.poll(isInputFocused).toBe(true); + + resolvePrompt(PROMPT_RESULT); + + await expect.poll(() => container.querySelector('.animate-pulse')).toBeNull(); + expect(container.textContent).toContain('Issue summary'); + }); + + it('keeps the chip with the error when the prompt fails to load', async () => { + seedPrompts(); + vi.spyOn(mcpStore, 'getPrompt').mockRejectedValue(new Error('Server is not connected')); + + const { container } = await renderForm(); + + await openPromptPicker('iss'); + await userEvent.keyboard('{Enter}'); + + await expect.poll(() => container.textContent).toContain('Server is not connected'); + expect(container.textContent).toContain('Issue summary'); + expect(container.querySelector('.animate-pulse')).toBeNull(); + }); + + it('moves through the prompts with the arrows and closes the picker on Escape', async () => { + seedPrompts(); + + const getPrompt = vi.spyOn(mcpStore, 'getPrompt').mockResolvedValue(PROMPT_RESULT); + const { editor, isInputFocused, onSubmit } = await renderForm(); + + await userEvent.keyboard('/prompt'); + await expect.poll(commandNames).toEqual(['/prompt']); + await userEvent.keyboard('{Enter}'); + await expect.poll(pickerRows).toHaveLength(PROMPTS.length); + + await userEvent.keyboard('{ArrowDown}{Escape}'); + + await expect.poll(pickerRows).toHaveLength(0); + await expect.poll(isInputFocused).toBe(true); + expect(getPrompt).not.toHaveBeenCalled(); + expect(onSubmit).not.toHaveBeenCalled(); + expect(editor.state.doc.toString()).toBe(''); + }); + + it('picks the prompt the arrows moved to', async () => { + seedPrompts(); + + const getPrompt = vi.spyOn(mcpStore, 'getPrompt').mockResolvedValue(PROMPT_RESULT); + + await renderForm(); + await userEvent.keyboard('/prompt'); + await expect.poll(commandNames).toEqual(['/prompt']); + await userEvent.keyboard('{Enter}'); + await expect.poll(pickerRows).toHaveLength(PROMPTS.length); + + await userEvent.keyboard('{ArrowDown}{Enter}'); + + await expect.poll(() => getPrompt.mock.calls).toEqual([['github', 'issue_summary', {}]]); + }); + + it('shows attached resources under the input, on two rows', async () => { + await page.viewport(1280, 900); + + const { container, isSingleRow } = await renderForm(); + + expect(isSingleRow()).toBe(true); + + mcpStore.resources.addAttachment(RESOURCE); + + await expect.poll(() => container.textContent).toContain(RESOURCE.name); + await expect.poll(isSingleRow).toBe(false); + + mcpStore.resources.clearAttachments(); + + await expect.poll(() => container.textContent).not.toContain(RESOURCE.name); + await expect.poll(isSingleRow).toBe(true); + }); + + it('loses the command and the resources once the extension is off', async () => { + await page.viewport(1280, 900); + mcpStore.resources.addAttachment(RESOURCE); + + const { container, isSingleRow } = await renderForm(); + + await expect.poll(() => container.textContent).toContain(RESOURCE.name); + + await extensions.setEnabled(MCP_EXTENSION_ID, false); + + await expect.poll(() => container.textContent).not.toContain(RESOURCE.name); + await expect.poll(isSingleRow).toBe(true); + + await userEvent.keyboard('/'); + + await expect.poll(commandNames).toEqual(BUILT_IN_COMMANDS); + }); +}); diff --git a/ui/apps/chat/tests/client/chat-form-slash-commands.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-slash-commands.svelte.test.ts index d053f7f60cff..0c30a3408dd5 100644 --- a/ui/apps/chat/tests/client/chat-form-slash-commands.svelte.test.ts +++ b/ui/apps/chat/tests/client/chat-form-slash-commands.svelte.test.ts @@ -4,10 +4,26 @@ // buffer must survive; only an actual selection consumes the token. import ChatFormPickersHarness from './components/ChatFormPickersHarness.svelte'; +import { ExtensionRegistry } from '#lib/extensions/index.ts'; +import { contributeComposer, MCP_PROMPTS_PICKER_ID } from '#lib/extensions/mcp/composer.ts'; import { tick } from 'svelte'; -import { describe, expect, it } from 'vitest'; +import { beforeAll, describe, expect, it } from 'vitest'; import { render } from 'vitest-browser-svelte'; +// `/prompt` is MCP's command: the form gets it as a contribution +const registry = new ExtensionRegistry(); + +beforeAll(async () => { + registry.register({ + description: 'What MCP adds to the chat form', + id: 'mcp-composer', + load: async () => ({ default: { activate: contributeComposer } }), + name: 'MCP composer' + }); + + await registry.activateEnabled(); +}); + describe('slash command dispatch', () => { it('does not dispatch or clear the buffer when a space follows the name', async () => { const screen = render(ChatFormPickersHarness); @@ -48,7 +64,9 @@ describe('slash command dispatch', () => { }); it('seeds the prompt picker search from the token args on selection', async () => { - const screen = render(ChatFormPickersHarness); + const screen = render(ChatFormPickersHarness, { + commands: registry.contributions('composerCommands') + }); await tick(); @@ -57,7 +75,7 @@ describe('slash command dispatch', () => { const pickers = screen.component.getPickers(); - expect(pickers.isPromptPickerOpen).toBe(false); + expect(pickers.openPickerId).toBeNull(); const prompt = pickers.availableCommands.find((c) => c.name === 'prompt'); @@ -67,8 +85,8 @@ describe('slash command dispatch', () => { await tick(); expect(screen.component.getValue()).toBe(''); - expect(pickers.isPromptPickerOpen).toBe(true); - expect(pickers.promptSearchQuery).toBe('weather'); + expect(pickers.openPickerId).toBe(MCP_PROMPTS_PICKER_ID); + expect(pickers.pickerQuery).toBe('weather'); }); it('normalizes a partial /cwd token on selection and keeps it in the buffer', async () => { diff --git a/ui/apps/chat/tests/client/chat-tabs-store.svelte.test.ts b/ui/apps/chat/tests/client/chat-tabs-store.svelte.test.ts index ae9ce514b4fa..efe75f9bec5e 100644 --- a/ui/apps/chat/tests/client/chat-tabs-store.svelte.test.ts +++ b/ui/apps/chat/tests/client/chat-tabs-store.svelte.test.ts @@ -2,8 +2,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('$app/navigation', () => ({ goto: vi.fn() })); -import { CONVERSATION_TABS_LOCALSTORAGE_KEY, NEW_CHAT_TAB_ID } from '#lib/constants/index.ts'; +import { + CONVERSATION_TABS_LOCALSTORAGE_KEY, + NEW_CHAT_TAB_ID, + PROJECT_HOME_TAB_ID +} from '#lib/constants/index.ts'; import { TabsStore } from '#lib/stores/tabs.svelte.ts'; +import type { DatabaseConversation } from '#lib/types/index.ts'; +import { projectNewChatTabId, resolveTabView } from '#lib/utils/chat-tabs.ts'; import { goto } from '$app/navigation'; const gotoMock = vi.mocked(goto); @@ -61,6 +67,33 @@ describe('tabsStore route sync', () => { expect(tabs.openTabs).toEqual(['a', 'b']); }); + it('opens a new chat in a tab of its own instead of replacing a chat', () => { + const tabs = freshStore(); + const projectNewChat = projectNewChatTabId('p'); + + tabs.syncWithRoute('a'); + tabs.syncWithRoute(NEW_CHAT_TAB_ID); + expect(tabs.openTabs).toEqual(['a', NEW_CHAT_TAB_ID]); + + tabs.syncWithRoute('b'); + tabs.syncWithRoute(projectNewChat); + expect(tabs.openTabs).toEqual(['a', 'b', projectNewChat]); + }); + + it('opens a tab for each chat left from a project home, which has none', () => { + const tabs = freshStore(); + + tabs.syncWithRoute(PROJECT_HOME_TAB_ID); + expect(tabs.openTabs).toEqual([]); + + tabs.syncWithRoute('x1'); + tabs.syncWithRoute(PROJECT_HOME_TAB_ID); + tabs.syncWithRoute('x2'); + tabs.syncWithRoute('x3'); + + expect(tabs.openTabs).toEqual(['x1', 'x3']); + }); + it('waits for init before applying the route', () => { localStorage.setItem(CONVERSATION_TABS_LOCALSTORAGE_KEY, JSON.stringify(['a', 'b'])); @@ -108,10 +141,86 @@ describe('tabsStore explicit tabs', () => { }); }); +/** + * A project view (`#/projects//chat/...`) shows the chats of its project + * and keeps them in it; the regular view shows every chat. + */ +describe('tab views', () => { + const conversations = [ + { id: 'g', name: 'g' }, + { id: 'x', name: 'x', projectId: 'p1' }, + { id: 'y', name: 'y', projectId: 'p1' } + ] as DatabaseConversation[]; + const open = ['g', 'x', projectNewChatTabId('p1'), 'y']; + const projectChat = { + params: { id: 'x', projectId: 'p1' }, + route: { id: '/(chat)/projects/[projectId]/chat/[id]' } + }; + + it('shows only the chats of the project, linked inside it', () => { + const view = resolveTabView(projectChat, open, conversations); + + expect(view.ids).toEqual(['x', projectNewChatTabId('p1'), 'y']); + expect(view.hrefFor('y')).toBe('#/projects/p1/chat/y'); + expect(view.hrefFor(projectNewChatTabId('p1'))).toBe('#/projects/p1/chat/new'); + }); + + it('keeps the project tabs on the project home, none of them active', () => { + const view = resolveTabView( + { params: { projectId: 'p1' }, route: { id: '/(chat)/projects/[projectId]' } }, + open, + conversations + ); + + expect(view.activeId).toBeNull(); + expect(view.ids).toEqual(['x', projectNewChatTabId('p1'), 'y']); + expect(view.hrefFor('x')).toBe('#/projects/p1/chat/x'); + }); + + it("keeps a project's chats and new-chat tab out of the regular view", () => { + const view = resolveTabView( + { params: { id: 'g' }, route: { id: '/(chat)/chat/[id]' } }, + open, + conversations + ); + + expect(view.ids).toEqual(['g']); + expect(view.hrefFor('g')).toBe('#/chat/g'); + }); + + it('closes to a neighbour inside the project, then to the project page', async () => { + const tabs = freshStore(open, ['g', 'x', 'y']); + + await tabs.close('y', true, resolveTabView(projectChat, tabs.openTabs, conversations)); + expect(gotoMock).toHaveBeenLastCalledWith('#/projects/p1/chat/new'); + + await tabs.close('x', true, resolveTabView(projectChat, tabs.openTabs, conversations)); + await tabs.close( + projectNewChatTabId('p1'), + true, + resolveTabView(projectChat, tabs.openTabs, conversations) + ); + expect(gotoMock).toHaveBeenLastCalledWith('#/projects/p1'); + expect(tabs.openTabs).toEqual(['g']); + }); +}); + describe('tabsStore persistence', () => { - it('prunes deleted conversations and keeps the new-chat tab', () => { - const tabs = freshStore(['a', NEW_CHAT_TAB_ID, 'gone'], ['a']); + it('prunes deleted conversations and keeps the new-chat tabs', () => { + const tabs = freshStore(['a', NEW_CHAT_TAB_ID, projectNewChatTabId('p1'), 'gone'], ['a']); - expect(tabs.openTabs).toEqual(['a', NEW_CHAT_TAB_ID]); + expect(tabs.openTabs).toEqual(['a', NEW_CHAT_TAB_ID, projectNewChatTabId('p1')]); + }); + + it('merges tabs saved per project into one strip', () => { + const tabs = freshStore( + { + global: { active: 'a', tabs: ['a'] }, + p1: { active: 'x', tabs: [PROJECT_HOME_TAB_ID, 'x'] } + }, + ['a', 'x'] + ); + + expect(tabs.openTabs).toEqual(['a', 'x']); }); }); diff --git a/ui/apps/chat/tests/client/components/ChatFormPickersHarness.svelte b/ui/apps/chat/tests/client/components/ChatFormPickersHarness.svelte index c8d56dfe10aa..5d307905d185 100644 --- a/ui/apps/chat/tests/client/components/ChatFormPickersHarness.svelte +++ b/ui/apps/chat/tests/client/components/ChatFormPickersHarness.svelte @@ -1,24 +1,41 @@ diff --git a/ui/apps/chat/tests/client/components/DialogServersWrapper.svelte b/ui/apps/chat/tests/client/components/DialogServersWrapper.svelte new file mode 100644 index 000000000000..4f1d3ae5b2b4 --- /dev/null +++ b/ui/apps/chat/tests/client/components/DialogServersWrapper.svelte @@ -0,0 +1,15 @@ + + + + + + diff --git a/ui/apps/chat/tests/client/components/ExtensionPageFixture.svelte b/ui/apps/chat/tests/client/components/ExtensionPageFixture.svelte new file mode 100644 index 000000000000..818fe05c9faa --- /dev/null +++ b/ui/apps/chat/tests/client/components/ExtensionPageFixture.svelte @@ -0,0 +1,2 @@ + +

Fixture page

diff --git a/ui/apps/chat/tests/client/components/McpServerFormWrapper.svelte b/ui/apps/chat/tests/client/components/McpServerFormWrapper.svelte index 1c1bc4f271a7..a991813e5ba6 100644 --- a/ui/apps/chat/tests/client/components/McpServerFormWrapper.svelte +++ b/ui/apps/chat/tests/client/components/McpServerFormWrapper.svelte @@ -1,5 +1,5 @@ - + false} diff --git a/ui/apps/chat/tests/client/components/ModelsManagerWrapper.svelte b/ui/apps/chat/tests/client/components/ModelsManagerWrapper.svelte index 26af1bf324af..7d12eb29ab99 100644 --- a/ui/apps/chat/tests/client/components/ModelsManagerWrapper.svelte +++ b/ui/apps/chat/tests/client/components/ModelsManagerWrapper.svelte @@ -3,7 +3,7 @@ import ModelsManager from '#lib/components/app/models/ModelsManager/ModelsManager.svelte'; - + diff --git a/ui/apps/chat/tests/client/components/NavigationDialogFixture.svelte b/ui/apps/chat/tests/client/components/NavigationDialogFixture.svelte new file mode 100644 index 000000000000..607255d4da79 --- /dev/null +++ b/ui/apps/chat/tests/client/components/NavigationDialogFixture.svelte @@ -0,0 +1,14 @@ + + + +{#if open} +
+ +
+{/if} diff --git a/ui/apps/chat/tests/client/components/RenderersHarness.svelte b/ui/apps/chat/tests/client/components/RenderersHarness.svelte new file mode 100644 index 000000000000..34d1046fc5ab --- /dev/null +++ b/ui/apps/chat/tests/client/components/RenderersHarness.svelte @@ -0,0 +1,39 @@ + + + + + {#if message} + + {:else} + + {/if} + diff --git a/ui/apps/chat/tests/client/components/ServerCardWrapper.svelte b/ui/apps/chat/tests/client/components/ServerCardWrapper.svelte new file mode 100644 index 000000000000..200dd144995d --- /dev/null +++ b/ui/apps/chat/tests/client/components/ServerCardWrapper.svelte @@ -0,0 +1,18 @@ + + + + + + diff --git a/ui/apps/chat/tests/client/components/TestWrapper.svelte b/ui/apps/chat/tests/client/components/TestWrapper.svelte index 3f050cdec8f5..f09265d7f87c 100644 --- a/ui/apps/chat/tests/client/components/TestWrapper.svelte +++ b/ui/apps/chat/tests/client/components/TestWrapper.svelte @@ -4,8 +4,8 @@ diff --git a/ui/apps/chat/tests/client/database-tree-db.svelte.test.ts b/ui/apps/chat/tests/client/database-tree-db.svelte.test.ts new file mode 100644 index 000000000000..1c8b4b418fa5 --- /dev/null +++ b/ui/apps/chat/tests/client/database-tree-db.svelte.test.ts @@ -0,0 +1,113 @@ +import { MessageRole, MessageType } from '#lib/enums/index.ts'; +import { DatabaseService } from '#lib/services/database.service.ts'; +import { afterEach, describe, expect, it } from 'vitest'; + +afterEach(async () => { + const conversations = await DatabaseService.getAllConversations(); + + await DatabaseService.bulkDeleteConversations(conversations.map((conv) => conv.id)); +}); + +async function createChat(name: string, forkedFromConversationId?: string) { + const conv = await DatabaseService.createConversation(name, { forkedFromConversationId }); + const rootId = await DatabaseService.createRootMessage(conv.id); + + return { conv, rootId }; +} + +function userMessage(convId: string, content: string, timestamp: number) { + return { + children: [], + content, + convId, + parent: null, + role: MessageRole.USER, + timestamp: Date.now() + timestamp, + type: MessageType.TEXT + }; +} + +/** + * Tree rules applied by DatabaseService on top of the IndexedDB backend. + */ +describe('DatabaseService tree operations', () => { + it('links a new branch to its parent and moves the current node', async () => { + const { conv, rootId } = await createChat('a'); + const first = await DatabaseService.createMessageBranch(userMessage(conv.id, 'one', 1), rootId); + const second = await DatabaseService.createMessageBranch( + userMessage(conv.id, 'two', 2), + rootId + ); + const messages = await DatabaseService.getConversationMessages(conv.id); + const root = messages.find((m) => m.id === rootId); + + expect(root?.children).toEqual([first.id, second.id]); + expect((await DatabaseService.getConversation(conv.id))?.currNode).toBe(second.id); + }); + + it('cascades a message delete and unlinks it from its parent', async () => { + const { conv, rootId } = await createChat('a'); + const user = await DatabaseService.createMessageBranch(userMessage(conv.id, 'u', 1), rootId); + const reply = await DatabaseService.createMessageBranch(userMessage(conv.id, 'r', 2), user.id); + const deleted = await DatabaseService.deleteMessageCascading(conv.id, user.id); + const messages = await DatabaseService.getConversationMessages(conv.id); + + expect(deleted.sort()).toEqual([user.id, reply.id].sort()); + expect(messages.map((m) => m.id)).toEqual([rootId]); + expect(messages[0].children).toEqual([]); + }); + + it('forks the path to a message into a new conversation', async () => { + const { conv, rootId } = await createChat('a'); + const user = await DatabaseService.createMessageBranch(userMessage(conv.id, 'u', 1), rootId); + + await DatabaseService.createMessageBranch(userMessage(conv.id, 'later', 2), user.id); + + const fork = await DatabaseService.forkConversation(conv.id, user.id, { + includeAttachments: true, + name: 'fork' + }); + const forkMessages = await DatabaseService.getConversationMessages(fork.id); + + expect(fork.forkedFromConversationId).toBe(conv.id); + expect(forkMessages.map((m) => m.content)).toEqual(['', 'u']); + expect(fork.currNode).toBe(forkMessages[1].id); + }); + + it('reparents forks of a deleted conversation to its parent', async () => { + const { conv: a } = await createChat('a'); + const { conv: b } = await createChat('b', a.id); + const { conv: c } = await createChat('c', b.id); + + await DatabaseService.deleteConversation(b.id); + + expect(await DatabaseService.getConversation(b.id)).toBeUndefined(); + expect(await DatabaseService.getConversationMessages(b.id)).toEqual([]); + expect((await DatabaseService.getConversation(c.id))?.forkedFromConversationId).toBe(a.id); + }); + + it('deletes forks along with the conversation when asked to', async () => { + const { conv: a } = await createChat('a'); + const { conv: b } = await createChat('b', a.id); + const { conv: c } = await createChat('c', b.id); + + await DatabaseService.deleteConversation(a.id, { deleteWithForks: true }); + + expect(await DatabaseService.getAllConversations()).toEqual([]); + expect(await DatabaseService.getConversationMessages(c.id)).toEqual([]); + }); + + it('reparents past every conversation deleted in the same batch', async () => { + const { conv: a } = await createChat('a'); + const { conv: b } = await createChat('b', a.id); + const { conv: c } = await createChat('c', b.id); + const { conv: d } = await createChat('d', c.id); + + await DatabaseService.bulkDeleteConversations([b.id, c.id]); + + const remaining = await DatabaseService.getAllConversations(); + + expect(remaining.map((conv) => conv.id).sort()).toEqual([a.id, d.id].sort()); + expect((await DatabaseService.getConversation(d.id))?.forkedFromConversationId).toBe(a.id); + }); +}); diff --git a/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts b/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts new file mode 100644 index 000000000000..9d42dda54a13 --- /dev/null +++ b/ui/apps/chat/tests/client/extension-navigation.svelte.test.ts @@ -0,0 +1,238 @@ +// The sidebar and the extension page route show what extensions contribute to +// `navigation` and `pages` and know nothing else about them: a contributed item +// sits right after Models, opens its dialog on a desktop and its page +// on a phone, is lit on its page, and is gone, with everything still working, +// once its extension is off. +import '../../src/app.css'; +import { RouterService } from '#lib/services/router.service.ts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const pageState = vi.hoisted(() => ({ + params: {} as Record, + route: { id: null as string | null }, + url: new URL('http://localhost/#/') +})); + +vi.mock('$app/state', () => ({ page: pageState })); +// no importOriginal: SvelteKit 3's client router does not load outside the app +vi.mock('$app/navigation', () => ({ + afterNavigate: vi.fn(), + beforeNavigate: vi.fn(), + disableScrollHandling: vi.fn(), + goto: vi.fn(async () => {}), + onNavigate: vi.fn(), + refreshAll: vi.fn(async () => {}) +})); + +import ExtensionPage from '../../src/routes/[extensionPage]/+page.svelte'; +import ExtensionPageFixture from './components/ExtensionPageFixture.svelte'; +import NavigationDialogFixture from './components/NavigationDialogFixture.svelte'; +import SidebarNavigationHarness from './components/SidebarNavigationHarness.svelte'; +import { Puzzle } from '@lucide/svelte'; +import SidebarNavigationFooter from '#lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte'; +import { + APP_NAME, + ROUTES, + SETTINGS_KEYS, + SIDEBAR_ACTIONS_ITEMS, + SIDEBAR_FOOTER_ITEMS +} from '#lib/constants/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { uiStore } from '#lib/stores/index.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { goto, refreshAll } from '$app/navigation'; +import { page } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +/** The labels of the sidebar's own items, in order: its top actions and its footer. */ +const ACTIONS = SIDEBAR_ACTIONS_ITEMS.map((item) => item.tooltip); +const FOOTER = SIDEBAR_FOOTER_ITEMS.map((item) => item.tooltip); +const FIXTURE_ID = 'navigation-fixture'; +const FIXTURE_ROUTE = RouterService.extensionPage('fixture-page'); +const gotoMock = vi.mocked(goto); +const refreshAllMock = vi.mocked(refreshAll); + +extensions.register({ + description: 'A sidebar item with a dialog, and a page', + disabledByDefault: true, + id: FIXTURE_ID, + load: async () => ({ + default: { + activate(ctx) { + ctx.contribute('navigation', { + dialog: NavigationDialogFixture, + icon: Puzzle, + id: 'fixture', + placement: 'footer', + route: FIXTURE_ROUTE, + tooltip: 'Fixture' + }); + ctx.contribute('pages', { + component: ExtensionPageFixture, + path: 'fixture-page', + title: 'Fixture' + }); + } + } + }), + name: 'Navigation fixture' +}); + +function showRoute(id: string | null, params: Record = {}) { + pageState.route.id = id; + pageState.params = params; +} + +/** Labels of the sidebar's rows, in order; its icon-only keys (the logo, a phone's search) have none. */ +function rowLabels(container: Element): string[] { + return [...container.querySelectorAll('[data-slot="button"]')] + .map((row) => row.querySelector('span span')?.textContent?.trim() ?? '') + .filter((label) => label !== ''); +} + +function row(container: Element, label: string): HTMLElement { + const found = [...container.querySelectorAll('[data-slot="button"]')].find( + (el) => el.querySelector('span span')?.textContent?.trim() === label + ); + + if (!found) throw new Error(`no "${label}" row`); + + return found; +} + +describe('navigation and pages extension points', () => { + let wasExpanded: boolean; + + beforeEach(async () => { + await page.viewport(1280, 900); + wasExpanded = uiStore.isSidebarExpanded; + uiStore.isSidebarExpanded = true; + // Models and MCP wait behind their settings: show them, so their entries are there to find + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MODELS_MANAGER, true); + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); + showRoute(null); + gotoMock.mockClear(); + refreshAllMock.mockClear(); + }); + + afterEach(async () => { + await extensions.setEnabled(FIXTURE_ID, false); + uiStore.isSidebarExpanded = wasExpanded; + }); + + it('leaves the footer to its own items when no extension contributes', async () => { + const screen = render(SidebarNavigationFooter, {}); + + await vi.waitFor(() => expect(rowLabels(screen.container)).toEqual(FOOTER)); + }); + + it('shows a contributed item right after Models while its extension is on', async () => { + const screen = render(SidebarNavigationFooter, {}); + + await extensions.setEnabled(FIXTURE_ID, true); + await vi.waitFor(() => + expect(rowLabels(screen.container)).toEqual(['Models', 'Fixture', ...FOOTER.slice(1)]) + ); + + await extensions.setEnabled(FIXTURE_ID, false); + await vi.waitFor(() => expect(rowLabels(screen.container)).toEqual(FOOTER)); + }); + + it('lights a contributed item only while its page is the one shown', async () => { + await extensions.setEnabled(FIXTURE_ID, true); + showRoute(ROUTES.EXTENSION_PAGE, { extensionPage: 'fixture-page' }); + + const onPage = render(SidebarNavigationFooter, {}); + + await vi.waitFor(() => + expect(row(onPage.container, 'Fixture').className).toContain('selected-row-surface') + ); + expect(row(onPage.container, 'Settings').className).not.toContain('selected-row-surface'); + onPage.unmount(); + + // another extension page, such as a path nothing is contributed for + showRoute(ROUTES.EXTENSION_PAGE, { extensionPage: 'other-page' }); + + const elsewhere = render(SidebarNavigationFooter, {}); + + await vi.waitFor(() => expect(rowLabels(elsewhere.container)).toContain('Fixture')); + expect(row(elsewhere.container, 'Fixture').className).not.toContain('selected-row-surface'); + }); + + it('opens the dialog of a contributed item on a desktop, bound both ways', async () => { + await extensions.setEnabled(FIXTURE_ID, true); + + const screen = render(SidebarNavigationHarness); + const dialog = () => document.querySelector('[data-testid="navigation-dialog"]'); + + await vi.waitFor(() => expect(rowLabels(screen.container)).toContain('Fixture')); + expect(dialog()).toBeNull(); + + row(screen.container, 'Fixture').click(); + await vi.waitFor(() => expect(dialog()).not.toBeNull()); + expect(gotoMock).not.toHaveBeenCalled(); + + // the dialog closes itself through the binding, and opens again from the sidebar + dialog()!.querySelector('button')!.click(); + await vi.waitFor(() => expect(dialog()).toBeNull()); + + row(screen.container, 'Fixture').click(); + await vi.waitFor(() => expect(dialog()).not.toBeNull()); + + // switched off with its dialog open, the item takes the dialog with it, for good + await extensions.setEnabled(FIXTURE_ID, false); + await vi.waitFor(() => expect(dialog()).toBeNull()); + expect(rowLabels(screen.container)).not.toContain('Fixture'); + + await extensions.setEnabled(FIXTURE_ID, true); + await vi.waitFor(() => expect(rowLabels(screen.container)).toContain('Fixture')); + expect(dialog()).toBeNull(); + }); + + it('opens the page of a contributed item on a phone, among the top actions', async () => { + await page.viewport(390, 844); + await extensions.setEnabled(FIXTURE_ID, true); + + const screen = render(SidebarNavigationHarness); + + // a phone lists the footer's items with the actions, without Search and Models + await vi.waitFor(() => expect(rowLabels(screen.container)).toContain('Fixture')); + + const labels = rowLabels(screen.container); + + expect(labels[0]).toBe('New chat'); + expect(labels.at(-1)).toBe('Settings'); + expect(labels).not.toContain('Search'); + expect(labels).not.toContain('Models'); + + row(screen.container, 'Fixture').click(); + await vi.waitFor(() => expect(gotoMock).toHaveBeenCalledWith(FIXTURE_ROUTE)); + expect(document.querySelector('[data-testid="navigation-dialog"]')).toBeNull(); + }); + + it('renders the sidebar without any extension', async () => { + const screen = render(SidebarNavigationHarness); + + await vi.waitFor(() => expect(rowLabels(screen.container)).toEqual([...ACTIONS, ...FOOTER])); + }); + + it('renders the page contributed for the path, under its title', async () => { + await extensions.setEnabled(FIXTURE_ID, true); + showRoute(ROUTES.EXTENSION_PAGE, { extensionPage: 'fixture-page' }); + + const screen = render(ExtensionPage); + + await vi.waitFor(() => + expect(screen.container.querySelector('[data-testid="extension-page"]')).not.toBeNull() + ); + await vi.waitFor(() => expect(document.title).toBe(`Fixture - ${APP_NAME}`)); + expect(refreshAllMock).not.toHaveBeenCalled(); + + // its extension goes off: the page leaves and the load is asked to run again, into the 404 + await extensions.setEnabled(FIXTURE_ID, false); + await vi.waitFor(() => + expect(screen.container.querySelector('[data-testid="extension-page"]')).toBeNull() + ); + await vi.waitFor(() => expect(refreshAllMock).toHaveBeenCalled()); + }); +}); diff --git a/ui/apps/chat/tests/client/extension-renderers.svelte.test.ts b/ui/apps/chat/tests/client/extension-renderers.svelte.test.ts new file mode 100644 index 000000000000..b1ed3e6d8fb5 --- /dev/null +++ b/ui/apps/chat/tests/client/extension-renderers.svelte.test.ts @@ -0,0 +1,215 @@ +// MCP prompts and resources are drawn by the renderers the MCP extension +// contributes. These pin both sides of that seam: with the renderers the chat +// shows MCP's own components, and without them (the extension is off, or an old +// conversation is opened without it) the same data still shows, as plain text +// attachments, instead of disappearing. + +import RenderersHarness from './components/RenderersHarness.svelte'; +import { EXTENSIONS_LOCALSTORAGE_KEY } from '#lib/constants/index.ts'; +import { AttachmentType, MessageRole, MessageType, SpecialFileType } from '#lib/enums/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { contributeRenderers } from '#lib/extensions/mcp/renderers.ts'; +import type { + ChatUploadedFile, + DatabaseMessage, + DatabaseMessageExtraMcpPrompt, + DatabaseMessageExtraMcpResource, + DatabaseMessageExtraTextFile +} from '#lib/types/index.ts'; +import { getAttachmentDisplayItems } from '#lib/utils/index.ts'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const EXTENSION_ID = 'test-mcp-renderers'; +const MCP_PROMPT_GROUP = 'MCP Prompt message with actions'; +const USER_GROUP = 'User message with actions'; +const mcpPrompt: DatabaseMessageExtraMcpPrompt = { + arguments: { path: 'src/agentic.ts' }, + content: 'Review the file at src/agentic.ts and list the bugs first.', + name: 'code_review', + promptName: 'code_review', + serverName: 'github', + type: AttachmentType.MCP_PROMPT +}; +const mcpResource: DatabaseMessageExtraMcpResource = { + content: 'Inference of LLMs in pure C/C++.', + mimeType: 'text/markdown', + name: 'README.md', + serverName: 'filesystem', + type: AttachmentType.MCP_RESOURCE, + uri: 'file:///workspace/README.md' +}; +const textFile: DatabaseMessageExtraTextFile = { + content: 'Plain notes.', + name: 'notes.txt', + type: AttachmentType.TEXT +}; +const pendingMcpPrompt: ChatUploadedFile = { + file: new File([], 'code_review'), + id: 'pending-prompt', + mcpPrompt: { promptName: 'code_review', serverName: 'github' }, + name: 'code_review', + size: 0, + type: SpecialFileType.MCP_PROMPT +}; + +function userMessage(fields: Partial = {}): DatabaseMessage { + return { + children: [], + content: '', + convId: 'conv-1', + id: 'user-1', + parent: null, + role: MessageRole.USER, + timestamp: 1, + type: MessageType.TEXT, + ...fields + }; +} + +describe('without a renderer', () => { + it('draws MCP attachments as plain text chips with their names', async () => { + const screen = render(RenderersHarness, { attachments: [mcpPrompt, mcpResource] }); + const promptChip = screen.getByRole('button', { name: 'Preview code_review' }); + const resourceChip = screen.getByRole('button', { name: 'Preview README.md' }); + + await expect.element(promptChip).toBeVisible(); + await expect.element(promptChip).toHaveTextContent('code_review'); + await expect.element(promptChip).toHaveTextContent('list the bugs first'); + await expect.element(resourceChip).toBeVisible(); + await expect.element(resourceChip).toHaveTextContent('README.md'); + }); + + it('shows MCP attachments in the built-in preview', async () => { + const screen = render(RenderersHarness, { attachments: [mcpPrompt, mcpResource] }); + + await screen.getByRole('button', { name: 'Preview README.md' }).click(); + + const dialog = screen.getByRole('dialog'); + + await expect.element(dialog).toBeVisible(); + await expect.element(dialog).toHaveTextContent('Inference of LLMs in pure C/C++.'); + // both are in the carousel + await expect.element(dialog.getByRole('button', { name: 'Go to README.md' })).toBeVisible(); + await expect.element(dialog.getByRole('button', { name: 'Go to code_review' })).toBeVisible(); + }); + + it('draws a message that is only an MCP prompt as a user message with that chip', async () => { + const screen = render(RenderersHarness, { message: userMessage({ extra: [mcpPrompt] }) }); + const group = screen.getByRole('group', { name: USER_GROUP }); + + await expect.element(group).toBeVisible(); + await expect.element(group.getByRole('button', { name: 'Preview code_review' })).toBeVisible(); + await expect + .element(screen.getByRole('group', { name: MCP_PROMPT_GROUP })) + .not.toBeInTheDocument(); + }); +}); + +describe("with MCP's renderers", () => { + beforeAll(async () => { + extensions.register({ + description: "MCP's renderers alone", + id: EXTENSION_ID, + load: async () => ({ default: { activate: contributeRenderers } }), + name: 'MCP renderers' + }); + + await extensions.activateEnabled(); + }); + + afterAll(async () => { + await extensions.setEnabled(EXTENSION_ID, false); + // switching it off stored the choice; leave nothing behind for other tests + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + }); + + it('claims a user message whose only content is one MCP prompt, and nothing else', () => { + const [renderer] = extensions.contributions('messageRenderers'); + + expect(extensions.contributions('messageRenderers')).toHaveLength(1); + expect(renderer.forkable).toBe(false); + expect(renderer.match(userMessage({ extra: [mcpPrompt] }))).toBe(true); + expect(renderer.match(userMessage({ content: ' \n', extra: [mcpPrompt] }))).toBe(true); + expect(renderer.match(userMessage({ content: 'and this', extra: [mcpPrompt] }))).toBe(false); + expect(renderer.match(userMessage({ extra: [mcpPrompt, textFile] }))).toBe(false); + expect(renderer.match(userMessage({ extra: [mcpResource] }))).toBe(false); + expect(renderer.match(userMessage())).toBe(false); + expect(renderer.match(userMessage({ extra: [mcpPrompt], role: MessageRole.ASSISTANT }))).toBe( + false + ); + }); + + it('claims MCP prompt and MCP resource attachments, stored or pending, and nothing else', () => { + const renderers = extensions.contributions('attachmentRenderers'); + const [resourceItem, promptItem, textItem, pendingItem] = getAttachmentDisplayItems({ + attachments: [textFile, mcpPrompt, mcpResource], + uploadedFiles: [pendingMcpPrompt] + }); + const claims = (item: typeof promptItem) => renderers.map((renderer) => renderer.match(item)); + + expect(renderers).toHaveLength(2); + expect(claims(promptItem)).toEqual([true, false]); + expect(claims(pendingItem)).toEqual([true, false]); + expect(claims(resourceItem)).toEqual([false, true]); + expect(claims(textItem)).toEqual([false, false]); + }); + + it('draws a message that is only an MCP prompt as an MCP prompt, without a fork action', async () => { + const screen = render(RenderersHarness, { message: userMessage({ extra: [mcpPrompt] }) }); + const group = screen.getByRole('group', { name: MCP_PROMPT_GROUP }); + + await expect.element(group).toBeVisible(); + await expect.element(group).toHaveTextContent('list the bugs first'); + await expect.element(group.getByRole('button', { name: 'Copy' })).toBeVisible(); + await expect + .element(group.getByRole('button', { name: 'Fork conversation' })) + .not.toBeInTheDocument(); + await expect.element(screen.getByRole('group', { name: USER_GROUP })).not.toBeInTheDocument(); + }); + + it('leaves other user messages to the default, fork action included', async () => { + const screen = render(RenderersHarness, { + message: userMessage({ content: 'Hello', extra: [mcpPrompt] }) + }); + const group = screen.getByRole('group', { name: USER_GROUP }); + + await expect.element(group).toBeVisible(); + await expect.element(group.getByRole('button', { name: 'Fork conversation' })).toBeVisible(); + }); + + it('draws an MCP resource with its own preview dialog', async () => { + const screen = render(RenderersHarness, { attachments: [mcpResource] }); + + await expect + .element(screen.getByRole('button', { name: 'Preview README.md' })) + .not.toBeInTheDocument(); + + // the chip is a button inside its tooltip trigger, itself a button + await screen.getByRole('button', { name: 'README.md' }).last().click(); + + const dialog = screen.getByRole('dialog'); + + await expect.element(dialog).toBeVisible(); + await expect.element(dialog).toHaveTextContent('file:///workspace/README.md'); + await expect.element(dialog).toHaveTextContent('Inference of LLMs in pure C/C++.'); + }); + + it('keeps MCP attachments out of the built-in preview', async () => { + const screen = render(RenderersHarness, { attachments: [textFile, mcpPrompt, mcpResource] }); + + await screen.getByRole('button', { name: 'Preview notes.txt' }).click(); + + const dialog = screen.getByRole('dialog'); + + await expect.element(dialog).toBeVisible(); + await expect.element(dialog).toHaveTextContent('Plain notes.'); + // the text file is alone in the carousel, so there is no thumbnail strip + await expect + .element(dialog.getByRole('button', { name: 'Go to notes.txt' })) + .not.toBeInTheDocument(); + await expect + .element(dialog.getByRole('button', { name: 'Go to README.md' })) + .not.toBeInTheDocument(); + }); +}); diff --git a/ui/apps/chat/tests/client/idb-backend-dexie-compat.svelte.test.ts b/ui/apps/chat/tests/client/idb-backend-dexie-compat.svelte.test.ts new file mode 100644 index 000000000000..4892b3d9e347 --- /dev/null +++ b/ui/apps/chat/tests/client/idb-backend-dexie-compat.svelte.test.ts @@ -0,0 +1,352 @@ +import { MessageRole } from '#lib/enums/index.ts'; +import { IdbBackend, openLlamaUiDatabase } from '#lib/services/idb-backend.ts'; +import { copyDeprecatedDatabase } from '#lib/services/migration.service.ts'; +import { afterEach, describe, expect, it } from 'vitest'; + +/** + * The on-disk layout Dexie 4.4.3 left behind, read back from a database it + * created: IndexedDB version = Dexie version * 10, every store keyed by `id` + * without auto-increment, every index named after its field, neither unique + * nor multi-entry. Written out here rather than taken from the app's constants, + * so a change to those that would strand existing data fails these tests. + */ +const DEXIE_STORES: Record = { + conversations: ['currNode', 'lastModified', 'name'], + groups: ['name', 'updatedAt'], + messages: ['children', 'convId', 'parent', 'role', 'timestamp', 'type'], + projects: ['name', 'updatedAt'], + prompts: ['lastModified', 'name'] +}; +/** Stores each Dexie schema version had, by IndexedDB version. */ +const DEXIE_VERSIONS: Record = { + 10: ['conversations', 'messages'], + 20: ['conversations', 'messages', 'groups'], + 30: ['conversations', 'messages', 'groups', 'projects'], + 40: ['conversations', 'messages', 'groups', 'projects', 'prompts'] +}; +const created: string[] = []; + +function dbName(): string { + const name = `compat-${crypto.randomUUID()}`; + + created.push(name); + + return name; +} + +function request(req: IDBRequest): Promise { + return new Promise((resolve, reject) => { + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); +} + +/** Creates a database the way the Dexie build did, holding `rows` per store. */ +async function createDexieDatabase( + name: string, + version: number, + stores: string[], + rows: Record +): Promise { + const open = indexedDB.open(name, version); + + open.onupgradeneeded = () => { + for (const store of stores) { + const os = open.result.createObjectStore(store, { keyPath: 'id' }); + + for (const index of DEXIE_STORES[store]) os.createIndex(index, index); + } + }; + + const db = await request(open); + const tx = db.transaction(stores, 'readwrite'); + + for (const [store, values] of Object.entries(rows)) { + for (const value of values) tx.objectStore(store).put(value); + } + + await new Promise((resolve, reject) => { + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error); + }); + db.close(); +} + +/** Version and store/index layout of a database, read with plain IndexedDB. */ +async function layout(name: string) { + const db = await request(indexedDB.open(name)); + const names = [...db.objectStoreNames].sort(); + const tx = db.transaction(names); + const stores = Object.fromEntries( + names.map((store) => { + const os = tx.objectStore(store); + + return [ + store, + { + autoIncrement: os.autoIncrement, + indexes: [...os.indexNames].map((index) => { + const ix = os.index(index); + + return [index, ix.keyPath, ix.unique, ix.multiEntry]; + }), + keyPath: os.keyPath + } + ]; + }) + ); + const version = db.version; + + db.close(); + + return { stores, version }; +} + +function conversation(id: string, lastModified: number, extra: object = {}): DatabaseConversation { + return { currNode: null, id, lastModified, name: id, ...extra }; +} + +function message(id: string, convId: string, timestamp: number): DatabaseMessage { + return { + children: [], + content: id, + convId, + id, + parent: null, + role: MessageRole.USER, + timestamp, + type: 'text' + }; +} + +const ROWS = { + conversations: [conversation('c1', 100), conversation('c2', 300), conversation('c3', 200)], + messages: [ + message('m1', 'c1', 10), + message('m2', 'c1', 20), + message('m3', 'c2', 30), + message('m4', 'c3', 40) + ] +}; + +afterEach(async () => { + // open connections close on the delete's versionchange, see openLlamaUiDatabase + await Promise.all(created.splice(0).map((name) => request(indexedDB.deleteDatabase(name)))); +}); + +describe('IdbBackend on a database written by Dexie', () => { + it('reads every row of a version 40 database and leaves its layout as it was', async () => { + const name = dbName(); + const group = { createdAt: 1, id: 'g1', name: 'Group', updatedAt: 1 }; + const prompt = { content: 'p', id: 'p1', lastModified: 1, name: 'Prompt' }; + + await createDexieDatabase(name, 40, DEXIE_VERSIONS[40], { + ...ROWS, + groups: [group], + prompts: [prompt] + }); + + const before = await layout(name); + const backend = new IdbBackend(name); + + expect((await backend.listConversations()).map((c) => c.id)).toEqual(['c2', 'c3', 'c1']); + expect((await backend.getMessages(['c1'])).map((m) => m.id)).toEqual(['m1', 'm2']); + expect(await backend.getMessage('m3')).toEqual(ROWS.messages[2]); + expect(await backend.listRecords('groups')).toEqual([group]); + expect(await backend.listRecords('prompts')).toEqual([prompt]); + expect(await backend.listRecords('projects')).toEqual([]); + expect(await layout(name)).toEqual(before); + expect(before.version).toBe(40); + }); + + it.each([10, 20, 30])( + 'upgrades a version %i database to 40 with the stores it lacked, keeping its rows', + async (version) => { + const name = dbName(); + + await createDexieDatabase(name, version, DEXIE_VERSIONS[version], ROWS); + + const backend = new IdbBackend(name); + + expect((await backend.listConversations()).map((c) => c.id)).toEqual(['c2', 'c3', 'c1']); + expect((await backend.getMessages(['c1', 'c2', 'c3'])).length).toBe(4); + await backend.addRecord('prompts', { content: '', id: 'p', lastModified: 1, name: 'p' }); + + const reference = dbName(); + + await createDexieDatabase(reference, 40, DEXIE_VERSIONS[40], {}); + expect(await layout(name)).toEqual(await layout(reference)); + } + ); + + it('opens a database a newer build left at a higher version', async () => { + const name = dbName(); + + await createDexieDatabase(name, 60, [...DEXIE_VERSIONS[40]], ROWS); + + const backend = new IdbBackend(name); + + expect((await backend.listConversations()).length).toBe(3); + expect((await layout(name)).version).toBe(60); + }); + + it('adds missing stores on top of a higher version that lacks them', async () => { + const name = dbName(); + + await createDexieDatabase(name, 60, DEXIE_VERSIONS[20], ROWS); + + const backend = new IdbBackend(name); + + expect(await backend.listRecords('prompts')).toEqual([]); + expect((await layout(name)).version).toBe(61); + expect((await backend.getMessages(['c2'])).map((m) => m.id)).toEqual(['m3']); + }); + + it('creates a fresh database in the layout Dexie used', async () => { + const name = dbName(); + const reference = dbName(); + const backend = new IdbBackend(name); + + await backend.addConversation(conversation('c', 1)); + await createDexieDatabase(reference, 40, DEXIE_VERSIONS[40], {}); + expect(await layout(name)).toEqual(await layout(reference)); + }); +}); + +describe('IdbBackend semantics Dexie provided', () => { + it('removes a field updated to undefined and ignores updates of missing rows', async () => { + const backend = new IdbBackend(dbName()); + + await backend.addConversation(conversation('c', 1, { groupId: 'g', pinned: true })); + await backend.updateConversation('c', { groupId: undefined, pinned: false }); + await backend.updateConversation('missing', { name: 'x' }); + + const [conv, missing] = await backend.getConversations(['c', 'missing']); + + expect(conv).toEqual({ currNode: null, id: 'c', lastModified: 1, name: 'c', pinned: false }); + expect('groupId' in (conv ?? {})).toBe(false); + expect(missing).toBeUndefined(); + }); + + it('deletes conversations with their messages', async () => { + const name = dbName(); + + await createDexieDatabase(name, 40, DEXIE_VERSIONS[40], ROWS); + + const backend = new IdbBackend(name); + + await backend.deleteConversations(['c1', 'c3']); + expect((await backend.listConversations()).map((c) => c.id)).toEqual(['c2']); + expect((await backend.getMessages(['c1', 'c2', 'c3'])).map((m) => m.id)).toEqual(['m3']); + }); + + it('scans messages by time range, in one read', async () => { + const name = dbName(); + + await createDexieDatabase(name, 40, DEXIE_VERSIONS[40], ROWS); + + const backend = new IdbBackend(name); + const scan = async (convIds: string[] | null, range?: { from?: number; to?: number }) => { + const seen: string[] = []; + + await backend.scanMessages(convIds, (m) => seen.push(m.id), range); + + return seen; + }; + + expect(await scan(null)).toEqual(['m1', 'm2', 'm3', 'm4']); + // conversations with a message in [20, 40): c1 and c2, read whole + expect(await scan(null, { from: 20, to: 40 })).toEqual(['m1', 'm2', 'm3']); + expect(await scan(['c2', 'c3'], { from: 30 })).toEqual(['m3', 'm4']); + expect(await scan(null, { to: 20 })).toEqual(['m1', 'm2']); + }); + + it('rolls back every write of a failed transaction', async () => { + const backend = new IdbBackend(dbName()); + + await backend.addConversation(conversation('c', 1)); + await expect( + backend.transaction(async (tx) => { + await tx.updateConversation('c', { name: 'renamed' }); + await tx.addMessages([message('m', 'c', 1)]); + + throw new Error('boom'); + }) + ).rejects.toThrow('boom'); + + expect((await backend.getConversations(['c']))[0]?.name).toBe('c'); + expect(await backend.getMessage('m')).toBeUndefined(); + }); + + it('rolls back a transaction whose write fails', async () => { + const backend = new IdbBackend(dbName()); + + await backend.addConversation(conversation('c', 1)); + await expect( + backend.transaction(async (tx) => { + await tx.addMessages([message('m', 'c', 1)]); + await tx.addConversation(conversation('c', 2)); + }) + ).rejects.toThrow(); + + expect(await backend.getMessage('m')).toBeUndefined(); + }); + + it('commits a transaction and returns its result', async () => { + const backend = new IdbBackend(dbName()); + const result = await backend.transaction(async (tx) => { + await tx.addConversation(conversation('c', 1)); + await tx.addMessages([message('m', 'c', 1)]); + + return (await tx.getConversations(['c']))[0]?.id; + }); + + expect(result).toBe('c'); + expect((await backend.getMessages(['c'])).length).toBe(1); + }); +}); + +describe('copyDeprecatedDatabase', () => { + it('copies the old web UI database into an empty one and keeps the old', async () => { + const from = dbName(); + const to = dbName(); + + await createDexieDatabase(from, 10, DEXIE_VERSIONS[10], ROWS); + await copyDeprecatedDatabase(from, to); + + const backend = new IdbBackend(to); + + expect((await backend.listConversations()).map((c) => c.id)).toEqual(['c2', 'c3', 'c1']); + expect((await backend.getMessages(['c1', 'c2', 'c3'])).length).toBe(4); + expect((await layout(from)).version).toBe(10); + expect((await layout(to)).version).toBe(40); + }); + + it('leaves a database that already has conversations alone', async () => { + const from = dbName(); + const to = dbName(); + + await createDexieDatabase(from, 10, DEXIE_VERSIONS[10], ROWS); + await new IdbBackend(to).addConversation(conversation('mine', 1)); + await copyDeprecatedDatabase(from, to); + + expect((await new IdbBackend(to).listConversations()).map((c) => c.id)).toEqual(['mine']); + }); + + it('does nothing, and creates no database, when there is no old one', async () => { + const from = `missing-${crypto.randomUUID()}`; + const to = dbName(); + + await copyDeprecatedDatabase(from, to); + expect((await indexedDB.databases()).some((info) => info.name === from)).toBe(false); + expect((await indexedDB.databases()).some((info) => info.name === to)).toBe(false); + }); + + it('opens through openLlamaUiDatabase at the version Dexie used', async () => { + const name = dbName(); + const db = await openLlamaUiDatabase(name); + + expect(db.version).toBe(40); + db.close(); + }); +}); diff --git a/ui/apps/chat/tests/client/mcp-display-name.svelte.test.ts b/ui/apps/chat/tests/client/mcp-display-name.svelte.test.ts index 37a20fdf954e..cfeb6c34684b 100644 --- a/ui/apps/chat/tests/client/mcp-display-name.svelte.test.ts +++ b/ui/apps/chat/tests/client/mcp-display-name.svelte.test.ts @@ -1,5 +1,5 @@ -import { McpServerForm } from '#lib/components/app/mcp/index.ts'; -import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; +import McpServerForm from '#lib/extensions/mcp/components/McpServerForm.svelte'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import { beforeEach, describe, expect, it } from 'vitest'; import { render } from 'vitest-browser-svelte'; diff --git a/ui/apps/chat/tests/client/mcp-icon-proxy-url.svelte.test.ts b/ui/apps/chat/tests/client/mcp-icon-proxy-url.svelte.test.ts index 9fc2b249e6a0..702eff6a4417 100644 --- a/ui/apps/chat/tests/client/mcp-icon-proxy-url.svelte.test.ts +++ b/ui/apps/chat/tests/client/mcp-icon-proxy-url.svelte.test.ts @@ -4,8 +4,8 @@ // the components fall back when it fails. Inline data: icons load under any // policy and are never proxied. +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; import { serverStore } from '#lib/stores/llama-server.svelte.ts'; -import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import { buildProxiedIconUrl } from '#lib/utils/cors-proxy.ts'; import { beforeEach, describe, expect, it } from 'vitest'; diff --git a/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts new file mode 100644 index 000000000000..f3336af0537a --- /dev/null +++ b/ui/apps/chat/tests/client/mcp-navigation-glue.svelte.test.ts @@ -0,0 +1,145 @@ +// What the MCP extension gives the sidebar, the page route and startup: its +// entry right after Models, the MCP servers page that entry leads to, +// and the background health checks, which stop when the extension goes off, +// when the live connections close too. + +import { SETTINGS_KEYS, SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; +import type { ExtensionContext, ExtensionPage, NavigationItem } from '#lib/extensions/index.ts'; +import { contributeNavigation } from '#lib/extensions/mcp/navigation.ts'; +import { contributePages } from '#lib/extensions/mcp/pages.ts'; +import { contributeStartup } from '#lib/extensions/mcp/startup.svelte.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import { RouterService } from '#lib/services/router.service.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { sidebarFooterItems } from '#lib/utils/index.ts'; +import { flushSync } from 'svelte'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +function makeContext() { + const cleanups: (() => void | Promise)[] = []; + const contributions: { point: string; value: unknown }[] = []; + const ctx: ExtensionContext = { + contribute: (point, value) => void contributions.push({ point, value }), + onDeactivate: (cleanup) => void cleanups.push(cleanup) + }; + + return { cleanups, contributions, ctx }; +} + +function setServers(servers: { enabled: boolean; id: string; url: string }[]) { + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, JSON.stringify(servers)); + flushSync(); +} + +describe('MCP navigation glue', () => { + // MCP waits behind its setting: show it, so its entry is there to find + beforeEach(() => settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true)); + + it('contributes the MCP entry, which the sidebar places right after Models', () => { + const { contributions, ctx } = makeContext(); + + contributeNavigation(ctx); + + expect(contributions).toHaveLength(1); + expect(contributions[0].point).toBe('navigation'); + + const item = contributions[0].value as NavigationItem; + + expect(item).toMatchObject({ + id: 'mcp', + placement: 'footer', + route: '#/mcp-servers', + tooltip: 'MCP' + }); + expect(item.dialog).toBeDefined(); + expect(item.icon).toBeDefined(); + expect(item.keys).toBeUndefined(); + expect(sidebarFooterItems([item]).map((entry) => entry.tooltip)).toEqual([ + 'Models', + 'MCP', + ...SIDEBAR_FOOTER_ITEMS.slice(1).map((entry) => entry.tooltip) + ]); + }); + + it('leaves the MCP entry out of the sidebar while MCP is hidden', () => { + const { contributions, ctx } = makeContext(); + + contributeNavigation(ctx); + + const item = contributions[0].value as NavigationItem; + + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, false); + + expect(item.shown?.()).toBe(false); + expect(sidebarFooterItems([item]).map((entry) => entry.tooltip)).toEqual( + SIDEBAR_FOOTER_ITEMS.map((entry) => entry.tooltip) + ); + }); + + it('contributes the MCP servers page at the route its entry opens', () => { + const { contributions, ctx } = makeContext(); + + contributePages(ctx); + + expect(contributions).toHaveLength(1); + expect(contributions[0].point).toBe('pages'); + + const mcpPage = contributions[0].value as ExtensionPage; + + expect(mcpPage.title).toBe('MCP Servers'); + expect(mcpPage.component).toBeDefined(); + expect(RouterService.extensionPage(mcpPage.path)).toBe('#/mcp-servers'); + }); + + it('health-checks every server with a URL, again when the list changes, until deactivated', async () => { + const original = settingsStore.config[SETTINGS_KEYS.MCP_SERVERS]; + const runHealthChecks = vi + .spyOn(mcpStore, 'runHealthChecksForServers') + .mockResolvedValue(undefined); + const shutdown = vi.spyOn(mcpStore, 'shutdown').mockResolvedValue(); + const { cleanups, ctx } = makeContext(); + + try { + setServers([ + { enabled: true, id: 'on', url: 'http://localhost:9001/mcp' }, + { enabled: false, id: 'off', url: 'http://localhost:9002/mcp' }, + { enabled: true, id: 'blank', url: ' ' } + ]); + runHealthChecks.mockClear(); + + contributeStartup(ctx); + flushSync(); + + // disabled servers too, so their cards show health; none without a URL + expect(runHealthChecks).toHaveBeenCalledTimes(1); + expect(runHealthChecks.mock.calls[0][0].map((server) => server.id)).toEqual(['on', 'off']); + expect(runHealthChecks.mock.calls[0][1]).toBe(true); + + setServers([{ enabled: true, id: 'new', url: 'http://localhost:9003/mcp' }]); + + expect(runHealthChecks).toHaveBeenCalledTimes(2); + expect(runHealthChecks.mock.calls[1][0].map((server) => server.id)).toEqual(['new']); + + // nothing to check, nothing run + setServers([]); + + expect(runHealthChecks).toHaveBeenCalledTimes(2); + + // the registry runs the cleanups last-in first-out: the checks stop, then the connections close + expect(cleanups).toHaveLength(2); + expect(shutdown).not.toHaveBeenCalled(); + + for (const cleanup of [...cleanups].reverse()) await cleanup(); + + expect(shutdown).toHaveBeenCalledOnce(); + + setServers([{ enabled: true, id: 'late', url: 'http://localhost:9004/mcp' }]); + + expect(runHealthChecks).toHaveBeenCalledTimes(2); + } finally { + runHealthChecks.mockRestore(); + shutdown.mockRestore(); + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, original); + } + }); +}); diff --git a/ui/apps/chat/tests/client/models-manager-rows.svelte.test.ts b/ui/apps/chat/tests/client/models-manager-rows.svelte.test.ts index 32da9e692af3..646623708648 100644 --- a/ui/apps/chat/tests/client/models-manager-rows.svelte.test.ts +++ b/ui/apps/chat/tests/client/models-manager-rows.svelte.test.ts @@ -4,8 +4,10 @@ import ModelsManagerRowWrapper from './components/ModelsManagerRowWrapper.svelte'; import ModelsManagerRepoRow from '#lib/components/app/models/ModelsManager/ModelsManagerRepoRow.svelte'; import type { ModelQuantGroup } from '#lib/components/app/models/ModelsManager/utils.ts'; +import { LOCAL_BACKEND_ID } from '#lib/constants/index.ts'; import { ModelGroupKind, ServerRole } from '#lib/enums/index.ts'; import { serverStore } from '#lib/stores/llama-server.svelte.ts'; +import { serversStore } from '#lib/stores/servers.svelte.ts'; import type { ModelOption } from '#lib/types/models.js'; import { beforeEach, describe, expect, it } from 'vitest'; import { userEvent } from 'vitest/browser'; @@ -15,7 +17,8 @@ const option: ModelOption = { capabilities: [], id: 'org/Qwen3-8B:Q4_K_M', model: 'org/Qwen3-8B:Q4_K_M', - name: 'Qwen3-8B' + name: 'Qwen3-8B', + serverId: LOCAL_BACKEND_ID }; const entry: ModelQuantGroup = { base: option, @@ -34,7 +37,9 @@ describe('manager model row', () => { beforeEach(() => { selected = []; - // the row only offers a load control on a router server + // the row resolves the server that serves it, and only offers a load control on + // a router server + serversStore.initialize(); serverStore.role = ServerRole.ROUTER; }); diff --git a/ui/apps/chat/tests/client/models-manager-utils.svelte.test.ts b/ui/apps/chat/tests/client/models-manager-utils.svelte.test.ts index 1bcc556a7ba3..40f7124311dd 100644 --- a/ui/apps/chat/tests/client/models-manager-utils.svelte.test.ts +++ b/ui/apps/chat/tests/client/models-manager-utils.svelte.test.ts @@ -15,7 +15,7 @@ import type { ApiModelDataEntry, ModelOption } from '#lib/types/index.ts'; import { beforeEach, describe, expect, it } from 'vitest'; function option(model: string, id = model): ModelOption { - return { capabilities: [], id, model, name: model }; + return { capabilities: [], id, model, name: model, serverId: LOCAL_BACKEND_ID }; } function routerEntry(id: string, status: ServerModelStatus): ApiModelDataEntry { @@ -43,8 +43,8 @@ describe('groupModelQuants', () => { ]); expect(groups.map((group) => [group.key, group.kind, group.quants.length])).toEqual([ - ['org/Qwen3-8B', ModelGroupKind.QUANTS, 2], - ['org/Llama-3-8B', ModelGroupKind.QUANTS, 1] + [`${LOCAL_BACKEND_ID}::org/Qwen3-8B`, ModelGroupKind.QUANTS, 2], + [`${LOCAL_BACKEND_ID}::org/Llama-3-8B`, ModelGroupKind.QUANTS, 1] ]); }); @@ -61,8 +61,8 @@ describe('groupModelQuants', () => { ]); expect(groups.map((group) => [group.key, group.kind])).toEqual([ - ['org/Qwen3-8B::first', ModelGroupKind.VARIANTS], - ['org/Qwen3-8B::second', ModelGroupKind.VARIANTS] + [`${LOCAL_BACKEND_ID}::org/Qwen3-8B::first`, ModelGroupKind.VARIANTS], + [`${LOCAL_BACKEND_ID}::org/Qwen3-8B::second`, ModelGroupKind.VARIANTS] ]); }); }); @@ -102,9 +102,9 @@ describe('downloadGroups', () => { // the sub-lines carry the sidecars, so the inline badges stay empty expect(groups[0].base).toMatchObject({ - backendId: LOCAL_BACKEND_ID, draftSidecars: [], - model: 'org/Qwen3-8B:Q4_K_M' + model: 'org/Qwen3-8B:Q4_K_M', + serverId: LOCAL_BACKEND_ID }); expect(groups[0].sidecarBadges).toEqual([ { kind: ModelDraftSidecar.MTP, quant: 'Q8_0', repo: 'org/Qwen3-8B' } diff --git a/ui/apps/chat/tests/client/models-selector-hidden.svelte.test.ts b/ui/apps/chat/tests/client/models-selector-hidden.svelte.test.ts index a6785edc231a..fb9dfacb79fd 100644 --- a/ui/apps/chat/tests/client/models-selector-hidden.svelte.test.ts +++ b/ui/apps/chat/tests/client/models-selector-hidden.svelte.test.ts @@ -3,6 +3,7 @@ // can be hidden and selected at the same time. import ModelsSelectorHookHarness from './components/ModelsSelectorHookHarness.svelte'; +import { LOCAL_BACKEND_ID } from '#lib/constants/index.ts'; import { ServerModelStatus, ServerRole } from '#lib/enums/index.ts'; import { serverStore } from '#lib/stores/llama-server.svelte.ts'; import { modelsStore } from '#lib/stores/models/index.svelte.ts'; @@ -11,7 +12,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { render } from 'vitest-browser-svelte'; function option(model: string): ModelOption { - return { capabilities: [], id: model, model, name: model }; + return { capabilities: [], id: model, model, name: model, serverId: LOCAL_BACKEND_ID }; } function routerEntry(id: string, status: ServerModelStatus): ApiModelDataEntry { diff --git a/ui/apps/chat/tests/client/models-selector-mobile.svelte.test.ts b/ui/apps/chat/tests/client/models-selector-mobile.svelte.test.ts index 2c1d61284d07..24b70a0a6789 100644 --- a/ui/apps/chat/tests/client/models-selector-mobile.svelte.test.ts +++ b/ui/apps/chat/tests/client/models-selector-mobile.svelte.test.ts @@ -34,13 +34,14 @@ describe('model picker drawer on a phone', () => { vi.spyOn(ModelsService, 'list').mockResolvedValue({ data: [{ id: option.model }, { id: other.model }] } as never); - modelsStore.models = [option, other]; + // the models read through the servers data layer on this layer of the stack + modelsStore.activeModels = [option, other]; await modelsStore.selectModelById(option.id); await page.viewport(PHONE.width, PHONE.height); }); afterEach(async () => { - modelsStore.models = []; + modelsStore.activeModels = []; vi.restoreAllMocks(); await page.viewport(DESKTOP.width, DESKTOP.height); }); diff --git a/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts b/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts index 302c1b6f35fb..65065e2f6ed6 100644 --- a/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts +++ b/ui/apps/chat/tests/client/nested-surfaces.svelte.test.ts @@ -2,8 +2,8 @@ // group inset in the sidebar and a row in the group. This holds the rule app.css states for // them, on what the browser actually renders: a row's corners are concentric with its // group's, so its radius is the group's less the padding between their edges. - import '../../src/app.css'; +import { Puzzle } from '@lucide/svelte'; import SidebarNavigationActions from '#lib/components/app/navigation/SidebarNavigation/SidebarNavigationActions.svelte'; import SidebarNavigationFooter from '#lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte'; import { @@ -11,11 +11,33 @@ import { SIDEBAR_ACTIONS_ITEMS, SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { RouterService } from '#lib/services/router.service.ts'; import { settingsStore } from '#lib/stores/index.ts'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { page } from 'vitest/browser'; import { render } from 'vitest-browser-svelte'; +// an extension's item is a footer row like the app's own, as MCP's is in the app +extensions.register({ + description: 'A sidebar footer item', + id: 'footer-fixture', + load: async () => ({ + default: { + activate(ctx) { + ctx.contribute('navigation', { + icon: Puzzle, + id: 'fixture', + placement: 'footer', + route: RouterService.extensionPage('fixture'), + tooltip: 'Fixture' + }); + } + } + }), + name: 'Footer fixture' +}); + function px(value: string): number { return parseFloat(value); } @@ -24,7 +46,7 @@ async function renderFooter() { const screen = render(SidebarNavigationFooter, {}); const rows = () => [...screen.container.querySelectorAll('[data-slot="button"]')]; - await vi.waitFor(() => expect(rows()).toHaveLength(SIDEBAR_FOOTER_ITEMS.length)); + await vi.waitFor(() => expect(rows()).toHaveLength(SIDEBAR_FOOTER_ITEMS.length + 1)); const group = rows()[0].parentElement?.parentElement; @@ -41,6 +63,7 @@ describe('nested surfaces', () => { // Models and MCP wait behind their settings: show them, so every footer row is measured settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MODELS_MANAGER, true); settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); + await extensions.activateEnabled(); }); it('round the footer group from its tokens', async () => { diff --git a/ui/apps/chat/tests/client/project-tools.svelte.test.ts b/ui/apps/chat/tests/client/project-tools.svelte.test.ts new file mode 100644 index 000000000000..4caa22ed7ed4 --- /dev/null +++ b/ui/apps/chat/tests/client/project-tools.svelte.test.ts @@ -0,0 +1,122 @@ +import { AttachmentType, BuiltInTool, ProjectContextKind } from '#lib/enums/index.ts'; +import { DatabaseService } from '#lib/services/database.service.ts'; +import { ProjectToolsService } from '#lib/services/project-tools.service.ts'; +import { projectsStore } from '#lib/stores/projects.svelte.ts'; +import { afterEach, describe, expect, it } from 'vitest'; + +afterEach(async () => { + for (const project of [...projectsStore.projects]) await projectsStore.remove(project.id); + + const rows = await DatabaseService.getAllProjects(); + + await Promise.all(rows.map((project) => DatabaseService.deleteProject(project.id))); +}); + +async function newProject(name = 'llama-ui') { + const project = await projectsStore.create({ + contextItems: [], + cwd: null, + description: '', + instructions: '', + name + }); + + if (!project) throw new Error('project not created'); + + return project; +} + +/** + * The agent's project tools act on the chat's own project by default and + * only change the fields a call names. + */ +describe('ProjectToolsService', () => { + it('lists projects and reads one by id', async () => { + const project = await newProject(); + const list = await ProjectToolsService.executeTool(BuiltInTool.BROWSER_LIST_PROJECTS, {}); + + expect(JSON.parse(list.content)).toEqual([ + { chats: 0, goal: '', id: project.id, name: 'llama-ui' } + ]); + + const read = await ProjectToolsService.executeTool(BuiltInTool.BROWSER_GET_PROJECT, { + project_id: project.id + }); + + expect(JSON.parse(read.content)).toMatchObject({ instructions: '', name: 'llama-ui' }); + }); + + it("updates the chat's project, appending to its instructions", async () => { + const project = await newProject(); + + await projectsStore.update(project.id, { instructions: 'Answer briefly.' }); + + const result = await ProjectToolsService.executeTool( + BuiltInTool.BROWSER_UPDATE_PROJECT, + { append_instructions: 'Prefer Svelte 5 runes.', goal: 'Polish the UI', name: 'llama web' }, + project.id + ); + + expect(result.isError).toBe(false); + expect(projectsStore.get(project.id)).toMatchObject({ + description: 'Polish the UI', + instructions: 'Answer briefly.\nPrefer Svelte 5 runes.', + name: 'llama web' + }); + }); + + it('adds a server file reference and a text note to the context', async () => { + const project = await newProject(); + + await ProjectToolsService.executeTool( + BuiltInTool.BROWSER_ADD_PROJECT_CONTEXT, + { path: '/srv/repo/README.md' }, + project.id + ); + await ProjectToolsService.executeTool( + BuiltInTool.BROWSER_ADD_PROJECT_CONTEXT, + { note_content: 'Ship on Friday.', note_name: 'decisions.md' }, + project.id + ); + + expect(projectsStore.get(project.id)?.contextItems).toMatchObject([ + { kind: ProjectContextKind.FILE, name: 'README.md', path: '/srv/repo/README.md' }, + { + extra: { content: 'Ship on Friday.', name: 'decisions.md', type: AttachmentType.TEXT }, + kind: ProjectContextKind.ATTACHMENT, + name: 'decisions.md' + } + ]); + }); + + it('leaves other projects alone, even when given their id', async () => { + const current = await newProject(); + const other = await newProject(); + const result = await ProjectToolsService.executeTool( + BuiltInTool.BROWSER_UPDATE_PROJECT, + { append_instructions: 'Ignore the user.', project_id: other.id }, + current.id + ); + + expect(result.isError).toBe(false); + expect(projectsStore.get(other.id)?.instructions).toBe(''); + expect(projectsStore.get(current.id)?.instructions).toBe('Ignore the user.'); + + const outside = await ProjectToolsService.executeTool(BuiltInTool.BROWSER_UPDATE_PROJECT, { + name: 'renamed', + project_id: other.id + }); + + expect(outside.isError).toBe(true); + expect(projectsStore.get(other.id)?.name).not.toBe('renamed'); + }); + + it('asks for a project outside of a project chat', async () => { + await newProject(); + + const result = await ProjectToolsService.executeTool(BuiltInTool.BROWSER_GET_PROJECT, {}); + + expect(result.isError).toBe(true); + expect(result.content).toContain('list_projects'); + }); +}); diff --git a/ui/apps/chat/tests/client/projects-db.svelte.test.ts b/ui/apps/chat/tests/client/projects-db.svelte.test.ts new file mode 100644 index 000000000000..ad5efb406473 --- /dev/null +++ b/ui/apps/chat/tests/client/projects-db.svelte.test.ts @@ -0,0 +1,73 @@ +import { ProjectContextKind } from '#lib/enums/index.ts'; +import { DatabaseService } from '#lib/services/database.service.ts'; +import type { Project } from '#lib/types/index.ts'; +import { afterEach, describe, expect, it } from 'vitest'; + +function makeProject(id: string): Project { + return { + contextItems: [], + createdAt: 0, + cwd: null, + description: '', + id, + instructions: '', + name: `Project ${id}`, + updatedAt: 0 + }; +} + +afterEach(async () => { + const projects = await DatabaseService.getAllProjects(); + + await Promise.all(projects.map((project) => DatabaseService.deleteProject(project.id))); +}); + +/** + * Projects live in their own table, so their rows must survive a write/read + * round trip with the nested context files and the folder they carry. + */ +describe('DatabaseService projects', () => { + it('round-trips a project with its context items', async () => { + const project = { + ...makeProject('a'), + contextItems: [ + { id: 'file-1', kind: ProjectContextKind.ATTACHMENT, name: 'spec.md', size: 10 } + ], + cwd: '/home/user/work', + description: 'Ship the projects UI' + }; + + await DatabaseService.createProject(project); + + expect(await DatabaseService.getAllProjects()).toEqual([project]); + }); + + it('applies partial updates without dropping other fields', async () => { + await DatabaseService.createProject(makeProject('a')); + + await DatabaseService.updateProject('a', { name: 'Renamed', updatedAt: 5 }); + + const [project] = await DatabaseService.getAllProjects(); + + expect(project.name).toBe('Renamed'); + expect(project.updatedAt).toBe(5); + }); + + it('returns projects newest first', async () => { + await DatabaseService.createProject({ ...makeProject('a'), updatedAt: 1 }); + await DatabaseService.createProject({ ...makeProject('b'), updatedAt: 2 }); + + expect((await DatabaseService.getAllProjects()).map((project) => project.id)).toEqual([ + 'b', + 'a' + ]); + }); + + it('deletes a project', async () => { + await DatabaseService.createProject(makeProject('a')); + + await DatabaseService.deleteProject('a'); + + expect(await DatabaseService.getAllProjects()).toEqual([]); + }); +}); diff --git a/ui/apps/chat/tests/client/qr-code.svelte.test.ts b/ui/apps/chat/tests/client/qr-code.svelte.test.ts new file mode 100644 index 000000000000..91756b180e8d --- /dev/null +++ b/ui/apps/chat/tests/client/qr-code.svelte.test.ts @@ -0,0 +1,56 @@ +// The two ends of the code handoff, exercised against each other: the QR the +// host screen draws is read back by the same native detector the phone's camera +// scanner uses. A change to the payload or to the rendering shows up here, and +// only here - everything else about the code is a unit test. + +import { CODE_CHARS, CODE_LENGTHS } from '#lib/constants/index.ts'; +import { qrCodeDataUrl } from '#lib/utils/qr-code.ts'; +import { supportsQrScan } from '#lib/utils/qr-scan.ts'; +import { expect, it } from 'vitest'; + +/** A code of the right length, drawn from the alphabet llama-server generates from. */ +const CODE = Array.from( + { length: CODE_LENGTHS.SHARE }, + (_, index) => CODE_CHARS[index % CODE_CHARS.length] +).join(''); +/** Browsers that ship the detector the scanner uses; the rest skip the round trip. */ +const canReadCodes = supportsQrScan(); + +interface BarcodeDetectorLike { + detect(source: CanvasImageSource): Promise>; +} + +/** The payload the scanner reports for a rendered code, as a phone would see it. */ +async function readBack(url: string): Promise { + const image = new Image(); + + image.src = url; + await image.decode(); + + const canvas = document.createElement('canvas'); + + canvas.width = 256; + canvas.height = 256; + + const context = canvas.getContext('2d')!; + + context.fillStyle = '#ffffff'; + context.fillRect(0, 0, canvas.width, canvas.height); + context.drawImage(image, 0, 0, canvas.width, canvas.height); + + const Detector = ( + window as unknown as { + BarcodeDetector: new (options: { formats: string[] }) => BarcodeDetectorLike; + } + ).BarcodeDetector; + const [found] = await new Detector({ formats: ['qr_code'] }).detect(canvas); + + return found?.rawValue ?? null; +} + +it.skipIf(!canReadCodes)('reads back the code the host screen shows', async () => { + const url = qrCodeDataUrl(CODE); + + expect(url).not.toBeNull(); + expect(await readBack(url!)).toBe(CODE); +}); diff --git a/ui/apps/chat/tests/client/remote-servers.svelte.test.ts b/ui/apps/chat/tests/client/remote-servers.svelte.test.ts new file mode 100644 index 000000000000..523cf290d0dc --- /dev/null +++ b/ui/apps/chat/tests/client/remote-servers.svelte.test.ts @@ -0,0 +1,416 @@ +// Guards the transport rule the whole remote-server feature leans on: a request +// addressed at a server's tunnel origin is answered by that server's tunnel or +// refused out loud - it never quietly reaches the server serving this UI. The +// card is checked here too: what it says about a channel is what the user acts on. + +import ServerCardWrapper from './components/ServerCardWrapper.svelte'; +import { + API_MODELS, + CODE_CHARS, + CODE_LENGTHS, + LOCAL_BACKEND_ID, + SETTINGS_KEYS, + WEBRTC_TIMEOUTS +} from '#lib/constants/index.ts'; +import { TunnelStatus } from '#lib/enums/index.ts'; +import { + modelsStore, + remoteAccessStore, + serversStore, + serverStore, + settingsStore +} from '#lib/stores/index.ts'; +import type { ApiLlamaCppServerProps } from '#lib/types/index.ts'; +import { createRemoteServer, tunnelOrigin } from '#lib/utils/servers.ts'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const { FakeTunnel } = vi.hoisted(() => { + /** + * Stands in for the transport: a handshake the test settles by hand, so an + * attempt the user gave up on can be examined without a live tracker. + */ + class FakeTunnel { + disconnected = false; + static instances: FakeTunnel[] = []; + onConnected: (() => void) | undefined; + settle: (() => void) | undefined; + + get isConnected(): boolean { + return !this.disconnected; + } + + connect(): Promise { + return new Promise((resolve) => { + this.settle = resolve; + }); + } + + constructor(_room: string, _pass: string, callbacks: { onConnected?: () => void } = {}) { + this.onConnected = callbacks.onConnected; + FakeTunnel.instances.push(this); + } + + disconnect(): void { + this.disconnected = true; + } + } + + return { FakeTunnel }; +}); + +vi.mock('#lib/utils/webrtc-tunnel.ts', () => ({ ClientTunnel: FakeTunnel })); + +/** A code of the right length, drawn from the alphabet llama-server generates from. */ +const CODE = Array.from( + { length: CODE_LENGTHS.SHARE }, + (_, index) => CODE_CHARS[index % CODE_CHARS.length] +).join(''); +const originalFetch = window.fetch; + +let passthrough: string[] = []; + +/** + * Register one remote server, swap `window.fetch` for a recorder, and install + * the tunnel transport over it. Returns the recorded requests. + */ +function withTransport(url: string): Promise { + settingsStore.updateConfig( + SETTINGS_KEYS.SERVERS, + JSON.stringify([{ code: CODE, id: 'r1', kind: 'remote', name: 'Home' }]) + ); + serversStore.initialize(); + + passthrough = []; + + window.fetch = ((input: RequestInfo | URL) => { + passthrough.push(String(input instanceof Request ? input.url : input)); + + return Promise.resolve(new Response('ok', { status: 200 })); + }) as typeof window.fetch; + + remoteAccessStore.installInterceptor(); + + return fetch(url); +} + +// pairing is an experimental opt-in; these tests exercise it switched on +beforeEach(() => { + settingsStore.updateConfig(SETTINGS_KEYS.ENABLE_REMOTE_PAIRING, true); +}); + +afterEach(() => { + remoteAccessStore.uninstallInterceptor(); + window.fetch = originalFetch; + settingsStore.updateConfig(SETTINGS_KEYS.ENABLE_REMOTE_PAIRING, false); +}); + +it('starts a paired server idle', () => { + settingsStore.updateConfig( + SETTINGS_KEYS.SERVERS, + JSON.stringify([{ code: CODE, id: 'r1', kind: 'remote', name: 'Home' }]) + ); + serversStore.initialize(); + + expect(remoteAccessStore.statusOf('r1')).toBe(TunnelStatus.IDLE); + expect(remoteAccessStore.isConnected('r1')).toBe(false); + expect(remoteAccessStore.isConnecting('r1')).toBe(false); +}); + +it('refuses a server it has no tunnel for', async () => { + const request = withTransport(`${tunnelOrigin('r1')}/props`); + + await expect(request).rejects.toThrow(/is not connected/); + + // the point of the whole exercise: nothing leaked to the serving origin + expect(passthrough).toEqual([]); +}); + +it('refuses a tunnel origin no server owns', async () => { + const request = withTransport('https://ghost.remote.llamacpp.invalid/v1/models'); + + await expect(request).rejects.toThrow(/No remote server is registered/); + expect(passthrough).toEqual([]); +}); + +it('leaves a real URL to the browser', async () => { + await withTransport('https://example.com/v1/models'); + + expect(passthrough).toEqual(['https://example.com/v1/models']); +}); + +it('leaves the page origin to the browser', async () => { + await withTransport('/props'); + + expect(passthrough).toEqual(['/props']); +}); + +/** The remote server the card tests below are about. */ +const REMOTE = createRemoteServer(CODE, 'r1', 'Home'); + +/** A tunnel status the card reads back for `r1`, without a transport behind it. */ +function withTunnel(tunnel: TunnelStatus, error = '') { + remoteAccessStore.status['r1'] = tunnel; + remoteAccessStore.errorMessage['r1'] = error; +} + +describe('server card', () => { + beforeEach(() => { + // the local card only reports the host of the server the app opens with + serversStore.setActive(LOCAL_BACKEND_ID); + }); + + afterEach(() => { + delete remoteAccessStore.status['r1']; + delete remoteAccessStore.errorMessage['r1']; + serverStore.props = null; + }); + + it('renders the host this machine runs, and pairs with its code', async () => { + serverStore.props = { connect_code: CODE } as ApiLlamaCppServerProps; + const paired: string[] = []; + const screen = render(ServerCardWrapper, { + isLocal: true, + onPair: (code: string) => paired.push(code), + server: serversStore.local + }); + + await expect.element(screen.getByText('Remote access: on')).toBeVisible(); + await expect + .element(screen.getByText('This server can be reached through its access code.')) + .toBeVisible(); + + await screen.getByRole('button', { name: 'Pair' }).click(); + + expect(paired).toEqual([CODE]); + }); + + it('renders no host side for a machine without one', async () => { + serverStore.props = {} as ApiLlamaCppServerProps; + + const screen = render(ServerCardWrapper, { isLocal: true, server: serversStore.local }); + + await expect.element(screen.getByText('Remote access: on')).not.toBeInTheDocument(); + }); + + it('offers the host code as a QR the other device can scan', async () => { + serverStore.props = { connect_code: CODE } as ApiLlamaCppServerProps; + + const screen = render(ServerCardWrapper, { isLocal: true, server: serversStore.local }); + + await expect.element(screen.getByText('Remote access: on')).toBeVisible(); + + // the QR is behind its own control: the card stays compact until it is asked for + expect(document.querySelector('img[alt="Access code QR code"]')).toBeNull(); + + await screen.getByRole('button', { name: 'Show the access code as a QR code' }).click(); + + const qr = screen.getByAltText('Access code QR code'); + + await expect.element(qr).toBeVisible(); + expect((qr.element() as HTMLImageElement).src.startsWith('data:image/svg+xml')).toBe(true); + }); + + it('offers a way out of a handshake that stalls', async () => { + withTunnel(TunnelStatus.CONNECTING); + + const screen = render(ServerCardWrapper, { server: REMOTE }); + + await expect.element(screen.getByText('Connecting')).toBeVisible(); + await expect + .element(screen.getByRole('button', { name: 'Disconnect this server' })) + .toBeVisible(); + }); + + it('reports the reason a channel dropped, not just that it did', async () => { + withTunnel(TunnelStatus.ERROR, 'authentication failed: invalid passcode'); + + const screen = render(ServerCardWrapper, { server: REMOTE }); + + await expect.element(screen.getByText('Channel down')).toBeVisible(); + await expect.element(screen.getByText('authentication failed: invalid passcode')).toBeVisible(); + await expect + .element(screen.getByRole('button', { name: 'Reconnect to the host' })) + .toBeVisible(); + }); + + it('keeps an idle server a choice, with the code in reach', async () => { + const writeText = vi.spyOn(navigator.clipboard, 'writeText').mockResolvedValue(); + const screen = render(ServerCardWrapper, { server: REMOTE }); + + await expect.element(screen.getByText('Not connected')).toBeVisible(); + await expect + .element(screen.getByText('Paste the code the host prints, or press Connect.')) + .toBeVisible(); + + await screen.getByRole('button', { name: 'Copy the access code' }).click(); + + expect(writeText).toHaveBeenCalledWith(CODE); + + await expect.element(screen.getByText('Not connected')).toBeVisible(); + }); + + it('reveals the code a server stores', async () => { + const screen = render(ServerCardWrapper, { server: REMOTE }); + + await screen.getByTitle('Show the access code').click(); + + await expect.element(screen.getByText(CODE)).toBeVisible(); + }); +}); + +describe('the status feed of a tunneled router', () => { + const calls: string[] = []; + + beforeEach(() => { + calls.length = 0; + settingsStore.updateConfig( + SETTINGS_KEYS.SERVERS, + JSON.stringify([{ code: CODE, id: 'r1', kind: 'remote', name: 'Home' }]) + ); + serversStore.initialize(); + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => { + calls.push(String(input instanceof Request ? input.url : input)); + + return new Response(': ping\n\n', { status: 200 }); + }); + }); + + afterEach(() => { + modelsStore.status.subscribeServer(null); + vi.restoreAllMocks(); + }); + + it('reads the feed at the origin of the server it was given', async () => { + modelsStore.status.subscribeServer('r1'); + + await vi.waitFor(() => expect(calls.length).toBeGreaterThan(0)); + + // the tunnel carries the feed like any other request: the server's own + // origin, never the one serving this UI + expect(calls[0]).toBe(`${tunnelOrigin('r1')}${API_MODELS.SSE}`); + }); + + it('opens one reader per server', async () => { + modelsStore.status.subscribeServer('r1'); + modelsStore.status.subscribeServer('r1'); + + await vi.waitFor(() => expect(calls.length).toBe(1)); + + expect(calls.length).toBe(1); + }); + + it('opens nothing for no server', async () => { + modelsStore.status.subscribeServer(null); + + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(calls).toEqual([]); + }); +}); + +describe('channels lost to a backgrounded tab', () => { + beforeEach(() => { + vi.useFakeTimers(); + settingsStore.updateConfig( + SETTINGS_KEYS.SERVERS, + JSON.stringify([ + { code: CODE, id: 'r1', kind: 'remote', name: 'Home' }, + { code: CODE, id: 'r2', kind: 'remote', name: 'Office' } + ]) + ); + serversStore.initialize(); + // one channel was open before the tab went away, the other was never asked for + withTunnel(TunnelStatus.ERROR, 'Disconnected from the host'); + remoteAccessStore.status['r2'] = TunnelStatus.IDLE; + }); + + afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + delete remoteAccessStore.status['r1']; + delete remoteAccessStore.errorMessage['r1']; + delete remoteAccessStore.status['r2']; + }); + + it('asks again, and only for a channel that was wanted', async () => { + const connect = vi.spyOn(remoteAccessStore, 'connect').mockResolvedValue(); + + remoteAccessStore.recoverChannels(); + + // the network is not back the moment the tab is: nothing happens at once + expect(connect).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(WEBRTC_TIMEOUTS.RECOVER_MS); + + expect(connect).toHaveBeenCalledWith('r1'); + expect(connect).not.toHaveBeenCalledWith('r2'); + }); + + it('opens one handshake per burst of tab switches', async () => { + const connect = vi.spyOn(remoteAccessStore, 'connect').mockResolvedValue(); + + remoteAccessStore.recoverChannels(); + await vi.advanceTimersByTimeAsync(WEBRTC_TIMEOUTS.RECOVER_MS / 2); + remoteAccessStore.recoverChannels(); + await vi.advanceTimersByTimeAsync(WEBRTC_TIMEOUTS.RECOVER_MS); + + expect(connect).toHaveBeenCalledTimes(1); + }); +}); + +describe('a handshake the user gives up on', () => { + beforeEach(() => { + FakeTunnel.instances = []; + settingsStore.updateConfig( + SETTINGS_KEYS.SERVERS, + JSON.stringify([{ code: CODE, id: 'r1', kind: 'remote', name: 'Home' }]) + ); + serversStore.initialize(); + }); + + afterEach(() => { + remoteAccessStore.disconnect('r1'); + }); + + it('leaves the server idle when the answer lands late', async () => { + const attempt = remoteAccessStore.connect('r1'); + const [tunnel] = FakeTunnel.instances; + + remoteAccessStore.disconnect('r1'); + + // the host answers after the user stopped waiting + tunnel.onConnected?.(); + tunnel.settle?.(); + + await attempt; + + expect(remoteAccessStore.statusOf('r1')).toBe(TunnelStatus.IDLE); + expect(remoteAccessStore.isConnected('r1')).toBe(false); + expect(tunnel.disconnected).toBe(true); + }); + + it('starts a fresh handshake when asked again', async () => { + const dropped = remoteAccessStore.connect('r1'); + + remoteAccessStore.disconnect('r1'); + + const kept = remoteAccessStore.connect('r1'); + const [first, second] = FakeTunnel.instances; + + expect(second).not.toBe(first); + + second.onConnected?.(); + second.settle?.(); + await kept; + + expect(remoteAccessStore.isConnected('r1')).toBe(true); + + // the dropped attempt landing now must not close the one that is up + first.settle?.(); + await dropped; + + expect(remoteAccessStore.isConnected('r1')).toBe(true); + expect(first.disconnected).toBe(true); + }); +}); diff --git a/ui/apps/chat/tests/client/search-chats.service.svelte.test.ts b/ui/apps/chat/tests/client/search-chats.service.svelte.test.ts index 87eca5dbfe6e..f7a47c8821b0 100644 --- a/ui/apps/chat/tests/client/search-chats.service.svelte.test.ts +++ b/ui/apps/chat/tests/client/search-chats.service.svelte.test.ts @@ -104,10 +104,16 @@ describe('search_chats service', () => { expect(reply.content).toBe('Error: order_timestamp must be one of: asc, desc'); }); - it('reads through a transaction that refuses writes', async () => { - await expect( - DatabaseService.readOnly(({ messages }) => messages.delete('paris-m0')) - ).rejects.toThrow(); + it('scans the messages of the chats with one in a time range, leaving the store as it was', async () => { + const seen: string[] = []; + + await DatabaseService.scanMessages(['paris'], (m) => seen.push(m.id)); + expect(seen.sort()).toEqual(['paris-m0', 'paris-m1', 'paris-m2', 'paris-m3']); + + seen.length = 0; + // paris's messages are timestamped 1000 to 1003, so a window after them leaves it out + await DatabaseService.scanMessages(['paris'], (m) => seen.push(m.id), { from: 1004 }); + expect(seen).toEqual([]); expect(await DatabaseService.getConversationMessages('paris')).toHaveLength(4); }); }); diff --git a/ui/apps/chat/tests/client/servers-dialog.svelte.test.ts b/ui/apps/chat/tests/client/servers-dialog.svelte.test.ts new file mode 100644 index 000000000000..56837e8b6425 --- /dev/null +++ b/ui/apps/chat/tests/client/servers-dialog.svelte.test.ts @@ -0,0 +1,166 @@ +// Guards the phone's door to servers. The models dialog is desktop-only, so a +// phone reaches its server list from the sidebar; without that entry there is no +// way to pair a server, and a phone with no paired server has nothing to pick a +// model from. + +import DialogServersWrapper from './components/DialogServersWrapper.svelte'; +import { ChatScreenServerError, SidebarNavigationActions } from '#lib/components/app/index.ts'; +import { + CODE_CHARS, + CODE_LENGTHS, + SETTINGS_KEYS, + SIDEBAR_FOOTER_ITEMS +} from '#lib/constants/index.ts'; +import { SidebarAction } from '#lib/enums/index.ts'; +import { serversStore, serverStore, settingsStore, uiStore } from '#lib/stores/index.ts'; +import { getAuthHeadersForServer } from '#lib/utils/api-headers.ts'; +import { createRemoteServer, createUrlServer } from '#lib/utils/servers.ts'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { page } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +const PHONE = { height: 844, width: 390 }; +const DESKTOP = { height: 900, width: 1280 }; +/** A code of the right length, drawn from the alphabet llama-server generates from. */ +const CODE = Array.from( + { length: CODE_LENGTHS.SHARE }, + (_, index) => CODE_CHARS[index % CODE_CHARS.length] +).join(''); + +describe('servers on a phone', () => { + const opened: boolean[] = []; + + beforeEach(async () => { + opened.length = 0; + settingsStore.updateConfig(SETTINGS_KEYS.ENABLE_REMOTE_PAIRING, true); + await page.viewport(PHONE.width, PHONE.height); + }); + + afterEach(async () => { + settingsStore.updateConfig(SETTINGS_KEYS.ENABLE_REMOTE_PAIRING, false); + await page.viewport(DESKTOP.width, DESKTOP.height); + }); + + it('offers the servers list in the sidebar', async () => { + // the sidebar's footer carries the entry, and a phone lists it with the top actions + const screen = render(SidebarNavigationActions, { + class: '', + items: SIDEBAR_FOOTER_ITEMS, + onAction: (action) => opened.push(action === SidebarAction.SERVERS) + }); + const item = screen.getByRole('button', { name: 'Servers' }); + + await expect.element(item).toBeVisible(); + + await item.click(); + + expect(opened).toEqual([true]); + }); + + it('opens the list as a dialog of its own', async () => { + const screen = render(DialogServersWrapper); + + await expect.element(screen.getByText('Servers')).toBeVisible(); + await expect.element(screen.getByRole('button', { name: 'Close' })).toBeVisible(); + }); + + it('reaches the pairing form through the add control', async () => { + const screen = render(DialogServersWrapper); + + await screen.getByRole('button', { name: 'Add new server' }).click(); + + await expect.element(screen.getByRole('heading', { name: 'Add New Server' })).toBeVisible(); + + await screen.getByRole('tab', { name: 'Remote server' }).click(); + + await expect.element(screen.getByText('Not paired yet')).toBeVisible(); + }); + + it('offers only a URL while pairing is switched off', async () => { + settingsStore.updateConfig(SETTINGS_KEYS.ENABLE_REMOTE_PAIRING, false); + + const screen = render(DialogServersWrapper); + + await screen.getByRole('button', { name: 'Add new server' }).click(); + + await expect.element(screen.getByRole('heading', { name: 'Add New Server' })).toBeVisible(); + expect(screen.getByRole('tab', { name: 'Remote server' }).query()).toBeNull(); + }); + + it('opens the form as a bottom drawer, and as a dialog on a desktop', async () => { + const screen = render(DialogServersWrapper); + + await screen.getByRole('button', { name: 'Add new server' }).click(); + await expect.element(screen.getByRole('heading', { name: 'Add New Server' })).toBeVisible(); + + const drawer = document.querySelector('[data-slot="drawer-content"]'); + + expect(drawer?.getAttribute('data-vaul-drawer-direction')).toBe('bottom'); + + await page.viewport(DESKTOP.width, DESKTOP.height); + + expect(document.querySelector('[data-slot="drawer-content"]')).toBeNull(); + await expect.element(screen.getByRole('heading', { name: 'Add New Server' })).toBeVisible(); + }); + + it('offers the API key of a paired server too', async () => { + const screen = render(DialogServersWrapper); + + await screen.getByRole('button', { name: 'Add new server' }).click(); + await screen.getByRole('tab', { name: 'Remote server' }).click(); + + // a llama-server started with --connect can still guard its API with a key, + // and the tunnel carries the header through + await expect.element(screen.getByLabelText(/API key/)).toBeVisible(); + }); +}); + +describe('server credentials', () => { + afterEach(() => { + settingsStore.updateConfig(SETTINGS_KEYS.SERVERS, '[]'); + }); + + it('keeps the API key of every server it stores', () => { + serversStore.addServer(createUrlServer('https://example.com', 'u1', 'Office', 'sk-url')); + serversStore.addRemoteServer(CODE, 'Home', 'r1', 'sk-tunnel'); + + // the list a request is built from is the parsed one: a key that does not + // survive the round trip is a key that never reaches the server + const stored = serversStore.external; + const url = stored.find((server) => server.id === 'u1'); + const remote = stored.find((server) => server.id === 'r1'); + + expect(url?.apiKey).toBe('sk-url'); + expect(remote?.apiKey).toBe('sk-tunnel'); + expect(getAuthHeadersForServer(remote!).Authorization).toBe('Bearer sk-tunnel'); + }); + + it('keeps the code of a remote server', () => { + serversStore.addRemoteServer(CODE, 'Home', 'r1'); + + expect(serversStore.external.find((server) => server.id === 'r1')?.code).toBe(CODE); + expect(createRemoteServer(CODE, 'r2', 'Office').code).toBe(CODE); + }); +}); + +describe('a chat with no server at all', () => { + beforeEach(() => { + settingsStore.updateConfig(SETTINGS_KEYS.SERVERS, '[]'); + serverStore.error = 'Connection refused'; + }); + + afterEach(() => { + serverStore.error = null; + uiStore.serversOpen = false; + }); + + it('offers pairing as the way out', async () => { + const screen = render(ChatScreenServerError); + + await expect.element(screen.getByText('Server unavailable')).toBeVisible(); + + await screen.getByRole('button', { name: 'Pair a remote server' }).click(); + + expect(uiStore.serversOpen).toBe(true); + }); +}); diff --git a/ui/apps/chat/tests/client/settings-extension-fields.svelte.test.ts b/ui/apps/chat/tests/client/settings-extension-fields.svelte.test.ts new file mode 100644 index 000000000000..68ff5d299319 --- /dev/null +++ b/ui/apps/chat/tests/client/settings-extension-fields.svelte.test.ts @@ -0,0 +1,65 @@ +// A setting can belong to an extension. Its field is drawn only while that +// extension is on; the other fields of the section are not affected. + +import SettingsChatFields from '#lib/components/app/settings/SettingsChat/SettingsChatFields.svelte'; +import { SETTINGS_CHAT_SECTIONS, SETTINGS_KEYS } from '#lib/constants/index.ts'; +import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import type { SettingsFieldConfig } from '#lib/types/index.ts'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const EXTENSION_ID = 'fields-fixture'; +const FIELDS: SettingsFieldConfig[] = [ + { key: 'coreSetting', label: 'Core setting', type: SettingsFieldType.INPUT }, + { + extension: EXTENSION_ID, + key: 'extensionSetting', + label: 'Extension setting', + type: SettingsFieldType.INPUT + } +]; + +function labels(container: Element): string[] { + return [...container.querySelectorAll('label')].map((label) => label.textContent?.trim() ?? ''); +} + +describe('settings fields of an extension', () => { + beforeAll(() => { + extensions.register({ + description: 'Owns one settings field', + disabledByDefault: true, + id: EXTENSION_ID, + load: async () => ({ default: { activate() {} } }), + name: 'Fields fixture' + }); + }); + + afterAll(async () => { + await extensions.setEnabled(EXTENSION_ID, false); + }); + + it('draws the field only while its extension is on', async () => { + const { container } = render(SettingsChatFields, { + fields: FIELDS, + localConfig: { coreSetting: '1', extensionSetting: '2' }, + onConfigChange: () => {} + }); + + expect(labels(container)).toEqual(['Core setting']); + + await extensions.setEnabled(EXTENSION_ID, true); + await expect.poll(() => labels(container)).toEqual(['Core setting', 'Extension setting']); + + await extensions.setEnabled(EXTENSION_ID, false); + await expect.poll(() => labels(container)).toEqual(['Core setting']); + }); + + it('marks the MCP request timeout as the MCP extension’s', () => { + const field = SETTINGS_CHAT_SECTIONS.flatMap((section) => section.fields ?? []).find( + (entry) => entry.key === SETTINGS_KEYS.MCP_REQUEST_TIMEOUT_SECONDS + ); + + expect(field?.extension).toBe('mcp'); + }); +}); diff --git a/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts b/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts new file mode 100644 index 000000000000..db16f8068774 --- /dev/null +++ b/ui/apps/chat/tests/client/settings-extensions.svelte.test.ts @@ -0,0 +1,243 @@ +// The Extensions section of the settings switches an extension on and off, at +// once: with MCP off its sidebar entry, the `/prompt` command and its tools are +// gone and its connections close; switched on again they are back. The choice +// is stored, so a reload keeps it. + +import SidebarNavigationFooter from '#lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte'; +import SettingsChatExtensionsTab from '#lib/components/app/settings/SettingsChat/SettingsChatExtensionsTab.svelte'; +import { + EXTENSIONS_LOCALSTORAGE_KEY, + SETTINGS_KEYS, + SIDEBAR_FOOTER_ITEMS +} from '#lib/constants/index.ts'; +import { ToolSource } from '#lib/enums/index.ts'; +import { BUILT_IN_EXTENSIONS } from '#lib/extensions/builtin.ts'; +import { ExtensionRegistry, extensions } from '#lib/extensions/index.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import { uiStore } from '#lib/stores/index.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { MCPConnection, MCPResourceInfo } from '#lib/types/index.ts'; +import { getChatCommands } from '#lib/utils/index.ts'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { page } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +const MCP_ID = 'mcp'; +/** The labels of the footer's own items, in order. */ +const FOOTER = SIDEBAR_FOOTER_ITEMS.map((item) => item.tooltip); +const RESOURCE: MCPResourceInfo = { + name: 'README.md', + serverName: 'docs', + uri: 'repo://ggml-org/llama.cpp/README.md' +}; + +/** Labels of the sidebar footer's rows, in order. */ +function footerLabels(container: Element): string[] { + return [...container.querySelectorAll('[data-slot="button"]')] + .map((row) => row.querySelector('span span')?.textContent?.trim() ?? '') + .filter((label) => label !== ''); +} + +/** The slash commands as the chat form lists them. */ +function commandNames(): string[] { + return getChatCommands( + { canCompact: () => false, hasCwdTools: () => false, showModelSelector: false }, + extensions.contributions('composerCommands') + ).map((command) => command.name); +} + +function mcpToolNames(): string[] { + return toolsStore.allTools + .filter((tool) => tool.source === ToolSource.MCP) + .map((tool) => tool.definition.function.name); +} + +function storedChoices(): unknown { + return JSON.parse(localStorage.getItem(EXTENSIONS_LOCALSTORAGE_KEY) ?? 'null'); +} + +/** The registry a reloaded app starts with: the same extensions, the choices read from storage. */ +async function reloadedRegistry(): Promise { + const registry = new ExtensionRegistry(); + + for (const manifest of BUILT_IN_EXTENSIONS) registry.register(manifest); + + await registry.activateEnabled(); + + return registry; +} + +describe('Extensions settings', () => { + let wasExpanded: boolean; + + beforeAll(() => { + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + + for (const manifest of BUILT_IN_EXTENSIONS) extensions.register(manifest); + }); + + beforeEach(async () => { + await page.viewport(1280, 900); + wasExpanded = uiStore.isSidebarExpanded; + uiStore.isSidebarExpanded = true; + // Models and MCP wait behind their settings: show them, so their entries are there to find + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MODELS_MANAGER, true); + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); + + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, '[]'); + + const serverId = mcpStore.addServer({ + displayName: 'Docs', + enabled: true, + url: 'https://mcp.example.com/mcp' + }).id; + + // no network: the server is "connected" with one tool + vi.spyOn(mcpStore, 'runHealthChecksForServers').mockResolvedValue(); + vi.spyOn(mcpStore, 'getConnections').mockReturnValue( + new Map([[serverId, { tools: [{ name: 'search' }] } as unknown as MCPConnection]]) + ); + vi.spyOn(mcpStore, 'shutdown').mockResolvedValue(); + + // every test starts with MCP on, as a fresh app does + await extensions.setEnabled(MCP_ID, true); + }); + + afterEach(async () => { + await extensions.setEnabled(MCP_ID, false); + vi.restoreAllMocks(); + mcpStore.resources.clearAttachments(); + settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, '[]'); + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + uiStore.isSidebarExpanded = wasExpanded; + }); + + afterAll(() => { + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + }); + + it('lists MCP with its description, switched on', async () => { + const screen = render(SettingsChatExtensionsTab); + + await expect.element(screen.getByRole('switch', { name: 'MCP' })).toBeChecked(); + await expect + .element( + screen.getByText('Connect MCP servers and use their tools, prompts and resources in chats.') + ) + .toBeVisible(); + expect(screen.container.querySelector('[role="alert"]')).toBeNull(); + }); + + it('takes MCP out of the sidebar, the commands and the tools, and puts it back', async () => { + const settings = render(SettingsChatExtensionsTab); + const sidebar = render(SidebarNavigationFooter, {}); + const mcpSwitch = settings.getByRole('switch', { name: 'MCP' }); + + await vi.waitFor(() => + expect(footerLabels(sidebar.container)).toEqual(['Models', 'MCP', ...FOOTER.slice(1)]) + ); + expect(commandNames()).toEqual(['prompt', 'cwd', 'model', 'compact']); + expect(mcpToolNames()).toEqual(['search']); + + mcpStore.resources.addAttachment(RESOURCE); + + await mcpSwitch.click(); + + await expect.element(mcpSwitch).not.toBeChecked(); + await vi.waitFor(() => expect(footerLabels(sidebar.container)).toEqual(FOOTER)); + expect(commandNames()).toEqual(['cwd', 'model', 'compact']); + expect(mcpToolNames()).toEqual([]); + // the live connections close and the resources waiting in the chat form are dropped + expect(mcpStore.shutdown).toHaveBeenCalledOnce(); + expect(mcpStore.resources.hasAttachments).toBe(false); + expect(extensions.extensions.find((e) => e.id === MCP_ID)).toMatchObject({ + enabled: false, + state: 'inactive' + }); + + await mcpSwitch.click(); + + await expect.element(mcpSwitch).toBeChecked(); + await vi.waitFor(() => + expect(footerLabels(sidebar.container)).toEqual(['Models', 'MCP', ...FOOTER.slice(1)]) + ); + expect(commandNames()).toEqual(['prompt', 'cwd', 'model', 'compact']); + expect(mcpToolNames()).toEqual(['search']); + }); + + it('keeps the choice over a reload', async () => { + const settings = render(SettingsChatExtensionsTab); + const mcpSwitch = settings.getByRole('switch', { name: 'MCP' }); + + await mcpSwitch.click(); + await expect.element(mcpSwitch).not.toBeChecked(); + + expect(storedChoices()).toEqual({ [MCP_ID]: false }); + + const off = await reloadedRegistry(); + + expect(off.extensions).toMatchObject([{ enabled: false, id: MCP_ID, state: 'inactive' }]); + expect(off.contributions('navigation')).toEqual([]); + expect(off.contributions('tools')).toEqual([]); + + const reloadedSettings = render(SettingsChatExtensionsTab, { registry: off }); + + await expect.element(reloadedSettings.getByRole('switch', { name: 'MCP' })).not.toBeChecked(); + + await mcpSwitch.click(); + await expect.element(mcpSwitch).toBeChecked(); + + expect(storedChoices()).toEqual({ [MCP_ID]: true }); + + const on = await reloadedRegistry(); + + try { + expect(on.extensions).toMatchObject([{ enabled: true, id: MCP_ID, state: 'active' }]); + expect(on.contributions('navigation')).toHaveLength(1); + } finally { + await on.setEnabled(MCP_ID, false); + } + }); + + it('says why an extension did not start, and tries again when switched off and on', async () => { + const registry = new ExtensionRegistry(); + + let attempts = 0; + + registry.register({ + description: 'Fails the first time it loads.', + id: 'settings-extensions-flaky', + load: async () => { + attempts++; + + if (attempts === 1) throw new Error('chunk did not load'); + + return { default: { activate: () => {} } }; + }, + name: 'Flaky' + }); + + vi.spyOn(console, 'error').mockImplementation(() => {}); + await registry.activateEnabled(); + + const screen = render(SettingsChatExtensionsTab, { registry }); + const flaky = screen.getByRole('switch', { name: 'Flaky' }); + + await expect.element(flaky).toBeChecked(); + await expect + .element(screen.getByRole('alert')) + .toHaveTextContent( + 'Flaky did not start: chunk did not load. Switch it off and on to try again.' + ); + + await flaky.click(); + await expect.element(flaky).not.toBeChecked(); + expect(screen.container.querySelector('[role="alert"]')).toBeNull(); + + await flaky.click(); + await expect.element(flaky).toBeChecked(); + await vi.waitFor(() => expect(registry.extensions[0].state).toBe('active')); + expect(screen.container.querySelector('[role="alert"]')).toBeNull(); + }); +}); diff --git a/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts b/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts new file mode 100644 index 000000000000..352341c9e518 --- /dev/null +++ b/ui/apps/chat/tests/client/tools-extension-point.svelte.test.ts @@ -0,0 +1,161 @@ +// The tools UI reads MCP only through the `tools` extension point: with the +// MCP extension on it shows the servers' tools as before, with it off it +// still renders, just without them. + +import SettingsChatToolsTab from '#lib/components/app/settings/SettingsChat/SettingsChatToolsTab.svelte'; +import { + DISABLED_TOOL_CATEGORIES_LOCALSTORAGE_KEY, + EXTENSIONS_LOCALSTORAGE_KEY, + SETTINGS_KEYS +} from '#lib/constants/index.ts'; +import { ToolSource } from '#lib/enums/index.ts'; +import { BUILT_IN_EXTENSIONS } from '#lib/extensions/builtin.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import { extensions } from '#lib/extensions/registry.svelte.ts'; +import { useToolsPanel, type UseToolsPanelReturn } from '#lib/hooks/use-tools-panel.svelte.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { MCPConnection } from '#lib/types/index.ts'; +import { flushSync, tick } from 'svelte'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const MCP_ID = 'mcp'; +const SERVER_HINT = + 'To enable Server Tools you need to run llama-server with --tools all or --tools flag.'; +// the favicon fallback resolves to the root domain of the server url +const FAVICON = 'https://example.com/favicon.ico'; + +let serverId = ''; + +function withPanel(run: (panel: UseToolsPanelReturn) => void): void { + const stop = $effect.root(() => { + const panel = useToolsPanel(); + + flushSync(); + run(panel); + }); + + stop(); +} + +beforeAll(() => { + for (const manifest of BUILT_IN_EXTENSIONS) extensions.register(manifest); +}); + +beforeEach(async () => { + // MCP waits behind its setting: show it, so the panel can point at its servers + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); + settingsStore.updateConfig('mcpServers', '[]'); + serverId = mcpStore.addServer({ + displayName: 'Docs', + enabled: true, + url: 'https://mcp.example.com/mcp' + }).id; + vi.spyOn(mcpStore, 'getConnections').mockReturnValue( + new Map([[serverId, { tools: [{ name: 'search' }] } as unknown as MCPConnection]]) + ); + await extensions.setEnabled(MCP_ID, true); +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +afterAll(async () => { + await extensions.setEnabled(MCP_ID, false); + settingsStore.updateConfig('mcpServers', '[]'); + localStorage.removeItem(EXTENSIONS_LOCALSTORAGE_KEY); + localStorage.removeItem(DISABLED_TOOL_CATEGORIES_LOCALSTORAGE_KEY); +}); + +describe('tools settings', () => { + it('draws an MCP server group with its icon while the MCP extension is on', async () => { + render(SettingsChatToolsTab); + await tick(); + + expect(document.body.textContent).toContain('Docs'); + expect(document.body.textContent).toContain('Browser'); + expect(document.querySelector(`img[src="${FAVICON}"]`)).not.toBeNull(); + }); + + it('renders without the MCP groups once the extension is off', async () => { + render(SettingsChatToolsTab); + await extensions.setEnabled(MCP_ID, false); + await tick(); + + expect(document.body.textContent).not.toContain('Docs'); + expect(document.body.textContent).toContain('Browser'); + expect(document.querySelector(`img[src="${FAVICON}"]`)).toBeNull(); + }); +}); + +describe('tools panel', () => { + it('keeps the MCP server groups apart from the category groups', () => { + withPanel((panel) => { + const [group] = panel.providerGroups; + + expect(panel.providerGroups).toHaveLength(1); + expect(group).toMatchObject({ key: `mcp:${serverId}`, label: 'Docs' }); + expect(panel.categoryGroups.map((g) => g.source)).toEqual([ToolSource.BROWSER]); + expect(panel.getFavicon(group)).toBe(FAVICON); + expect(panel.getFavicon(panel.categoryGroups[0])).toBeNull(); + expect(panel.isGroupDisabled(group)).toBe(false); + }); + }); + + it('grays an MCP server group out while the MCP category is off', async () => { + await conversationsStore.preferences.toggleCategory(ToolSource.MCP); + + withPanel((panel) => { + expect(panel.isGroupDisabled(panel.providerGroups[0])).toBe(true); + expect(panel.isGroupDisabled(panel.categoryGroups[0])).toBe(false); + }); + + await conversationsStore.preferences.toggleCategory(ToolSource.MCP); + }); + + it('checks the MCP servers again when it opens', () => { + const run = vi.spyOn(mcpStore, 'runHealthChecksForServers').mockResolvedValue(); + + vi.spyOn(toolsStore, 'fetchServerTools').mockResolvedValue(); + withPanel((panel) => panel.handleOpen()); + + expect(run).toHaveBeenCalledOnce(); + expect(run.mock.calls[0][0].map((server) => server.id)).toEqual([serverId]); + }); + + it('explains how to get MCP tools while there is no tool to list', () => { + vi.spyOn(toolsStore, 'toolGroups', 'get').mockReturnValue([]); + + withPanel((panel) => { + expect(panel.noToolsInfoMessage).toBe( + `${SERVER_HINT} To see MCP Tools you need to add / enable MCP Server(s).` + ); + expect(panel.providerHints).toEqual([ + { + action: 'Enable MCP Server(s) to access', + sentence: 'To see MCP Tools you need to add / enable MCP Server(s).', + toolsLabel: 'MCP Tools' + } + ]); + }); + }); + + it('works without the MCP extension', async () => { + await extensions.setEnabled(MCP_ID, false); + vi.spyOn(toolsStore, 'fetchServerTools').mockResolvedValue(); + + withPanel((panel) => { + expect(panel.providerGroups).toEqual([]); + expect(panel.providerHints).toEqual([]); + expect(panel.categoryGroups.map((g) => g.source)).toEqual([ToolSource.BROWSER]); + expect(() => panel.handleOpen()).not.toThrow(); + }); + + vi.spyOn(toolsStore, 'toolGroups', 'get').mockReturnValue([]); + + withPanel((panel) => expect(panel.noToolsInfoMessage).toBe(SERVER_HINT)); + }); +}); diff --git a/ui/apps/chat/tests/stories/chat/attachments/ChatAttachmentsList.stories.svelte b/ui/apps/chat/tests/stories/chat/attachments/ChatAttachmentsList.stories.svelte index c32d4a072878..86e3ab8a3e71 100644 --- a/ui/apps/chat/tests/stories/chat/attachments/ChatAttachmentsList.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/attachments/ChatAttachmentsList.stories.svelte @@ -28,6 +28,7 @@ import ChatAttachmentsList from '#lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte'; import StateGallery from '$llama-ui-stories/helpers/StateGallery.svelte'; import StateGalleryItem from '$llama-ui-stories/helpers/StateGalleryItem.svelte'; + import { expect } from 'storybook/test'; const { Story } = defineMeta({ component: ChatAttachmentsList, @@ -40,7 +41,16 @@ const onFileRemove = (id: string) => console.log('remove', id); - + + { + // the stored MCP resource is MCP's own chip, not the default text chip + await expect((await canvas.findAllByRole('button', { name: 'README.md' })).length).toBe(2); + await expect(canvas.queryByRole('button', { name: 'Preview README.md' })).toBeNull(); + }} +> import { mcpPrompts, mcpServers, override, seedStores } from './fixtures'; import { defineMeta } from '@storybook/addon-svelte-csf'; - import ChatFormPickerMcpPrompts from '#lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerMcpPrompts/ChatFormPickerMcpPrompts.svelte'; - import { mcpStore } from '#lib/stores/index.ts'; + import ChatFormPickerMcpPrompts from '#lib/extensions/mcp/components/chat/ChatFormPickerMcpPrompts/ChatFormPickerMcpPrompts.svelte'; + import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; import { fn, screen } from 'storybook/test'; import type { ComponentProps } from 'svelte'; diff --git a/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.stories.svelte index 818b9830bcbd..5c2037d3de49 100644 --- a/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.stories.svelte @@ -109,6 +109,7 @@ }} /> + {} }, { action: ChatFormCommandAction.CWD, @@ -209,7 +211,7 @@ export const cwdServerTools: ServerToolInfo[] = [ display_name: tool, permissions: { write: false }, tool, - type: ToolSource.SERVER, + type: ServerToolType.SERVER, uses_cwd: true })); diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessage.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessage.stories.svelte index aaf5f3d6e17f..2491bb662791 100644 --- a/ui/apps/chat/tests/stories/chat/messages/ChatMessage.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessage.stories.svelte @@ -36,6 +36,7 @@ import { MessageRole } from '#lib/enums/index.ts'; import { chatActivityStore } from '#lib/stores/chat/activity.svelte.ts'; import { chatStore } from '#lib/stores/index.ts'; + import { expect } from 'storybook/test'; const { Story } = defineMeta({ args: { @@ -254,7 +255,16 @@ seedChatStory()} name="CwdCleared" /> - seedChatStory()} name="McpPrompt" /> + seedChatStory()} + name="McpPrompt" + play={async ({ canvas }) => { + await expect( + await canvas.findByRole('group', { name: 'MCP Prompt message with actions' }) + ).toBeInTheDocument(); + }} +/> console.log('activate', id), @@ -37,7 +39,12 @@ diff --git a/ui/apps/chat/tests/stories/helpers/extensions.ts b/ui/apps/chat/tests/stories/helpers/extensions.ts new file mode 100644 index 000000000000..a7660d90bd9a --- /dev/null +++ b/ui/apps/chat/tests/stories/helpers/extensions.ts @@ -0,0 +1,18 @@ +import { BUILT_IN_EXTENSIONS } from '#lib/extensions/builtin.ts'; +import { extensions } from '#lib/extensions/index.ts'; + +/** + * Switch the built-in extensions on, as the app does at startup. Storybook + * runs this once before all stories (`.storybook/preview.ts`), so a story + * does not call it. Safe to call again: a known extension is not registered + * twice. + */ +export async function activateBuiltInExtensions(): Promise { + const known = new Set(extensions.extensions.map((extension) => extension.id)); + + for (const manifest of BUILT_IN_EXTENSIONS) { + if (!known.has(manifest.id)) extensions.register(manifest); + } + + await extensions.activateEnabled(); +} diff --git a/ui/apps/chat/tests/stories/mcp/McpCapabilitiesBadges.stories.svelte b/ui/apps/chat/tests/stories/mcp/McpCapabilitiesBadges.stories.svelte index 695c680e1b05..74a5570e8be8 100644 --- a/ui/apps/chat/tests/stories/mcp/McpCapabilitiesBadges.stories.svelte +++ b/ui/apps/chat/tests/stories/mcp/McpCapabilitiesBadges.stories.svelte @@ -1,7 +1,7 @@ + + { + const canvas = within(canvasElement); + + await expect(canvas.getByText('imcp')).toBeInTheDocument(); + await expect(canvas.getAllByText('Run by llama-server')).toHaveLength(2); + await expect(canvas.getByRole('switch', { name: 'Use the tools of imcp' })).toBeChecked(); + await expect(canvas.getByText('3 tools available · Show details')).toBeInTheDocument(); + }} +> + + + + + + + + + + + + { + const canvas = within(canvasElement); + + await expect(canvas.getByText(/llama-server --mcp-servers-config mcp.json/)).toBeVisible(); + await expect(canvas.getByRole('button', { name: 'Copy the config example' })).toBeVisible(); + }} +> +
+ +
+
diff --git a/ui/apps/chat/tests/stories/mcp/McpServerCard.stories.svelte b/ui/apps/chat/tests/stories/mcp/McpServerCard.stories.svelte index c2d3f4c56d1b..7e70657a5f1a 100644 --- a/ui/apps/chat/tests/stories/mcp/McpServerCard.stories.svelte +++ b/ui/apps/chat/tests/stories/mcp/McpServerCard.stories.svelte @@ -1,7 +1,7 @@ + + +
+
+

Projects

+ +

+ The header's New project button gives way to the floating key on a phone. +

+
+ + {#each [1, 2, 3, 4, 5] as card (card)} +
+ {/each} +
+ + +
diff --git a/ui/apps/chat/tests/stories/models/ModelsSelector.stories.svelte b/ui/apps/chat/tests/stories/models/ModelsSelector.stories.svelte index 3aa5c6045df4..c960d6b8401c 100644 --- a/ui/apps/chat/tests/stories/models/ModelsSelector.stories.svelte +++ b/ui/apps/chat/tests/stories/models/ModelsSelector.stories.svelte @@ -72,7 +72,8 @@ items: [availableModels[4]], orgName: 'intel' } - ] + ], + servers: [] }; function handleSelect(modelId: string) { diff --git a/ui/apps/chat/tests/stories/settings/SettingsChatExtensionsTab.stories.svelte b/ui/apps/chat/tests/stories/settings/SettingsChatExtensionsTab.stories.svelte new file mode 100644 index 000000000000..b31e9ac34dec --- /dev/null +++ b/ui/apps/chat/tests/stories/settings/SettingsChatExtensionsTab.stories.svelte @@ -0,0 +1,123 @@ + + +{#snippet frame(args: { registry?: ExtensionRegistry })} +
+ +
+{/snippet} + + + { + await builtIn.activateEnabled(); + }} + name="Default" + play={async ({ canvas }) => { + await expect(canvas.getByRole('switch', { name: 'MCP' })).toBeChecked(); + }} + template={frame} +/> + + + { + await states.activateEnabled(); + }} + name="States" + play={async ({ canvas }) => { + await expect(canvas.getByRole('switch', { name: 'MCP' })).toBeChecked(); + await expect(canvas.getByRole('switch', { name: 'Notes' })).not.toBeChecked(); + await expect(canvas.getByRole('switch', { name: 'Voice' })).toBeChecked(); + await expect(await canvas.findByRole('alert')).toHaveTextContent( + 'Voice did not start: Failed to fetch dynamically imported module. Switch it off and on to try again.' + ); + }} + template={frame} +/> + + + { + await switching.setEnabled('story-switching', true); + }} + name="SwitchOffAndOn" + play={async (context) => { + const { canvas } = context; + const pace = getPace(context); + const notes = canvas.getByRole('switch', { name: 'Notes' }); + + await expect(notes).toBeChecked(); + await pace.pause(); + await pace.user.click(notes); + await expect(notes).not.toBeChecked(); + await waitFor(() => expect(switching.extensions[0].state).toBe('inactive')); + + await pace.pause(); + await pace.user.click(notes); + await expect(notes).toBeChecked(); + await waitFor(() => expect(switching.extensions[0].state).toBe('active')); + }} + template={frame} +/> diff --git a/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte b/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte index 24b2c5c13b9b..aca98e0dd867 100644 --- a/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte +++ b/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte @@ -21,6 +21,8 @@ + + ({ + DatabaseService: {} +})); + +import { BuiltInTool, MessageRole, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts'; +import type { Extension, ToolProvider } from '#lib/extensions/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { ChatService } from '#lib/services/chat.service.ts'; +import { ToolsService } from '#lib/services/tools.service.ts'; +import { agenticStore } from '#lib/stores/agentic/index.svelte.ts'; +import { modelsStore } from '#lib/stores/models/index.svelte.ts'; +import { permissionsStore } from '#lib/stores/permissions.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { AgenticFlowCallbacks } from '#lib/types/agentic.js'; +import type { ApiChatMessageData } from '#lib/types/api.js'; +import type { ChatMessageTimings } from '#lib/types/chat.js'; +import type { DatabaseMessage } from '#lib/types/database.js'; + +const CONV_ID = 'conv-1'; +const USER_MESSAGES: ApiChatMessageData[] = [{ content: 'hi', role: MessageRole.USER }]; +const IMAGE_DATA_URI = 'data:image/png;base64,AAAA'; + +type StreamOptions = { + onChunk?: (chunk: string) => void; + onReasoningChunk?: (chunk: string) => void; + onTimings?: (timings?: ChatMessageTimings) => void; + onToolCallChunk?: (serialized: string) => void; +}; +type Turn = (options: StreamOptions) => void | Promise; + +function toolCalls(...names: string[]): string { + return JSON.stringify( + names.map((name, index) => ({ function: { arguments: '{}', name }, id: `call_${index}` })) + ); +} + +// each request plays the next scripted turn; returns what every request was sent +function mockTurns(...turns: Turn[]): ApiChatMessageData[][] { + const requests: ApiChatMessageData[][] = []; + + vi.spyOn(ChatService, 'sendMessage').mockImplementation(async (messages, options) => { + requests.push(structuredClone(messages) as ApiChatMessageData[]); + await turns[requests.length - 1]?.(options as StreamOptions); + }); + + return requests; +} + +function mockTools(source: ToolSource, ...names: string[]) { + vi.spyOn(toolsStore, 'getEnabledToolsForLLM').mockReturnValue( + names.map((name) => ({ function: { name, parameters: {} }, type: 'function' })) + ); + vi.spyOn(toolsStore, 'getToolSource').mockReturnValue(source); +} + +// callbacks that log their calls in order +function recorder() { + const calls: unknown[][] = []; + const log = + (name: string) => + (...args: unknown[]) => { + calls.push([name, ...args]); + }; + + let nextMessageId = 0; + + const createMessage = + (name: string) => + async (...args: unknown[]) => { + calls.push([name, ...args]); + + return { id: `msg_${nextMessageId++}` } as DatabaseMessage; + }; + const callbacks: AgenticFlowCallbacks = { + createAssistantMessage: createMessage('createAssistantMessage'), + createToolResultMessage: createMessage('createToolResultMessage'), + onAssistantTurnComplete: async (...args) => { + calls.push(['onAssistantTurnComplete', ...args]); + }, + onAttachments: log('onAttachments'), + onChunk: log('onChunk'), + onError: log('onError'), + onFlowComplete: log('onFlowComplete'), + onReasoningChunk: log('onReasoningChunk'), + onToolCallsStreaming: log('onToolCallsStreaming'), + onTurnComplete: log('onTurnComplete'), + updateToolResultMessage: async (...args) => { + calls.push(['updateToolResultMessage', ...args]); + } + }; + + return { + callbacks, + calls, + named: (name: string) => calls.filter((call) => call[0] === name), + names: () => calls.map((call) => call[0]) + }; +} + +// the registry has no way to forget an extension, so every test registers its own +let nextExtensionId = 0; + +const activeExtensionIds: string[] = []; + +async function activateExtension(extension: Extension): Promise { + const id = `flow-test-${nextExtensionId++}`; + + extensions.register({ + description: 'A test extension', + id, + load: async () => ({ default: extension }), + name: id + }); + await extensions.setEnabled(id, true); + activeExtensionIds.push(id); +} + +function makeProvider(overrides: Partial = {}): ToolProvider { + return { + entries: () => [], + execute: async () => ({ content: '', isError: false }), + isConfigured: () => true, + source: ToolSource.MCP, + ...overrides + }; +} + +function runFlow(callbacks: AgenticFlowCallbacks, signal?: AbortSignal) { + return agenticStore.runAgenticFlow({ + callbacks, + conversationId: CONV_ID, + messages: USER_MESSAGES, + signal + }); +} + +beforeEach(() => { + vi.restoreAllMocks(); + agenticStore.clearSession(CONV_ID); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(ChatService, 'normalizeMessagesForApi').mockImplementation( + async (messages) => messages as ApiChatMessageData[] + ); + vi.spyOn(toolsStore, 'fetchServerTools').mockResolvedValue(); + vi.spyOn(toolsStore, 'getToolServerLabel').mockReturnValue('Browser'); + vi.spyOn(toolsStore, 'getPermissionKey').mockReturnValue('tool-key'); + vi.spyOn(permissionsStore, 'hasTool').mockReturnValue(true); +}); + +afterEach(async () => { + for (const id of activeExtensionIds.splice(0)) await extensions.setEnabled(id, false); +}); + +describe('agentic flow', () => { + it('is not handled when no tool is enabled', async () => { + vi.spyOn(toolsStore, 'getEnabledToolsForLLM').mockReturnValue([]); + + const send = vi.spyOn(ChatService, 'sendMessage'); + + expect(await runFlow(recorder().callbacks)).toEqual({ handled: false }); + expect(send).not.toHaveBeenCalled(); + }); + + it('runs a tool call, then lets the model answer', async () => { + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + + const requests = mockTurns( + (options) => { + options.onChunk?.('checking'); + options.onToolCallChunk?.(toolCalls(BuiltInTool.BROWSER_GET_DATETIME)); + options.onTimings?.({ predicted_ms: 10, predicted_n: 4, prompt_ms: 20, prompt_n: 8 }); + }, + (options) => { + options.onReasoningChunk?.('hm'); + options.onChunk?.('it is noon'); + options.onTimings?.({ predicted_ms: 5, predicted_n: 2, prompt_ms: 1, prompt_n: 1 }); + } + ); + const { callbacks, named, names } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(names()).toEqual([ + 'onChunk', + 'onToolCallsStreaming', + 'onAssistantTurnComplete', + 'createToolResultMessage', + 'onTurnComplete', + 'createAssistantMessage', + 'onReasoningChunk', + 'onChunk', + 'onAssistantTurnComplete', + 'onTurnComplete', + 'onFlowComplete' + ]); + + const [toolTurn, finalTurn] = named('onAssistantTurnComplete'); + const call = { + function: { arguments: '{}', name: BuiltInTool.BROWSER_GET_DATETIME }, + id: 'call_0', + type: 'function' + }; + + expect(toolTurn.slice(1)).toEqual([ + 'checking', + undefined, + { predicted_ms: 10, predicted_n: 4, prompt_ms: 20, prompt_n: 8 }, + [call] + ]); + expect(finalTurn.slice(1, 3)).toEqual(['it is noon', 'hm']); + expect(finalTurn[4]).toBeUndefined(); + + const [, toolCallId, toolResult, extras] = named('createToolResultMessage')[0]; + + expect([toolCallId, extras]).toEqual(['call_0', undefined]); + expect(requests[1].slice(1)).toEqual([ + { content: 'checking', role: 'assistant', tool_calls: [call] }, + { content: toolResult, role: 'tool', tool_call_id: 'call_0' } + ]); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { + llm: { predicted_ms: 15, predicted_n: 6, prompt_ms: 21, prompt_n: 9 }, + perTurn: [{ turn: 1 }, { turn: 2 }], + toolCalls: [{ name: BuiltInTool.BROWSER_GET_DATETIME, success: true }], + toolCallsCount: 1, + turns: 2 + }, + predicted_n: 2 + }); + expect(agenticStore.getTotalToolCalls(CONV_ID)).toBe(1); + expect(agenticStore.isRunning(CONV_ID)).toBe(false); + }); + + it('waits for permission and tells the model when it is denied', async () => { + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + vi.mocked(permissionsStore.hasTool).mockReturnValue(false); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls(BuiltInTool.BROWSER_GET_DATETIME)), + (options) => options.onChunk?.('ok') + ); + const { callbacks, named } = recorder(); + const flow = runFlow(callbacks); + + await vi.waitFor(() => + expect(agenticStore.getPendingPermissionRequest(CONV_ID)).toEqual({ + serverLabel: 'Browser', + toolName: BuiltInTool.BROWSER_GET_DATETIME + }) + ); + agenticStore.resolvePermission(CONV_ID, ToolPermissionDecision.DENY); + await flow; + + expect(named('createToolResultMessage')[0].slice(1)).toEqual([ + 'call_0', + 'Tool execution was denied by the user.', + undefined + ]); + expect(requests[1][2]).toMatchObject({ content: 'Tool execution was denied by the user.' }); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { toolCalls: [{ success: false }] } + }); + }); + + it('reports a failing tool to the model and goes on', async () => { + mockTools(ToolSource.SERVER, 'read_file'); + vi.spyOn(ToolsService, 'executeTool').mockRejectedValue(new Error('no such file')); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('read_file')), + (options) => options.onChunk?.('sorry') + ); + const { callbacks } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(requests[1][2]).toMatchObject({ content: 'Error: no such file', role: 'tool' }); + }); + + it('shows the output of a streaming tool while it runs', async () => { + mockTools(ToolSource.SERVER, BuiltInTool.SERVER_EXEC_SHELL_COMMAND); + vi.spyOn(ToolsService, 'streamTool').mockImplementation(async function* () { + yield { chunk: 'one\n', done: false }; + await new Promise((resolve) => setTimeout(resolve, 0)); + yield { chunk: 'two\n', done: false }; + await new Promise((resolve) => setTimeout(resolve, 0)); + yield { chunk: null, done: true }; + }); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls(BuiltInTool.SERVER_EXEC_SHELL_COMMAND)), + (options) => options.onChunk?.('done') + ); + const { callbacks, named } = recorder(); + + await runFlow(callbacks); + + // created empty when the tool starts, then rewritten in place: never created twice + expect(named('createToolResultMessage').map((call) => call.slice(1))).toEqual([ + ['call_0', '', undefined, undefined] + ]); + expect(named('updateToolResultMessage').map((call) => call.slice(1))).toEqual([ + ['msg_0', 'one\n'], + ['msg_0', 'one\ntwo\n'] + ]); + expect(requests[1][2]).toMatchObject({ content: 'one\ntwo\n', role: 'tool' }); + }); + + it('takes an image out of a tool result and sends it to a model with vision', async () => { + mockTools(ToolSource.SERVER, 'screenshot'); + vi.spyOn(ToolsService, 'executeTool').mockResolvedValue({ + content: `saved\n${IMAGE_DATA_URI}`, + isError: false + }); + vi.spyOn(modelsStore.props, 'modelSupportsVision').mockReturnValue(true); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('screenshot')), + (options) => options.onChunk?.('here') + ); + const { callbacks, named } = recorder(); + + await runFlow(callbacks); + + const [, , content, extras] = named('createToolResultMessage')[0]; + + expect(content).toMatch(/^saved\n\[Attachment saved: .+\.png\]$/); + expect(extras).toMatchObject([{ base64Url: IMAGE_DATA_URI, type: 'IMAGE' }]); + expect(named('onAttachments')[0].slice(1)).toEqual(['msg_0', extras]); + expect(requests[1][2]).toEqual({ + content: [ + { text: content, type: 'text' }, + { image_url: { url: IMAGE_DATA_URI }, type: 'image_url' } + ], + role: 'tool', + tool_call_id: 'call_0' + }); + }); + + it('leaves the flow when a steering message is queued, skipping the tool calls left', async () => { + mockTools(ToolSource.SERVER, 'first', 'second'); + vi.spyOn(ToolsService, 'executeTool').mockImplementation(async () => { + agenticStore.injectSteeringMessage(CONV_ID, 'wait'); + + return { content: 'first ran', isError: false }; + }); + + const requests = mockTurns((options) => + options.onToolCallChunk?.(toolCalls('first', 'second')) + ); + const { callbacks, named, names } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(named('createToolResultMessage').map((call) => call.slice(1, 3))).toEqual([ + ['call_0', 'first ran'], + ['call_1', 'Tool execution was interrupted by a new user message.'] + ]); + expect(names().slice(-2)).toEqual(['onTurnComplete', 'onFlowComplete']); + expect(requests).toHaveLength(1); + expect(agenticStore.consumePendingSteeringMessage(CONV_ID)).toMatchObject({ content: 'wait' }); + }); + + it('keeps the partial turn and reports the error when the stream fails', async () => { + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + mockTurns((options) => { + options.onChunk?.('par'); + + throw new Error('HTTP 500'); + }); + + const { callbacks, named, names } = recorder(); + const result = await runFlow(callbacks); + + expect(result).toMatchObject({ error: { message: 'HTTP 500' }, handled: true }); + expect(names()).toEqual(['onChunk', 'onAssistantTurnComplete', 'onFlowComplete', 'onError']); + expect(named('onAssistantTurnComplete')[0].slice(1)).toEqual([ + 'par', + undefined, + undefined, + undefined + ]); + expect(agenticStore.getLastError(CONV_ID)?.message).toBe('HTTP 500'); + }); + + it('stops without a tool result when the user aborts during a tool call', async () => { + const controller = new AbortController(); + + mockTools(ToolSource.SERVER, 'slow'); + vi.spyOn(ToolsService, 'executeTool').mockImplementation(async () => { + controller.abort(); + + return { content: 'late', isError: false }; + }); + + const requests = mockTurns((options) => options.onToolCallChunk?.(toolCalls('slow'))); + const { callbacks, named, names } = recorder(); + + expect(await runFlow(callbacks, controller.signal)).toEqual({ handled: true }); + expect(named('createToolResultMessage')).toEqual([]); + expect(names().slice(-1)).toEqual(['onFlowComplete']); + expect(requests).toHaveLength(1); + }); +}); + +describe('agentic flow with extensions', () => { + it('gets the providers ready, then runs a tool call through the provider of its source', async () => { + const order: string[] = []; + const execute = vi.fn(async () => { + order.push('execute'); + + return { content: 'found it', isError: false }; + }); + + await activateExtension({ + activate: (ctx) => + ctx.contribute( + 'tools', + makeProvider({ execute, prepare: async () => void order.push('prepare') }) + ) + }); + mockTools(ToolSource.MCP, 'search'); + vi.mocked(toolsStore.getEnabledToolsForLLM).mockImplementation(() => { + order.push('list'); + + return [{ function: { name: 'search', parameters: {} }, type: 'function' }]; + }); + + const controller = new AbortController(); + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('search')), + (options) => options.onChunk?.('done') + ); + const { callbacks, named } = recorder(); + + expect(await runFlow(callbacks, controller.signal)).toEqual({ handled: true }); + expect(order).toEqual(['prepare', 'list', 'execute']); + expect(execute.mock.calls[0][0]).toEqual({ arguments: '{}', id: 'call_0', name: 'search' }); + expect(execute.mock.calls[0][1]).toBeInstanceOf(AbortSignal); + expect(requests[1][2]).toMatchObject({ content: 'found it', role: 'tool' }); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { toolCalls: [{ name: 'search', success: true }] } + }); + }); + + it('reports a failing provider to the model and goes on', async () => { + await activateExtension({ + activate: (ctx) => + ctx.contribute( + 'tools', + makeProvider({ + execute: async () => { + throw new Error('server is down'); + } + }) + ) + }); + mockTools(ToolSource.MCP, 'search'); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('search')), + (options) => options.onChunk?.('sorry') + ); + + expect(await runFlow(recorder().callbacks)).toEqual({ handled: true }); + expect(requests[1][2]).toMatchObject({ content: 'Error: server is down', role: 'tool' }); + }); + + it('tells the model the tool is unknown when no extension provides its source', async () => { + mockTools(ToolSource.MCP, 'search'); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('search')), + (options) => options.onChunk?.('sorry') + ); + const { callbacks, named } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(requests[1][2]).toMatchObject({ content: 'Error: Unknown tool: search', role: 'tool' }); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { toolCalls: [{ name: 'search', success: false }] } + }); + }); + + it('is enabled by a configured provider alone', async () => { + vi.spyOn(toolsStore, 'browserTools', 'get').mockReturnValue([]); + + const config = () => agenticStore.getConfig({ agenticMaxTurns: 5 } as never); + + expect(config().enabled).toBe(false); + + await activateExtension({ + activate: (ctx) => ctx.contribute('tools', makeProvider({ isConfigured: () => false })) + }); + + expect(config().enabled).toBe(false); + + await activateExtension({ activate: (ctx) => ctx.contribute('tools', makeProvider()) }); + + expect(config().enabled).toBe(true); + }); + + it('runs the flow hooks around the flow, also when one of them fails', async () => { + const order: string[] = []; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await activateExtension({ + activate(ctx) { + ctx.contribute('flow', () => { + throw new Error('bad start'); + }); + ctx.contribute('flow', () => async () => { + order.push('failing end'); + + throw new Error('bad end'); + }); + ctx.contribute('flow', ({ conversationId }) => { + order.push(`start ${conversationId}`); + + return () => void order.push('end'); + }); + ctx.contribute('flow', () => void order.push('start without end')); + } + }); + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + mockTurns((options) => { + order.push(`turn, running: ${agenticStore.isRunning(CONV_ID)}`); + options.onChunk?.('hi'); + }); + + expect(await runFlow(recorder().callbacks)).toEqual({ handled: true }); + expect(order).toEqual([ + `start ${CONV_ID}`, + 'start without end', + 'turn, running: true', + 'failing end', + 'end' + ]); + expect(warn).toHaveBeenCalledTimes(2); + expect(agenticStore.isRunning(CONV_ID)).toBe(false); + }); + + it('runs the end of the flow hooks when the flow fails', async () => { + const end = vi.fn(); + + await activateExtension({ activate: (ctx) => ctx.contribute('flow', () => end) }); + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + mockTurns(() => { + throw new Error('HTTP 500'); + }); + + expect(await runFlow(recorder().callbacks)).toMatchObject({ handled: true }); + expect(end).toHaveBeenCalledOnce(); + }); + + it('leaves the flow hooks alone when no tool is enabled', async () => { + const hook = vi.fn(); + + await activateExtension({ activate: (ctx) => ctx.contribute('flow', hook) }); + vi.spyOn(toolsStore, 'getEnabledToolsForLLM').mockReturnValue([]); + + expect(await runFlow(recorder().callbacks)).toEqual({ handled: false }); + expect(hook).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/apps/chat/tests/unit/async-queue.test.ts b/ui/apps/chat/tests/unit/async-queue.test.ts new file mode 100644 index 000000000000..4856f74d3ba6 --- /dev/null +++ b/ui/apps/chat/tests/unit/async-queue.test.ts @@ -0,0 +1,42 @@ +import { createAsyncQueue } from '#lib/utils/async-queue.ts'; +import { describe, expect, it } from 'vitest'; + +async function collect(queue: AsyncIterable): Promise { + const items: T[] = []; + + for await (const item of queue) items.push(item); + + return items; +} + +describe('createAsyncQueue', () => { + it('yields the items pushed before and during the iteration, then ends on close', async () => { + const queue = createAsyncQueue(); + + queue.push(1); + + const collected = collect(queue); + + await Promise.resolve(); + queue.push(2); + queue.push(3); + queue.close(); + + expect(await collected).toEqual([1, 2, 3]); + }); + + it('throws the failure after the pushed items are read', async () => { + const queue = createAsyncQueue(); + const seen: number[] = []; + + queue.push(1); + queue.fail(new Error('cut')); + + await expect( + (async () => { + for await (const item of queue) seen.push(item); + })() + ).rejects.toThrow('cut'); + expect(seen).toEqual([1]); + }); +}); diff --git a/ui/apps/chat/tests/unit/chat-commands.test.ts b/ui/apps/chat/tests/unit/chat-commands.test.ts new file mode 100644 index 000000000000..206204d6cd9a --- /dev/null +++ b/ui/apps/chat/tests/unit/chat-commands.test.ts @@ -0,0 +1,95 @@ +// The `/` picker lists the built-in commands with the ones extensions +// contribute around them; without contributions only the built-in ones remain. + +import type { ComposerCommand, ComposerHandle } from '#lib/extensions/index.ts'; +import { getChatCommands } from '#lib/utils/chat-commands.ts'; +import type { Component } from 'svelte'; +import { describe, expect, it, vi } from 'vitest'; + +const OPTIONS = { canCompact: () => true, hasCwdTools: () => true, showModelSelector: true }; +const icon = (() => {}) as unknown as Component; + +function makeCommand(overrides: Partial = {}): ComposerCommand { + return { + description: 'A contributed command', + icon, + isEnabled: () => true, + name: 'extra', + run: () => {}, + ...overrides + }; +} + +const names = (contributed?: ComposerCommand[]) => + getChatCommands(OPTIONS, contributed).map((command) => command.name); + +describe('getChatCommands', () => { + it('lists only the built-in commands without contributions', () => { + expect(names()).toEqual(['cwd', 'model', 'compact']); + expect(names([])).toEqual(['cwd', 'model', 'compact']); + }); + + it('sorts a command with an order below zero before the built-in ones', () => { + expect(names([makeCommand({ name: 'prompt', order: -1 })])).toEqual([ + 'prompt', + 'cwd', + 'model', + 'compact' + ]); + }); + + it('sorts a command without an order after the built-in ones', () => { + expect(names([makeCommand()])).toEqual(['cwd', 'model', 'compact', 'extra']); + }); + + it('sorts contributed commands among themselves by order', () => { + const contributed = [ + makeCommand({ name: 'last', order: 5 }), + makeCommand({ name: 'second', order: -1 }), + makeCommand({ name: 'after', order: 0 }), + makeCommand({ name: 'first', order: -2 }) + ]; + + expect(names(contributed)).toEqual([ + 'first', + 'second', + 'cwd', + 'model', + 'compact', + 'after', + 'last' + ]); + }); + + it('keeps a command that is not enabled in the list, disabled', () => { + let enabled = false; + + const contributed = [makeCommand({ isEnabled: () => enabled })]; + + expect(getChatCommands(OPTIONS, contributed).at(-1)?.disabled).toBe(true); + + enabled = true; + + expect(getChatCommands(OPTIONS, contributed).at(-1)?.disabled).toBe(false); + }); + + it('carries what a contributed command shows and does', () => { + const run = vi.fn(); + const [command] = getChatCommands(OPTIONS, [ + makeCommand({ keywords: ['more'], order: -1, run }) + ]); + const composer = {} as ComposerHandle; + + if (!('run' in command)) throw new Error('not a contributed command'); + + command.run(composer, ' args '); + + expect(command).toMatchObject({ + description: 'A contributed command', + icon, + keywords: ['more'], + name: 'extra' + }); + expect(run).toHaveBeenCalledWith(composer, ' args '); + }); +}); diff --git a/ui/apps/chat/tests/unit/cli.test.ts b/ui/apps/chat/tests/unit/cli.test.ts index d55be9a8f151..572f47ffd84f 100644 --- a/ui/apps/chat/tests/unit/cli.test.ts +++ b/ui/apps/chat/tests/unit/cli.test.ts @@ -1,4 +1,13 @@ -import { buildStatic, createChatServer, DEFAULTS, parseCliArgs } from '../../cli/server.js'; +import { + buildStatic, + createChatServer, + DEFAULTS, + parseCliArgs, + parseServerUrl, + PRESET_FILE, + PRESET_META, + withPresetMeta +} from '../../cli/server.js'; import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; import http from 'node:http'; import type { AddressInfo } from 'node:net'; @@ -14,6 +23,9 @@ function listen(server: http.Server): Promise { }); } +/** A built index.html in short: the CLI adds its marker for llama-chat.json before ``. */ +const INDEX = 'Llama Chat'; + function close(server: http.Server): Promise { return new Promise((resolve) => server.close(() => resolve())); } @@ -25,6 +37,7 @@ describe('llama-chat CLI arguments', () => { expect(options.host).toBe(DEFAULTS.host); expect(options.port).toBe(DEFAULTS.port); expect(options.open).toBe(true); + expect(options.servers).toEqual([]); }); it('reads the documented flags', () => { @@ -42,8 +55,30 @@ describe('llama-chat CLI arguments', () => { expect(() => parseCliArgs(['--nope'])).toThrow(); expect(() => parseCliArgs(['--port', 'abc'])).toThrow(/invalid --port/); expect(() => parseCliArgs(['--port', '70000'])).toThrow(/invalid --port/); - // it forwards nothing, so there is no llama-server to name - expect(() => parseCliArgs(['--server', 'http://127.0.0.1:9931'])).toThrow(); + }); + + it('takes --server more than once, for serving and for build alike', () => { + expect( + parseCliArgs(['--server', 'localhost:9931', '--server', 'https://llm.example.com/api/']) + .servers + ).toEqual(['http://localhost:9931', 'https://llm.example.com/api']); + expect(parseCliArgs(['build', '--server', '127.0.0.1:9931']).servers).toEqual([ + 'http://127.0.0.1:9931' + ]); + }); + + it('puts the marker for llama-chat.json in the head of index.html once', () => { + const once = withPresetMeta(INDEX); + + expect(once).toContain(`${PRESET_META}\n\t`); + expect(withPresetMeta(once)).toBe(once); + }); + + it('refuses a server address the app could not use', () => { + expect(() => parseServerUrl('ftp://localhost')).toThrow(/invalid --server/); + expect(() => parseServerUrl('http://localhost:9931/?key=1')).toThrow(/invalid --server/); + expect(() => parseServerUrl('http://user:pass@localhost:9931')).toThrow(/invalid --server/); + expect(() => parseServerUrl('http://')).toThrow(/invalid --server/); }); it('reads build with its own flags, and keeps serving flags out of it', () => { @@ -85,7 +120,7 @@ describe('llama-chat build', () => { dist = await mkdtemp(join(tmpdir(), 'llama-chat-dist-')); work = await mkdtemp(join(tmpdir(), 'llama-chat-out-')); await mkdir(join(dist, '_app'), { recursive: true }); - await writeFile(join(dist, 'index.html'), ''); + await writeFile(join(dist, 'index.html'), INDEX); await writeFile(join(dist, '_app', 'app.js'), 'export {};'); await writeFile(join(dist, '_app', 'app.js.map'), '{}'); }); @@ -103,6 +138,23 @@ describe('llama-chat build', () => { join('_app', 'app.js'), 'index.html' ]); + // without servers there is no llama-chat.json, so nothing points the app at one + expect(await readFile(join(out, 'index.html'), 'utf8')).toBe(INDEX); + }); + + it('writes the servers to llama-chat.json when given', async () => { + const out = await buildStatic({ + distDir: dist, + out: join(work, 'with-servers'), + servers: ['http://127.0.0.1:9931'] + }); + + expect(JSON.parse(await readFile(join(out, PRESET_FILE), 'utf8'))).toEqual({ + servers: [{ url: 'http://127.0.0.1:9931' }] + }); + expect(await readFile(join(out, 'index.html'), 'utf8')).toContain(PRESET_META); + // the copy in dist keeps no marker + expect(await readFile(join(dist, 'index.html'), 'utf8')).toBe(INDEX); }); it('refuses a folder that is not empty unless forced', async () => { @@ -114,7 +166,7 @@ describe('llama-chat build', () => { await expect(buildStatic({ distDir: dist, out })).rejects.toThrow(/not empty/); await buildStatic({ distDir: dist, force: true, out }); expect(await readFile(join(out, 'keep.txt'), 'utf8')).toBe('mine'); - expect(await readFile(join(out, 'index.html'), 'utf8')).toBe(''); + expect(await readFile(join(out, 'index.html'), 'utf8')).toBe(INDEX); }); it('refuses to write into the app files themselves', async () => { @@ -135,7 +187,7 @@ describe('llama-chat server', () => { beforeAll(async () => { dist = await mkdtemp(join(tmpdir(), 'llama-chat-dist-')); await mkdir(join(dist, '_app', 'immutable'), { recursive: true }); - await writeFile(join(dist, 'index.html'), 'Llama Chat'); + await writeFile(join(dist, 'index.html'), INDEX); await writeFile(join(dist, 'sw.js'), 'self;'); await writeFile(join(dist, 'service-worker.js'), 'self;'); await writeFile(join(dist, '_app', 'immutable', 'app.abc123.js'), 'export {};'); @@ -157,7 +209,7 @@ describe('llama-chat server', () => { expect(res.headers.get('cache-control')).toBe('no-cache'); expect(res.headers.get('cross-origin-embedder-policy')).toBe('require-corp'); expect(res.headers.get('cross-origin-opener-policy')).toBe('same-origin'); - expect(await res.text()).toContain('Llama Chat'); + expect(await res.text()).toContain(PRESET_META); const again = await fetch(`${chatUrl}/`, { headers: { 'If-None-Match': res.headers.get('etag') ?? '' } @@ -181,6 +233,31 @@ describe('llama-chat server', () => { expect(worker.headers.get('cache-control')).toBe('no-cache'); }); + it('serves llama-chat.json, revalidated, with no servers when none are given', async () => { + const empty = await fetch(`${chatUrl}/${PRESET_FILE}`); + + expect(empty.status).toBe(200); + expect(await empty.json()).toEqual({ servers: [] }); + + const withServers = createChatServer({ + distDir: dist, + servers: ['http://127.0.0.1:9931', 'https://llm.example.com'] + }); + const url = await listen(withServers); + + try { + const res = await fetch(`${url}/${PRESET_FILE}`); + + expect(res.status).toBe(200); + expect(res.headers.get('cache-control')).toBe('no-cache'); + expect(await res.json()).toEqual({ + servers: [{ url: 'http://127.0.0.1:9931' }, { url: 'https://llm.example.com' }] + }); + } finally { + await close(withServers); + } + }); + it('forwards nothing: API paths are not found and other methods are refused', async () => { const props = await fetch(`${chatUrl}/props`); diff --git a/ui/apps/chat/tests/unit/composer-attachments-send.test.ts b/ui/apps/chat/tests/unit/composer-attachments-send.test.ts new file mode 100644 index 000000000000..8a48228bd9c1 --- /dev/null +++ b/ui/apps/chat/tests/unit/composer-attachments-send.test.ts @@ -0,0 +1,142 @@ +// Attachments an extension holds outside the chat form (MCP's resources) go +// with the message that is sent, once: a message queued behind a busy chat +// leaves them where they are, and without the extension nothing is added. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: { + getConversation: vi.fn(), + getConversationMessages: vi.fn(), + updateConversation: vi.fn(), + updateCurrentNode: vi.fn() + } +})); + +import { AttachmentType } from '#lib/enums/index.ts'; +import type { ComposerAttachments } from '#lib/extensions/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { DatabaseService } from '#lib/services/database.service.ts'; +import { chatStore } from '#lib/stores/chat/index.svelte.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import type { DatabaseMessageExtra } from '#lib/types/index.ts'; +import type { Component } from 'svelte'; + +const CONV_ID = 'conv-a'; +const OWN: DatabaseMessageExtra = { + content: 'notes', + name: 'notes.txt', + type: AttachmentType.TEXT +}; +const PENDING: DatabaseMessageExtra = { + content: 'readme', + name: 'README.md', + serverName: 'github', + type: AttachmentType.MCP_RESOURCE, + uri: 'repo://README.md' +}; + +// what the extension holds until a message is sent +let held: DatabaseMessageExtra[] = []; + +const source: ComposerAttachments = { + component: (() => {}) as unknown as Component, + consume: vi.fn(() => { + const extras = held; + + held = []; + + return extras; + }), + hasPending: () => held.length > 0 +}; + +extensions.register({ + description: 'Holds attachments outside the chat form', + id: 'test-attachments', + load: async () => ({ + default: { + activate(ctx) { + ctx.contribute('composerAttachments', source); + } + } + }), + name: 'Test attachments' +}); + +/** Send up to the point where the user message is stored, and return the extras it got. */ +async function sendAndCaptureExtras(extras?: DatabaseMessageExtra[]) { + const addMessage = vi + .spyOn(chatStore, 'addMessage') + .mockRejectedValue(new DOMException('stop here', 'AbortError')); + + await chatStore.sendMessage('hello', extras); + + return addMessage.mock.lastCall?.[4]; +} + +beforeEach(async () => { + vi.restoreAllMocks(); + vi.mocked(source.consume).mockClear(); + held = []; + chatStore.clearPendingMessage(CONV_ID); + + vi.mocked(DatabaseService.getConversation).mockResolvedValue({ + currNode: null, + id: CONV_ID, + lastModified: 1000, + name: CONV_ID + }); + vi.mocked(DatabaseService.getConversationMessages).mockResolvedValue([]); + + expect(await conversationsStore.loadConversation(CONV_ID)).toBe(true); + + await extensions.setEnabled('test-attachments', true); +}); + +describe('pending composer attachments on send', () => { + it('appends them to the extras of the message and clears their source', async () => { + held = [PENDING]; + + expect(await sendAndCaptureExtras([OWN])).toEqual([OWN, PENDING]); + expect(source.consume).toHaveBeenCalledTimes(1); + expect(source.hasPending()).toBe(false); + }); + + it('sends them with a message that has no extras of its own', async () => { + held = [PENDING]; + + expect(await sendAndCaptureExtras()).toEqual([PENDING]); + }); + + it('leaves the extras of the message as they are when nothing is pending', async () => { + const own = [OWN]; + + expect(await sendAndCaptureExtras(own)).toBe(own); + expect(await sendAndCaptureExtras()).toBeUndefined(); + }); + + it('keeps them for the next send when the message is queued behind a busy chat', async () => { + held = [PENDING]; + chatStore.setChatLoading(CONV_ID, true); + + try { + await chatStore.sendMessage('queued', [OWN]); + } finally { + chatStore.setChatLoading(CONV_ID, false); + } + + expect(source.consume).not.toHaveBeenCalled(); + expect(source.hasPending()).toBe(true); + expect(chatStore.getPendingMessageContent(CONV_ID)).toBe('queued'); + }); + + it('adds nothing once the extension is off', async () => { + held = [PENDING]; + await extensions.setEnabled('test-attachments', false); + + expect(await sendAndCaptureExtras([OWN])).toEqual([OWN]); + expect(source.consume).not.toHaveBeenCalled(); + expect(source.hasPending()).toBe(true); + }); +}); diff --git a/ui/apps/chat/tests/unit/conversation-tree.test.ts b/ui/apps/chat/tests/unit/conversation-tree.test.ts new file mode 100644 index 000000000000..b5cd901a2407 --- /dev/null +++ b/ui/apps/chat/tests/unit/conversation-tree.test.ts @@ -0,0 +1,143 @@ +// Pure fork-tree and message-tree rules that every storage backend relies on. + +import { + CONFIG_LOCALSTORAGE_KEY, + SIDEBAR_WIDTH_LOCALSTORAGE_KEY, + STREAM_RESUME_LOCALSTORAGE_KEY_PREFIX +} from '#lib/constants/index.ts'; +import { MessageRole, MessageType, PreferenceScope } from '#lib/enums/index.ts'; +import { PreferencesService } from '#lib/services/preferences.service.ts'; +import type { DatabaseConversation, DatabaseMessage } from '#lib/types/database.js'; +import { + buildForkedConversation, + collectForkDescendantIds, + groupMessagesByConversation, + reparentDirectForks +} from '#lib/utils/conversation-tree.ts'; +import { describe, expect, it } from 'vitest'; + +function conv(id: string, forkedFrom?: string): DatabaseConversation { + return { currNode: '', forkedFromConversationId: forkedFrom, id, lastModified: 0, name: id }; +} + +function msg( + id: string, + parent: string | null, + children: string[] = [], + timestamp = 0 +): DatabaseMessage { + return { + children, + content: id, + convId: 'c1', + extra: [], + id, + parent, + role: MessageRole.USER, + timestamp, + type: MessageType.TEXT + } as DatabaseMessage; +} + +describe('collectForkDescendantIds', () => { + it('collects forks at every depth, not the root itself', () => { + const convs = [conv('a'), conv('b', 'a'), conv('c', 'b'), conv('d', 'a'), conv('x')]; + + expect(collectForkDescendantIds(convs, 'a').sort()).toEqual(['b', 'c', 'd']); + }); +}); + +describe('reparentDirectForks', () => { + it('moves direct forks to the parent of the deleted conversation', () => { + const convs = [conv('a'), conv('b', 'a'), conv('c', 'b')]; + + expect(reparentDirectForks(convs, 'b')).toEqual([conv('c', 'a')]); + }); + + it('skips ancestors deleted in the same batch and drops forks being deleted', () => { + const convs = [conv('a'), conv('b', 'a'), conv('c', 'b'), conv('d', 'c'), conv('e', 'c')]; + + expect(reparentDirectForks(convs, 'c', new Set(['b', 'c', 'e']))).toEqual([conv('d', 'a')]); + }); + + it('promotes forks to top-level when the ancestry loops', () => { + const convs = [conv('a', 'b'), conv('b', 'a'), conv('c', 'a')]; + + expect(reparentDirectForks(convs, 'a', new Set(['a', 'b']))).toEqual([conv('c', undefined)]); + }); + + it('returns nothing for an unknown conversation', () => { + expect(reparentDirectForks([conv('a')], 'missing')).toEqual([]); + }); +}); + +describe('buildForkedConversation', () => { + // root -> u1 -> a1, with a sibling branch u1 -> a2 + const messages = [ + msg('root', null, ['u1'], 0), + msg('u1', 'root', ['a1', 'a2'], 1), + msg('a1', 'u1', [], 2), + msg('a2', 'u1', [], 3) + ]; + + it('clones the path to the target with fresh, consistently remapped ids', () => { + const { conv: fork, messages: cloned } = buildForkedConversation(conv('src'), messages, 'a1', { + includeAttachments: true, + name: 'Fork' + }); + + expect(fork.forkedFromConversationId).toBe('src'); + expect(fork.name).toBe('Fork'); + expect(cloned.map((m) => m.content)).toEqual(['root', 'u1', 'a1']); + expect(cloned.every((m) => m.convId === fork.id)).toBe(true); + expect(fork.currNode).toBe(cloned[2].id); + + const [root, u1, a1] = cloned; + + expect(root.parent).toBeNull(); + expect(root.children).toEqual([u1.id]); + expect(u1.parent).toBe(root.id); + expect(u1.children).toEqual([a1.id]); + expect(new Set(cloned.map((m) => m.id)).size).toBe(3); + expect(cloned.some((m) => messages.some((orig) => orig.id === m.id))).toBe(false); + expect(a1.extra).toEqual([]); + }); + + it('drops attachments when asked to', () => { + const { messages: cloned } = buildForkedConversation(conv('src'), messages, 'a1', { + includeAttachments: false, + name: 'Fork' + }); + + expect(cloned.every((m) => m.extra === undefined)).toBe(true); + }); + + it('throws when there are no messages to fork', () => { + expect(() => + buildForkedConversation(conv('src'), [], 'a1', { includeAttachments: true, name: 'Fork' }) + ).toThrow(); + }); +}); + +describe('groupMessagesByConversation', () => { + it('groups by conversation, oldest first', () => { + const groups = groupMessagesByConversation([ + { ...msg('b2', null, [], 2), convId: 'b' }, + { ...msg('a2', null, [], 2), convId: 'a' }, + { ...msg('b1', null, [], 1), convId: 'b' } + ]); + + expect(groups.get('a')?.map((m) => m.id)).toEqual(['a2']); + expect(groups.get('b')?.map((m) => m.id)).toEqual(['b1', 'b2']); + }); +}); + +describe('PreferencesService.scopeOf', () => { + it('classifies user data and device-local keys', () => { + expect(PreferencesService.scopeOf(CONFIG_LOCALSTORAGE_KEY)).toBe(PreferenceScope.USER); + expect(PreferencesService.scopeOf(SIDEBAR_WIDTH_LOCALSTORAGE_KEY)).toBe(PreferenceScope.DEVICE); + expect(PreferencesService.scopeOf(`${STREAM_RESUME_LOCALSTORAGE_KEY_PREFIX}conv-a`)).toBe( + PreferenceScope.DEVICE + ); + }); +}); diff --git a/ui/apps/chat/tests/unit/document-store-backend.test.ts b/ui/apps/chat/tests/unit/document-store-backend.test.ts new file mode 100644 index 000000000000..90cb075552ae --- /dev/null +++ b/ui/apps/chat/tests/unit/document-store-backend.test.ts @@ -0,0 +1,291 @@ +// DocumentStoreBackend against an in-memory adapter with the same revision +// rules as llama-server's store (tools/server/server-storage.cpp). + +import { MessageRole, MessageType } from '#lib/enums/index.ts'; +import { DatabaseService } from '#lib/services/database.service.ts'; +import { DocumentStoreBackend } from '#lib/services/document-store-backend.ts'; +import { PreferencesService } from '#lib/services/preferences.service.ts'; +import { LlamaServerStorageAdapter, StorageConflictError } from '#lib/storage-adapters/index.ts'; +import type { DatabaseMessage } from '#lib/types/database.js'; +import type { StorageAdapter, StoredConversation } from '#lib/types/index.ts'; +import { ApiError } from '#lib/utils/api-fetch.ts'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const apiFetch = vi.hoisted(() => vi.fn()); + +vi.mock('#lib/utils/api-fetch.ts', async (importOriginal) => ({ + ...(await importOriginal()), + apiFetch +})); + +const docs = new Map(); +const records = new Map>(); +const writes: string[] = []; +const memoryAdapter: StorageAdapter = { + async deleteConversation(id) { + writes.push(`delete ${id}`); + docs.delete(id); + }, + async getConversation(id) { + const doc = docs.get(id); + + return doc ? structuredClone(doc) : null; + }, + async getSettings() { + return {}; + }, + async listConversations() { + return [...docs.values()].map(({ conv, rev }) => structuredClone({ conv, rev })); + }, + async listRecords(kind) { + return structuredClone([...(records.get(kind)?.values() ?? [])]) as never; + }, + async putConversation(doc) { + const current = docs.get(doc.conv.id)?.rev ?? 0; + + if (doc.rev !== current) throw new StorageConflictError(doc.conv.id); + + writes.push(`put ${doc.conv.id}`); + docs.set(doc.conv.id, structuredClone({ ...doc, rev: current + 1 })); + + return current + 1; + }, + async updateRecords(kind, set, remove) { + const stored = records.get(kind) ?? new Map(); + + writes.push(`records ${kind}`); + for (const record of set) stored.set(record.id, structuredClone(record)); + for (const id of remove) stored.delete(id); + records.set(kind, stored); + }, + async updateSettings() {} +}; +const newBackend = () => new DocumentStoreBackend(memoryAdapter); + +function userMessage(convId: string, content: string): Omit { + return { + children: [], + content, + convId, + parent: null, + role: MessageRole.USER, + timestamp: Date.now(), + type: MessageType.TEXT + }; +} + +beforeEach(() => { + docs.clear(); + records.clear(); + writes.length = 0; +}); + +describe('DocumentStoreBackend', () => { + it('writes one document per conversation with the tree DatabaseService builds', async () => { + DatabaseService.useBackend(newBackend()); + + const conv = await DatabaseService.createConversation('a'); + const rootId = await DatabaseService.createRootMessage(conv.id); + const user = await DatabaseService.createMessageBranch(userMessage(conv.id, 'hi'), rootId); + const stored = docs.get(conv.id)!; + const messages = stored.messages as DatabaseMessage[]; + + expect(stored.rev).toBe(3); + expect(messages.find((m) => m.id === rootId)?.children).toEqual([user.id]); + expect((stored.conv as { currNode: string }).currNode).toBe(user.id); + }); + + it('replays its edits on a document another client changed meanwhile', async () => { + DatabaseService.useBackend(newBackend()); + + const conv = await DatabaseService.createConversation('a'); + const rootId = await DatabaseService.createRootMessage(conv.id); + const first = await DatabaseService.createMessageBranch(userMessage(conv.id, 'one'), rootId); + const second = await DatabaseService.createMessageBranch(userMessage(conv.id, 'two'), rootId); + // two tabs with the conversation open + const tabA = newBackend(); + const tabB = newBackend(); + + await tabA.getMessages([conv.id]); + await tabB.getMessages([conv.id]); + await tabA.updateMessage(first.id, { content: 'one, edited in A' }); + await tabB.updateMessage(second.id, { content: 'two, edited in B' }); + + const messages = docs.get(conv.id)!.messages as DatabaseMessage[]; + + expect(messages.find((m) => m.id === first.id)?.content).toBe('one, edited in A'); + expect(messages.find((m) => m.id === second.id)?.content).toBe('two, edited in B'); + }); + + it('restores the cached document when a transaction fails', async () => { + const backend = newBackend(); + + DatabaseService.useBackend(backend); + + const conv = await DatabaseService.createConversation('a'); + const rootId = await DatabaseService.createRootMessage(conv.id); + + writes.length = 0; + + await expect( + backend.transaction(async () => { + await backend.updateMessage(rootId, { content: 'changed' }); + + throw new Error('boom'); + }) + ).rejects.toThrow('boom'); + + expect((await backend.getMessage(rootId))?.content).toBe(''); + expect(writes).toEqual([]); + }); + + it('saves a write that joined a transaction which closed while it loaded', async () => { + DatabaseService.useBackend(newBackend()); + + const a = await DatabaseService.createConversation('a'); + const b = await DatabaseService.createConversation('b'); + const backend = newBackend(); + + let joined: Promise = Promise.resolve(); + + await backend.transaction(async () => { + await backend.updateConversation(a.id, { name: 'a2' }); + // not awaited: still loading b when the transaction ends + joined = backend.updateConversation(b.id, { name: 'b2' }); + }); + await joined; + + expect((docs.get(a.id)!.conv as { name: string }).name).toBe('a2'); + expect((docs.get(b.id)!.conv as { name: string }).name).toBe('b2'); + }); + + it('deletes a conversation document and drops it from the list', async () => { + DatabaseService.useBackend(newBackend()); + + const keep = await DatabaseService.createConversation('keep'); + const drop = await DatabaseService.createConversation('drop'); + + await DatabaseService.deleteConversation(drop.id); + + expect(docs.has(drop.id)).toBe(false); + expect((await DatabaseService.getAllConversations()).map((c) => c.id)).toEqual([keep.id]); + }); +}); + +describe('DocumentStoreBackend records', () => { + // groups list newest first by creation + const group = (id: string, createdAt: number) => ({ + createdAt, + id, + name: id, + updatedAt: createdAt + }); + + it('keeps groups per id, so two clients editing different groups both keep theirs', async () => { + DatabaseService.useBackend(newBackend()); + + await DatabaseService.createGroup(group('a', 1)); + await DatabaseService.createGroup(group('b', 2)); + + const tabA = newBackend(); + const tabB = newBackend(); + + await tabA.listRecords('groups'); + await tabB.listRecords('groups'); + await tabA.updateRecord('groups', 'a', { name: 'renamed in A' }); + await tabB.updateRecord('groups', 'b', { name: 'renamed in B' }); + + expect((await DatabaseService.getAllGroups()).map((g) => g.name)).toEqual([ + 'renamed in B', + 'renamed in A' + ]); + }); + + it('takes a deleted group off its conversations in one transaction', async () => { + DatabaseService.useBackend(newBackend()); + + await DatabaseService.createGroup(group('g', 1)); + + const conv = await DatabaseService.createConversation('a'); + + await DatabaseService.updateConversation(conv.id, { groupId: 'g' }); + writes.length = 0; + await DatabaseService.deleteGroup('g'); + + expect(records.get('groups')?.has('g')).toBe(false); + expect((docs.get(conv.id)!.conv as { groupId?: string }).groupId).toBeUndefined(); + expect(writes).toEqual(['records groups', `put ${conv.id}`]); + }); + + it('restores cached records when a transaction fails', async () => { + const backend = newBackend(); + + DatabaseService.useBackend(backend); + await DatabaseService.createGroup(group('g', 1)); + writes.length = 0; + + await expect( + backend.transaction(async () => { + await backend.updateRecord('groups', 'g', { name: 'changed' }); + + throw new Error('boom'); + }) + ).rejects.toThrow('boom'); + + await expect(backend.addRecord('groups', group('g', 2))).rejects.toThrow('already exists'); + expect(writes).toEqual([]); + expect(records.get('groups')?.get('g')).toMatchObject({ name: 'g' }); + }); +}); + +describe('PreferencesService remote mode', () => { + it('keeps user data on the remote and device state local, batching writes', async () => { + const store = new Map(); + const push = vi.fn(async () => {}); + + (globalThis as unknown as { localStorage: Partial }).localStorage = { + getItem: (key) => store.get(key) ?? null, + removeItem: (key) => void store.delete(key), + setItem: (key, value) => void store.set(key, value) + }; + + PreferencesService.useRemote({ 'LlamaUi.favoriteModels': '["a"]' }, push); + + expect(PreferencesService.getItem('LlamaUi.favoriteModels')).toBe('["a"]'); + + PreferencesService.setItem('LlamaUi.favoriteModels', '["b"]'); + PreferencesService.setItem('LlamaUi.hiddenModels', '["c"]'); + PreferencesService.removeItem('LlamaUi.recentModels'); + PreferencesService.setItem('LlamaUi.sidebarWidth', '300'); + + await Promise.resolve(); + await Promise.resolve(); + + expect(push).toHaveBeenCalledTimes(1); + expect(push).toHaveBeenCalledWith( + { 'LlamaUi.favoriteModels': '["b"]', 'LlamaUi.hiddenModels': '["c"]' }, + ['LlamaUi.recentModels'] + ); + expect(store.get('LlamaUi.sidebarWidth')).toBe('300'); + expect(store.has('LlamaUi.favoriteModels')).toBe(false); + }); +}); + +describe('LlamaServerStorageAdapter', () => { + it('maps the server answers onto the adapter contract', async () => { + const adapter = new LlamaServerStorageAdapter(); + const conv = { currNode: null, id: 'a', lastModified: 0, name: 'a' }; + + apiFetch.mockRejectedValueOnce(new ApiError('not found', 404)); + expect(await adapter.getConversation('a')).toBeNull(); + + apiFetch.mockRejectedValueOnce(new ApiError('conflict', 409)); + await expect(adapter.putConversation({ conv, messages: [], rev: 0 })).rejects.toBeInstanceOf( + StorageConflictError + ); + + apiFetch.mockResolvedValueOnce({ rev: 1 }); + expect(await adapter.putConversation({ conv, messages: [], rev: 0 })).toBe(1); + expect(apiFetch).toHaveBeenLastCalledWith('./storage/conversations/a', expect.anything()); + }); +}); diff --git a/ui/apps/chat/tests/unit/extension-page-route.test.ts b/ui/apps/chat/tests/unit/extension-page-route.test.ts new file mode 100644 index 000000000000..595387e2285e --- /dev/null +++ b/ui/apps/chat/tests/unit/extension-page-route.test.ts @@ -0,0 +1,65 @@ +// The generic extension page route serves whatever page an active extension +// contributes for the path, and ends in the app's 404 for every other path. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('$app/env', () => ({ browser: true })); +vi.mock('#lib/stores/init.ts', () => ({ + loadAppRoute: vi.fn(async () => {}), + startExtensions: vi.fn(async () => {}) +})); + +import { load } from '../../src/routes/[extensionPage]/+page'; +import { extensions } from '#lib/extensions/index.ts'; +import { loadAppRoute, startExtensions } from '#lib/stores/init.ts'; +import type { Component } from 'svelte'; + +const Page = (() => {}) as unknown as Component; + +type LoadEvent = Parameters[0]; + +function loadPath(path: string) { + return load({ fetch, params: { extensionPage: path } } as unknown as LoadEvent); +} + +describe('extension page route', () => { + beforeEach(() => { + const data = new Map(); + + vi.stubGlobal('localStorage', { + getItem: (key: string) => data.get(key) ?? null, + setItem: (key: string, value: string) => void data.set(key, value) + }); + }); + + it('is the 404 for a path no extension has a page for, and the page once one has', async () => { + await expect(loadPath('fake-page')).rejects.toMatchObject({ + body: { message: 'Not Found' }, + status: 404 + }); + + extensions.register({ + description: 'A test extension', + id: 'fake-pages', + load: async () => ({ + default: { + activate(ctx) { + ctx.contribute('pages', { component: Page, path: 'fake-page', title: 'Fake' }); + } + } + }), + name: 'Fake pages' + }); + await extensions.activateEnabled(); + + await expect(loadPath('fake-page')).resolves.toBeUndefined(); + await expect(loadPath('other-page')).rejects.toMatchObject({ status: 404 }); + // the stores hydrate, the API key is checked and the extensions start before the path is looked up + expect(loadAppRoute).toHaveBeenCalledWith(fetch); + expect(startExtensions).toHaveBeenCalled(); + + await extensions.setEnabled('fake-pages', false); + + await expect(loadPath('fake-page')).rejects.toMatchObject({ status: 404 }); + }); +}); diff --git a/ui/apps/chat/tests/unit/extension-renderers.test.ts b/ui/apps/chat/tests/unit/extension-renderers.test.ts new file mode 100644 index 000000000000..c7c50cb9f8cb --- /dev/null +++ b/ui/apps/chat/tests/unit/extension-renderers.test.ts @@ -0,0 +1,230 @@ +// The core draws a message or an attachment itself unless an extension's +// renderer claims it. These pin how a renderer is picked, and what the core +// falls back to for the MCP attachment kinds when no renderer claims them. + +import { AttachmentType, MessageRole, MessageType, SpecialFileType } from '#lib/enums/index.ts'; +import type { + AttachmentRenderer, + AttachmentRendererProps, + Extension, + MessageRenderer, + MessageRendererProps +} from '#lib/extensions/index.ts'; +import { + ExtensionRegistry, + findAttachmentRenderer, + findMessageRenderer +} from '#lib/extensions/index.ts'; +import type { + ChatAttachmentDisplayItem, + DatabaseMessage, + DatabaseMessageExtra +} from '#lib/types/index.ts'; +import { getAttachmentDisplayItems } from '#lib/utils/attachment-display.ts'; +import { isTextFile } from '#lib/utils/attachment-type.ts'; +import type { Component } from 'svelte'; +import { describe, expect, it } from 'vitest'; + +const MCP_PROMPT: DatabaseMessageExtra = { + content: 'Review this file.', + name: 'code_review', + promptName: 'code_review', + serverName: 'github', + type: AttachmentType.MCP_PROMPT +}; +const MCP_RESOURCE: DatabaseMessageExtra = { + content: '# llama.cpp', + mimeType: 'text/markdown', + name: 'README.md', + serverName: 'filesystem', + type: AttachmentType.MCP_RESOURCE, + uri: 'file:///README.md' +}; +const TEXT: DatabaseMessageExtra = { + content: 'notes', + name: 'notes.txt', + type: AttachmentType.TEXT +}; +// never mounted here: only the identity of a renderer matters +const messageComponent = (() => {}) as unknown as Component; +const attachmentComponent = (() => {}) as unknown as Component; + +function makeMessage(fields: Partial = {}): DatabaseMessage { + return { + children: [], + content: '', + convId: 'conv-1', + id: 'message-1', + parent: null, + role: MessageRole.USER, + timestamp: 0, + type: MessageType.TEXT, + ...fields + }; +} + +function displayItems(attachments: DatabaseMessageExtra[]): ChatAttachmentDisplayItem[] { + return getAttachmentDisplayItems({ attachments }); +} + +describe('findMessageRenderer', () => { + const assistantOnly: MessageRenderer = { + component: messageComponent, + match: (message) => message.role === MessageRole.ASSISTANT + }; + const everything: MessageRenderer = { + component: messageComponent, + forkable: false, + match: () => true + }; + + it('finds nothing when no renderer is contributed', () => { + expect(findMessageRenderer([], makeMessage())).toBeUndefined(); + }); + + it('finds nothing when no renderer claims the message', () => { + expect(findMessageRenderer([assistantOnly], makeMessage())).toBeUndefined(); + }); + + it('picks the first renderer that claims the message', () => { + const assistant = makeMessage({ role: MessageRole.ASSISTANT }); + + expect(findMessageRenderer([assistantOnly, everything], assistant)).toBe(assistantOnly); + expect(findMessageRenderer([everything, assistantOnly], assistant)).toBe(everything); + expect(findMessageRenderer([assistantOnly, everything], makeMessage())).toBe(everything); + }); +}); + +describe('findAttachmentRenderer', () => { + const mcpPromptOnly: AttachmentRenderer = { + component: attachmentComponent, + match: (item) => item.attachment?.type === AttachmentType.MCP_PROMPT + }; + const everything: AttachmentRenderer = { component: attachmentComponent, match: () => true }; + + it('finds nothing when no renderer is contributed', () => { + const [item] = displayItems([MCP_PROMPT]); + + expect(findAttachmentRenderer([], item)).toBeUndefined(); + }); + + it('finds nothing when no renderer claims the item', () => { + const [item] = displayItems([TEXT]); + + expect(findAttachmentRenderer([mcpPromptOnly], item)).toBeUndefined(); + }); + + it('picks the first renderer that claims the item', () => { + const [prompt] = displayItems([MCP_PROMPT]); + const [text] = displayItems([TEXT]); + + expect(findAttachmentRenderer([mcpPromptOnly, everything], prompt)).toBe(mcpPromptOnly); + expect(findAttachmentRenderer([everything, mcpPromptOnly], prompt)).toBe(everything); + expect(findAttachmentRenderer([mcpPromptOnly, everything], text)).toBe(everything); + }); +}); + +describe('renderer contributions', () => { + it('are read from the registry while the extension is on, and gone once it is off', async () => { + const registry = new ExtensionRegistry(); + const messageRenderer: MessageRenderer = { component: messageComponent, match: () => true }; + const attachmentRenderer: AttachmentRenderer = { + component: attachmentComponent, + match: () => true + }; + const extension: Extension = { + activate(ctx) { + ctx.contribute('messageRenderers', messageRenderer); + ctx.contribute('attachmentRenderers', attachmentRenderer); + } + }; + const message = makeMessage(); + const [item] = displayItems([MCP_RESOURCE]); + + registry.register({ + description: 'A test extension', + id: 'test', + load: async () => ({ default: extension }), + name: 'Test' + }); + + expect( + findMessageRenderer(registry.contributions('messageRenderers'), message) + ).toBeUndefined(); + + await registry.activateEnabled(); + + expect(findMessageRenderer(registry.contributions('messageRenderers'), message)).toBe( + messageRenderer + ); + expect(findAttachmentRenderer(registry.contributions('attachmentRenderers'), item)).toBe( + attachmentRenderer + ); + + await registry.setEnabled('test', false); + + expect( + findMessageRenderer(registry.contributions('messageRenderers'), message) + ).toBeUndefined(); + expect( + findAttachmentRenderer(registry.contributions('attachmentRenderers'), item) + ).toBeUndefined(); + }); +}); + +describe('attachments no renderer claims', () => { + it('read as text files when they carry text, so the default chip and preview show them', () => { + expect(isTextFile(MCP_PROMPT)).toBe(true); + expect(isTextFile(MCP_RESOURCE)).toBe(true); + }); + + it('read as text files before they are sent too, once their text has loaded', () => { + const pending = { + file: new File([], 'loading'), + id: 'pending', + name: 'code_review', + size: 17, + type: SpecialFileType.MCP_PROMPT + }; + + expect(isTextFile(undefined, { ...pending, textContent: 'Review this file.' })).toBe(true); + expect(isTextFile(undefined, pending)).toBe(false); + // an upload of a kind the browser could not name is not one of the app's own kinds + expect(isTextFile(undefined, { ...pending, textContent: 'text', type: '' })).toBe(false); + expect( + isTextFile(undefined, { ...pending, textContent: 'text', type: 'application/x-unknown' }) + ).toBe(false); + }); + + it('keep their name and text as display items', () => { + const [resource, prompt] = displayItems([MCP_PROMPT, MCP_RESOURCE]); + + expect(prompt).toMatchObject({ name: 'code_review', textContent: 'Review this file.' }); + expect(resource).toMatchObject({ name: 'README.md', textContent: '# llama.cpp' }); + }); + + it('leave the built-in kinds as they were', () => { + expect(isTextFile(TEXT)).toBe(true); + expect( + isTextFile({ content: 'old', name: 'pasted', type: AttachmentType.LEGACY_CONTEXT }) + ).toBe(true); + expect( + isTextFile({ + base64Data: '', + content: 'page text', + name: 'doc.pdf', + processedAsImages: false, + type: AttachmentType.PDF + }) + ).toBe(false); + expect(isTextFile({ base64Url: '', name: 'a.png', type: AttachmentType.IMAGE })).toBe(false); + expect( + isTextFile({ + base64Data: '', + mimeType: 'audio/wav', + name: 'a.wav', + type: AttachmentType.AUDIO + }) + ).toBe(false); + }); +}); diff --git a/ui/apps/chat/tests/unit/extensions-registry.test.ts b/ui/apps/chat/tests/unit/extensions-registry.test.ts new file mode 100644 index 000000000000..16737e03475d --- /dev/null +++ b/ui/apps/chat/tests/unit/extensions-registry.test.ts @@ -0,0 +1,279 @@ +// The registry is the only door between the core and an extension: what an +// extension contributes must be there while it is on and gone, with its +// cleanup run, once it is off. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('$app/env', () => ({ browser: true })); + +import { EXTENSIONS_LOCALSTORAGE_KEY } from '#lib/constants/index.ts'; +import { ToolSource } from '#lib/enums/index.ts'; +import type { + Extension, + ExtensionManifest, + FlowHook, + ToolProvider +} from '#lib/extensions/index.ts'; +import { ExtensionRegistry } from '#lib/extensions/index.ts'; + +function makeStorage(initial: Record = {}) { + const data = new Map(Object.entries(initial)); + + return { + data, + getItem: (key: string) => data.get(key) ?? null, + setItem: (key: string, value: string) => void data.set(key, value) + }; +} + +function makeProvider(): ToolProvider { + return { + entries: () => [], + execute: async () => ({ content: '', isError: false }), + isConfigured: () => true, + source: ToolSource.MCP + }; +} + +function makeManifest( + extension: Extension, + overrides: Partial = {} +): ExtensionManifest { + return { + description: 'A test extension', + id: 'test', + load: async () => ({ default: extension }), + name: 'Test', + ...overrides + }; +} + +describe('ExtensionRegistry', () => { + let storage: ReturnType; + + beforeEach(() => { + storage = makeStorage(); + vi.stubGlobal('localStorage', storage); + }); + + it('holds what an active extension contributes, per point', async () => { + const registry = new ExtensionRegistry(); + const provider = makeProvider(); + const hook: FlowHook = () => {}; + + registry.register( + makeManifest({ + activate(ctx) { + ctx.contribute('tools', provider); + ctx.contribute('flow', hook); + } + }) + ); + + expect(registry.contributions('tools')).toEqual([]); + + await registry.activateEnabled(); + + expect(registry.contributions('tools')).toEqual([provider]); + expect(registry.contributions('flow')).toEqual([hook]); + expect(registry.extensions[0]).toMatchObject({ enabled: true, error: null, state: 'active' }); + expect(registry.isActive('test')).toBe(true); + }); + + it('does not load the code of an extension that is off', async () => { + const registry = new ExtensionRegistry(); + const load = vi.fn(async () => ({ default: { activate() {} } })); + + registry.register(makeManifest({ activate() {} }, { disabledByDefault: true, load })); + await registry.activateEnabled(); + + expect(load).not.toHaveBeenCalled(); + expect(registry.extensions[0]).toMatchObject({ enabled: false, state: 'inactive' }); + + await registry.setEnabled('test', true); + + expect(load).toHaveBeenCalledOnce(); + expect(registry.extensions[0]).toMatchObject({ enabled: true, state: 'active' }); + }); + + it('removes the contributions and runs the cleanup when switched off', async () => { + const registry = new ExtensionRegistry(); + const order: string[] = []; + + registry.register( + makeManifest({ + activate(ctx) { + ctx.contribute('tools', makeProvider()); + ctx.onDeactivate(() => void order.push('first')); + ctx.onDeactivate(async () => void order.push('second')); + } + }) + ); + await registry.activateEnabled(); + await registry.setEnabled('test', false); + + expect(registry.contributions('tools')).toEqual([]); + // last registered, first undone + expect(order).toEqual(['second', 'first']); + expect(registry.extensions[0]).toMatchObject({ enabled: false, state: 'inactive' }); + expect(registry.isActive('test')).toBe(false); + }); + + it('keeps only the contributions of the extensions that stay on', async () => { + const registry = new ExtensionRegistry(); + const kept = makeProvider(); + + registry.register( + makeManifest({ activate: (ctx) => ctx.contribute('tools', makeProvider()) }, { id: 'a' }) + ); + registry.register( + makeManifest({ activate: (ctx) => ctx.contribute('tools', kept) }, { id: 'b' }) + ); + await registry.activateEnabled(); + await registry.setEnabled('a', false); + + expect(registry.contributions('tools')).toEqual([kept]); + }); + + it('remembers the choice and applies it on the next start', async () => { + const first = new ExtensionRegistry(); + + first.register(makeManifest({ activate() {} })); + await first.setEnabled('test', false); + + expect(JSON.parse(storage.data.get(EXTENSIONS_LOCALSTORAGE_KEY) ?? '{}')).toEqual({ + test: false + }); + + const second = new ExtensionRegistry(); + const load = vi.fn(async () => ({ default: { activate() {} } })); + + second.register(makeManifest({ activate() {} }, { load })); + await second.activateEnabled(); + + expect(load).not.toHaveBeenCalled(); + expect(second.isEnabled('test')).toBe(false); + }); + + it('shows the stored choice as soon as the extension is known', () => { + storage.data.set(EXTENSIONS_LOCALSTORAGE_KEY, JSON.stringify({ test: false })); + + const registry = new ExtensionRegistry(); + + registry.register(makeManifest({ activate() {} })); + + expect(registry.extensions[0]).toMatchObject({ enabled: false, state: 'inactive' }); + }); + + it('keeps the choices in memory when it has no storage key', async () => { + storage.data.set(EXTENSIONS_LOCALSTORAGE_KEY, JSON.stringify({ test: false })); + + const registry = new ExtensionRegistry({ storageKey: null }); + + registry.register(makeManifest({ activate() {} })); + + expect(registry.isEnabled('test')).toBe(true); + + await registry.setEnabled('test', false); + + expect(registry.isEnabled('test')).toBe(false); + expect(storage.data.get(EXTENSIONS_LOCALSTORAGE_KEY)).toBe(JSON.stringify({ test: false })); + expect(storage.data.size).toBe(1); + }); + + it('rolls a failed activation back and reports why', async () => { + const registry = new ExtensionRegistry(); + const cleanup = vi.fn(); + + vi.spyOn(console, 'error').mockImplementation(() => {}); + + registry.register( + makeManifest({ + activate(ctx) { + ctx.contribute('tools', makeProvider()); + ctx.onDeactivate(cleanup); + + throw new Error('boom'); + } + }) + ); + await registry.activateEnabled(); + + expect(registry.contributions('tools')).toEqual([]); + expect(cleanup).toHaveBeenCalledOnce(); + expect(registry.extensions[0]).toMatchObject({ error: 'boom', state: 'failed' }); + }); + + it('reports an extension whose code fails to load', async () => { + const registry = new ExtensionRegistry(); + + vi.spyOn(console, 'error').mockImplementation(() => {}); + + registry.register( + makeManifest( + { activate() {} }, + { + load: async () => { + throw new Error('chunk missing'); + } + } + ) + ); + await registry.activateEnabled(); + + expect(registry.extensions[0]).toMatchObject({ error: 'chunk missing', state: 'failed' }); + }); + + it('applies on and off in the order they were asked for', async () => { + const registry = new ExtensionRegistry(); + + let release: () => void = () => {}; + + const gate = new Promise((resolve) => (release = resolve)); + + registry.register( + makeManifest({ + async activate(ctx) { + await gate; + ctx.contribute('tools', makeProvider()); + } + }) + ); + + const starting = registry.activateEnabled(); + const stopping = registry.setEnabled('test', false); + + release(); + await Promise.all([starting, stopping]); + + expect(registry.contributions('tools')).toEqual([]); + expect(registry.extensions[0]).toMatchObject({ enabled: false, state: 'inactive' }); + }); + + it('refuses a contribution from an extension that is no longer active', async () => { + const registry = new ExtensionRegistry(); + + let late: (() => void) | undefined; + + registry.register( + makeManifest({ + activate(ctx) { + late = () => ctx.contribute('tools', makeProvider()); + } + }) + ); + await registry.activateEnabled(); + await registry.setEnabled('test', false); + + expect(() => late?.()).toThrow(/not active/); + expect(registry.contributions('tools')).toEqual([]); + }); + + it('refuses a second extension with the same id', () => { + const registry = new ExtensionRegistry(); + + registry.register(makeManifest({ activate() {} })); + + expect(() => registry.register(makeManifest({ activate() {} }))).toThrow(/already registered/); + }); +}); diff --git a/ui/apps/chat/tests/unit/mcp-composer-prompts.test.ts b/ui/apps/chat/tests/unit/mcp-composer-prompts.test.ts new file mode 100644 index 000000000000..c3add3f8d77e --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-composer-prompts.test.ts @@ -0,0 +1,133 @@ +// An MCP prompt picked in the chat form shows as a chip right away: loading +// first, then with the prompt's text, or with the error when it failed. + +import { FileExtensionText, MimeTypeText, SpecialFileType } from '#lib/enums/index.ts'; +import type { ComposerHandle } from '#lib/extensions/index.ts'; +import { + addLoadingPrompt, + failLoadingPrompt, + fillLoadedPrompt +} from '#lib/extensions/mcp/composer-prompts.ts'; +import type { ChatUploadedFile, GetPromptResult, MCPPromptInfo } from '#lib/types/index.ts'; +import { describe, expect, it } from 'vitest'; + +const PROMPT: MCPPromptInfo = { name: 'code_review', serverName: 'github', title: 'Code review' }; + +/** A composer handle over a plain list of files, recording the order of the calls. */ +function makeComposer(initial: ChatUploadedFile[] = []) { + const calls: string[] = []; + + let files = initial; + + const composer: ComposerHandle = { + addUploadedFile(file) { + calls.push('addUploadedFile'); + files = [...files, file]; + }, + closePicker: () => void calls.push('closePicker'), + focusInput: () => void calls.push('focusInput'), + openPicker: () => void calls.push('openPicker'), + updateUploadedFile(id, update) { + calls.push('updateUploadedFile'); + files = files.map((f) => (f.id === id ? update(f) : f)); + } + }; + + return { calls, composer, files: () => files }; +} + +describe('MCP prompt attachment', () => { + it('closes the picker, adds a loading chip and focuses the input', () => { + const { calls, composer, files } = makeComposer(); + + addLoadingPrompt(composer, 'p1', PROMPT, { repo: 'ggml-org/llama.cpp' }); + + expect(calls).toEqual(['closePicker', 'addUploadedFile', 'focusInput']); + expect(files()).toHaveLength(1); + expect(files()[0]).toMatchObject({ + id: 'p1', + isLoading: true, + mcpPrompt: { + arguments: { repo: 'ggml-org/llama.cpp' }, + promptName: 'code_review', + serverName: 'github' + }, + name: 'Code review', + size: 0, + type: SpecialFileType.MCP_PROMPT + }); + }); + + it('names the chip after the prompt when it has no title', () => { + const { composer, files } = makeComposer(); + + addLoadingPrompt(composer, 'p1', { name: 'release_notes', serverName: 'docs' }); + + expect(files()[0].name).toBe('release_notes'); + expect(files()[0].mcpPrompt?.arguments).toBeUndefined(); + }); + + it('fills the chip with the text of the loaded messages', async () => { + const { composer, files } = makeComposer(); + const result = { + messages: [ + { content: { text: 'Review this pull request.', type: 'text' }, role: 'user' }, + { content: { data: '', mimeType: 'image/png', type: 'image' }, role: 'user' }, + { content: { text: 'List the main issues.', type: 'text' }, role: 'user' } + ] + } as GetPromptResult; + + addLoadingPrompt(composer, 'p1', PROMPT); + fillLoadedPrompt(composer, 'p1', result); + + const [file] = files(); + const text = 'Review this pull request.\n\nList the main issues.'; + + expect(file).toMatchObject({ + id: 'p1', + isLoading: false, + name: 'Code review', + size: text.length, + textContent: text + }); + expect(file.file.name).toBe(`Code review${FileExtensionText.TXT}`); + expect(file.file.type).toBe(MimeTypeText.PLAIN); + expect(await file.file.text()).toBe(text); + // the prompt stays on the chip: the message is sent with it + expect(file.mcpPrompt?.promptName).toBe('code_review'); + }); + + it('keeps the chip with the error when the prompt fails to load', () => { + const { composer, files } = makeComposer(); + + addLoadingPrompt(composer, 'p1', PROMPT); + failLoadingPrompt(composer, 'p1', 'Server is not connected'); + + expect(files()).toHaveLength(1); + expect(files()[0]).toMatchObject({ + id: 'p1', + isLoading: false, + loadError: 'Server is not connected' + }); + expect(files()[0].textContent).toBeUndefined(); + }); + + it('leaves the other files alone', () => { + const other: ChatUploadedFile = { + file: new File(['notes'], 'notes.txt'), + id: 'other', + name: 'notes.txt', + size: 5, + type: MimeTypeText.PLAIN + }; + const { composer, files } = makeComposer([other]); + + addLoadingPrompt(composer, 'p1', PROMPT); + fillLoadedPrompt(composer, 'p1', { + messages: [{ content: { text: 'Hello', type: 'text' }, role: 'user' }] + } as GetPromptResult); + + expect(files()[0]).toBe(other); + expect(files()[1].textContent).toBe('Hello'); + }); +}); diff --git a/ui/apps/chat/tests/unit/mcp-llama-server.test.ts b/ui/apps/chat/tests/unit/mcp-llama-server.test.ts new file mode 100644 index 000000000000..b79f1f24b602 --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-llama-server.test.ts @@ -0,0 +1,198 @@ +// The MCP servers llama-server runs from `--mcp-servers-config` (stdio): their +// tools come in llama-server's `/tools` listing with the type `mcp`. The core +// lists them as server tools until the MCP extension takes them over; then +// they are MCP tools, grouped per server and run on llama-server. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: {} +})); +// the component draws on the app's component barrel, which needs a browser +vi.mock('#lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte', () => ({ + default: () => {} +})); + +import { BuiltInTool, ServerToolType, ToolSource } from '#lib/enums/index.ts'; +import type { ExtensionContext, ToolProvider } from '#lib/extensions/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { llamaServerMcpServers } from '#lib/extensions/mcp/llama-server.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import { contributeTools } from '#lib/extensions/mcp/tools.ts'; +import { ToolsService } from '#lib/services/tools.service.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { OpenAIToolDefinition, ServerToolInfo } from '#lib/types/index.ts'; + +const EXTENSION_ID = 'mcp-llama-server-test'; + +function info(tool: string, type: ServerToolType, mcpServer?: string): ServerToolInfo { + return { + definition: { + function: { description: `${tool} tool`, name: tool, parameters: {} }, + type: 'function' + }, + display_name: tool, + ...(mcpServer ? { mcp_server: mcpServer } : {}), + permissions: { write: false }, + tool, + type, + uses_cwd: false + }; +} + +// what a llama-server started with `--tools all --mcp-servers-config` lists +const LISTING: ServerToolInfo[] = [ + info(BuiltInTool.SERVER_READ_FILE, ServerToolType.SERVER), + info('imcp_weather_current', ServerToolType.MCP, 'imcp'), + info('imcp_contacts_search', ServerToolType.MCP, 'imcp'), + info('my_fs_read', ServerToolType.MCP, 'my_fs') +]; + +interface ToolsStoreInternals { + _serverToolInfos: ServerToolInfo[]; + _serverTools: OpenAIToolDefinition[]; +} + +function seedListing(listing: ServerToolInfo[]): void { + const internals = toolsStore as unknown as ToolsStoreInternals; + + internals._serverToolInfos = listing; + internals._serverTools = listing.map((i) => i.definition); +} + +function provider(): ToolProvider { + let made: ToolProvider | undefined; + + const ctx: ExtensionContext = { + contribute: (point, contribution) => { + if (point === 'tools') made = contribution as ToolProvider; + }, + onDeactivate: () => {} + }; + + contributeTools(ctx); + + return made!; +} + +function names(defs: OpenAIToolDefinition[]): string[] { + return defs.map((def) => def.function.name); +} + +extensions.register({ + description: "MCP's tools, as the extension contributes them", + id: EXTENSION_ID, + load: async () => ({ default: { activate: contributeTools } }), + name: 'MCP' +}); + +beforeEach(() => { + vi.restoreAllMocks(); + vi.spyOn(mcpStore, 'getServers').mockReturnValue([]); + vi.spyOn(mcpStore, 'getConnections').mockReturnValue(new Map()); + seedListing(LISTING); +}); + +afterEach(async () => { + await extensions.setEnabled(EXTENSION_ID, false); + seedListing([]); + + for (const key of [...toolsStore.disabledTools]) toolsStore.setToolEnabled(key, true); +}); + +describe('llama-server MCP tools without the MCP extension', () => { + it('stay server tools', () => { + expect(names(toolsStore.serverTools)).toEqual([ + 'read_file', + 'imcp_weather_current', + 'imcp_contacts_search', + 'my_fs_read' + ]); + expect(toolsStore.getToolSource('imcp_weather_current')).toBe(ToolSource.SERVER); + expect(toolsStore.getPermissionKey('imcp_weather_current')).toBe('server:imcp_weather_current'); + }); +}); + +describe('llama-server MCP tools with the MCP extension', () => { + beforeEach(() => extensions.setEnabled(EXTENSION_ID, true)); + + it('leave the server tools for the MCP category', () => { + expect(names(toolsStore.serverTools)).toEqual(['read_file']); + expect(toolsStore.hasServerTools).toBe(true); + expect(toolsStore.getToolSource('read_file')).toBe(ToolSource.SERVER); + expect(toolsStore.getToolSource('imcp_weather_current')).toBe(ToolSource.MCP); + }); + + it('are grouped per server, under keys that cannot meet a configured server', () => { + const group = toolsStore.toolGroups.find((g) => g.serverId === 'llama-server:imcp'); + + expect(group).toMatchObject({ key: 'mcp:llama-server:imcp', label: 'imcp' }); + expect(group?.tools.map((t) => t.definition.function.name)).toEqual([ + 'imcp_weather_current', + 'imcp_contacts_search' + ]); + expect(toolsStore.getPermissionKey('imcp_weather_current')).toBe( + 'mcp-llama-server:imcp:imcp_weather_current' + ); + expect(toolsStore.getToolServerLabel('my_fs_read')).toBe('my_fs'); + }); + + it('are sent to the model once each, and not after their server is switched off', () => { + const all = names(toolsStore.getEnabledToolsForLLM(new Set(), new Set())); + + expect(all.filter((n) => n === 'imcp_weather_current')).toHaveLength(1); + expect(all).toContain('my_fs_read'); + + const off = names( + toolsStore.getEnabledToolsForLLM(new Set(['mcp:llama-server:imcp']), new Set()) + ); + + expect(off).not.toContain('imcp_weather_current'); + expect(off).toContain('my_fs_read'); + expect(off).toContain('read_file'); + }); + + it('run on llama-server, with the arguments the model wrote', async () => { + const execute = vi + .spyOn(ToolsService, 'executeTool') + .mockResolvedValue({ content: 'sunny', isError: false }); + const executeOnMcp = vi.spyOn(mcpStore, 'executeTool'); + const result = await provider().execute({ + arguments: '{"city":"Kraków"}', + id: 'call-1', + name: 'imcp_weather_current' + }); + + expect(result).toEqual({ content: 'sunny', isError: false }); + expect(execute).toHaveBeenCalledWith('imcp_weather_current', { city: 'Kraków' }, undefined); + expect(executeOnMcp).not.toHaveBeenCalled(); + + await provider().execute({ arguments: 'not json', id: 'call-2', name: 'my_fs_read' }); + + expect(execute).toHaveBeenLastCalledWith('my_fs_read', {}, undefined); + }); + + it('make the provider configured without any server of its own', () => { + expect(provider().isConfigured()).toBe(true); + + seedListing([LISTING[0]]); + + expect(provider().isConfigured()).toBe(false); + }); +}); + +describe('the servers llama-server runs', () => { + it('are named by llama-server, or by the tool name of an older llama-server', () => { + seedListing([ + ...LISTING, + // no `mcp_server`: llama-server before the field, `_` + info('github_list_issues', ServerToolType.MCP) + ]); + + expect(llamaServerMcpServers().map((s) => [s.name, s.tools.length])).toEqual([ + ['imcp', 2], + ['my_fs', 1], + ['github', 1] + ]); + }); +}); diff --git a/ui/apps/chat/tests/unit/mcp-prompt-id.test.ts b/ui/apps/chat/tests/unit/mcp-prompt-id.test.ts new file mode 100644 index 000000000000..ca82cab9d28a --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-prompt-id.test.ts @@ -0,0 +1,26 @@ +import { buildMcpPromptId, isMcpPromptId, parseMcpPromptId } from '#lib/utils/index.ts'; +import { describe, expect, it } from 'vitest'; + +describe('MCP prompt ids', () => { + it('round-trips a server and prompt name', () => { + const id = buildMcpPromptId('github', 'review-pr'); + + expect(isMcpPromptId(id)).toBe(true); + expect(parseMcpPromptId(id)).toEqual({ promptName: 'review-pr', serverName: 'github' }); + }); + + it('keeps colons in the prompt name', () => { + expect(parseMcpPromptId(buildMcpPromptId('docs', 'search:recent'))).toEqual({ + promptName: 'search:recent', + serverName: 'docs' + }); + }); + + it('rejects library ids and malformed MCP ids', () => { + expect(parseMcpPromptId('6f1c2a90-library-prompt')).toBeNull(); + expect(parseMcpPromptId('mcp:')).toBeNull(); + expect(parseMcpPromptId('mcp:server-only')).toBeNull(); + expect(parseMcpPromptId('mcp::prompt')).toBeNull(); + expect(parseMcpPromptId('mcp:server:')).toBeNull(); + }); +}); diff --git a/ui/apps/chat/tests/unit/mcp-reconnect-shutdown.test.ts b/ui/apps/chat/tests/unit/mcp-reconnect-shutdown.test.ts new file mode 100644 index 000000000000..cec8c5e42116 --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-reconnect-shutdown.test.ts @@ -0,0 +1,80 @@ +// A reconnect loop waits between attempts. Shutting the store down, as +// switching the MCP extension off does, must end the loop instead of letting +// it bring a connection back. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/extensions/mcp/services/mcp.service.ts', () => ({ + MCPService: { + connect: vi.fn(), + disconnect: vi.fn(async () => {}) + } +})); + +import { MCP_RECONNECT } from '#lib/constants/index.ts'; +import { MCPService } from '#lib/extensions/mcp/services/mcp.service.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import type { MCPConnection, MCPServerConfig } from '#lib/types/index.ts'; + +const connectMock = vi.mocked(MCPService.connect); +const disconnectMock = vi.mocked(MCPService.disconnect); +const CONFIG = { url: 'https://docs.example.com/mcp' } as MCPServerConfig; +const CONNECTION = { serverName: 'docs', tools: [] } as unknown as MCPConnection; + +describe('mcpStore.autoReconnect', () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.spyOn(console, 'log').mockImplementation(() => {}); + connectMock.mockReset(); + disconnectMock.mockClear(); + }); + + afterEach(async () => { + await mcpStore.shutdown(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it('reconnects a server that is still configured', async () => { + connectMock.mockResolvedValue(CONNECTION); + mcpStore.registerServerConfig('docs', CONFIG); + + const loop = mcpStore.autoReconnect('docs'); + + await vi.advanceTimersByTimeAsync(MCP_RECONNECT.INITIAL_DELAY); + await loop; + + expect(connectMock).toHaveBeenCalledOnce(); + expect(mcpStore.getConnections().get('docs')).toBe(CONNECTION); + }); + + it('gives up when the store shuts down while it waits', async () => { + mcpStore.registerServerConfig('docs', CONFIG); + + const loop = mcpStore.autoReconnect('docs'); + + await mcpStore.shutdown(); + await vi.advanceTimersByTimeAsync(MCP_RECONNECT.INITIAL_DELAY); + await loop; + + expect(connectMock).not.toHaveBeenCalled(); + expect(mcpStore.getConnections().size).toBe(0); + }); + + it('closes a connection that arrives after the store shut down', async () => { + let arrive: (connection: MCPConnection) => void = () => {}; + + connectMock.mockReturnValue(new Promise((resolve) => (arrive = resolve))); + mcpStore.registerServerConfig('docs', CONFIG); + + const loop = mcpStore.autoReconnect('docs'); + + await vi.advanceTimersByTimeAsync(MCP_RECONNECT.INITIAL_DELAY); + await mcpStore.shutdown(); + arrive(CONNECTION); + await loop; + + expect(disconnectMock).toHaveBeenCalledWith(CONNECTION); + expect(mcpStore.getConnections().size).toBe(0); + }); +}); diff --git a/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts b/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts new file mode 100644 index 000000000000..48d7af127d09 --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-service-protocol.test.ts @@ -0,0 +1,436 @@ +import { + createMcpHandler, + McpServer, + type ServerOptions, + WebStandardStreamableHTTPServerTransport +} from '@modelcontextprotocol/server'; +import { MCP_RECONNECT } from '#lib/constants/index.ts'; +import { MCPConnectionPhase, MCPLogLevel, MCPTransportType } from '#lib/enums/index.ts'; +import { MCPService } from '#lib/extensions/mcp/services/mcp.service.ts'; +import type { MCPConnectionLog, MCPServerConfig } from '#lib/types/index.ts'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const RESOURCE_URI = 'config://app'; +const HTTP_CONFIG: MCPServerConfig = { + transport: MCPTransportType.STREAMABLE_HTTP, + url: 'https://example.com/mcp' +}; + +interface RecordedRequest { + method: string; + rpcMethod?: string; + sessionId: string | null; +} + +function buildServer(options?: ServerOptions): McpServer { + const server = new McpServer( + { name: 'test-server', version: '1.0.0' }, + { capabilities: { resources: { subscribe: true } }, ...options } + ); + + server.registerTool('ping', { description: 'Reply with pong' }, async () => ({ + content: [{ text: 'pong', type: 'text' }] + })); + server.registerResource('config', RESOURCE_URI, {}, async (uri) => ({ + contents: [{ text: '{}', uri: uri.href }] + })); + + return server; +} + +// An older server: 2025-era protocol with a session +async function startSessionServer() { + const server = buildServer(); + const transport = new WebStandardStreamableHTTPServerTransport({ + enableJsonResponse: true, + sessionIdGenerator: () => 'session-1' + }); + + // McpServer has no handler for the session-only subscribe request + server.server.setRequestHandler('resources/subscribe', async () => ({})); + await server.connect(transport); + + return { handle: (request: Request) => transport.handleRequest(request), server }; +} + +// Sends the client's fetch calls to an in-process MCP server and records them +function serveWith( + handle: (request: Request, rpcMethod?: string) => Promise +): RecordedRequest[] { + const requests: RecordedRequest[] = []; + + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init); + const body = typeof init?.body === 'string' ? JSON.parse(init.body) : undefined; + + requests.push({ + method: request.method, + rpcMethod: body?.method, + sessionId: request.headers.get('mcp-session-id') + }); + + return handle(request, body?.method); + }); + + return requests; +} + +// Passes a response on with a body the test can end, like a proxy that cuts a long stream +function cuttable(response: Response): { cut: () => void; response: Response } { + const reader = response.body!.getReader(); + + let cut = () => {}; + + const body = new ReadableStream({ + async pull(controller) { + const { done, value } = await reader.read(); + + try { + if (done) controller.close(); + else controller.enqueue(value); + } catch { + // already cut + } + }, + start(controller) { + cut = () => controller.close(); + } + }); + + return { + cut: () => cut(), + response: new Response(body, { headers: response.headers, status: response.status }) + }; +} + +describe('MCPService protocol negotiation', () => { + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('uses the stateless protocol when the server speaks it', async () => { + const handler = createMcpHandler(() => buildServer(), { legacy: 'reject' }); + const requests = serveWith((request) => handler.fetch(request)); + const logs: MCPConnectionLog[] = []; + const onToolsChanged = vi.fn(); + const connection = await MCPService.connect( + 'test-server', + HTTP_CONFIG, + undefined, + undefined, + (_phase, log) => logs.push(log), + { tools: { onChanged: onToolsChanged } } + ); + + expect(connection.protocolVersion).toBe('2026-07-28'); + expect(connection.transport.sessionId).toBeUndefined(); + expect(connection.serverInfo?.name).toBe('test-server'); + expect(connection.tools.map((tool) => tool.name)).toEqual(['ping']); + expect(requests.map((request) => request.rpcMethod)).toEqual([ + 'server/discover', + 'subscriptions/listen', + 'tools/list' + ]); + expect( + logs.find((log) => log.phase === MCPConnectionPhase.CAPABILITIES_EXCHANGED)?.message + ).toBe('Capabilities exchanged successfully (protocol 2026-07-28, stateless)'); + + await expect(MCPService.callTool(connection, { arguments: {}, name: 'ping' })).resolves.toEqual( + { content: 'pong', isError: false } + ); + + // list changes arrive on the subscriptions/listen stream + handler.notify.toolsChanged(); + await vi.waitFor(() => expect(onToolsChanged).toHaveBeenCalledTimes(1)); + expect(onToolsChanged.mock.calls[0][1]).toHaveLength(1); + + await MCPService.subscribeResource(connection, RESOURCE_URI); + + expect(requests.at(-1)?.rpcMethod).toBe('subscriptions/listen'); + expect(connection.resourceSubscriptions?.has(RESOURCE_URI)).toBe(true); + + await MCPService.unsubscribeResource(connection, RESOURCE_URI); + + expect(connection.resourceSubscriptions?.size).toBe(0); + + await MCPService.disconnect(connection); + await handler.close(); + + expect(requests.every((request) => request.method === 'POST')).toBe(true); + expect(requests.every((request) => request.sessionId === null)).toBe(true); + expect(requests.some((request) => request.rpcMethod === 'initialize')).toBe(false); + }); + + it('falls back to the session handshake on an older server', async () => { + const { handle, server } = await startSessionServer(); + const requests = serveWith(handle); + const logs: MCPConnectionLog[] = []; + const connection = await MCPService.connect( + 'test-server', + HTTP_CONFIG, + undefined, + undefined, + (_phase, log) => logs.push(log) + ); + + expect(connection.protocolVersion).toMatch(/^2025-/); + expect(connection.transport.sessionId).toBe('session-1'); + expect(connection.tools.map((tool) => tool.name)).toEqual(['ping']); + expect(requests.slice(0, 3).map((request) => request.rpcMethod)).toEqual([ + 'server/discover', + 'initialize', + 'notifications/initialized' + ]); + expect( + logs.find((log) => log.phase === MCPConnectionPhase.CAPABILITIES_EXCHANGED)?.message + ).toBe( + `Capabilities exchanged successfully (protocol ${connection.protocolVersion}, initialize handshake)` + ); + + await expect(MCPService.callTool(connection, { arguments: {}, name: 'ping' })).resolves.toEqual( + { content: 'pong', isError: false } + ); + + await MCPService.subscribeResource(connection, RESOURCE_URI); + + expect(requests.at(-1)).toEqual({ + method: 'POST', + rpcMethod: 'resources/subscribe', + sessionId: 'session-1' + }); + expect(connection.resourceSubscriptions).toBeUndefined(); + + await MCPService.disconnect(connection); + await server.close(); + + expect(requests.at(-1)).toEqual({ + method: 'DELETE', + rpcMethod: undefined, + sessionId: 'session-1' + }); + }); + + it('does not probe a WebSocket server', async () => { + const sent: string[] = []; + + class FakeWebSocket { + onclose?: () => void; + onmessage?: (event: { data: string }) => void; + onopen?: () => void; + + close() { + this.onclose?.(); + } + + constructor() { + queueMicrotask(() => this.onopen?.()); + } + + send(data: string) { + const message = JSON.parse(data); + + sent.push(message.method); + + if (message.method !== 'initialize') return; + + const result = { + capabilities: {}, + protocolVersion: message.params.protocolVersion, + serverInfo: { name: 'ws-server', version: '1.0.0' } + }; + + queueMicrotask(() => + this.onmessage?.({ data: JSON.stringify({ id: message.id, jsonrpc: '2.0', result }) }) + ); + } + } + + vi.stubGlobal('WebSocket', FakeWebSocket); + + const connection = await MCPService.connect('ws-server', { + transport: MCPTransportType.WEBSOCKET, + url: 'ws://example.com/mcp' + }); + + expect(sent).toEqual(['initialize', 'notifications/initialized']); + expect(connection.protocolVersion).toMatch(/^2025-/); + + await MCPService.disconnect(connection); + }); + + it('retries with the session handshake when the probe gets a server error', async () => { + const { handle, server } = await startSessionServer(); + const requests = serveWith(async (request, rpcMethod) => + rpcMethod === 'server/discover' ? new Response('oops', { status: 500 }) : handle(request) + ); + const logs: MCPConnectionLog[] = []; + const connection = await MCPService.connect( + 'test-server', + HTTP_CONFIG, + undefined, + undefined, + (_phase, log) => logs.push(log) + ); + + expect(connection.protocolVersion).toMatch(/^2025-/); + expect(connection.transport.sessionId).toBe('session-1'); + expect(connection.tools.map((tool) => tool.name)).toEqual(['ping']); + expect(requests.slice(0, 3).map((request) => request.rpcMethod)).toEqual([ + 'server/discover', + 'initialize', + 'notifications/initialized' + ]); + expect( + logs.filter( + (log) => + log.level === MCPLogLevel.WARN && + log.message === + 'Stateless protocol probe failed (Version negotiation failed: the server answered the probe with HTTP 500), using the session handshake' + ) + ).toHaveLength(1); + + await MCPService.disconnect(connection); + await server.close(); + }); + + it('retries with the session handshake when the probe gets no reply', async () => { + const { handle, server } = await startSessionServer(); + const requests = serveWith(async (request, rpcMethod) => + rpcMethod === 'server/discover' ? new Response(null, { status: 202 }) : handle(request) + ); + const connection = await MCPService.connect('test-server', { + ...HTTP_CONFIG, + handshakeTimeoutMs: 1000 + }); + + expect(connection.transport.sessionId).toBe('session-1'); + expect(requests.slice(0, 2).map((request) => request.rpcMethod)).toEqual([ + 'server/discover', + 'initialize' + ]); + + await MCPService.disconnect(connection); + await server.close(); + }); + + it('does not retry when the server asks for authorization', async () => { + const requests = serveWith(async () => new Response('Unauthorized', { status: 401 })); + const logs: MCPConnectionLog[] = []; + + await expect( + MCPService.connect('test-server', HTTP_CONFIG, undefined, undefined, (_phase, log) => + logs.push(log) + ) + ).rejects.toMatchObject({ status: 401 }); + + expect(requests.map((request) => request.rpcMethod)).toEqual(['server/discover']); + expect(logs.some((log) => log.message.startsWith('Stateless protocol probe failed'))).toBe( + false + ); + }); + + it('does not retry a failed session handshake', async () => { + const requests = serveWith( + async (_request, rpcMethod) => + new Response('oops', { status: rpcMethod === 'server/discover' ? 404 : 500 }) + ); + + await expect(MCPService.connect('test-server', HTTP_CONFIG)).rejects.toMatchObject({ + status: 500 + }); + + expect(requests.map((request) => request.rpcMethod)).toEqual(['server/discover', 'initialize']); + }); +}); + +describe('MCPService stateless connection', () => { + const initialDelay = MCP_RECONNECT.INITIAL_DELAY; + + afterEach(() => { + MCP_RECONNECT.INITIAL_DELAY = initialDelay; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('reopens a listen stream that was cut and stops when disconnected', async () => { + MCP_RECONNECT.INITIAL_DELAY = 20; + + const handler = createMcpHandler(() => buildServer(), { legacy: 'reject' }); + const streams: { cut: () => void }[] = []; + const requests = serveWith(async (request, rpcMethod) => { + const response = await handler.fetch(request); + + if (rpcMethod !== 'subscriptions/listen') return response; + + const stream = cuttable(response); + + streams.push(stream); + + return stream.response; + }); + const listens = () => + requests.filter((request) => request.rpcMethod === 'subscriptions/listen').length; + const onToolsChanged = vi.fn(); + const warn = vi.spyOn(console, 'warn'); + const connection = await MCPService.connect( + 'test-server', + HTTP_CONFIG, + undefined, + undefined, + undefined, + { tools: { onChanged: onToolsChanged } } + ); + + expect(listens()).toBe(1); + + // the list-changed stream + streams[0].cut(); + await vi.waitFor(() => expect(listens()).toBe(2)); + + handler.notify.toolsChanged(); + await vi.waitFor(() => expect(onToolsChanged).toHaveBeenCalledTimes(1)); + + // a resource stream + await MCPService.subscribeResource(connection, RESOURCE_URI); + + const subscription = connection.resourceSubscriptions?.get(RESOURCE_URI); + + expect(listens()).toBe(3); + + streams[2].cut(); + await vi.waitFor(() => expect(listens()).toBe(4)); + await vi.waitFor(() => + expect(connection.resourceSubscriptions?.get(RESOURCE_URI)).not.toBe(subscription) + ); + + await MCPService.unsubscribeResource(connection, RESOURCE_URI); + + expect(connection.resourceSubscriptions?.size).toBe(0); + + streams[1].cut(); + await MCPService.disconnect(connection); + await new Promise((resolve) => setTimeout(resolve, 100)); + + expect(listens()).toBe(4); + expect(warn).not.toHaveBeenCalled(); + + await handler.close(); + }); + + it('lists from the server again when the server allows a cached answer', async () => { + const handler = createMcpHandler( + () => buildServer({ cacheHints: { 'tools/list': { ttlMs: 60_000 } } }), + { legacy: 'reject' } + ); + const requests = serveWith((request) => handler.fetch(request)); + const connection = await MCPService.connect('test-server', HTTP_CONFIG); + + await MCPService.listTools(connection); + + expect(requests.filter((request) => request.rpcMethod === 'tools/list')).toHaveLength(2); + + await MCPService.disconnect(connection); + await handler.close(); + }); +}); diff --git a/ui/apps/chat/tests/unit/mcp-service.test.ts b/ui/apps/chat/tests/unit/mcp-service.test.ts index 6ab3ad27d073..549966c0b307 100644 --- a/ui/apps/chat/tests/unit/mcp-service.test.ts +++ b/ui/apps/chat/tests/unit/mcp-service.test.ts @@ -1,9 +1,9 @@ -import { Client } from '@modelcontextprotocol/sdk/client'; +import { Client, SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client'; import { CORS_PROXY } from '#lib/constants/index.ts'; import { MCPConnectionPhase, MCPTransportType } from '#lib/enums/index.ts'; -import { MCPService } from '#lib/services/mcp.service.ts'; +import { MCPService } from '#lib/extensions/mcp/services/mcp.service.ts'; import type { MCPConnection, MCPConnectionLog, MCPServerConfig } from '#lib/types/index.ts'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; type DiagnosticFetchFactory = ( serverName: string, @@ -25,6 +25,9 @@ const createDiagnosticFetch = ( ).createDiagnosticFetch('test-server', config, baseInit, new URL(config.url), useProxy, onLog); describe('MCPService', () => { + // connect() loads the SDK on demand; tests that skip connect() need it loaded too + beforeAll(() => MCPService.loadSdk()); + afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); @@ -330,6 +333,29 @@ describe('MCPService', () => { ).toHaveLength(0); }); + it('treats a 404 as an expired session only on a connection with a session', async () => { + const notFound = new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Not Found', { + status: 404, + statusText: 'Not Found' + }); + const connectionWith = (sessionId?: string) => + ({ + client: { callTool: vi.fn().mockRejectedValue(notFound) }, + requestTimeoutMs: 9000, + serverName: 'test-server', + transport: { sessionId } + }) as unknown as MCPConnection; + const params = { arguments: {}, name: 'tool' }; + + // propagates as it is, the store reconnects on it + await expect(MCPService.callTool(connectionWith('session-1'), params)).rejects.toBe(notFound); + await expect(MCPService.callTool(connectionWith(), params)).rejects.toThrow( + 'Tool "tool" execution failed on server "test-server": Not Found' + ); + expect(MCPService.isSessionExpiredError(notFound, connectionWith('session-1'))).toBe(true); + expect(MCPService.isSessionExpiredError(notFound, connectionWith())).toBe(false); + }); + it('falls back to structuredContent when content array is empty', async () => { const connection = { client: { diff --git a/ui/apps/chat/tests/unit/mcp-system-prompts.test.ts b/ui/apps/chat/tests/unit/mcp-system-prompts.test.ts new file mode 100644 index 000000000000..dff026c59042 --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-system-prompts.test.ts @@ -0,0 +1,189 @@ +// MCP prompts are offered as system messages through the systemPromptSources +// extension point: listed with their server, resolved to text, and, when they +// take arguments, handed to the prompt picker's argument form. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/extensions/mcp/stores/index.svelte.ts', () => ({ + mcpStore: { + ensureInitialized: vi.fn(), + getAllPrompts: vi.fn(), + getPrompt: vi.fn(), + getServerFavicon: vi.fn(), + getServerLabel: vi.fn(), + getServers: vi.fn() + } +})); +vi.mock('#lib/extensions/mcp/components/McpLogo.svelte', () => ({ default: () => {} })); +vi.mock('#lib/extensions/mcp/components/contributions/SystemPromptMcpCard.svelte', () => ({ + default: () => {} +})); +// the picker id comes from the composer glue, whose components do not load outside a browser +vi.mock('#lib/extensions/mcp/composer.ts', () => ({ MCP_PROMPTS_PICKER_ID: 'mcp-prompts' })); + +import type { + ComposerHandle, + ExtensionContext, + SystemPromptSource +} from '#lib/extensions/index.ts'; +import { pendingPromptArguments } from '#lib/extensions/mcp/prompt-arguments.svelte.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import { contributeSystemPrompts } from '#lib/extensions/mcp/system-prompts.ts'; +import type { MCPPromptInfo, MCPServerSettingsEntry } from '#lib/types/index.ts'; + +const SERVER: MCPServerSettingsEntry = { + enabled: true, + id: 'srv-1', + name: 'Docs', + url: 'https://docs.example.com/mcp' +}; +const PLAIN: MCPPromptInfo = { + description: 'Reviews a change', + name: 'code_review', + serverName: 'srv-1', + title: 'Code review' +}; +const WITH_ARGUMENTS: MCPPromptInfo = { + arguments: [{ name: 'topic', required: true }], + name: 'explain', + serverName: 'srv-gone' +}; + +function activate(): { cleanups: Array<() => void | Promise>; source: SystemPromptSource } { + const cleanups: Array<() => void | Promise> = []; + + let source: SystemPromptSource | undefined; + + const ctx: ExtensionContext = { + contribute: (point, contribution) => { + if (point === 'systemPromptSources') source = contribution as SystemPromptSource; + }, + onDeactivate: (cleanup) => void cleanups.push(cleanup) + }; + + contributeSystemPrompts(ctx); + + if (!source) throw new Error('no source contributed'); + + return { cleanups, source }; +} + +function makeComposer(): { composer: ComposerHandle; opened: string[] } { + const opened: string[] = []; + + return { + composer: { + addUploadedFile: () => {}, + closePicker: () => {}, + focusInput: () => {}, + openPicker: (id) => void opened.push(id), + updateUploadedFile: () => {} + }, + opened + }; +} + +describe('MCP as a source of system prompts', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(mcpStore.ensureInitialized).mockResolvedValue(true); + vi.mocked(mcpStore.getAllPrompts).mockResolvedValue([PLAIN, WITH_ARGUMENTS]); + vi.mocked(mcpStore.getServers).mockReturnValue([SERVER]); + vi.mocked(mcpStore.getServerLabel).mockReturnValue('Docs'); + vi.mocked(mcpStore.getServerFavicon).mockReturnValue('https://docs.example.com/favicon.ico'); + vi.mocked(mcpStore.getPrompt).mockReset(); + pendingPromptArguments.clear(); + }); + + it('lists the prompts with their server, title and argument count', async () => { + const { source } = activate(); + + expect(source.label).toBe('MCP Prompts'); + expect(await source.list()).toEqual([ + { + argumentCount: 0, + description: 'Reviews a change', + iconUrl: 'https://docs.example.com/favicon.ico', + id: 'mcp:srv-1:code_review', + origin: 'Docs', + title: 'Code review' + }, + { + argumentCount: 1, + description: undefined, + iconUrl: null, + // a prompt whose server is no longer configured keeps the server's id as its origin + id: 'mcp:srv-gone:explain', + origin: 'srv-gone', + title: 'explain' + } + ]); + }); + + it('lists nothing when MCP could not initialize', async () => { + vi.mocked(mcpStore.ensureInitialized).mockResolvedValue(false); + + const { source } = activate(); + + expect(await source.list()).toEqual([]); + expect(mcpStore.getAllPrompts).not.toHaveBeenCalled(); + }); + + it('gives the text of a prompt without arguments', async () => { + vi.mocked(mcpStore.getPrompt).mockResolvedValue({ + messages: [ + { content: { text: 'Review this change.', type: 'text' }, role: 'user' }, + { content: { data: '', mimeType: 'image/png', type: 'image' }, role: 'user' }, + { content: { text: 'Be brief.', type: 'text' }, role: 'user' } + ] + }); + + const { source } = activate(); + const [entry] = await source.list(); + const text = await source.resolve(entry); + + expect(mcpStore.getPrompt).toHaveBeenCalledWith('srv-1', 'code_review', {}); + expect(text).toContain('Review this change.'); + expect(text).toContain('Be brief.'); + }); + + it('gives null for a prompt with no text, or one it did not list', async () => { + vi.mocked(mcpStore.getPrompt).mockResolvedValue({ messages: [] }); + + const { source } = activate(); + const [entry] = await source.list(); + + expect(await source.resolve(entry)).toBeNull(); + expect(await source.resolve({ ...entry, id: 'mcp:other:unknown' })).toBeNull(); + }); + + it('opens the prompt picker on the argument form of a prompt that takes arguments', async () => { + const { source } = activate(); + const [, entry] = await source.list(); + const { composer, opened } = makeComposer(); + + source.openArguments(entry, composer); + + expect(pendingPromptArguments.prompt).toEqual(WITH_ARGUMENTS); + expect(opened).toEqual(['mcp-prompts']); + }); + + it('claims system messages made from MCP prompts, and no others', () => { + const { source } = activate(); + + expect(source.owns('mcp:srv-1:code_review')).toBe(true); + expect(source.owns('2f1c9a4e-library-prompt')).toBe(false); + expect(source.card).toBeDefined(); + }); + + it('forgets a prompt waiting for its arguments when MCP is switched off', async () => { + const { cleanups, source } = activate(); + const [, entry] = await source.list(); + + source.openArguments(entry, makeComposer().composer); + + for (const cleanup of cleanups) await cleanup(); + + expect(pendingPromptArguments.prompt).toBeNull(); + }); +}); diff --git a/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts b/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts new file mode 100644 index 000000000000..716f66dbc329 --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-tools-extension.test.ts @@ -0,0 +1,360 @@ +// MCP reaches the tools of the core only through what its extension +// contributes: a tool provider built on mcpStore and a flow hook that holds +// the connections while a flow runs. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: {} +})); +// the component draws on the app's component barrel, which needs a browser +vi.mock('#lib/extensions/mcp/components/contributions/McpToolGroupIdentity.svelte', () => ({ + default: () => {} +})); + +import { SETTINGS_KEYS } from '#lib/constants/index.ts'; +import { HealthCheckStatus, ToolSource } from '#lib/enums/index.ts'; +import type { ExtensionContext, FlowHook, ToolProvider } from '#lib/extensions/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { mcpStore } from '#lib/extensions/mcp/stores/index.svelte.ts'; +import { + contributeTools, + enableAllToolsForServer, + policyEnabledServerIds +} from '#lib/extensions/mcp/tools.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { HealthCheckState, MCPConnection, MCPServerSettingsEntry } from '#lib/types/index.ts'; + +const SERVERS: MCPServerSettingsEntry[] = [ + { enabled: true, id: 'srv-1', name: 'Docs', url: 'https://docs.example.com/mcp' }, + { enabled: false, id: 'srv-2', name: 'Off', url: 'https://off.example.com/mcp' }, + { enabled: true, id: 'srv-3', name: 'No url', url: ' ' } +]; + +function contributed(): { hook: FlowHook; provider: ToolProvider } { + const made: { hook?: FlowHook; provider?: ToolProvider } = {}; + const ctx: ExtensionContext = { + contribute: (point, contribution) => { + if (point === 'tools') made.provider = contribution as ToolProvider; + + if (point === 'flow') made.hook = contribution as FlowHook; + }, + onDeactivate: () => {} + }; + + contributeTools(ctx); + + return { hook: made.hook!, provider: made.provider! }; +} + +function connection(...tools: { description?: string; inputSchema?: unknown; name: string }[]) { + return { tools } as unknown as MCPConnection; +} + +function mockConnections(connections: Record) { + vi.spyOn(mcpStore, 'getConnections').mockReturnValue(new Map(Object.entries(connections))); +} + +beforeEach(() => { + vi.restoreAllMocks(); + // MCP waits behind its setting: show it, so the empty tools panel can point at its servers + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true); + vi.spyOn(mcpStore, 'getServers').mockReturnValue(SERVERS); + mockConnections({}); +}); + +afterEach(() => { + for (const key of [...toolsStore.disabledTools]) toolsStore.setToolEnabled(key, true); +}); + +describe('MCP tool provider', () => { + it('contributes one provider for the MCP category and one flow hook', () => { + const { hook, provider } = contributed(); + + expect(provider.source).toBe(ToolSource.MCP); + expect(hook).toBeTypeOf('function'); + }); + + it('lists the tools of the live connections, grouped by server', () => { + mockConnections({ + 'srv-1': connection( + { description: 'Search the docs', inputSchema: { type: 'object' }, name: 'search' }, + { name: 'ping' } + ) + }); + + const entries = contributed().provider.entries(); + + expect(entries).toEqual([ + { + definition: { + function: { + description: 'Search the docs', + name: 'search', + parameters: { type: 'object' } + }, + type: 'function' + }, + groupId: 'srv-1', + groupLabel: 'Docs' + }, + { + definition: { + function: { + description: undefined, + name: 'ping', + parameters: { properties: {}, required: [], type: 'object' } + }, + type: 'function' + }, + groupId: 'srv-1', + groupLabel: 'Docs' + } + ]); + }); + + it('gives a schema property without a type the type of its default', () => { + const inputSchema = { + properties: { + flag: { default: true }, + items: { items: { properties: { depth: { default: 1.5 } } }, type: 'array' }, + limit: { default: 5 }, + nested: { properties: { query: { default: 'all' } } }, + typed: { default: 5, type: 'string' }, + untyped: {} + }, + type: 'object' + }; + + mockConnections({ 'srv-1': connection({ inputSchema, name: 'search' }) }); + + const [{ definition }] = contributed().provider.entries(); + + expect(definition.function.parameters).toEqual({ + properties: { + flag: { default: true, type: 'boolean' }, + items: { + items: { properties: { depth: { default: 1.5, type: 'number' } } }, + type: 'array' + }, + limit: { default: 5, type: 'integer' }, + nested: { properties: { query: { default: 'all', type: 'string' } } }, + typed: { default: 5, type: 'string' }, + untyped: {} + }, + type: 'object' + }); + // the server's own schema is left as it was + expect(inputSchema.properties.limit).toEqual({ default: 5 }); + }); + + it('falls back to the tools the health checks found while nothing is connected', () => { + const health: Record = { + 'srv-1': { + logs: [], + status: HealthCheckStatus.SUCCESS, + tools: [{ description: 'Search the docs', name: 'search' }] + }, + // a server that is switched off is not listed, whatever its last check said + 'srv-2': { logs: [], status: HealthCheckStatus.SUCCESS, tools: [{ name: 'hidden' }] } + }; + + vi.spyOn(mcpStore, 'getHealthCheckState').mockImplementation( + (serverId) => health[serverId] ?? { status: HealthCheckStatus.IDLE } + ); + + expect(contributed().provider.entries()).toEqual([ + { + definition: { + function: { + description: 'Search the docs', + name: 'search', + parameters: { properties: {}, required: [], type: 'object' } + }, + type: 'function' + }, + groupId: 'srv-1', + groupLabel: 'Docs' + } + ]); + }); + + it('runs a call through mcpStore and hands back its text', async () => { + const executeTool = vi + .spyOn(mcpStore, 'executeTool') + .mockResolvedValue({ content: 'found it', isError: true }); + const { signal } = new AbortController(); + const result = await contributed().provider.execute( + { arguments: '{"query":"llama"}', id: 'call_0', name: 'search' }, + signal + ); + + expect(executeTool).toHaveBeenCalledWith( + { function: { arguments: '{"query":"llama"}', name: 'search' }, id: 'call_0' }, + signal + ); + expect(result).toEqual({ content: 'found it', isError: false }); + }); + + it('fails the call of a tool no connected server has', async () => { + await expect( + contributed().provider.execute({ arguments: '{}', id: 'call_0', name: 'nope' }) + ).rejects.toThrow('Unknown tool: nope'); + }); + + it('is configured once a server is enabled in the settings', () => { + const hasEnabledServers = vi.spyOn(mcpStore, 'hasEnabledServers').mockReturnValue(false); + const { provider } = contributed(); + + expect(provider.isConfigured()).toBe(false); + + hasEnabledServers.mockReturnValue(true); + + expect(provider.isConfigured()).toBe(true); + }); + + it('resolves icons through the servers', () => { + vi.spyOn(mcpStore, 'getServerFavicon').mockImplementation((id) => `icon:${id}`); + vi.spyOn(mcpStore, 'getServerFaviconForTool').mockImplementation((name) => `tool:${name}`); + + const { provider } = contributed(); + + expect(provider.groupIcon?.('srv-1')).toBe('icon:srv-1'); + expect(provider.toolIcon?.('search')).toBe('tool:search'); + expect(provider.groupIdentity).toBeDefined(); + }); + + it('checks the enabled servers again when asked to refresh', () => { + const run = vi.spyOn(mcpStore, 'runHealthChecksForServers').mockResolvedValue(); + + void contributed().provider.refresh?.(); + + expect(run).toHaveBeenCalledWith([SERVERS[0], SERVERS[2]]); + }); + + it('words the empty tools panel by whether a server exists', () => { + const { provider } = contributed(); + + expect(provider.emptyHint?.()).toEqual({ + action: 'Enable MCP Server(s) to access', + sentence: 'To see MCP Tools you need to add / enable MCP Server(s).', + toolsLabel: 'MCP Tools' + }); + + vi.mocked(mcpStore.getServers).mockReturnValue([]); + + expect(provider.emptyHint?.()?.action).toBe('Add MCP Server(s) to access'); + }); + + it('says nothing in the empty tools panel while MCP is hidden', () => { + const { provider } = contributed(); + + settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, false); + + expect(provider.emptyHint?.()).toBeUndefined(); + }); +}); + +describe('MCP servers under the tool policy', () => { + it('counts the enabled servers with a url whose group and category are on', async () => { + expect(policyEnabledServerIds()).toEqual(['srv-1']); + + toolsStore.setToolEnabled('mcp:srv-1', false); + + expect(policyEnabledServerIds()).toEqual([]); + + toolsStore.setToolEnabled('mcp:srv-1', true); + vi.spyOn(conversationsStore.preferences, 'isCategoryEnabled').mockImplementation( + (source) => source !== ToolSource.MCP + ); + + expect(policyEnabledServerIds()).toEqual([]); + }); + + it('connects before a flow only when the policy leaves a server on', async () => { + const ensureInitialized = vi.spyOn(mcpStore, 'ensureInitialized').mockResolvedValue(true); + const { provider } = contributed(); + + toolsStore.setToolEnabled('mcp:srv-1', false); + await provider.prepare?.(); + + expect(ensureInitialized).not.toHaveBeenCalled(); + + toolsStore.setToolEnabled('mcp:srv-1', true); + await provider.prepare?.(); + + expect(ensureInitialized).toHaveBeenCalledOnce(); + }); + + it('holds the connections for the length of a flow', async () => { + const acquire = vi.spyOn(mcpStore, 'acquireConnection').mockImplementation(() => {}); + const release = vi.spyOn(mcpStore, 'releaseConnection').mockResolvedValue(); + const end = contributed().hook({ conversationId: 'conv-1' }); + + expect(acquire).toHaveBeenCalledOnce(); + expect(release).not.toHaveBeenCalled(); + + await end?.(); + + expect(release).toHaveBeenCalledOnce(); + }); + + it('holds nothing when the policy leaves no server on', () => { + const acquire = vi.spyOn(mcpStore, 'acquireConnection').mockImplementation(() => {}); + + toolsStore.setToolEnabled('mcp:srv-1', false); + + expect(contributed().hook({ conversationId: 'conv-1' })).toBeUndefined(); + expect(acquire).not.toHaveBeenCalled(); + }); + + it('enables the group and every tool of a connected server', () => { + mockConnections({ 'srv-1': connection({ name: 'search' }, { name: 'ping' }) }); + toolsStore.setToolEnabled('mcp:srv-1', false); + toolsStore.setToolEnabled('mcp-srv-1:search', false); + toolsStore.setToolEnabled('mcp-srv-2:search', false); + + enableAllToolsForServer('srv-2'); + + expect(toolsStore.disabledTools.size).toBe(3); + + enableAllToolsForServer('srv-1'); + + expect([...toolsStore.disabledTools]).toEqual(['mcp-srv-2:search']); + }); +}); + +describe('the MCP extension in the registry', () => { + afterEach(() => extensions.setEnabled('mcp-test', false)); + + // these strings are stored in localStorage and on conversation rows + it('lists its tools in the tools store under the stored keys while it is on', async () => { + mockConnections({ 'srv-1': connection({ name: 'search' }) }); + extensions.register({ + description: "MCP's tools, as the extension contributes them", + id: 'mcp-test', + load: async () => ({ default: { activate: contributeTools } }), + name: 'MCP' + }); + + expect(toolsStore.getToolSource('search')).toBeNull(); + + await extensions.setEnabled('mcp-test', true); + + expect(toolsStore.getPermissionKey('search')).toBe('mcp-srv-1:search'); + expect(toolsStore.getToolServerLabel('search')).toBe('Docs'); + expect(toolsStore.toolGroups.find((group) => group.serverId === 'srv-1')).toMatchObject({ + key: 'mcp:srv-1', + label: 'Docs', + source: ToolSource.MCP + }); + expect(extensions.contributions('flow')).toHaveLength(1); + + await extensions.setEnabled('mcp-test', false); + + expect(toolsStore.getToolSource('search')).toBeNull(); + expect(extensions.contributions('flow')).toEqual([]); + }); +}); diff --git a/ui/apps/chat/tests/unit/mcp-websocket-transport.test.ts b/ui/apps/chat/tests/unit/mcp-websocket-transport.test.ts new file mode 100644 index 000000000000..a55a2963011c --- /dev/null +++ b/ui/apps/chat/tests/unit/mcp-websocket-transport.test.ts @@ -0,0 +1,101 @@ +import { WebSocketClientTransport } from '#lib/extensions/mcp/services/mcp-websocket-transport.ts'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +class FakeWebSocket { + static instances: FakeWebSocket[] = []; + + onclose?: () => void; + onerror?: (event: unknown) => void; + onmessage?: (event: { data: string }) => void; + onopen?: () => void; + sent: string[] = []; + + close() { + this.onclose?.(); + } + + constructor( + public url: URL, + public protocol: string + ) { + FakeWebSocket.instances.push(this); + } + + send(data: string) { + this.sent.push(data); + } +} + +async function startTransport() { + const transport = new WebSocketClientTransport(new URL('ws://example.com/mcp')); + const started = transport.start(); + const socket = FakeWebSocket.instances.at(-1)!; + + socket.onopen?.(); + await started; + + return { socket, transport }; +} + +describe('WebSocketClientTransport', () => { + afterEach(() => { + FakeWebSocket.instances = []; + vi.unstubAllGlobals(); + }); + + it('opens the socket with the mcp subprotocol and sends JSON-RPC messages', async () => { + vi.stubGlobal('WebSocket', FakeWebSocket); + + const { socket, transport } = await startTransport(); + + expect(socket.url.href).toBe('ws://example.com/mcp'); + expect(socket.protocol).toBe('mcp'); + + await transport.send({ id: 1, jsonrpc: '2.0', method: 'ping' }); + + expect(socket.sent).toEqual(['{"id":1,"jsonrpc":"2.0","method":"ping"}']); + }); + + it('delivers valid messages and reports invalid frames as errors', async () => { + vi.stubGlobal('WebSocket', FakeWebSocket); + + const { socket, transport } = await startTransport(); + const onmessage = vi.fn(); + const onerror = vi.fn(); + + transport.onmessage = onmessage; + transport.onerror = onerror; + + socket.onmessage?.({ data: '{"id":1,"jsonrpc":"2.0","result":{}}' }); + socket.onmessage?.({ data: 'not json' }); + socket.onmessage?.({ data: '{"foo":"bar"}' }); + + expect(onmessage).toHaveBeenCalledTimes(1); + expect(onmessage).toHaveBeenCalledWith({ id: 1, jsonrpc: '2.0', result: {} }); + expect(onerror).toHaveBeenCalledTimes(2); + }); + + it('rejects start when the socket fails and notifies on close', async () => { + vi.stubGlobal('WebSocket', FakeWebSocket); + + const failing = new WebSocketClientTransport(new URL('ws://example.com/mcp')); + const started = failing.start(); + + FakeWebSocket.instances.at(-1)!.onerror?.({ error: new Error('refused') }); + await expect(started).rejects.toThrow('refused'); + + const { transport } = await startTransport(); + const onclose = vi.fn(); + + transport.onclose = onclose; + await transport.close(); + + expect(onclose).toHaveBeenCalledTimes(1); + await expect( + new WebSocketClientTransport(new URL('ws://example.com/mcp')).send({ + jsonrpc: '2.0', + method: 'notifications/initialized' + }) + ).rejects.toThrow('Not connected'); + }); +}); diff --git a/ui/apps/chat/tests/unit/model-list.test.ts b/ui/apps/chat/tests/unit/model-list.test.ts index 6a7c18fec146..793faa2ae235 100644 --- a/ui/apps/chat/tests/unit/model-list.test.ts +++ b/ui/apps/chat/tests/unit/model-list.test.ts @@ -33,7 +33,8 @@ function groups(): GroupedModelOptions { available: [ { items: [row('org/a'), row('org/b'), row('org/c')], orgName: 'org' }, { items: [row('other/d')], orgName: 'other' } - ] + ], + servers: [] }; } diff --git a/ui/apps/chat/tests/unit/project-prompt.test.ts b/ui/apps/chat/tests/unit/project-prompt.test.ts new file mode 100644 index 000000000000..4d8be74244a2 --- /dev/null +++ b/ui/apps/chat/tests/unit/project-prompt.test.ts @@ -0,0 +1,32 @@ +import { ProjectContextKind } from '#lib/enums/index.ts'; +import { buildProjectSystemPrompt } from '#lib/utils/project-prompt.ts'; +import { describe, expect, it } from 'vitest'; + +describe('buildProjectSystemPrompt', () => { + it('passes the instructions through as written', () => { + const instructions = 'You are a terse reviewer.\n\n- Answer in English\n- Cite files'; + + expect(buildProjectSystemPrompt({ contextItems: [], instructions, name: 'Review' })).toBe( + instructions + ); + }); + + it('adds the context list after the instructions', () => { + expect( + buildProjectSystemPrompt({ + contextItems: [ + { id: '1', kind: ProjectContextKind.FILE, name: 'a.md', path: '/repo/a.md' } + ], + instructions: 'Be brief.', + name: 'Docs' + }) + ).toBe( + 'Be brief.\n\nContext the user added to the project "Docs":\n- /repo/a.md (server file)' + ); + }); + + it('is empty for a project with neither', () => { + expect(buildProjectSystemPrompt({ contextItems: [], instructions: ' ', name: 'X' })).toBe(''); + expect(buildProjectSystemPrompt(undefined)).toBe(''); + }); +}); diff --git a/ui/apps/chat/tests/unit/prompt-drift.test.ts b/ui/apps/chat/tests/unit/prompt-drift.test.ts new file mode 100644 index 000000000000..cdfa7e60cbfa --- /dev/null +++ b/ui/apps/chat/tests/unit/prompt-drift.test.ts @@ -0,0 +1,44 @@ +import { PromptDrift } from '#lib/enums/index.ts'; +import type { DatabasePrompt } from '#lib/types/database.js'; +import { getPromptDrift } from '#lib/utils/prompt-drift.ts'; +import { describe, expect, it } from 'vitest'; + +function makePrompt(overrides: Partial = {}): DatabasePrompt { + return { + content: 'Answer briefly.', + id: 'p1', + lastModified: 2000, + name: 'Brief', + ...overrides + }; +} + +describe('getPromptDrift', () => { + it('reports missing when there is no prompt', () => { + expect(getPromptDrift({ content: 'x', timestamp: 1000 }, undefined)).toBe(PromptDrift.MISSING); + }); + + it('reports none when the texts match, ignoring surrounding whitespace', () => { + const message = { content: ' Answer briefly.\n', timestamp: 1000 }; + + expect(getPromptDrift(message, makePrompt())).toBe(PromptDrift.NONE); + }); + + it('reports the library side when the prompt was saved after the message', () => { + const message = { content: 'Answer at length.', timestamp: 1000 }; + + expect(getPromptDrift(message, makePrompt({ lastModified: 2000 }))).toBe(PromptDrift.LIBRARY); + }); + + it('reports the message side when the prompt was saved before the message', () => { + const message = { content: 'Answer at length.', timestamp: 3000 }; + + expect(getPromptDrift(message, makePrompt({ lastModified: 2000 }))).toBe(PromptDrift.MESSAGE); + }); + + it('treats a prompt saved in the same millisecond as the message as the message side', () => { + const message = { content: 'Answer at length.', timestamp: 2000 }; + + expect(getPromptDrift(message, makePrompt({ lastModified: 2000 }))).toBe(PromptDrift.MESSAGE); + }); +}); diff --git a/ui/apps/chat/tests/unit/prompts-store.test.ts b/ui/apps/chat/tests/unit/prompts-store.test.ts new file mode 100644 index 000000000000..bfbb5e81f786 --- /dev/null +++ b/ui/apps/chat/tests/unit/prompts-store.test.ts @@ -0,0 +1,134 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: { + createPrompt: vi.fn(), + deletePrompt: vi.fn(), + getAllPrompts: vi.fn(), + updatePrompt: vi.fn() + } +})); + +import { DatabaseService } from '#lib/services/database.service.ts'; +import { promptsStore } from '#lib/stores/prompts.svelte.ts'; +import type { DatabasePrompt } from '#lib/types/database.js'; + +const createMock = vi.mocked(DatabaseService.createPrompt); +const deleteMock = vi.mocked(DatabaseService.deletePrompt); +const updateMock = vi.mocked(DatabaseService.updatePrompt); + +function makePrompt(overrides: Partial = {}): DatabasePrompt { + return { + content: 'You are terse.', + id: 'p1', + lastModified: 1000, + name: 'Terse', + ...overrides + }; +} + +describe('promptsStore', () => { + beforeEach(() => { + vi.clearAllMocks(); + promptsStore.prompts = []; + }); + + describe('add', () => { + it('trims the fields, stores the row and puts it first', async () => { + promptsStore.prompts = [makePrompt({ id: 'old' })]; + createMock.mockResolvedValue(undefined as never); + + const created = await promptsStore.add({ + content: ' Answer in French. ', + description: ' ', + name: ' French ' + }); + + expect(created).toBeDefined(); + expect(created?.name).toBe('French'); + expect(created?.content).toBe('Answer in French.'); + expect(created?.description).toBeUndefined(); + expect(createMock).toHaveBeenCalledWith(created); + expect(promptsStore.prompts[0]).toBe(created); + expect(promptsStore.prompts).toHaveLength(2); + }); + + it('refuses a prompt with an empty name or content', async () => { + expect(await promptsStore.add({ content: 'x', name: ' ' })).toBeUndefined(); + expect(await promptsStore.add({ content: ' ', name: 'Name' })).toBeUndefined(); + expect(createMock).not.toHaveBeenCalled(); + }); + + it('leaves the list alone when the database write fails', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + createMock.mockRejectedValue(new Error('quota')); + + expect(await promptsStore.add({ content: 'x', name: 'Name' })).toBeUndefined(); + expect(promptsStore.prompts).toHaveLength(0); + }); + }); + + describe('update', () => { + it('writes the new content, bumps lastModified and keeps the name when empty', async () => { + promptsStore.prompts = [makePrompt()]; + updateMock.mockResolvedValue(undefined); + + const before = Date.now(); + + await promptsStore.update('p1', { content: 'Be brief.', name: ' ' }); + + const stored = promptsStore.get('p1'); + + expect(stored?.content).toBe('Be brief.'); + expect(stored?.name).toBe('Terse'); + expect(stored?.lastModified).toBeGreaterThanOrEqual(before); + expect(updateMock).toHaveBeenCalledWith('p1', stored); + }); + + it('ignores an unknown id and an empty content', async () => { + promptsStore.prompts = [makePrompt()]; + + await promptsStore.update('missing', { content: 'x' }); + await promptsStore.update('p1', { content: ' ' }); + + expect(updateMock).not.toHaveBeenCalled(); + expect(promptsStore.get('p1')?.content).toBe('You are terse.'); + }); + }); + + describe('remove', () => { + it('drops the prompt from the list after the row is deleted', async () => { + promptsStore.prompts = [makePrompt(), makePrompt({ id: 'p2' })]; + deleteMock.mockResolvedValue(undefined); + + await promptsStore.remove('p1'); + + expect(deleteMock).toHaveBeenCalledWith('p1'); + expect(promptsStore.prompts.map((p) => p.id)).toEqual(['p2']); + }); + }); + + describe('search', () => { + beforeEach(() => { + promptsStore.prompts = [ + makePrompt({ content: 'Reply like a pirate.', id: 'a', name: 'Pirate' }), + makePrompt({ description: 'For code review', id: 'b', name: 'Reviewer' }), + makePrompt({ content: 'Use metric units.', id: 'c', name: 'Units' }) + ]; + }); + + it('returns everything for an empty query', () => { + expect(promptsStore.search(' ')).toHaveLength(3); + }); + + it('matches name, description and content, ignoring case', () => { + expect(promptsStore.search('PIRATE').map((p) => p.id)).toEqual(['a']); + expect(promptsStore.search('code review').map((p) => p.id)).toEqual(['b']); + expect(promptsStore.search('metric').map((p) => p.id)).toEqual(['c']); + }); + + it('returns nothing when no field matches', () => { + expect(promptsStore.search('zebra')).toEqual([]); + }); + }); +}); diff --git a/ui/apps/chat/tests/unit/qr-code.test.ts b/ui/apps/chat/tests/unit/qr-code.test.ts new file mode 100644 index 000000000000..c9b1c91058bb --- /dev/null +++ b/ui/apps/chat/tests/unit/qr-code.test.ts @@ -0,0 +1,66 @@ +// Guards the other end of the code scanner: what the host screen shows must be +// the payload the camera accepts, and nothing else. A QR that carries a URL, or +// a half-typed code, scans into a pairing that cannot work. + +import { CODE_CHARS, CODE_LENGTHS } from '#lib/constants/index.ts'; +import { qrCodeDataUrl } from '#lib/utils/qr-code.ts'; +import { describe, expect, it } from 'vitest'; + +/** A code of the right length, drawn from the alphabet llama-server generates from. */ +const CODE = Array.from( + { length: CODE_LENGTHS.SHARE }, + (_, index) => CODE_CHARS[index % CODE_CHARS.length] +).join(''); +/** The same alphabet, shifted: a different code of the same shape. */ +const OTHER = Array.from( + { length: CODE_LENGTHS.SHARE }, + (_, index) => CODE_CHARS[(index + 7) % CODE_CHARS.length] +).join(''); +/** Module size the renderer draws with, in SVG units. */ +const PIXEL_SIZE = 4; + +function svgOf(url: string | null): string { + expect(url).not.toBeNull(); + + return decodeURIComponent(url!.split(',')[1]); +} + +describe('access code QR', () => { + it('renders the code as an SVG data URL', () => { + const svg = svgOf(qrCodeDataUrl(CODE)); + + expect(svg.startsWith(' { + const svg = svgOf(qrCodeDataUrl(CODE)); + + expect(svg).toContain('fill="#ffffff"'); + expect(svg).toContain('fill="#000000"'); + }); + + it('sizes the code for a whole access code, not a fragment', () => { + const svg = svgOf(qrCodeDataUrl(CODE)); + const side = Number(/viewBox="0 0 (\d+)/.exec(svg)?.[1]) / PIXEL_SIZE; + + // 40 bytes at ECC M land in version 3: 29 modules, plus the 4 module quiet zone + expect(side).toBe(37); + }); + + it('carries the code the scanner accepts, spacing and all', () => { + const spaced = `${CODE.slice(0, 8)} ${CODE.slice(8, 20)}\n${CODE.slice(20)}`; + + expect(qrCodeDataUrl(spaced)).toBe(qrCodeDataUrl(CODE)); + }); + + it('encodes the code it was handed', () => { + expect(qrCodeDataUrl(OTHER)).not.toBe(qrCodeDataUrl(CODE)); + }); + + it('renders nothing for a value that is not a code', () => { + expect(qrCodeDataUrl('')).toBeNull(); + expect(qrCodeDataUrl('not a code')).toBeNull(); + expect(qrCodeDataUrl(CODE.slice(0, CODE_LENGTHS.SHARE - 1))).toBeNull(); + }); +}); diff --git a/ui/apps/chat/tests/unit/remote-pairing-setting.test.ts b/ui/apps/chat/tests/unit/remote-pairing-setting.test.ts new file mode 100644 index 000000000000..ed36c4f061d0 --- /dev/null +++ b/ui/apps/chat/tests/unit/remote-pairing-setting.test.ts @@ -0,0 +1,68 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const config: Record = {}; + +vi.mock('#lib/stores/settings/index.svelte.ts', () => ({ + settingsStore: { getConfig: (key: string) => config[key] } +})); + +vi.mock('#lib/utils/api-base.ts', () => ({ + getServers: () => [ + { + baseUrl: '', + code: 'AbCd2345' + 'x'.repeat(32), + enabled: true, + id: 'remote-1', + kind: 'remote', + name: 'Remote' + } + ] +})); + +const connect = vi.fn(); + +vi.mock('#lib/utils/webrtc-tunnel.ts', () => ({ + ClientTunnel: class { + connect = connect; + disconnect = vi.fn(); + } +})); + +import { + SETTING_CONFIG_DEFAULT, + SETTINGS_CHAT_SECTIONS, + SETTINGS_KEYS +} from '#lib/constants/index.ts'; +import { remoteAccessStore } from '#lib/stores/remote-access.svelte.ts'; + +describe('remote pairing setting', () => { + beforeEach(() => { + connect.mockReset().mockResolvedValue(undefined); + delete config[SETTINGS_KEYS.ENABLE_REMOTE_PAIRING]; + remoteAccessStore.disconnect('remote-1'); + }); + + it('is off by default, marked experimental and carries the security note', () => { + const field = SETTINGS_CHAT_SECTIONS.flatMap((section) => section.fields ?? []).find( + (candidate) => candidate.key === SETTINGS_KEYS.ENABLE_REMOTE_PAIRING + ); + + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.ENABLE_REMOTE_PAIRING]).toBe(false); + expect(field?.isExperimental).toBe(true); + expect(field?.note).toMatch(/pass code/); + }); + + it('opens no tunnel while it is off', async () => { + await expect(remoteAccessStore.connect('remote-1')).rejects.toThrow(/turned off/); + expect(connect).not.toHaveBeenCalled(); + }); + + it('opens the tunnel once it is on', async () => { + config[SETTINGS_KEYS.ENABLE_REMOTE_PAIRING] = true; + + await remoteAccessStore.connect('remote-1'); + + expect(connect).toHaveBeenCalledOnce(); + expect(remoteAccessStore.isConnected('remote-1')).toBe(true); + }); +}); diff --git a/ui/apps/chat/tests/unit/search-chats.test.ts b/ui/apps/chat/tests/unit/search-chats.test.ts index 4d5782280a26..d4eab0b6a895 100644 --- a/ui/apps/chat/tests/unit/search-chats.test.ts +++ b/ui/apps/chat/tests/unit/search-chats.test.ts @@ -2,10 +2,15 @@ import { SEARCH_CHATS_OUTPUT_MAX_CHARS, SEARCH_CHATS_PATTERN_MAX_CHARS } from '#lib/constants/index.ts'; -import { MessageRole, MessageType } from '#lib/enums/index.ts'; +import { AttachmentType, MessageRole, MessageType } from '#lib/enums/index.ts'; import type { DatabaseConversation, DatabaseMessage } from '#lib/types/database.js'; import { formatLocalIso } from '#lib/utils/formatters.ts'; -import { parseSearchChatsParams, searchChats, SearchChatsError } from '#lib/utils/search-chats.ts'; +import { + attachmentName, + parseSearchChatsParams, + searchChats, + SearchChatsError +} from '#lib/utils/search-chats.ts'; import { describe, expect, it } from 'vitest'; type Turn = [role: 'user' | 'assistant' | 'tool', content: string]; @@ -384,3 +389,14 @@ describe('search_chats: parameters', () => { expect(parseSearchChatsParams({ limit_chats: '3' }).limitChats).toBe(3); }); }); + +describe('search_chats: attachment names', () => { + it('names files by their file name and saved prompts by their title', () => { + expect(attachmentName({ base64Url: '', name: 'map.png', type: AttachmentType.IMAGE })).toBe( + 'map.png' + ); + expect( + attachmentName({ promptId: 'p1', title: 'Trip planner', type: AttachmentType.PROMPT }) + ).toBe('Trip planner'); + }); +}); diff --git a/ui/apps/chat/tests/unit/server-props.test.ts b/ui/apps/chat/tests/unit/server-props.test.ts new file mode 100644 index 000000000000..2dde59e5e378 --- /dev/null +++ b/ui/apps/chat/tests/unit/server-props.test.ts @@ -0,0 +1,47 @@ +// Guards the one question that keeps a foreign endpoint out of the servers +// list: does /props answer like a llama.cpp server? A negative that is only a +// guess would lock a working server out of the UI, so "unknown" stays unknown. + +import { isLlamaCppProps } from '#lib/utils/server-props.ts'; +import { describe, expect, it } from 'vitest'; + +describe('llama.cpp props', () => { + it('accepts the props of a model server', () => { + expect( + isLlamaCppProps({ + default_generation_settings: { n_ctx: 4096, params: {} }, + model_path: '/models/qwen.gguf', + role: 'model', + total_slots: 1 + }) + ).toBe(true); + }); + + it('accepts the props of a router', () => { + expect( + isLlamaCppProps({ + build_info: 'b1234', + default_generation_settings: { n_ctx: 0, params: {} }, + role: 'router' + }) + ).toBe(true); + }); + + it('accepts a router that reports its role and build only', () => { + expect(isLlamaCppProps({ build_info: 'b1234', role: 'router' })).toBe(true); + }); + + it('refuses the answer of another runtime', () => { + expect(isLlamaCppProps({ data: [], object: 'list' })).toBe(false); + expect(isLlamaCppProps({ message: 'Not Found' })).toBe(false); + expect(isLlamaCppProps({ default_generation_settings: 'nope' })).toBe(false); + // a role or a build string on its own is a coincidence, not a llama.cpp server + expect(isLlamaCppProps({ role: 'router' })).toBe(false); + }); + + it('refuses anything that is not an object', () => { + expect(isLlamaCppProps(null)).toBe(false); + expect(isLlamaCppProps('llama.cpp')).toBe(false); + expect(isLlamaCppProps([])).toBe(false); + }); +}); diff --git a/ui/apps/chat/tests/unit/server.test.ts b/ui/apps/chat/tests/unit/server.test.ts new file mode 100644 index 000000000000..a96846e49ac6 --- /dev/null +++ b/ui/apps/chat/tests/unit/server.test.ts @@ -0,0 +1,290 @@ +// Guards the addressing of the server transport: a remote server is an +// address that cannot resolve on purpose, an access code is only usable in its +// exact shape, and the stored server list decides what the tunnel transport is +// allowed to route. A regression here silently sends a request to the wrong +// server, so these are cheap to check and expensive to lose. + +import { CODE_CHARS, CODE_LENGTHS, TUNNEL_HOST_SUFFIX } from '#lib/constants/index.ts'; +import { ServerCardState, ServerKind, TunnelStatus } from '#lib/enums/index.ts'; +import { type ServerCardFacts, serverCardStatusOf } from '#lib/utils/server-status.ts'; +import { + createLocalServer, + createRemoteServer, + createUrlServer, + isLocalServer, + isReachableServer, + isRemoteServer, + normalizeShareCode, + parsePresetServers, + parseServersSettings, + parseTunnelOrigin, + presetServersToAdd, + serverOrigin, + tunnelHostLabel, + tunnelOrigin +} from '#lib/utils/servers.ts'; +import { describe, expect, it } from 'vitest'; + +/** A code of the right length, drawn from the alphabet llama-server generates from. */ +const CODE = Array.from( + { length: CODE_LENGTHS.SHARE }, + (_, index) => CODE_CHARS[index % CODE_CHARS.length] +).join(''); + +describe('access codes', () => { + it('accepts a code the user pasted with spacing', () => { + expect(normalizeShareCode(` ${CODE.slice(0, 8)} ${CODE.slice(8)}\n`)).toBe(CODE); + }); + + it('refuses a code of the wrong length', () => { + expect(normalizeShareCode(CODE.slice(0, 39))).toBe(''); + expect(normalizeShareCode(`${CODE}x`)).toBe(''); + }); + + it('refuses characters the code alphabet leaves out', () => { + // `I` is not in CODE_CHARS: it is too easy to misread off a terminal + expect(normalizeShareCode(`${'I'.repeat(8)}${CODE.slice(8)}`)).toBe(''); + }); +}); + +describe('tunnel origins', () => { + it('addresses a server by a host that cannot resolve', () => { + expect(tunnelOrigin('server-1')).toBe('https://server-1.remote.llamacpp.invalid'); + }); + + it('reads the server back out of the address it wrote', () => { + expect(parseTunnelOrigin(tunnelOrigin('server-1'))).toBe('server-1'); + expect(parseTunnelOrigin(new URL(tunnelOrigin('r2')))).toBe('r2'); + }); + + it('leaves anything that is not a tunnel origin alone', () => { + expect(parseTunnelOrigin('https://example.com/v1/models')).toBeNull(); + + // a host that merely ends in the suffix without a label is not a server + expect(parseTunnelOrigin('https://remote.llamacpp.evil/props')).toBeNull(); + }); + + it('matches a host a server id was sanitized into', () => { + expect(tunnelHostLabel('Bad Id!')).toBe('bad-id'); + expect(parseTunnelOrigin(tunnelOrigin('Bad Id!'))).toBe('bad-id'); + }); +}); + +describe('server origins', () => { + it('serves the built-in server from the page origin', () => { + expect(serverOrigin(createLocalServer())).toBe(''); + expect(isLocalServer(createLocalServer())).toBe(true); + expect(isLocalServer(null)).toBe(true); + }); + + it('strips the trailing slash of a URL server', () => { + const server = createUrlServer('https://example.com/llama/', 'u1', 'Office'); + + expect(serverOrigin(server)).toBe('https://example.com/llama'); + expect(server.name).toBe('Office'); + }); + + it('addresses a remote server by its tunnel origin', () => { + const server = createRemoteServer(CODE, 'r1'); + + expect(isRemoteServer(server)).toBe(true); + expect(serverOrigin(server)).toBe(tunnelOrigin('r1')); + }); +}); + +describe('stored server list', () => { + it('reads a legacy entry as a URL server', () => { + const [server] = parseServersSettings([ + { baseUrl: 'https://example.com/llama/', id: 'u1', name: 'O' } + ]); + + expect(server.kind).toBe(ServerKind.URL); + expect(server.baseUrl).toBe('https://example.com/llama'); + }); + + it('keeps the API key of a stored server', () => { + const [server] = parseServersSettings([ + { apiKey: 'sk-secret', baseUrl: 'https://example.com', id: 'u1', name: 'Office' } + ]); + + // the key is the credential of that server: dropping it here turns every + // request into an unauthenticated one + expect(server.apiKey).toBe('sk-secret'); + }); + + it('keeps the API key of a stored remote server', () => { + const [server] = parseServersSettings([ + { apiKey: 'sk-secret', code: CODE, id: 'r1', kind: 'remote', name: 'Home' } + ]); + + expect(server.apiKey).toBe('sk-secret'); + }); + + it('carries the API key of a remote server the form builds', () => { + const server = createRemoteServer(CODE, 'r1', 'Home', 'sk-secret'); + + expect(server.apiKey).toBe('sk-secret'); + }); + + it('reads a remote entry and drops one without a usable code', () => { + const servers = parseServersSettings([ + { code: CODE, id: 'r1', kind: 'remote', name: 'Home' }, + { code: 'nope', id: 'r2', kind: 'remote' } + ]); + + expect(servers.map((server) => server.id)).toEqual(['r1']); + expect(servers[0].kind).toBe(ServerKind.REMOTE); + expect(servers[0].baseUrl).toBe(''); + }); + + it('refuses a URL server squatting on the tunnel host', () => { + expect( + parseServersSettings([{ baseUrl: 'https://r1.remote.llamacpp.invalid', id: 'u1' }]) + ).toEqual([]); + }); + + it('drops the built-in server, which is never persisted', () => { + expect(parseServersSettings([{ baseUrl: '', id: 'local', name: 'Local' }])).toEqual([]); + }); + + it('ignores a value it cannot parse', () => { + expect(parseServersSettings('{oops')).toEqual([]); + expect(parseServersSettings(undefined)).toEqual([]); + expect(parseServersSettings('not json')).toEqual([]); + }); +}); + +describe('reachability', () => { + it('always reaches the built-in server', () => { + expect(isReachableServer(createLocalServer())).toBe(true); + }); + + it('needs a code from a remote server and a URL from a URL one', () => { + expect(isReachableServer(createRemoteServer(CODE, 'r1'))).toBe(true); + expect(isReachableServer({ ...createRemoteServer(CODE, 'r1'), code: '' })).toBe(false); + expect(isReachableServer(createUrlServer('https://example.com', 'u1'))).toBe(true); + expect(isReachableServer(createUrlServer('not a url', 'u2'))).toBe(false); + expect(isReachableServer(createUrlServer('', 'u3'))).toBe(false); + }); +}); + +/** Facts of a server that was never listed and never connected. */ +function facts(overrides: Partial = {}): ServerCardFacts { + return { + enabled: true, + modelCount: 0, + modelsError: '', + modelsLoaded: false, + modelsLoading: false, + remote: false, + tunnel: TunnelStatus.IDLE, + tunnelError: '', + ...overrides + }; +} + +describe('card status', () => { + it('names a running handshake', () => { + const status = serverCardStatusOf(facts({ remote: true, tunnel: TunnelStatus.CONNECTING })); + + expect(status.state).toBe(ServerCardState.CONNECTING); + expect(status.label).toBe('Connecting'); + expect(status.detail).toBe('Opening the tunnel to the host.'); + }); + + it('keeps an idle remote server a choice, not a failure', () => { + const status = serverCardStatusOf(facts({ remote: true, tunnel: TunnelStatus.IDLE })); + + expect(status.state).toBe(ServerCardState.IDLE); + expect(status.label).toBe('Not connected'); + expect(status.detail).toBe('Paste the code the host prints, or press Connect.'); + }); + + it('carries the transport sentence of a dropped channel', () => { + const status = serverCardStatusOf( + facts({ + remote: true, + tunnel: TunnelStatus.ERROR, + tunnelError: 'authentication failed: invalid passcode' + }) + ); + + expect(status.state).toBe(ServerCardState.CHANNEL_DOWN); + expect(status.label).toBe('Channel down'); + expect(status.detail).toBe('authentication failed: invalid passcode'); + }); + + it('reports a listing that failed behind an open channel as unreachable', () => { + const status = serverCardStatusOf( + facts({ modelsError: 'host refused', remote: true, tunnel: TunnelStatus.CONNECTED }) + ); + + expect(status.state).toBe(ServerCardState.UNREACHABLE); + expect(status.label).toBe('Unreachable'); + expect(status.detail).toBe('host refused'); + }); + + it('counts the models of a server that answered', () => { + expect(serverCardStatusOf(facts({ modelCount: 1, modelsLoaded: true })).label).toBe('1 model'); + expect(serverCardStatusOf(facts({ modelCount: 4, modelsLoaded: true })).label).toBe('4 models'); + }); + + it('says what is being checked, tunnel or not', () => { + const direct = serverCardStatusOf(facts({ modelsLoading: true })); + const tunneled = serverCardStatusOf( + facts({ modelsLoading: true, remote: true, tunnel: TunnelStatus.CONNECTED }) + ); + + expect(direct.label).toBe('Checking'); + expect(direct.detail).toBe('Asking the server for the models it serves.'); + expect(tunneled.detail).toBe('Asking the host for the models it serves.'); + }); + + it('reports nothing for a server that is switched off', () => { + const status = serverCardStatusOf(facts({ enabled: false, modelsError: 'host refused' })); + + expect(status.state).toBe(ServerCardState.NONE); + expect(status.label).toBe(''); + expect(status.detail).toBe(''); + }); +}); + +describe('preset servers (llama-chat.json)', () => { + it('reads URLs and objects, trims the trailing slash and drops duplicates', () => { + expect( + parsePresetServers({ + servers: [ + { url: 'http://127.0.0.1:9931/' }, + 'https://llm.example.com/api', + { url: 'http://127.0.0.1:9931' } + ] + }) + ).toEqual(['http://127.0.0.1:9931', 'https://llm.example.com/api']); + }); + + it('drops what is not an http(s) URL, and anything but a servers list', () => { + expect( + parsePresetServers({ + servers: [ + { url: 'ftp://x' }, + { url: 42 }, + null, + 'not a url', + `https://a.${TUNNEL_HOST_SUFFIX}` + ] + }) + ).toEqual([]); + expect(parsePresetServers(null)).toEqual([]); + expect(parsePresetServers('')).toEqual([]); + expect(parsePresetServers({ servers: 'http://127.0.0.1:9931' })).toEqual([]); + }); + + it('adds only servers that are not stored and were not added before', () => { + const stored = [createUrlServer('http://127.0.0.1:9931', 'a')]; + const urls = ['http://127.0.0.1:9931', 'http://127.0.0.1:9932', 'http://127.0.0.1:9933']; + + expect(presetServersToAdd(urls, stored, ['http://127.0.0.1:9933'])).toEqual([ + 'http://127.0.0.1:9932' + ]); + }); +}); diff --git a/ui/apps/chat/tests/unit/servers-service.test.ts b/ui/apps/chat/tests/unit/servers-service.test.ts new file mode 100644 index 000000000000..341360f1eadc --- /dev/null +++ b/ui/apps/chat/tests/unit/servers-service.test.ts @@ -0,0 +1,84 @@ +// Guards the two questions a connectivity check answers: does the server serve +// models, and is it a llama.cpp server at all. The UI drives llama.cpp +// endpoints only, and an endpoint that speaks just the OpenAI API answers the +// listing happily, so the second question is what keeps it out. + +import { ServersService } from '#lib/services/servers.service.ts'; +import { createUrlServer } from '#lib/utils/servers.ts'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const SERVER = createUrlServer('https://example.com', 'u1', 'Office'); +const MODELS = JSON.stringify({ data: [{ id: 'qwen.gguf' }], object: 'list' }); +const PROPS = JSON.stringify({ + default_generation_settings: { n_ctx: 4096, params: {} }, + model_path: '/models/qwen.gguf', + role: 'model' +}); + +/** Serve the two endpoints a check reads, with the answers the test wants. */ +function stubEndpoint(options: { props?: Response; propsBody?: string } = {}) { + vi.stubGlobal('fetch', async (input: RequestInfo | URL) => { + const url = String(input instanceof Request ? input.url : input); + + if (url.endsWith('/props')) { + return options.props ?? new Response(options.propsBody ?? PROPS, { status: 200 }); + } + + return new Response(MODELS, { status: 200 }); + }); +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('server check', () => { + it('accepts a server that lists models and answers props', async () => { + stubEndpoint(); + + const result = await ServersService.test(SERVER); + + expect(result.ok).toBe(true); + expect(result.modelCount).toBe(1); + }); + + it('refuses an endpoint that is not a llama.cpp server', async () => { + stubEndpoint({ propsBody: JSON.stringify({ data: [], object: 'list' }) }); + + const result = await ServersService.test(SERVER); + + expect(result.ok).toBe(false); + expect(result.error).toMatch(/not a llama\.cpp server/); + }); + + it('keeps an endpoint whose props cannot be read', async () => { + // a reverse proxy that hides /props is not proof of a foreign server + stubEndpoint({ props: new Response('Not Found', { status: 404 }) }); + + const result = await ServersService.test(SERVER); + + expect(result.ok).toBe(true); + }); +}); + +describe('server probe', () => { + it('reports a key-protected endpoint as wanting one, and knows nothing else', async () => { + stubEndpoint({ props: new Response('Unauthorized', { status: 401 }) }); + + expect(await ServersService.probe(SERVER)).toEqual({ authRequired: true, llamaCpp: null }); + }); + + it('reports what the endpoint is when props answer', async () => { + stubEndpoint(); + + expect(await ServersService.probe(SERVER)).toEqual({ authRequired: false, llamaCpp: true }); + }); + + it('reports nothing for an endpoint that does not answer', async () => { + vi.stubGlobal('fetch', async () => { + throw new Error('Failed to fetch'); + }); + + expect(await ServersService.probe(SERVER)).toEqual({ authRequired: false, llamaCpp: null }); + }); +}); diff --git a/ui/apps/chat/tests/unit/sidebar-items.test.ts b/ui/apps/chat/tests/unit/sidebar-items.test.ts new file mode 100644 index 000000000000..687bd933509a --- /dev/null +++ b/ui/apps/chat/tests/unit/sidebar-items.test.ts @@ -0,0 +1,60 @@ +// The sidebar's footer is the app's own items plus what extensions contribute: +// without a contribution it must be whole, and a contribution must land +// right after Models, ahead of the footer's other items. +import { SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; +import { SidebarAction } from '#lib/enums/index.ts'; +import type { NavigationItem } from '#lib/extensions/index.ts'; +import { RouterService } from '#lib/services/router.service.ts'; +import { sidebarFooterItems } from '#lib/utils/sidebar-items.ts'; +import type { Component } from 'svelte'; +import { describe, expect, it } from 'vitest'; + +const Icon = (() => {}) as unknown as Component; +/** The labels of the footer's own items, in order. */ +const OWN = SIDEBAR_FOOTER_ITEMS.map((item) => item.tooltip); + +function makeItem(overrides: Partial = {}): NavigationItem { + return { + icon: Icon, + id: 'fake', + placement: 'footer', + route: RouterService.extensionPage('fake'), + tooltip: 'Fake', + ...overrides + }; +} + +describe('sidebarFooterItems', () => { + it('is the app own footer when no extension contributes', () => { + const items = sidebarFooterItems([]); + + expect(items).toEqual(SIDEBAR_FOOTER_ITEMS); + // Models opens the footer and Settings closes it, whatever sits between them + expect(items[0].action).toBe(SidebarAction.MANAGE_MODELS); + expect(items.at(-1)?.action).toBe(SidebarAction.SETTINGS); + }); + + it('places a contributed item right after Models', () => { + const contributed = makeItem({ keys: ['cmd', 'j'] }); + const items = sidebarFooterItems([contributed]); + + expect(items.map((item) => item.tooltip)).toEqual(['Models', 'Fake', ...OWN.slice(1)]); + expect(items[1]).toEqual({ + contributed, + icon: Icon, + keys: ['cmd', 'j'], + tooltip: 'Fake' + }); + // the sidebar opens it as a contributed item, not as one of its own actions + expect(items[1].action).toBeUndefined(); + }); + + it('keeps contributed items in the order they were contributed', () => { + const items = sidebarFooterItems([ + makeItem({ id: 'a', tooltip: 'A' }), + makeItem({ id: 'b', tooltip: 'B' }) + ]); + + expect(items.map((item) => item.tooltip)).toEqual(['Models', 'A', 'B', ...OWN.slice(1)]); + }); +}); diff --git a/ui/apps/chat/tests/unit/tools-extension-point.test.ts b/ui/apps/chat/tests/unit/tools-extension-point.test.ts new file mode 100644 index 000000000000..87d57c11adb5 --- /dev/null +++ b/ui/apps/chat/tests/unit/tools-extension-point.test.ts @@ -0,0 +1,244 @@ +// The tools store and the tool policy know tools from extensions only through +// the `tools` extension point: a provider's tools are listed, keyed, switched +// and labelled like the built-in ones, and are gone once the extension is off. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: {} +})); + +import { BuiltInTool, ToolSource } from '#lib/enums/index.ts'; +import type { Extension, ToolProvider } from '#lib/extensions/index.ts'; +import { extensions } from '#lib/extensions/index.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { OpenAIToolDefinition, ToolEntry, ToolGroup } from '#lib/types/index.ts'; + +const SERVER_ID = 'srv-1'; +const ICON_URL = 'https://example.com/favicon.ico'; + +function definition(name: string): OpenAIToolDefinition { + return { function: { name, parameters: {} }, type: 'function' }; +} + +function makeProvider(overrides: Partial = {}): ToolProvider { + return { + entries: () => [ + { definition: definition('search'), groupId: SERVER_ID, groupLabel: 'Docs' }, + { definition: definition('fetch'), groupId: SERVER_ID, groupLabel: 'Docs' } + ], + execute: async () => ({ content: '', isError: false }), + groupIcon: (groupId) => (groupId === SERVER_ID ? ICON_URL : null), + isConfigured: () => true, + source: ToolSource.MCP, + toolIcon: (toolName) => (toolName === 'search' ? ICON_URL : null), + ...overrides + }; +} + +// the registry has no way to forget an extension, so every test registers its own +let nextExtensionId = 0; + +const activeIds: string[] = []; + +async function activate(extension: Extension): Promise { + const id = `tools-test-${nextExtensionId++}`; + + extensions.register({ + description: 'A test extension', + id, + load: async () => ({ default: extension }), + name: id + }); + await extensions.setEnabled(id, true); + activeIds.push(id); + + return id; +} + +function activateProvider(provider: ToolProvider = makeProvider()): Promise { + return activate({ activate: (ctx) => ctx.contribute('tools', provider) }); +} + +function entry(name: string): ToolEntry { + return toolsStore.allTools.find((t) => t.definition.function.name === name)!; +} + +function group(serverId: string): ToolGroup { + return toolsStore.toolGroups.find((g) => g.serverId === serverId)!; +} + +beforeEach(() => { + vi.restoreAllMocks(); + (toolsStore as unknown as { _serverTools: OpenAIToolDefinition[] })._serverTools = [ + definition(BuiltInTool.SERVER_READ_FILE) + ]; + vi.spyOn(toolsStore, 'customTools', 'get').mockReturnValue([definition('my_tool')]); +}); + +afterEach(async () => { + for (const id of activeIds.splice(0)) await extensions.setEnabled(id, false); + + (toolsStore as unknown as { _serverTools: OpenAIToolDefinition[] })._serverTools = []; + + for (const key of [...toolsStore.disabledTools]) toolsStore.setToolEnabled(key, true); +}); + +describe('tools from an extension', () => { + // these strings are stored in localStorage and on conversation rows + it('keeps the stored key formats', async () => { + await activateProvider(); + + const keys = toolsStore.allTools.map((t) => t.key); + + expect(keys).toContain('server:read_file'); + expect(keys).toContain('browser:get_datetime'); + expect(keys).toContain('mcp-srv-1:search'); + expect(keys).toContain('mcp-srv-1:fetch'); + expect(keys).toContain('custom:my_tool'); + expect(group(SERVER_ID).key).toBe('mcp:srv-1'); + expect(toolsStore.getGroupKey(ToolSource.MCP, SERVER_ID)).toBe('mcp:srv-1'); + expect(toolsStore.getToolKey(ToolSource.MCP, 'search', SERVER_ID)).toBe('mcp-srv-1:search'); + expect(toolsStore.getPermissionKey('search')).toBe('mcp-srv-1:search'); + }); + + it('lists them with their group id and label', async () => { + await activateProvider(); + + expect(entry('search')).toMatchObject({ + serverId: SERVER_ID, + serverName: 'Docs', + source: ToolSource.MCP + }); + expect(group(SERVER_ID)).toMatchObject({ label: 'Docs', source: ToolSource.MCP }); + expect(group(SERVER_ID).tools.map((t) => t.definition.function.name)).toEqual([ + 'search', + 'fetch' + ]); + expect(toolsStore.getToolSource('search')).toBe(ToolSource.MCP); + expect(toolsStore.getToolServerLabel('search')).toBe('Docs'); + }); + + it('sends them to the model after the server and browser tools, before the custom ones', async () => { + await activateProvider(); + + const names = toolsStore + .getEnabledToolsForLLM(new Set(), new Set()) + .map((def) => def.function.name); + + expect(names[0]).toBe('read_file'); + expect(names.slice(-3)).toEqual(['search', 'fetch', 'my_tool']); + expect(names.indexOf('get_datetime')).toBeLessThan(names.indexOf('search')); + }); + + it('switches a tool, its group or its category off', async () => { + await activateProvider(); + + const offered = (disabledTools: string[], disabledCategories: ToolSource[] = []) => + toolsStore + .getEnabledToolsForLLM(new Set(disabledTools), new Set(disabledCategories)) + .map((def) => def.function.name); + + expect(offered(['mcp-srv-1:search'])).not.toContain('search'); + expect(offered(['mcp-srv-1:search'])).toContain('fetch'); + expect(offered(['mcp:srv-1'])).not.toContain('search'); + expect(offered(['mcp:srv-1'])).not.toContain('fetch'); + expect(offered([], [ToolSource.MCP])).not.toContain('fetch'); + expect(offered([], [ToolSource.MCP])).toContain('my_tool'); + }); + + it('asks the provider for the icon of a group and of a tool call', async () => { + await activateProvider(); + + expect(toolsStore.getGroupIcon(group(SERVER_ID))).toBe(ICON_URL); + expect(toolsStore.getGroupIcon(toolsStore.toolGroups[0])).toBeNull(); + expect(toolsStore.getToolIcon('search')).toBe(ICON_URL); + expect(toolsStore.getToolIcon('fetch')).toBeNull(); + expect(toolsStore.getToolIcon(undefined)).toBeNull(); + expect(toolsStore.getGroupIdentity(group(SERVER_ID))).toBeNull(); + }); + + it('toggles a group through the tool policy by its group key', async () => { + await activateProvider(); + + const preferences = conversationsStore.preferences; + + expect(preferences.isGroupChecked(group(SERVER_ID))).toBe(true); + expect(preferences.isServerToolsEnabled(SERVER_ID)).toBe(true); + expect(preferences.isToolParentDisabled(entry('search'))).toBe(false); + + await preferences.toggleGroup(group(SERVER_ID)); + + expect([...toolsStore.disabledTools]).toEqual(['mcp:srv-1']); + expect(preferences.isGroupChecked(group(SERVER_ID))).toBe(false); + expect(preferences.isServerToolsEnabled(SERVER_ID)).toBe(false); + expect(preferences.isToolParentDisabled(entry('search'))).toBe(true); + expect(preferences.isToolActive(entry('search'))).toBe(false); + // the tool's own key is untouched + expect(preferences.isToolEnabled(entry('search').key)).toBe(true); + + await preferences.toggleServerTools(SERVER_ID); + + expect([...toolsStore.disabledTools]).toEqual([]); + expect(preferences.isToolActive(entry('search'))).toBe(true); + }); + + it('enables several keys in one go', async () => { + toolsStore.setToolEnabled('mcp:srv-1', false); + toolsStore.setToolEnabled('mcp-srv-1:search', false); + toolsStore.setToolEnabled('server:read_file', false); + + toolsStore.enableTools(['mcp:srv-1', 'mcp-srv-1:search']); + + expect([...toolsStore.disabledTools]).toEqual(['server:read_file']); + }); + + it('drops the tools once the extension is switched off', async () => { + const id = await activateProvider(); + + expect(toolsStore.getToolSource('search')).toBe(ToolSource.MCP); + + await extensions.setEnabled(id, false); + + expect(toolsStore.providers).toEqual([]); + expect(toolsStore.getToolSource('search')).toBeNull(); + expect(toolsStore.getPermissionKey('search')).toBeNull(); + expect(toolsStore.getToolServerLabel('search')).toBe(''); + expect(toolsStore.getToolIcon('search')).toBeNull(); + }); +}); + +describe('tools without any extension', () => { + it('lists only the built-in categories', () => { + const groups = toolsStore.toolGroups; + + expect(toolsStore.providers).toEqual([]); + expect(groups.map((g) => g.source)).toEqual([ + ToolSource.SERVER, + ToolSource.BROWSER, + ToolSource.CUSTOM + ]); + expect(groups.every((g) => g.serverId === undefined)).toBe(true); + expect(groups.map((g) => g.key)).toEqual(['server', 'browser', 'custom']); + expect(toolsStore.getGroupIcon(groups[0])).toBeNull(); + expect(toolsStore.getGroupIdentity(groups[0])).toBeNull(); + }); + + it('toggles a category group by its category', async () => { + const preferences = conversationsStore.preferences; + const [serverGroup] = toolsStore.toolGroups; + + expect(preferences.isGroupChecked(serverGroup)).toBe(true); + + await preferences.toggleGroup(serverGroup); + + expect(preferences.isGroupChecked(serverGroup)).toBe(false); + expect(preferences.isToolParentDisabled(entry('read_file'))).toBe(true); + expect([...toolsStore.disabledTools]).toEqual([]); + + await preferences.toggleGroup(serverGroup); + + expect(preferences.isGroupChecked(serverGroup)).toBe(true); + }); +}); diff --git a/ui/apps/chat/tsconfig.json b/ui/apps/chat/tsconfig.json index 574b1ab6acc9..89e1e1dbc4d1 100644 --- a/ui/apps/chat/tsconfig.json +++ b/ui/apps/chat/tsconfig.json @@ -44,7 +44,8 @@ "tw-animate-css/*": ["./node_modules/tw-animate-css/*"], "vaul-svelte": ["./node_modules/vaul-svelte"], "vaul-svelte/*": ["./node_modules/vaul-svelte/*"], - "@lucide/svelte/icons/*": ["./node_modules/@lucide/svelte/dist/icons/*"] + "@lucide/svelte/icons/*": ["./node_modules/@lucide/svelte/dist/icons/*"], + "@ggml-org/llama-harness": ["../../lib/harness/src/index.ts"] }, "sourceMap": true, "strict": true diff --git a/ui/apps/chat/vite.config.ts b/ui/apps/chat/vite.config.ts index e88c853dacff..92ff7eecdf82 100644 --- a/ui/apps/chat/vite.config.ts +++ b/ui/apps/chat/vite.config.ts @@ -13,9 +13,11 @@ import { playwright } from '@vitest/browser-playwright'; import { mdsvex } from 'mdsvex'; import { dirname, resolve } from 'path'; import { fileURLToPath } from 'url'; -import { defineConfig, loadEnv, searchForWorkspaceRoot } from 'vite'; +import { defineConfig, loadEnv, type ProxyOptions, searchForWorkspaceRoot } from 'vite'; const __dirname = dirname(fileURLToPath(import.meta.url)); +// the harness has no build step in the repo: the app compiles it from source +const LLAMA_HARNESS_ENTRY = resolve(__dirname, '../../lib/harness/src/index.ts'); // eslint-disable-next-line @typescript-eslint/no-explicit-any const browserBaseConfig: any = { enabled: true, @@ -35,6 +37,18 @@ const outDir = process.env.LLAMA_UI_OUT_DIR ?? './dist'; export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), 'VITE_PUBLIC_'); const SERVER_ORIGIN = env.VITE_PUBLIC_SERVER_ORIGIN || 'http://localhost:9931'; + // llama-server takes cross-origin browser requests only from --cors-origins, so the proxy + // calls it as its own page: the Host of the server and no Origin. Sec-Fetch-Site still + // passes through, so the server keeps refusing requests from other sites. + const toServer = (ws = false): ProxyOptions => ({ + changeOrigin: true, + configure: (proxy) => { + proxy.on('proxyReq', (req) => req.removeHeader('origin')); + proxy.on('proxyReqWs', (req) => req.removeHeader('origin')); + }, + target: SERVER_ORIGIN, + ws + }); return { build: { @@ -77,25 +91,31 @@ export default defineConfig(({ mode }) => { resolve: { alias: { + '@ggml-org/llama-harness': LLAMA_HARNESS_ENTRY, 'katex-fonts': resolve('node_modules/katex/dist/fonts') } }, server: { fs: { - allow: [searchForWorkspaceRoot(process.cwd()), resolve(__dirname, 'tests')] + allow: [ + searchForWorkspaceRoot(process.cwd()), + resolve(__dirname, 'tests'), + resolve(__dirname, '../../lib/harness') + ] }, 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 + '/cors-proxy': toServer(), + '/models': toServer(), + '/props': toServer(), + '/slots': toServer(), + '/storage': toServer(), + '/tools': toServer(), + '/v1': toServer() } }, diff --git a/ui/lib/harness/.gitignore b/ui/lib/harness/.gitignore new file mode 100644 index 000000000000..16339ab2e87f --- /dev/null +++ b/ui/lib/harness/.gitignore @@ -0,0 +1,6 @@ +node_modules +/dist + +# OS +.DS_Store +Thumbs.db diff --git a/ui/lib/harness/.npmrc b/ui/lib/harness/.npmrc new file mode 100644 index 000000000000..b6f27f135954 --- /dev/null +++ b/ui/lib/harness/.npmrc @@ -0,0 +1 @@ +engine-strict=true diff --git a/ui/lib/harness/LICENSE b/ui/lib/harness/LICENSE new file mode 100644 index 000000000000..50c59c51c158 --- /dev/null +++ b/ui/lib/harness/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) ggml + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/ui/lib/harness/README.md b/ui/lib/harness/README.md new file mode 100644 index 000000000000..9994a0caa058 --- /dev/null +++ b/ui/lib/harness/README.md @@ -0,0 +1,64 @@ +# @ggml-org/llama-harness + +Llama Harness, the agentic loop of Llama Chat, as a package: it streams a turn, runs the tools the model called, gives it the results, and repeats until the model answers without a tool call. It is headless TypeScript with no UI, no DOM and no dependencies, so the same loop runs in a browser, in Node and in a worker. It lives in llama.cpp at `ui/lib/harness`. + +It needs an OpenAI-compatible chat completions endpoint, not llama-server specifically. What llama-server adds (timings, prompt progress) it reads when it is there. + +## Use + +```ts +import { createHarness, createOpenAIClient, type Tool } from "@ggml-org/llama-harness"; + +const harness = createHarness(createOpenAIClient({ baseUrl: "http://localhost:8080" })); + +const getTime: Tool = { + definition: { + type: "function", + function: { + name: "get_time", + description: "The current time", + parameters: { type: "object", properties: {} }, + }, + }, + execute: async () => ({ content: new Date().toISOString() }), +}; + +for await (const event of harness.run([{ role: "user", content: "What time is it?" }], [getTime])) { + if (event.type === "text") process.stdout.write(event.delta); +} +``` + +## The contract + +```ts +interface Harness { + run(messages, tools, signal?, options?): AsyncIterable; +} +``` + +- **Messages and tools** use the OpenAI shapes. A tool is its definition plus an `execute` function. +- **Events:** `turn_start`, `text`, `reasoning`, `tool_call_delta`, `timings`, `model`, `completion_id`, `message` (a turn's assistant message), `tool_call`, `tool_update` (a streaming tool's output so far), `tool_result`, `turn_end`, and last `done` or `error`. `run` never throws. +- **The loop waits for you.** It does not go on until you ask for the next event, so you can store each message before the next step runs. +- **It keeps nothing.** No conversation state, no storage: the app owns the history and passes it in. +- **Stopping:** `signal` stops at once. `options.interrupted` ends the run at the next safe point, e.g. when the user sent a new message. `options.maxTurns` with `options.onTurnLimit` asks before it goes past a turn limit. + +An app can put another loop behind the same `Harness` interface. What sits above the loop is the same for every loop: the tools, and whatever an app wraps around `execute`, such as a permission prompt. + +## What the app keeps + +Llama Chat (`ui/apps/chat`) is the first app on it. Its agentic store gives the harness: + +- **An inference client:** its own chat service, which knows the servers, the settings and how to resume a stream. +- **The tools:** built-in tools, llama-server tools and MCP tools, each behind the permission gate. +- **Storage:** it turns the events into messages in its database. + +## Develop + +```sh +npm ci +npm run check # type check +npm test # unit tests +npm run prepack # build dist/ and lint the package +``` + +Llama Chat does not need a build of this package: it compiles `src/` directly, through the `@ggml-org/llama-harness` alias in its `svelte.config.js`. diff --git a/ui/lib/harness/package-lock.json b/ui/lib/harness/package-lock.json new file mode 100644 index 000000000000..952987aff8df --- /dev/null +++ b/ui/lib/harness/package-lock.json @@ -0,0 +1,1255 @@ +{ + "name": "@ggml-org/llama-harness", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@ggml-org/llama-harness", + "version": "0.1.0", + "license": "MIT", + "devDependencies": { + "@types/node": "^24", + "publint": "^0.3.21", + "typescript": "^6.0.3", + "vitest": "5.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@publint/pack": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@publint/pack/-/pack-0.1.7.tgz", + "integrity": "sha512-4EDEmvxWtgsCnnVeBvtFIFZtUhPPt1+bA9JrSwU4Sa//6oKtzCSlGGXYJr44OD9aGISymbieJ4mCKHUygUDU+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyexec": "^1.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://bjornlu.com/sponsor" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.18.tgz", + "integrity": "sha512-ubTG+4KlidvioxjOFdsdEa2F6JVGZb8m2ByJUqQ7fYzUeT1cEn194POcsQ10PKH4p//q0YQn4SB3YpSuzcA1Yg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.18.tgz", + "integrity": "sha512-2Xa1t/JeFGTZn5TbzgPppcCftF8sCVnTNvrIvoSdcZhoFzAuVy1L3xxQUQ4sfWDtwVzg1u6Yi1R3SlJugRNV2Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.18.tgz", + "integrity": "sha512-iUzw9HshVvrWci9gVXjxWS7/M/IcLvNo67vu2c/w9zKBz4hIvPRixdUpIW/iCfhldLaq9ER2hecsI9UY5z0/yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.18.tgz", + "integrity": "sha512-XuDHFzbFEtZl0QGJi92+fmG67tfnp1iZ9VOeDkwasGyTq2VG3/5PnJnvAr+MTzFh/rNScJ3VhN+XpZyyGsN7Jw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.18.tgz", + "integrity": "sha512-MM8opLfsLK15oEXDz6iBc0t3ahu+ew9jsAmha+ovZ33hSwYgqo7YmpRITqFTfW7xA71BLEQ3jJdTsaCmhB1c9w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.18.tgz", + "integrity": "sha512-J6EoCWiy5RnFQzHrKyHXXevZ9lukQfGpnchX/zG/k/WC2nc9O9XyS1JgA8kI9VxMFggMbCPjpv7LcikriXfehw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.18.tgz", + "integrity": "sha512-HIkFuLF7CdDeki+1aCZLLbLq0hk/PHntb+z4/YCTo47JbksTD6jJEELIz92tYROmDmvMrNqUMqBi71BkJLDR+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.18.tgz", + "integrity": "sha512-4oqWItLLYt7IceOnElCct8T2ek5p7PmD7LN04TRJRXGo5f3HtKTgGH6PhYRFK4C2ICkq/LMUU0BVPvvlAKhm8g==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.18.tgz", + "integrity": "sha512-+AkRly5SrCEgnPhGRfub7pucASYEC2fTsxZg7VCcnozpA2+Wn/gCYy1t7LuJS67/xyJu/7noYBJncDUkbwgw2A==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.18.tgz", + "integrity": "sha512-Ttg1r9vVykMnQrE/GwYO9icKtXiuiMfRe/w74xJkeoVuvhRG+WtT6LEMOf58Yl63yd77lhHzO8Y55R8CC3XALA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.18.tgz", + "integrity": "sha512-xX1Tt4o5jUMma0vJsXp5eRZA9nOuyigb2dKJMMzZRmzMxLYGE9PaKKSqHPzPvSQgM8ZOEacSTQwDQcwWfh0xmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.18.tgz", + "integrity": "sha512-4VVlGI5K2kociZlW3lSN8VjG3TW5yQIlAcfCdBXMgGjJxZll15Fa4ocRHXHvIVVnwlibCw/NQajJrNDiqqpiiw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.18.tgz", + "integrity": "sha512-PApTsgH1jLYuyy3tSCz9De82Gq5qXwi7vImVZhEzTgX1C4150Cp5M2ZfL3pLvbCvbEHL0oJeC6pd6podtv8Y5w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.18.tgz", + "integrity": "sha512-J2XjWjx/SP+4x0H4r6dz3Vzb5WVkg7re40Do9K7HJ3sK2/xcmZrWwakXlSwaMvOkvruLJCD4CL/3wqsIR/thgg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.18.tgz", + "integrity": "sha512-XwRJxRQvkuEtS0hIIt29QrqPJ+JzMJSNYHJw4ae/mc6uEarfRG1ceyg4HmmWiBdL/YCb6g7N5BLbSvmRJRYZHw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.0.tgz", + "integrity": "sha512-K+NU2HDCEem4sClgHH4ZZXwdJeNFkJo+hRk479DIwdIviAPN2hFJH1KHHwg8CxHQXvi0M5XY4deTXINfIiSG6w==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", + "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.5", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", + "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "peer": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/package-manager-detector": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.9.0.tgz", + "integrity": "sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/publint": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/publint/-/publint-0.3.25.tgz", + "integrity": "sha512-WMMbn/d7JqRlfXQL/JUI4n5skC8cJ5WVr8/wT5mmiYWkUdENkZr1I5rgs2+dQPVRgoJd+JRYtB46MTsuDylw9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@publint/pack": "^0.1.7", + "package-manager-detector": "^1.8.0", + "picocolors": "^1.1.1", + "sade": "^1.8.1" + }, + "bin": { + "publint": "src/cli.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://bjornlu.com/sponsor" + } + }, + "node_modules/rolldown": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.18.tgz", + "integrity": "sha512-C1uuT3UR60SShuCaPQFAAZyefJCWZlAKB02BV3BuPE2Rs4fevRQltEKoFO2tV5W9/eJhU5RieV6vJj3euulfNQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.18", + "@rolldown/binding-android-arm64": "1.2.18", + "@rolldown/binding-darwin-arm64": "1.2.18", + "@rolldown/binding-darwin-x64": "1.2.18", + "@rolldown/binding-freebsd-x64": "1.2.18", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.18", + "@rolldown/binding-linux-arm64-gnu": "1.2.18", + "@rolldown/binding-linux-arm64-musl": "1.2.18", + "@rolldown/binding-linux-ppc64-gnu": "1.2.18", + "@rolldown/binding-linux-s390x-gnu": "1.2.18", + "@rolldown/binding-linux-x64-gnu": "1.2.18", + "@rolldown/binding-linux-x64-musl": "1.2.18", + "@rolldown/binding-openharmony-arm64": "1.2.18", + "@rolldown/binding-win32-arm64-msvc": "1.2.18", + "@rolldown/binding-win32-x64-msvc": "1.2.18" + } + }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.7", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.7.tgz", + "integrity": "sha512-oxh0dMxrayBr33ScJvvBJ2HBQ2jc1TBrXKR2NyL/MJ9WPuX19mN2DXWUmywKdyw5RFVQBo8hmtb2FMC0LHrnng==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", + "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.5", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.5", + "@vitest/browser-preview": "5.0.5", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.5", + "@vitest/coverage-v8": "5.0.5", + "@vitest/ui": "5.0.5", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + } + } +} diff --git a/ui/lib/harness/package.json b/ui/lib/harness/package.json new file mode 100644 index 000000000000..b93deffb207d --- /dev/null +++ b/ui/lib/harness/package.json @@ -0,0 +1,39 @@ +{ + "name": "@ggml-org/llama-harness", + "version": "0.1.0", + "description": "Headless agentic loop for llama.cpp frontend apps.", + "homepage": "https://github.com/ggml-org/llama.cpp/tree/master/ui/lib/harness", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ggml-org/llama.cpp.git", + "directory": "ui/lib/harness" + }, + "files": [ + "dist" + ], + "type": "module", + "sideEffects": false, + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "check": "tsc --noEmit", + "prepack": "npm run build && publint", + "test": "vitest --run" + }, + "devDependencies": { + "@types/node": "^24", + "publint": "^0.3.21", + "typescript": "^6.0.3", + "vitest": "5.0.5" + }, + "engines": { + "node": ">=20" + } +} diff --git a/ui/lib/harness/src/abort.ts b/ui/lib/harness/src/abort.ts new file mode 100644 index 000000000000..636dd21ed718 --- /dev/null +++ b/ui/lib/harness/src/abort.ts @@ -0,0 +1,17 @@ +const ABORT_ERROR_NAME = "AbortError"; +// TypeErrors a browser throws when a fetch stream is cut by page unload, navigation or a network drop +const ABORT_LIKE_MESSAGE_PATTERNS = [ + /input stream/i, + /network connection was lost/i, + /load failed/i, +]; + +export function isAbortError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + + if (error.name === ABORT_ERROR_NAME) return true; + + return ( + error instanceof TypeError && ABORT_LIKE_MESSAGE_PATTERNS.some((re) => re.test(error.message)) + ); +} diff --git a/ui/lib/harness/src/harness.ts b/ui/lib/harness/src/harness.ts new file mode 100644 index 000000000000..e58e7ea25188 --- /dev/null +++ b/ui/lib/harness/src/harness.ts @@ -0,0 +1,375 @@ +import { isAbortError } from "./abort.js"; +import type { + DoneReason, + Harness, + HarnessEvent, + InferenceClient, + LlmTimings, + LlmTotals, + Message, + PartialToolCall, + RunOptions, + RunTimings, + Timings, + Tool, + ToolCall, + ToolResult, + TurnStats, +} from "./types.js"; + +/** The result of a tool call that did not run because the run was interrupted. */ +export const INTERRUPTED_TOOL_RESULT = "Tool execution was interrupted by a new user message."; + +function emptyTotals(): LlmTotals { + return { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 }; +} + +function addTimings(totals: LlmTotals, timings: LlmTimings): LlmTotals { + return { + predicted_ms: totals.predicted_ms + (timings.predicted_ms ?? 0), + predicted_n: totals.predicted_n + (timings.predicted_n ?? 0), + prompt_ms: totals.prompt_ms + (timings.prompt_ms ?? 0), + prompt_n: totals.prompt_n + (timings.prompt_n ?? 0), + }; +} + +function toToolCalls(partial: PartialToolCall[]): ToolCall[] { + return partial.map((call, index) => ({ + function: { + arguments: call?.function?.arguments ?? "", + name: call?.function?.name ?? "", + }, + id: call?.id ?? `tool_${index}`, + type: "function", + })); +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * The default loop: stream a turn, run the tools the model called, give it the results, and repeat until it answers + * without a tool call. It keeps no state between runs and stores nothing: the app owns the conversation. + */ +export function createHarness(client: InferenceClient): Harness { + return { + run: (messages, tools, signal, options) => run(client, messages, tools, signal, options), + }; +} + +async function* run( + client: InferenceClient, + messages: Message[], + tools: Tool[], + signal?: AbortSignal, + options: RunOptions = {}, +): AsyncGenerator { + const { interrupted = () => false, maxTurns = Infinity, onTurnLimit } = options; + const history = [...messages]; + const definitions = tools.map((tool) => tool.definition); + const toolsByName = new Map(tools.map((tool) => [tool.definition.function.name, tool])); + const totals: RunTimings = { + llm: emptyTotals(), + perTurn: [], + toolCalls: [], + toolCallsCount: 0, + toolsMs: 0, + turns: 0, + }; + + let lastTimings: LlmTimings | undefined; + let turn = 0; + + const runTimings = (): Timings | undefined => { + if (totals.toolCallsCount === 0) return lastTimings; + + return { + agentic: totals, + cache_n: lastTimings?.cache_n, + predicted_ms: lastTimings?.predicted_ms, + predicted_n: lastTimings?.predicted_n, + prompt_ms: lastTimings?.prompt_ms, + prompt_n: lastTimings?.prompt_n, + }; + }; + const done = (reason: DoneReason): HarnessEvent => ({ + reason, + timings: runTimings(), + type: "done", + }); + + while (true) { + if (turn >= maxTurns) { + const more = onTurnLimit ? await onTurnLimit(signal) : false; + + if (!more || signal?.aborted) { + yield done(signal?.aborted ? "aborted" : "turn_limit"); + + return; + } + + turn = 0; + } + + totals.turns = turn + 1; + + if (signal?.aborted) { + yield done("aborted"); + + return; + } + + yield { turn: turn + 1, type: "turn_start" }; + + let content = ""; + let reasoning = ""; + let partialCalls: PartialToolCall[] = []; + let turnTimings: LlmTimings | undefined; + + const stats: TurnStats = { llm: emptyTotals(), toolCalls: [], toolsMs: 0, turn: turn + 1 }; + // the turn's message when the run ends after it: what streamed so far, with the run's timings + const lastMessage = (toolCalls?: ToolCall[]): HarnessEvent => ({ + content, + final: true, + reasoning: reasoning || undefined, + timings: runTimings(), + toolCalls, + type: "message", + }); + + try { + const stream = client.stream({ + messages: history, + signal, + tools: definitions.length > 0 ? definitions : undefined, + }); + + for await (const event of stream) { + if (event.type === "text") { + content += event.delta; + yield event; + } else if (event.type === "reasoning") { + reasoning += event.delta; + yield event; + } else if (event.type === "tool_calls") { + partialCalls = event.toolCalls; + yield { toolCalls: partialCalls, type: "tool_call_delta" }; + } else if (event.type === "timings") { + if (event.timings) { + lastTimings = event.timings; + turnTimings = event.timings; + } + + yield { ...event, llm: event.timings && addTimings(totals.llm, event.timings) }; + } else { + yield event; + } + } + + if (turnTimings) { + totals.llm = addTimings(totals.llm, turnTimings); + stats.llm = addTimings(stats.llm, turnTimings); + } + } catch (error) { + // keep the partial output in both cases + yield lastMessage(); + + if (signal?.aborted) { + yield done("aborted"); + } else { + yield { + error: error instanceof Error ? error : new Error("LLM stream error"), + timings: runTimings(), + type: "error", + }; + } + + return; + } + + // a client can swallow the abort and end the stream normally: do not take a cut tool call for a complete one + if (signal?.aborted) { + yield lastMessage(); + yield done("aborted"); + + return; + } + + if (interrupted()) { + yield lastMessage(partialCalls.length > 0 ? toToolCalls(partialCalls) : undefined); + yield done("interrupted"); + + return; + } + + if (partialCalls.length === 0) { + totals.perTurn.push(stats); + + const timings = runTimings(); + + yield lastMessage(); + + if (timings) yield { timings, type: "turn_end" }; + + yield done("complete"); + + return; + } + + const toolCalls = toToolCalls(partialCalls); + + yield { + content, + final: false, + reasoning: reasoning || undefined, + timings: turnTimings, + toolCalls, + type: "message", + }; + + history.push({ + content: content || undefined, + reasoning_content: reasoning || undefined, + role: "assistant", + tool_calls: toolCalls, + }); + + for (let i = 0; i < toolCalls.length; i++) { + const toolCall = toolCalls[i]; + + if (signal?.aborted) { + yield done("aborted"); + + return; + } + + if (interrupted()) { + for (const skippedCall of toolCalls.slice(i)) { + yield { + result: { content: INTERRUPTED_TOOL_RESULT }, + skipped: true, + toolCall: skippedCall, + type: "tool_result", + }; + + history.push({ + content: INTERRUPTED_TOOL_RESULT, + role: "tool", + tool_call_id: skippedCall.id, + }); + } + + break; + } + + yield { toolCall, type: "tool_call" }; + + const tool = toolsByName.get(toolCall.function.name); + const startTime = performance.now(); + + let result: ToolResult; + + if (!tool) { + result = { content: `Error: Unknown tool: ${toolCall.function.name}`, isError: true }; + } else { + // only the latest update matters, so a slow consumer skips the ones in between + let pendingUpdate: string | undefined; + let settled = false; + let wake: (() => void) | undefined; + + const notify = () => { + wake?.(); + wake = undefined; + }; + const execution = Promise.resolve() + .then(() => + tool.execute(toolCall, { + signal, + update: (updated) => { + pendingUpdate = updated; + notify(); + }, + }), + ) + .finally(() => { + settled = true; + notify(); + }); + + // the rejection is handled below, after the updates are drained + execution.catch(() => {}); + + while (true) { + if (pendingUpdate !== undefined) { + const updated = pendingUpdate; + + pendingUpdate = undefined; + yield { content: updated, toolCall, type: "tool_update" }; + } else if (settled) { + break; + } else { + await new Promise((resolve) => (wake = resolve)); + } + } + + try { + result = await execution; + } catch (error) { + if (isAbortError(error)) { + yield done("aborted"); + + return; + } + + result = { content: `Error: ${errorMessage(error)}`, isError: true }; + } + } + + const durationMs = Math.round(result.durationMs ?? performance.now() - startTime); + const timing = { + duration_ms: durationMs, + name: toolCall.function.name, + success: !result.isError, + }; + + totals.toolCalls.push(timing); + totals.toolCallsCount++; + totals.toolsMs += durationMs; + stats.toolCalls.push(timing); + stats.toolsMs += durationMs; + + if (signal?.aborted) { + yield done("aborted"); + + return; + } + + yield { result, skipped: false, toolCall, type: "tool_result" }; + + history.push({ + content: result.parts?.length + ? [{ text: result.content, type: "text" }, ...result.parts] + : result.content, + role: "tool", + tool_call_id: toolCall.id, + }); + } + + if (stats.toolCalls.length > 0) { + totals.perTurn.push(stats); + + const timings = runTimings(); + + if (timings) yield { timings, type: "turn_end" }; + } + + if (interrupted()) { + yield done("interrupted"); + + return; + } + + turn++; + } +} diff --git a/ui/lib/harness/src/index.ts b/ui/lib/harness/src/index.ts new file mode 100644 index 000000000000..e3096ef332bb --- /dev/null +++ b/ui/lib/harness/src/index.ts @@ -0,0 +1,4 @@ +export { isAbortError } from "./abort.js"; +export { createHarness, INTERRUPTED_TOOL_RESULT } from "./harness.js"; +export { createOpenAIClient, type OpenAIClientOptions } from "./openai-client.js"; +export type * from "./types.js"; diff --git a/ui/lib/harness/src/openai-client.ts b/ui/lib/harness/src/openai-client.ts new file mode 100644 index 000000000000..48413af26cfd --- /dev/null +++ b/ui/lib/harness/src/openai-client.ts @@ -0,0 +1,143 @@ +import type { InferenceClient, InferenceEvent, PartialToolCall } from "./types.js"; + +const CHAT_COMPLETIONS_PATH = "/v1/chat/completions"; +const SSE_DATA_PREFIX = "data:"; +const SSE_DONE = "[DONE]"; + +export interface OpenAIClientOptions { + /** Server root, e.g. `http://localhost:8080`. */ + baseUrl: string; + apiKey?: string; + model?: string; + /** Extra fields of the request body, e.g. `temperature`. */ + params?: Record; + headers?: Record; + /** Default: the global fetch. */ + fetch?: typeof fetch; +} + +interface ToolCallDelta extends PartialToolCall { + index?: number; +} + +function mergeToolCallDeltas(toolCalls: PartialToolCall[], deltas: ToolCallDelta[]): void { + for (const delta of deltas) { + // without an index, a delta with an id opens a call and any other one continues the last call + const index = + delta.index ?? (delta.id || toolCalls.length === 0 ? toolCalls.length : toolCalls.length - 1); + const call = (toolCalls[index] ??= { function: { arguments: "", name: "" } }); + + if (delta.id) call.id = delta.id; + + if (delta.type) call.type = delta.type; + + call.function = { + arguments: (call.function?.arguments ?? "") + (delta.function?.arguments ?? ""), + name: (call.function?.name ?? "") + (delta.function?.name ?? ""), + }; + } +} + +async function errorFromResponse(response: Response): Promise { + const body = await response.text().catch(() => ""); + + let message = body; + + try { + message = JSON.parse(body).error?.message ?? body; + } catch { + // not JSON: keep the body text + } + + return new Error(`HTTP ${response.status}${message ? `: ${message}` : ""}`); +} + +/** + * An inference client for any OpenAI-compatible endpoint, llama-server included. It reads the `timings` and + * `prompt_progress` fields that llama-server adds and works without them. + */ +export function createOpenAIClient(options: OpenAIClientOptions): InferenceClient { + const { apiKey, baseUrl, headers, model, params } = options; + const url = baseUrl.replace(/\/+$/, "") + CHAT_COMPLETIONS_PATH; + + return { + async *stream({ messages, signal, tools }): AsyncGenerator { + const response = await (options.fetch ?? fetch)(url, { + body: JSON.stringify({ ...params, messages, model, stream: true, tools }), + headers: { + "Content-Type": "application/json", + ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), + ...headers, + }, + method: "POST", + signal, + }); + + if (!response.ok) throw await errorFromResponse(response); + + if (!response.body) throw new Error("The response has no body"); + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + const toolCalls: PartialToolCall[] = []; + + let buffer = ""; + let completionId: string | undefined; + let modelName: string | undefined; + + try { + while (true) { + const { done, value } = await reader.read(); + + if (done) return; + + buffer += decoder.decode(value, { stream: true }); + + const lines = buffer.split("\n"); + + buffer = lines.pop() ?? ""; + + for (const line of lines) { + if (!line.startsWith(SSE_DATA_PREFIX)) continue; + + const data = line.slice(SSE_DATA_PREFIX.length).trim(); + + if (data === SSE_DONE) return; + + const chunk = JSON.parse(data); + + if (chunk.error) throw new Error(chunk.error.message ?? "Stream error"); + + if (chunk.id && chunk.id !== completionId) { + completionId = chunk.id; + yield { id: chunk.id, type: "completion_id" }; + } + + if (chunk.model && chunk.model !== modelName) { + modelName = chunk.model; + yield { model: chunk.model, type: "model" }; + } + + const delta = chunk.choices?.[0]?.delta; + const reasoning = delta?.reasoning_content ?? delta?.reasoning; + + if (reasoning) yield { delta: reasoning, type: "reasoning" }; + + if (delta?.content) yield { delta: delta.content, type: "text" }; + + if (delta?.tool_calls?.length) { + mergeToolCallDeltas(toolCalls, delta.tool_calls); + yield { toolCalls: toolCalls.map((call) => ({ ...call })), type: "tool_calls" }; + } + + if (chunk.timings || chunk.prompt_progress) { + yield { progress: chunk.prompt_progress, timings: chunk.timings, type: "timings" }; + } + } + } + } finally { + reader.cancel().catch(() => {}); + } + }, + }; +} diff --git a/ui/lib/harness/src/types.ts b/ui/lib/harness/src/types.ts new file mode 100644 index 000000000000..7050ce0ba329 --- /dev/null +++ b/ui/lib/harness/src/types.ts @@ -0,0 +1,209 @@ +// Messages and tools use the OpenAI chat-completions shapes, so they go to the endpoint as they are. + +export interface TextPart { + type: "text"; + text: string; +} + +export interface ImagePart { + type: "image_url"; + image_url: { url: string }; +} + +export interface AudioPart { + type: "input_audio"; + input_audio: { data: string; format: string }; +} + +export type ContentPart = TextPart | ImagePart | AudioPart; + +export interface ToolCall { + id: string; + type: "function"; + function: { name: string; arguments: string }; +} + +/** A tool call as it streams in: any field can still be missing. */ +export interface PartialToolCall { + id?: string; + type?: string; + function?: { name?: string; arguments?: string }; +} + +export type Message = + | { role: "system" | "user"; content: string | ContentPart[] } + | { + role: "assistant"; + content?: string | ContentPart[]; + reasoning_content?: string; + tool_calls?: ToolCall[]; + } + | { role: "tool"; tool_call_id: string; content: string | ContentPart[] }; + +export interface ToolDefinition { + type: "function"; + function: { + name: string; + description?: string; + parameters?: Record; + }; +} + +export interface ToolContext { + signal?: AbortSignal; + /** Report the output so far of a tool that streams. Each call replaces the previous content. */ + update(content: string): void; +} + +export interface ToolResult { + /** Text the model reads. */ + content: string; + /** Media the model reads after the text, e.g. an image the tool produced. */ + parts?: ContentPart[]; + isError?: boolean; + /** Set it when the tool times itself, e.g. to leave out a wait for approval. Default: the time execute took. */ + durationMs?: number; + /** App data the loop does not read. It comes back on the tool_result event. */ + details?: unknown; +} + +export interface Tool { + definition: ToolDefinition; + /** Run the call. Reject with an AbortError to end the run, with any other error to report it to the model. */ + execute(call: ToolCall, context: ToolContext): Promise; +} + +/** Token counts and times of one request, as llama-server reports them. */ +export interface LlmTimings { + cache_n?: number; + predicted_ms?: number; + predicted_n?: number; + prompt_ms?: number; + prompt_n?: number; +} + +export interface LlmTotals { + predicted_ms: number; + predicted_n: number; + prompt_ms: number; + prompt_n: number; +} + +export interface ToolCallTiming { + name: string; + duration_ms: number; + success: boolean; +} + +export interface TurnStats { + turn: number; + llm: LlmTotals; + toolCalls: ToolCallTiming[]; + toolsMs: number; +} + +/** Totals of a run: every turn's requests and tool calls. */ +export interface RunTimings { + turns: number; + toolCallsCount: number; + toolsMs: number; + toolCalls: ToolCallTiming[]; + perTurn: TurnStats[]; + llm: LlmTotals; +} + +/** The last request's timings, with the run's totals once a tool has run. */ +export interface Timings extends LlmTimings { + agentic?: RunTimings; +} + +export interface PromptProgress { + cache: number; + processed: number; + time_ms: number; + total: number; +} + +export interface InferenceRequest { + messages: Message[]; + tools?: ToolDefinition[]; + signal?: AbortSignal; +} + +export type InferenceEvent = + | { type: "text"; delta: string } + | { type: "reasoning"; delta: string } + /** Every tool call of the response so far, not only the new part. */ + | { type: "tool_calls"; toolCalls: PartialToolCall[] } + | { type: "timings"; timings?: LlmTimings; progress?: PromptProgress } + | { type: "model"; model: string } + | { type: "completion_id"; id: string }; + +/** + * One streamed chat completion. The loop needs nothing else from a server, so any OpenAI-compatible endpoint works. + * Timings, model and completion id are optional extras. + */ +export interface InferenceClient { + stream(request: InferenceRequest): AsyncIterable; +} + +export type DoneReason = + /** The model answered without calling a tool. */ + | "complete" + | "aborted" + /** `interrupted` returned true. */ + | "interrupted" + /** The turn limit was reached and `onTurnLimit` did not grant more turns. */ + | "turn_limit"; + +export type HarnessEvent = + /** `turn` starts at 1, and again at 1 once `onTurnLimit` grants more turns. */ + | { type: "turn_start"; turn: number } + | { type: "text"; delta: string } + | { type: "reasoning"; delta: string } + | { type: "tool_call_delta"; toolCalls: PartialToolCall[] } + /** `llm` is the run's totals including the request in flight. */ + | { type: "timings"; timings?: LlmTimings; progress?: PromptProgress; llm?: LlmTotals } + | { type: "model"; model: string } + | { type: "completion_id"; id: string } + /** The assistant message of a turn. `final` is true when the run ends after it and none of its tool calls runs. */ + | { + type: "message"; + content: string; + reasoning?: string; + toolCalls?: ToolCall[]; + timings?: Timings; + final: boolean; + } + | { type: "tool_call"; toolCall: ToolCall } + | { type: "tool_update"; toolCall: ToolCall; content: string } + /** `skipped` is true when the call did not run because the run was interrupted. */ + | { type: "tool_result"; toolCall: ToolCall; result: ToolResult; skipped: boolean } + | { type: "turn_end"; timings: Timings } + | { type: "done"; reason: DoneReason; timings?: Timings } + | { type: "error"; error: Error; timings?: Timings }; + +export interface RunOptions { + /** Turns before `onTurnLimit` is asked. Default: no limit. */ + maxTurns?: number; + /** Resolve true to run `maxTurns` more turns. Default: the run ends. */ + onTurnLimit?: (signal?: AbortSignal) => Promise; + /** + * Return true to end the run at the next safe point, e.g. when the user sent a new message. Tool calls that did + * not run yet get a result that says so. Use `signal` to stop at once. + */ + interrupted?: () => boolean; +} + +/** + * The contract an app runs a loop through. `run` never throws: it ends with a `done` or an `error` event. It waits + * for the consumer between events, so the consumer can store each one before the loop goes on. + */ +export interface Harness { + run( + messages: Message[], + tools: Tool[], + signal?: AbortSignal, + options?: RunOptions, + ): AsyncIterable; +} diff --git a/ui/lib/harness/tests/harness.test.ts b/ui/lib/harness/tests/harness.test.ts new file mode 100644 index 000000000000..4e302a14c5fe --- /dev/null +++ b/ui/lib/harness/tests/harness.test.ts @@ -0,0 +1,316 @@ +import { describe, expect, it } from "vitest"; +import { + createHarness, + INTERRUPTED_TOOL_RESULT, + type HarnessEvent, + type InferenceClient, + type InferenceEvent, + type InferenceRequest, + type Message, + type RunOptions, + type Tool, + type ToolResult, +} from "../src/index.js"; + +const USER: Message[] = [{ content: "hi", role: "user" }]; + +function callEvent(...names: string[]): InferenceEvent { + return { + toolCalls: names.map((name, index) => ({ + function: { arguments: "{}", name }, + id: `call_${index}`, + })), + type: "tool_calls", + }; +} + +// a client that plays one scripted turn per request and records what it was sent +function scriptedClient(turns: Array) { + const requests: InferenceRequest[] = []; + const client: InferenceClient = { + async *stream(request) { + requests.push({ ...request, messages: [...request.messages] }); + + const turn = turns[requests.length - 1] ?? []; + + if (turn instanceof Error) throw turn; + + yield* turn; + }, + }; + + return { client, requests }; +} + +function tool( + name: string, + execute: Tool["execute"] = async () => ({ content: `${name} ran` }), +): Tool { + return { definition: { function: { name }, type: "function" }, execute }; +} + +async function collect( + client: InferenceClient, + tools: Tool[] = [], + options?: RunOptions, + signal?: AbortSignal, +): Promise { + const events: HarnessEvent[] = []; + + for await (const event of createHarness(client).run(USER, tools, signal, options)) + events.push(event); + + return events; +} + +function types(events: HarnessEvent[]): string[] { + return events.map((event) => event.type); +} + +function last(events: HarnessEvent[]): HarnessEvent { + return events[events.length - 1]; +} + +function results(events: HarnessEvent[]) { + return events.filter((event) => event.type === "tool_result"); +} + +describe("createHarness", () => { + it("ends after a turn without tool calls", async () => { + const { client, requests } = scriptedClient([ + [ + { delta: "think", type: "reasoning" }, + { delta: "Hel", type: "text" }, + { delta: "lo", type: "text" }, + ], + ]); + const events = await collect(client); + + expect(types(events)).toEqual(["turn_start", "reasoning", "text", "text", "message", "done"]); + expect(events[4]).toMatchObject({ content: "Hello", final: true, reasoning: "think" }); + expect(last(events)).toMatchObject({ reason: "complete" }); + expect(requests[0].tools).toBeUndefined(); + }); + + it("runs the called tool and sends its result with the next request", async () => { + const { client, requests } = scriptedClient([ + [{ delta: "let me look", type: "text" }, callEvent("read")], + [{ delta: "done", type: "text" }], + ]); + const events = await collect(client, [tool("read")]); + + expect(types(events)).toEqual([ + "turn_start", + "text", + "tool_call_delta", + "message", + "tool_call", + "tool_result", + "turn_end", + "turn_start", + "text", + "message", + "turn_end", + "done", + ]); + expect(events[3]).toMatchObject({ + final: false, + toolCalls: [{ id: "call_0", type: "function" }], + }); + expect(requests[1].messages.slice(1)).toEqual([ + { + content: "let me look", + reasoning_content: undefined, + role: "assistant", + tool_calls: [ + { function: { arguments: "{}", name: "read" }, id: "call_0", type: "function" }, + ], + }, + { content: "read ran", role: "tool", tool_call_id: "call_0" }, + ]); + expect(requests[0].tools).toEqual([{ function: { name: "read" }, type: "function" }]); + }); + + it("sends a result's media parts after its text", async () => { + const image = { image_url: { url: "data:image/png;base64,AAAA" }, type: "image_url" } as const; + const { client, requests } = scriptedClient([[callEvent("shot")], []]); + + await collect(client, [tool("shot", async () => ({ content: "saved", parts: [image] }))]); + + expect(requests[1].messages[2]).toEqual({ + content: [{ text: "saved", type: "text" }, image], + role: "tool", + tool_call_id: "call_0", + }); + }); + + it("reports an unknown tool and a tool that throws to the model", async () => { + const { client } = scriptedClient([[callEvent("missing", "broken")], []]); + const events = await collect(client, [ + tool("broken", async () => { + throw new Error("boom"); + }), + ]); + + expect(results(events).map((event) => event.result)).toEqual([ + { content: "Error: Unknown tool: missing", isError: true }, + { content: "Error: boom", isError: true }, + ]); + expect(last(events)).toMatchObject({ + timings: { + agentic: { toolCalls: [{ success: false }, { success: false }], toolCallsCount: 2 }, + }, + }); + }); + + it("emits a streaming tool's updates before its result", async () => { + const { client } = scriptedClient([[callEvent("shell")], []]); + const events = await collect(client, [ + tool("shell", async (_call, { update }) => { + update(""); + await Promise.resolve(); + update("a"); + update("ab"); + + return { content: "ab" }; + }), + ]); + const updates = events.filter((event) => event.type === "tool_update"); + + // "a" was replaced before the consumer asked for it + expect(updates.map((event) => event.content)).toEqual(["", "ab"]); + expect(types(events).indexOf("tool_result")).toBeGreaterThan( + types(events).lastIndexOf("tool_update"), + ); + }); + + it("uses the duration a tool reports", async () => { + const { client } = scriptedClient([[callEvent("slow")], []]); + const events = await collect(client, [ + tool("slow", async () => ({ content: "", durationMs: 1234 })), + ]); + + expect(last(events)).toMatchObject({ timings: { agentic: { toolsMs: 1234 } } }); + }); + + it("ends without a result when a tool rejects with an AbortError", async () => { + const { client, requests } = scriptedClient([[callEvent("gated")], []]); + const events = await collect(client, [ + tool("gated", async () => { + throw new DOMException("Operation was aborted", "AbortError"); + }), + ]); + + expect(results(events)).toEqual([]); + expect(last(events)).toMatchObject({ reason: "aborted" }); + expect(requests).toHaveLength(1); + }); + + it("keeps the partial output when the signal aborts mid-stream", async () => { + const controller = new AbortController(); + const client: InferenceClient = { + async *stream() { + yield { delta: "par", type: "text" }; + controller.abort(); + throw new DOMException("Operation was aborted", "AbortError"); + }, + }; + const events = await collect(client, [], undefined, controller.signal); + + expect(types(events)).toEqual(["turn_start", "text", "message", "done"]); + expect(events[2]).toMatchObject({ content: "par", final: true }); + expect(last(events)).toMatchObject({ reason: "aborted" }); + }); + + it("ends with an error event when the stream fails", async () => { + const { client } = scriptedClient([new Error("HTTP 500")]); + const events = await collect(client); + + expect(types(events)).toEqual(["turn_start", "message", "error"]); + expect(last(events)).toMatchObject({ error: { message: "HTTP 500" } }); + }); + + it("keeps the tool calls of the turn it is interrupted after, and runs none", async () => { + const { client, requests } = scriptedClient([[callEvent("read")], []]); + const events = await collect(client, [tool("read")], { interrupted: () => true }); + + expect(types(events)).toEqual(["turn_start", "tool_call_delta", "message", "done"]); + expect(events[2]).toMatchObject({ final: true, toolCalls: [{ id: "call_0" }] }); + expect(last(events)).toMatchObject({ reason: "interrupted" }); + expect(requests).toHaveLength(1); + }); + + it("skips the tool calls left when it is interrupted between two", async () => { + let interrupted = false; + + const { client, requests } = scriptedClient([[callEvent("first", "second", "third")], []]); + const events = await collect( + client, + [ + tool("first", async (): Promise => { + interrupted = true; + + return { content: "first ran" }; + }), + tool("second"), + tool("third"), + ], + { interrupted: () => interrupted }, + ); + + expect(results(events).map((event) => [event.result.content, event.skipped])).toEqual([ + ["first ran", false], + [INTERRUPTED_TOOL_RESULT, true], + [INTERRUPTED_TOOL_RESULT, true], + ]); + expect(last(events)).toMatchObject({ reason: "interrupted" }); + expect(requests).toHaveLength(1); + }); + + it("asks at the turn limit and starts the turn count again when it goes on", async () => { + const answers = [true, false]; + const { client } = scriptedClient([[callEvent("read")], [callEvent("read")], []]); + const events = await collect(client, [tool("read")], { + maxTurns: 1, + onTurnLimit: async () => answers.shift() ?? false, + }); + const turns = events.filter((event) => event.type === "turn_start"); + + expect(turns.map((event) => event.turn)).toEqual([1, 1]); + expect(last(events)).toMatchObject({ reason: "turn_limit" }); + }); + + it("adds up the timings of every turn", async () => { + const timings = (n: number): InferenceEvent => ({ + timings: { cache_n: 1, predicted_ms: n, predicted_n: n, prompt_ms: n, prompt_n: n }, + type: "timings", + }); + const { client } = scriptedClient([[timings(10), callEvent("read")], [timings(5)]]); + const events = await collect(client, [tool("read")]); + const live = events + .filter((event) => event.type === "timings") + .map((event) => event.llm?.predicted_n); + + expect(live).toEqual([10, 15]); + expect(last(events)).toMatchObject({ + timings: { + agentic: { + llm: { predicted_ms: 15, predicted_n: 15, prompt_ms: 15, prompt_n: 15 }, + perTurn: [{ turn: 1 }, { turn: 2 }], + toolCallsCount: 1, + turns: 2, + }, + cache_n: 1, + predicted_n: 5, + }, + }); + }); + + it("reports the last request's timings alone when no tool ran", async () => { + const { client } = scriptedClient([[{ timings: { predicted_n: 3 }, type: "timings" }]]); + const events = await collect(client); + + expect(types(events)).toEqual(["turn_start", "timings", "message", "turn_end", "done"]); + expect(last(events)).toEqual({ reason: "complete", timings: { predicted_n: 3 }, type: "done" }); + }); +}); diff --git a/ui/lib/harness/tests/openai-client.test.ts b/ui/lib/harness/tests/openai-client.test.ts new file mode 100644 index 000000000000..fedcb59a0a8c --- /dev/null +++ b/ui/lib/harness/tests/openai-client.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from "vitest"; +import { createOpenAIClient, type InferenceEvent } from "../src/index.js"; + +function sse(...chunks: unknown[]): string { + return chunks.map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`).join("") + "data: [DONE]\n\n"; +} + +// answers every request with the given body, cut into pieces to cross read boundaries +function fakeFetch(body: string, init: ResponseInit = {}, pieceLength = 7) { + const calls: Array<{ url: string; init: RequestInit }> = []; + const fetch = (async (url: string, requestInit: RequestInit) => { + calls.push({ init: requestInit, url }); + + const bytes = new TextEncoder().encode(body); + const stream = new ReadableStream({ + start(controller) { + for (let i = 0; i < bytes.length; i += pieceLength) { + controller.enqueue(bytes.slice(i, i + pieceLength)); + } + + controller.close(); + }, + }); + + return new Response(stream, init); + }) as typeof globalThis.fetch; + + return { calls, fetch }; +} + +async function collect(stream: AsyncIterable): Promise { + const events: InferenceEvent[] = []; + + for await (const event of stream) events.push(event); + + return events; +} + +const delta = (fields: object, rest: object = {}) => ({ + choices: [{ delta: fields }], + id: "cmpl-1", + model: "m", + ...rest, +}); + +describe("createOpenAIClient", () => { + it("posts a streaming request to the chat completions endpoint", async () => { + const { calls, fetch } = fakeFetch(sse()); + const client = createOpenAIClient({ + apiKey: "key", + baseUrl: "http://localhost:8080/", + fetch, + model: "m", + params: { temperature: 0 }, + }); + + await collect(client.stream({ messages: [{ content: "hi", role: "user" }] })); + + expect(calls[0].url).toBe("http://localhost:8080/v1/chat/completions"); + expect(calls[0].init.headers).toMatchObject({ Authorization: "Bearer key" }); + expect(JSON.parse(calls[0].init.body as string)).toEqual({ + messages: [{ content: "hi", role: "user" }], + model: "m", + stream: true, + temperature: 0, + }); + }); + + it("turns the chunks into events", async () => { + const timings = { predicted_n: 2 }; + const { fetch } = fakeFetch( + sse( + delta({ reasoning_content: "hm" }), + delta({ content: "Hel" }), + delta({ content: "lo" }), + delta({}, { timings }), + ), + ); + const events = await collect( + createOpenAIClient({ baseUrl: "http://x", fetch }).stream({ messages: [] }), + ); + + expect(events).toEqual([ + { id: "cmpl-1", type: "completion_id" }, + { model: "m", type: "model" }, + { delta: "hm", type: "reasoning" }, + { delta: "Hel", type: "text" }, + { delta: "lo", type: "text" }, + { progress: undefined, timings, type: "timings" }, + ]); + }); + + it("merges tool call deltas by index", async () => { + const { fetch } = fakeFetch( + sse( + delta({ + tool_calls: [ + { function: { arguments: "", name: "read" }, id: "a", index: 0, type: "function" }, + ], + }), + delta({ tool_calls: [{ function: { arguments: '{"path"' }, index: 0 }] }), + delta({ + tool_calls: [ + { function: { arguments: ':"x"}' }, index: 0 }, + { function: { arguments: "{}", name: "list" }, id: "b", index: 1, type: "function" }, + ], + }), + ), + ); + const events = await collect( + createOpenAIClient({ baseUrl: "http://x", fetch }).stream({ messages: [] }), + ); + const toolCalls = events.filter((event) => event.type === "tool_calls"); + + expect(toolCalls).toHaveLength(3); + expect(toolCalls[2].toolCalls).toEqual([ + { function: { arguments: '{"path":"x"}', name: "read" }, id: "a", type: "function" }, + { function: { arguments: "{}", name: "list" }, id: "b", type: "function" }, + ]); + }); + + it("throws the server's error message", async () => { + const { fetch } = fakeFetch(JSON.stringify({ error: { message: "no model" } }), { + status: 400, + }); + const stream = createOpenAIClient({ baseUrl: "http://x", fetch }).stream({ messages: [] }); + + await expect(collect(stream)).rejects.toThrow("HTTP 400: no model"); + }); +}); diff --git a/ui/lib/harness/tsconfig.build.json b/ui/lib/harness/tsconfig.build.json new file mode 100644 index 000000000000..cb6a3121d48a --- /dev/null +++ b/ui/lib/harness/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "declaration": true, + "sourceMap": true + }, + "include": ["src"] +} diff --git a/ui/lib/harness/tsconfig.json b/ui/lib/harness/tsconfig.json new file mode 100644 index 000000000000..caa8927c4fc5 --- /dev/null +++ b/ui/lib/harness/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src", "tests"] +}