Commit 00d5c142c for llama.cpp
commit 00d5c142c8c7c0212d0933afa43ebdccd6ccaa8f
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date: Fri Nov 27 10:09:42 2026 +0100
ui: share conversations to Hugging Face datasets as agent traces (#32608)
* ui: add @ggml-org/llama-huggingface, a Hugging Face account as a package
A package in ui/lib that gives an app running in the browser, with no
server of its own, a Hugging Face account. Its plain entry holds "Sign in
with Hugging Face" (OAuth with PKCE and dynamic client registration) and
the Hub calls: who the account is, its datasets, and committing a trace
file to one. Its Svelte entry holds the account as state (HfAccount) and
the components that show it, built on Llama UI: the account panel and the
dialog that shares a trace.
It knows no app: the app says who it is and hands over what to share.
Llama Chat compiles it from source, like the other packages, so the
llama-server image builds (.devops) and the asset staging
(scripts/ui-assets.cmake) copy its sources next to the other packages'.
CI checks and tests it.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: share conversations to Hugging Face datasets as agent traces
A conversation's menu and each message get a Share action. It uploads the
conversation, or the branch up to that message, to a Hugging Face dataset
as a JSONL trace, which the Hub shows in its trace viewer.
The sign-in is part of the share: the dialog (@ggml-org/llama-huggingface)
asks for it with "Sign in with Hugging Face" (contribute-repos: the app
creates datasets and writes only to the ones it created) or with a pasted
access token. It then shows the datasets the account can add to as tiles,
with a tile to create a new one (public unless the private option is
ticked); with none to add to, it asks for the name of a new dataset. A
pasted token reaches every dataset of the account; a sign-in reaches the
ones this browser shared to.
Once shared, the dialog shows the trace as a file with the first messages
of the conversation fading out below it, and every action in one place at
the bottom right.
Once signed in, Settings > General shows the account with its Sign out;
before that it shows nothing.
The builds we release have the sharing: the prebuilt UI llama-server
downloads, the llama-server images and the npm package. A build of your
own has it only when asked for. VITE_PUBLIC_HUGGING_FACE=true bundles the
package's sign-in, upload and dialogs; without it the package's Svelte
entry resolves to an inert stand-in, which CI checks against the bundle
built with it. The dev server, the tests and Storybook have it.
-DLLAMA_UI_HUGGING_FACE=ON adds it to llama-server's UI built from source
(it builds again when the option changes), and the Docker images take the
variable as a build argument.
The conversation menu is now one component, ConversationActions, used by
the sidebar row, the search results and the chat tabs, so each offers the
same actions.
Llama Chat and its llama-chat alias go to 0.4.0.
Assisted-by: Claude (Opus 5.5 Medium)
diff --git a/.devops/cann.Dockerfile b/.devops/cann.Dockerfile
index 83beced0a..eb871a504 100644
--- a/.devops/cann.Dockerfile
+++ b/.devops/cann.Dockerfile
@@ -18,6 +18,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
+# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
+ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -25,11 +27,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
-# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
+# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
+COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/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 fb3b5e9d9..be2602e0f 100644
--- a/.devops/cpu.Dockerfile
+++ b/.devops/cpu.Dockerfile
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
+# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
+ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -15,11 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
-# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
+# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
+COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/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 058212e2c..a7649543c 100644
--- a/.devops/cuda.Dockerfile
+++ b/.devops/cuda.Dockerfile
@@ -16,6 +16,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
+# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
+ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -23,11 +25,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
-# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
+# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
+COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/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 5a4ddabe5..978bef5e8 100644
--- a/.devops/intel.Dockerfile
+++ b/.devops/intel.Dockerfile
@@ -10,6 +10,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
+# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
+ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -17,11 +19,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
-# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
+# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
+COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/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 665688855..5d8f5857d 100644
--- a/.devops/musa.Dockerfile
+++ b/.devops/musa.Dockerfile
@@ -14,6 +14,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
+# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
+ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -21,11 +23,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
-# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
+# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
+COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
FROM ${BASE_MUSA_DEV_CONTAINER} AS build
diff --git a/.devops/openvino.Dockerfile b/.devops/openvino.Dockerfile
index 1509796dd..be2891742 100644
--- a/.devops/openvino.Dockerfile
+++ b/.devops/openvino.Dockerfile
@@ -27,6 +27,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
+# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
+ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -34,11 +36,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
-# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
+# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
+COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
## Build Image
diff --git a/.devops/rocm.Dockerfile b/.devops/rocm.Dockerfile
index b7e5938d9..d7c821af7 100644
--- a/.devops/rocm.Dockerfile
+++ b/.devops/rocm.Dockerfile
@@ -16,6 +16,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
+# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
+ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -23,11 +25,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
-# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
+# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
+COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
### Build image
diff --git a/.devops/vulkan.Dockerfile b/.devops/vulkan.Dockerfile
index 4e97422d6..23b55c1d5 100644
--- a/.devops/vulkan.Dockerfile
+++ b/.devops/vulkan.Dockerfile
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
+# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
+ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -15,11 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
-# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
+# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
+COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/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 da2fea2df..fdde42c75 100644
--- a/.devops/zendnn.Dockerfile
+++ b/.devops/zendnn.Dockerfile
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
+# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
+ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -15,11 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
-# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
+# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
+COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index 2272ac35a..99c984a47 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -269,6 +269,7 @@ jobs:
build-args: |
BUILD_DATE=${{ steps.build_date.outputs.date }}
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
+ VITE_PUBLIC_HUGGING_FACE=true
APP_REVISION=${{ steps.checkout.outputs.commit }}
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
@@ -306,6 +307,7 @@ jobs:
build-args: |
BUILD_DATE=${{ steps.build_date.outputs.date }}
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
+ VITE_PUBLIC_HUGGING_FACE=true
APP_REVISION=${{ steps.checkout.outputs.commit }}
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
@@ -343,6 +345,7 @@ jobs:
build-args: |
BUILD_DATE=${{ steps.build_date.outputs.date }}
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
+ VITE_PUBLIC_HUGGING_FACE=true
APP_REVISION=${{ steps.checkout.outputs.commit }}
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
diff --git a/.github/workflows/ui-build-self-hosted.yml b/.github/workflows/ui-build-self-hosted.yml
index 660786ff7..53ee7563e 100644
--- a/.github/workflows/ui-build-self-hosted.yml
+++ b/.github/workflows/ui-build-self-hosted.yml
@@ -33,6 +33,9 @@ jobs:
- name: Build application
run: npm run build
working-directory: ui/apps/chat
+ env:
+ # as in ui-build.yml: the UI under test has the Hugging Face lib
+ VITE_PUBLIC_HUGGING_FACE: "true"
- name: Upload built UI
uses: actions/upload-artifact@v6
diff --git a/.github/workflows/ui-build.yml b/.github/workflows/ui-build.yml
index 67fc2fadc..f1d054099 100644
--- a/.github/workflows/ui-build.yml
+++ b/.github/workflows/ui-build.yml
@@ -47,6 +47,8 @@ jobs:
- name: Build application
env:
LLAMA_BUILD_NUMBER: ${{ steps.version.outputs.ui_version }}
+ # the UI that the releases and the prebuilt download are made of has the Hugging Face lib
+ VITE_PUBLIC_HUGGING_FACE: "true"
run: npm run build
working-directory: ui/apps/chat
diff --git a/.github/workflows/ui-chat-publish.yml b/.github/workflows/ui-chat-publish.yml
index 193aa375f..31f72e1ce 100644
--- a/.github/workflows/ui-chat-publish.yml
+++ b/.github/workflows/ui-chat-publish.yml
@@ -94,6 +94,9 @@ jobs:
# This folder's .npmrc sets ignore-scripts, so npm never builds it: this step does.
run: LLAMA_BUILD_NUMBER="b$(git rev-list --count HEAD)" npm run build
working-directory: ${{ env.APP_DIR }}
+ env:
+ # the same app as the UI llama-server embeds, with the Hugging Face lib
+ VITE_PUBLIC_HUGGING_FACE: "true"
- name: Test the CLI and the alias version
run: npx vitest --project=unit --run tests/unit/cli.test.ts
diff --git a/.github/workflows/ui-self-hosted.yml b/.github/workflows/ui-self-hosted.yml
index f254f3b0c..634526c10 100644
--- a/.github/workflows/ui-self-hosted.yml
+++ b/.github/workflows/ui-self-hosted.yml
@@ -21,6 +21,7 @@ on:
'ui/lib/ui/**.*',
'ui/lib/voice/**.*',
'ui/lib/harness/**.*',
+ 'ui/lib/huggingface/**.*',
'tools/server/tests/**.*'
]
pull_request:
@@ -32,6 +33,7 @@ on:
'ui/lib/ui/**.*',
'ui/lib/voice/**.*',
'ui/lib/harness/**.*',
+ 'ui/lib/huggingface/**.*',
'tools/server/tests/**.*'
]
@@ -127,6 +129,9 @@ jobs:
if: ${{ always() && steps.setup.conclusion == 'success' }}
run: npm run build-storybook
working-directory: ui/apps/chat
+ env:
+ # its stories show the Hugging Face lib
+ VITE_PUBLIC_HUGGING_FACE: "true"
- name: Run UI tests
if: ${{ always() && steps.setup.conclusion == 'success' }}
diff --git a/.github/workflows/ui-storybook.yml b/.github/workflows/ui-storybook.yml
index fe922b1a2..f5c9716e1 100644
--- a/.github/workflows/ui-storybook.yml
+++ b/.github/workflows/ui-storybook.yml
@@ -49,6 +49,9 @@ jobs:
- name: Build Storybook
run: npm run build-storybook
working-directory: ui/apps/chat
+ env:
+ # its stories show the Hugging Face lib
+ VITE_PUBLIC_HUGGING_FACE: "true"
- name: Write the Space card
run: |
diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml
index 60e5e8582..2c3e954d6 100644
--- a/.github/workflows/ui.yml
+++ b/.github/workflows/ui.yml
@@ -275,6 +275,71 @@ jobs:
fi
working-directory: ui/apps/chat
+ huggingface-lib-bundle:
+ name: Hugging Face lib in the bundle
+ 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/apps/chat
+
+ - name: Build with and without the Hugging Face lib
+ run: |
+ npm run build
+ VITE_PUBLIC_HUGGING_FACE=true LLAMA_UI_OUT_DIR=dist-with-sharing npm run build
+ working-directory: ui/apps/chat
+
+ # a text of the lib's sign-in: it is in the bundle only when the lib is
+ - name: Check the Hugging Face lib is only in the bundle built with it
+ run: |
+ marker="Hugging Face sent no access token back"
+ if ! grep -rlq "$marker" dist-with-sharing; then
+ echo "The bundle built with the Hugging Face lib does not contain it" && exit 1
+ fi
+ if grep -rlq "$marker" dist; then
+ echo "The default bundle contains the Hugging Face lib" && exit 1
+ fi
+ working-directory: ui/apps/chat
+
+ huggingface-lib-checks:
+ name: Hugging Face lib 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/huggingface
+
+ # its plain TypeScript; the components are checked with the app that compiles them
+ - name: Run type checking
+ run: npm run check
+ working-directory: ui/lib/huggingface
+
+ - name: Run tests
+ run: npm test
+ working-directory: ui/lib/huggingface
+
e2e-tests:
name: E2E Tests
needs: ui-build
@@ -317,6 +382,9 @@ jobs:
if: ${{ always() && steps.playwright.conclusion == 'success' }}
run: npm run build-storybook
working-directory: ui/apps/chat
+ env:
+ # its stories show the Hugging Face lib
+ VITE_PUBLIC_HUGGING_FACE: "true"
- name: Run UI tests
if: ${{ always() && steps.playwright.conclusion == 'success' }}
diff --git a/scripts/ui-assets.cmake b/scripts/ui-assets.cmake
index 633b19a79..931ae4b77 100644
--- a/scripts/ui-assets.cmake
+++ b/scripts/ui-assets.cmake
@@ -16,19 +16,24 @@ set(HF_VERSION "" CACHE STRING "Version to download (empty = resolve from
set(HF_ENABLED "" CACHE STRING "Whether to allow HF Bucket download (ON/OFF)")
set(BUILD_UI "" CACHE STRING "Build UI via npm (ON/OFF)")
set(LLAMA_UI_GZIP "" CACHE STRING "Apply gzip compress to assets to save bandwidth")
+# OFF unless it is turned on: a UI built here has sharing conversations to Hugging Face in it
+# only when asked for (the prebuilt one, which releases are made of, has it)
+set(LLAMA_UI_HUGGING_FACE OFF CACHE STRING "Whether the UI built here has sharing to Hugging Face (ON/OFF)")
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),
-# and those of Llama Voice and the harness in lib/voice and lib/harness (see
-# ui/apps/chat/vite.config.ts).
+# and those of Llama Voice, the harness and Llama Hugging Face in lib/voice, lib/harness and
+# lib/huggingface (see ui/apps/chat/vite.config.ts).
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(UI_VOICE_DIR "${UI_SOURCE_DIR}/../../lib/voice")
set(HARNESS_DIR "${UI_SOURCE_DIR}/../../lib/harness")
+set(UI_HUGGINGFACE_DIR "${UI_SOURCE_DIR}/../../lib/huggingface")
set(STAMP_FILE "${UI_BINARY_DIR}/.ui-stamp")
+set(BUILD_OPTIONS_STAMP "${UI_BINARY_DIR}/.ui-build-options")
set(EMBED_STAMP "${UI_BINARY_DIR}/.ui-embed.sha256")
set(UI_CPP "${UI_BINARY_DIR}/ui.cpp")
set(UI_H "${UI_BINARY_DIR}/ui.h")
@@ -295,6 +300,16 @@ function(emit_files dist_dir)
message(STATUS "UI: embedded ${n_assets} assets")
endfunction()
+# What the npm build is told, as environment variables (see ui/apps/chat/vite.config.ts).
+# They are set either way, so the build does not depend on the environment it runs in.
+function(ui_build_options out_var)
+ if(LLAMA_UI_HUGGING_FACE)
+ set(${out_var} "VITE_PUBLIC_HUGGING_FACE=true" PARENT_SCOPE)
+ else()
+ set(${out_var} "VITE_PUBLIC_HUGGING_FACE=false" PARENT_SCOPE)
+ endif()
+endfunction()
+
function(npm_build_should_skip out_var)
set(${out_var} FALSE PARENT_SCOPE)
@@ -306,6 +321,18 @@ function(npm_build_should_skip out_var)
return()
endif()
+ # an output built with other options is out of date, whatever its sources;
+ # one from before the options has none of the opt-in features
+ ui_build_options(options)
+ set(built_with "VITE_PUBLIC_HUGGING_FACE=false")
+ if(EXISTS "${BUILD_OPTIONS_STAMP}")
+ file(READ "${BUILD_OPTIONS_STAMP}" built_with)
+ string(STRIP "${built_with}" built_with)
+ endif()
+ if(NOT built_with STREQUAL options)
+ return()
+ endif()
+
if(NOT EXISTS "${UI_SOURCE_DIR}/sources.cmake")
return()
endif()
@@ -380,6 +407,12 @@ function(stage_sources)
DESTINATION "${STAGE_DIR}/lib/harness"
NO_SOURCE_PERMISSIONS
)
+
+ # and of Llama Hugging Face, its sources only too
+ file(COPY "${UI_HUGGINGFACE_DIR}/src"
+ DESTINATION "${STAGE_DIR}/lib/huggingface"
+ NO_SOURCE_PERMISSIONS
+ )
endfunction()
function(npm_build out_var)
@@ -440,9 +473,11 @@ function(npm_build out_var)
file(MAKE_DIRECTORY "${DIST_DIR}")
- message(STATUS "UI: running npm run build, output -> ${DIST_DIR}")
+ ui_build_options(options)
+
+ message(STATUS "UI: running npm run build (${options}), output -> ${DIST_DIR}")
execute_process(
- COMMAND ${CMAKE_COMMAND} -E env "LLAMA_UI_OUT_DIR=${DIST_DIR}" "LLAMA_UI_VERSION=${HF_VERSION}" "LLAMA_BUILD_NUMBER=${LLAMA_BUILD_NUMBER}"
+ COMMAND ${CMAKE_COMMAND} -E env "LLAMA_UI_OUT_DIR=${DIST_DIR}" "LLAMA_UI_VERSION=${HF_VERSION}" "LLAMA_BUILD_NUMBER=${LLAMA_BUILD_NUMBER}" "${options}"
${NPM_EXECUTABLE} run build
WORKING_DIRECTORY "${WORK_DIR}"
RESULT_VARIABLE rc
@@ -461,6 +496,7 @@ function(npm_build out_var)
message(STATUS "UI: npm build succeeded")
file(REMOVE "${STAMP_FILE}")
+ file(WRITE "${BUILD_OPTIONS_STAMP}" "${options}")
set(${out_var} TRUE PARENT_SCOPE)
endfunction()
diff --git a/ui/README.md b/ui/README.md
index 6c7acf476..43ba242cd 100644
--- a/ui/README.md
+++ b/ui/README.md
@@ -5,10 +5,11 @@ The UI of llama.cpp: the packages in `lib` and the apps built on them.
```text
ui/
├── lib/
-│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components
-│ ├── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation
-│ ├── harness/ @ggml-org/llama-harness: the agentic loop, headless
-│ └── demo/ @ggml-org/llama-demo: scripted demo videos for PRs and docs
+│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components
+│ ├── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation
+│ ├── harness/ @ggml-org/llama-harness: the agentic loop, headless
+│ ├── demo/ @ggml-org/llama-demo: scripted demo videos for PRs and docs
+│ └── huggingface/ @ggml-org/llama-huggingface: a Hugging Face account, and sharing to it
└── apps/
└── chat/ Llama Chat, the chat app that llama-server serves
```
@@ -24,6 +25,9 @@ ui/
- [`lib/demo`](lib/demo/README.md) records scripted demo videos of the apps for PRs and docs, and renders them on the
Llama brand. It is Node TypeScript that an app adds as a local `file:` dependency and imports by name, with the app's own
Playwright; it is private, not published to npm.
+- [`lib/huggingface`](lib/huggingface/README.md) gives an app a Hugging Face account: signing in from the browser,
+ and sharing a conversation to a dataset as an agent trace, with the components for both. It knows no app; apps in
+ this repo compile its sources too. It is not published yet.
- [`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.
diff --git a/ui/apps/chat/.env.example b/ui/apps/chat/.env.example
index 8941a8a90..4210659f6 100644
--- a/ui/apps/chat/.env.example
+++ b/ui/apps/chat/.env.example
@@ -1,6 +1,9 @@
VITE_PUBLIC_APP_NAME='Llama Chat'
# 'false' builds a chat-only app: no tools, no MCP, no agentic loop
# VITE_PUBLIC_AGENTIC='false'
+# 'true' builds an app with sharing conversations to Hugging Face, and its sign-in; a build
+# has neither without it, the dev server has both unless this is 'false'
+# VITE_PUBLIC_HUGGING_FACE='true'
VITE_DEBUG='true'
VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033'
diff --git a/ui/apps/chat/CMakeLists.txt b/ui/apps/chat/CMakeLists.txt
index 61776f96d..ed76c1798 100644
--- a/ui/apps/chat/CMakeLists.txt
+++ b/ui/apps/chat/CMakeLists.txt
@@ -2,6 +2,7 @@ set(TARGET llama-ui)
set(LLAMA_UI_HF_BUCKET "ggml-org/llama-ui" CACHE STRING "Hugging Face bucket name for prebuilt UI assets")
set(LLAMA_UI_GZIP ON CACHE BOOL "Apply gzip compress to assets to save bandwidth")
+set(LLAMA_UI_HUGGING_FACE OFF CACHE BOOL "Include sharing conversations to Hugging Face, and its sign-in, in a UI built from source (the prebuilt UI has them)")
# Backward compat: forward old var to new one
if(DEFINED LLAMA_BUILD_WEBUI)
@@ -79,6 +80,7 @@ add_custom_target(llama-ui-assets ALL
"-DHF_ENABLED=${LLAMA_USE_PREBUILT_UI}"
"-DBUILD_UI=${LLAMA_BUILD_UI}"
"-DLLAMA_UI_GZIP=${LLAMA_UI_GZIP}"
+ "-DLLAMA_UI_HUGGING_FACE=${LLAMA_UI_HUGGING_FACE}"
-P "${PROJECT_SOURCE_DIR}/scripts/ui-assets.cmake"
COMMENT "Provisioning UI assets"
VERBATIM
diff --git a/ui/apps/chat/DESIGN.md b/ui/apps/chat/DESIGN.md
index cda28f00d..ae905de93 100644
--- a/ui/apps/chat/DESIGN.md
+++ b/ui/apps/chat/DESIGN.md
@@ -715,6 +715,9 @@ here; if something really is missing, add it here first.
- **Sizes:** Tailwind's 4px spacing scale. Icons are Lucide, `size-icon-md` (16px), or
`size-icon-sm` (14px) in compact controls. Controls are `h-control-sm`, `h-control-md` or
`h-control-lg` (32, 36, 40px).
+- **Sharing:** anything that shares out of the app (an action, a button, a dialog title) uses
+ one icon, Lucide's `Share`: a box with an arrow leaving it (`SHARE_ICON`). Never `Share2`,
+ the three joined dots.
- **Surfaces:** one surface utility per element (`card-surface`, `matte-float`, `matte-key`,
`matte-well`), never raw `shadow-*`, `border-*` and `backdrop-blur-*` combinations.
- **Tokens:** read a semantic token directly. A component token is only for a value the
diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md
index 639587467..ed783db1d 100644
--- a/ui/apps/chat/README.md
+++ b/ui/apps/chat/README.md
@@ -92,17 +92,18 @@ 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/<name>` 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 |
-| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) |
-| 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, 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, MCP, settings and dialogs, grouped by area |
+| UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI |
+| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) |
+| Hugging Face | `ui/lib/huggingface` | A Hugging Face account: sign-in and sharing conversations as agent traces (`@ggml-org/llama-huggingface`) |
+| 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, 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` |
```mermaid
flowchart LR
@@ -166,6 +167,8 @@ llama-server embeds it: when llama-server is built, `scripts/ui-assets.cmake` ta
**Chat-only build.** `VITE_PUBLIC_AGENTIC=false npm run build` builds an app that is a plain chat for every server, and `npm run dev:chat-only` runs the dev server the same way. Llama Harness's loop is left out of its bundle.
+**Sharing to Hugging Face.** Sharing a conversation to a Hugging Face dataset, and the sign-in it needs, is in the builds we release: the prebuilt UI llama-server downloads, the llama-server Docker images and the npm package. A build of your own leaves it out unless you ask for it: `npm run build` bundles an app without `@ggml-org/llama-huggingface`, whose sign-in, upload and dialogs are then not in it, and the app offers no sharing; `VITE_PUBLIC_HUGGING_FACE=true npm run build` bundles one with it. The dev server, the tests and Storybook have it. To embed a UI with it that llama-server builds from source (`-DLLAMA_BUILD_UI=ON`), configure with `-DLLAMA_UI_HUGGING_FACE=ON`; it builds again when the option changes, and the default prebuilt UI has the sharing whatever the option. A Docker image takes `--build-arg VITE_PUBLIC_HUGGING_FACE=true`. A `dist/` you put in `ui/apps/chat` is embedded as it is.
+
```text
ui/apps/chat/
├── src/
diff --git a/ui/apps/chat/alias/package.json b/ui/apps/chat/alias/package.json
index cf9582d80..529f0d10b 100644
--- a/ui/apps/chat/alias/package.json
+++ b/ui/apps/chat/alias/package.json
@@ -1,6 +1,6 @@
{
"name": "llama-chat",
- "version": "0.3.1",
+ "version": "0.4.0",
"description": "npx llama-chat: runs Llama Chat, the chat app for llama.cpp. Same as npx @ggml-org/llama-chat.",
"keywords": [
"llama.cpp",
@@ -28,6 +28,6 @@
"node": ">=20"
},
"dependencies": {
- "@ggml-org/llama-chat": "0.3.1"
+ "@ggml-org/llama-chat": "0.4.0"
}
}
diff --git a/ui/apps/chat/package-lock.json b/ui/apps/chat/package-lock.json
index 2f400eaa0..898fb4ba6 100644
--- a/ui/apps/chat/package-lock.json
+++ b/ui/apps/chat/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@ggml-org/llama-chat",
- "version": "0.3.1",
+ "version": "0.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ggml-org/llama-chat",
- "version": "0.3.1",
+ "version": "0.4.0",
"license": "MIT",
"bin": {
"llama-chat": "bin/cli.js"
diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json
index b0342802c..fdf1c8add 100644
--- a/ui/apps/chat/package.json
+++ b/ui/apps/chat/package.json
@@ -1,6 +1,6 @@
{
"name": "@ggml-org/llama-chat",
- "version": "0.3.1",
+ "version": "0.4.0",
"description": "Llama Chat, the chat app for llama.cpp. Run it with npx @ggml-org/llama-chat against any llama-server.",
"keywords": [
"llama.cpp",
diff --git a/ui/apps/chat/sources.cmake b/ui/apps/chat/sources.cmake
index f12daa813..e2ae0ecdc 100644
--- a/ui/apps/chat/sources.cmake
+++ b/ui/apps/chat/sources.cmake
@@ -8,6 +8,8 @@ set(UI_SOURCE_GLOBS
# Llama Voice, also compiled from source
../../lib/voice/src/*
../../lib/harness/src/*
+ # and Llama Hugging Face
+ ../../lib/huggingface/src/*
)
set(UI_SOURCE_FILES
diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css
index 6620a32a4..b6bd589a5 100644
--- a/ui/apps/chat/src/app.css
+++ b/ui/apps/chat/src/app.css
@@ -4,6 +4,8 @@
which this Storybook shows as well */
@source '../tests/stories';
@source '../../../lib/ui/tests/stories';
+/* Llama Hugging Face's components (ui/lib/huggingface), compiled as part of this app */
+@source '../../../lib/huggingface/src';
@plugin '@tailwindcss/forms';
@plugin '@tailwindcss/typography';
@import 'tw-animate-css';
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 0086107ee..a66c07d5e 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
@@ -9,6 +9,7 @@
} from '#lib/components/app/chat/index.ts';
import {
AGENTIC_TEXT_COPY_SEPARATOR,
+ HUGGING_FACE_ENABLED,
REASONING_TAGS,
ROUTES,
SYSTEM_MESSAGE_PLACEHOLDER
@@ -21,7 +22,7 @@
MessageType
} from '#lib/enums/index.ts';
import { DatabaseService } from '#lib/services/database.service.ts';
- import { chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts';
+ import { chatStore, conversationsStore, deviceStore, uiStore } from '#lib/stores/index.ts';
import type {
ChatMessageActions,
ChatMessageDeletionInfo,
@@ -197,6 +198,7 @@
setShowForkDialog: (show: boolean) => {
showForkDialog = show;
},
+ share: HUGGING_FACE_ENABLED ? handleShare : undefined,
get showDeleteDialog() {
return showDeleteDialog;
},
@@ -339,6 +341,14 @@
chatActions.forkConversation(message, options);
}
+ // an agentic turn renders as one message, so a share from it ends at its last step
+ function handleShare() {
+ uiStore.openConversationShare({
+ conversationId: message.convId,
+ messageId: toolMessages.at(-1)?.id ?? message.id
+ });
+ }
+
function handleNavigateToSibling(siblingId: string) {
chatActions.navigateToSibling(siblingId);
}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte
index a300da736..be0fcc028 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionIcons/ChatMessageActionIcons.svelte
@@ -9,6 +9,7 @@
ChatMessageActionIconsBranchingControls,
DialogConfirmation
} from '#lib/components/app/index.ts';
+ import { SHARE_ACTION } from '#lib/constants/index.ts';
import { getChatMessageActionsContext, getChatMessageEditContext } from '#lib/contexts/index.ts';
import { conversationsStore } from '#lib/stores/index.ts';
import { untrack } from 'svelte';
@@ -97,6 +98,14 @@
/>
{/if}
+ {#if messageActions.share}
+ <ActionIcon
+ icon={SHARE_ACTION.icon}
+ onclick={messageActions.share}
+ tooltip={SHARE_ACTION.label}
+ />
+ {/if}
+
<ActionIcon icon={Trash2} onclick={messageActions.requestDelete} tooltip="Delete" />
</div>
</div>
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageContextMenu.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageContextMenu.svelte
index 8d25ae74d..bf0030051 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageContextMenu.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageContextMenu.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import { ArrowRight, Copy, Edit, GitBranch, RefreshCw, Trash2 } from '@lucide/svelte';
import { ContextMenuActions } from '#lib/components/app/index.ts';
- import { NATIVE_CONTEXT_MENU_SELECTOR } from '#lib/constants/index.ts';
+ import { NATIVE_CONTEXT_MENU_SELECTOR, SHARE_ACTION } from '#lib/constants/index.ts';
import { getChatMessageActionsContext, getChatMessageEditContext } from '#lib/contexts/index.ts';
import { MessageRole } from '#lib/enums/index.ts';
import type { MenuAction } from '#lib/types/index.ts';
@@ -39,6 +39,7 @@
}
]
: []),
+ ...(messageActions.share ? [{ ...SHARE_ACTION, onclick: messageActions.share }] : []),
{
icon: Trash2,
label: 'Delete',
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 60f185e1b..0b5d6b52d 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
@@ -2,7 +2,11 @@
import ChatTabsItem from './ChatTabsItem.svelte';
import ChatTabsNewChatButton from './ChatTabsNewChatButton.svelte';
import { ArrowRightToLine, ListX, Square, SquarePen, X } from '@lucide/svelte';
- import { ContextMenuActions, ScrollCarousel } from '#lib/components/app/index.ts';
+ import {
+ ContextMenuActions,
+ ConversationActions,
+ ScrollCarousel
+ } from '#lib/components/app/index.ts';
import {
CHAT_TABS_MAX_WIDTH,
NEW_CHAT_LABEL,
@@ -25,16 +29,20 @@
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) {
+ return { href: view.hrefFor(id), icon: SquarePen, id, name: NEW_CHAT_LABEL };
+ }
+
+ const conversation = conversationsStore.conversations.find((c) => c.id === id);
+
+ return {
+ conversation,
+ href: view.hrefFor(id),
+ id,
+ name: conversation?.name ?? UNNAMED_CHAT_LABEL
+ };
+ })
);
// hide the New chat button while a new-chat tab is already open
@@ -126,6 +134,20 @@
});
</script>
+{#snippet tabItem(tab: (typeof tabs)[number], actions: MenuAction[])}
+ <ContextMenuActions {actions}>
+ <ChatTabsItem
+ isActive={tab.id === activeId}
+ isLoading={loadingIds.has(tab.id)}
+ onActivate={(id) => tabsStore.activate(id)}
+ onAuxClick={handleAuxClick}
+ onClose={handleClose}
+ onStop={handleStop}
+ {tab}
+ />
+ </ContextMenuActions>
+{/snippet}
+
<nav
aria-label="Open conversations"
class={[
@@ -143,17 +165,21 @@
innerClass="items-center gap-1.25"
>
{#each tabs as tab (tab.id)}
- <ContextMenuActions actions={tabActions(tab.id)}>
- <ChatTabsItem
+ <!-- a chat's tab also offers what its sidebar row does, after the tab's own actions -->
+ {#if tab.conversation}
+ <ConversationActions
+ conversation={tab.conversation}
isActive={tab.id === activeId}
- isLoading={loadingIds.has(tab.id)}
- onActivate={(id) => tabsStore.activate(id)}
- onAuxClick={handleAuxClick}
- onClose={handleClose}
- onStop={handleStop}
- {tab}
- />
- </ContextMenuActions>
+ leadingActions={tabActions(tab.id)}
+ showOpenInNewTab={false}
+ >
+ {#snippet children(actions)}
+ {@render tabItem(tab, actions)}
+ {/snippet}
+ </ConversationActions>
+ {:else}
+ {@render tabItem(tab, tabActions(tab.id))}
+ {/if}
{/each}
{#if showNewChatButton}
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogConversationShare.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogConversationShare.svelte
new file mode 100644
index 000000000..929e7aabe
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogConversationShare.svelte
@@ -0,0 +1,87 @@
+<script lang="ts">
+ import type { HfShareScope, HfTraceFile } from '@ggml-org/llama-huggingface';
+ import { HfShareDialog } from '@ggml-org/llama-huggingface/svelte';
+ import { CONVERSATION_SHARE_TEXT as TEXT, HUGGING_FACE_ENABLED } from '#lib/constants/index.ts';
+ import { ConversationShareScope } from '#lib/enums/index.ts';
+ import { ConversationTransferService } from '#lib/services/conversation-transfer.service.ts';
+ import { conversationsStore, huggingFace, uiStore } from '#lib/stores/index.ts';
+ import {
+ buildConversationTrace,
+ buildTracePreview,
+ copyToClipboard,
+ filterByLeafNodeId
+ } from '#lib/utils/index.ts';
+ import { toast } from 'svelte-sonner';
+
+ // what a conversation is, for the share dialog: its branches as scopes, and its trace
+
+ let options = $derived(uiStore.conversationShare);
+ let conversation = $derived(
+ conversationsStore.conversations.find((conv) => conv.id === options?.conversationId)
+ );
+
+ let messages = $state<DatabaseMessage[]>([]);
+
+ $effect.pre(() => {
+ const conversationId = options?.conversationId;
+
+ messages = [];
+
+ if (!conversationId) return;
+
+ void conversationsStore.getConversationMessages(conversationId).then((loaded) => {
+ if (uiStore.conversationShare?.conversationId === conversationId) messages = loaded;
+ });
+ });
+
+ function scopeOf(id: ConversationShareScope, label: string, leafId: string): HfShareScope {
+ const path = filterByLeafNodeId(messages, leafId);
+
+ return {
+ // nothing to count while the messages load
+ detail: path.length ? TEXT.messageCount(path.length) : undefined,
+ hasAttachments: path.some((message) => !!message.extra?.length),
+ id,
+ isEmpty: !path.length,
+ label
+ };
+ }
+
+ let scopes = $derived([
+ ...(options?.messageId
+ ? [scopeOf(ConversationShareScope.UP_TO_MESSAGE, TEXT.SCOPE_UP_TO_MESSAGE, options.messageId)]
+ : []),
+ scopeOf(ConversationShareScope.ALL, TEXT.SCOPE_ALL, conversation?.currNode ?? '')
+ ]);
+
+ async function buildTrace(scope: string, includeAttachments: boolean): Promise<HfTraceFile> {
+ const conversationId = options?.conversationId ?? '';
+ const [exported] = await conversationsStore.getConversationsForExport([conversationId]);
+
+ if (!exported) throw new Error(TEXT.CONVERSATION_NOT_FOUND);
+
+ const trace = buildConversationTrace(exported, {
+ includeAttachments,
+ upToMessageId: scope === ConversationShareScope.UP_TO_MESSAGE ? options?.messageId : undefined
+ });
+
+ return {
+ commitMessage: TEXT.commitMessage(trace.conv.name),
+ content: ConversationTransferService.serializeSessionToJsonl(trace),
+ path: ConversationTransferService.generateConversationFilename(trace.conv, trace.messages),
+ preview: buildTracePreview(trace)
+ };
+ }
+</script>
+
+{#if HUGGING_FACE_ENABLED}
+ <HfShareDialog
+ bind:open={() => options !== null, (open) => !open && (uiStore.conversationShare = null)}
+ account={huggingFace}
+ {buildTrace}
+ onCopyLink={(url) => void copyToClipboard(url, TEXT.LINK_COPIED)}
+ onShared={() => toast.success(TEXT.SHARED)}
+ {scopes}
+ subject={conversation ? TEXT.subject(conversation.name) : TEXT.SUBJECT_FALLBACK}
+ />
+{/if}
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/index.ts b/ui/apps/chat/src/lib/components/app/dialogs/index.ts
index ac2c655f3..09bdd1a9c 100644
--- a/ui/apps/chat/src/lib/components/app/dialogs/index.ts
+++ b/ui/apps/chat/src/lib/components/app/dialogs/index.ts
@@ -145,6 +145,16 @@ export { default as DialogConversationDelete } from './DialogConversationDelete.
*/
export { default as DialogConversationRename } from './DialogConversationRename.svelte';
+/**
+ * **DialogConversationShare** - Share a conversation to Hugging Face
+ *
+ * Uploads a conversation, or its branch up to a message, to a dataset of the user's Hugging
+ * Face account as an agent trace. The dialog itself (sign-in, dataset picker, upload) is
+ * `HfShareDialog` of @ggml-org/llama-huggingface; this component says what a conversation is:
+ * its scopes and its trace. It opens from `uiStore.conversationShare`, so it is mounted once.
+ */
+export { default as DialogConversationShare } from './DialogConversationShare.svelte';
+
/**
* **DialogGroup** - Name a new sidebar group, or rename one
*
diff --git a/ui/apps/chat/src/lib/components/app/navigation/ConversationActions.svelte b/ui/apps/chat/src/lib/components/app/navigation/ConversationActions.svelte
new file mode 100644
index 000000000..11f70042b
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/navigation/ConversationActions.svelte
@@ -0,0 +1,157 @@
+<script lang="ts">
+ import SidebarNavigationGroupSubmenu from './SidebarNavigation/SidebarNavigationGroupSubmenu.svelte';
+ import {
+ Download,
+ FolderInput,
+ ListChecks,
+ PanelTopOpen,
+ Pencil,
+ Pin,
+ PinOff,
+ Trash2,
+ Unlink
+ } from '@lucide/svelte';
+ import {
+ HUGGING_FACE_ENABLED,
+ SHARE_ACTION,
+ SHORTCUT_DELETE_CONVERSATION,
+ SHORTCUT_EDIT_CONVERSATION,
+ SHORTCUT_EXPORT_CONVERSATION
+ } from '#lib/constants/index.ts';
+ import type { MenuKind } from '#lib/enums/index.ts';
+ import {
+ conversationsStore,
+ groupsStore,
+ settingsStore,
+ tabsStore,
+ uiStore
+ } from '#lib/stores/index.ts';
+ import type { MenuAction } from '#lib/types/index.ts';
+ import type { Snippet } from 'svelte';
+
+ const MOVE_TO_GROUP_LABEL = 'Move to group';
+
+ interface Props {
+ conversation: DatabaseConversation;
+ /** The active conversation's menu shows the shortcuts, which act on it. */
+ isActive?: boolean;
+ /** Offer "Open in new tab"; a tab's own menu leaves it out. */
+ showOpenInNewTab?: boolean;
+ /** Actions of the caller's own, listed before the conversation's, with a separator between. */
+ leadingActions?: MenuAction[];
+ /** Enter the sidebar's selection mode; the action shows only when given. */
+ onEnterSelectionMode?: () => void;
+ /** Renders the menu that shows the actions. */
+ children: Snippet<[MenuAction[]]>;
+ }
+
+ let {
+ children,
+ conversation,
+ isActive = false,
+ leadingActions = [],
+ onEnterSelectionMode,
+ showOpenInNewTab = true
+ }: Props = $props();
+
+ let canOpenInNewTab = $derived(
+ showOpenInNewTab && Boolean(settingsStore.config.conversationTabs)
+ );
+
+ // a group the chat points at may be gone; then it is in none
+ let groupId = $derived(groupsStore.groupIdOf(conversation));
+
+ // menus sit on clickable rows and tabs, so an action must not also click them
+ function run(action: () => void) {
+ return (event: Event) => {
+ event.stopPropagation();
+ action();
+ };
+ }
+
+ function setGroup(groupId: string | null) {
+ void conversationsStore.setConversationGroup(conversation.id, groupId);
+ }
+
+ let conversationActions = $derived<MenuAction[]>([
+ ...(canOpenInNewTab
+ ? [
+ {
+ icon: PanelTopOpen,
+ label: 'Open in new tab',
+ onclick: run(() => void tabsStore.openInNewTab(conversation.id))
+ }
+ ]
+ : []),
+ {
+ icon: conversation.pinned ? PinOff : Pin,
+ label: conversation.pinned ? 'Unpin' : 'Pin',
+ onclick: run(() => void conversationsStore.toggleConversationPin(conversation.id)),
+ separator: canOpenInNewTab
+ },
+ {
+ icon: Pencil,
+ label: 'Edit',
+ onclick: run(() => uiStore.openConversationRename(conversation.id)),
+ shortcut: isActive ? SHORTCUT_EDIT_CONVERSATION : undefined
+ },
+ // the picker stands in for the submenu where a phone's menu shows no flyouts
+ {
+ icon: FolderInput,
+ label: MOVE_TO_GROUP_LABEL,
+ onclick: run(() => uiStore.openGroupPicker({ currentGroupId: groupId, onSelect: setGroup })),
+ submenu: groupSubmenu
+ },
+ ...(groupId
+ ? [{ icon: Unlink, label: 'Remove from group', onclick: run(() => setGroup(null)) }]
+ : []),
+ {
+ icon: Download,
+ label: 'Export',
+ onclick: run(() => void conversationsStore.downloadConversation(conversation.id)),
+ shortcut: isActive ? SHORTCUT_EXPORT_CONVERSATION : undefined
+ },
+ ...(HUGGING_FACE_ENABLED
+ ? [
+ {
+ ...SHARE_ACTION,
+ onclick: run(() => uiStore.openConversationShare({ conversationId: conversation.id }))
+ }
+ ]
+ : []),
+ ...(onEnterSelectionMode
+ ? [{ icon: ListChecks, label: 'Select', onclick: run(onEnterSelectionMode) }]
+ : []),
+ {
+ icon: Trash2,
+ label: 'Delete',
+ onclick: run(() => uiStore.openConversationDelete(conversation.id)),
+ separator: true,
+ shortcut: isActive ? SHORTCUT_DELETE_CONVERSATION : undefined,
+ variant: 'destructive'
+ }
+ ]);
+
+ // the caller's own actions come first, and the conversation's start under a separator
+ let actions = $derived<MenuAction[]>(
+ leadingActions.length
+ ? [
+ ...leadingActions,
+ { ...conversationActions[0], separator: true },
+ ...conversationActions.slice(1)
+ ]
+ : conversationActions
+ );
+</script>
+
+{@render children(actions)}
+
+{#snippet groupSubmenu({ close, kind }: { close: () => void; kind: MenuKind })}
+ <SidebarNavigationGroupSubmenu
+ currentGroupId={groupId}
+ {kind}
+ label={MOVE_TO_GROUP_LABEL}
+ onClose={close}
+ onSelect={setGroup}
+ />
+{/snippet}
diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte
index ec77caace..2193aef89 100644
--- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte
+++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte
@@ -5,6 +5,7 @@
ActionIcon,
DialogConversationDelete,
DialogConversationRename,
+ DialogConversationShare,
DialogDiscoverModels,
DialogGroup,
DialogGroupPicker,
@@ -45,7 +46,7 @@
import { buildConversationTree, hapticTap, remToPx } from '#lib/utils/index.ts';
import { goto } from '$app/navigation';
import { page } from '$app/state';
- import { tick } from 'svelte';
+ import { tick, untrack } from 'svelte';
import { SvelteSet } from 'svelte/reactivity';
import { fade } from 'svelte/transition';
@@ -172,11 +173,9 @@
let isSelectionMode = $state(false);
let selectedIds = new SvelteSet<string>();
- let renameDialogOpen = $state(false);
let settingsDialogOpen = $state(false);
// a phone's settings: a sheet over the page, where a desktop or tablet opens the dialog
let settingsSheetOpen = $state(false);
- let renameTargetConversationId = $state<string | null>(null);
let renameDraft = $state('');
let renameOriginalTitle = $state('');
@@ -314,19 +313,25 @@
navigateBehind(() => goto(RouterService.chat(id)));
}
- async function handleEditConversation(id: string) {
- const conversation = conversationsStore.conversations.find((conv) => conv.id === id);
+ // the sidebar hosts the rename and delete dialogs for every conversation menu, tabs included
+ let renameTarget = $derived(
+ conversationsStore.conversations.find((conv) => conv.id === uiStore.conversationRenameId)
+ );
- if (!conversation) return;
+ let renameTargetId = $derived(renameTarget?.id);
- renameTargetConversationId = id;
- renameOriginalTitle = conversation.name;
- renameDraft = conversation.name;
- renameDialogOpen = true;
- }
+ // a fresh draft every time the rename dialog opens, not when the conversation changes under it
+ $effect.pre(() => {
+ if (!renameTargetId) return;
+
+ untrack(() => {
+ renameOriginalTitle = renameTarget?.name ?? '';
+ renameDraft = renameOriginalTitle;
+ });
+ });
async function handleRenameConfirm() {
- const id = renameTargetConversationId;
+ const id = renameTarget?.id;
if (!id) return;
@@ -336,33 +341,19 @@
await conversationsStore.updateConversationName(id, nextName);
- renameDialogOpen = false;
- renameTargetConversationId = null;
+ uiStore.conversationRenameId = null;
}
function handleRenameCancel() {
- renameDialogOpen = false;
- renameTargetConversationId = null;
+ uiStore.conversationRenameId = null;
renameDraft = '';
renameOriginalTitle = '';
}
- let deleteDialogOpen = $state(false);
- let deleteTargetId = $state<string | null>(null);
-
- function handleDeleteConversation(id: string) {
- const conversation = conversationsStore.conversations.find((conv) => conv.id === id);
-
- if (!conversation) return;
-
- deleteTargetId = conversation.id;
- deleteDialogOpen = true;
- }
-
async function handleDeleteConfirm() {
- const id = deleteTargetId;
+ const id = uiStore.conversationDeleteId;
- deleteDialogOpen = false;
+ uiStore.conversationDeleteId = null;
if (!id) return;
@@ -370,7 +361,7 @@
}
function handleDeleteCancel() {
- deleteDialogOpen = false;
+ uiStore.conversationDeleteId = null;
}
function handleStopGeneration(id: string) {
@@ -688,8 +679,6 @@
onBulkExport={handleBulkExport}
onBulkPinToggle={handleBulkPinToggle}
onCloseSelection={exitSelectionMode}
- onDelete={handleDeleteConversation}
- onEdit={handleEditConversation}
onEnterSelectionMode={enterSelectionMode}
onRowMouseDown={handleRowMouseDown}
onSelect={selectConversation}
@@ -771,7 +760,7 @@
{/if}
<DialogConversationRename
- bind:open={renameDialogOpen}
+ bind:open={() => !!renameTarget, (open) => !open && handleRenameCancel()}
bind:value={renameDraft}
currentTitle={renameOriginalTitle}
onCancel={handleRenameCancel}
@@ -779,7 +768,7 @@
/>
<DialogConversationDelete
- bind:open={deleteDialogOpen}
+ bind:open={() => uiStore.conversationDeleteId !== null, (open) => !open && handleDeleteCancel()}
onCancel={handleDeleteCancel}
onConfirm={handleDeleteConfirm}
/>
@@ -800,6 +789,8 @@
<DialogGroupPicker />
+<DialogConversationShare />
+
<ModelsManagerModelDrawer />
<style>
diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationConversationItem.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationConversationItem.svelte
index a59aaddb8..c986ea94f 100644
--- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationConversationItem.svelte
+++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationConversationItem.svelte
@@ -1,41 +1,24 @@
<script lang="ts">
- import SidebarNavigationGroupSubmenu from './SidebarNavigationGroupSubmenu.svelte';
import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox';
import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip';
+ import { GitBranch, Loader2, MoreHorizontal, Square } from '@lucide/svelte';
import {
- Download,
- FolderInput,
- GitBranch,
- ListChecks,
- Loader2,
- MoreHorizontal,
- PanelTopOpen,
- Pencil,
- Pin,
- PinOff,
- Square,
- Trash2,
- Unlink
- } from '@lucide/svelte';
- import { ContextMenuActions, DropdownMenuActions } from '#lib/components/app/index.ts';
+ ContextMenuActions,
+ ConversationActions,
+ DropdownMenuActions
+ } from '#lib/components/app/index.ts';
import { TruncatedText } from '#lib/components/app/index.ts';
import {
FORK_TREE_DEPTH_PADDING,
ICON_CLASS_DEFAULT,
ROW_LONG_PRESS_MS,
- SHORTCUT_DELETE_CONVERSATION,
- SHORTCUT_EDIT_CONVERSATION,
- SHORTCUT_EXPORT_CONVERSATION,
UI_DATA_ATTRS
} from '#lib/constants/index.ts';
- import type { MenuKind } from '#lib/enums/index.ts';
import { useLongPress } from '#lib/hooks/use-long-press.svelte.ts';
import { RouterService } from '#lib/services/router.service.ts';
import {
chatStore,
- conversationsStore,
deviceStore,
- groupsStore,
settingsStore,
sidebarDragStore,
tabsStore,
@@ -51,8 +34,6 @@
conversation: DatabaseConversation;
isSelectionMode?: boolean;
isSelected?: boolean;
- onDelete?: (id: string) => void;
- onEdit?: (id: string) => void;
onSelect?: (id: string) => void;
onStop?: (id: string) => void;
onToggleSelect?: (id: string) => void;
@@ -67,8 +48,6 @@
isActive = false,
isSelected = false,
isSelectionMode = false,
- onDelete,
- onEdit,
onEnterSelectionMode,
onRowMouseDown,
onSelect,
@@ -111,16 +90,6 @@
sidebarDragStore.pressConversation(event, conversation.id);
}
- function handleEdit(event: Event) {
- event.stopPropagation();
- onEdit?.(conversation.id);
- }
-
- function handleDelete(event: Event) {
- event.stopPropagation();
- onDelete?.(conversation.id);
- }
-
function handleStop(event: Event) {
event.stopPropagation();
onStop?.(conversation.id);
@@ -140,102 +109,7 @@
openInNewTab();
}
- function setGroup(groupId: string | null) {
- void conversationsStore.setConversationGroup(conversation.id, groupId);
- }
-
- // a group the chat points at may be gone; then it is in none
- let groupId = $derived(groupsStore.groupIdOf(conversation));
-
- // the picker stands in for the submenu where a phone's menu shows no flyouts
- function handlePickGroup(event: Event) {
- event.stopPropagation();
- uiStore.openGroupPicker({ currentGroupId: groupId, onSelect: setGroup });
- }
-
- // a chat in a group can move to another one or leave it, a loose chat can join one
- let groupActions = $derived<MenuAction[]>([
- {
- icon: FolderInput,
- label: 'Move to group',
- onclick: handlePickGroup,
- submenu: groupSubmenu
- },
- ...(groupId
- ? [
- {
- icon: Unlink,
- label: 'Remove from group',
- onclick: (event: Event) => {
- event.stopPropagation();
- setGroup(null);
- }
- }
- ]
- : [])
- ]);
-
- // the "more actions" dropdown and the right-click menu offer the same actions; the
- // shortcuts act on the active conversation, so only its row shows them
- let actions = $derived<MenuAction[]>([
- ...(canOpenInNewTab
- ? [
- {
- icon: PanelTopOpen,
- label: 'Open in new tab',
- onclick: (e: Event) => {
- e.stopPropagation();
- openInNewTab();
- }
- }
- ]
- : []),
- {
- icon: conversation.pinned ? PinOff : Pin,
- label: conversation.pinned ? 'Unpin' : 'Pin',
- onclick: (e: Event) => {
- e.stopPropagation();
- handleTogglePin();
- },
- separator: canOpenInNewTab
- },
- {
- icon: Pencil,
- label: 'Edit',
- onclick: handleEdit,
- shortcut: isActive ? SHORTCUT_EDIT_CONVERSATION : undefined
- },
- ...groupActions,
- {
- icon: Download,
- label: 'Export',
- onclick: (e: Event) => {
- e.stopPropagation();
- conversationsStore.downloadConversation(conversation.id);
- },
- shortcut: isActive ? SHORTCUT_EXPORT_CONVERSATION : undefined
- },
- {
- icon: ListChecks,
- label: 'Select',
- onclick: handleEnterSelectionMode
- },
- {
- icon: Trash2,
- label: 'Delete',
- onclick: handleDelete,
- separator: true,
- shortcut: isActive ? SHORTCUT_DELETE_CONVERSATION : undefined,
- variant: 'destructive'
- }
- ]);
-
- function handleTogglePin() {
- conversationsStore.toggleConversationPin(conversation.id);
- }
-
- function handleEnterSelectionMode(event: Event) {
- event.stopPropagation();
+ function handleEnterSelectionMode() {
onEnterSelectionMode?.(conversation.id);
}
@@ -243,7 +117,7 @@
const customEvent = event as CustomEvent<{ conversationId: string }>;
if (customEvent.detail.conversationId === conversation.id && isActive) {
- handleEdit(event);
+ uiStore.openConversationRename(conversation.id);
}
}
@@ -316,142 +190,146 @@
});
</script>
-<ContextMenuActions bind:open={contextMenuOpen} {actions} disabled={isSelectionMode}>
- <button
- bind:this={rowElement}
- style:--row-hold-ms="{ROW_LONG_PRESS_MS}ms"
- class={[
- 'group flex min-h-9 w-full cursor-pointer items-center justify-between space-x-3 rounded-lg px-2 py-1.5 text-left select-none [-webkit-touch-callout:none] transition-[background-color,color,scale] hover:bg-foreground/10 hover:text-foreground max-md:min-h-12 max-md:rounded-2xl max-md:px-3.5 max-md:py-3 md:min-h-8 md:py-1',
- isLanding && 'invisible',
- isActive ? 'selected-row-surface text-accent-foreground' : 'text-foreground/75',
- contextMenuOpen && 'bg-foreground/10',
- isSelected && 'bg-primary/10 hover:bg-primary/15',
- isSelectionMode && 'is-selection-mode',
- // the row sinks while a finger holds it, and stays lit while its menu is open
- longPress.isPressing && 'scale-97 bg-foreground/10 duration-(--row-hold-ms) ease-out',
- deviceStore.isMobile && dropdownOpen && 'bg-foreground/10'
- ]}
- {...{ [UI_DATA_ATTRS.CONVERSATION_ROW]: conversation.id }}
- onauxclick={handleAuxClick}
- onclick={(e) => handleSelect(e)}
- onclickcapture={longPress.handleClickCapture}
- oncontextmenu={longPress.handleContextMenu}
- ondragstart={(e) => e.preventDefault()}
- onfocusin={handleMouseOver}
- onfocusout={(e) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
- handleMouseLeave();
- }
- }}
- onmousedown={(e) => handleRowMouseDown(e)}
- onmouseleave={handleMouseLeave}
- onmouseover={handleMouseOver}
- onpointercancel={longPress.handlePointerEnd}
- onpointerdown={(e) => {
- // a mouse drags the row, a finger holds it for its menu
- handlePointerDown(e);
- longPress.handlePointerDown(e);
- }}
- onpointermove={longPress.handlePointerMove}
- onpointerup={longPress.handlePointerEnd}
- >
- <div
- style:padding-left="{depth * FORK_TREE_DEPTH_PADDING}px"
- class="flex min-w-0 flex-1 items-center gap-2"
+<ConversationActions
+ {conversation}
+ {isActive}
+ onEnterSelectionMode={onEnterSelectionMode ? handleEnterSelectionMode : undefined}
+>
+ {#snippet children(actions)}
+ {@render row(actions)}
+ {/snippet}
+</ConversationActions>
+
+{#snippet row(actions: MenuAction[])}
+ <ContextMenuActions bind:open={contextMenuOpen} {actions} disabled={isSelectionMode}>
+ <button
+ bind:this={rowElement}
+ style:--row-hold-ms="{ROW_LONG_PRESS_MS}ms"
+ class={[
+ 'group flex min-h-9 w-full cursor-pointer items-center justify-between space-x-3 rounded-lg px-2 py-1.5 text-left select-none [-webkit-touch-callout:none] transition-[background-color,color,scale] hover:bg-foreground/10 hover:text-foreground max-md:min-h-12 max-md:rounded-2xl max-md:px-3.5 max-md:py-3 md:min-h-8 md:py-1',
+ isLanding && 'invisible',
+ isActive ? 'selected-row-surface text-accent-foreground' : 'text-foreground/75',
+ contextMenuOpen && 'bg-foreground/10',
+ isSelected && 'bg-primary/10 hover:bg-primary/15',
+ isSelectionMode && 'is-selection-mode',
+ // the row sinks while a finger holds it, and stays lit while its menu is open
+ longPress.isPressing && 'scale-97 bg-foreground/10 duration-(--row-hold-ms) ease-out',
+ deviceStore.isMobile && dropdownOpen && 'bg-foreground/10'
+ ]}
+ {...{ [UI_DATA_ATTRS.CONVERSATION_ROW]: conversation.id }}
+ onauxclick={handleAuxClick}
+ onclick={(e) => handleSelect(e)}
+ onclickcapture={longPress.handleClickCapture}
+ oncontextmenu={longPress.handleContextMenu}
+ ondragstart={(e) => e.preventDefault()}
+ onfocusin={handleMouseOver}
+ onfocusout={(e) => {
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
+ handleMouseLeave();
+ }
+ }}
+ onmousedown={(e) => handleRowMouseDown(e)}
+ onmouseleave={handleMouseLeave}
+ onmouseover={handleMouseOver}
+ onpointercancel={longPress.handlePointerEnd}
+ onpointerdown={(e) => {
+ // a mouse drags the row, a finger holds it for its menu
+ handlePointerDown(e);
+ longPress.handlePointerDown(e);
+ }}
+ onpointermove={longPress.handlePointerMove}
+ onpointerup={longPress.handlePointerEnd}
>
- {#if isSelectionMode}
- <div
- aria-checked={isSelected}
- aria-label={isSelected ? `Deselect ${conversation.name}` : `Select ${conversation.name}`}
- class="shrink-0"
- onclick={(e) => handleCheckboxClick(e)}
- onkeydown={handleCheckboxKeydown}
- role="checkbox"
- tabindex="-1"
- >
- <Checkbox
+ <div
+ style:padding-left="{depth * FORK_TREE_DEPTH_PADDING}px"
+ class="flex min-w-0 flex-1 items-center gap-2"
+ >
+ {#if isSelectionMode}
+ <div
+ aria-checked={isSelected}
aria-label={isSelected
? `Deselect ${conversation.name}`
: `Select ${conversation.name}`}
- checked={isSelected}
- />
- </div>
- {/if}
-
- {#if depth > 0}
- <Tooltip.Root>
- <Tooltip.Trigger>
- <!-- prevent another nested button element -->
- {#snippet child({ props })}
- <a
- {...props}
- class="flex shrink-0 items-center text-muted-foreground transition-colors hover:text-foreground"
- href={RouterService.chat(conversation.forkedFromConversationId)}
+ class="shrink-0"
+ onclick={(e) => handleCheckboxClick(e)}
+ onkeydown={handleCheckboxKeydown}
+ role="checkbox"
+ tabindex="-1"
+ >
+ <Checkbox
+ aria-label={isSelected
+ ? `Deselect ${conversation.name}`
+ : `Select ${conversation.name}`}
+ checked={isSelected}
+ />
+ </div>
+ {/if}
+
+ {#if depth > 0}
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <!-- prevent another nested button element -->
+ {#snippet child({ props })}
+ <a
+ {...props}
+ class="flex shrink-0 items-center text-muted-foreground transition-colors hover:text-foreground"
+ href={RouterService.chat(conversation.forkedFromConversationId)}
+ >
+ <GitBranch class="h-3.5 w-3.5" />
+ </a>
+ {/snippet}
+ </Tooltip.Trigger>
+
+ <Tooltip.Content>
+ <p>See parent conversation</p>
+ </Tooltip.Content>
+ </Tooltip.Root>
+ {/if}
+
+ {#if isLoading}
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <div
+ aria-label="Stop generation"
+ class="stop-button flex {ICON_CLASS_DEFAULT} shrink-0 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:text-foreground"
+ onclick={handleStop}
+ onkeydown={(e) => e.key === 'Enter' && handleStop(e)}
+ role="button"
+ tabindex="0"
>
- <GitBranch class="h-3.5 w-3.5" />
- </a>
- {/snippet}
- </Tooltip.Trigger>
-
- <Tooltip.Content>
- <p>See parent conversation</p>
- </Tooltip.Content>
- </Tooltip.Root>
- {/if}
-
- {#if isLoading}
- <Tooltip.Root>
- <Tooltip.Trigger>
- <div
- aria-label="Stop generation"
- class="stop-button flex {ICON_CLASS_DEFAULT} shrink-0 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:text-foreground"
- onclick={handleStop}
- onkeydown={(e) => e.key === 'Enter' && handleStop(e)}
- role="button"
- tabindex="0"
- >
- <Loader2 class="loading-icon h-3.5 w-3.5 animate-spin" />
-
- <Square class="stop-icon hidden h-3 w-3 fill-current text-destructive" />
- </div>
- </Tooltip.Trigger>
-
- <Tooltip.Content>
- <p>Stop generation</p>
- </Tooltip.Content>
- </Tooltip.Root>
- {/if}
-
- <TruncatedText
- class="text-body-sm max-md:text-body"
- showTooltip={false}
- text={conversation.name}
- />
- </div>
-
- {#if !isSelectionMode && renderActionsDropdown}
- <!-- a phone opens the menu by holding the row, so it shows no trigger -->
- <div class="actions flex items-center" hidden={deviceStore.isMobile}>
- <DropdownMenuActions
- bind:open={dropdownOpen}
- {actions}
- anchor={deviceStore.isMobile ? rowElement : null}
- triggerIcon={MoreHorizontal}
- triggerTooltip="More actions"
+ <Loader2 class="loading-icon h-3.5 w-3.5 animate-spin" />
+
+ <Square class="stop-icon hidden h-3 w-3 fill-current text-destructive" />
+ </div>
+ </Tooltip.Trigger>
+
+ <Tooltip.Content>
+ <p>Stop generation</p>
+ </Tooltip.Content>
+ </Tooltip.Root>
+ {/if}
+
+ <TruncatedText
+ class="text-body-sm max-md:text-body"
+ showTooltip={false}
+ text={conversation.name}
/>
</div>
- {/if}
- </button>
-</ContextMenuActions>
-
-{#snippet groupSubmenu({ close, kind }: { close: () => void; kind: MenuKind })}
- <SidebarNavigationGroupSubmenu
- currentGroupId={groupId}
- {kind}
- label="Move to group"
- onClose={close}
- onSelect={setGroup}
- />
+
+ {#if !isSelectionMode && renderActionsDropdown}
+ <!-- a phone opens the menu by holding the row, so it shows no trigger -->
+ <div class="actions flex items-center" hidden={deviceStore.isMobile}>
+ <DropdownMenuActions
+ bind:open={dropdownOpen}
+ {actions}
+ anchor={deviceStore.isMobile ? rowElement : null}
+ triggerIcon={MoreHorizontal}
+ triggerTooltip="More actions"
+ />
+ </div>
+ {/if}
+ </button>
+ </ContextMenuActions>
{/snippet}
<style>
diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationConversationList.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationConversationList.svelte
index b4acae529..79a52302c 100644
--- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationConversationList.svelte
+++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationConversationList.svelte
@@ -34,8 +34,6 @@
isSelectionMode?: boolean;
selectedIds?: Set<string>;
onSelect: (id: string) => void;
- onEdit: (id: string) => void;
- onDelete: (id: string) => void;
onStop: (id: string) => void;
onToggleSelect?: (id: string) => void;
onEnterSelectionMode?: (id: string) => void;
@@ -64,8 +62,6 @@
onBulkExport,
onBulkPinToggle,
onCloseSelection,
- onDelete,
- onEdit,
onEnterSelectionMode,
onRowMouseDown,
onSelect,
@@ -274,8 +270,6 @@
isActive={currentChatId === conversation.id}
isSelected={selectedIds.has(conversation.id)}
{isSelectionMode}
- {onDelete}
- {onEdit}
{onEnterSelectionMode}
{onRowMouseDown}
{onSelect}
diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationSearchResults.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationSearchResults.svelte
index 1314f04bf..a7f270f44 100644
--- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationSearchResults.svelte
+++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationSearchResults.svelte
@@ -10,8 +10,6 @@
isSelectionMode?: boolean;
selectedIds?: Set<string>;
onSelect: (id: string) => void;
- onEdit: (id: string) => void;
- onDelete: (id: string) => void;
onStop: (id: string) => void;
onToggleSelect?: (id: string) => void;
onEnterSelectionMode?: (id: string) => void;
@@ -24,8 +22,6 @@
currentChatId,
filteredConversations,
isSelectionMode = false,
- onDelete,
- onEdit,
onEnterSelectionMode,
onRowMouseDown,
onSelect,
@@ -68,8 +64,6 @@
isActive={currentChatId === conversation.id}
isSelected={selectedIds.has(conversation.id)}
{isSelectionMode}
- {onDelete}
- {onEdit}
{onEnterSelectionMode}
{onRowMouseDown}
{onSelect}
diff --git a/ui/apps/chat/src/lib/components/app/navigation/index.ts b/ui/apps/chat/src/lib/components/app/navigation/index.ts
index 0f74bc739..230bfb70d 100644
--- a/ui/apps/chat/src/lib/components/app/navigation/index.ts
+++ b/ui/apps/chat/src/lib/components/app/navigation/index.ts
@@ -173,8 +173,6 @@ export { default as SidebarNavigationSelectionBar } from './SidebarNavigation/Si
* {conversations}
* {currentChatId}
* onSelect={...}
- * onEdit={...}
- * onDelete={...}
* onStop={...}
* />
* ```
@@ -185,6 +183,27 @@ export { default as SidebarNavigationActions } from './SidebarNavigation/Sidebar
/** The sidebar's footer: Models and Settings in a group inset in the sidebar. */
export { default as SidebarNavigationFooter } from './SidebarNavigation/SidebarNavigationFooter.svelte';
+/**
+ * **ConversationActions** - The actions a conversation's menus offer
+ *
+ * Owns which actions a conversation has and what they do: open in a new tab,
+ * pin, rename, move to a group, export, share to Hugging Face, select and
+ * delete. It draws no menu itself: it hands the actions to its `children`,
+ * so the sidebar row's dropdown and right-click menu and a tab's right-click
+ * menu all show the same list. Rename, delete and share open the dialogs the
+ * sidebar hosts through `uiStore`.
+ *
+ * @example
+ * ```svelte
+ * <ConversationActions {conversation} isActive showOpenInNewTab={false}>
+ * {#snippet children(actions)}
+ * <ContextMenuActions {actions}>...</ContextMenuActions>
+ * {/snippet}
+ * </ConversationActions>
+ * ```
+ */
+export { default as ConversationActions } from './ConversationActions.svelte';
+
/**
* **SidebarNavigationSearchResults** - Filtered conversation list for search.
*
@@ -203,8 +222,6 @@ export { default as SidebarNavigationFooter } from './SidebarNavigation/SidebarN
* {filteredConversations}
* {currentChatId}
* onSelect={...}
- * onEdit={...}
- * onDelete={...}
* onStop={...}
* />
* ```
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 d150e9699..664f0c8ce 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
@@ -9,6 +9,7 @@
SettingsChatToolsTab,
SettingsChatVoiceTab,
SettingsFooter,
+ SettingsHuggingFaceAccount,
SettingsResetButton
} from '#lib/components/app/settings/index.ts';
import {
@@ -225,6 +226,8 @@
/>
{#if currentSection.slug === SETTINGS_SECTION_SLUGS.GENERAL}
+ <SettingsHuggingFaceAccount />
+
<div class="flex justify-end gap-2">
<SettingsResetButton onReset={handleReset} />
diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsHuggingFaceAccount.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsHuggingFaceAccount.svelte
new file mode 100644
index 000000000..c7172dfbf
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/settings/SettingsHuggingFaceAccount.svelte
@@ -0,0 +1,40 @@
+<script lang="ts">
+ import { HfAccountPanel, HfLogo } from '@ggml-org/llama-huggingface/svelte';
+ import { InsetList } from '@ggml-org/llama-ui/app/sheets';
+ import { HUGGING_FACE_ENABLED } from '#lib/constants/index.ts';
+ import { huggingFace } from '#lib/stores/index.ts';
+
+ interface Props {
+ /** As a group of a phone's settings sheet, where the desktop settings show a labelled row. */
+ inset?: boolean;
+ }
+
+ let { inset = false }: Props = $props();
+
+ const TITLE = 'Hugging Face';
+ const CAPTION =
+ "Conversations you share go to this account's datasets. The sign-in stays in this browser.";
+</script>
+
+<!-- a share is what signs the app in, so there is nothing to show before one did -->
+{#if HUGGING_FACE_ENABLED && huggingFace.user}
+ {#if inset}
+ <InsetList caption={CAPTION} title={TITLE}>
+ <div class="px-4 py-2">
+ <HfAccountPanel account={huggingFace} />
+ </div>
+ </InsetList>
+ {:else}
+ <section aria-labelledby="settings-hugging-face-account" class="flex flex-col gap-2">
+ <h3 class="flex items-center gap-1.5 text-label" id="settings-hugging-face-account">
+ <HfLogo class="size-icon-md" />
+
+ {TITLE}
+ </h3>
+
+ <HfAccountPanel account={huggingFace} />
+
+ <p class="text-caption text-muted-foreground">{CAPTION}</p>
+ </section>
+ {/if}
+{/if}
diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsSheet/SettingsSheet.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsSheet/SettingsSheet.svelte
index 9829de518..22ee24b9a 100644
--- a/ui/apps/chat/src/lib/components/app/settings/SettingsSheet/SettingsSheet.svelte
+++ b/ui/apps/chat/src/lib/components/app/settings/SettingsSheet/SettingsSheet.svelte
@@ -20,6 +20,7 @@
SettingsChatFieldsInset,
SettingsChatImportExportTab,
SettingsChatVoiceTab,
+ SettingsHuggingFaceAccount,
SettingsMcpServers
} from '#lib/components/app/settings/index.ts';
import {
@@ -356,6 +357,8 @@
/>
{#if slug === SETTINGS_SECTION_SLUGS.GENERAL}
+ <SettingsHuggingFaceAccount inset />
+
<InsetList title={SETTINGS_SHEET_TEXT.APP}>
<InsetListRow icon={RefreshCw} onclick={() => window.location.reload()}>
{SETTINGS_SHEET_TEXT.RELOAD_APP}
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 f6947a362..12f87417d 100644
--- a/ui/apps/chat/src/lib/components/app/settings/index.ts
+++ b/ui/apps/chat/src/lib/components/app/settings/index.ts
@@ -34,6 +34,12 @@ export { default as SettingsChatParameterSourceIndicator } from './SettingsChat/
*/
export { default as SettingsGroup } from './SettingsGroup.svelte';
+/**
+ * The Hugging Face account the app is signed in with, and its Sign out. Shows nothing until
+ * a share has signed the app in.
+ */
+export { default as SettingsHuggingFaceAccount } from './SettingsHuggingFaceAccount.svelte';
+
/**
* Sticky footer with the save button for settings panel, shown only when
* there are unsaved changes. Save commits form state to config store.
diff --git a/ui/apps/chat/src/lib/constants/app.constants.ts b/ui/apps/chat/src/lib/constants/app.constants.ts
index d6d15e073..9fa5aff2d 100644
--- a/ui/apps/chat/src/lib/constants/app.constants.ts
+++ b/ui/apps/chat/src/lib/constants/app.constants.ts
@@ -8,3 +8,11 @@ export const APP_NAME = import.meta.env?.VITE_PUBLIC_APP_NAME || 'Llama Chat';
* `agenticMode.enabled`, not this constant, to decide what to show.
*/
export const AGENTIC_ENABLED = import.meta.env?.VITE_PUBLIC_AGENTIC !== 'false';
+
+/**
+ * Whether this build can share conversations to Hugging Face: a build has the
+ * sharing and its sign-in only when made with VITE_PUBLIC_HUGGING_FACE=true
+ * (the release builds are); the dev server, the tests and Storybook have it
+ * without (see vite.config.ts).
+ */
+export const HUGGING_FACE_ENABLED = import.meta.env?.VITE_PUBLIC_HUGGING_FACE === 'true';
diff --git a/ui/apps/chat/src/lib/constants/huggingface-account.constants.ts b/ui/apps/chat/src/lib/constants/huggingface-account.constants.ts
new file mode 100644
index 000000000..bc2376491
--- /dev/null
+++ b/ui/apps/chat/src/lib/constants/huggingface-account.constants.ts
@@ -0,0 +1,40 @@
+/**
+ * What Llama Chat tells Hugging Face about itself when it signs in, which it does to share a
+ * conversation as an agent trace.
+ */
+
+/**
+ * What the sign-in is asked for: read the account, and create datasets and commit traces to
+ * the ones the app created. No scope reaches any other repository.
+ */
+export const HUGGING_FACE_SCOPES = ['openid', 'profile', 'contribute-repos'] as const;
+/** The scope a share cannot do without: creating a dataset and committing a trace. */
+export const HUGGING_FACE_REQUIRED_SCOPE = 'contribute-repos';
+/** The name the app registers under, shown on the Hugging Face authorization page. */
+export const HUGGING_FACE_CLIENT_NAME = 'Llama Chat';
+/** The app's icon, shown for it on Hugging Face (@ggml-org/llama-brand, from npm's CDN). */
+export const HUGGING_FACE_LOGO_URL =
+ 'https://cdn.jsdelivr.net/npm/@ggml-org/llama-brand@0.1.0/logo/svg/app/web/maskable-icon-512x512.svg';
+/** The dataset a first share suggests, under the account's name. */
+export const HUGGING_FACE_DEFAULT_DATASET_NAME = 'llama-chat-traces';
+/** How long a finished sign-in popup waits to close itself before saying it can be closed. */
+export const HUGGING_FACE_POPUP_CLOSE_GRACE_MS = 400;
+
+/** What the share dialog and the sign-in say for the app: they are about a conversation. */
+export const CONVERSATION_SHARE_TEXT = {
+ commitMessage: (name: string) => `Add trace: ${name}`,
+ CONVERSATION_NOT_FOUND: 'Conversation not found.',
+ LINK_COPIED: 'Link copied',
+ messageCount: (count: number) => (count === 1 ? '1 message' : `${count} messages`),
+ SCOPE_ALL: 'Whole conversation',
+ SCOPE_UP_TO_MESSAGE: 'Up to this message',
+ SHARED: 'Conversation shared to Hugging Face',
+ subject: (name: string) => `"${name}"`,
+ SUBJECT_FALLBACK: 'this conversation'
+} as const;
+
+export const HUGGING_FACE_SIGN_IN_TEXT = {
+ CLOSE_WINDOW: 'You can close this window.',
+ FAILED: 'The sign-in failed.',
+ SIGNED_IN: 'Signed in to Hugging Face'
+} as const;
diff --git a/ui/apps/chat/src/lib/constants/huggingface.constants.ts b/ui/apps/chat/src/lib/constants/huggingface.constants.ts
index cff3b6f60..729ef98f6 100644
--- a/ui/apps/chat/src/lib/constants/huggingface.constants.ts
+++ b/ui/apps/chat/src/lib/constants/huggingface.constants.ts
@@ -5,6 +5,7 @@
* Reference: https://huggingface.co/docs/huggingface_hub/package_reference/hf_api
*/
+import { HF_BASE_URL } from '@ggml-org/llama-huggingface';
import { GIGABYTE, KILOBYTE, MEGABYTE } from '@ggml-org/llama-ui/models';
export {
BYTE_LABEL,
@@ -19,7 +20,7 @@ export {
// API endpoints
-export const HF_BASE_URL = 'https://huggingface.co';
+export { HF_BASE_URL };
export const HF_API_MODELS_URL = `${HF_BASE_URL}/api/models`;
// Query params
diff --git a/ui/apps/chat/src/lib/constants/icons.constants.ts b/ui/apps/chat/src/lib/constants/icons.constants.ts
index 3642b0af0..7faef9767 100644
--- a/ui/apps/chat/src/lib/constants/icons.constants.ts
+++ b/ui/apps/chat/src/lib/constants/icons.constants.ts
@@ -18,6 +18,8 @@ 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';
+// the box with an arrow leaving it, not the three joined dots
+import ShareIcon from '@lucide/svelte/icons/share';
import VideoIcon from '@lucide/svelte/icons/video';
import CancelLoadIcon from '@lucide/svelte/icons/x';
import { FileTypeCategory, ModelCapability } from '#lib/enums/index.ts';
@@ -44,6 +46,12 @@ export const DEFAULT_FILE_ICON = FileIcon;
/** The mark for a model, wherever one is listed. */
export const MODEL_ICON = ModelIcon;
+/** Sharing something out of the app: every share action, button and dialog uses this one icon. */
+export const SHARE_ICON = ShareIcon;
+
+/** What sharing a conversation looks like as an action, on a message and in every conversation menu. */
+export const SHARE_ACTION = { icon: SHARE_ICON, label: 'Share' } as const;
+
/** The mark for the Discover Models surface and its entry points. */
export const DISCOVER_ICON = DiscoverIcon;
diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts
index 2fdd1d598..b01f3f57f 100644
--- a/ui/apps/chat/src/lib/constants/index.ts
+++ b/ui/apps/chat/src/lib/constants/index.ts
@@ -55,6 +55,7 @@ export * from './models-discover.constants';
export * from './models-discover-download.constants';
export * from './model-compatibility.constants';
export * from './huggingface.constants';
+export * from './huggingface-account.constants';
export * from './precision.constants';
export * from './pwa.constants';
export * from './routes.constants';
diff --git a/ui/apps/chat/src/lib/enums/chat.enums.ts b/ui/apps/chat/src/lib/enums/chat.enums.ts
index fcf542f52..971f9f25e 100644
--- a/ui/apps/chat/src/lib/enums/chat.enums.ts
+++ b/ui/apps/chat/src/lib/enums/chat.enums.ts
@@ -80,6 +80,12 @@ export enum PdfViewMode {
TEXT = 'text'
}
+/** How much of a conversation a share uploads. */
+export enum ConversationShareScope {
+ ALL = 'all',
+ UP_TO_MESSAGE = 'up-to-message'
+}
+
export enum ChatFormCommandAction {
COMPACT = 'compact',
CWD = 'cwd',
diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts
index 0d0743c7b..088d0d0c7 100644
--- a/ui/apps/chat/src/lib/enums/index.ts
+++ b/ui/apps/chat/src/lib/enums/index.ts
@@ -22,6 +22,7 @@ export {
StreamConnectionState,
ContentPartType,
ConversationSelectionMode,
+ ConversationShareScope,
ErrorDialogType,
MessageRole,
MessageType,
diff --git a/ui/apps/chat/src/lib/stores/huggingface-disabled.ts b/ui/apps/chat/src/lib/stores/huggingface-disabled.ts
new file mode 100644
index 000000000..44a13db5c
--- /dev/null
+++ b/ui/apps/chat/src/lib/stores/huggingface-disabled.ts
@@ -0,0 +1,26 @@
+// What `@ggml-org/llama-huggingface/svelte` resolves to in a build without sharing to
+// Hugging Face (a build not made with VITE_PUBLIC_HUGGING_FACE=true, see vite.config.ts):
+// an account that is never signed in and components that draw nothing, so the sign-in, the
+// upload and the dialogs are not in the bundle. The app reads HUGGING_FACE_ENABLED before it
+// shows or starts any of them.
+
+import type { HfAccount as HfAccountState } from '@ggml-org/llama-huggingface/svelte';
+
+type HfAccountApp = Pick<HfAccountState, 'completeSignInFromLocation' | 'restoreSession' | 'user'>;
+
+export class HfAccount implements HfAccountApp {
+ user = null;
+
+ async completeSignInFromLocation(): Promise<null> {
+ return null;
+ }
+
+ async restoreSession(): Promise<void> {}
+}
+
+/** A component that draws nothing: a Svelte component is a function of its anchor and props. */
+const NO_COMPONENT = (): void => {};
+
+export const HfAccountPanel = NO_COMPONENT;
+export const HfLogo = NO_COMPONENT;
+export const HfShareDialog = NO_COMPONENT;
diff --git a/ui/apps/chat/src/lib/stores/huggingface.svelte.ts b/ui/apps/chat/src/lib/stores/huggingface.svelte.ts
new file mode 100644
index 000000000..6fb61e9f7
--- /dev/null
+++ b/ui/apps/chat/src/lib/stores/huggingface.svelte.ts
@@ -0,0 +1,70 @@
+/**
+ * huggingFace - the Hugging Face account Llama Chat is signed in with
+ *
+ * The account, its sign-in and the upload of a trace live in @ggml-org/llama-huggingface;
+ * this file says who the app is. Sharing a conversation is what asks for the sign-in, so it
+ * starts in the share dialog, and Settings > General shows the account once there is one.
+ */
+
+import { HfAccount } from '@ggml-org/llama-huggingface/svelte';
+import { HUGGING_FACE_ENABLED } from '#lib/constants/app.constants.ts';
+import {
+ HUGGING_FACE_CLIENT_NAME,
+ HUGGING_FACE_DEFAULT_DATASET_NAME,
+ HUGGING_FACE_LOGO_URL,
+ HUGGING_FACE_POPUP_CLOSE_GRACE_MS,
+ HUGGING_FACE_REQUIRED_SCOPE,
+ HUGGING_FACE_SCOPES,
+ HUGGING_FACE_SIGN_IN_TEXT
+} from '#lib/constants/huggingface-account.constants.ts';
+import { STORAGE_APP_NAME } from '#lib/constants/storage.constants.ts';
+import { withBase } from '#lib/utils/base-path.ts';
+import { toast } from 'svelte-sonner';
+
+export const huggingFace = new HfAccount({
+ callbackUrl: () => `${window.location.origin}${withBase('/')}`,
+ clientName: HUGGING_FACE_CLIENT_NAME,
+ defaultDatasetName: HUGGING_FACE_DEFAULT_DATASET_NAME,
+ logoUrl: HUGGING_FACE_LOGO_URL,
+ requiredScope: HUGGING_FACE_REQUIRED_SCOPE,
+ scopes: HUGGING_FACE_SCOPES,
+ storagePrefix: STORAGE_APP_NAME
+});
+
+const { CLOSE_WINDOW, FAILED, SIGNED_IN } = HUGGING_FACE_SIGN_IN_TEXT;
+
+/** Finishes a sign-in when this page load is Hugging Face sending the browser back. */
+async function completeSignIn(): Promise<void> {
+ const outcome = await huggingFace.completeSignInFromLocation();
+
+ if (!outcome?.result) return;
+
+ const { result } = outcome;
+
+ if (outcome.closeWindow) {
+ window.close();
+
+ // a browser may keep a window its script did not open in this document: say so
+ setTimeout(() => {
+ if (result.ok) toast.success(`${SIGNED_IN} ${CLOSE_WINDOW}`);
+ else toast.error(`${result.error ?? FAILED} ${CLOSE_WINDOW}`);
+ }, HUGGING_FACE_POPUP_CLOSE_GRACE_MS);
+
+ return;
+ }
+
+ if (result.ok) toast.success(SIGNED_IN);
+ else toast.error(result.error ?? FAILED);
+}
+
+/**
+ * Run once when the app starts: finishes a sign-in this page load brings back, and looks up
+ * who a remembered sign-in belongs to. Without either, no request leaves the browser. A build
+ * without sharing does neither.
+ */
+export function startHuggingFace(): void {
+ if (!HUGGING_FACE_ENABLED) return;
+
+ void completeSignIn();
+ void huggingFace.restoreSession();
+}
diff --git a/ui/apps/chat/src/lib/stores/index.ts b/ui/apps/chat/src/lib/stores/index.ts
index eef37b252..3ca69b1d9 100644
--- a/ui/apps/chat/src/lib/stores/index.ts
+++ b/ui/apps/chat/src/lib/stores/index.ts
@@ -44,6 +44,9 @@ export { mcpStore } from './mcp/index.svelte';
// GROUPS (named sidebar sections for chats)
export { groupsStore } from './groups.svelte';
+// HUGGING FACE ACCOUNT (sharing conversations as traces)
+export { huggingFace } from './huggingface.svelte';
+
// MODELS
export { modelsStore } from './models/index.svelte';
diff --git a/ui/apps/chat/src/lib/stores/ui.svelte.ts b/ui/apps/chat/src/lib/stores/ui.svelte.ts
index f2c923ab7..da9eeea05 100644
--- a/ui/apps/chat/src/lib/stores/ui.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/ui.svelte.ts
@@ -27,6 +27,12 @@ import { goto } from '$app/navigation';
import { page } from '$app/state';
import { SvelteSet } from 'svelte/reactivity';
+interface ConversationShareOptions {
+ conversationId: string;
+ /** The message a share can end at, when it was started from one. */
+ messageId?: string;
+}
+
interface GroupDialogOptions {
/** Group to rename; without it the dialog creates a new one. */
groupId?: string;
@@ -75,6 +81,15 @@ class UiStore {
/** Set when a flow outside the chat wants the composer focused once it can take it. */
composerFocusRequested = $state(false);
+ /** Conversation the delete dialog asks about, `null` while closed. */
+ conversationDeleteId = $state<string | null>(null);
+
+ /** Conversation the rename dialog edits, `null` while closed. */
+ conversationRenameId = $state<string | null>(null);
+
+ /** The share the share dialog is open for, `null` while closed. */
+ conversationShare = $state<ConversationShareOptions | null>(null);
+
/** Repo the Discover dialog selects when it opens, set by a model row. */
discoverModelFocus = $state<string | null>(null);
@@ -193,6 +208,21 @@ class UiStore {
return !this.collapsedSidebarSections.has(id);
}
+ /** Ask to delete a conversation, from any of its menus. */
+ openConversationDelete(conversationId: string): void {
+ this.conversationDeleteId = conversationId;
+ }
+
+ /** Rename a conversation, from any of its menus. */
+ openConversationRename(conversationId: string): void {
+ this.conversationRenameId = conversationId;
+ }
+
+ /** Share a conversation to Hugging Face, from any of its menus or from a message. */
+ openConversationShare(options: ConversationShareOptions): void {
+ this.conversationShare = options;
+ }
+
/** Open the group dialog to create a group, or to rename `groupId`. */
openGroupDialog(options: GroupDialogOptions = {}): void {
this.groupDialog = options;
diff --git a/ui/apps/chat/src/lib/types/chat.d.ts b/ui/apps/chat/src/lib/types/chat.d.ts
index 144c0f129..a4d0f3520 100644
--- a/ui/apps/chat/src/lib/types/chat.d.ts
+++ b/ui/apps/chat/src/lib/types/chat.d.ts
@@ -328,6 +328,8 @@ export interface ChatMessageActionsContext {
setShowForkDialog: (show: boolean) => void;
navigateToSibling: (siblingId: string) => void;
forkConversation?: (options: { name: string; includeAttachments: boolean }) => void;
+ /** Shares the conversation up to this message; absent in a build without sharing. */
+ share?: () => void;
}
export interface ChatMessageEditState {
diff --git a/ui/apps/chat/src/lib/utils/conversation-trace.ts b/ui/apps/chat/src/lib/utils/conversation-trace.ts
new file mode 100644
index 000000000..523e6a75e
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/conversation-trace.ts
@@ -0,0 +1,87 @@
+/**
+ * Builds the trace a share uploads: one branch of a conversation, from its start to a message.
+ */
+
+import {
+ HF_PREVIEW_LINES_MAX,
+ HF_PREVIEW_TEXT_MAX,
+ type HfTracePreviewLine
+} from '@ggml-org/llama-huggingface';
+import { MessageRole, MessageType } from '#lib/enums/index.ts';
+import { filterByLeafNodeId } from '#lib/utils/branching.ts';
+
+const WHITESPACE = /\s+/g;
+/** A fenced code block, or what is left of one the preview cut short. */
+const FENCED_CODE = /```[\s\S]*?(?:```|$)/g;
+const BACKTICKS = /`/g;
+
+export interface ConversationTraceOptions {
+ /** Last message of the trace; the conversation's current message when omitted. */
+ upToMessageId?: string;
+ includeAttachments?: boolean;
+}
+
+/**
+ * Picks the branch that ends at `upToMessageId` out of the conversation's message tree.
+ * The trace viewer reads messages as one line, so other branches are left out.
+ * Local details (working directories, sidebar group) stay on this device.
+ * @returns The trace as an exported conversation, ready for the JSONL serializer
+ */
+export function buildConversationTrace(
+ data: ExportedConversation,
+ options: ConversationTraceOptions = {}
+): ExportedConversation {
+ const { conv, messages } = data;
+ const leafId = options.upToMessageId ?? conv.currNode ?? '';
+ const path = filterByLeafNodeId(messages, leafId);
+ const pathIds = new Set(path.map((message) => message.id));
+ const traceMessages = path.map((message) => {
+ const { extra, toolCwd: _toolCwd, ...rest } = message;
+ const traceMessage: DatabaseMessage = {
+ ...rest,
+ children: message.children.filter((id: string) => pathIds.has(id))
+ };
+
+ if (options.includeAttachments && extra?.length) traceMessage.extra = extra;
+
+ return traceMessage;
+ });
+ const { cwd: _cwd, groupId: _groupId, ...sharedConv } = conv;
+
+ return {
+ conv: { ...sharedConv, currNode: traceMessages.at(-1)?.id ?? null },
+ messages: traceMessages
+ };
+}
+
+/**
+ * The first messages of a trace, as the dialog shows them faded once the trace is shared:
+ * what the user and the assistant said, in one line each, without code blocks. Tool calls,
+ * reasoning, a compaction and messages the app made itself have no place in it.
+ */
+export function buildTracePreview(trace: ExportedConversation): HfTracePreviewLine[] {
+ const lines: HfTracePreviewLine[] = [];
+
+ for (const message of trace.messages) {
+ if (lines.length >= HF_PREVIEW_LINES_MAX) break;
+
+ if (message.isSynthetic || message.type !== MessageType.TEXT) continue;
+
+ const role =
+ message.role === MessageRole.USER
+ ? 'user'
+ : message.role === MessageRole.ASSISTANT
+ ? 'assistant'
+ : null;
+ const text = message.content
+ .replace(FENCED_CODE, ' ')
+ .replace(BACKTICKS, '')
+ .replace(WHITESPACE, ' ')
+ .trim()
+ .slice(0, HF_PREVIEW_TEXT_MAX);
+
+ if (role && text) lines.push({ role, text });
+ }
+
+ return lines;
+}
diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts
index 786d6a24a..2229262d3 100644
--- a/ui/apps/chat/src/lib/utils/index.ts
+++ b/ui/apps/chat/src/lib/utils/index.ts
@@ -39,6 +39,13 @@ export {
buildSiblingInfoMap
} from './branching';
+// Conversation traces (sharing to Hugging Face)
+export {
+ buildConversationTrace,
+ buildTracePreview,
+ type ConversationTraceOptions
+} from './conversation-trace';
+
// Code
export {
highlightCode,
diff --git a/ui/apps/chat/src/routes/+layout.svelte b/ui/apps/chat/src/routes/+layout.svelte
index e02f9c0c3..b8fb56ab6 100644
--- a/ui/apps/chat/src/routes/+layout.svelte
+++ b/ui/apps/chat/src/routes/+layout.svelte
@@ -30,6 +30,7 @@
import { usePwa } from '#lib/hooks/use-pwa.svelte.ts';
import { useSidebarReveal } from '#lib/hooks/use-sidebar-reveal.svelte.ts';
import { RouterService } from '#lib/services/router.service.ts';
+ import { startHuggingFace } from '#lib/stores/huggingface.svelte.ts';
import {
chatStore,
conversationsStore,
@@ -213,6 +214,9 @@
onMount(() => {
updateFavicon();
+
+ startHuggingFace();
+
// snapshot of every backend 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();
diff --git a/ui/apps/chat/src/routes/search/+page.svelte b/ui/apps/chat/src/routes/search/+page.svelte
index eafe23391..ad9fe10c2 100644
--- a/ui/apps/chat/src/routes/search/+page.svelte
+++ b/ui/apps/chat/src/routes/search/+page.svelte
@@ -1,9 +1,5 @@
<script lang="ts">
- import {
- DialogConversationDelete,
- SearchInput,
- SidebarNavigationSearchResults
- } from '#lib/components/app/index.ts';
+ import { SearchInput, SidebarNavigationSearchResults } from '#lib/components/app/index.ts';
import { ROUTES } from '#lib/constants/index.ts';
import { RouterService } from '#lib/services/router.service.ts';
import { chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts';
@@ -36,44 +32,6 @@
await goto(RouterService.chat(id));
}
- async function handleEditConversation(id: string) {
- const conversation = conversationsStore.conversations.find((c) => c.id === id);
-
- if (!conversation) return;
-
- const newName = window.prompt('Rename conversation', conversation.name);
-
- if (newName && newName.trim()) {
- await conversationsStore.updateConversationName(id, newName.trim());
- }
- }
-
- let deleteDialogOpen = $state(false);
- let deleteTargetId = $state<string | null>(null);
-
- function handleDeleteConversation(id: string) {
- const conversation = conversationsStore.conversations.find((c) => c.id === id);
-
- if (!conversation) return;
-
- deleteTargetId = conversation.id;
- deleteDialogOpen = true;
- }
-
- async function handleDeleteConfirm() {
- const id = deleteTargetId;
-
- deleteDialogOpen = false;
-
- if (!id) return;
-
- await conversationsStore.deleteConversation(id, { deleteWithForks: false });
- }
-
- function handleDeleteCancel() {
- deleteDialogOpen = false;
- }
-
function handleStopGeneration(id: string) {
chatStore.stopGenerationForChat(id);
}
@@ -105,16 +63,8 @@
<SidebarNavigationSearchResults
{currentChatId}
{filteredConversations}
- onDelete={handleDeleteConversation}
- onEdit={handleEditConversation}
onSelect={selectConversation}
onStop={handleStopGeneration}
{searchQuery}
/>
</div>
-
-<DialogConversationDelete
- bind:open={deleteDialogOpen}
- onCancel={handleDeleteCancel}
- onConfirm={handleDeleteConfirm}
-/>
diff --git a/ui/apps/chat/tests/client/hf-share-dialog.svelte.test.ts b/ui/apps/chat/tests/client/hf-share-dialog.svelte.test.ts
new file mode 100644
index 000000000..4f4e0770f
--- /dev/null
+++ b/ui/apps/chat/tests/client/hf-share-dialog.svelte.test.ts
@@ -0,0 +1,81 @@
+// The share dialog of Llama Hugging Face, against an account it does not call out of: which
+// datasets it offers as tiles, and that its pick never points at one the account cannot add to.
+
+import HfShareDialogStoryHost from '../stories/dialogs/HfShareDialogStoryHost.svelte';
+import {
+ FAKE_OWNER,
+ type FakeAccount,
+ fakeAccountWith
+} from '../stories/fixtures/hf-fake-account.svelte.ts';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { page, userEvent } from 'vitest/browser';
+import { render } from 'vitest-browser-svelte';
+
+function renderDialog(account: FakeAccount) {
+ render(HfShareDialogStoryHost, { account });
+}
+
+const tile = (name: string) => page.getByRole('button', { name: new RegExp(`^${name}\\b`) });
+
+describe('HfShareDialog datasets', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it('offers the datasets as tiles, with the first picked, and a tile for a new one', async () => {
+ renderDialog(fakeAccountWith('alpha', 'beta'));
+
+ await expect.element(tile('alpha')).toHaveAttribute('aria-pressed', 'true');
+ await expect.element(tile('beta')).toHaveAttribute('aria-pressed', 'false');
+ await expect.element(page.getByRole('button', { name: /^New dataset/ })).toBeVisible();
+ });
+
+ it('goes straight to naming a new dataset when there is none to add to', async () => {
+ renderDialog(fakeAccountWith());
+
+ await expect
+ .element(page.getByLabelText('New dataset name'))
+ .toHaveValue('me/llama-chat-traces');
+ await expect.element(page.getByText('Create a dataset')).toBeVisible();
+ });
+
+ it('shows a few tiles and the rest behind "Show more"', async () => {
+ renderDialog(fakeAccountWith('a', 'b', 'c', 'd', 'e'));
+
+ await expect.element(tile('c')).toBeVisible();
+ expect(page.getByRole('button', { name: /^d\b/ }).elements()).toHaveLength(0);
+
+ await userEvent.click(page.getByRole('button', { name: 'Show 2 more' }));
+ await expect.element(tile('e')).toBeVisible();
+ });
+
+ it('picks again when the Hub turns the picked dataset down, instead of keeping a stale pick', async () => {
+ const account = fakeAccountWith('alpha', 'beta');
+
+ account.refused.add(`${FAKE_OWNER}/alpha`);
+ renderDialog(account);
+
+ await userEvent.click(page.getByRole('button', { exact: true, name: 'Share' }));
+ await expect.element(page.getByText('cannot add traces to me/alpha')).toBeVisible();
+
+ // the refused tile is gone and the next one is picked: Share does not aim at it again
+ expect(page.getByRole('button', { name: /^alpha\b/ }).elements()).toHaveLength(0);
+ await expect.element(tile('beta')).toHaveAttribute('aria-pressed', 'true');
+
+ await userEvent.click(page.getByRole('button', { exact: true, name: 'Share' }));
+ await expect.element(page.getByText('Shared to Hugging Face')).toBeVisible();
+ expect(account.uploads).toEqual([`${FAKE_OWNER}/alpha`, `${FAKE_OWNER}/beta`]);
+ });
+
+ it('picks again for the next account when the signed-in one changes', async () => {
+ const account = fakeAccountWith('alpha');
+
+ renderDialog(account);
+ await expect.element(tile('alpha')).toHaveAttribute('aria-pressed', 'true');
+
+ // another account signs in, with a dataset of its own, while the dialog is open
+ account.user = null;
+ account.datasets = [{ id: 'you/zeta', isPrivate: false }];
+ account.user = { name: 'you' };
+
+ await expect.element(tile('zeta')).toHaveAttribute('aria-pressed', 'true');
+ });
+});
diff --git a/ui/apps/chat/tests/client/huggingface-account.svelte.test.ts b/ui/apps/chat/tests/client/huggingface-account.svelte.test.ts
new file mode 100644
index 000000000..40f852168
--- /dev/null
+++ b/ui/apps/chat/tests/client/huggingface-account.svelte.test.ts
@@ -0,0 +1,277 @@
+import {
+ HF_STORAGE_KEY_OAUTH,
+ HF_STORAGE_KEY_SEPARATOR,
+ HF_STORAGE_KEY_TOKEN
+} from '@ggml-org/llama-huggingface';
+import { STORAGE_APP_NAME } from '#lib/constants/index.ts';
+import { huggingFace } from '#lib/stores/huggingface.svelte.ts';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// the sign-in itself is tested in ui/lib/huggingface; these cover what the account does around
+// it, as Llama Chat sets it up
+
+const HF_OAUTH_LOCALSTORAGE_KEY = [STORAGE_APP_NAME, HF_STORAGE_KEY_OAUTH].join(
+ HF_STORAGE_KEY_SEPARATOR
+);
+const HF_TOKEN_LOCALSTORAGE_KEY = [STORAGE_APP_NAME, HF_STORAGE_KEY_TOKEN].join(
+ HF_STORAGE_KEY_SEPARATOR
+);
+
+interface HubMock {
+ /** The datasets the account lists; one of them by default. */
+ datasets?: { id: string; private: boolean }[];
+ /** Status a share's preupload answers with, instead of accepting the file. */
+ preupload?: number;
+ register?: () => Response;
+ whoami?: () => Response;
+}
+
+// the Hub's lookup of one dataset: /api/datasets/<owner>/<name>
+const DATASET_LOOKUP_URL = /\/api\/datasets\/[^/]+\/[^/?]+$/;
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status });
+}
+
+function mockHub({ datasets, preupload, register, whoami }: HubMock = {}) {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const url = String(input instanceof Request ? input.url : input);
+
+ if (url.endsWith('/oauth/register')) {
+ return register ? register() : json({ client_id: 'client-1' }, 201);
+ }
+
+ if (url.endsWith('/oauth/token')) {
+ return json({ access_token: 'hf_oauth_a', expires_in: 3600, refresh_token: 'r1' });
+ }
+
+ if (url.endsWith('/api/whoami-v2')) return whoami ? whoami() : json({ name: 'me' });
+
+ if (url.includes('/api/datasets?')) {
+ return json(datasets ?? [{ id: 'me/traces', private: false }]);
+ }
+
+ // a share to a dataset that exists: look it up, check the file, commit it
+ if (DATASET_LOOKUP_URL.test(url)) return json({});
+
+ if (url.endsWith('/preupload/main')) {
+ return preupload
+ ? json({ error: 'Forbidden' }, preupload)
+ : json({ files: [{ uploadMode: 'regular' }] });
+ }
+
+ if (url.endsWith('/commit/main')) return json({});
+
+ throw new Error(`unexpected request: ${url}`);
+ });
+}
+
+function fakePopup() {
+ return { close: vi.fn(), location: { href: '' } };
+}
+
+/** Signs in through a popup, up to Hugging Face sending the browser back. */
+async function signInWithHuggingFace() {
+ const popup = fakePopup();
+
+ await huggingFace.signInWithHuggingFace(popup as unknown as Window);
+
+ const authorization = new URL(popup.location.href);
+ const callback = new URL(authorization.searchParams.get('redirect_uri') ?? '');
+
+ callback.searchParams.set('code', 'code-1');
+ callback.searchParams.set('state', authorization.searchParams.get('state') ?? '');
+
+ return huggingFace.completeSignInFromLocation(callback);
+}
+
+beforeEach(() => {
+ localStorage.removeItem(HF_OAUTH_LOCALSTORAGE_KEY);
+ huggingFace.signOut();
+ huggingFace.oauthError = null;
+ // the callback clears its parameters from the address; leave the test page's own alone
+ vi.spyOn(window.history, 'replaceState').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ huggingFace.cancelSignInWithHf();
+ vi.restoreAllMocks();
+ // other tests share this browser's storage: leave no sign-in behind
+ huggingFace.signOut();
+});
+
+describe('the Hugging Face account of Llama Chat', () => {
+ it('signs in with Hugging Face, then checks who signed in and lists their datasets', async () => {
+ mockHub();
+
+ const outcome = await signInWithHuggingFace();
+
+ expect(outcome).toEqual({ closeWindow: true, result: { ok: true } });
+ await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(1));
+ expect(huggingFace.user?.name).toBe('me');
+ expect(huggingFace.isSigningInWithHf).toBe(false);
+ });
+
+ it('says when the datasets of the signed-in account are listed, so a share can wait for them', async () => {
+ mockHub();
+ expect(huggingFace.hasListedDatasets).toBe(false);
+
+ await signInWithHuggingFace();
+ await vi.waitFor(() => expect(huggingFace.hasListedDatasets).toBe(true));
+ expect(huggingFace.datasets).toHaveLength(1);
+
+ huggingFace.signOut();
+
+ expect(huggingFace.hasListedDatasets).toBe(false);
+ });
+
+ it('points back to token sign-in when Hugging Face will not register the app', async () => {
+ mockHub({ register: () => json({ error: 'invalid_redirect_uri' }, 400) });
+
+ await huggingFace.signInWithHuggingFace(fakePopup() as unknown as Window);
+
+ expect(huggingFace.isSigningInWithHf).toBe(false);
+ expect(huggingFace.oauthError).toContain('does not allow signing in from');
+ expect(huggingFace.oauthError).toContain('Sign in with an access token instead.');
+ });
+
+ it('signs in with a pasted token and refuses one the Hub rejects', async () => {
+ mockHub({ whoami: () => json({ error: 'Invalid credentials' }, 401) });
+ await expect(huggingFace.signIn('hf_bad')).rejects.toThrow('did not accept this token');
+ expect(localStorage.getItem(HF_TOKEN_LOCALSTORAGE_KEY)).toBeNull();
+
+ vi.restoreAllMocks();
+ mockHub();
+ await huggingFace.signIn(' hf_good ');
+
+ expect(huggingFace.user?.name).toBe('me');
+ expect(localStorage.getItem(HF_TOKEN_LOCALSTORAGE_KEY)).toBe('hf_good');
+ });
+
+ it('keeps a remembered token when the Hub cannot be reached, forgets one it rejects', async () => {
+ mockHub();
+ await huggingFace.signIn('hf_good');
+ huggingFace.user = null;
+
+ vi.restoreAllMocks();
+ mockHub({ whoami: () => json({ error: 'Down' }, 503) });
+ await huggingFace.restoreSession();
+
+ expect(localStorage.getItem(HF_TOKEN_LOCALSTORAGE_KEY)).toBe('hf_good');
+
+ vi.restoreAllMocks();
+ mockHub({ whoami: () => json({ error: 'Invalid credentials' }, 401) });
+ await huggingFace.restoreSession();
+
+ expect(localStorage.getItem(HF_TOKEN_LOCALSTORAGE_KEY)).toBeNull();
+ });
+
+ it('forgets the account and its last dataset on sign-out', async () => {
+ mockHub();
+ await signInWithHuggingFace();
+ await vi.waitFor(() => expect(huggingFace.user?.name).toBe('me'));
+ huggingFace.lastDataset = 'me/traces';
+ huggingFace.signOut();
+
+ expect(huggingFace.user).toBeNull();
+ expect(huggingFace.suggestedDataset).toBe('');
+ expect(
+ JSON.parse(localStorage.getItem(HF_OAUTH_LOCALSTORAGE_KEY) ?? '{}').tokens
+ ).toBeUndefined();
+ });
+
+ describe('the datasets a share can go to', () => {
+ const TRACE = { commitMessage: 'Add trace', content: '{}', isPrivate: false, path: 't.jsonl' };
+
+ // the account remembers what each account shared to, so every test signs in as another one
+ let owner = '';
+ let datasets: { id: string; private: boolean }[] = [];
+ let accountNumber = 0;
+
+ const writableIds = () => huggingFace.writableDatasets.map((dataset) => dataset.id);
+ const whoamiAs = (role?: string) => () =>
+ json({ auth: role ? { accessToken: { role } } : undefined, name: owner });
+
+ beforeEach(() => {
+ owner = `account-${accountNumber++}`;
+ datasets = [
+ { id: `${owner}/notes`, private: true },
+ { id: `${owner}/traces`, private: false },
+ { id: `${owner}/images`, private: false }
+ ];
+ });
+
+ it('offers none to a sign-in with Hugging Face, which has shared to none yet', async () => {
+ mockHub({ datasets, whoami: whoamiAs() });
+ await signInWithHuggingFace();
+ await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
+
+ expect(huggingFace.writableDatasets).toEqual([]);
+ });
+
+ it('offers the ones it shared to, the last one first, and remembers them', async () => {
+ mockHub({ datasets, whoami: whoamiAs() });
+ await signInWithHuggingFace();
+ await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
+
+ await huggingFace.uploadTrace({ ...TRACE, repoId: `${owner}/images` });
+ await huggingFace.uploadTrace({ ...TRACE, repoId: `${owner}/notes` });
+
+ expect(writableIds()).toEqual([`${owner}/notes`, `${owner}/images`]);
+
+ // the same account signing in again still has them
+ huggingFace.signOut();
+ await signInWithHuggingFace();
+ await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
+
+ expect(writableIds().sort()).toEqual([`${owner}/images`, `${owner}/notes`]);
+ });
+
+ it('stops offering one the Hub turns down', async () => {
+ mockHub({ datasets, whoami: whoamiAs() });
+ await signInWithHuggingFace();
+ await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
+ await huggingFace.uploadTrace({ ...TRACE, repoId: `${owner}/images` });
+
+ vi.restoreAllMocks();
+ mockHub({ datasets, preupload: 403, whoami: whoamiAs() });
+
+ await expect(
+ huggingFace.uploadTrace({ ...TRACE, repoId: `${owner}/images` })
+ ).rejects.toThrow(`cannot add traces to ${owner}/images`);
+ expect(huggingFace.writableDatasets).toEqual([]);
+ });
+
+ it('offers every one to a pasted token, and none to a token that only reads', async () => {
+ mockHub({ datasets, whoami: whoamiAs('write') });
+ await huggingFace.signIn('hf_good');
+ await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
+
+ expect(huggingFace.writableDatasets).toHaveLength(3);
+
+ huggingFace.signOut();
+ vi.restoreAllMocks();
+ mockHub({ datasets, whoami: whoamiAs('read') });
+ await huggingFace.signIn('hf_read');
+ await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
+
+ expect(huggingFace.isReadOnly).toBe(true);
+ expect(huggingFace.writableDatasets).toEqual([]);
+ });
+
+ it('starts a new name with the usual dataset, unless it exists', async () => {
+ mockHub({ datasets, whoami: whoamiAs('write') });
+ await huggingFace.signIn('hf_good');
+ await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
+
+ expect(huggingFace.newDatasetStart).toBe(`${owner}/llama-chat-traces`);
+
+ huggingFace.datasets = [
+ ...huggingFace.datasets,
+ { id: `${owner}/llama-chat-traces`, isPrivate: false }
+ ];
+
+ expect(huggingFace.newDatasetStart).toBe(`${owner}/`);
+ });
+ });
+});
diff --git a/ui/apps/chat/tests/stories/dialogs/DialogHfShare.a11y.stories.svelte b/ui/apps/chat/tests/stories/dialogs/DialogHfShare.a11y.stories.svelte
new file mode 100644
index 000000000..c49f31392
--- /dev/null
+++ b/ui/apps/chat/tests/stories/dialogs/DialogHfShare.a11y.stories.svelte
@@ -0,0 +1,70 @@
+<script lang="ts" module>
+ import { fakeAccountWith } from '../fixtures/hf-fake-account.svelte.ts';
+ import HfShareDialogStoryHost from './HfShareDialogStoryHost.svelte';
+ import { defineMeta } from '@storybook/addon-svelte-csf';
+ import { expect, screen, waitFor, within } from 'storybook/test';
+
+ const { Story } = defineMeta({
+ component: HfShareDialogStoryHost,
+ parameters: {
+ layout: 'centered'
+ },
+ tags: ['!dev'],
+ title: 'Llama Chat/Dialogs/HfShareDialog/Accessibility'
+ });
+</script>
+
+<Story
+ args={{ account: fakeAccountWith('alpha') }}
+ name="DialogIsNamedAndTakesFocus"
+ play={async () => {
+ const dialog = await screen.findByRole('alertdialog', { name: /Share to Hugging Face/ });
+
+ await waitFor(() => expect(dialog).toContainElement(document.activeElement as HTMLElement));
+ }}
+/>
+
+<Story
+ args={{ account: fakeAccountWith('alpha', 'beta') }}
+ name="DatasetsAreOneGroupOfToggleButtons"
+ play={async () => {
+ const group = await screen.findByRole('group', { name: 'Dataset' });
+ const alpha = await within(group).findByRole('button', { name: /^alpha\b/ });
+ const beta = await within(group).findByRole('button', { name: /^beta\b/ });
+
+ await expect(alpha).toHaveAttribute('aria-pressed', 'true');
+ await expect(beta).toHaveAttribute('aria-pressed', 'false');
+ }}
+/>
+
+<Story
+ args={{ account: fakeAccountWith('alpha', 'beta') }}
+ name="KeyboardPicksATile"
+ play={async ({ userEvent }) => {
+ const dialog = await screen.findByRole('alertdialog');
+ const alpha = await screen.findByRole('button', { name: /^alpha\b/ });
+ const beta = await screen.findByRole('button', { name: /^beta\b/ });
+
+ // the dialog moves focus itself as it opens: start from the tile once that has settled
+ await waitFor(() => expect(dialog).toContainElement(document.activeElement as HTMLElement));
+ alpha.focus();
+ await expect(alpha).toHaveFocus();
+ await userEvent.tab();
+ await expect(beta).toHaveFocus();
+
+ await userEvent.keyboard('{Enter}');
+ await waitFor(() => expect(beta).toHaveAttribute('aria-pressed', 'true'));
+ await expect(alpha).toHaveAttribute('aria-pressed', 'false');
+ }}
+/>
+
+<Story
+ args={{ account: fakeAccountWith() }}
+ name="NewDatasetNameIsLabelled"
+ play={async () => {
+ const field = await screen.findByLabelText('New dataset name');
+
+ // the dialog fades in: it is visible once it has finished
+ await waitFor(() => expect(field).toBeVisible());
+ }}
+/>
diff --git a/ui/apps/chat/tests/stories/dialogs/DialogHfShare.stories.svelte b/ui/apps/chat/tests/stories/dialogs/DialogHfShare.stories.svelte
new file mode 100644
index 000000000..4d0e80655
--- /dev/null
+++ b/ui/apps/chat/tests/stories/dialogs/DialogHfShare.stories.svelte
@@ -0,0 +1,47 @@
+<script lang="ts" module>
+ import { fakeAccountWith } from '../fixtures/hf-fake-account.svelte.ts';
+ import HfShareDialogStoryHost from './HfShareDialogStoryHost.svelte';
+ import { defineMeta } from '@storybook/addon-svelte-csf';
+ import { expect, screen, userEvent, waitFor } from 'storybook/test';
+
+ // the dialog that shares a conversation to a Hugging Face dataset; an account with no calls out of it
+ const { Story } = defineMeta({
+ component: HfShareDialogStoryHost,
+ parameters: {
+ layout: 'centered'
+ },
+ title: 'Llama Chat/Dialogs/HfShareDialog'
+ });
+</script>
+
+<Story
+ args={{ account: fakeAccountWith('agent-traces', 'llama-chat-traces') }}
+ name="DatasetsToAddTo"
+/>
+
+<Story args={{ account: fakeAccountWith() }} name="NoDatasetYet" />
+
+<Story
+ args={{ account: fakeAccountWith('a', 'b', 'c', 'd', 'e') }}
+ name="MoreDatasets"
+ play={async () => {
+ await userEvent.click(await screen.findByRole('button', { name: 'Show 2 more' }));
+
+ const tile = await screen.findByRole('button', { name: /^e\b/ });
+
+ // the dialog fades in: it is visible once it has finished
+ await waitFor(() => expect(tile).toBeVisible());
+ }}
+/>
+
+<Story
+ args={{ account: fakeAccountWith('agent-traces') }}
+ name="Shared"
+ play={async () => {
+ await userEvent.click(await screen.findByRole('button', { name: 'Share' }));
+
+ const title = await screen.findByText('Shared to Hugging Face');
+
+ await waitFor(() => expect(title).toBeVisible());
+ }}
+/>
diff --git a/ui/apps/chat/tests/stories/dialogs/HfShareDialogStoryHost.svelte b/ui/apps/chat/tests/stories/dialogs/HfShareDialogStoryHost.svelte
new file mode 100644
index 000000000..1194c94ef
--- /dev/null
+++ b/ui/apps/chat/tests/stories/dialogs/HfShareDialogStoryHost.svelte
@@ -0,0 +1,34 @@
+<script lang="ts">
+ import { asHfAccount, type FakeAccount } from '../fixtures/hf-fake-account.svelte.ts';
+ import type { HfTraceFile } from '@ggml-org/llama-huggingface';
+ import { HfShareDialog } from '@ggml-org/llama-huggingface/svelte';
+
+ // the share dialog, open, on an account that calls out of nowhere: what its stories and its tests share
+
+ interface Props {
+ account: FakeAccount;
+ }
+
+ const SCOPES = [
+ { id: 'conversation', label: 'This conversation' },
+ { id: 'branch', label: 'This branch only' }
+ ];
+ const TRACE: HfTraceFile = {
+ commitMessage: 'Add trace',
+ content: '{"type":"user","message":{"role":"user","content":"Hello"}}',
+ path: 'trace.jsonl'
+ };
+
+ let { account }: Props = $props();
+
+ let open = $state(true);
+</script>
+
+<HfShareDialog
+ bind:open
+ account={asHfAccount(account)}
+ buildTrace={async () => TRACE}
+ onCopyLink={() => {}}
+ scopes={SCOPES}
+ subject="this conversation"
+/>
diff --git a/ui/apps/chat/tests/stories/fixtures/hf-fake-account.svelte.ts b/ui/apps/chat/tests/stories/fixtures/hf-fake-account.svelte.ts
new file mode 100644
index 000000000..34e25a0f7
--- /dev/null
+++ b/ui/apps/chat/tests/stories/fixtures/hf-fake-account.svelte.ts
@@ -0,0 +1,63 @@
+// A stand-in for the Hugging Face account that the share dialog reads and calls, as plain state:
+// it calls out of nowhere, so a test or a story can set up who is signed in and which datasets
+// the account can add to, and watch what the dialog does with them.
+
+import { type HfDataset, HfNotWritableError } from '@ggml-org/llama-huggingface';
+import type { HfAccount } from '@ggml-org/llama-huggingface/svelte';
+import { SvelteSet } from 'svelte/reactivity';
+
+export const FAKE_OWNER = 'me';
+export const FAKE_SHARED_URL = 'https://huggingface.co/datasets/me/a/blob/main/t.jsonl';
+
+/** The part of an account the dialog reads and calls, as plain state. */
+export class FakeAccount {
+ datasets = $state<HfDataset[]>([]);
+ hasListedDatasets = $state(true);
+ isLoadingDatasets = $state(false);
+ isReadOnly = false;
+ isSigningInWithHf = $state(false);
+ lastDataset = $state<string | null>(null);
+ loadDatasets = async () => {};
+ newDatasetStart = `${FAKE_OWNER}/llama-chat-traces`;
+ oauthError = $state<string | null>(null);
+ /** Repo IDs the Hub turns down. */
+ refused = new SvelteSet<string>();
+ restoreSession = async () => {};
+ signOut = () => {
+ this.user = null;
+ };
+
+ suggestedDataset = '';
+
+ uploads: string[] = [];
+ uploadTrace = async ({ repoId }: { repoId: string }): Promise<string> => {
+ this.uploads.push(repoId);
+
+ if (this.refused.has(repoId)) {
+ // as the real account does: the dataset is not one it can add to any more
+ this.datasets = this.datasets.filter((dataset) => dataset.id !== repoId);
+
+ throw new HfNotWritableError(repoId);
+ }
+
+ return FAKE_SHARED_URL;
+ };
+ user = $state<{ name: string } | null>({ name: FAKE_OWNER });
+
+ get writableDatasets(): HfDataset[] {
+ return this.datasets;
+ }
+}
+
+/** An account that can add to datasets of the given names, as the account `me`. */
+export function fakeAccountWith(...names: string[]): FakeAccount {
+ const account = new FakeAccount();
+
+ account.datasets = names.map((name) => ({ id: `${FAKE_OWNER}/${name}`, isPrivate: false }));
+
+ return account;
+}
+
+export function asHfAccount(account: FakeAccount): HfAccount {
+ return account as unknown as HfAccount;
+}
diff --git a/ui/apps/chat/tests/unit/conversation-trace.test.ts b/ui/apps/chat/tests/unit/conversation-trace.test.ts
new file mode 100644
index 000000000..1689bc82c
--- /dev/null
+++ b/ui/apps/chat/tests/unit/conversation-trace.test.ts
@@ -0,0 +1,159 @@
+import { HF_PREVIEW_LINES_MAX, HF_PREVIEW_TEXT_MAX } from '@ggml-org/llama-huggingface';
+import { ConversationTransferService } from '#lib/services/conversation-transfer.service.ts';
+import { buildConversationTrace, buildTracePreview } from '#lib/utils/conversation-trace.ts';
+import { describe, expect, it } from 'vitest';
+
+function message(
+ id: string,
+ parent: string | null,
+ children: string[],
+ overrides: Partial<DatabaseMessage> = {}
+): DatabaseMessage {
+ return {
+ children,
+ content: id,
+ convId: 'conv',
+ id,
+ parent,
+ role: 'user',
+ timestamp: Number(id.replace(/\D/g, '') || 0),
+ type: 'text',
+ ...overrides
+ } as DatabaseMessage;
+}
+
+// root -> m1 -> m2 -> m3
+// \-> m4 (another branch, current)
+const exported: ExportedConversation = {
+ conv: {
+ currNode: 'm4',
+ cwd: '/home/me/project',
+ groupId: 'g1',
+ id: 'conv',
+ lastModified: 4,
+ name: 'Trace test'
+ },
+ group: { id: 'g1', name: 'Work' },
+ messages: [
+ message('root', null, ['m1'], { type: 'root' }),
+ message('m1', 'root', ['m2'], {
+ extra: [{ content: 'notes', name: 'a.txt', type: 'TEXT' } as unknown as DatabaseMessageExtra]
+ }),
+ message('m2', 'm1', ['m3', 'm4'], { role: 'assistant', toolCwd: '/home/me/project' }),
+ message('m3', 'm2', []),
+ message('m4', 'm2', [])
+ ]
+};
+
+describe('buildConversationTrace', () => {
+ it('keeps the current branch only, without the root', () => {
+ const trace = buildConversationTrace(exported);
+
+ expect(trace.messages.map((m: DatabaseMessage) => m.id)).toEqual(['m1', 'm2', 'm4']);
+ expect(trace.messages[1].children).toEqual(['m4']);
+ expect(trace.conv.currNode).toBe('m4');
+ });
+
+ it('ends the trace at the given message', () => {
+ const trace = buildConversationTrace(exported, { upToMessageId: 'm2' });
+
+ expect(trace.messages.map((m: DatabaseMessage) => m.id)).toEqual(['m1', 'm2']);
+ expect(trace.messages[1].children).toEqual([]);
+ expect(trace.conv.currNode).toBe('m2');
+ });
+
+ it('leaves local paths, the group and attachments on this device', () => {
+ const trace = buildConversationTrace(exported);
+
+ expect(trace.conv).not.toHaveProperty('cwd');
+ expect(trace.conv).not.toHaveProperty('groupId');
+ expect(trace).not.toHaveProperty('group');
+ expect(trace.messages[0]).not.toHaveProperty('extra');
+ expect(trace.messages[1]).not.toHaveProperty('toolCwd');
+ });
+
+ it('keeps attachments when asked to', () => {
+ const trace = buildConversationTrace(exported, { includeAttachments: true });
+
+ expect(trace.messages[0].extra).toHaveLength(1);
+ });
+
+ it('serializes to the Session Traces Format the Hub reads', () => {
+ const jsonl = ConversationTransferService.serializeSessionToJsonl(
+ buildConversationTrace(exported)
+ );
+ const [header, ...lines] = jsonl.split('\n').map((line) => JSON.parse(line));
+
+ expect(header).toMatchObject({ harness: 'llama.app', id: 'conv', type: 'session' });
+ expect(lines).toHaveLength(3);
+ expect(lines[0]).toMatchObject({ message: { content: 'm1', role: 'user' }, type: 'message' });
+ });
+});
+
+describe('buildTracePreview', () => {
+ function talk(overrides: Record<string, Partial<DatabaseMessage>>): ExportedConversation {
+ const ids = ['u1', 'a1', 'u2', 'a2', 'u3', 'a3'];
+
+ return {
+ conv: { ...exported.conv, currNode: 'a3' },
+ messages: ids.map((id, index) =>
+ message(id, index ? ids[index - 1] : null, ids[index + 1] ? [ids[index + 1]] : [], {
+ content: `${id} said`,
+ role: id.startsWith('u') ? 'user' : 'assistant',
+ ...overrides[id]
+ })
+ )
+ };
+ }
+
+ it("takes the first messages, up to the package's cap, one line each, by who said them", () => {
+ const preview = buildTracePreview(talk({}));
+
+ expect(preview).toHaveLength(HF_PREVIEW_LINES_MAX);
+ expect(preview.slice(0, 2)).toEqual([
+ { role: 'user', text: 'u1 said' },
+ { role: 'assistant', text: 'a1 said' }
+ ]);
+ });
+
+ it('skips what is not talk: tool calls, reasoning, messages the app made, empty ones', () => {
+ const preview = buildTracePreview(
+ talk({
+ a1: { content: '' },
+ a2: { isSynthetic: true },
+ u2: { type: 'think' },
+ u3: { role: 'tool' }
+ })
+ );
+
+ expect(preview).toEqual([
+ { role: 'user', text: 'u1 said' },
+ { role: 'assistant', text: 'a3 said' }
+ ]);
+ });
+
+ it('folds whitespace and cuts a long message', () => {
+ const [line] = buildTracePreview(
+ talk({ u1: { content: ` one\n\n two\t${'x'.repeat(400)}` } })
+ );
+
+ expect(line.text.startsWith('one two xxx')).toBe(true);
+ expect(line.text).toHaveLength(HF_PREVIEW_TEXT_MAX);
+ });
+
+ it('leaves out code blocks, and a message that is only code', () => {
+ const preview = buildTracePreview(
+ talk({
+ a1: { content: '```rust\nfn main() {}\n```' },
+ u1: { content: 'Fix `foo`:\n```rust\nfn main() {}\n```\nthanks' },
+ u2: { content: 'cut short\n```rust\nfn ma' }
+ })
+ );
+
+ expect(preview.map((line) => line.text).slice(0, 2)).toEqual(['Fix foo: thanks', 'cut short']);
+ });
+
+ it('is empty for a conversation with no talk', () => {
+ expect(buildTracePreview({ conv: exported.conv, messages: [] })).toEqual([]);
+ });
+});
diff --git a/ui/apps/chat/tests/unit/token-roles.test.ts b/ui/apps/chat/tests/unit/token-roles.test.ts
index 5449c6b7d..d2faab28f 100644
--- a/ui/apps/chat/tests/unit/token-roles.test.ts
+++ b/ui/apps/chat/tests/unit/token-roles.test.ts
@@ -6,7 +6,13 @@ import { describe, expect, it } from 'vitest';
// Type is set through the roles in ui/lib/ui/src/lib/styles/tokens/semantic.css (text-body-sm, text-label,
// text-caption ...), never Tailwind's own sizes or a size in brackets: see Typography in DESIGN.md.
const ui = fileURLToPath(new URL('../../../../', import.meta.url));
-const ROOTS = ['apps/chat/src', 'apps/chat/tests/stories', 'lib/ui/src', 'lib/ui/tests/stories'];
+const ROOTS = [
+ 'apps/chat/src',
+ 'apps/chat/tests/stories',
+ 'lib/huggingface/src',
+ 'lib/ui/src',
+ 'lib/ui/tests/stories'
+];
const SOURCE = /\.(svelte|ts|js|css|svx)$/;
const TAILWIND_SIZE = /(?<![\w-])text-(?:xs|sm|base|lg|xl|[2-9]xl)(?![\w-])/g;
// a size relative to the text around it (text-[0.875em]) is not one off the scale
@@ -16,6 +22,8 @@ const BRACKET_SIZE = /(?<![\w-])text-\[[\d.]+(?:px|rem)\]/g;
const TAILWIND_SHADOW = /(?<![\w-])shadow-(?:2xs|xs|sm|md|lg|xl|2xl)(?![\w-])/g;
const CORNER_ROLE =
/(?<![\w-])rounded(?:-[a-z]{1,2})?-(?:control|panel|card|container|surface)(?![\w])/g;
+// sharing is one icon everywhere, the box with an arrow leaving it: see Sharing in DESIGN.md
+const SHARE2_ICON = /(?<![\w-])(?:Share2|share-2)(?![\w-])/g;
function sources(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
@@ -54,3 +62,9 @@ describe('shadows and corners', () => {
expect(matches(CORNER_ROLE)).toEqual([]);
});
});
+
+describe('icons', () => {
+ it('shares with no other icon than Share', () => {
+ expect(matches(SHARE2_ICON)).toEqual([]);
+ });
+});
diff --git a/ui/apps/chat/tsconfig.json b/ui/apps/chat/tsconfig.json
index 7c4511141..52ee3acea 100644
--- a/ui/apps/chat/tsconfig.json
+++ b/ui/apps/chat/tsconfig.json
@@ -18,6 +18,8 @@
"@ggml-org/llama-ui": ["../../lib/ui/src/lib/index.ts"],
"@ggml-org/llama-voice": ["../../lib/voice/src/index.ts"],
"@ggml-org/llama-voice/svelte": ["../../lib/voice/src/svelte/index.ts"],
+ "@ggml-org/llama-huggingface": ["../../lib/huggingface/src/index.ts"],
+ "@ggml-org/llama-huggingface/svelte": ["../../lib/huggingface/src/svelte/index.ts"],
"$llama-ui-stories/*": ["../../lib/ui/tests/stories/*"],
"@internationalized/date": ["./node_modules/@internationalized/date"],
"@internationalized/date/*": ["./node_modules/@internationalized/date/*"],
@@ -67,6 +69,8 @@
"tests/**/*.svelte",
".storybook/**/*.ts",
"../../lib/ui/tests/stories/svx.d.ts",
+ "../../lib/huggingface/src/**/*.ts",
+ "../../lib/huggingface/src/**/*.svelte",
".storybook/**/*.svelte"
],
"exclude": ["src/lib/services/sandbox-worker.js", "src/lib/vendors/**", "src/service-worker"]
diff --git a/ui/apps/chat/vite.config.ts b/ui/apps/chat/vite.config.ts
index ebbb7d401..80e60ef94 100644
--- a/ui/apps/chat/vite.config.ts
+++ b/ui/apps/chat/vite.config.ts
@@ -17,6 +17,8 @@ import { defineConfig, loadEnv, searchForWorkspaceRoot } from 'vite';
const __dirname = dirname(fileURLToPath(import.meta.url));
const LLAMA_VOICE_SOURCE = resolve(__dirname, '../../lib/voice/src');
+// Llama Hugging Face has no build step in the repo either: the app compiles it from source
+const LLAMA_HUGGINGFACE_ROOT = resolve(__dirname, '../../lib/huggingface');
// 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');
const LLAMA_HARNESS_TRACE_ENTRY = resolve(__dirname, '../../lib/harness/src/trace/index.ts');
@@ -25,6 +27,13 @@ const LLAMA_HARNESS_CHAT_ONLY_ENTRY = resolve(
__dirname,
'src/lib/stores/agentic/harness-chat-only.ts'
);
+// what a build without sharing to Hugging Face (a build that is not asked for it with
+// VITE_PUBLIC_HUGGING_FACE=true) gets in place of the package's Svelte entry: an account that is
+// never signed in, and components that draw nothing
+const LLAMA_HUGGINGFACE_DISABLED_ENTRY = resolve(
+ __dirname,
+ 'src/lib/stores/huggingface-disabled.ts'
+);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const browserBaseConfig: any = {
enabled: true,
@@ -41,9 +50,14 @@ const browserBaseConfig: any = {
// `npm run build` runs without the env var default to ./dist.
const outDir = process.env.LLAMA_UI_OUT_DIR ?? './dist';
-export default defineConfig(({ mode }) => {
+export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, process.cwd(), 'VITE_PUBLIC_');
const SERVER_ORIGIN = env.VITE_PUBLIC_SERVER_ORIGIN || 'http://localhost:9931';
+ // A build has sharing to Hugging Face only when asked for: VITE_PUBLIC_HUGGING_FACE=true. The
+ // dev server, the tests and Storybook have it unless told otherwise (=false).
+ const huggingFace = env.VITE_PUBLIC_HUGGING_FACE
+ ? env.VITE_PUBLIC_HUGGING_FACE === 'true'
+ : command === 'serve';
return {
build: {
@@ -52,6 +66,11 @@ export default defineConfig(({ mode }) => {
minify: true
},
+ // what the app reads as HUGGING_FACE_ENABLED, so it agrees with the alias below
+ define: {
+ 'import.meta.env.VITE_PUBLIC_HUGGING_FACE': JSON.stringify(String(huggingFace))
+ },
+
plugins: [
llamaUiPlugin(),
tailwindcss(),
@@ -93,6 +112,16 @@ export default defineConfig(({ mode }) => {
replacement: resolve(LLAMA_VOICE_SOURCE, 'svelte/index.ts')
},
{ find: /^@ggml-org\/llama-voice$/, replacement: resolve(LLAMA_VOICE_SOURCE, 'index.ts') },
+ {
+ find: /^@ggml-org\/llama-huggingface\/svelte$/,
+ replacement: huggingFace
+ ? resolve(LLAMA_HUGGINGFACE_ROOT, 'src/svelte/index.ts')
+ : LLAMA_HUGGINGFACE_DISABLED_ENTRY
+ },
+ {
+ find: /^@ggml-org\/llama-huggingface$/,
+ replacement: resolve(LLAMA_HUGGINGFACE_ROOT, 'src/index.ts')
+ },
{ find: /^@ggml-org\/llama-harness\/trace$/, replacement: LLAMA_HARNESS_TRACE_ENTRY },
{
find: /^@ggml-org\/llama-harness$/,
@@ -111,6 +140,7 @@ export default defineConfig(({ mode }) => {
searchForWorkspaceRoot(process.cwd()),
resolve(__dirname, 'tests'),
LLAMA_VOICE_SOURCE,
+ LLAMA_HUGGINGFACE_ROOT,
resolve(__dirname, '../../lib/harness')
]
},
diff --git a/ui/lib/huggingface/.gitignore b/ui/lib/huggingface/.gitignore
new file mode 100644
index 000000000..16339ab2e
--- /dev/null
+++ b/ui/lib/huggingface/.gitignore
@@ -0,0 +1,6 @@
+node_modules
+/dist
+
+# OS
+.DS_Store
+Thumbs.db
diff --git a/ui/lib/huggingface/.npmrc b/ui/lib/huggingface/.npmrc
new file mode 100644
index 000000000..b6f27f135
--- /dev/null
+++ b/ui/lib/huggingface/.npmrc
@@ -0,0 +1 @@
+engine-strict=true
diff --git a/ui/lib/huggingface/.prettierrc b/ui/lib/huggingface/.prettierrc
new file mode 100644
index 000000000..43d8d5352
--- /dev/null
+++ b/ui/lib/huggingface/.prettierrc
@@ -0,0 +1,16 @@
+{
+ "useTabs": true,
+ "singleQuote": true,
+ "trailingComma": "none",
+ "printWidth": 100,
+ "plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
+ "overrides": [
+ {
+ "files": "*.svelte",
+ "options": {
+ "parser": "svelte"
+ }
+ }
+ ],
+ "tailwindStylesheet": "../../apps/chat/src/app.css"
+}
diff --git a/ui/lib/huggingface/LICENSE b/ui/lib/huggingface/LICENSE
new file mode 100644
index 000000000..50c59c51c
--- /dev/null
+++ b/ui/lib/huggingface/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/huggingface/README.md b/ui/lib/huggingface/README.md
new file mode 100644
index 000000000..26929ae32
--- /dev/null
+++ b/ui/lib/huggingface/README.md
@@ -0,0 +1,69 @@
+# Llama Hugging Face
+
+`@ggml-org/llama-huggingface` gives an app that runs in the browser, with no server of its own, a Hugging Face account: signing in, and sharing a conversation to a dataset as an [agent trace](https://huggingface.co/docs/hub/agent-traces).
+
+It knows no app. The app says who it is, hands over what to share, and decides where the components show.
+
+| Entry | What it holds |
+| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `@ggml-org/llama-huggingface` | Plain TypeScript, no dependencies: "Sign in with Hugging Face" (OAuth with PKCE and dynamic client registration, `HfOAuthSignIn`) and the Hub calls (`whoAmI`, `listDatasets`, `uploadTrace`). |
+| `@ggml-org/llama-huggingface/svelte` | The account as Svelte state (`HfAccount`) and the components that show it, built on `@ggml-org/llama-ui`: `HfAccountPanel`, `HfShareDialog`, `HfLogo`. |
+
+## Use
+
+```ts
+import { HfAccount } from '@ggml-org/llama-huggingface/svelte';
+
+export const account = new HfAccount({
+ callbackUrl: () => new URL('/', window.location.origin).href,
+ clientName: 'My app',
+ defaultDatasetName: 'my-app-traces',
+ logoUrl: 'https://example.com/my-app.png', // optional: shown for the app on Hugging Face
+ requiredScope: 'contribute-repos',
+ scopes: ['openid', 'profile', 'contribute-repos'],
+ storagePrefix: 'my-app'
+});
+
+// on every page load: finishes a sign-in when Hugging Face sent the browser back
+const outcome = await account.completeSignInFromLocation();
+
+if (outcome?.closeWindow) window.close();
+```
+
+```svelte
+<script lang="ts">
+ import { HfAccountPanel, HfShareDialog } from '@ggml-org/llama-huggingface/svelte';
+</script>
+
+<!-- who is signed in, or the two ways to sign in: a button, or a pasted access token -->
+<HfAccountPanel {account} />
+
+<HfShareDialog
+ bind:open
+ {account}
+ buildTrace={async (scope, includeAttachments) => ({
+ commitMessage: 'Add trace: my chat',
+ content: jsonl, // Session Traces Format, one JSON object per line
+ path: 'my-chat.jsonl',
+ preview: [{ role: 'user', text: 'What is Rust?' }] // optional: shown faded once it is shared
+ })}
+ onCopyLink={(url) => navigator.clipboard.writeText(url)}
+ scopes={[{ id: 'all', label: 'Whole conversation', detail: '12 messages' }]}
+ subject={'"My chat"'}
+/>
+```
+
+- The share dialog offers the datasets a share can go to as tiles, and a tile to create one. An access token that was pasted reaches every dataset of the account; a sign-in with Hugging Face reaches only the ones the app created, which the browser knows as the ones it shared to (`HfAccount.writableDatasets`). With none, the dialog asks for the name of a new one.
+- A sign-in opens the Hugging Face authorization page in a popup, or in the tab when the popup is blocked. The app registers itself for its own origin on first use, so it works from any host and port.
+- The sign-in and the pasted token are kept in `localStorage`, under the app's `storagePrefix`.
+- With `contribute-repos`, a sign-in can write only to the datasets the app created; a pasted access token with write access is not limited that way.
+
+## Development
+
+The package has no build step and is not published yet: apps in this repo compile its sources, and its components are type-checked by the app that uses them.
+
+```bash
+npm install
+npm run check
+npm test
+```
diff --git a/ui/lib/huggingface/package-lock.json b/ui/lib/huggingface/package-lock.json
new file mode 100644
index 000000000..19958852c
--- /dev/null
+++ b/ui/lib/huggingface/package-lock.json
@@ -0,0 +1,1474 @@
+{
+ "name": "@ggml-org/llama-huggingface",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@ggml-org/llama-huggingface",
+ "version": "0.1.0",
+ "license": "MIT",
+ "devDependencies": {
+ "@types/node": "24.19.2",
+ "svelte": "5.57.3",
+ "typescript": "6.0.3",
+ "vitest": "5.0.5"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "peerDependencies": {
+ "@ggml-org/llama-ui": "^0.7.0",
+ "@lucide/svelte": "^1.0.0",
+ "svelte": "^5.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@ggml-org/llama-ui": {
+ "optional": true
+ },
+ "@lucide/svelte": {
+ "optional": true
+ },
+ "svelte": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@emnapi/core": {
+ "version": "2.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
+ "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "2.2.0",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "2.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz",
+ "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/wasi-threads": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
+ "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/remapping": {
+ "version": "2.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",
+ "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",
+ "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/@napi-rs/wasm-runtime": {
+ "version": "1.2.6",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz",
+ "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.3"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1 || 2.0.0-beta.2",
+ "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2"
+ }
+ },
+ "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/@rolldown/binding-android-arm-eabi": {
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz",
+ "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz",
+ "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz",
+ "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz",
+ "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz",
+ "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz",
+ "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz",
+ "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz",
+ "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz",
+ "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz",
+ "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz",
+ "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz",
+ "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz",
+ "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-wasm32-wasi": {
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz",
+ "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "@emnapi/core": "2.0.0-beta.2",
+ "@emnapi/runtime": "2.0.0-beta.2",
+ "@napi-rs/wasm-runtime": "1.2.6"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz",
+ "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==",
+ "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.19",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz",
+ "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==",
+ "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.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
+ "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true
+ },
+ "node_modules/@sveltejs/acorn-typescript": {
+ "version": "1.0.13",
+ "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz",
+ "integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "acorn": "^8.9.0"
+ }
+ },
+ "node_modules/@tybys/wasm-util": {
+ "version": "0.10.5",
+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
+ "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "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.11",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.11.tgz",
+ "integrity": "sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg==",
+ "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/acorn": {
+ "version": "8.19.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",
+ "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/aria-query": {
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz",
+ "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "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/axobject-query": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
+ "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "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/clsx": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "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/devalue": {
+ "version": "5.9.4",
+ "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz",
+ "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "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/esm-env": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz",
+ "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esrap": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.2.tgz",
+ "integrity": "sha512-WpVZsWnSheHBy+fGrO/0duwnbe6ODZH1QyBbjupreSCJGojaBWRncrq+HVeIJ8eHQjEwSJg9hC4yPJyNVOrpqg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.4.15"
+ },
+ "peerDependencies": {
+ "@typescript-eslint/types": "^8.2.0"
+ },
+ "peerDependenciesMeta": {
+ "@typescript-eslint/types": {
+ "optional": true
+ }
+ }
+ },
+ "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/is-reference": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz",
+ "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.6"
+ }
+ },
+ "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/locate-character": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz",
+ "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "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/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/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",
+ "peer": true
+ },
+ "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.33",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
+ "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==",
+ "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/rolldown": {
+ "version": "1.2.19",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz",
+ "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==",
+ "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.19",
+ "@rolldown/binding-android-arm64": "1.2.19",
+ "@rolldown/binding-darwin-arm64": "1.2.19",
+ "@rolldown/binding-darwin-x64": "1.2.19",
+ "@rolldown/binding-freebsd-x64": "1.2.19",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.19",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.19",
+ "@rolldown/binding-linux-arm64-musl": "1.2.19",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.19",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.19",
+ "@rolldown/binding-linux-x64-gnu": "1.2.19",
+ "@rolldown/binding-linux-x64-musl": "1.2.19",
+ "@rolldown/binding-openharmony-arm64": "1.2.19",
+ "@rolldown/binding-wasm32-wasi": "1.2.19",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.19",
+ "@rolldown/binding-win32-x64-msvc": "1.2.19"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz",
+ "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "peer": true,
+ "engines": {
+ "node": ">=6.0.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/svelte": {
+ "version": "5.57.3",
+ "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.3.tgz",
+ "integrity": "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/remapping": "^2.3.5",
+ "@jridgewell/sourcemap-codec": "^1.6.0",
+ "@sveltejs/acorn-typescript": "^1.0.13",
+ "@types/estree": "^1.0.9",
+ "acorn": "^8.18.0",
+ "aria-query": "5.3.1",
+ "axobject-query": "^4.1.0",
+ "clsx": "^2.1.1",
+ "devalue": "^5.9.2",
+ "esm-env": "^1.2.1",
+ "esrap": "^2.3.6",
+ "is-reference": "^3.0.3",
+ "locate-character": "^3.0.0",
+ "magic-string": "^0.30.11",
+ "zimmerframe": "^1.1.2"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/svelte/node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/tinybench": {
+ "version": "6.2.5",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.5.tgz",
+ "integrity": "sha512-b/8GRMdnY4cqkfCLyaFpTGIv1qwfi3oT0mWaepwT++6Z/ZrYehNfZZ2JDKVLKGhNoEkS3IIB1ELtCT0XS5DtOA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/tinyexec": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.4.0.tgz",
+ "integrity": "sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg==",
+ "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/tslib": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
+ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
+ "dev": true,
+ "license": "0BSD",
+ "optional": true,
+ "peer": true
+ },
+ "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.8",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz",
+ "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==",
+ "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"
+ }
+ },
+ "node_modules/zimmerframe": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz",
+ "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/ui/lib/huggingface/package.json b/ui/lib/huggingface/package.json
new file mode 100644
index 000000000..eb8f10a36
--- /dev/null
+++ b/ui/lib/huggingface/package.json
@@ -0,0 +1,51 @@
+{
+ "name": "@ggml-org/llama-huggingface",
+ "version": "0.1.0",
+ "private": true,
+ "description": "A Hugging Face account for llama.cpp frontend apps: sign in from the browser and share conversations as agent traces.",
+ "homepage": "https://github.com/ggml-org/llama.cpp/tree/master/ui/lib/huggingface",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/ggml-org/llama.cpp.git",
+ "directory": "ui/lib/huggingface"
+ },
+ "type": "module",
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts",
+ "./svelte": {
+ "svelte": "./src/svelte/index.ts",
+ "default": "./src/svelte/index.ts"
+ }
+ },
+ "scripts": {
+ "check": "tsc --noEmit",
+ "test": "vitest --run"
+ },
+ "peerDependencies": {
+ "@ggml-org/llama-ui": "^0.7.0",
+ "@lucide/svelte": "^1.0.0",
+ "svelte": "^5.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@ggml-org/llama-ui": {
+ "optional": true
+ },
+ "@lucide/svelte": {
+ "optional": true
+ },
+ "svelte": {
+ "optional": true
+ }
+ },
+ "devDependencies": {
+ "@types/node": "24.19.2",
+ "svelte": "5.57.3",
+ "typescript": "6.0.3",
+ "vitest": "5.0.5"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+}
diff --git a/ui/lib/huggingface/src/client.ts b/ui/lib/huggingface/src/client.ts
new file mode 100644
index 000000000..a76bbb5e2
--- /dev/null
+++ b/ui/lib/huggingface/src/client.ts
@@ -0,0 +1,227 @@
+/**
+ * The OAuth calls of a public client in the browser: dynamic client registration, then the
+ * authorization code flow with PKCE. The endpoints answer cross-origin requests, so no server
+ * is involved. Stateless: HfOAuthSignIn (./sign-in.ts) keeps what a sign-in needs between them.
+ */
+
+import {
+ HF_CONTENT_TYPE_FORM,
+ HF_CONTENT_TYPE_JSON,
+ HF_HEADER_CONTENT_TYPE,
+ HF_HTTP_CLIENT_ERROR_MIN,
+ HF_HTTP_POST,
+ HF_HTTP_SERVER_ERROR_MIN,
+ HF_MS_PER_SECOND,
+ HF_OAUTH_AUTHORIZE_URL,
+ HF_OAUTH_CODE_CHALLENGE_HASH,
+ HF_OAUTH_CODE_CHALLENGE_METHOD,
+ HF_OAUTH_RANDOM_BYTES,
+ HF_OAUTH_REGISTER_URL,
+ HF_OAUTH_RESPONSE_TYPE,
+ HF_OAUTH_SCOPE_SEPARATOR,
+ HF_OAUTH_TOKEN_ENDPOINT_AUTH_METHOD,
+ HF_OAUTH_TOKEN_URL
+} from './constants.js';
+import { HfOAuthGrantType, HfOAuthParam } from './enums.js';
+import { HfTokenRejectedError } from './errors.js';
+import { HF_ACTION, type HfAction, HF_MESSAGE } from './messages.js';
+import type {
+ HfOAuthClient,
+ HfOAuthTokens,
+ HfRegistrationResponse,
+ HfTokenResponse
+} from './types.js';
+import { bytesToBase64Url } from './util.js';
+
+/** A random URL-safe string: a PKCE verifier, or a state. */
+export function createRandomString(): string {
+ return bytesToBase64Url(crypto.getRandomValues(new Uint8Array(HF_OAUTH_RANDOM_BYTES)));
+}
+
+/** The S256 challenge of a PKCE verifier. */
+export async function createCodeChallenge(verifier: string): Promise<string> {
+ // the Web Crypto digest exists only on a secure page
+ if (!globalThis.crypto?.subtle) throw new Error(HF_MESSAGE.SECURE_PAGE_NEEDED);
+
+ const digest = await crypto.subtle.digest(
+ HF_OAUTH_CODE_CHALLENGE_HASH,
+ new TextEncoder().encode(verifier)
+ );
+
+ return bytesToBase64Url(new Uint8Array(digest));
+}
+
+/** The OAuth error of a failed response, as one readable line. */
+async function describeError(response: Response): Promise<string> {
+ try {
+ const body = await response.json();
+ const parts = [body?.[HfOAuthParam.ERROR], body?.[HfOAuthParam.ERROR_DESCRIPTION]].filter(
+ (part) => typeof part === 'string' && part
+ );
+
+ if (parts.length) return parts.join(': ');
+ } catch {
+ // not JSON; keep the status
+ }
+
+ return HF_MESSAGE.status(response.status);
+}
+
+/** A POST that says `unreachable` when no answer comes, instead of the browser's own error. */
+async function post(
+ url: string,
+ body: string,
+ contentType: string,
+ unreachable: string
+): Promise<Response> {
+ try {
+ return await fetch(url, {
+ body,
+ headers: { [HF_HEADER_CONTENT_TYPE]: contentType },
+ method: HF_HTTP_POST
+ });
+ } catch {
+ throw new Error(unreachable);
+ }
+}
+
+async function requestTokens(
+ fields: Record<string, string>,
+ action: HfAction
+): Promise<HfOAuthTokens> {
+ const now = Date.now();
+ const response = await post(
+ HF_OAUTH_TOKEN_URL,
+ new URLSearchParams(fields).toString(),
+ HF_CONTENT_TYPE_FORM,
+ HF_MESSAGE.tokenRequestUnreachable(action)
+ );
+
+ if (!response.ok) {
+ const message = HF_MESSAGE.tokenRequestFailed(action, await describeError(response));
+
+ // a 4xx is the endpoint saying no, for good; a 5xx may pass
+ throw response.status >= HF_HTTP_CLIENT_ERROR_MIN && response.status < HF_HTTP_SERVER_ERROR_MIN
+ ? new HfTokenRejectedError(message)
+ : new Error(message);
+ }
+
+ const body: HfTokenResponse = await response.json();
+
+ if (typeof body?.access_token !== 'string') throw new Error(HF_MESSAGE.ACCESS_TOKEN_MISSING);
+
+ return {
+ accessToken: body.access_token,
+ expiresAt:
+ typeof body.expires_in === 'number' ? now + body.expires_in * HF_MS_PER_SECOND : undefined,
+ refreshToken: typeof body.refresh_token === 'string' ? body.refresh_token : undefined,
+ scope: typeof body.scope === 'string' ? body.scope : undefined
+ };
+}
+
+/**
+ * Registers the app as a public client for one redirect URL.
+ * @returns The client ID
+ * @throws When Hugging Face turns the registration down
+ */
+export async function registerClient(client: HfOAuthClient): Promise<string> {
+ const response = await post(
+ HF_OAUTH_REGISTER_URL,
+ JSON.stringify({
+ client_name: client.clientName,
+ grant_types: [HfOAuthGrantType.AUTHORIZATION_CODE, HfOAuthGrantType.REFRESH_TOKEN],
+ logo_uri: client.logoUrl,
+ redirect_uris: [client.redirectUrl],
+ response_types: [HF_OAUTH_RESPONSE_TYPE],
+ scope: client.scopes.join(HF_OAUTH_SCOPE_SEPARATOR),
+ token_endpoint_auth_method: HF_OAUTH_TOKEN_ENDPOINT_AUTH_METHOD
+ }),
+ HF_CONTENT_TYPE_JSON,
+ HF_MESSAGE.APP_NOT_REGISTERED
+ );
+
+ if (!response.ok) {
+ throw new Error(
+ HF_MESSAGE.registrationRefused(
+ new URL(client.redirectUrl).origin,
+ await describeError(response)
+ )
+ );
+ }
+
+ const body: HfRegistrationResponse = await response.json();
+
+ if (typeof body?.client_id !== 'string') throw new Error(HF_MESSAGE.CLIENT_ID_MISSING);
+
+ return body.client_id;
+}
+
+/** The Hugging Face page that asks the user to let the app in. */
+export function authorizationUrl(params: {
+ clientId: string;
+ codeChallenge: string;
+ redirectUrl: string;
+ scopes: readonly string[];
+ state: string;
+}): URL {
+ const url = new URL(HF_OAUTH_AUTHORIZE_URL);
+
+ url.searchParams.set(HfOAuthParam.CLIENT_ID, params.clientId);
+ url.searchParams.set(HfOAuthParam.CODE_CHALLENGE, params.codeChallenge);
+ url.searchParams.set(HfOAuthParam.CODE_CHALLENGE_METHOD, HF_OAUTH_CODE_CHALLENGE_METHOD);
+ url.searchParams.set(HfOAuthParam.REDIRECT_URI, params.redirectUrl);
+ url.searchParams.set(HfOAuthParam.RESPONSE_TYPE, HF_OAUTH_RESPONSE_TYPE);
+ url.searchParams.set(HfOAuthParam.SCOPE, params.scopes.join(HF_OAUTH_SCOPE_SEPARATOR));
+ url.searchParams.set(HfOAuthParam.STATE, params.state);
+
+ return url;
+}
+
+/**
+ * Trades the code the authorization page sent back for tokens.
+ * @throws When Hugging Face refuses the code
+ */
+export function exchangeCode(params: {
+ clientId: string;
+ code: string;
+ codeVerifier: string;
+ redirectUrl: string;
+}): Promise<HfOAuthTokens> {
+ return requestTokens(
+ {
+ [HfOAuthParam.CLIENT_ID]: params.clientId,
+ [HfOAuthParam.CODE]: params.code,
+ [HfOAuthParam.CODE_VERIFIER]: params.codeVerifier,
+ [HfOAuthParam.GRANT_TYPE]: HfOAuthGrantType.AUTHORIZATION_CODE,
+ [HfOAuthParam.REDIRECT_URI]: params.redirectUrl
+ },
+ HF_ACTION.SIGN_IN
+ );
+}
+
+/**
+ * Gets a new access token with a refresh token.
+ * @throws HfTokenRejectedError when the refresh token is no longer good; any other error when
+ * Hugging Face could not be reached or failed
+ */
+export async function refreshTokens(
+ clientId: string,
+ refreshToken: string
+): Promise<HfOAuthTokens> {
+ const tokens = await requestTokens(
+ {
+ [HfOAuthParam.CLIENT_ID]: clientId,
+ [HfOAuthParam.GRANT_TYPE]: HfOAuthGrantType.REFRESH_TOKEN,
+ [HfOAuthParam.REFRESH_TOKEN]: refreshToken
+ },
+ HF_ACTION.SIGN_IN_RENEWAL
+ );
+
+ // a refresh may hand out no new refresh token: the old one stays good
+ return { ...tokens, refreshToken: tokens.refreshToken ?? refreshToken };
+}
+
+/** Whether tokens carry a scope; tokens that do not say which they carry are let through. */
+export function hasScope(tokens: HfOAuthTokens, scope: string): boolean {
+ return !tokens.scope || tokens.scope.split(HF_OAUTH_SCOPE_SEPARATOR).includes(scope);
+}
diff --git a/ui/lib/huggingface/src/constants.ts b/ui/lib/huggingface/src/constants.ts
new file mode 100644
index 000000000..f4d5b536e
--- /dev/null
+++ b/ui/lib/huggingface/src/constants.ts
@@ -0,0 +1,127 @@
+/**
+ * Hugging Face endpoints and the values the Hub API and the OAuth flow take.
+ * References: https://huggingface.co/docs/hub/oauth, https://huggingface.co/docs/hub/api,
+ * https://huggingface.co/docs/hub/session-traces-format
+ */
+
+export const HF_BASE_URL = 'https://huggingface.co';
+
+// OAuth
+
+export const HF_OAUTH_AUTHORIZE_URL = `${HF_BASE_URL}/oauth/authorize`;
+export const HF_OAUTH_REGISTER_URL = `${HF_BASE_URL}/oauth/register`;
+export const HF_OAUTH_TOKEN_URL = `${HF_BASE_URL}/oauth/token`;
+
+/** Query parameter that marks a page load as Hugging Face sending the browser back. */
+export const HF_OAUTH_CALLBACK_PARAM = 'hf_oauth';
+export const HF_OAUTH_CALLBACK_VALUE = '1';
+
+export const HF_OAUTH_SCOPE_SEPARATOR = ' ';
+export const HF_OAUTH_RESPONSE_TYPE = 'code';
+export const HF_OAUTH_CODE_CHALLENGE_METHOD = 'S256';
+export const HF_OAUTH_CODE_CHALLENGE_HASH = 'SHA-256';
+/** A public client: the browser holds no secret. */
+export const HF_OAUTH_TOKEN_ENDPOINT_AUTH_METHOD = 'none';
+/** Bytes of randomness in a PKCE verifier and in a state. */
+export const HF_OAUTH_RANDOM_BYTES = 32;
+
+export const HF_MS_PER_SECOND = 1000;
+/** A sign-in that has not come back by then is dropped. */
+export const HF_OAUTH_PENDING_TTL_MS = 15 * 60 * HF_MS_PER_SECOND;
+/** An access token is renewed this long before it expires. */
+export const HF_OAUTH_EXPIRY_MARGIN_MS = 60 * HF_MS_PER_SECOND;
+
+/** The window a sign-in opens the authorization page in. */
+export const HF_OAUTH_POPUP_NAME = 'hf-oauth';
+export const HF_OAUTH_POPUP_FEATURES = 'popup,width=520,height=720';
+/** Where the popup waits while the app registers with Hugging Face. */
+export const HF_OAUTH_POPUP_BLANK_URL = 'about:blank';
+
+// HTTP
+
+export const HF_HEADER_AUTHORIZATION = 'Authorization';
+export const HF_HEADER_CONTENT_TYPE = 'Content-Type';
+export const HF_BEARER_PREFIX = 'Bearer ';
+export const HF_CONTENT_TYPE_JSON = 'application/json';
+export const HF_CONTENT_TYPE_FORM = 'application/x-www-form-urlencoded';
+/** Commit API body: one JSON operation per line. */
+export const HF_CONTENT_TYPE_NDJSON = 'application/x-ndjson';
+export const HF_HTTP_POST = 'POST';
+/** A Hub call that has not answered by then is given up, so it cannot hold a dialog open. */
+export const HF_REQUEST_TIMEOUT_MS = 60 * HF_MS_PER_SECOND;
+/**
+ * The slowest uplink a call is given time for: its timeout grows by the time its body takes to
+ * send at this speed, so a large trace on a slow link is not given up while it is going out.
+ */
+export const HF_UPLOAD_MIN_BYTES_PER_SECOND = 32 * 1024;
+/** The name of the error `AbortSignal.timeout` aborts a request with. */
+export const HF_TIMEOUT_ERROR_NAME = 'TimeoutError';
+/** The first status of a request the Hub turned down, and of one it failed to answer. */
+export const HF_HTTP_CLIENT_ERROR_MIN = 400;
+export const HF_HTTP_SERVER_ERROR_MIN = 500;
+export const HF_HTTP_UNAUTHORIZED = 401;
+export const HF_HTTP_FORBIDDEN = 403;
+export const HF_HTTP_NOT_FOUND = 404;
+export const HF_HTTP_CONFLICT = 409;
+
+// Hub API
+
+export const HF_API_WHOAMI_URL = `${HF_BASE_URL}/api/whoami-v2`;
+export const HF_API_CREATE_REPO_URL = `${HF_BASE_URL}/api/repos/create`;
+export const HF_API_DATASETS_URL = `${HF_BASE_URL}/api/datasets`;
+export const HF_DATASETS_URL = `${HF_BASE_URL}/datasets`;
+export const HF_TRACES_DOCS_URL = `${HF_BASE_URL}/docs/hub/agent-traces`;
+/** Opens the token form with write access picked, the access a share needs. */
+export const HF_NEW_TOKEN_URL = `${HF_BASE_URL}/settings/tokens/new?tokenType=write`;
+
+export const HF_REPO_TYPE_DATASET = 'dataset';
+export const HF_MAIN_BRANCH = 'main';
+/** Separates the owner from the name in a repo ID. */
+export const HF_REPO_ID_SEPARATOR = '/';
+/** `owner/name`, each part made of letters, digits, `-`, `_` and `.`. */
+export const HF_REPO_ID_REGEX = /^[\w.-]+\/[\w.-]+$/;
+
+/** Datasets listed to pick from. */
+export const HF_DATASETS_LIST_LIMIT = 100;
+/** Query of the dataset list: an account's datasets, most recently changed first. */
+export const HF_DATASETS_LIST_QUERY = {
+ direction: '-1',
+ limit: String(HF_DATASETS_LIST_LIMIT),
+ sort: 'lastModified'
+} as const;
+export const HF_DATASETS_AUTHOR_PARAM = 'author';
+
+export const HF_COMMIT_LINE_SEPARATOR = '\n';
+export const HF_COMMIT_KEY_HEADER = 'header';
+export const HF_COMMIT_KEY_FILE = 'file';
+export const HF_COMMIT_ENCODING = 'base64';
+/** Bytes turned to base64 at a time, under the argument limit of String.fromCharCode. */
+export const HF_BASE64_CHUNK_BYTES = 0x8000;
+/** Bytes of the file the preupload check reads to pick regular or LFS upload. */
+export const HF_PREUPLOAD_SAMPLE_BYTES = 512;
+export const HF_UPLOAD_MODE_LFS = 'lfs';
+/** The Hub takes files up to this size in a commit; larger ones need LFS, which a share does not do. */
+export const HF_REGULAR_FILE_MAX_BYTES = 10 * 1024 * 1024;
+
+// What the account keeps in localStorage, after the app's own prefix
+
+export const HF_STORAGE_KEY_OAUTH = 'huggingFaceOAuth';
+export const HF_STORAGE_KEY_TOKEN = 'huggingFaceToken';
+export const HF_STORAGE_KEY_DATASET = 'huggingFaceTracesDataset';
+export const HF_STORAGE_KEY_SHARED_DATASETS = 'huggingFaceSharedDatasets';
+export const HF_STORAGE_KEY_SEPARATOR = '.';
+
+/** The name of the error for a dataset the account cannot write to. */
+export const HF_NOT_WRITABLE_ERROR_NAME = 'HfNotWritableError';
+/** The name of the error for a token the Hugging Face turned down. */
+export const HF_TOKEN_REJECTED_ERROR_NAME = 'HfTokenRejectedError';
+/** Messages of a conversation a finished share shows faded, and the text kept of each. */
+export const HF_PREVIEW_LINES_MAX = 4;
+export const HF_PREVIEW_TEXT_MAX = 200;
+
+/** Choice value of the "New dataset" tile; repo IDs always hold a slash, so it never clashes. */
+export const HF_NEW_DATASET_VALUE = 'new';
+/** Datasets a sign-in remembers having shared to, per account: the ones it can write to again. */
+export const HF_SHARED_DATASETS_MAX = 20;
+/** Dataset tiles a share shows before "Show all". */
+export const HF_DATASET_TILES_SHOWN = 3;
diff --git a/ui/lib/huggingface/src/enums.ts b/ui/lib/huggingface/src/enums.ts
new file mode 100644
index 000000000..4de55b536
--- /dev/null
+++ b/ui/lib/huggingface/src/enums.ts
@@ -0,0 +1,41 @@
+/** How a sign-in that left for the authorization page comes back. */
+export enum HfOAuthFlowMode {
+ /** In a popup, which can close once the tokens are in. */
+ POPUP = 'popup',
+ /** In the tab that started it, which goes back to where it was. */
+ REDIRECT = 'redirect'
+}
+
+export enum HfOAuthGrantType {
+ AUTHORIZATION_CODE = 'authorization_code',
+ REFRESH_TOKEN = 'refresh_token'
+}
+
+/** Names of the OAuth request and callback parameters. */
+export enum HfOAuthParam {
+ CLIENT_ID = 'client_id',
+ CODE = 'code',
+ CODE_CHALLENGE = 'code_challenge',
+ CODE_CHALLENGE_METHOD = 'code_challenge_method',
+ CODE_VERIFIER = 'code_verifier',
+ ERROR = 'error',
+ ERROR_DESCRIPTION = 'error_description',
+ GRANT_TYPE = 'grant_type',
+ REDIRECT_URI = 'redirect_uri',
+ REFRESH_TOKEN = 'refresh_token',
+ RESPONSE_TYPE = 'response_type',
+ SCOPE = 'scope',
+ STATE = 'state'
+}
+
+/** Error codes the authorization page sends back that get their own wording. */
+export enum HfOAuthErrorCode {
+ ACCESS_DENIED = 'access_denied'
+}
+
+/** What an access token may do, as `/api/whoami-v2` reports it. */
+export enum HfTokenRole {
+ FINE_GRAINED = 'fineGrained',
+ READ = 'read',
+ WRITE = 'write'
+}
diff --git a/ui/lib/huggingface/src/errors.ts b/ui/lib/huggingface/src/errors.ts
new file mode 100644
index 000000000..3a0a0add4
--- /dev/null
+++ b/ui/lib/huggingface/src/errors.ts
@@ -0,0 +1,27 @@
+/** The errors a caller can tell from the rest and act on. */
+
+import { HF_NOT_WRITABLE_ERROR_NAME, HF_TOKEN_REJECTED_ERROR_NAME } from './constants.js';
+import { HF_MESSAGE } from './messages.js';
+
+/** The Hub turned down a share because the account cannot write to the dataset. */
+export class HfNotWritableError extends Error {
+ readonly repoId: string;
+
+ constructor(repoId: string) {
+ super(HF_MESSAGE.notWritable(repoId));
+ this.name = HF_NOT_WRITABLE_ERROR_NAME;
+ this.repoId = repoId;
+ }
+}
+
+/**
+ * The token endpoint turned a request down (a 4xx), as it does a refresh token that was
+ * revoked or has expired for good. An endpoint that could not be reached, or failed (a 5xx),
+ * is a plain Error: asking again later may work.
+ */
+export class HfTokenRejectedError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = HF_TOKEN_REJECTED_ERROR_NAME;
+ }
+}
diff --git a/ui/lib/huggingface/src/hub.ts b/ui/lib/huggingface/src/hub.ts
new file mode 100644
index 000000000..e4fb886f4
--- /dev/null
+++ b/ui/lib/huggingface/src/hub.ts
@@ -0,0 +1,237 @@
+/**
+ * The Hub API calls of an account: who it is, its datasets, and committing a trace to one.
+ * Stateless, and callable from the browser: the Hub API allows cross-origin requests.
+ * Reference: https://huggingface.co/docs/hub/api
+ */
+
+import {
+ HF_API_CREATE_REPO_URL,
+ HF_API_DATASETS_URL,
+ HF_API_WHOAMI_URL,
+ HF_BEARER_PREFIX,
+ HF_COMMIT_ENCODING,
+ HF_COMMIT_KEY_FILE,
+ HF_COMMIT_KEY_HEADER,
+ HF_COMMIT_LINE_SEPARATOR,
+ HF_CONTENT_TYPE_JSON,
+ HF_CONTENT_TYPE_NDJSON,
+ HF_DATASETS_AUTHOR_PARAM,
+ HF_DATASETS_LIST_QUERY,
+ HF_DATASETS_URL,
+ HF_HEADER_AUTHORIZATION,
+ HF_HEADER_CONTENT_TYPE,
+ HF_HTTP_CONFLICT,
+ HF_HTTP_FORBIDDEN,
+ HF_HTTP_NOT_FOUND,
+ HF_HTTP_POST,
+ HF_HTTP_UNAUTHORIZED,
+ HF_MAIN_BRANCH,
+ HF_MS_PER_SECOND,
+ HF_PREUPLOAD_SAMPLE_BYTES,
+ HF_REGULAR_FILE_MAX_BYTES,
+ HF_REPO_ID_REGEX,
+ HF_REPO_TYPE_DATASET,
+ HF_REQUEST_TIMEOUT_MS,
+ HF_TIMEOUT_ERROR_NAME,
+ HF_UPLOAD_MIN_BYTES_PER_SECOND,
+ HF_UPLOAD_MODE_LFS
+} from './constants.js';
+import { HfNotWritableError } from './errors.js';
+import { HF_ACTION, type HfAction, HF_MESSAGE } from './messages.js';
+import type { HfDataset, HfTraceUpload, HfUser } from './types.js';
+import { bytesToBase64, splitRepoId } from './util.js';
+
+/** The headers of a Hub call: the token, and what the body is when there is one. */
+function headers(token: string, contentType?: string): Record<string, string> {
+ return {
+ [HF_HEADER_AUTHORIZATION]: `${HF_BEARER_PREFIX}${token}`,
+ ...(contentType ? { [HF_HEADER_CONTENT_TYPE]: contentType } : {})
+ };
+}
+
+/**
+ * How long a call may take: the usual limit, and the time its body needs to go out on the
+ * slowest link it is given time for. The timeout counts the upload too.
+ */
+function timeoutFor(init: RequestInit): number {
+ const bodyBytes = typeof init.body === 'string' ? init.body.length : 0;
+
+ return (
+ HF_REQUEST_TIMEOUT_MS + Math.ceil(bodyBytes / HF_UPLOAD_MIN_BYTES_PER_SECOND) * HF_MS_PER_SECOND
+ );
+}
+
+/** A request to the Hub that is given up after its timeout instead of waiting for good. */
+async function hubFetch(url: string, init: RequestInit = {}): Promise<Response> {
+ try {
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutFor(init)) });
+ } catch (error) {
+ if (error instanceof Error && error.name === HF_TIMEOUT_ERROR_NAME) {
+ throw new Error(HF_MESSAGE.REQUEST_TIMED_OUT, { cause: error });
+ }
+
+ throw error;
+ }
+}
+
+/** Throws with the Hub's own error text when it gives one. */
+async function ensureOk(response: Response, action: HfAction): Promise<void> {
+ if (response.ok) return;
+
+ let detail = response.statusText;
+
+ try {
+ const body = await response.json();
+
+ if (typeof body?.error === 'string') detail = body.error;
+ } catch {
+ // not JSON; keep the status text
+ }
+
+ throw new Error(HF_MESSAGE.requestFailed(action, response.status, detail));
+}
+
+/**
+ * A sign-in with Hugging Face reaches only the datasets the app created, so the Hub turns down
+ * a share to any other dataset: a 403, or a 409 for creating one the sign-in cannot see.
+ */
+function ensureWritable(response: Response, repoId: string): void {
+ if (response.status !== HF_HTTP_FORBIDDEN && response.status !== HF_HTTP_CONFLICT) return;
+
+ throw new HfNotWritableError(repoId);
+}
+
+/** Throws unless the ID is `owner/name`: the Hub's URLs and the creation call both read it. */
+function ensureRepoId(repoId: string): void {
+ if (!HF_REPO_ID_REGEX.test(repoId)) throw new Error(HF_MESSAGE.invalidRepoId(repoId));
+}
+
+/**
+ * Reads the account a token belongs to.
+ * @returns Null when the Hub does not accept the token: it is wrong, revoked or expired
+ * @throws When the Hub cannot be asked
+ */
+export async function whoAmI(token: string): Promise<HfUser | null> {
+ const response = await hubFetch(HF_API_WHOAMI_URL, { headers: headers(token) });
+
+ if (response.status === HF_HTTP_UNAUTHORIZED) return null;
+
+ await ensureOk(response, HF_ACTION.ACCOUNT_CHECK);
+
+ const body = await response.json();
+
+ return {
+ fullname: body.fullname,
+ name: body.name,
+ tokenRole: body.auth?.accessToken?.role
+ };
+}
+
+/**
+ * Lists the datasets of an account, most recently changed first; the token brings in the
+ * private ones it may read.
+ */
+export async function listDatasets(token: string, author: string): Promise<HfDataset[]> {
+ const query = new URLSearchParams({
+ ...HF_DATASETS_LIST_QUERY,
+ [HF_DATASETS_AUTHOR_PARAM]: author
+ });
+ const response = await hubFetch(`${HF_API_DATASETS_URL}?${query}`, {
+ headers: headers(token)
+ });
+
+ await ensureOk(response, HF_ACTION.DATASET_LIST);
+
+ const body: unknown = await response.json();
+
+ if (!Array.isArray(body)) return [];
+
+ return body
+ .filter((dataset) => typeof dataset?.id === 'string')
+ .map((dataset) => ({ id: dataset.id, isPrivate: dataset.private === true }));
+}
+
+/** Creates the dataset unless it already exists; an existing one keeps its visibility. */
+export async function ensureDataset(
+ token: string,
+ repoId: string,
+ isPrivate: boolean
+): Promise<void> {
+ ensureRepoId(repoId);
+
+ const existing = await hubFetch(`${HF_API_DATASETS_URL}/${repoId}`, {
+ headers: headers(token)
+ });
+
+ if (existing.ok) return;
+
+ if (existing.status !== HF_HTTP_NOT_FOUND) await ensureOk(existing, HF_ACTION.DATASET_LOOKUP);
+
+ const [organization, name] = splitRepoId(repoId);
+ const response = await hubFetch(HF_API_CREATE_REPO_URL, {
+ body: JSON.stringify({ name, organization, private: isPrivate, type: HF_REPO_TYPE_DATASET }),
+ headers: headers(token, HF_CONTENT_TYPE_JSON),
+ method: HF_HTTP_POST
+ });
+
+ ensureWritable(response, repoId);
+ await ensureOk(response, HF_ACTION.DATASET_CREATION);
+}
+
+/**
+ * Commits one trace file to a dataset, creating the dataset first when needed.
+ * @returns The URL of the file on the Hub
+ */
+export async function uploadTrace(token: string, upload: HfTraceUpload): Promise<string> {
+ const { commitMessage, content, isPrivate, path, repoId } = upload;
+ const bytes = new TextEncoder().encode(content);
+
+ if (bytes.length > HF_REGULAR_FILE_MAX_BYTES) throw new Error(HF_MESSAGE.TRACE_TOO_LARGE);
+
+ await ensureDataset(token, repoId, isPrivate);
+
+ const repoApi = `${HF_API_DATASETS_URL}/${repoId}`;
+ // a dataset whose .gitattributes sends .jsonl to LFS needs an upload this share does not do
+ const preupload = await hubFetch(`${repoApi}/preupload/${HF_MAIN_BRANCH}`, {
+ body: JSON.stringify({
+ files: [
+ {
+ path,
+ sample: bytesToBase64(bytes.subarray(0, HF_PREUPLOAD_SAMPLE_BYTES)),
+ size: bytes.length
+ }
+ ]
+ }),
+ headers: headers(token, HF_CONTENT_TYPE_JSON),
+ method: HF_HTTP_POST
+ });
+
+ ensureWritable(preupload, repoId);
+ await ensureOk(preupload, HF_ACTION.UPLOAD_CHECK);
+
+ const { files } = await preupload.json();
+
+ if (files?.[0]?.uploadMode === HF_UPLOAD_MODE_LFS) {
+ throw new Error(HF_MESSAGE.lfsNotSupported(repoId));
+ }
+
+ const body = [
+ { key: HF_COMMIT_KEY_HEADER, value: { description: '', summary: commitMessage } },
+ {
+ key: HF_COMMIT_KEY_FILE,
+ value: { content: bytesToBase64(bytes), encoding: HF_COMMIT_ENCODING, path }
+ }
+ ]
+ .map((line) => JSON.stringify(line))
+ .join(HF_COMMIT_LINE_SEPARATOR);
+ const commit = await hubFetch(`${repoApi}/commit/${HF_MAIN_BRANCH}`, {
+ body,
+ headers: headers(token, HF_CONTENT_TYPE_NDJSON),
+ method: HF_HTTP_POST
+ });
+
+ ensureWritable(commit, repoId);
+ await ensureOk(commit, HF_ACTION.UPLOAD);
+
+ return `${HF_DATASETS_URL}/${repoId}/blob/${HF_MAIN_BRANCH}/${encodeURIComponent(path)}`;
+}
diff --git a/ui/lib/huggingface/src/index.ts b/ui/lib/huggingface/src/index.ts
new file mode 100644
index 000000000..ad7f4ae49
--- /dev/null
+++ b/ui/lib/huggingface/src/index.ts
@@ -0,0 +1,62 @@
+/**
+ * Llama Hugging Face: a Hugging Face account for an app that runs in the browser, with no
+ * server of its own. Signing in ("Sign in with Hugging Face", or a pasted access token) and
+ * sharing a conversation to a dataset as an agent trace.
+ *
+ * This entry is plain TypeScript: the OAuth flow and the Hub calls. The account as reactive
+ * state and the components that show it are in @ggml-org/llama-huggingface/svelte.
+ * It knows no app: the app says who it is (HfAccountOptions) and hands over what to share.
+ */
+
+export {
+ authorizationUrl,
+ createCodeChallenge,
+ createRandomString,
+ exchangeCode,
+ hasScope,
+ refreshTokens,
+ registerClient
+} from './client.js';
+export {
+ HF_BASE_URL,
+ HF_NEW_TOKEN_URL,
+ HF_OAUTH_CALLBACK_PARAM,
+ HF_PREVIEW_LINES_MAX,
+ HF_PREVIEW_TEXT_MAX,
+ HF_REGULAR_FILE_MAX_BYTES,
+ HF_REPO_ID_REGEX,
+ HF_REPO_ID_SEPARATOR,
+ HF_STORAGE_KEY_DATASET,
+ HF_STORAGE_KEY_OAUTH,
+ HF_STORAGE_KEY_SEPARATOR,
+ HF_STORAGE_KEY_TOKEN,
+ HF_TRACES_DOCS_URL
+} from './constants.js';
+export {
+ HfOAuthErrorCode,
+ HfOAuthFlowMode,
+ HfOAuthGrantType,
+ HfOAuthParam,
+ HfTokenRole
+} from './enums.js';
+export { HfNotWritableError, HfTokenRejectedError } from './errors.js';
+export { ensureDataset, listDatasets, uploadTrace, whoAmI } from './hub.js';
+export { HF_ACTION, HF_MESSAGE } from './messages.js';
+export { HfOAuthSignIn } from './sign-in.js';
+export { errorMessage, splitRepoId } from './util.js';
+export type {
+ HfAccountOptions,
+ HfDataset,
+ HfOAuthCallbackOutcome,
+ HfOAuthClient,
+ HfOAuthPendingFlow,
+ HfOAuthRecord,
+ HfOAuthResult,
+ HfOAuthSignInOptions,
+ HfOAuthTokens,
+ HfShareScope,
+ HfTraceFile,
+ HfTracePreviewLine,
+ HfTraceUpload,
+ HfUser
+} from './types.js';
diff --git a/ui/lib/huggingface/src/messages.ts b/ui/lib/huggingface/src/messages.ts
new file mode 100644
index 000000000..8f195fd06
--- /dev/null
+++ b/ui/lib/huggingface/src/messages.ts
@@ -0,0 +1,48 @@
+/**
+ * What the package says when something goes wrong, and what it calls the calls that can.
+ * Named here, so a wording is changed in one place and a test can read the same text.
+ */
+
+/** What an error names a failed call as: "Dataset list failed (500): ...". */
+export const HF_ACTION = {
+ ACCOUNT_CHECK: 'Sign in',
+ DATASET_CREATION: 'Dataset creation',
+ DATASET_LIST: 'Dataset list',
+ DATASET_LOOKUP: 'Dataset lookup',
+ SIGN_IN: 'The sign-in',
+ SIGN_IN_RENEWAL: 'Renewing the sign-in',
+ UPLOAD: 'Upload',
+ UPLOAD_CHECK: 'Upload check'
+} as const;
+
+export type HfAction = (typeof HF_ACTION)[keyof typeof HF_ACTION];
+
+export const HF_MESSAGE = {
+ ACCESS_TOKEN_MISSING: 'Hugging Face sent no access token back.',
+ APP_NOT_REGISTERED: 'Could not reach Hugging Face to start the sign-in.',
+ CLIENT_ID_MISSING: 'Hugging Face registered the app but sent no client ID back.',
+ CODE_MISSING: 'Hugging Face sent no code back.',
+ REQUEST_TIMED_OUT: 'Hugging Face did not answer in time. Try again.',
+ SCOPE_NOT_GRANTED: 'Hugging Face did not grant the access the app asked for.',
+ SECURE_PAGE_NEEDED: 'Signing in with Hugging Face needs a secure page: https, or localhost.',
+ // not the error's description: it comes from the address bar, anyone could have written it
+ SIGN_IN_CANCELLED: 'The sign-in was cancelled.',
+ SIGN_IN_FAILED_FALLBACK: 'Sign in with an access token instead.',
+ SIGN_IN_REFUSED: 'Hugging Face refused the sign-in.',
+ SIGN_IN_REQUIRED: 'Sign in to Hugging Face first.',
+ TOKEN_REJECTED: 'Hugging Face did not accept this token. Check it and try again.',
+ TRACE_TOO_LARGE:
+ 'This trace is too large to share. Leave attachments out or share fewer messages.',
+ invalidRepoId: (repoId: string) => `${repoId} is not a dataset name of the form owner/name.`,
+ lfsNotSupported: (repoId: string) =>
+ `${repoId} stores .jsonl files with LFS, which sharing does not support yet.`,
+ notWritable: (repoId: string) =>
+ `You cannot add traces to ${repoId}. Signing in with Hugging Face lets the app write only to datasets it created: pick a new dataset name, or sign in with an access token that has write access.`,
+ registrationRefused: (origin: string, detail: string) =>
+ `Hugging Face does not allow signing in from ${origin} (${detail}).`,
+ requestFailed: (action: HfAction, status: number, detail: string) =>
+ `${action} failed (${status}): ${detail}`,
+ status: (status: number) => `HTTP ${status}`,
+ tokenRequestFailed: (action: HfAction, detail: string) => `${action} failed: ${detail}.`,
+ tokenRequestUnreachable: (action: HfAction) => `${action} could not reach Hugging Face.`
+} as const;
diff --git a/ui/lib/huggingface/src/sign-in.ts b/ui/lib/huggingface/src/sign-in.ts
new file mode 100644
index 000000000..573e0c423
--- /dev/null
+++ b/ui/lib/huggingface/src/sign-in.ts
@@ -0,0 +1,276 @@
+/**
+ * A sign-in with Hugging Face, start to finish, in the browser.
+ *
+ * start() sends a popup (or, without one, this tab) to the authorization page. Hugging Face
+ * sends the browser back to the app with a code, and complete(), called on that page load,
+ * trades it for tokens. The popup may not be able to reach the tab that opened it (an app
+ * served with COOP same-origin), so the result goes out on a BroadcastChannel to every tab.
+ * The registered client and the tokens are kept in localStorage.
+ */
+
+import {
+ authorizationUrl,
+ createCodeChallenge,
+ createRandomString,
+ exchangeCode,
+ hasScope,
+ refreshTokens,
+ registerClient
+} from './client.js';
+import {
+ HF_OAUTH_CALLBACK_PARAM,
+ HF_OAUTH_CALLBACK_VALUE,
+ HF_OAUTH_EXPIRY_MARGIN_MS,
+ HF_OAUTH_PENDING_TTL_MS,
+ HF_OAUTH_SCOPE_SEPARATOR
+} from './constants.js';
+import { HfOAuthErrorCode, HfOAuthFlowMode, HfOAuthParam } from './enums.js';
+import { HfTokenRejectedError } from './errors.js';
+import { HF_MESSAGE } from './messages.js';
+import { readJsonStorage, writeJsonStorage } from './storage.js';
+import type {
+ HfOAuthCallbackOutcome,
+ HfOAuthRecord,
+ HfOAuthResult,
+ HfOAuthSignInOptions
+} from './types.js';
+import { errorMessage } from './util.js';
+
+/** The callback's own query parameters, cleared from the address once read. */
+const CALLBACK_PARAMS = [
+ HF_OAUTH_CALLBACK_PARAM,
+ HfOAuthParam.CODE,
+ HfOAuthParam.STATE,
+ HfOAuthParam.ERROR,
+ HfOAuthParam.ERROR_DESCRIPTION
+];
+
+export class HfOAuthSignIn {
+ #channel: BroadcastChannel | null = null;
+ #options: HfOAuthSignInOptions;
+
+ constructor(options: HfOAuthSignInOptions) {
+ this.#options = options;
+
+ if (typeof window === 'undefined' || typeof BroadcastChannel === 'undefined') return;
+
+ this.#channel = new BroadcastChannel(options.storageKey);
+ this.#channel.onmessage = (event: MessageEvent<HfOAuthResult>) =>
+ options.onResult?.(event.data);
+ }
+
+ /** The stored access token, which may have expired: freshToken() renews it. */
+ get accessToken(): string | null {
+ return this.#read()?.tokens?.accessToken ?? null;
+ }
+
+ /** The page Hugging Face sends the browser back to: the app's callback page, with a marker. */
+ get redirectUrl(): string {
+ const url = new URL(this.#options.callbackUrl());
+
+ url.searchParams.set(HF_OAUTH_CALLBACK_PARAM, HF_OAUTH_CALLBACK_VALUE);
+
+ return url.href;
+ }
+
+ /**
+ * Finishes a sign-in when this page load is Hugging Face sending the browser back.
+ * Reads and clears the callback's parameters; returns null for any other page load.
+ */
+ async complete(
+ location: URL = new URL(window.location.href)
+ ): Promise<HfOAuthCallbackOutcome | null> {
+ if (!location.searchParams.has(HF_OAUTH_CALLBACK_PARAM)) return null;
+
+ const params = new URLSearchParams(location.search);
+ const cleaned = new URL(location.href);
+
+ for (const name of CALLBACK_PARAMS) cleaned.searchParams.delete(name);
+
+ // a reload must not run the exchange again
+ window.history.replaceState(window.history.state, '', cleaned.href);
+
+ const record = this.#read();
+ const pending = record?.pending;
+ const state = params.get(HfOAuthParam.STATE);
+
+ if (
+ !record ||
+ !pending ||
+ pending.state !== state ||
+ Date.now() - pending.startedAt > HF_OAUTH_PENDING_TTL_MS
+ ) {
+ return { closeWindow: false, result: null };
+ }
+
+ this.#write({ ...record, pending: undefined });
+
+ const result = await this.#exchange(record, params, pending.codeVerifier);
+ const closeWindow = pending.mode === HfOAuthFlowMode.POPUP;
+
+ this.#options.onResult?.(result);
+ // a channel does not hear its own messages: the other tabs do
+ this.#channel?.postMessage(result);
+
+ // a sign-in that took over this tab goes back to where it started
+ if (!closeWindow && pending.returnUrl !== cleaned.href) {
+ window.location.replace(pending.returnUrl);
+ }
+
+ return { closeWindow, result };
+ }
+
+ /**
+ * The access token to call the Hub with, renewed when it is about to expire.
+ * @returns Null when no one is signed in or the sign-in cannot be renewed
+ * @throws When renewing fails
+ */
+ async freshToken(): Promise<string | null> {
+ const record = this.#read();
+ const tokens = record?.tokens;
+
+ if (!record || !tokens) return null;
+
+ if (!tokens.expiresAt || Date.now() < tokens.expiresAt - HF_OAUTH_EXPIRY_MARGIN_MS) {
+ return tokens.accessToken;
+ }
+
+ if (!tokens.refreshToken) return null;
+
+ try {
+ const renewed = await refreshTokens(record.clientId, tokens.refreshToken);
+
+ this.#write({ ...record, tokens: renewed });
+
+ return renewed.accessToken;
+ } catch (error) {
+ // another tab may have renewed first, which can spend the refresh token
+ const current = this.#read()?.tokens;
+
+ if (current && current.accessToken !== tokens.accessToken) return current.accessToken;
+
+ // a refresh token Hugging Face turned down is no use any more: this is not a sign-in
+ // that an unreachable Hub only keeps from renewing
+ if (error instanceof HfTokenRejectedError) {
+ this.signOut();
+
+ return null;
+ }
+
+ throw error;
+ }
+ }
+
+ /** Forgets the tokens. The client registration stays: the next sign-in reuses it. */
+ signOut(): void {
+ const record = this.#read();
+
+ if (record?.tokens) this.#write({ ...record, tokens: undefined });
+ }
+
+ /**
+ * Starts a sign-in. Call it from the click that asks for it, with the popup opened in that
+ * same click (browsers block a popup opened later); without one, this tab goes to the
+ * authorization page.
+ * @throws When Hugging Face will not register the app; the popup is closed
+ */
+ async start(popup: Window | null): Promise<void> {
+ const { clientName, logoUrl, scopes } = this.#options;
+ const redirectUrl = this.redirectUrl;
+ const scope = scopes.join(HF_OAUTH_SCOPE_SEPARATOR);
+ const record = this.#read();
+ // a client is registered with its redirect URL, scopes and logo: a change registers again
+ const known =
+ record?.redirectUrl === redirectUrl && record.scope === scope && record.logoUrl === logoUrl
+ ? record
+ : null;
+
+ try {
+ const codeVerifier = createRandomString();
+ // first, so a page that cannot sign in registers nothing
+ const codeChallenge = await createCodeChallenge(codeVerifier);
+ const clientId =
+ known?.clientId ?? (await registerClient({ clientName, logoUrl, redirectUrl, scopes }));
+ const state = createRandomString();
+
+ this.#write({
+ clientId,
+ pending: {
+ codeVerifier,
+ mode: popup ? HfOAuthFlowMode.POPUP : HfOAuthFlowMode.REDIRECT,
+ returnUrl: window.location.href,
+ startedAt: Date.now(),
+ state
+ },
+ logoUrl,
+ redirectUrl,
+ scope,
+ tokens: known?.tokens
+ });
+
+ const { href } = authorizationUrl({
+ clientId,
+ codeChallenge,
+ redirectUrl,
+ scopes,
+ state
+ });
+
+ if (popup) popup.location.href = href;
+ else window.location.assign(href);
+ } catch (error) {
+ popup?.close();
+
+ throw error;
+ }
+ }
+
+ async #exchange(
+ record: HfOAuthRecord,
+ params: URLSearchParams,
+ codeVerifier: string
+ ): Promise<HfOAuthResult> {
+ const failure = params.get(HfOAuthParam.ERROR);
+ const code = params.get(HfOAuthParam.CODE);
+ const { requiredScope } = this.#options;
+
+ if (failure === HfOAuthErrorCode.ACCESS_DENIED) {
+ return { error: HF_MESSAGE.SIGN_IN_CANCELLED, ok: false };
+ }
+
+ if (failure) return { error: HF_MESSAGE.SIGN_IN_REFUSED, ok: false };
+
+ if (!code) return { error: HF_MESSAGE.CODE_MISSING, ok: false };
+
+ try {
+ const { clientId, redirectUrl } = record;
+ const tokens = await exchangeCode({
+ clientId,
+ code,
+ codeVerifier,
+ redirectUrl
+ });
+
+ if (requiredScope && !hasScope(tokens, requiredScope)) {
+ return { error: HF_MESSAGE.SCOPE_NOT_GRANTED, ok: false };
+ }
+
+ this.#write({ ...record, pending: undefined, tokens });
+
+ return { ok: true };
+ } catch (error) {
+ return { error: errorMessage(error), ok: false };
+ }
+ }
+
+ #read(): HfOAuthRecord | null {
+ const parsed = readJsonStorage(this.#options.storageKey);
+
+ return parsed && typeof parsed === 'object' ? (parsed as HfOAuthRecord) : null;
+ }
+
+ /** A sign-in that cannot be kept (no storage) lasts until the page is closed. */
+ #write(record: HfOAuthRecord): void {
+ writeJsonStorage(this.#options.storageKey, record);
+ }
+}
diff --git a/ui/lib/huggingface/src/storage.ts b/ui/lib/huggingface/src/storage.ts
new file mode 100644
index 000000000..51c0a9473
--- /dev/null
+++ b/ui/lib/huggingface/src/storage.ts
@@ -0,0 +1,36 @@
+/**
+ * What the package keeps in localStorage. Every access is allowed to fail, for there may be no
+ * storage (outside a browser, or blocked), and the value then lives for this session only.
+ */
+
+export function readStorage(key: string): string | null {
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ // no storage, e.g. outside a browser
+ return null;
+ }
+}
+
+export function writeStorage(key: string, value: string | null): void {
+ try {
+ if (value === null) localStorage.removeItem(key);
+ else localStorage.setItem(key, value);
+ } catch {
+ // storage full or blocked
+ }
+}
+
+/** The JSON a key holds, or `null` when there is none or it is not JSON. */
+export function readJsonStorage(key: string): unknown {
+ try {
+ return JSON.parse(readStorage(key) ?? 'null');
+ } catch {
+ // not what the package wrote
+ return null;
+ }
+}
+
+export function writeJsonStorage(key: string, value: unknown): void {
+ writeStorage(key, JSON.stringify(value));
+}
diff --git a/ui/lib/huggingface/src/svelte/HfAccountPanel.svelte b/ui/lib/huggingface/src/svelte/HfAccountPanel.svelte
new file mode 100644
index 000000000..cc2164ce7
--- /dev/null
+++ b/ui/lib/huggingface/src/svelte/HfAccountPanel.svelte
@@ -0,0 +1,150 @@
+<script lang="ts">
+ import type { HfAccount } from './account.svelte.js';
+ import HfLogo from './HfLogo.svelte';
+ import {
+ HF_NEW_TOKEN_URL,
+ HF_OAUTH_POPUP_BLANK_URL,
+ HF_OAUTH_POPUP_FEATURES,
+ HF_OAUTH_POPUP_NAME
+ } from '../constants.js';
+ import { errorMessage } from '../util.js';
+ import { ModelOrgAvatar } from '@ggml-org/llama-ui/models';
+ import { Button } from '@ggml-org/llama-ui/ui/button';
+ import { Input } from '@ggml-org/llama-ui/ui/input';
+ import { Label } from '@ggml-org/llama-ui/ui/label';
+ import { Loader2 } from '@lucide/svelte';
+
+ interface Props {
+ account: HfAccount;
+ /** Locks the account while something uses it, e.g. a share on its way. */
+ disabled?: boolean;
+ }
+
+ let { account, disabled = false }: Props = $props();
+
+ let token = $state('');
+ let tokenError = $state<string | null>(null);
+
+ let user = $derived(account.user);
+ let isSigningInWithHf = $derived(account.isSigningInWithHf);
+ let isBusy = $derived(disabled || account.isCheckingToken || isSigningInWithHf);
+
+ function handleSignInWithHf() {
+ tokenError = null;
+
+ // opened in the click itself: a popup opened after an await is blocked
+ const popup = window.open(
+ HF_OAUTH_POPUP_BLANK_URL,
+ HF_OAUTH_POPUP_NAME,
+ HF_OAUTH_POPUP_FEATURES
+ );
+
+ void account.signInWithHuggingFace(popup);
+ }
+
+ async function handleSignInWithToken(event: SubmitEvent) {
+ event.preventDefault();
+
+ if (!token.trim()) return;
+
+ tokenError = null;
+
+ try {
+ await account.signIn(token);
+
+ token = '';
+ } catch (error) {
+ tokenError = errorMessage(error);
+ }
+ }
+</script>
+
+{#if user}
+ <div class="flex flex-col gap-2">
+ <div class="flex items-center gap-2 text-body-sm">
+ <ModelOrgAvatar org={user.name} size="size-6" />
+
+ <span class="min-w-0 flex-1 truncate">
+ Signed in as <span class="font-medium">{user.name}</span>
+ </span>
+
+ <Button {disabled} onclick={() => account.signOut()} size="sm" variant="ghost">
+ Sign out
+ </Button>
+ </div>
+
+ {#if account.isReadOnly}
+ <p class="text-caption text-destructive">
+ This token can only read. <a
+ class="underline"
+ href={HF_NEW_TOKEN_URL}
+ rel="noopener noreferrer"
+ target="_blank">Create one with write access</a
+ >, then sign out and in again.
+ </p>
+ {/if}
+ </div>
+{:else}
+ <form class="flex flex-col gap-4" onsubmit={handleSignInWithToken}>
+ <div class="flex flex-col gap-2">
+ <Button disabled={isBusy} onclick={handleSignInWithHf} type="button" variant="outline">
+ {#if isSigningInWithHf}
+ <Loader2 class="h-4 w-4 animate-spin" />
+ {:else}
+ <HfLogo />
+ {/if}
+ Sign in with Hugging Face
+ </Button>
+
+ {#if isSigningInWithHf}
+ <p class="text-caption text-muted-foreground">
+ Finish signing in on the Hugging Face page.
+ <button class="underline" onclick={() => account.cancelSignInWithHf()} type="button">
+ Cancel
+ </button>
+ </p>
+ {:else if account.oauthError}
+ <p class="text-caption text-destructive">{account.oauthError}</p>
+ {/if}
+ </div>
+
+ <div class="flex items-center gap-3 text-caption text-muted-foreground">
+ <span class="h-px flex-1 bg-border"></span>
+ or use an access token
+ <span class="h-px flex-1 bg-border"></span>
+ </div>
+
+ <div class="flex flex-col gap-2">
+ <Label for="hf-token">Hugging Face access token</Label>
+
+ <div class="flex gap-2">
+ <Input
+ bind:value={token}
+ autocomplete="off"
+ class="flex-1"
+ disabled={isBusy}
+ id="hf-token"
+ placeholder="hf_..."
+ type="password"
+ />
+
+ <Button disabled={!token.trim() || isBusy} type="submit">
+ {#if account.isCheckingToken}
+ <Loader2 class="h-4 w-4 animate-spin" />
+ {/if}
+ Sign in
+ </Button>
+ </div>
+
+ <p class="text-caption text-muted-foreground">
+ <a class="underline" href={HF_NEW_TOKEN_URL} rel="noopener noreferrer" target="_blank">
+ Create a token with write access
+ </a>. It stays in this browser and goes to huggingface.co.
+ </p>
+
+ {#if tokenError}
+ <p class="text-caption text-destructive">{tokenError}</p>
+ {/if}
+ </div>
+ </form>
+{/if}
diff --git a/ui/lib/huggingface/src/svelte/HfChoiceTile.svelte b/ui/lib/huggingface/src/svelte/HfChoiceTile.svelte
new file mode 100644
index 000000000..20ced96d8
--- /dev/null
+++ b/ui/lib/huggingface/src/svelte/HfChoiceTile.svelte
@@ -0,0 +1,50 @@
+<script lang="ts">
+ import { Check } from '@lucide/svelte';
+ import type { Component, Snippet } from 'svelte';
+
+ interface Props {
+ /** The line under the name. */
+ children: Snippet;
+ /** Before the name; the picked tile shows a check in its place. */
+ icon: Component<{ class?: string }>;
+ isPicked: boolean;
+ label: string;
+ disabled?: boolean;
+ onpick: () => void;
+ /** The whole name, for a tile that has to cut it short. */
+ title?: string;
+ }
+
+ let { children, disabled = false, icon: Icon, isPicked, label, onpick, title }: Props = $props();
+</script>
+
+<!-- one of a few choices, shown as tiles: the picked one takes the row surface and a check -->
+<button
+ aria-pressed={isPicked}
+ class={[
+ 'relative flex min-w-0 cursor-pointer flex-col items-start gap-1 rounded-xl border px-3 py-2.5 text-left outline-none',
+ 'transition-colors duration-200 ease-out-quint focus-visible:ring-3 focus-visible:ring-ring/50',
+ 'disabled:pointer-events-none disabled:opacity-50',
+ isPicked
+ ? 'selected-row-surface border-transparent'
+ : 'matte-key border-(--line-control) bg-(--field-background) hover:bg-(--action-ghost-hover)'
+ ]}
+ {disabled}
+ onclick={onpick}
+ {title}
+ type="button"
+>
+ <span class="flex w-full min-w-0 items-center gap-1.5 text-label">
+ {#if isPicked}
+ <Check class="size-icon-sm shrink-0 text-(--action-primary)" />
+ {:else}
+ <Icon class="size-icon-sm shrink-0 text-muted-foreground" />
+ {/if}
+
+ <span class="truncate">{label}</span>
+ </span>
+
+ <span class="flex w-full min-w-0 items-center gap-1 text-caption text-muted-foreground">
+ {@render children()}
+ </span>
+</button>
diff --git a/ui/lib/huggingface/src/svelte/HfLogo.svelte b/ui/lib/huggingface/src/svelte/HfLogo.svelte
new file mode 100644
index 000000000..eb747173e
--- /dev/null
+++ b/ui/lib/huggingface/src/svelte/HfLogo.svelte
@@ -0,0 +1,11 @@
+<script lang="ts">
+ import hfLogo from './assets/hf-logo.svg?url';
+
+ interface Props {
+ class?: string;
+ }
+
+ let { class: className = 'size-4' }: Props = $props();
+</script>
+
+<img alt="" class={className} src={hfLogo} />
diff --git a/ui/lib/huggingface/src/svelte/HfShareDialog.svelte b/ui/lib/huggingface/src/svelte/HfShareDialog.svelte
new file mode 100644
index 000000000..f1ef9d77e
--- /dev/null
+++ b/ui/lib/huggingface/src/svelte/HfShareDialog.svelte
@@ -0,0 +1,407 @@
+<script lang="ts">
+ import type { HfAccount } from './account.svelte.js';
+ import HfAccountPanel from './HfAccountPanel.svelte';
+ import HfChoiceTile from './HfChoiceTile.svelte';
+ import HfTracePreview from './HfTracePreview.svelte';
+ import {
+ HF_DATASET_TILES_SHOWN,
+ HF_NEW_DATASET_VALUE,
+ HF_REPO_ID_REGEX,
+ HF_REPO_ID_SEPARATOR,
+ HF_TRACES_DOCS_URL
+ } from '../constants.js';
+ import type { HfShareScope, HfTraceFile, HfTracePreviewLine } from '../types.js';
+ import { errorMessage, splitRepoId } from '../util.js';
+ import * as AlertDialog from '@ggml-org/llama-ui/ui/alert-dialog';
+ import { Button } from '@ggml-org/llama-ui/ui/button';
+ import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox';
+ import { Input } from '@ggml-org/llama-ui/ui/input';
+ import { Label } from '@ggml-org/llama-ui/ui/label';
+ import * as RadioGroup from '@ggml-org/llama-ui/ui/radio-group';
+ import { Skeleton } from '@ggml-org/llama-ui/ui/skeleton';
+ import {
+ CircleCheck,
+ Copy,
+ Database,
+ ExternalLink,
+ Globe,
+ Loader2,
+ Lock,
+ Plus,
+ Share,
+ TriangleAlert
+ } from '@lucide/svelte';
+ import { tick, untrack } from 'svelte';
+
+ interface Props {
+ account: HfAccount;
+ open: boolean;
+ /** What is shared, as the description names it, e.g. `"My chat"` or `this conversation`. */
+ subject: string;
+ /** The parts that can be shared; the choice shows when there is more than one. */
+ scopes: HfShareScope[];
+ /** The scope picked when the dialog opens; the first one otherwise. */
+ initialScope?: string;
+ /** Builds the trace of a scope, with or without its attachments. */
+ buildTrace: (scope: string, includeAttachments: boolean) => Promise<HfTraceFile>;
+ onShared?: (url: string) => void;
+ onCopyLink: (url: string) => void;
+ }
+
+ let {
+ account,
+ buildTrace,
+ initialScope,
+ onCopyLink,
+ onShared,
+ open = $bindable(),
+ scopes,
+ subject
+ }: Props = $props();
+
+ const DATASET_LABEL_ID = 'hf-dataset-label';
+
+ let scopeId = $state('');
+ /** A listed dataset's ID, or HF_NEW_DATASET_VALUE to name a new one. */
+ let datasetChoice = $state('');
+ let newDataset = $state('');
+ let newDatasetInput = $state<HTMLInputElement | null>(null);
+ let isShowingAllDatasets = $state(false);
+ let isPrivate = $state(false);
+ let includeAttachments = $state(false);
+ let isSharing = $state(false);
+ let shareError = $state<string | null>(null);
+ let sharedUrl = $state<string | null>(null);
+ /** The file a finished share added, and the messages its preview shows. */
+ let sharedFile = $state<{ path: string; preview?: HfTracePreviewLine[] } | null>(null);
+
+ // a fresh form every time the dialog opens
+ $effect.pre(() => {
+ if (!open) return;
+
+ untrack(() => {
+ scopeId = initialScope ?? scopes[0]?.id ?? '';
+ datasetChoice = '';
+ newDataset = '';
+ isShowingAllDatasets = false;
+ isPrivate = false;
+ includeAttachments = false;
+ shareError = null;
+ sharedUrl = null;
+ sharedFile = null;
+
+ if (!account.isSigningInWithHf) account.oauthError = null;
+
+ // the list is fetched again on every open, so datasets made elsewhere show up
+ void account.restoreSession().then(() => account.loadDatasets());
+ });
+ });
+
+ let scope = $derived(scopes.find((entry) => entry.id === scopeId) ?? scopes[0]);
+
+ let user = $derived(account.user);
+ let datasets = $derived(account.datasets);
+ // the datasets this account can add to, shown as tiles; the rest of its datasets stay out of it
+ let writableDatasets = $derived(account.writableDatasets);
+ let tiles = $derived(
+ isShowingAllDatasets ? writableDatasets : writableDatasets.slice(0, HF_DATASET_TILES_SHOWN)
+ );
+ let isListingDatasets = $derived(!account.hasListedDatasets || account.isLoadingDatasets);
+ let isNewDataset = $derived(datasetChoice === HF_NEW_DATASET_VALUE);
+ let dataset = $derived(isNewDataset ? newDataset.trim() : datasetChoice);
+ let pickedDataset = $derived(datasets.find((entry) => entry.id === datasetChoice));
+
+ // a pick that is no longer one the account can add to: another account signed in, or the Hub
+ // turned its dataset down, which makes the account forget it
+ let isPickStale = $derived(
+ !!datasetChoice &&
+ datasetChoice !== HF_NEW_DATASET_VALUE &&
+ !writableDatasets.some((entry) => entry.id === datasetChoice)
+ );
+
+ // once the account's datasets are in, pick the one traces went to last, else the first one it
+ // can add to, else offer a new one, and again when the pick goes stale; this also covers a
+ // sign-in that finished elsewhere (a popup, another tab)
+ $effect(() => {
+ if (!open || !user || isListingDatasets || (datasetChoice && !isPickStale)) return;
+
+ untrack(() => {
+ datasetChoice = writableDatasets[0]?.id ?? HF_NEW_DATASET_VALUE;
+ newDataset = account.newDatasetStart;
+ });
+ });
+
+ let isDatasetValid = $derived(HF_REPO_ID_REGEX.test(dataset));
+ // the owner alone, as the field starts, is not a mistake yet
+ let isDatasetNameStarted = $derived(!!dataset && !dataset.endsWith(HF_REPO_ID_SEPARATOR));
+ let canShare = $derived(
+ !!user && !account.isReadOnly && isDatasetValid && !!scope && !scope.isEmpty && !isSharing
+ );
+
+ async function handlePickNew() {
+ datasetChoice = HF_NEW_DATASET_VALUE;
+
+ await tick();
+ newDatasetInput?.focus();
+ }
+
+ function handleOpenChange(isOpen: boolean) {
+ // a share on its way keeps the dialog
+ if (!isOpen && !isSharing) open = false;
+ }
+
+ async function handleShare(event: SubmitEvent) {
+ event.preventDefault();
+
+ if (!canShare || !scope) return;
+
+ isSharing = true;
+ shareError = null;
+
+ try {
+ // the preview is for this dialog: only the file goes to the Hub
+ const { preview, ...file } = await buildTrace(
+ scope.id,
+ !!scope.hasAttachments && includeAttachments
+ );
+
+ const url = await account.uploadTrace({
+ ...file,
+ isPrivate: isNewDataset ? isPrivate : !!pickedDataset?.isPrivate,
+ repoId: dataset
+ });
+
+ sharedFile = { path: file.path, preview };
+ sharedUrl = url;
+ onShared?.(url);
+ } catch (error) {
+ shareError = errorMessage(error);
+ } finally {
+ isSharing = false;
+ }
+ }
+</script>
+
+<AlertDialog.Root onOpenChange={handleOpenChange} {open}>
+ <AlertDialog.Content class="sm:max-w-lg">
+ <AlertDialog.Header>
+ {#if sharedUrl}
+ <AlertDialog.Title class="flex items-center gap-2">
+ <CircleCheck class="size-5 text-fg-success" />
+
+ Shared to Hugging Face
+ </AlertDialog.Title>
+
+ <AlertDialog.Description>
+ Added to <span class="font-medium text-foreground">{dataset}</span> as an agent trace, which
+ the Hub shows in its trace viewer.
+ </AlertDialog.Description>
+ {:else}
+ <AlertDialog.Title class="flex items-center gap-2">
+ <Share class="h-5 w-5" />
+
+ Share to Hugging Face
+ </AlertDialog.Title>
+
+ <AlertDialog.Description>
+ Upload {subject} to a Hugging Face dataset as an
+ <a class="underline" href={HF_TRACES_DOCS_URL} rel="noopener noreferrer" target="_blank">
+ agent trace
+ </a>, which the Hub shows in its trace viewer.
+ </AlertDialog.Description>
+ {/if}
+ </AlertDialog.Header>
+
+ {#if sharedUrl}
+ {@const url = sharedUrl}
+
+ {#if sharedFile}
+ <HfTracePreview lines={sharedFile.preview} path={sharedFile.path} />
+ {/if}
+
+ <!-- every action in one place, at the bottom right: the main one last -->
+ <AlertDialog.Footer class="max-sm:flex-col-reverse">
+ <Button onclick={() => (open = false)} variant="ghost">Done</Button>
+
+ <Button onclick={() => onCopyLink(url)} variant="outline">
+ <Copy />
+ Copy link
+ </Button>
+
+ <Button href={url} rel="noopener noreferrer" target="_blank">
+ <ExternalLink />
+ Open on Hugging Face
+ </Button>
+ </AlertDialog.Footer>
+ {:else if !user}
+ <HfAccountPanel {account} />
+
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel type="button">Cancel</AlertDialog.Cancel>
+ </AlertDialog.Footer>
+ {:else}
+ <form class="contents" onsubmit={handleShare}>
+ <div class="flex flex-col gap-4">
+ <HfAccountPanel {account} disabled={isSharing} />
+
+ {#if scopes.length > 1}
+ <RadioGroup.Root
+ class="gap-2"
+ onValueChange={(value) => (scopeId = value)}
+ value={scopeId}
+ >
+ {#each scopes as entry (entry.id)}
+ <div class="flex items-center gap-2">
+ <RadioGroup.Item id="hf-share-scope-{entry.id}" value={entry.id} />
+
+ <Label
+ class="cursor-pointer text-body-sm font-normal"
+ for="hf-share-scope-{entry.id}"
+ >
+ {entry.label}
+ {#if entry.detail}<span class="text-muted-foreground">({entry.detail})</span
+ >{/if}
+ </Label>
+ </div>
+ {/each}
+ </RadioGroup.Root>
+ {/if}
+
+ <div class="flex flex-col gap-2">
+ <Label id={DATASET_LABEL_ID}>
+ {!isListingDatasets && !writableDatasets.length ? 'Create a dataset' : 'Dataset'}
+ </Label>
+
+ {#if isListingDatasets}
+ <div class="grid grid-cols-2 gap-2">
+ <Skeleton class="h-14 rounded-xl" />
+
+ <Skeleton class="h-14 rounded-xl" />
+ </div>
+ {:else if writableDatasets.length}
+ <!-- the datasets it can add to, and a tile to make a new one -->
+ <div
+ class={[
+ 'grid grid-cols-2 gap-2',
+ isShowingAllDatasets && 'max-h-56 overflow-y-auto'
+ ]}
+ aria-labelledby={DATASET_LABEL_ID}
+ role="group"
+ >
+ {#each tiles as entry (entry.id)}
+ <HfChoiceTile
+ disabled={isSharing}
+ icon={Database}
+ isPicked={datasetChoice === entry.id}
+ label={splitRepoId(entry.id)[1]}
+ onpick={() => (datasetChoice = entry.id)}
+ title={entry.id}
+ >
+ {#if entry.isPrivate}
+ <Lock class="size-icon-sm shrink-0" />
+ Private
+ {:else}
+ <Globe class="size-icon-sm shrink-0" />
+ Public
+ {/if}
+ </HfChoiceTile>
+ {/each}
+
+ <HfChoiceTile
+ disabled={isSharing}
+ icon={Plus}
+ isPicked={isNewDataset}
+ label="New dataset"
+ onpick={handlePickNew}
+ >
+ <span class="truncate">A fresh one</span>
+ </HfChoiceTile>
+ </div>
+
+ {#if writableDatasets.length > tiles.length}
+ <button
+ class="self-start text-caption text-muted-foreground underline"
+ onclick={() => (isShowingAllDatasets = true)}
+ type="button"
+ >
+ Show {writableDatasets.length - tiles.length} more
+ </button>
+ {/if}
+ {/if}
+
+ {#if isNewDataset}
+ <Input
+ bind:ref={newDatasetInput}
+ bind:value={newDataset}
+ aria-label="New dataset name"
+ autocomplete="off"
+ disabled={isSharing}
+ id="hf-dataset"
+ placeholder={account.newDatasetStart}
+ />
+ {/if}
+
+ <p class="text-caption text-muted-foreground">
+ {#if isNewDataset && isDatasetNameStarted && !isDatasetValid}
+ <span class="text-destructive">Use the form owner/name.</span>
+ {:else if isNewDataset && datasets.some((entry) => entry.id === dataset)}
+ {dataset} already exists: the trace goes to it.
+ {:else if isNewDataset}
+ Created on Hugging Face when you share. Each share adds one file to it.
+ {:else if !isListingDatasets}
+ Each share adds one file to it.
+ {/if}
+ </p>
+ </div>
+
+ <div class="flex flex-col gap-3">
+ {#if isNewDataset}
+ <div class="flex items-center gap-2">
+ <Checkbox bind:checked={isPrivate} disabled={isSharing} id="hf-private" />
+
+ <Label class="cursor-pointer text-body-sm font-normal" for="hf-private">
+ Make the new dataset private
+ </Label>
+ </div>
+ {/if}
+
+ {#if scope?.hasAttachments}
+ <div class="flex items-center gap-2">
+ <Checkbox
+ bind:checked={includeAttachments}
+ disabled={isSharing}
+ id="hf-attachments"
+ />
+
+ <Label class="cursor-pointer text-body-sm font-normal" for="hf-attachments">
+ Include attachments
+ </Label>
+ </div>
+ {/if}
+ </div>
+
+ <p class="flex gap-2 text-caption text-muted-foreground">
+ <TriangleAlert class="h-4 w-4 shrink-0" />
+ Traces can hold personal data, file paths, tool output and secrets. Review the conversation
+ before you share it to a public dataset.
+ </p>
+
+ {#if shareError}
+ <p class="text-caption text-destructive">{shareError}</p>
+ {/if}
+ </div>
+
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel disabled={isSharing} type="button">Cancel</AlertDialog.Cancel>
+
+ <Button disabled={!canShare} type="submit">
+ {#if isSharing}
+ <Loader2 class="h-4 w-4 animate-spin" />
+ {/if}
+ Share
+ </Button>
+ </AlertDialog.Footer>
+ </form>
+ {/if}
+ </AlertDialog.Content>
+</AlertDialog.Root>
diff --git a/ui/lib/huggingface/src/svelte/HfTracePreview.svelte b/ui/lib/huggingface/src/svelte/HfTracePreview.svelte
new file mode 100644
index 000000000..bfc1a7bc1
--- /dev/null
+++ b/ui/lib/huggingface/src/svelte/HfTracePreview.svelte
@@ -0,0 +1,45 @@
+<script lang="ts">
+ import { HF_PREVIEW_LINES_MAX, HF_PREVIEW_TEXT_MAX } from '../constants.js';
+ import type { HfTracePreviewLine } from '../types.js';
+ import { FileText } from '@lucide/svelte';
+
+ interface Props {
+ /** The trace file, as it is named on the Hub. */
+ path: string;
+ /** The first messages of the conversation; the file alone shows without them. */
+ lines?: HfTracePreviewLine[];
+ }
+
+ let { lines = [], path }: Props = $props();
+
+ // the first messages only, as much of each as a row can show
+ let shown = $derived(lines.slice(0, HF_PREVIEW_LINES_MAX));
+
+ const ROLE_LABELS = { assistant: 'Assistant', user: 'You' } as const;
+</script>
+
+<!-- the trace as a file, with its first messages fading out below, as if the rest went on -->
+<div
+ class="inset-group-surface overflow-hidden motion-safe:animate-in motion-safe:duration-500 motion-safe:ease-out-quint motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-2"
+ data-slot="hf-trace-preview"
+>
+ <div class="flex items-center gap-2 border-b border-(--line-default) px-3 py-2">
+ <FileText class="size-icon-md shrink-0 text-muted-foreground" />
+
+ <span class="truncate font-mono text-caption text-muted-foreground">{path}</span>
+ </div>
+
+ {#if shown.length}
+ <ul class="flex max-h-36 flex-col gap-2.5 overflow-hidden px-3 pt-3 mask-b-from-35%">
+ {#each shown as line, index (index)}
+ <li class="grid grid-cols-[4.5rem_1fr] items-baseline gap-2">
+ <span class="text-caption font-medium text-muted-foreground"
+ >{ROLE_LABELS[line.role]}</span
+ >
+
+ <span class="line-clamp-2 text-body-sm">{line.text.slice(0, HF_PREVIEW_TEXT_MAX)}</span>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+</div>
diff --git a/ui/lib/huggingface/src/svelte/account.svelte.ts b/ui/lib/huggingface/src/svelte/account.svelte.ts
new file mode 100644
index 000000000..1efe45fb2
--- /dev/null
+++ b/ui/lib/huggingface/src/svelte/account.svelte.ts
@@ -0,0 +1,334 @@
+/**
+ * HfAccount - the Hugging Face account an app is signed in with, as reactive state
+ *
+ * Holds who is signed in, their datasets and the dataset traces went to last. The token is
+ * either one the user pasted or one "Sign in with Hugging Face" got; the components read the
+ * same state either way. An app makes one HfAccount and passes it to them.
+ */
+
+import {
+ HF_REPO_ID_SEPARATOR,
+ HF_SHARED_DATASETS_MAX,
+ HF_STORAGE_KEY_DATASET,
+ HF_STORAGE_KEY_OAUTH,
+ HF_STORAGE_KEY_SEPARATOR,
+ HF_STORAGE_KEY_SHARED_DATASETS,
+ HF_STORAGE_KEY_TOKEN
+} from '../constants.js';
+import { HfTokenRole } from '../enums.js';
+import { HfNotWritableError } from '../errors.js';
+import { listDatasets, uploadTrace, whoAmI } from '../hub.js';
+import { HF_MESSAGE } from '../messages.js';
+import { HfOAuthSignIn } from '../sign-in.js';
+import { readJsonStorage, readStorage, writeJsonStorage, writeStorage } from '../storage.js';
+import type {
+ HfAccountOptions,
+ HfDataset,
+ HfOAuthCallbackOutcome,
+ HfOAuthResult,
+ HfTraceUpload,
+ HfUser
+} from '../types.js';
+import { errorMessage } from '../util.js';
+
+/** The datasets each account shared to from this browser, as stored: account name to repo IDs. */
+function readSharedDatasets(key: string): Record<string, string[]> {
+ const parsed = readJsonStorage(key);
+
+ if (!parsed || typeof parsed !== 'object') return {};
+
+ return Object.fromEntries(
+ Object.entries(parsed).filter(
+ (entry): entry is [string, string[]] =>
+ Array.isArray(entry[1]) && entry[1].every((id) => typeof id === 'string')
+ )
+ );
+}
+
+export class HfAccount {
+ /** Datasets of the account a share can go to, most recently changed first. */
+ datasets = $state<HfDataset[]>([]);
+
+ /** Set once the datasets were listed for the account that is signed in, so a share can suggest one of them. */
+ hasListedDatasets = $state(false);
+
+ /** Set while the token is being checked against the Hub. */
+ isCheckingToken = $state(false);
+
+ /** Set while the account's datasets are being listed. */
+ isLoadingDatasets = $state(false);
+
+ /** Set while a sign-in with Hugging Face waits for the authorization page. */
+ isSigningInWithHf = $state(false);
+
+ /** Dataset the last share went to, `owner/name`. */
+ lastDataset = $state<string | null>(null);
+
+ /** Why the last sign-in with Hugging Face failed. */
+ oauthError = $state<string | null>(null);
+
+ /** The account the token belongs to, once checked. */
+ user = $state<HfUser | null>(null);
+
+ #datasetKey: string;
+ #defaultDatasetName: string;
+ #oauth: HfOAuthSignIn;
+ /** The pasted access token; a sign-in with Hugging Face keeps its own. */
+ #pastedToken = $state<string | null>(null);
+ /** The datasets each account shared to from this browser, the most recent first. */
+ #shared = $state<Record<string, string[]>>({});
+ #sharedKey: string;
+ #tokenKey: string;
+
+ constructor(options: HfAccountOptions) {
+ const { defaultDatasetName, storagePrefix, ...signIn } = options;
+ const key = (name: string) => [storagePrefix, name].join(HF_STORAGE_KEY_SEPARATOR);
+
+ this.#datasetKey = key(HF_STORAGE_KEY_DATASET);
+ this.#tokenKey = key(HF_STORAGE_KEY_TOKEN);
+ this.#sharedKey = key(HF_STORAGE_KEY_SHARED_DATASETS);
+ this.#defaultDatasetName = defaultDatasetName;
+ this.#shared = readSharedDatasets(this.#sharedKey);
+ this.#pastedToken = readStorage(this.#tokenKey);
+ this.lastDataset = readStorage(this.#datasetKey);
+ this.#oauth = new HfOAuthSignIn({
+ ...signIn,
+ onResult: (result) => this.#settle(result),
+ storageKey: key(HF_STORAGE_KEY_OAUTH)
+ });
+ }
+
+ /** A read-only access token signs in, but cannot share. */
+ get isReadOnly(): boolean {
+ return this.user?.tokenRole === HfTokenRole.READ;
+ }
+
+ /**
+ * What the name of a new dataset starts with: the usual one under the account's name, or only
+ * the account's name when a dataset of that name exists, so the name is left to be typed.
+ */
+ get newDatasetStart(): string {
+ if (!this.user) return '';
+
+ const owner = `${this.user.name}${HF_REPO_ID_SEPARATOR}`;
+ const usual = `${owner}${this.#defaultDatasetName}`;
+
+ return this.datasets.some((dataset) => dataset.id === usual) ? owner : usual;
+ }
+
+ /** Dataset a new share suggests: the last one, else one under the account's name. */
+ get suggestedDataset(): string {
+ if (this.lastDataset) return this.lastDataset;
+
+ return this.user ? [this.user.name, this.#defaultDatasetName].join(HF_REPO_ID_SEPARATOR) : '';
+ }
+
+ /**
+ * The datasets a share can go to, the one the last share went to first. An access token that
+ * was pasted reaches all of the account's datasets. A sign-in with Hugging Face reaches only
+ * the ones the app created, which this browser knows as the ones it shared to.
+ */
+ get writableDatasets(): HfDataset[] {
+ const user = this.user;
+
+ if (!user || this.isReadOnly) return [];
+
+ const shared = this.#shared[user.name] ?? [];
+ const writable = this.#pastedToken
+ ? this.datasets
+ : this.datasets.filter(
+ (dataset) => dataset.id === this.lastDataset || shared.includes(dataset.id)
+ );
+ const last = writable.find((dataset) => dataset.id === this.lastDataset);
+
+ return last ? [last, ...writable.filter((dataset) => dataset !== last)] : writable;
+ }
+
+ /** Stop waiting for a sign-in the user gave up on, e.g. by closing the popup. */
+ cancelSignInWithHf(): void {
+ this.isSigningInWithHf = false;
+ }
+
+ /** Finish a sign-in with Hugging Face when this page load is its callback; null otherwise. */
+ completeSignInFromLocation(location?: URL): Promise<HfOAuthCallbackOutcome | null> {
+ return this.#oauth.complete(location);
+ }
+
+ /**
+ * The token to call the Hub with: the pasted one, else the sign-in's, renewed when due.
+ * @returns Null when no one is signed in
+ */
+ freshToken(): Promise<string | null> {
+ return this.#pastedToken ? Promise.resolve(this.#pastedToken) : this.#oauth.freshToken();
+ }
+
+ /** Lists the account's datasets. A failed list leaves it empty, so a new one can be named. */
+ async loadDatasets(): Promise<void> {
+ const user = this.user;
+
+ if (!user || this.isLoadingDatasets) return;
+
+ this.isLoadingDatasets = true;
+
+ try {
+ const token = await this.freshToken();
+ const datasets = token ? await listDatasets(token, user.name) : [];
+
+ // the account may have changed while the list was on its way
+ if (this.user === user) this.datasets = datasets;
+ } catch {
+ if (this.user === user) this.datasets = [];
+ } finally {
+ if (this.user === user) this.hasListedDatasets = true;
+
+ this.isLoadingDatasets = false;
+ }
+ }
+
+ /**
+ * Checks a remembered token once, to know who is signed in. Only a token the Hub rejects is
+ * forgotten: a Hub that cannot be reached leaves it for the next try.
+ */
+ async restoreSession(): Promise<void> {
+ if (this.user || this.isCheckingToken) return;
+
+ this.isCheckingToken = true;
+
+ try {
+ const token = await this.freshToken();
+
+ if (!token) return;
+
+ const user = await whoAmI(token);
+
+ if (user) this.user = user;
+ else this.signOut();
+ } catch {
+ // offline, or the Hub is down
+ } finally {
+ this.isCheckingToken = false;
+ }
+ }
+
+ /**
+ * Checks a pasted access token with the Hub and remembers it.
+ * @throws When the Hub rejects the token
+ */
+ async signIn(token: string): Promise<void> {
+ const trimmed = token.trim();
+
+ this.isCheckingToken = true;
+
+ try {
+ const user = await whoAmI(trimmed);
+
+ if (!user) throw new Error(HF_MESSAGE.TOKEN_REJECTED);
+
+ // one way of signing in at a time
+ this.#oauth.signOut();
+ this.hasListedDatasets = false;
+ this.#pastedToken = trimmed;
+ writeStorage(this.#tokenKey, trimmed);
+ this.user = user;
+ } finally {
+ this.isCheckingToken = false;
+ }
+
+ void this.loadDatasets();
+ }
+
+ /**
+ * Start a sign-in with Hugging Face. Call it from the click that asks for it, with the popup
+ * opened in that same click; without one, this tab goes to the authorization page.
+ */
+ async signInWithHuggingFace(popup: Window | null): Promise<void> {
+ this.oauthError = null;
+ this.isSigningInWithHf = true;
+
+ try {
+ await this.#oauth.start(popup);
+ } catch (error) {
+ this.#settle({ error: errorMessage(error), ok: false });
+ }
+ }
+
+ signOut(): void {
+ this.#forgetAccount();
+ this.#oauth.signOut();
+ // the next account has its own datasets
+ this.#rememberDataset(null);
+ }
+
+ /**
+ * Commits a trace to a dataset of the account, and remembers the dataset for the next one.
+ * @returns The URL of the trace file on the Hub
+ */
+ async uploadTrace(upload: HfTraceUpload): Promise<string> {
+ const token = await this.freshToken();
+
+ if (!token) throw new Error(HF_MESSAGE.SIGN_IN_REQUIRED);
+
+ let url: string;
+
+ try {
+ url = await uploadTrace(token, upload);
+ } catch (error) {
+ // the Hub says this dataset is not one the account can write to: stop offering it
+ if (error instanceof HfNotWritableError) {
+ this.#rememberShared(upload.repoId, false);
+
+ if (this.lastDataset === upload.repoId) this.#rememberDataset(null);
+ }
+
+ throw error;
+ }
+
+ if (!this.datasets.some((dataset) => dataset.id === upload.repoId)) {
+ this.datasets = [{ id: upload.repoId, isPrivate: upload.isPrivate }, ...this.datasets];
+ }
+
+ this.#rememberDataset(upload.repoId);
+ this.#rememberShared(upload.repoId, true);
+
+ return url;
+ }
+
+ #rememberDataset(repoId: string | null): void {
+ this.lastDataset = repoId;
+ writeStorage(this.#datasetKey, repoId);
+ }
+
+ /** Forgets who is signed in, their datasets and the pasted token, but not the sign-in's tokens. */
+ #forgetAccount(): void {
+ this.user = null;
+ this.datasets = [];
+ this.hasListedDatasets = false;
+ this.#pastedToken = null;
+ writeStorage(this.#tokenKey, null);
+ }
+
+ /** Remembers that a dataset can be written to by the account that is signed in, or that it cannot. */
+ #rememberShared(repoId: string, isWritable: boolean): void {
+ const user = this.user;
+
+ if (!user) return;
+
+ const others = (this.#shared[user.name] ?? []).filter((id) => id !== repoId);
+ const ids = isWritable ? [repoId, ...others].slice(0, HF_SHARED_DATASETS_MAX) : others;
+
+ this.#shared = { ...this.#shared, [user.name]: ids };
+ writeJsonStorage(this.#sharedKey, this.#shared);
+ }
+
+ /** A sign-in with Hugging Face ended, in this tab or another one. */
+ #settle(result: HfOAuthResult): void {
+ this.isSigningInWithHf = false;
+ this.oauthError = result.ok ? null : `${result.error} ${HF_MESSAGE.SIGN_IN_FAILED_FALLBACK}`;
+
+ if (!result.ok) return;
+
+ // one way of signing in at a time; the tab that came back stored the tokens
+ this.#forgetAccount();
+ void this.restoreSession().then(() => this.loadDatasets());
+ }
+}
diff --git a/ui/lib/huggingface/src/svelte/assets/hf-logo.svg b/ui/lib/huggingface/src/svelte/assets/hf-logo.svg
new file mode 100644
index 000000000..d55ea22a2
--- /dev/null
+++ b/ui/lib/huggingface/src/svelte/assets/hf-logo.svg
@@ -0,0 +1,8 @@
+<svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M230.721 172.7C230.183 170.673 229.313 168.75 228.146 167.008C228.396 166.091 228.587 165.159 228.714 164.217C229.543 158.241 227.471 152.77 223.567 148.537C221.452 146.225 219.185 144.698 216.784 143.761C218.36 137.018 219.157 130.117 219.161 123.193C219.161 120.03 218.982 116.932 218.682 113.88C218.526 112.356 218.337 110.836 218.115 109.32C217.428 104.847 216.408 100.431 215.064 96.11C214.183 93.2707 213.164 90.476 212.01 87.736C210.281 83.6782 208.262 79.75 205.969 75.982C204.465 73.475 202.827 71.0508 201.062 68.72C200.197 67.543 199.296 66.3938 198.358 65.274C195.58 61.898 192.561 58.7277 189.325 55.788C188.25 54.7997 187.145 53.8453 186.01 52.926C184.893 51.9943 183.751 51.0927 182.586 50.222C180.241 48.4766 177.818 46.8392 175.324 45.315C161.543 36.945 145.382 32.145 128.109 32.145C77.817 32.145 37.057 72.907 37.057 123.196C37.055 130.208 37.867 137.196 39.477 144.02C37.317 144.958 35.247 146.42 33.327 148.535C29.424 152.766 27.351 158.217 28.18 164.193C28.306 165.142 28.495 166.082 28.747 167.006C27.5811 168.749 26.7117 170.673 26.174 172.7C24.974 177.261 25.369 181.374 26.894 184.978C25.236 189.688 25.65 194.704 27.809 199.065C29.379 202.25 31.626 204.714 34.396 206.916C37.689 209.534 41.811 211.758 46.783 213.892C52.715 216.422 59.956 218.799 63.249 219.671C71.755 221.873 79.911 223.269 88.177 223.337C99.954 223.446 110.096 220.677 117.357 213.59C120.924 214.027 124.515 214.246 128.109 214.244C131.906 214.236 135.699 213.997 139.467 213.529C146.711 220.661 156.892 223.455 168.712 223.343C176.977 223.277 185.133 221.881 193.617 219.676C196.932 218.804 204.17 216.427 210.105 213.897C215.077 211.76 219.199 209.536 222.514 206.922C225.263 204.719 227.508 202.256 229.079 199.071C231.26 194.709 231.652 189.693 230.017 184.983C231.527 181.379 231.92 177.257 230.721 172.7ZM222.281 184.673C223.952 187.844 224.059 191.427 222.585 194.764C220.349 199.821 214.795 203.805 204.008 208.082C197.3 210.742 191.158 212.443 191.104 212.458C182.232 214.759 174.208 215.928 167.262 215.928C155.76 215.928 147.201 212.754 141.773 206.486C132.594 208.05 123.222 208.103 114.026 206.644C108.591 212.808 100.081 215.928 88.676 215.928C81.729 215.928 73.706 214.759 64.833 212.458C64.779 212.443 58.639 210.742 51.929 208.082C41.143 203.805 35.587 199.824 33.352 194.764C31.878 191.427 31.985 187.844 33.656 184.673C33.81 184.378 33.976 184.091 34.153 183.813C33.1516 182.309 32.4799 180.61 32.182 178.827C31.8842 177.045 31.967 175.22 32.425 173.472C33.089 170.949 34.46 168.851 36.322 167.344C35.425 165.87 34.8365 164.23 34.592 162.522C34.056 158.808 35.289 155.1 38.062 152.076C40.222 149.723 43.275 148.428 46.655 148.428H46.745C44.1965 140.259 42.9044 131.75 42.913 123.193C42.913 76.522 80.749 38.683 127.427 38.683C174.104 38.683 211.94 76.518 211.94 123.193C211.947 131.773 210.646 140.304 208.081 148.492C208.489 148.452 208.889 148.432 209.282 148.431C212.662 148.431 215.716 149.726 217.874 152.079C220.647 155.1 221.881 158.811 221.344 162.525C221.1 164.233 220.511 165.873 219.615 167.347C221.477 168.854 222.849 170.952 223.512 173.475C223.97 175.223 224.053 177.048 223.755 178.831C223.458 180.613 222.786 182.312 221.784 183.816C221.961 184.091 222.129 184.378 222.281 184.673Z" fill="white"/>
+<path d="M221.784 183.816C222.786 182.312 223.458 180.613 223.756 178.831C224.053 177.048 223.97 175.223 223.512 173.475C222.848 170.952 221.476 168.854 219.615 167.347C220.512 165.873 221.1 164.233 221.344 162.525C221.881 158.811 220.648 155.103 217.874 152.079C215.716 149.726 212.662 148.431 209.282 148.431C208.889 148.431 208.489 148.452 208.081 148.492C210.643 140.304 211.942 131.774 211.933 123.195C211.933 76.5231 174.097 38.6851 127.424 38.6851C80.75 38.6851 42.9099 76.5191 42.9099 123.195C42.9015 131.752 44.1936 140.261 46.742 148.43H46.6519C43.2719 148.43 40.219 149.724 38.06 152.077C35.287 155.098 34.0529 158.81 34.5899 162.523C34.8346 164.231 35.4231 165.872 36.3199 167.346C34.4579 168.852 33.086 170.95 32.422 173.473C31.9642 175.222 31.8817 177.047 32.1799 178.83C32.4781 180.612 33.1501 182.312 34.1519 183.816C33.9739 184.094 33.8099 184.381 33.6549 184.676C31.9849 187.847 31.877 191.43 33.352 194.767C35.588 199.824 41.1419 203.808 51.9289 208.085C58.6359 210.745 64.779 212.446 64.833 212.461C73.705 214.762 81.729 215.931 88.675 215.931C100.081 215.931 108.591 212.811 114.026 206.647C123.222 208.106 132.594 208.052 141.773 206.489C147.201 212.757 155.76 215.931 167.262 215.931C174.208 215.931 182.232 214.762 191.103 212.461C191.158 212.446 197.298 210.745 204.008 208.085C214.795 203.808 220.35 199.824 222.585 194.767C224.059 191.43 223.952 187.847 222.281 184.676C222.129 184.379 221.961 184.091 221.784 183.816ZM110.137 196.997C109.669 197.815 109.168 198.614 108.635 199.391C107.23 201.448 105.382 203.02 103.237 204.188C99.1369 206.424 93.947 207.205 88.675 207.205C80.346 207.205 71.808 205.256 67.023 204.015C66.787 203.954 37.689 195.735 41.373 188.739C41.993 187.562 43.0129 187.092 44.2979 187.092C49.4849 187.092 58.9299 194.816 62.9889 194.816C63.8959 194.816 64.5359 194.43 64.7969 193.488C66.5269 187.284 38.5039 184.676 40.8639 175.692C41.2799 174.102 42.41 173.456 43.998 173.456C50.856 173.455 66.248 185.516 69.467 185.516C69.714 185.516 69.8909 185.443 69.9869 185.291C70.0009 185.268 70.015 185.246 70.028 185.222C71.539 182.727 70.6719 180.913 60.3209 174.573L59.3269 173.968C47.9359 167.074 39.9409 162.925 44.4879 157.975C45.0109 157.404 45.7529 157.151 46.6539 157.151C47.7219 157.151 49.0149 157.508 50.4389 158.108C56.4549 160.645 64.793 167.564 68.276 170.581C68.8239 171.057 69.3683 171.538 69.9089 172.022C69.9089 172.022 74.319 176.608 76.985 176.608C77.599 176.608 78.1199 176.366 78.4729 175.768C80.364 172.58 60.9099 157.838 59.8129 151.755C59.0689 147.634 60.3349 145.546 62.6749 145.546C63.7879 145.546 65.1459 146.02 66.6449 146.971C71.2949 149.922 80.2729 165.35 83.5599 171.352C84.6619 173.363 86.5429 174.213 88.2379 174.213C91.6009 174.213 94.2299 170.87 88.5459 166.622C80.0029 160.23 83.001 149.782 87.078 149.139C87.252 149.111 87.4279 149.097 87.6029 149.097C91.3109 149.097 92.9459 155.486 92.9459 155.486C92.9459 155.486 97.7399 167.524 105.975 175.753C113.447 183.222 114.491 189.351 110.137 196.997ZM136.766 198.407L136.339 198.458L135.611 198.541C135.228 198.581 134.844 198.619 134.459 198.654L134.084 198.688L133.741 198.717L133.255 198.756L132.718 198.795L132.182 198.83L132.063 198.838C131.923 198.846 131.783 198.855 131.641 198.862L131.462 198.872C131.296 198.881 131.13 198.889 130.962 198.896L130.381 198.921L129.854 198.939L129.502 198.949H129.323C129.213 198.949 129.104 198.955 128.994 198.956H128.82C128.71 198.956 128.601 198.956 128.491 198.961L128.043 198.967H127.418C126.927 198.967 126.437 198.962 125.949 198.952L125.553 198.943C125.44 198.943 125.327 198.938 125.216 198.934L124.796 198.922L124.275 198.902L123.805 198.881L123.684 198.876L123.237 198.853C123.112 198.846 122.989 198.84 122.865 198.831L122.576 198.814C122.213 198.791 121.85 198.766 121.487 198.738L121.107 198.707C120.947 198.695 120.787 198.68 120.628 198.666C120.441 198.65 120.254 198.632 120.067 198.614C119.754 198.585 119.441 198.553 119.128 198.519H119.113C123.683 188.324 121.372 178.802 112.137 169.575C106.08 163.526 102.051 154.594 101.215 152.633C99.5229 146.828 95.045 140.375 87.608 140.375C86.979 140.375 86.351 140.425 85.73 140.523C82.472 141.036 79.624 142.911 77.592 145.733C75.396 143.002 73.262 140.831 71.332 139.605C68.422 137.76 65.5179 136.824 62.6889 136.824C59.1579 136.824 56.0019 138.274 53.8019 140.904L53.7459 140.971C53.7039 140.798 53.6639 140.625 53.6229 140.451L53.6179 140.428C53.1992 138.638 52.8477 136.833 52.5639 135.016C52.5639 135.004 52.5639 134.992 52.5579 134.98C52.5359 134.843 52.5159 134.705 52.4949 134.568C52.4334 134.162 52.3757 133.755 52.3219 133.348C52.2979 133.163 52.2719 132.978 52.2489 132.793L52.1809 132.238C52.1589 132.053 52.1409 131.885 52.1209 131.709L52.115 131.665C52.0351 130.945 51.9651 130.225 51.9049 129.503L51.8829 129.226L51.8479 128.754C51.8379 128.625 51.8279 128.495 51.8209 128.365C51.8209 128.334 51.8159 128.304 51.8149 128.275C51.7895 127.913 51.7678 127.55 51.7499 127.187C51.7399 126.998 51.7299 126.81 51.7219 126.62L51.7019 126.124L51.6969 125.974L51.6809 125.517L51.6709 125.128C51.6709 124.973 51.6629 124.818 51.6609 124.663C51.6579 124.508 51.6539 124.338 51.6529 124.174C51.6509 124.01 51.6529 123.848 51.6479 123.685C51.6439 123.521 51.6479 123.358 51.6479 123.195C51.6479 81.3421 85.5789 47.4111 127.436 47.4111C169.292 47.4111 203.222 81.3411 203.222 123.195V124.174C203.222 124.337 203.217 124.501 203.214 124.663C203.214 124.798 203.208 124.931 203.204 125.068C203.204 125.188 203.199 125.309 203.195 125.425C203.195 125.578 203.186 125.731 203.181 125.884V125.896L203.16 126.427C203.153 126.582 203.147 126.738 203.139 126.893L203.134 127.003L203.107 127.499C203.048 128.562 202.967 129.623 202.866 130.683V130.696C202.849 130.87 202.832 131.044 202.813 131.218L202.768 131.629L202.679 132.433L202.628 132.84L202.565 133.319C202.542 133.493 202.519 133.668 202.493 133.841C202.467 134.036 202.438 134.23 202.409 134.424L202.34 134.883L202.258 135.403C202.23 135.576 202.2 135.748 202.168 135.92C202.135 136.093 202.109 136.265 202.079 136.437C202.019 136.781 201.956 137.125 201.89 137.468C201.789 137.981 201.686 138.493 201.58 139.005L201.47 139.512C201.434 139.681 201.395 139.851 201.357 140.02C199.224 137.947 196.399 136.818 193.284 136.818C190.457 136.818 187.55 137.753 184.641 139.598C182.711 140.824 180.578 142.996 178.381 145.726C176.346 142.904 173.498 141.029 170.242 140.516C169.621 140.418 168.993 140.368 168.364 140.368C160.925 140.368 156.45 146.821 154.757 152.626C153.917 154.587 149.887 163.519 143.825 169.577C134.596 178.775 132.268 188.254 136.766 198.407ZM215.007 177.998L214.977 178.087C214.901 178.288 214.813 178.484 214.714 178.674C214.639 178.814 214.558 178.95 214.47 179.082C214.303 179.331 214.12 179.569 213.921 179.793C213.875 179.845 213.831 179.897 213.779 179.948C213.707 180.025 213.634 180.101 213.559 180.175C212.213 181.509 210.161 182.679 207.841 183.752C207.578 183.871 207.311 183.99 207.042 184.11L206.774 184.229C206.595 184.308 206.416 184.386 206.228 184.463C206.049 184.541 205.863 184.619 205.677 184.695L205.119 184.925C203.814 185.462 202.477 185.974 201.173 186.479L200.615 186.696L200.064 186.912C199.697 187.055 199.335 187.198 198.979 187.341L198.448 187.555L197.926 187.768L197.67 187.876C197.499 187.947 197.332 188.018 197.165 188.089C193.328 189.736 190.567 191.411 191.147 193.489C191.163 193.548 191.181 193.604 191.201 193.659C191.253 193.813 191.324 193.958 191.413 194.095C191.465 194.176 191.525 194.253 191.592 194.323C192.274 195.032 193.515 194.92 195.08 194.357C195.3 194.276 195.519 194.192 195.736 194.104L195.872 194.048C196.23 193.896 196.609 193.726 196.996 193.542C197.093 193.496 197.191 193.452 197.289 193.401C199.203 192.465 201.372 191.205 203.524 190.058C204.385 189.593 205.258 189.152 206.142 188.733C208.18 187.774 210.096 187.094 211.636 187.094C212.359 187.094 212.997 187.242 213.529 187.582L213.618 187.641C213.952 187.876 214.232 188.178 214.441 188.528C214.482 188.595 214.522 188.666 214.561 188.739C215.322 190.184 214.685 191.68 213.194 193.147C211.763 194.556 209.537 195.937 207.007 197.215C206.819 197.31 206.631 197.405 206.44 197.498C198.91 201.196 189.049 203.981 188.912 204.016C186.284 204.697 182.526 205.591 178.292 206.26L177.666 206.358L177.563 206.373C177.089 206.445 176.614 206.512 176.138 206.574C175.655 206.639 175.167 206.698 174.676 206.753L174.586 206.763C172.806 206.968 171.019 207.104 169.228 207.169H169.202C168.554 207.192 167.907 207.204 167.259 207.204H166.512C165.524 207.191 164.538 207.146 163.553 207.07C163.53 207.07 163.505 207.07 163.482 207.064C163.129 207.037 162.777 207.004 162.425 206.965C162.06 206.926 161.696 206.882 161.333 206.833C161.094 206.801 160.856 206.765 160.618 206.726C160.376 206.687 160.134 206.647 159.893 206.605L159.564 206.543L159.539 206.538C159.192 206.472 158.847 206.399 158.503 206.319C158.303 206.274 158.104 206.23 157.907 206.176L157.788 206.146C157.69 206.122 157.595 206.096 157.498 206.07L157.445 206.056L157.137 205.966C157.025 205.935 156.913 205.901 156.801 205.868L156.762 205.857L156.471 205.768C156.361 205.734 156.251 205.698 156.142 205.662L155.874 205.573L155.677 205.504C155.487 205.437 155.298 205.368 155.111 205.296L154.933 205.226L154.786 205.168C154.502 205.054 154.22 204.935 153.941 204.81L153.756 204.72L153.725 204.706C153.659 204.675 153.594 204.644 153.528 204.617C153.399 204.555 153.271 204.491 153.144 204.426L153.105 204.407L152.921 204.31C152.594 204.139 152.274 203.957 151.96 203.764L151.788 203.658C151.702 203.605 151.616 203.55 151.532 203.494L151.308 203.346L151.067 203.18L150.923 203.077C150.771 202.969 150.622 202.857 150.476 202.742L150.243 202.563C150.15 202.488 150.058 202.412 149.967 202.335C149.89 202.272 149.815 202.206 149.74 202.14L149.734 202.135C149.653 202.064 149.574 201.993 149.495 201.92C149.417 201.849 149.339 201.777 149.263 201.704L149.254 201.695C149.174 201.619 149.096 201.542 149.019 201.463C148.942 201.385 148.863 201.307 148.788 201.227C148.713 201.148 148.636 201.067 148.562 200.984C148.488 200.902 148.42 200.827 148.35 200.746L148.327 200.719C148.259 200.641 148.192 200.562 148.126 200.481C147.983 200.31 147.844 200.135 147.71 199.956C147.575 199.776 147.443 199.592 147.314 199.405L147.191 199.221C147.027 198.981 146.867 198.739 146.712 198.493C146.596 198.316 146.483 198.138 146.373 197.957C146.302 197.844 146.234 197.73 146.166 197.618L146.138 197.572C146.073 197.462 146.009 197.354 145.947 197.245C145.911 197.186 145.877 197.127 145.845 197.066C145.812 197.004 145.774 196.941 145.739 196.878L145.682 196.779L145.647 196.715C145.58 196.595 145.514 196.474 145.45 196.352C145.42 196.298 145.391 196.244 145.36 196.192L145.271 196.019L145.181 195.848C144.956 195.398 144.743 194.942 144.543 194.48L144.472 194.311C144.426 194.198 144.383 194.086 144.337 193.975C144.315 193.921 144.293 193.868 144.274 193.814C144.167 193.537 144.067 193.257 143.975 192.975C143.942 192.874 143.91 192.775 143.88 192.675C143.808 192.448 143.743 192.219 143.685 191.988C143.614 191.719 143.551 191.448 143.498 191.175C143.487 191.12 143.476 191.065 143.467 191.012C143.415 190.745 143.373 190.476 143.34 190.206C143.332 190.153 143.326 190.1 143.32 190.047L143.303 189.885C143.281 189.673 143.264 189.46 143.254 189.247C143.254 189.193 143.249 189.139 143.247 189.087C143.242 188.981 143.24 188.875 143.239 188.769C143.183 184.496 145.345 180.388 149.968 175.767C158.203 167.54 162.997 155.501 162.997 155.501C162.997 155.501 163.126 154.996 163.394 154.269C163.431 154.168 163.47 154.064 163.514 153.955C163.67 153.548 163.846 153.148 164.041 152.758L164.08 152.683C164.246 152.351 164.428 152.027 164.624 151.712C164.67 151.639 164.714 151.567 164.765 151.494C164.912 151.277 165.067 151.065 165.23 150.86C165.319 150.749 165.416 150.639 165.513 150.532C165.552 150.49 165.59 150.448 165.631 150.408C166.108 149.915 166.653 149.513 167.27 149.299L167.348 149.273C167.4 149.256 167.452 149.24 167.505 149.225C167.566 149.209 167.627 149.195 167.69 149.182L167.719 149.176C167.849 149.15 167.981 149.133 168.114 149.124H168.125C168.194 149.124 168.264 149.117 168.335 149.117C168.424 149.117 168.507 149.117 168.594 149.126C168.684 149.134 168.773 149.144 168.863 149.158C169.605 149.276 170.311 149.718 170.919 150.4C171.15 150.66 171.358 150.94 171.54 151.236C171.66 151.428 171.773 151.631 171.88 151.845C171.923 151.934 171.964 152.016 172.004 152.104C172.108 152.33 172.202 152.56 172.284 152.795C172.479 153.345 172.626 153.911 172.723 154.487C172.807 154.992 172.857 155.502 172.873 156.013C172.881 156.286 172.881 156.563 172.873 156.842C172.819 158.14 172.553 159.421 172.086 160.634C172.044 160.745 171.997 160.857 171.952 160.969C171.86 161.195 171.759 161.417 171.65 161.634C171.569 161.799 171.484 161.965 171.392 162.13C171.332 162.24 171.269 162.35 171.206 162.46C171.045 162.734 170.871 163.006 170.684 163.277L170.571 163.439C170.129 164.055 169.637 164.633 169.099 165.167C168.569 165.698 168.001 166.189 167.4 166.637C166.798 167.083 166.233 167.577 165.711 168.114C164.208 169.691 163.858 171.083 164.196 172.138C164.25 172.304 164.321 172.465 164.407 172.617C164.508 172.791 164.628 172.951 164.764 173.097L164.817 173.152L164.871 173.206C164.925 173.258 164.982 173.309 165.043 173.359L165.103 173.407C165.248 173.519 165.402 173.619 165.563 173.707C165.61 173.732 165.652 173.757 165.705 173.781C165.879 173.866 166.058 173.939 166.242 173.998C166.293 174.015 166.344 174.03 166.396 174.046L166.461 174.063L166.551 174.087L166.628 174.106L166.712 174.124L166.795 174.141L166.874 174.154C166.932 174.164 166.992 174.174 167.052 174.181L167.109 174.19L167.213 174.2L167.277 174.207L167.382 174.214H167.444L167.554 174.22H167.9L167.999 174.214L168.113 174.207L168.252 174.194L168.382 174.179C168.412 174.179 168.442 174.171 168.472 174.165C168.872 174.107 169.264 174.001 169.639 173.849L169.798 173.782C169.887 173.743 169.977 173.702 170.059 173.658C170.235 173.57 170.406 173.47 170.57 173.361C170.799 173.211 171.015 173.043 171.217 172.858C171.265 172.815 171.312 172.769 171.358 172.725C171.381 172.703 171.403 172.682 171.425 172.658C171.469 172.613 171.514 172.569 171.558 172.52C171.878 172.168 172.155 171.78 172.383 171.363C174.34 167.804 176.391 164.298 178.534 160.849L178.828 160.378L179.125 159.907C179.273 159.668 179.423 159.433 179.572 159.199L179.722 158.965C180.22 158.185 180.726 157.41 181.241 156.641L181.546 156.185C182.158 155.278 182.768 154.396 183.373 153.558L183.674 153.143C184.332 152.236 185.017 151.348 185.728 150.482L186.01 150.144C186.057 150.088 186.1 150.032 186.151 149.978C186.244 149.868 186.337 149.761 186.428 149.657C186.474 149.604 186.517 149.552 186.566 149.5L186.834 149.198L186.968 149.051C187.103 148.906 187.235 148.767 187.365 148.634C187.455 148.544 187.538 148.455 187.624 148.371C188.131 147.853 188.69 147.388 189.293 146.985L189.433 146.895C189.567 146.805 189.706 146.721 189.848 146.645C192.212 145.303 194.169 145.204 195.296 146.331C195.978 147.013 196.356 148.144 196.335 149.718C196.335 149.787 196.335 149.857 196.33 149.929V150.006C196.33 150.078 196.324 150.15 196.318 150.223C196.318 150.313 196.308 150.402 196.299 150.492C196.29 150.581 196.285 150.649 196.276 150.729C196.276 150.751 196.272 150.774 196.268 150.798C196.262 150.867 196.253 150.938 196.243 151.009C196.243 151.03 196.243 151.052 196.235 151.074C196.224 151.169 196.21 151.263 196.194 151.357C196.183 151.447 196.168 151.531 196.152 151.619L196.126 151.768C196.1 151.91 196.067 152.05 196.026 152.188C195.948 152.447 195.854 152.7 195.743 152.946C195.588 153.284 195.417 153.613 195.229 153.933C195.125 154.111 195.018 154.286 194.907 154.459C194.793 154.638 194.673 154.819 194.549 155.002C194.233 155.454 193.905 155.897 193.564 156.33L193.408 156.527C192.852 157.22 192.278 157.899 191.686 158.562L191.499 158.772C191.247 159.053 190.991 159.336 190.729 159.62L190.532 159.834C190.401 159.977 190.264 160.12 190.132 160.264C190.001 160.407 189.864 160.552 189.726 160.697L189.315 161.13L188.898 161.566L188.478 162.002C188.196 162.294 187.913 162.586 187.628 162.878C183.573 167.037 179.301 171.182 177.855 173.766C177.758 173.934 177.671 174.108 177.593 174.285C177.387 174.755 177.301 175.157 177.36 175.482C177.379 175.589 177.416 175.691 177.471 175.785C177.552 175.926 177.651 176.056 177.766 176.172C177.819 176.224 177.875 176.272 177.934 176.316C178.232 176.528 178.591 176.637 178.957 176.627H179.071L179.188 176.618L179.305 176.605L179.402 176.591C179.415 176.589 179.429 176.587 179.442 176.583L179.531 176.566L179.554 176.561L179.653 176.54L179.688 176.531C179.723 176.522 179.757 176.513 179.792 176.503C179.827 176.493 179.875 176.48 179.917 176.466C180.093 176.413 180.265 176.35 180.434 176.278C180.523 176.242 180.61 176.203 180.696 176.161C180.741 176.141 180.786 176.12 180.828 176.098L180.962 176.032C181.282 175.866 181.594 175.685 181.898 175.491L182.031 175.401C182.076 175.373 182.121 175.344 182.164 175.312L182.297 175.223L182.368 175.174L182.56 175.039C182.739 174.916 182.906 174.789 183.075 174.66L183.09 174.648L183.359 174.44C183.726 174.15 184.074 173.858 184.39 173.583L184.6 173.399L184.619 173.381L184.729 173.284C184.987 173.052 185.217 172.836 185.408 172.658L185.487 172.581C185.556 172.516 185.619 172.455 185.676 172.403L185.788 172.292L185.828 172.253L185.839 172.242L185.956 172.125L186.03 172.048L186.039 172.041L186.074 172.009L186.118 171.969L186.132 171.956L186.169 171.922L186.373 171.743L186.487 171.641C186.548 171.588 186.607 171.534 186.666 171.479L186.802 171.358C186.827 171.338 186.851 171.316 186.876 171.294L187.019 171.169L187.229 170.984L187.341 170.887C187.776 170.509 188.305 170.052 188.913 169.537L189.162 169.326L189.573 168.981L189.994 168.63C190.544 168.173 191.136 167.688 191.762 167.185L192.173 166.855C192.523 166.576 192.882 166.292 193.246 166.006C193.393 165.891 193.542 165.776 193.694 165.662C194.066 165.373 194.44 165.086 194.817 164.803C195.675 164.155 196.56 163.506 197.456 162.874L197.84 162.606C198.109 162.421 198.377 162.235 198.645 162.054L198.888 161.89C199.367 161.565 199.853 161.248 200.343 160.939L200.586 160.786L200.827 160.636C201.069 160.486 201.309 160.339 201.548 160.196L201.787 160.053L202.265 159.775L202.734 159.506L202.829 159.454L203.2 159.25C203.355 159.166 203.509 159.085 203.663 159.006L203.892 158.888L204.115 158.776C204.193 158.739 204.27 158.7 204.346 158.663C204.848 158.415 205.36 158.187 205.88 157.979C206.021 157.919 206.161 157.865 206.3 157.818L206.71 157.674C206.833 157.633 206.953 157.594 207.068 157.559L207.108 157.547C207.17 157.527 207.232 157.509 207.293 157.493L207.311 157.488C207.439 157.451 207.566 157.419 207.691 157.389H207.7C208.054 157.304 208.414 157.243 208.777 157.206C208.944 157.189 209.111 157.18 209.279 157.181H209.363C209.475 157.181 209.583 157.188 209.69 157.199C209.739 157.199 209.788 157.209 209.836 157.215H209.856C209.904 157.221 209.952 157.228 210 157.239C210.047 157.248 210.095 157.256 210.141 157.267H210.156C210.203 157.277 210.245 157.289 210.294 157.303C210.548 157.374 210.79 157.484 211.012 157.628C211.121 157.699 211.223 157.779 211.317 157.868L211.344 157.894C211.362 157.91 211.379 157.927 211.395 157.944L211.444 157.997C211.846 158.418 212.178 158.901 212.428 159.427L212.466 159.517C212.551 159.717 212.618 159.924 212.666 160.135C212.808 160.781 212.753 161.455 212.508 162.07C212.415 162.318 212.302 162.557 212.169 162.785C211.858 163.309 211.489 163.796 211.07 164.237L210.981 164.332C210.848 164.472 210.71 164.612 210.565 164.752C210.501 164.815 210.434 164.877 210.367 164.94L210.162 165.129L210.055 165.224C209.797 165.454 209.532 165.677 209.263 165.893C209.1 166.025 208.936 166.154 208.77 166.281C208.184 166.729 207.587 167.161 206.979 167.578C206.612 167.83 206.242 168.077 205.869 168.321C204.95 168.924 204.021 169.512 203.083 170.084C201.115 171.294 198.934 172.588 196.609 173.995L196.007 174.36C195.348 174.762 194.726 175.146 194.14 175.512L193.845 175.697L193.287 176.055C192.917 176.292 192.548 176.531 192.179 176.77L191.882 176.966C191.737 177.06 191.593 177.156 191.449 177.252L191.308 177.342L190.876 177.633L190.647 177.79L190.379 177.976L190.13 178.149C189.713 178.444 189.325 178.725 188.968 178.992L188.834 179.094C188.624 179.253 188.416 179.415 188.211 179.58C187.902 179.829 187.62 180.067 187.367 180.296L187.243 180.409C187.172 180.474 187.102 180.539 187.035 180.603C186.989 180.648 186.946 180.693 186.898 180.736L186.834 180.8C186.691 180.944 186.551 181.091 186.416 181.242L186.35 181.318C186.203 181.488 186.075 181.651 185.963 181.81L185.913 181.881C185.825 182.009 185.744 182.141 185.671 182.277C185.652 182.311 185.635 182.345 185.618 182.379L185.569 182.481L185.536 182.555L185.515 182.605L185.498 182.65L185.475 182.711C185.413 182.88 185.37 183.056 185.345 183.234L185.337 183.296L185.331 183.354V183.669C185.331 183.695 185.331 183.721 185.338 183.749L185.343 183.797C185.343 183.823 185.349 183.848 185.353 183.876C185.357 183.902 185.364 183.949 185.372 183.986V183.991C185.379 184.026 185.386 184.06 185.395 184.095C185.404 184.13 185.413 184.17 185.424 184.206C185.443 184.277 185.467 184.347 185.492 184.417C185.508 184.459 185.523 184.5 185.54 184.541C185.54 184.549 185.546 184.558 185.55 184.566L185.586 184.647L185.636 184.758C185.69 184.873 185.749 184.985 185.813 185.094L185.879 185.208L185.947 185.322C185.959 185.341 185.973 185.359 185.988 185.376L186.01 185.399L186.035 185.422L186.061 185.442C186.099 185.469 186.14 185.49 186.183 185.505C186.206 185.513 186.23 185.519 186.254 185.525C186.831 185.655 188.017 185.178 189.593 184.346C189.682 184.298 189.78 184.248 189.875 184.196L190.355 183.934L190.589 183.804C190.756 183.715 190.926 183.614 191.1 183.515L191.417 183.336C193.5 182.137 195.988 180.597 198.56 179.093C198.801 178.952 199.043 178.811 199.285 178.672L199.771 178.361C200.335 178.038 200.902 177.719 201.471 177.404C202.188 177.01 202.91 176.626 203.639 176.254L204.115 176.013C204.431 175.857 204.744 175.705 205.053 175.557C205.651 175.273 206.256 175.003 206.868 174.748L207.203 174.612L207.243 174.596C209.018 173.893 210.627 173.459 211.929 173.459C212.21 173.456 212.492 173.48 212.769 173.528H212.778C212.867 173.544 212.948 173.562 213.031 173.582H213.046C213.259 173.636 213.466 173.713 213.662 173.812C213.937 173.954 214.184 174.143 214.393 174.371C214.489 174.477 214.574 174.592 214.649 174.714C214.789 174.929 214.899 175.162 214.978 175.406C215.01 175.501 215.038 175.594 215.067 175.693C215.278 176.45 215.257 177.253 215.007 177.998Z" fill="#FF9D00"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M203.21 123.685V123.194C203.21 81.34 169.292 47.411 127.435 47.411C85.5791 47.411 51.648 81.342 51.648 123.194V123.358C51.646 123.467 51.645 123.576 51.648 123.685C51.6529 123.848 51.6546 124.011 51.653 124.174L51.6581 124.534L51.661 124.663C51.661 124.723 51.6631 124.782 51.6651 124.842C51.6681 124.937 51.67 125.033 51.67 125.128L51.681 125.517L51.697 125.974L51.702 126.124L51.722 126.597V126.62C51.73 126.805 51.7401 126.989 51.7491 127.173L51.75 127.187C51.76 127.375 51.7701 127.564 51.7821 127.753C51.7921 127.927 51.802 128.101 51.815 128.275L51.8171 128.306C51.8258 128.455 51.8358 128.605 51.847 128.754L51.85 128.794L51.883 129.226L51.8861 129.254C51.8921 129.338 51.898 129.422 51.906 129.503C51.9658 130.224 52.0355 130.945 52.1151 131.664L52.12 131.709L52.181 132.238L52.2491 132.793L52.299 133.17L52.322 133.347C52.3753 133.755 52.433 134.162 52.495 134.568L52.4991 134.595L52.558 134.979C52.8435 136.808 53.1971 138.626 53.618 140.429L53.6231 140.451L53.655 140.586L53.746 140.971L53.802 140.904C56.002 138.274 59.158 136.824 62.689 136.824C65.519 136.824 68.4221 137.76 71.3321 139.605C73.2621 140.831 75.3961 143.002 77.5921 145.733C79.6241 142.911 82.4721 141.035 85.7301 140.523C86.3513 140.425 86.9792 140.376 87.6081 140.375C95.0441 140.375 99.523 146.828 101.215 152.633C102.051 154.594 106.08 163.526 112.156 169.568C121.392 178.795 123.703 188.316 119.132 198.511H119.148C119.459 198.546 119.772 198.578 120.087 198.607C120.274 198.625 120.46 198.643 120.648 198.659L120.714 198.665L121.127 198.7L121.507 198.73C121.869 198.758 122.232 198.784 122.596 198.807L122.885 198.824L123.114 198.838L123.256 198.846L123.703 198.869L123.825 198.874L124.294 198.895L124.816 198.915L125.235 198.927L125.305 198.929C125.394 198.933 125.483 198.936 125.572 198.936L125.668 198.939C126.258 198.953 126.847 198.96 127.437 198.959H128.063L128.51 198.954C128.62 198.949 128.729 198.949 128.84 198.949H129.014L129.165 198.945C129.224 198.943 129.283 198.941 129.343 198.941H129.522L129.873 198.932L130.401 198.914L130.982 198.888C131.15 198.882 131.316 198.873 131.482 198.865L131.661 198.854L131.927 198.84L132.083 198.831L132.201 198.823L132.738 198.788L133.274 198.749L133.761 198.71L134.103 198.681L134.479 198.647C135.107 198.591 135.733 198.525 136.359 198.45L136.786 198.399C132.287 188.247 134.616 178.767 143.813 169.577C149.876 163.519 153.905 154.587 154.745 152.625C156.438 146.821 160.914 140.368 168.352 140.368C168.981 140.368 169.61 140.418 170.231 140.516C173.486 141.028 176.334 142.904 178.369 145.726C180.566 142.996 182.699 140.823 184.63 139.597C187.539 137.753 190.445 136.817 193.272 136.817C196.388 136.817 199.212 137.947 201.345 140.02C201.384 139.851 201.422 139.682 201.459 139.512L201.568 139.006C201.607 138.821 201.646 138.636 201.683 138.451C201.749 138.124 201.815 137.797 201.878 137.467C201.944 137.125 202.007 136.781 202.067 136.437L202.098 136.251C202.117 136.141 202.135 136.031 202.156 135.92C202.19 135.748 202.218 135.576 202.246 135.402L202.257 135.336L202.328 134.883L202.398 134.424V134.42C202.449 134.081 202.497 133.742 202.542 133.403L202.553 133.319L202.616 132.841L202.667 132.433L202.757 131.629L202.792 131.306L202.801 131.218C202.82 131.044 202.838 130.87 202.854 130.696V130.682C202.867 130.544 202.881 130.405 202.893 130.266C202.964 129.478 203.024 128.686 203.072 127.891C203.081 127.761 203.088 127.63 203.096 127.499V127.493L203.122 127.002L203.128 126.892C203.144 126.56 203.158 126.228 203.169 125.896V125.884L203.174 125.754C203.179 125.645 203.183 125.535 203.183 125.425L203.185 125.381C203.189 125.278 203.193 125.172 203.193 125.067L203.196 124.977C203.199 124.872 203.202 124.768 203.202 124.663L203.204 124.574C203.207 124.441 203.21 124.307 203.21 124.174V123.685ZM108.638 199.391C114.64 190.59 114.214 183.984 105.98 175.754C97.7441 167.523 92.951 155.487 92.951 155.487C92.951 155.487 91.1621 148.496 87.0821 149.138C83.0021 149.78 80.0091 160.227 88.5521 166.622C97.0941 173.017 86.8521 177.353 83.5641 171.352C80.2761 165.35 71.299 149.923 66.645 146.972C61.991 144.021 58.718 145.675 59.815 151.757C60.36 154.776 65.4281 159.929 70.1631 164.743C74.9671 169.627 79.428 174.163 78.474 175.768C76.581 178.955 69.9141 172.023 69.9141 172.023C69.9141 172.023 49.038 153.025 44.494 157.976C40.304 162.539 46.765 166.418 56.7211 172.397C57.5671 172.905 58.4391 173.429 59.3321 173.969C70.7231 180.865 71.609 182.684 69.992 185.293C69.395 186.257 65.582 183.968 60.892 181.153C52.897 176.352 42.3551 170.023 40.8661 175.688C39.5781 180.591 47.334 183.595 54.368 186.32C60.228 188.59 65.5881 190.666 64.7991 193.484C63.9821 196.406 59.5531 193.969 54.7121 191.305C49.2771 188.314 43.3221 185.038 41.3731 188.735C37.6901 195.725 66.7831 203.954 67.0231 204.015C76.4231 206.453 100.295 211.619 108.638 199.391ZM147.303 199.391C141.301 190.59 141.727 183.984 149.962 175.754C158.197 167.523 162.99 155.487 162.99 155.487C162.99 155.487 164.779 148.496 168.859 149.138C172.939 149.78 175.932 160.227 167.39 166.622C158.847 173.017 169.089 177.353 172.377 171.352C175.666 165.35 184.637 149.923 189.291 146.972C193.945 144.021 197.22 145.675 196.122 151.757C195.578 154.776 190.509 159.929 185.774 164.744C180.97 169.628 176.509 174.163 177.462 175.768C179.355 178.955 186.027 172.019 186.027 172.019C186.027 172.019 206.902 153.022 211.448 157.973C215.637 162.535 209.176 166.415 199.219 172.394C198.348 172.917 197.478 173.441 196.609 173.966C185.218 180.862 184.332 182.681 185.948 185.289C186.546 186.254 190.359 183.964 195.048 181.149C203.044 176.349 213.586 170.019 215.075 175.685C216.364 180.588 208.607 183.592 201.573 186.317C195.713 188.587 190.353 190.663 191.141 193.481C191.957 196.402 196.385 193.965 201.225 191.301C206.66 188.31 212.616 185.032 214.564 188.732C218.248 195.726 189.15 203.947 188.915 204.007C179.515 206.453 155.643 211.619 147.303 199.391Z" fill="#FFD21E"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M152.047 102.567C153.229 102.985 154.108 104.257 154.944 105.468C156.074 107.104 157.126 108.627 158.74 107.769C160.644 106.756 162.205 105.202 163.225 103.302C164.246 101.402 164.681 99.2427 164.475 97.096C164.321 95.4908 163.813 93.9398 162.987 92.5548C162.161 91.1697 161.038 89.985 159.7 89.0862C158.361 88.1874 156.839 87.5968 155.245 87.3569C153.65 87.117 152.022 87.2339 150.478 87.699C148.934 88.1639 147.513 88.9653 146.316 90.0455C145.119 91.1257 144.176 92.4578 143.556 93.946C142.936 95.4342 142.653 97.0415 142.728 98.652C142.804 100.263 143.235 101.836 143.992 103.26C144.74 104.667 146.4 104.003 148.152 103.302C149.525 102.753 150.956 102.181 152.047 102.567ZM100.672 102.567C99.49 102.985 98.611 104.258 97.775 105.468C96.645 107.105 95.592 108.627 93.979 107.769C91.5845 106.501 89.7482 104.386 88.8278 101.838C87.9075 99.2895 87.9692 96.4896 89.0008 93.9841C90.0324 91.4786 91.9601 89.4471 94.408 88.2855C96.856 87.1239 99.6488 86.9156 102.242 87.701C104.307 88.3228 106.141 89.5427 107.513 91.2065C108.885 92.8704 109.732 94.9035 109.949 97.049C110.165 99.1945 109.74 101.356 108.728 103.26C107.979 104.667 106.319 104.003 104.567 103.303C103.193 102.753 101.764 102.181 100.672 102.567ZM144.099 149.318C152.242 142.903 155.233 132.429 155.233 125.977C155.233 120.877 151.802 122.482 146.309 125.202L145.999 125.355C140.957 127.852 134.245 131.177 126.877 131.177C119.508 131.177 112.796 127.852 107.755 125.354C102.084 122.545 98.527 120.783 98.527 125.978C98.527 132.634 101.709 143.563 110.443 149.912C111.596 147.573 113.219 145.497 115.211 143.813C117.202 142.129 119.52 140.874 122.018 140.126C122.89 139.866 123.788 141.367 124.707 142.904C125.594 144.386 126.501 145.902 127.423 145.902C128.406 145.902 129.371 144.408 130.314 142.95C131.299 141.425 132.26 139.94 133.189 140.237C137.864 141.738 141.775 144.993 144.099 149.318Z" fill="#32343D"/>
+<path d="M144.097 149.317C139.856 152.659 134.219 154.9 126.878 154.9C119.981 154.9 114.587 152.922 110.443 149.911C111.596 147.572 113.219 145.495 115.211 143.812C117.202 142.128 119.52 140.873 122.018 140.125C123.73 139.614 125.545 145.901 127.423 145.901C129.433 145.901 131.37 139.655 133.189 140.236C137.863 141.738 141.773 144.993 144.097 149.317Z" fill="#FF323D"/>
+<path fill-rule="evenodd" clip-rule="evenodd" d="M81.2 111.64C80.2312 112.288 79.1173 112.687 77.9572 112.801C76.7971 112.916 75.6267 112.742 74.55 112.295C73.6893 111.94 72.9072 111.418 72.2488 110.759C71.5903 110.101 71.0684 109.319 70.713 108.458C70.267 107.381 70.0935 106.211 70.2082 105.051C70.3228 103.891 70.7219 102.777 71.37 101.808C72.1488 100.642 73.2558 99.7333 74.5512 99.1967C75.8466 98.6601 77.272 98.5197 78.6471 98.7935C80.0223 99.0672 81.2853 99.7427 82.2764 100.734C83.2675 101.726 83.9422 102.99 84.215 104.365C84.4883 105.74 84.3477 107.165 83.8113 108.46C83.2748 109.755 82.3654 110.861 81.2 111.64ZM182.613 111.64C181.644 112.288 180.53 112.687 179.37 112.801C178.209 112.916 177.039 112.742 175.962 112.295C175.101 111.939 174.319 111.418 173.661 110.759C173.003 110.101 172.481 109.319 172.125 108.458C171.68 107.381 171.507 106.211 171.621 105.051C171.736 103.891 172.135 102.777 172.782 101.808C173.364 100.936 174.133 100.205 175.032 99.6658C175.931 99.1269 176.938 98.7942 177.981 98.6917C179.025 98.5891 180.078 98.7193 181.064 99.0728C182.051 99.4264 182.947 99.9944 183.688 100.736C184.68 101.727 185.355 102.99 185.628 104.365C185.902 105.74 185.761 107.165 185.224 108.46C184.687 109.755 183.779 110.861 182.613 111.64Z" fill="#FFAD03"/>
+</svg>
\ No newline at end of file
diff --git a/ui/lib/huggingface/src/svelte/index.ts b/ui/lib/huggingface/src/svelte/index.ts
new file mode 100644
index 000000000..41e789147
--- /dev/null
+++ b/ui/lib/huggingface/src/svelte/index.ts
@@ -0,0 +1,12 @@
+/**
+ * The Hugging Face account as Svelte state, and the components that show it. They build on
+ * Llama UI (@ggml-org/llama-ui), so an app that uses them has it too.
+ */
+
+export { HfAccount } from './account.svelte.js';
+/** Who is signed in, with Sign out; or the two ways to sign in. */
+export { default as HfAccountPanel } from './HfAccountPanel.svelte';
+/** The Hugging Face logo. */
+export { default as HfLogo } from './HfLogo.svelte';
+/** Share a trace to a dataset of the account: sign in, pick what and where, upload. */
+export { default as HfShareDialog } from './HfShareDialog.svelte';
diff --git a/ui/lib/huggingface/src/types.ts b/ui/lib/huggingface/src/types.ts
new file mode 100644
index 000000000..ed9f2c7a5
--- /dev/null
+++ b/ui/lib/huggingface/src/types.ts
@@ -0,0 +1,142 @@
+import type { HfOAuthFlowMode, HfTokenRole } from './enums.js';
+
+/** Tokens a sign-in got, as kept in the browser. */
+export interface HfOAuthTokens {
+ accessToken: string;
+ refreshToken?: string;
+ /** Epoch milliseconds; unknown when Hugging Face did not say. */
+ expiresAt?: number;
+ /** The scopes Hugging Face granted, space-separated. */
+ scope?: string;
+}
+
+/** A sign-in waiting for its callback. */
+export interface HfOAuthPendingFlow {
+ codeVerifier: string;
+ mode: HfOAuthFlowMode;
+ /** Where a redirect sign-in returns to. */
+ returnUrl: string;
+ startedAt: number;
+ state: string;
+}
+
+/** What the browser keeps: the client as it was registered, and its tokens. */
+export interface HfOAuthRecord {
+ clientId: string;
+ redirectUrl: string;
+ scope: string;
+ logoUrl?: string;
+ pending?: HfOAuthPendingFlow;
+ tokens?: HfOAuthTokens;
+}
+
+/** How a sign-in ended, as every tab of the app hears it. */
+export interface HfOAuthResult {
+ ok: boolean;
+ error?: string;
+}
+
+/** What a page load that came back from the authorization page did. */
+export interface HfOAuthCallbackOutcome {
+ /** The window was a sign-in popup: it is done and can close. */
+ closeWindow: boolean;
+ /** Null for a callback this browser did not start, or already finished. */
+ result: HfOAuthResult | null;
+}
+
+/** What the token endpoint answers, before it is checked: any field may be missing. */
+export interface HfTokenResponse {
+ access_token?: unknown;
+ expires_in?: unknown;
+ refresh_token?: unknown;
+ scope?: unknown;
+}
+
+/** What the registration endpoint answers, before it is checked. */
+export interface HfRegistrationResponse {
+ client_id?: unknown;
+}
+
+export interface HfOAuthClient {
+ clientName: string;
+ redirectUrl: string;
+ scopes: readonly string[];
+ logoUrl?: string;
+}
+
+export interface HfOAuthSignInOptions {
+ /** The name shown on the Hugging Face authorization page. */
+ clientName: string;
+ /** A public image Hugging Face shows for the app, e.g. among the user's connected apps. */
+ logoUrl?: string;
+ scopes: readonly string[];
+ /** A scope the app cannot do without: tokens that lack it are refused. */
+ requiredScope?: string;
+ /** The page of the app Hugging Face sends the browser back to, usually its root. */
+ callbackUrl: () => string;
+ /** localStorage key of the record; also names the channel the tabs share. */
+ storageKey: string;
+ /** Called in every tab of the app when a sign-in ends. */
+ onResult?: (result: HfOAuthResult) => void;
+}
+
+// Hub
+
+/** The signed-in account, from `/api/whoami-v2`. */
+export interface HfUser {
+ name: string;
+ fullname?: string;
+ /** Set for a user access token; a read token cannot write. */
+ tokenRole?: HfTokenRole;
+}
+
+/** A dataset of the account. */
+export interface HfDataset {
+ /** `owner/name` */
+ id: string;
+ isPrivate: boolean;
+}
+
+/** A message of the shared conversation, as the faded preview of a finished share shows it. */
+export interface HfTracePreviewLine {
+ role: 'user' | 'assistant';
+ text: string;
+}
+
+/** A trace as the app hands it over: one JSONL file and how its commit reads. */
+export interface HfTraceFile {
+ path: string;
+ content: string;
+ commitMessage: string;
+ /** The first messages of the conversation, shown faded once it is shared. Nothing is uploaded from it. */
+ preview?: HfTracePreviewLine[];
+}
+
+/** A trace file and the dataset it goes to. */
+export interface HfTraceUpload extends HfTraceFile {
+ repoId: string;
+ /** Visibility of the dataset when the upload creates it; an existing one keeps its own. */
+ isPrivate: boolean;
+}
+
+// Account (./svelte)
+
+/** What the app tells the account about itself. */
+export interface HfAccountOptions extends Omit<HfOAuthSignInOptions, 'onResult' | 'storageKey'> {
+ /** Prefix of the localStorage keys the account keeps its sign-in under, e.g. the app's name. */
+ storagePrefix: string;
+ /** The dataset name a first share suggests, under the account's own name. */
+ defaultDatasetName: string;
+}
+
+/** One part of a conversation that can be shared, e.g. all of it or up to a message. */
+export interface HfShareScope {
+ id: string;
+ label: string;
+ /** Shown after the label, e.g. `12 messages`. */
+ detail?: string;
+ /** Offers to include attachments, which are left out otherwise. */
+ hasAttachments?: boolean;
+ /** Nothing to share yet, e.g. while its messages load. */
+ isEmpty?: boolean;
+}
diff --git a/ui/lib/huggingface/src/util.ts b/ui/lib/huggingface/src/util.ts
new file mode 100644
index 000000000..210d79063
--- /dev/null
+++ b/ui/lib/huggingface/src/util.ts
@@ -0,0 +1,34 @@
+/** Small helpers the package's modules share. */
+
+import { HF_BASE64_CHUNK_BYTES, HF_REPO_ID_SEPARATOR } from './constants.js';
+
+/** The text of anything thrown: an Error's message, else the value as a string. */
+export function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+/** Base64 of bytes, a chunk at a time, under the argument limit of String.fromCharCode. */
+export function bytesToBase64(bytes: Uint8Array): string {
+ let binary = '';
+
+ for (let i = 0; i < bytes.length; i += HF_BASE64_CHUNK_BYTES) {
+ binary += String.fromCharCode(...bytes.subarray(i, i + HF_BASE64_CHUNK_BYTES));
+ }
+
+ return btoa(binary);
+}
+
+/** Base64 for a URL: `-` and `_` for `+` and `/`, no padding (what PKCE and a state use). */
+export function bytesToBase64Url(bytes: Uint8Array): string {
+ return bytesToBase64(bytes).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
+}
+
+/**
+ * Splits the repo ID `owner/name` of a dataset into its owner and its name. An ID without a
+ * separator is all name.
+ */
+export function splitRepoId(repoId: string): [owner: string, name: string] {
+ const at = repoId.indexOf(HF_REPO_ID_SEPARATOR);
+
+ return at === -1 ? ['', repoId] : [repoId.slice(0, at), repoId.slice(at + 1)];
+}
diff --git a/ui/lib/huggingface/tests/client.test.ts b/ui/lib/huggingface/tests/client.test.ts
new file mode 100644
index 000000000..3538c06d1
--- /dev/null
+++ b/ui/lib/huggingface/tests/client.test.ts
@@ -0,0 +1,190 @@
+import {
+ authorizationUrl,
+ createCodeChallenge,
+ createRandomString,
+ exchangeCode,
+ hasScope,
+ refreshTokens,
+ registerClient
+} from '../src/index.js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const REDIRECT = 'http://192.168.1.5:8080/?hf_oauth=1';
+const SCOPES = ['openid', 'profile', 'contribute-repos'];
+const LOGO = 'https://example.com/logo.svg';
+const CLIENT = {
+ clientName: 'Test app',
+ logoUrl: LOGO,
+ redirectUrl: REDIRECT,
+ scopes: SCOPES
+};
+
+interface Call {
+ url: string;
+ init?: RequestInit;
+}
+
+let calls: Call[];
+
+function respond(handler: (url: string) => Response) {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: string, init?: RequestInit) => {
+ calls.push({ init, url });
+
+ return handler(url);
+ })
+ );
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status });
+}
+
+beforeEach(() => {
+ calls = [];
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+describe('OAuth client', () => {
+ it('derives the S256 challenge of a verifier (RFC 7636 appendix B)', async () => {
+ expect(await createCodeChallenge('dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk')).toBe(
+ 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM'
+ );
+ });
+
+ it('makes random strings URL-safe and different each time', () => {
+ expect(createRandomString()).toMatch(/^[\w-]{43}$/);
+ expect(createRandomString()).not.toBe(createRandomString());
+ });
+
+ it('registers a public client for the redirect URL with its scopes', async () => {
+ respond(() => json({ client_id: 'client-1' }, 201));
+
+ const clientId = await registerClient(CLIENT);
+ const body = JSON.parse(calls[0].init?.body as string);
+
+ expect(clientId).toBe('client-1');
+ expect(calls[0].url).toBe('https://huggingface.co/oauth/register');
+ expect(body).toMatchObject({
+ client_name: 'Test app',
+ logo_uri: LOGO,
+ redirect_uris: [REDIRECT],
+ response_types: ['code'],
+ scope: 'openid profile contribute-repos',
+ token_endpoint_auth_method: 'none'
+ });
+ });
+
+ it('says which origin Hugging Face would not register', async () => {
+ respond(() => json({ error: 'invalid_redirect_uri', error_description: 'not allowed' }, 400));
+
+ await expect(registerClient(CLIENT)).rejects.toThrow(
+ 'Hugging Face does not allow signing in from http://192.168.1.5:8080 (invalid_redirect_uri: not allowed).'
+ );
+ });
+
+ it('reports a registration it could not send', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')));
+
+ await expect(registerClient(CLIENT)).rejects.toThrow(
+ 'Could not reach Hugging Face to start the sign-in.'
+ );
+ });
+
+ it('builds the authorization URL with PKCE and the state', () => {
+ const url = authorizationUrl({
+ clientId: 'client-1',
+ codeChallenge: 'challenge',
+ redirectUrl: REDIRECT,
+ scopes: SCOPES,
+ state: 'state-1'
+ });
+
+ expect(url.origin + url.pathname).toBe('https://huggingface.co/oauth/authorize');
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ client_id: 'client-1',
+ code_challenge: 'challenge',
+ code_challenge_method: 'S256',
+ redirect_uri: REDIRECT,
+ response_type: 'code',
+ scope: 'openid profile contribute-repos',
+ state: 'state-1'
+ });
+ });
+
+ it('trades a code for tokens without a client secret', async () => {
+ vi.useFakeTimers({ now: 1_000_000 });
+ respond(() =>
+ json({
+ access_token: 'hf_oauth_a',
+ expires_in: 3600,
+ refresh_token: 'r1',
+ scope: 'openid profile contribute-repos',
+ token_type: 'bearer'
+ })
+ );
+
+ const tokens = await exchangeCode({
+ clientId: 'client-1',
+ code: 'code-1',
+ codeVerifier: 'verifier-1',
+ redirectUrl: REDIRECT
+ });
+ const sent = new URLSearchParams(calls[0].init?.body as string);
+
+ expect(calls[0].url).toBe('https://huggingface.co/oauth/token');
+ expect(Object.fromEntries(sent)).toEqual({
+ client_id: 'client-1',
+ code: 'code-1',
+ code_verifier: 'verifier-1',
+ grant_type: 'authorization_code',
+ redirect_uri: REDIRECT
+ });
+ expect(tokens).toEqual({
+ accessToken: 'hf_oauth_a',
+ expiresAt: 1_000_000 + 3_600_000,
+ refreshToken: 'r1',
+ scope: 'openid profile contribute-repos'
+ });
+ });
+
+ it('passes on why a code was refused', async () => {
+ respond(() => json({ error: 'invalid_grant', error_description: 'code expired' }, 400));
+
+ await expect(
+ exchangeCode({
+ clientId: 'c',
+ code: 'x',
+ codeVerifier: 'v',
+ redirectUrl: REDIRECT
+ })
+ ).rejects.toThrow('The sign-in failed: invalid_grant: code expired.');
+ });
+
+ it('keeps the refresh token when a refresh hands out no new one', async () => {
+ respond(() => json({ access_token: 'hf_oauth_b', expires_in: 60 }));
+
+ const tokens = await refreshTokens('client-1', 'r1');
+ const sent = new URLSearchParams(calls[0].init?.body as string);
+
+ expect(sent.get('grant_type')).toBe('refresh_token');
+ expect(sent.get('refresh_token')).toBe('r1');
+ expect(tokens).toMatchObject({
+ accessToken: 'hf_oauth_b',
+ refreshToken: 'r1'
+ });
+ });
+
+ it('tells whether tokens carry a scope', () => {
+ const scope = 'contribute-repos';
+
+ expect(hasScope({ accessToken: 'a', scope: 'openid contribute-repos' }, scope)).toBe(true);
+ expect(hasScope({ accessToken: 'a', scope: 'openid profile' }, scope)).toBe(false);
+ expect(hasScope({ accessToken: 'a' }, scope)).toBe(true);
+ });
+});
diff --git a/ui/lib/huggingface/tests/hub.test.ts b/ui/lib/huggingface/tests/hub.test.ts
new file mode 100644
index 000000000..ceb6411a5
--- /dev/null
+++ b/ui/lib/huggingface/tests/hub.test.ts
@@ -0,0 +1,245 @@
+import {
+ ensureDataset,
+ HF_REGULAR_FILE_MAX_BYTES,
+ HfNotWritableError,
+ listDatasets,
+ uploadTrace,
+ whoAmI
+} from '../src/index.js';
+import {
+ HF_MS_PER_SECOND,
+ HF_REQUEST_TIMEOUT_MS,
+ HF_UPLOAD_MIN_BYTES_PER_SECOND
+} from '../src/constants.js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const TOKEN = 'hf_test';
+
+interface Call {
+ url: string;
+ init?: RequestInit;
+}
+
+let calls: Call[];
+
+function respond(routes: Record<string, () => Response>) {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (input: string | URL, init?: RequestInit) => {
+ const url = String(input);
+
+ calls.push({ init, url });
+
+ const route = Object.keys(routes).find((key) => url.endsWith(key));
+
+ if (!route) throw new Error(`unexpected request: ${url}`);
+
+ return routes[route]();
+ })
+ );
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status });
+}
+
+const upload = {
+ commitMessage: 'Add trace: test',
+ content: '{"type":"session","harness":"llama.app","id":"c1"}',
+ isPrivate: true,
+ path: 'trace.jsonl',
+ repoId: 'me/llama-chat-traces'
+};
+
+beforeEach(() => {
+ calls = [];
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('Hub calls', () => {
+ it('reads the account and its token role', async () => {
+ respond({
+ '/api/whoami-v2': () =>
+ json({ auth: { accessToken: { role: 'write' } }, name: 'me', orgs: [{ name: 'org' }] })
+ });
+
+ const user = await whoAmI(TOKEN);
+
+ expect(user).toMatchObject({ name: 'me', tokenRole: 'write' });
+ expect(new Headers(calls[0].init?.headers).get('Authorization')).toBe(`Bearer ${TOKEN}`);
+ });
+
+ it('knows no account for a token the Hub rejects', async () => {
+ respond({ '/api/whoami-v2': () => json({ error: 'Invalid credentials' }, 401) });
+
+ expect(await whoAmI(TOKEN)).toBeNull();
+ });
+
+ it('passes on other Hub errors', async () => {
+ respond({ '/api/whoami-v2': () => json({ error: 'Rate limited' }, 429) });
+
+ await expect(whoAmI(TOKEN)).rejects.toThrow('Rate limited');
+ });
+
+ it('lists the account datasets, newest first, private ones marked', async () => {
+ respond({
+ '/api/datasets?direction=-1&limit=100&sort=lastModified&author=me': () =>
+ json([
+ { id: 'me/llama-chat-traces', private: false },
+ { id: 'me/secret', private: true }
+ ])
+ });
+
+ const datasets = await listDatasets(TOKEN, 'me');
+
+ expect(datasets).toEqual([
+ { id: 'me/llama-chat-traces', isPrivate: false },
+ { id: 'me/secret', isPrivate: true }
+ ]);
+ expect(new Headers(calls[0].init?.headers).get('Authorization')).toBe(`Bearer ${TOKEN}`);
+ });
+
+ it('creates a missing dataset, then commits the trace as one regular file', async () => {
+ respond({
+ '/api/datasets/me/llama-chat-traces': () => json({ error: 'not found' }, 404),
+ '/api/datasets/me/llama-chat-traces/commit/main': () => json({ commitUrl: 'x' }),
+ '/api/datasets/me/llama-chat-traces/preupload/main': () =>
+ json({ files: [{ path: 'trace.jsonl', uploadMode: 'regular' }] }),
+ '/api/repos/create': () => json({ url: 'x' })
+ });
+
+ const url = await uploadTrace(TOKEN, upload);
+
+ expect(url).toBe('https://huggingface.co/datasets/me/llama-chat-traces/blob/main/trace.jsonl');
+ expect(JSON.parse(String(calls[1].init?.body))).toEqual({
+ name: 'llama-chat-traces',
+ organization: 'me',
+ private: true,
+ type: 'dataset'
+ });
+
+ const [header, file] = String(calls[3].init?.body)
+ .split('\n')
+ .map((line) => JSON.parse(line));
+
+ expect(header).toEqual({
+ key: 'header',
+ value: { description: '', summary: upload.commitMessage }
+ });
+ expect(file.key).toBe('file');
+ expect(file.value.path).toBe('trace.jsonl');
+ expect(atob(file.value.content)).toBe(upload.content);
+ });
+
+ it('leaves an existing dataset as it is', async () => {
+ respond({
+ '/api/datasets/me/llama-chat-traces': () => json({ id: 'me/llama-chat-traces' }),
+ '/commit/main': () => json({}),
+ '/preupload/main': () => json({ files: [{ uploadMode: 'regular' }] })
+ });
+
+ await uploadTrace(TOKEN, upload);
+
+ expect(calls.some((call) => call.url.endsWith('/api/repos/create'))).toBe(false);
+ });
+
+ it('refuses a dataset that stores .jsonl with LFS', async () => {
+ respond({
+ '/api/datasets/me/llama-chat-traces': () => json({}),
+ '/preupload/main': () => json({ files: [{ uploadMode: 'lfs' }] })
+ });
+
+ await expect(uploadTrace(TOKEN, upload)).rejects.toThrow('LFS');
+ });
+
+ it('explains a dataset the sign-in may not write to', async () => {
+ respond({
+ '/api/datasets/me/llama-chat-traces': () => json({}),
+ '/preupload/main': () => json({ error: 'Forbidden' }, 403)
+ });
+
+ await expect(uploadTrace(TOKEN, upload)).rejects.toThrow('datasets it created');
+ await expect(uploadTrace(TOKEN, upload)).rejects.toMatchObject({
+ name: 'HfNotWritableError',
+ repoId: 'me/llama-chat-traces'
+ });
+ await expect(uploadTrace(TOKEN, upload)).rejects.toBeInstanceOf(HfNotWritableError);
+ });
+
+ it('explains a dataset the sign-in cannot see, which it cannot create either', async () => {
+ respond({
+ '/api/datasets/me/llama-chat-traces': () => json({ error: 'Not found' }, 404),
+ '/api/repos/create': () => json({ error: 'You already created this dataset repo' }, 409)
+ });
+
+ await expect(uploadTrace(TOKEN, upload)).rejects.toThrow(
+ 'You cannot add traces to me/llama-chat-traces.'
+ );
+ });
+
+ it('refuses a trace too large for a regular commit before any request', async () => {
+ respond({});
+
+ await expect(
+ uploadTrace(TOKEN, {
+ ...upload,
+ content: 'x'.repeat(HF_REGULAR_FILE_MAX_BYTES + 1)
+ })
+ ).rejects.toThrow('too large');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('gives up on a call the Hub does not answer, instead of waiting for good', async () => {
+ respond({
+ '/api/datasets/me/llama-chat-traces': () => json({}),
+ '/preupload/main': () => {
+ throw new DOMException('The operation timed out.', 'TimeoutError');
+ }
+ });
+
+ await expect(uploadTrace(TOKEN, upload)).rejects.toThrow('did not answer in time');
+ // every call carries the time limit
+ expect(calls.every((call) => call.init?.signal instanceof AbortSignal)).toBe(true);
+ });
+
+ it('refuses a dataset name that is not owner/name before any request', async () => {
+ respond({});
+
+ await expect(uploadTrace(TOKEN, { ...upload, repoId: 'owner/name/extra' })).rejects.toThrow(
+ 'owner/name'
+ );
+ await expect(ensureDataset(TOKEN, 'name', false)).rejects.toThrow('owner/name');
+ expect(calls).toHaveLength(0);
+ });
+
+ it('gives a large body the time to go out, on top of the usual limit', async () => {
+ const timeouts: number[] = [];
+ const timeout = AbortSignal.timeout.bind(AbortSignal);
+
+ vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms: number) => {
+ timeouts.push(ms);
+
+ return timeout(ms);
+ });
+ respond({
+ '/api/datasets/me/llama-chat-traces': () => json({}),
+ '/commit/main': () => json({}),
+ '/preupload/main': () => json({ files: [{ uploadMode: 'regular' }] })
+ });
+
+ const content = 'x'.repeat(4 * HF_UPLOAD_MIN_BYTES_PER_SECOND);
+
+ await uploadTrace(TOKEN, { ...upload, content });
+
+ // the lookup and the check carry little; the commit carries the file, base64 encoded
+ const encoded = Math.ceil((content.length * 4) / 3 / HF_UPLOAD_MIN_BYTES_PER_SECOND);
+
+ expect(timeouts[0]).toBe(HF_REQUEST_TIMEOUT_MS);
+ expect(timeouts.at(-1)).toBeGreaterThanOrEqual(
+ HF_REQUEST_TIMEOUT_MS + encoded * HF_MS_PER_SECOND
+ );
+ });
+});
diff --git a/ui/lib/huggingface/tests/sign-in.test.ts b/ui/lib/huggingface/tests/sign-in.test.ts
new file mode 100644
index 000000000..60c61ce71
--- /dev/null
+++ b/ui/lib/huggingface/tests/sign-in.test.ts
@@ -0,0 +1,287 @@
+import { HfOAuthSignIn, type HfOAuthResult } from '../src/index.js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const APP_URL = 'http://localhost:8080/';
+const STORAGE_KEY = 'test.hfOAuth';
+const SCOPE = 'openid profile contribute-repos';
+
+let requests: { body?: string; url: string }[];
+let results: HfOAuthResult[];
+let storage: Map<string, string>;
+let tokenResponse: () => Response;
+let registerResponse: () => Response;
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status });
+}
+
+function createSignIn(logoUrl?: string): HfOAuthSignIn {
+ return new HfOAuthSignIn({
+ callbackUrl: () => APP_URL,
+ clientName: 'Test app',
+ logoUrl,
+ onResult: (result) => results.push(result),
+ requiredScope: 'contribute-repos',
+ scopes: SCOPE.split(' '),
+ storageKey: STORAGE_KEY
+ });
+}
+
+function fakePopup() {
+ return { close: vi.fn(), location: { href: '' } };
+}
+
+function stored() {
+ return JSON.parse(storage.get(STORAGE_KEY) ?? '{}');
+}
+
+/** Starts a sign-in in a popup and returns the address Hugging Face would send it back to. */
+async function start(signIn: HfOAuthSignIn, popup = fakePopup()): Promise<URL> {
+ await signIn.start(popup as unknown as Window);
+
+ const callback = new URL(signIn.redirectUrl);
+
+ callback.searchParams.set('code', 'code-1');
+ callback.searchParams.set('state', new URL(popup.location.href).searchParams.get('state') ?? '');
+
+ return callback;
+}
+
+beforeEach(() => {
+ requests = [];
+ results = [];
+ storage = new Map();
+ registerResponse = () => json({ client_id: 'client-1' }, 201);
+ tokenResponse = () =>
+ json({
+ access_token: 'hf_oauth_a',
+ expires_in: 3600,
+ refresh_token: 'r1',
+ scope: SCOPE
+ });
+
+ vi.stubGlobal('localStorage', {
+ getItem: (key: string) => storage.get(key) ?? null,
+ setItem: (key: string, value: string) => void storage.set(key, value)
+ });
+ vi.stubGlobal('window', {
+ history: { replaceState: vi.fn(), state: null },
+ location: { assign: vi.fn(), href: APP_URL, replace: vi.fn() }
+ });
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: string, init?: RequestInit) => {
+ requests.push({ body: init?.body as string | undefined, url });
+
+ return url.endsWith('/oauth/register') ? registerResponse() : tokenResponse();
+ })
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('HfOAuthSignIn', () => {
+ it('signs in through a popup', async () => {
+ const signIn = createSignIn();
+ const popup = fakePopup();
+ const callback = await start(signIn, popup);
+ const authorization = new URL(popup.location.href);
+
+ expect(authorization.origin + authorization.pathname).toBe(
+ 'https://huggingface.co/oauth/authorize'
+ );
+ expect(authorization.searchParams.get('redirect_uri')).toBe(`${APP_URL}?hf_oauth=1`);
+
+ expect(await signIn.complete(callback)).toEqual({
+ closeWindow: true,
+ result: { ok: true }
+ });
+ expect(results).toEqual([{ ok: true }]);
+ expect(signIn.accessToken).toBe('hf_oauth_a');
+ expect(await signIn.freshToken()).toBe('hf_oauth_a');
+
+ const exchange = new URLSearchParams(requests.at(-1)?.body);
+
+ expect(exchange.get('code')).toBe('code-1');
+ expect(exchange.get('code_verifier')).toMatch(/^[\w-]{43}$/);
+ });
+
+ it('sends this tab to the authorization page without a popup, then back', async () => {
+ const signIn = createSignIn();
+
+ window.location.href = `${APP_URL}#/chat/1`;
+ await signIn.start(null);
+
+ const authorization = new URL(vi.mocked(window.location.assign).mock.calls[0][0] as string);
+ const callback = new URL(signIn.redirectUrl);
+
+ callback.searchParams.set('code', 'code-1');
+ callback.searchParams.set('state', authorization.searchParams.get('state') ?? '');
+
+ expect(await signIn.complete(callback)).toEqual({
+ closeWindow: false,
+ result: { ok: true }
+ });
+ expect(window.location.replace).toHaveBeenCalledWith(`${APP_URL}#/chat/1`);
+ });
+
+ it('ignores page loads that are not a callback, and callbacks it did not start', async () => {
+ const signIn = createSignIn();
+ const callback = await start(signIn);
+
+ callback.searchParams.set('state', 'forged');
+
+ expect(await signIn.complete(new URL(APP_URL))).toBeNull();
+ expect(await signIn.complete(callback)).toEqual({
+ closeWindow: false,
+ result: null
+ });
+ expect(requests.some((request) => request.url.endsWith('/oauth/token'))).toBe(false);
+ });
+
+ it('reuses the registered client on the next sign-in', async () => {
+ const signIn = createSignIn();
+
+ await signIn.complete(await start(signIn));
+ signIn.signOut();
+ await start(signIn);
+
+ expect(requests.filter((request) => request.url.endsWith('/oauth/register'))).toHaveLength(1);
+ expect(stored().tokens).toBeUndefined();
+ });
+
+ it('registers again when the app gets a logo', async () => {
+ await start(createSignIn());
+ await start(createSignIn('https://example.com/logo.svg'));
+
+ const registrations = requests.filter((request) => request.url.endsWith('/oauth/register'));
+
+ expect(registrations).toHaveLength(2);
+ expect(JSON.parse(registrations[1].body ?? '{}').logo_uri).toBe('https://example.com/logo.svg');
+ });
+
+ it('says so on a page that is not secure, and registers nothing', async () => {
+ vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) });
+
+ const popup = fakePopup();
+
+ await expect(createSignIn().start(popup as unknown as Window)).rejects.toThrow('secure page');
+ expect(popup.close).toHaveBeenCalled();
+ expect(requests).toEqual([]);
+ });
+
+ it('closes the popup when Hugging Face will not register the app', async () => {
+ registerResponse = () => json({ error: 'invalid_redirect_uri' }, 400);
+
+ const popup = fakePopup();
+
+ await expect(createSignIn().start(popup as unknown as Window)).rejects.toThrow(
+ 'does not allow signing in from'
+ );
+ expect(popup.close).toHaveBeenCalled();
+ });
+
+ it('refuses tokens without the scope the app needs', async () => {
+ tokenResponse = () => json({ access_token: 'hf_oauth_a', scope: 'openid profile' });
+
+ const signIn = createSignIn();
+ const outcome = await signIn.complete(await start(signIn));
+
+ expect(outcome?.result?.ok).toBe(false);
+ expect(signIn.accessToken).toBeNull();
+ });
+
+ it('says when the user turned the sign-in down', async () => {
+ const signIn = createSignIn();
+ const callback = await start(signIn);
+
+ callback.searchParams.delete('code');
+ callback.searchParams.set('error', 'access_denied');
+
+ expect((await signIn.complete(callback))?.result).toEqual({
+ error: 'The sign-in was cancelled.',
+ ok: false
+ });
+ });
+
+ it('renews an expired token with its refresh token', async () => {
+ tokenResponse = () =>
+ json({
+ access_token: 'hf_oauth_a',
+ expires_in: 0,
+ refresh_token: 'r1',
+ scope: SCOPE
+ });
+
+ const signIn = createSignIn();
+
+ await signIn.complete(await start(signIn));
+ tokenResponse = () => json({ access_token: 'hf_oauth_b', expires_in: 3600 });
+
+ expect(await signIn.freshToken()).toBe('hf_oauth_b');
+ expect(new URLSearchParams(requests.at(-1)?.body).get('grant_type')).toBe('refresh_token');
+ expect(stored().tokens).toMatchObject({
+ accessToken: 'hf_oauth_b',
+ refreshToken: 'r1'
+ });
+ });
+
+ it('takes the token another tab renewed when its own refresh is refused', async () => {
+ tokenResponse = () =>
+ json({
+ access_token: 'hf_oauth_a',
+ expires_in: 0,
+ refresh_token: 'r1',
+ scope: SCOPE
+ });
+
+ const signIn = createSignIn();
+
+ await signIn.complete(await start(signIn));
+ tokenResponse = () => {
+ const record = stored();
+
+ storage.set(
+ STORAGE_KEY,
+ JSON.stringify({
+ ...record,
+ tokens: { accessToken: 'hf_oauth_c', refreshToken: 'r2' }
+ })
+ );
+
+ return json({ error: 'invalid_grant' }, 400);
+ };
+
+ expect(await signIn.freshToken()).toBe('hf_oauth_c');
+ });
+
+ it('forgets a sign-in whose refresh token Hugging Face turned down for good', async () => {
+ tokenResponse = () =>
+ json({ access_token: 'hf_oauth_a', expires_in: 0, refresh_token: 'r1', scope: SCOPE });
+
+ const signIn = createSignIn();
+
+ await signIn.complete(await start(signIn));
+ tokenResponse = () => json({ error: 'invalid_grant' }, 400);
+
+ expect(await signIn.freshToken()).toBeNull();
+ expect(stored().tokens).toBeUndefined();
+ // the registered client stays for the next sign-in
+ expect(stored().clientId).toBe('client-1');
+ });
+
+ it('keeps a sign-in it could not renew because Hugging Face failed', async () => {
+ tokenResponse = () =>
+ json({ access_token: 'hf_oauth_a', expires_in: 0, refresh_token: 'r1', scope: SCOPE });
+
+ const signIn = createSignIn();
+
+ await signIn.complete(await start(signIn));
+ tokenResponse = () => json({ error: 'unavailable' }, 503);
+
+ await expect(signIn.freshToken()).rejects.toThrow('Renewing the sign-in failed');
+ expect(stored().tokens).toMatchObject({ accessToken: 'hf_oauth_a', refreshToken: 'r1' });
+ });
+});
diff --git a/ui/lib/huggingface/tsconfig.json b/ui/lib/huggingface/tsconfig.json
new file mode 100644
index 000000000..dce869073
--- /dev/null
+++ b/ui/lib/huggingface/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", "svelte"]
+ },
+ "include": ["src/**/*.ts", "tests"]
+}
diff --git a/ui/lib/huggingface/vitest.config.ts b/ui/lib/huggingface/vitest.config.ts
new file mode 100644
index 000000000..d49f1d4d6
--- /dev/null
+++ b/ui/lib/huggingface/vitest.config.ts
@@ -0,0 +1,5 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: { environment: 'node', include: ['tests/**/*.test.ts'] }
+});