ui: open settings, the + menu and the model picker as sheets on phones, and manage MCP from settings (#33036)
Some checks failed
Behavior Check / ubuntu (push) Waiting to run
Behavior Check / windows (push) Waiting to run
CI (3rd-party) / ubuntu-26-llguidance (push) Waiting to run
CI (android) / default (push) Waiting to run
CI (android) / ndk (push) Waiting to run
CI (android) / arm64 (push) Waiting to run
CI (apple) / macos-latest-arm64 (push) Waiting to run
CI (cpu) / ubuntu (arm64, ubuntu-26.04-arm) (push) Waiting to run
CI (cpu) / ubuntu (x64, ubuntu-26.04) (push) Waiting to run
CI (cpu) / windows / arm64 (push) Waiting to run
CI (cpu) / windows / x64-cpu-static (push) Waiting to run
CI (cpu) / windows / x64-openblas (push) Waiting to run
CI (cpu) / build-cmake-pkg (push) Waiting to run
CI (CUDA, ubuntu) / cuda (push) Waiting to run
CI (CUDA, ubuntu) / hip (push) Waiting to run
CI (CUDA, ubuntu) / musa (push) Waiting to run
CI (ibm) / ubuntu-26-s390x (VXE OFF) (push) Waiting to run
CI (ibm) / ubuntu-26-s390x (VXE ON) (push) Waiting to run
CI (ibm) / ubuntu-26-zdnn-s390x (push) Waiting to run
CI (ibm) / ubuntu-26-ppc64le (push) Waiting to run
CI (opencl) / windows-2025-opencl-adreno (push) Waiting to run
CI (openvino) / openvino-windows-2022 (push) Waiting to run
Release / ubuntu-cpu (s390x, ubuntu-24.04-s390x) (push) Blocked by required conditions
Release / ubuntu-cpu (x64, ubuntu-22.04) (push) Blocked by required conditions
CI (riscv) / ubuntu-cpu-riscv64-native (push) Waiting to run
CI (sanitize) / ctest (ubuntu-26.04, ADDRESS) (push) Waiting to run
CI (sanitize) / ctest (ubuntu-26.04, THREAD) (push) Waiting to run
CI (sanitize) / ctest (ubuntu-26.04, UNDEFINED) (push) Waiting to run
CI (sycl) / ubuntu-26-sycl (fp16, ON) (push) Waiting to run
CI (sycl) / ubuntu-26-sycl (fp32, OFF) (push) Waiting to run
CI (sycl) / windows-latest-sycl (push) Waiting to run
CI (virtgpu) / ubuntu-26-virtgpu (push) Waiting to run
CI (vulkan) / ubuntu (push) Waiting to run
CI (vulkan) / ubuntu-llvmpipe (push) Waiting to run
CI (vulkan) / windows / arm64 (push) Waiting to run
CI (vulkan) / windows / x64 (push) Waiting to run
CI (wasi) / ubuntu-webgpu (push) Waiting to run
CI (wasm) / ubuntu-webgpu (push) Waiting to run
CI (self-hosted CPU backend) / cpu-arm64-high-perf-graviton4 (push) Waiting to run
CI (self-hosted CPU backend) / cpu-x64-high-perf (push) Waiting to run
CI (self-hosted CUDA backend) / gpu-cuda (push) Waiting to run
CI (self-hosted CUDA backend) / gpu-rocm (gfx1151) (push) Waiting to run
CI (self-hosted CUDA backend) / gpu-rocm (gfx1201) (push) Waiting to run
CI (self-hosted KleidiAI backend) / cpu-arm64-graviton4-kleidiai (push) Waiting to run
CI (self-hosted Metal backend) / gpu-metal (push) Waiting to run
CI (self-hosted OpenVINO backend) / gpu-openvino-low-perf (push) Waiting to run
CI (self-hosted Vulkan backend) / gpu-vulkan-nvidia-cm (push) Waiting to run
CI (self-hosted Vulkan backend) / gpu-vulkan-nvidia-cm2 (push) Waiting to run
CI (self-hosted Vulkan backend) / gpu-vulkan-apple (push) Waiting to run
CI (self-hosted Vulkan backend) / gpu-vulkan-intel-linux (push) Waiting to run
CI (self-hosted Vulkan backend) / gpu-vulkan-intel-windows (push) Waiting to run
CI (self-hosted WebGPU backend) / gpu-webgpu-nvidia (push) Waiting to run
CI (self-hosted WebGPU backend) / gpu-webgpu-apple (push) Waiting to run
Code Style Checker / model-naming (push) Waiting to run
EditorConfig Checker / editorconfig (push) Waiting to run
HIP quality check / ubuntu-22-hip-quality-check (push) Waiting to run
Models Backend Check / cuda (push) Waiting to run
Models Backend Check / metal (push) Waiting to run
Models Backend Check / rocm (push) Waiting to run
Models Backend Check / vulkan-nvidia (push) Waiting to run
Models Backend Check / vulkan-amd (push) Waiting to run
Models Backend Check / webgpu-nvidia (push) Waiting to run
flake8 Lint / Lint (push) Waiting to run
Python Type-Check / python type-check (push) Waiting to run
Release / check-release (push) Waiting to run
Release / macos-cpu (arm64, arm64, -DGGML_METAL_EMBED_LIBRARY=ON -DCMAKE_OSX_DEPLOYMENT_TARGET=13.3, macos-26) (push) Blocked by required conditions
Release / macos-cpu (x64, x64, -DGGML_METAL=OFF -DCMAKE_OSX_DEPLOYMENT_TARGET=13.3, macos-15-intel) (push) Blocked by required conditions
Release / ubuntu-cpu (26.04-s390x, ubuntu-26.04-s390x) (push) Blocked by required conditions
Release / ubuntu-cpu (arm64, ubuntu-24.04-arm) (push) Blocked by required conditions
Release / ubuntu-vulkan (arm64, ubuntu-24.04-arm) (push) Blocked by required conditions
Release / ubuntu-vulkan (x64, ubuntu-22.04) (push) Blocked by required conditions
Release / ubuntu-cuda (13.5, arm64) (push) Blocked by required conditions
Release / ubuntu-cuda (12.8, x64) (push) Blocked by required conditions
Release / ubuntu-cuda (13.5, x64) (push) Blocked by required conditions
Release / android-arm64 (push) Blocked by required conditions
Release / android-arm64-snapdragon (push) Blocked by required conditions
Release / linux-arm64-snapdragon (push) Blocked by required conditions
Release / ubuntu-24-openvino (push) Blocked by required conditions
Release / windows-openvino (push) Blocked by required conditions
Release / windows-cpu / arm64 (push) Blocked by required conditions
Release / windows-cpu / x64 (push) Blocked by required conditions
Release / windows-rocm (10.0.0, x64, gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1153;gfx1200;gfx1201) (push) Blocked by required conditions
Release / windows (arm64, opencl-adreno, -G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON -DGGML_OPENCL_ADRENO_BIN_KERN… (push) Blocked by required conditions
Release / windows (arm64, vulkan, -G "Ninja Multi-Config" -DGGML_VULKAN=ON -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake, ggml-vulkan) (push) Blocked by required conditions
Release / windows (x64, vulkan, -DGGML_VULKAN=ON, ggml-vulkan) (push) Blocked by required conditions
Release / windows-cuda (13.5, arm64) (push) Blocked by required conditions
Release / windows-cuda (12.4, x64) (push) Blocked by required conditions
Release / windows-cuda (13.5, x64) (push) Blocked by required conditions
Release / windows-sycl (push) Blocked by required conditions
Release / ubuntu-24-sycl (fp16, ON) (push) Blocked by required conditions
Release / ubuntu-24-sycl (fp32, OFF) (push) Blocked by required conditions
Release / ubuntu-24-rocm (10.0.0, x64, gfx908;gfx90a;gfx942;gfx950;gfx1010;gfx1011;gfx1012;gfx1030;gfx1031;gfx1032;gfx1033;gfx1034;gfx1035;gfx1036;gfx1100;gfx1101;gfx1102;gfx1103;gfx1150;gfx1151;gfx1152;gfx1200;gfx1201) (push) Blocked by required conditions
Release / ubuntu-26-zdnn (push) Blocked by required conditions
Release / ios-xcode (push) Blocked by required conditions
Release / ui-build (push) Blocked by required conditions
Server (sanitize) / server (RelWithDebInfo, ADDRESS) (push) Waiting to run
Server (sanitize) / server (RelWithDebInfo, UNDEFINED) (push) Waiting to run
Server (self-hosted) / server-cuda (push) Waiting to run
Server (self-hosted) / server-metal (push) Waiting to run
Server (self-hosted) / server-kleidiai (push) Waiting to run
Server / ubuntu (push) Waiting to run
Server / windows (push) Waiting to run
UI (self-hosted) / E2E Tests (push) Blocked by required conditions
UI (self-hosted) / Build static output (push) Waiting to run
UI (self-hosted) / Checks (push) Blocked by required conditions
UI Storybook / Deploy to Hugging Face Spaces (push) Waiting to run
UI / Build static output (push) Waiting to run
UI / Checks (push) Blocked by required conditions
UI / Library checks (push) Waiting to run
UI / Voice checks (push) Waiting to run
UI / Harness checks (push) Waiting to run
UI / Chat-only build (push) Waiting to run
UI / E2E Tests (push) Blocked by required conditions
Check Pre-Tokenizer Hashes / pre-tokenizer-hashes (push) Has been cancelled
Python check requirements.txt / check-requirements (push) Has been cancelled

* ui: add inset lists, rounder bottom sheets and a native select to the design system

Inset lists (grouped rows with inset dividers, titles and captions) are surface utilities in llama-ui, documented in DESIGN.md and the Surfaces story. Bottom drawers get the sheet radius and rounder inset groups, switches a finger-sized variant, and SearchInput an inputClass prop.

NativeSelect is a trigger styled like the app's select that opens the OS's own picker, and useSheetPages a page stack with slide transitions for sheets.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: open settings and the add menu on phones as sheets of inset pages, and manage MCP from settings

On a phone, Settings is a full-height sheet over the sidebar: theme tiles, then a row per section that pushes the section's page, with Tools, tool groups and MCP servers as further pages. Changes apply as they are made. Selects open the OS picker, number fields are 16px so iOS does not zoom, and switches are finger-sized.

The + menu is a sheet of the same inset pages, which stays open while the file picker is up. Settings and a primary New chat button sit at the bottom of the phone sidebar, and Show less sticks to the bottom of the chat list.

Show MCP becomes Enable MCP: while it is off, no MCP server is connected and chats get no MCP tools. The servers are managed from Settings, in a dialog on the desktop and a page in the phone sheet; the sidebar entry and /mcp-servers are removed. Someone who already added a server gets Enable MCP on.

A setting can name the devices it applies to, and is listed only there. Switching sections scrolls back to the top, the system message has a placeholder, inputs offer no browser autofill, the desktop settings sidebar sits on the dialog's background, and the sidebar footer groups its rows only when it shows more than one.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: pick models on a phone from a short sheet, and list the desktop selector's models without a Local models section

On a phone, the model picker opens on a short view: the chat's model, the dictation model, loaded models, favorites and recent ones, marked In chat and Dictation. A tap switches the model; holding a row opens its menu, with More details and Unload for a loaded model. All models is a page of its own, in the same grouped rows. The reasoning effort keeps its list of levels, above the search, which is a SearchInput at the foot of the sheet in the chat form's surface.

On the desktop, the server's models are listed in their family groups without a Local models section around them. They sit in an Other models section only when favorites or loaded models are listed above them, and the section headings have no icons.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: let demos touch, hold and seed chats, and import traces through either settings section

demo.tap and demo.hold drive touch input on a phone viewport, a chats option seeds the sidebar with conversations, and trace imports find Data or Import/Export in the settings.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: release llama-ui 0.7.0 and llama-chat 0.3.0

Llama UI gains the sheet components (SheetHeader, SheetPages, InsetList and its rows) and NativeSelect; Llama Chat gains the phone sheets and Enable MCP.

Assisted-by: Claude (Opus 5.5 Medium)
This commit is contained in:
Aleksander Grygier 2026-11-25 22:39:55 +01:00 • committed by GitHub
parent 7135e2fd69
commit 9c003a97ab
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
103 changed files with 4319 additions and 738 deletions

View file

@ -51,6 +51,7 @@ const preview: Preview = {
[
'Foundations',
['Safe areas', 'Brand'],
'Mobile',
'Chat',
[
'ChatScreen',
@ -65,7 +66,7 @@ const preview: Preview = {
'MCP',
'Navigation',
'Settings',
['DialogSettingsChat', 'Navigation', 'Sections'],
['DialogSettingsChat', 'SettingsSheet', 'Navigation', 'Sections'],
'Dialogs',
'Forms',
'Actions',

View file

@ -3,7 +3,7 @@
These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/<name>`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. The agentic loop is `ui/lib/harness` (`@ggml-org/llama-harness`).
- **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual. Its token sections (`colors`, `typography`, `rounded`) are generated from the CSS with `npm run design:tokens`, and CI checks they are current; the rest is written by hand, and when it and the CSS disagree, the CSS wins and DESIGN.md is updated.
- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/<area>`, one folder per `src/lib/components/app/<area>` (`chat/` has one per Chat folder), titled `Llama Chat/<Area>/<Component>`. An accessibility story sits next to its component's, as `<Component>.a11y.stories.svelte`, titled `.../<Component>/Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here.
- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/<area>`, one folder per `src/lib/components/app/<area>` (`chat/` has one per Chat folder), titled `Llama Chat/<Area>/<Component>`. How the app works on a phone (the sidebar's keys, the sheets and the pages each pushes) is written up in `tests/stories/mobile`, titled `Llama Chat/Mobile/Flows`: update it when a sheet gains or loses a page. An accessibility story sits next to its component's, as `<Component>.a11y.stories.svelte`, titled `.../<Component>/Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here.
- **Releases:** `@ggml-org/llama-chat` and `@ggml-org/llama-ui` are versioned by hand and published by CI when a new version reaches `master` (see [Releases](../../README.md#releases)). Bump a version only when asked to release, never as a side effect of a change; Chat's version and its alias's (`alias/package.json`) always move together.
- **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions.

View file

@ -1097,6 +1097,16 @@ screens. Status lamps, avatars and the round icon buttons in the chat form are f
shade, which makes a field. Unlike the other `matte-glass` surfaces it does not blur: it
already sits on glass, and a second backdrop blur re-paints the panel's fill behind it and
turns the group visibly lighter, whatever its own fill.
- **Inset lists:** a phone's sheets (settings, add to chat, the model picker) list their
options the native way. `inset-list` is an inset group of rows, `inset-list-row` a row a
finger tall (3rem) that is tappable as a whole, and `inset-list-row-body` its label and value,
whose top border is the divider: it starts at the label, past the row's icon, and the first
row has none. `inset-list-title` sits above a group and `inset-list-caption` below it. Inside
a drawer the groups take `--sheet-group-radius` (1.25rem, the chat form's single-row radius) in place of the card radius, to sit
with the sheet's own 2.5rem corners. A sheet's close or back key is `sheet-key`, a round key
1rem from the top and from the side, with the title centered on its middle. Build them with Llama UI's
`InsetList`, `InsetListRow`, `InsetListSplitRow`, `SheetHeader` and `SheetPages`
(`@ggml-org/llama-ui/app/sheets`) rather than with the utilities by hand.
- **Selected rows:** `selected-row-surface` marks the row a sidebar list is on: a
conversation, a project or a top action, on desktop and on a phone. It is a 5% tint of the
text colour, under hover's 10%, with the inset group's edge and shade, so the selected row

View file

@ -1,6 +1,6 @@
{
"name": "llama-chat",
"version": "0.2.0",
"version": "0.3.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.2.0"
"@ggml-org/llama-chat": "0.3.0"
}
}

View file

@ -237,6 +237,26 @@ export class Demo {
this.y = (viewport?.height ?? 0) / 2;
}
/**
* Touches `target` for `ms` and lifts: a tap, or with a longer `ms` a press-and-hold, as a
* phone's held rows ask for. It needs a touch device (`hasTouch`), and shows a fingertip.
*/
async hold(target: Locator, ms = 900, after = 500): Promise<void> {
await target.scrollIntoViewIfNeeded();
const { x, y } = await this.center(target);
const cdp = await this.session();
await this.page.waitForTimeout(this.between(60, 140));
await cdp.send('Input.dispatchTouchEvent', { touchPoints: [{ x, y }], type: 'touchStart' });
await this.page.waitForTimeout(ms);
await cdp.send('Input.dispatchTouchEvent', { touchPoints: [], type: 'touchEnd' });
await this.liftFingers();
this.x = x;
this.y = y;
await this.pause(after);
}
async hover(target: Locator, ms = 350): Promise<void> {
await this.moveTo(target);
await this.pause(ms);
@ -326,6 +346,11 @@ export class Demo {
await this.pause(ms);
}
/** Taps `target` with a fingertip, on a touch device. */
tap(target: Locator, after = 500): Promise<void> {
return this.hold(target, this.between(60, 110), after);
}
/** Types quickly with uneven key timing, a little slower after spaces and punctuation. */
async type(target: Locator, text: string, ms = 500): Promise<void> {
await this.click(target, 200);
@ -447,6 +472,8 @@ export class Demo {
}
interface DemoOptions {
/** Empty conversations added to the library before the demo starts, e.g. to fill a list. */
chats: number;
/** Path the demo starts from. */
startPath: string;
/** Extra UI settings merged into the seeded config. */
@ -478,7 +505,7 @@ function loadTrace(name: string, dir: string): string {
return readFileSync(join(dir, `${name}.jsonl`), 'utf8');
}
/** Imports conversations through Settings > Import/Export, like a user would. */
/** Imports conversations through Settings > Data, like a user would. */
async function importTraces(page: Page, file: string): Promise<void> {
// the expanded sidebar adds the shortcut to the name
const settings = page.getByRole('button', { name: /^Settings(\s|$)/ }).first();
@ -515,7 +542,12 @@ async function importTraces(page: Page, file: string): Promise<void> {
const scope = (await page.getByRole('dialog').count()) > 0 ? page.getByRole('dialog') : page;
await scope.getByText('Import/Export', { exact: true }).filter({ visible: true }).click();
// the section is Data in the regrouped settings, Import/Export before
await scope
.getByText(/^(Data|Import\/Export)$/)
.filter({ visible: true })
.first()
.click();
const chooser = page.waitForEvent('filechooser');
@ -544,11 +576,66 @@ async function importTraces(page: Page, file: string): Promise<void> {
});
}
/** The app's IndexedDB database and its conversations store, which a demo seeds. */
const DEMO_DATABASE = 'LlamaUi';
const DEMO_CONVERSATIONS_STORE = 'conversations';
const HOUR_MS = 3_600_000;
/** Names of the seeded conversations, repeated when a demo asks for more. */
const DEMO_CHAT_NAMES = [
'Plan a trip to Lisbon',
'Explain tail recursion',
'Draft a polite follow-up',
'Summarize this changelog',
'Regex for ISO dates',
'Ideas for a weekend project',
'Debug a flaky test',
'Meal plan for the week'
];
/** Adds `count` empty conversations to the library, so a list has enough chats to fold. */
async function seedChats(page: Page, count: number): Promise<void> {
await page.goto('/');
await page
.getByRole('textbox', { name: 'Type a message...' })
.waitFor({ timeout: APP_READY_TIMEOUT_MS });
await page.evaluate(
async ({ database, hourMs, names, store, total }) => {
const request = indexedDB.open(database);
const db = await new Promise<IDBDatabase>((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
const tx = db.transaction(store, 'readwrite');
for (let i = 0; i < total; i++) {
tx.objectStore(store).put({
currNode: null,
id: `demo-chat-${i}`,
lastModified: Date.now() - i * hourMs,
name: names[i % names.length]
});
}
await new Promise((resolve) => (tx.oncomplete = resolve));
db.close();
},
{
database: DEMO_DATABASE,
hourMs: HOUR_MS,
names: DEMO_CHAT_NAMES,
store: DEMO_CONVERSATIONS_STORE,
total: count
}
);
}
export const test = base.extend<DemoOptions & { demo: Demo }>({
chats: [0, { option: true }],
demo: async ({ page }, use, testInfo) => {
await use(new Demo(page, `${testInfo.file}:${testInfo.title}`));
},
page: async ({ page, settings, startPath, traces }, use, testInfo) => {
page: async ({ chats, page, settings, startPath, traces }, use, testInfo) => {
await page.addInitScript(installCursorOverlay);
await page.addInitScript(seedSettings, {
mcpServers: JSON.stringify(demoMcpServerSettings()),
@ -568,10 +655,12 @@ export const test = base.extend<DemoOptions & { demo: Demo }>({
await importTraces(page, file);
}
if (chats > 0) await seedChats(page, chats);
await page.goto(startPath);
// a hash route after the import doesn't reload, which the conversations list needs
if (traces.length > 0) await page.reload();
if (traces.length > 0 || chats > 0) await page.reload();
// a fresh checkout's dev server optimizes its dependencies on the first load and reloads the
// page, which can take well past an action's timeout; the recording has not started yet

View file

@ -1,12 +1,12 @@
{
"name": "@ggml-org/llama-chat",
"version": "0.2.0",
"version": "0.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ggml-org/llama-chat",
"version": "0.2.0",
"version": "0.3.0",
"license": "MIT",
"bin": {
"llama-chat": "bin/cli.js"

View file

@ -1,6 +1,6 @@
{
"name": "@ggml-org/llama-chat",
"version": "0.2.0",
"version": "0.3.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",

View file

@ -60,8 +60,9 @@
--chat-form-collapsed-height: 6.375rem;
/* the empty chat form card, its text and actions in one row: a new chat centers its top edge */
--chat-form-resting-height: 3.375rem;
/* the chat form's corners while its text and actions share one row */
--chat-form-single-row-radius: 1.25rem;
/* the chat form's corners while its text and actions share one row: a sheet group's, so the
phone sheets' search, groups and keys round alike */
--chat-form-single-row-radius: var(--sheet-group-radius);
/* the card's translucent fill over the page, made opaque: the phone sheet, and the page and Safari's bars around it */
--chat-form-sheet-fill: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page));
--max-message-height: max(24rem, min(80dvh, calc(100dvh - var(--chat-form-area-height) - 12rem)));

View file

@ -198,7 +198,7 @@
hasPrompts: () => {
const prefs = conversationsStore.preferences;
if (!prefs.isCategoryEnabled(ToolSource.MCP)) return false;
if (!mcpStore.isFeatureEnabled || !prefs.isCategoryEnabled(ToolSource.MCP)) return false;
return mcpStore
.getServers()
@ -911,6 +911,7 @@
isVoiceRefining={voice.isRefining}
micWarning={micUnavailableReason ?? micError}
onFileUpload={handleFileUpload}
onFilesSelect={handleFileSelect}
onMicClick={handleMicClick}
{onStop}
onSystemPromptClick={() =>

View file

@ -1,28 +1,42 @@
<script lang="ts">
import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox';
import * as Collapsible from '@ggml-org/llama-ui/ui/collapsible';
import * as Drawer from '@ggml-org/llama-ui/ui/drawer';
import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip';
import {
ChevronDown,
ChevronRight,
InsetList,
InsetListRow,
InsetListSplitRow,
SheetHeader,
SheetPages,
useSheetPages
} from '@ggml-org/llama-ui/app/sheets';
import { SHEET_CONTENT_CLASS } from '@ggml-org/llama-ui/constants';
import * as Drawer from '@ggml-org/llama-ui/ui/drawer';
import { Switch } from '@ggml-org/llama-ui/ui/switch';
import {
Braces,
Camera,
File,
Folder,
Globe,
Info,
Loader2,
MessageSquare,
PencilRuler
PencilRuler,
Server
} from '@lucide/svelte';
import {
ATTACHMENT_FILE_ITEMS,
ATTACHMENT_MENU_TEXT,
ATTACHMENT_MODALITY_TEXT,
ICON_CLASS_DEFAULT,
MODALITY_ICONS
MODALITY_ICONS,
SHEET_SHORT_HEIGHT_CLASS
} from '#lib/constants/index.ts';
import { getChatFormActionsContext } from '#lib/contexts/index.ts';
import { AttachmentAction, AttachmentItemEnabledWhen } from '#lib/enums/attachment.enums.ts';
import { ModelModality } from '#lib/enums/index.ts';
import { AddSheetPage, ModelModality, ToolSource } from '#lib/enums/index.ts';
import { useAttachmentMenu } from '#lib/hooks/use-attachment-menu.svelte.ts';
import { useToolsPanel } from '#lib/hooks/use-tools-panel.svelte.ts';
import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts';
import { toolsStore } from '#lib/stores/index.ts';
import type { ToolGroup } from '#lib/types/index.ts';
import type { Component, Snippet } from 'svelte';
@ -35,8 +49,27 @@
const chatFormActions = getChatFormActionsContext();
/** The sheet's pages: the root menu, the tools list, and one tool group's tools. */
type Page =
| { id: AddSheetPage.ROOT }
| { id: AddSheetPage.TOOLS }
| { groupKey: string; id: AddSheetPage.TOOL_GROUP };
let drawerOpen = $state(false);
let toolsExpanded = $state(false);
const pages = useSheetPages<Page>({ id: AddSheetPage.ROOT });
const page = $derived(pages.page);
const TOOL_SOURCE_ICONS: Partial<Record<ToolSource, Component>> = {
[ToolSource.BROWSER]: Globe,
[ToolSource.CUSTOM]: Braces,
[ToolSource.SERVER]: Server
};
/** What the camera row's picker takes: a photo. */
const CAMERA_ACCEPT = 'image/*';
let cameraInput: HTMLInputElement | undefined = $state();
let filesInput: HTMLInputElement | undefined = $state();
const attachmentMenu = useAttachmentMenu(
() => ({
@ -74,148 +107,278 @@
.filter((modality) => modality !== undefined)
);
// the sheet's own pickers keep it open while the native picker is up; it closes once files arrive
const canPickFiles = $derived(!!chatFormActions.onFilesSelect);
// the camera only makes sense for a model that can see what it gives
const canUseCamera = $derived(chatFormActions.hasVisionModality && canPickFiles);
const toolsPanel = useToolsPanel();
const allGroups = $derived([...toolsPanel.categoryGroups, ...toolsPanel.mcpGroups]);
const enabledToolCount = $derived(
allGroups.reduce((n, group) => n + toolsPanel.getEnabledToolCount(group), 0)
);
const currentGroup = $derived(
page.id === AddSheetPage.TOOL_GROUP
? allGroups.find((group) => group.key === page.groupKey)
: undefined
);
const itemClass =
'flex w-full items-center gap-3 rounded-md px-3 py-2.5 text-left text-body-sm transition-colors hover:bg-accent active:bg-accent disabled:cursor-not-allowed disabled:opacity-50';
const title = $derived.by(() => {
if (page.id === AddSheetPage.TOOLS) return ATTACHMENT_MENU_TEXT.TOOLS;
const itemRowClass =
'flex w-full items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-body-sm transition-colors hover:bg-accent';
if (page.id === AddSheetPage.TOOL_GROUP)
return currentGroup?.label ?? ATTACHMENT_MENU_TEXT.TOOLS;
return ATTACHMENT_MENU_TEXT.ADD_TO_CHAT;
});
function open() {
pages.reset();
drawerOpen = true;
}
function push(next: Page) {
if (next.id === AddSheetPage.TOOLS) toolsPanel.handleOpen();
pages.push(next);
}
function handleAddFiles() {
if (canPickFiles) {
filesInput?.click();
} else {
attachmentMenu.callbacks[AttachmentAction.FILE_UPLOAD]();
}
}
function handleFilesSelect(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const files = input.files ? Array.from(input.files) : [];
// cleared so the same file can be picked again
input.value = '';
if (files.length === 0) return;
drawerOpen = false;
chatFormActions.onFilesSelect?.(files);
}
</script>
<!-- hidden pickers: capture opens the camera on phones, the plain input the system file picker -->
<input
bind:this={cameraInput}
accept={CAMERA_ACCEPT}
capture="environment"
class="hidden"
onchange={handleFilesSelect}
type="file"
/>
<input bind:this={filesInput} class="hidden" multiple onchange={handleFilesSelect} type="file" />
<div class="flex items-center gap-1 {className}">
<Drawer.Root bind:open={drawerOpen}>
{@render trigger({ disabled: chatFormActions.disabled, onclick: () => (drawerOpen = true) })}
{@render trigger({ disabled: chatFormActions.disabled, onclick: open })}
<Drawer.Content class="gap-0 overflow-y-auto">
<Drawer.Header>
<Drawer.Title>{ATTACHMENT_MENU_TEXT.ADD_TO_CHAT}</Drawer.Title>
<Drawer.Content class="gap-0 {SHEET_SHORT_HEIGHT_CLASS} {SHEET_CONTENT_CLASS}">
<SheetHeader canGoBack={pages.canGoBack} onBack={pages.pop} {title} />
<Drawer.Description class="sr-only">
{ATTACHMENT_MENU_TEXT.DESCRIPTION}
</Drawer.Description>
</Drawer.Header>
<Drawer.Description class="sr-only">{ATTACHMENT_MENU_TEXT.DESCRIPTION}</Drawer.Description>
<div class="flex flex-col gap-1 px-1.5 pb-2">
<button
class={itemClass}
onclick={() => attachmentMenu.callbacks[AttachmentAction.FILE_UPLOAD]()}
type="button"
>
<File class="{ICON_CLASS_DEFAULT} shrink-0" />
<span class="flex min-w-0 items-center gap-2">
<span>{ATTACHMENT_MENU_TEXT.ADD_FILES}</span>
{#if supportedModalities.length > 0}
<span class="flex items-center gap-0.75 text-muted-foreground">
{#each supportedModalities as modality (modality.label)}
<Tooltip.Root>
<Tooltip.Trigger>
<modality.icon class="size-2.75" />
</Tooltip.Trigger>
<Tooltip.Content>
<p>{modality.label}</p>
</Tooltip.Content>
</Tooltip.Root>
{/each}
</span>
{/if}
</span>
</button>
<button
class={itemClass}
onclick={() => attachmentMenu.callbacks[AttachmentAction.SYSTEM_PROMPT_CLICK]()}
type="button"
>
<MessageSquare class="{ICON_CLASS_DEFAULT} shrink-0" />
<span>{ATTACHMENT_MENU_TEXT.SYSTEM_MESSAGE}</span>
</button>
{#if chatFormActions.onWorkingDirectoryClick}
<button
class={itemClass}
onclick={() => {
drawerOpen = false;
chatFormActions.onWorkingDirectoryClick?.();
}}
type="button"
>
<Folder class="{ICON_CLASS_DEFAULT} shrink-0" />
<span class="truncate">{chatFormActions.workingDirectoryLabel}</span>
</button>
<SheetPages
class="gap-4 px-3 pb-[max(1rem,var(--safe-area-bottom))]"
keepFirstPageHeight
pageKey={JSON.stringify(page)}
{pages}
>
{#if page.id === AddSheetPage.ROOT}
{@render rootPage()}
{:else if page.id === AddSheetPage.TOOLS}
{@render toolsPage()}
{:else if currentGroup}
{@render groupPage(currentGroup)}
{/if}
{#if toolsPanel.totalToolCount > 0}
<Collapsible.Root onOpenChange={(open) => (toolsExpanded = open)} open={toolsExpanded}>
<Collapsible.Trigger class={itemClass}>
{#if toolsExpanded}
<ChevronDown class="{ICON_CLASS_DEFAULT} shrink-0" />
{:else}
<ChevronRight class="{ICON_CLASS_DEFAULT} shrink-0" />
{/if}
<PencilRuler class="inline {ICON_CLASS_DEFAULT} shrink-0" />
<span class="flex-1">{ATTACHMENT_MENU_TEXT.TOOLS}</span>
</Collapsible.Trigger>
<Collapsible.Content>
<div class="flex flex-col gap-0.5 pl-4">
{#each toolsPanel.categoryGroups as group (group.key)}
{@render groupRow(group)}
{/each}
{#each toolsPanel.mcpGroups as group (group.key)}
{@render groupRow(group)}
{/each}
</div>
</Collapsible.Content>
</Collapsible.Root>
{/if}
</div>
</SheetPages>
</Drawer.Content>
</Drawer.Root>
</div>
{#snippet groupRow(group: ToolGroup)}
{@const checkState = toolsPanel.getGroupCheckState(group)}
{@const enabledCount = toolsPanel.getEnabledToolCount(group)}
{@const favicon = toolsPanel.getFavicon(group)}
{@const groupDisabled = toolsPanel.isGroupDisabled(group)}
<button
class="{itemRowClass} {groupDisabled ? 'pointer-events-none opacity-50' : ''}"
onclick={() => toolsPanel.toggleGroupByKey(group.key)}
type="button"
>
{#if favicon}
<img
alt=""
class="{ICON_CLASS_DEFAULT} shrink-0 rounded-sm"
onerror={(e) => {
(e.currentTarget as HTMLImageElement).style.display = 'none';
}}
src={favicon}
/>
{#snippet rootPage()}
<InsetList>
{#if canUseCamera}
<InsetListRow icon={Camera} onclick={() => cameraInput?.click()}>
{ATTACHMENT_MENU_TEXT.CAMERA}
</InsetListRow>
{/if}
<span class="min-w-0 flex-1 truncate text-label">{group.label}</span>
<InsetListRow icon={File} onclick={handleAddFiles}>
<span class="flex-1">{ATTACHMENT_MENU_TEXT.ADD_FILES}</span>
<span class="shrink-0 text-caption text-muted-foreground">
{enabledCount}/{group.tools.length}
{#if supportedModalities.length > 0}
<span class="flex items-center gap-1 text-muted-foreground">
{#each supportedModalities as modality (modality.label)}
<modality.icon aria-label={modality.label} class="size-3" />
{/each}
</span>
{/if}
</InsetListRow>
</InsetList>
<InsetList>
<InsetListRow
icon={MessageSquare}
onclick={() => attachmentMenu.callbacks[AttachmentAction.SYSTEM_PROMPT_CLICK]()}
>
{ATTACHMENT_MENU_TEXT.SYSTEM_MESSAGE}
</InsetListRow>
{#if chatFormActions.onWorkingDirectoryClick}
<InsetListRow
chevron
icon={Folder}
onclick={() => {
drawerOpen = false;
chatFormActions.onWorkingDirectoryClick?.();
}}
>
<span class="shrink-0">{ATTACHMENT_MENU_TEXT.WORKING_DIRECTORY}</span>
<span class="min-w-0 flex-1 truncate text-right text-body-sm text-muted-foreground">
{chatFormActions.workingDirectory ?? ATTACHMENT_MENU_TEXT.NONE}
</span>
</InsetListRow>
{/if}
<!-- a plain chat has no tools to pick -->
{#if agenticMode.enabled}
<InsetListRow chevron icon={PencilRuler} onclick={() => push({ id: AddSheetPage.TOOLS })}>
<span class="flex-1">{ATTACHMENT_MENU_TEXT.TOOLS}</span>
{#if toolsPanel.totalToolCount > 0}
<span class="text-body-sm text-muted-foreground tabular-nums">
{enabledToolCount}/{toolsPanel.totalToolCount}
</span>
{/if}
</InsetListRow>
{/if}
</InsetList>
{/snippet}
{#snippet toolsPage()}
{#if toolsPanel.totalToolCount === 0}
<InsetList class="px-4 py-4 text-body-sm text-muted-foreground">
{#if toolsStore.loading}
<span class="flex items-center justify-center gap-2">
<Loader2 class="{ICON_CLASS_DEFAULT} animate-spin" />
{ATTACHMENT_MENU_TEXT.LOADING_TOOLS}
</span>
{:else if toolsStore.error && !toolsStore.isToolsEndpointUnreachable}
<span class="text-center">{ATTACHMENT_MENU_TEXT.TOOLS_FAILED}</span>
{:else}
<span class="flex gap-2">
<Info class="mt-0.5 {ICON_CLASS_DEFAULT} shrink-0" />
<span>{toolsPanel.noToolsInfoMessage ?? ATTACHMENT_MENU_TEXT.NO_TOOLS}</span>
</span>
{/if}
</InsetList>
{:else}
{#if toolsPanel.categoryGroups.length > 0}
<InsetList>
{#each toolsPanel.categoryGroups as group (group.key)}
{@render groupRow(group)}
{/each}
</InsetList>
{/if}
{#if toolsPanel.mcpGroups.length > 0}
<InsetList title={ATTACHMENT_MENU_TEXT.MCP_SERVERS}>
{#each toolsPanel.mcpGroups as group (group.key)}
{@render groupRow(group)}
{/each}
</InsetList>
{/if}
{/if}
{/snippet}
{#snippet groupSwitch(group: ToolGroup, label?: string)}
<Switch
aria-label={label}
checked={toolsPanel.getGroupCheckState(group).checked}
disabled={toolsPanel.isGroupDisabled(group)}
onCheckedChange={() => toolsPanel.toggleGroupByKey(group.key)}
size="lg"
/>
{/snippet}
{#snippet groupRow(group: ToolGroup)}
{@const favicon = toolsPanel.getFavicon(group)}
{@const isChecked = toolsPanel.getGroupCheckState(group).checked}
<InsetListSplitRow
dimmed={toolsPanel.isGroupDisabled(group)}
onclick={() => push({ groupKey: group.key, id: AddSheetPage.TOOL_GROUP })}
>
{#snippet leading()}
{#if favicon}
<img
alt=""
class="{ICON_CLASS_DEFAULT} shrink-0 rounded-sm"
onerror={(e) => {
(e.currentTarget as HTMLImageElement).style.display = 'none';
}}
src={favicon}
/>
{:else}
{@const SourceIcon = TOOL_SOURCE_ICONS[group.source] ?? Server}
<SourceIcon class="{ICON_CLASS_DEFAULT} shrink-0" />
{/if}
{/snippet}
<span class="min-w-0 flex-1 truncate">{group.label}</span>
<span class="text-body-sm text-muted-foreground tabular-nums">
{toolsPanel.getEnabledToolCount(group)}/{group.tools.length}
</span>
<Checkbox
checked={checkState.checked}
class="{ICON_CLASS_DEFAULT} shrink-0"
indeterminate={checkState.indeterminate}
onCheckedChange={() => toolsPanel.toggleGroupByKey(group.key)}
onclick={(e) => e.stopPropagation()}
/>
</button>
{#snippet trailing()}
{@render groupSwitch(
group,
isChecked
? ATTACHMENT_MENU_TEXT.DISABLE_GROUP(group.label)
: ATTACHMENT_MENU_TEXT.ENABLE_GROUP(group.label)
)}
{/snippet}
</InsetListSplitRow>
{/snippet}
{#snippet groupPage(group: ToolGroup)}
<InsetList class={toolsPanel.isGroupDisabled(group) ? 'opacity-50' : undefined}>
<InsetListRow as="label" icon={PencilRuler}>
<span class="flex-1">{ATTACHMENT_MENU_TEXT.ALL_TOOLS}</span>
{@render groupSwitch(group)}
</InsetListRow>
</InsetList>
<InsetList>
{#each group.tools as entry (entry.key)}
<InsetListRow
as="label"
class={toolsPanel.isToolParentDisabled(entry) ? 'opacity-50' : undefined}
>
<span class="min-w-0 flex-1 truncate font-mono text-body-sm">
{entry.definition.function.name}
</span>
<Switch
checked={toolsPanel.isToolEnabled(entry)}
onCheckedChange={() => toolsPanel.toggleTool(entry)}
size="lg"
/>
</InsetListRow>
{/each}
</InsetList>
{/snippet}

View file

@ -26,7 +26,7 @@
<div class="px-3 py-4 text-center text-body-sm text-muted-foreground">
<Loader2 class="mx-auto mb-1 {ICON_CLASS_DEFAULT} animate-spin" />
Loading tools...
{ATTACHMENT_MENU_TEXT.LOADING_TOOLS}
</div>
{:else if toolsStore.isToolsEndpointUnreachable}
<div class="grid gap-2.5 px-3 py-4 text-body-sm text-muted-foreground">
@ -40,8 +40,8 @@
</span>
</span>
<!-- only while MCP shows: with it hidden, there is nowhere to add a server -->
{#if uiStore.isMcpShown}
<!-- only while MCP is on -->
{#if uiStore.isMcpEnabled}
<span class="flex gap-2">
<Info class="mt-0.5 {ICON_CLASS_DEFAULT} shrink-0" />
@ -55,7 +55,7 @@
</div>
{:else if toolsStore.error}
<div class="px-3 py-4 text-center text-body-sm text-muted-foreground">
Failed to load tools
{ATTACHMENT_MENU_TEXT.TOOLS_FAILED}
</div>
{:else if toolsPanel.noToolsInfoMessage}
<div class="flex gap-2 px-3 py-4 text-body-sm text-muted-foreground">
@ -65,7 +65,7 @@
</div>
{:else}
<div class="px-3 py-4 text-center text-body-sm text-muted-foreground">
No tools available
{ATTACHMENT_MENU_TEXT.NO_TOOLS}
</div>
{/if}
{:else}

View file

@ -50,6 +50,7 @@
/** The chat's working directory, which the + menu names. */
workingDirectory?: string | null;
onFileUpload?: () => void;
onFilesSelect?: (files: File[]) => void;
onMicClick?: () => void;
onStop?: () => void;
onSystemPromptClick?: () => void;
@ -66,6 +67,7 @@
isSendWaiting = false,
isVoiceRefining = false,
micWarning = null,
onFilesSelect,
onFileUpload,
onMicClick,
onStop,
@ -132,6 +134,9 @@
get hasVisionModality() {
return hasVisionModality;
},
get onFilesSelect() {
return onFilesSelect;
},
get onFileUpload() {
return onFileUpload;
},
@ -141,10 +146,13 @@
get onWorkingDirectoryClick() {
return onWorkingDirectoryClick;
},
get workingDirectoryLabel() {
get workingDirectory() {
return workingDirectory
? abbreviateWorkingDir(workingDirectory, toolsStore.serverHome)
: SET_WORKING_DIRECTORY_LABEL;
: null;
},
get workingDirectoryLabel() {
return this.workingDirectory ?? SET_WORKING_DIRECTORY_LABEL;
}
});
</script>

View file

@ -22,7 +22,7 @@
ICON_CLASS_SM,
ICON_CLASS_XS,
SIDEBAR_ACTIONS_ITEMS,
sidebarFooterItems
SIDEBAR_FOOTER_ITEMS
} from '#lib/constants/index.ts';
import { KeyboardKey, SidebarAction } from '#lib/enums/index.ts';
import { useDebouncedSearch } from '#lib/hooks/use-debounced-search.svelte.ts';
@ -32,7 +32,6 @@
HuggingFaceService
} from '#lib/services/index.ts';
import { RouterService } from '#lib/services/router.service.ts';
import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts';
import {
conversationsStore,
deviceStore,
@ -249,7 +248,7 @@
const actionEntries = $derived.by((): SearchEntry[] =>
// every sidebar action the sidebar shows but Search itself, which is what opened this
// dialog, and the models manager on a phone, which picks its models in the selector
[...SIDEBAR_ACTIONS_ITEMS, ...sidebarFooterItems(agenticMode.enabled)]
[...SIDEBAR_ACTIONS_ITEMS, ...SIDEBAR_FOOTER_ITEMS]
.filter(
(item) =>
item.action &&

View file

@ -19,10 +19,9 @@
export { default as DialogMcpServerAddNew } from './DialogMcpServerAddNew.svelte';
/**
* **DialogMcpServers** - MCP servers dialog shown from the chat form
* **DialogMcpServers** - MCP servers dialog, opened with `uiStore.openMcpServers`
*
* Shows the same MCP server list as the `/mcp-servers` route inside a modal
* dialog.
* Lists the MCP servers, to add, edit, turn on and remove them.
*/
export { default as DialogMcpServers } from './DialogMcpServers.svelte';

View file

@ -1,21 +1,19 @@
<script lang="ts">
import ModelLoadHighlight from '../ModelLoadHighlight.svelte';
import ModelsSelectorReasoning from './ModelsSelectorReasoning.svelte';
import ModelsSelectorReasoningBadge from './ModelsSelectorReasoningBadge.svelte';
import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip';
import { ChevronDown, Loader2 } from '@lucide/svelte';
import {
ChatFormActionReasoning,
ModelId,
ModelsSelectorDrawer,
ModelsSelectorDropdown,
ModelsSelectorList,
ModelsSelectorOption,
ModelsSelectorSheet,
ModelsSelectorTriggerIcon
} from '#lib/components/app/index.ts';
import {
DROPDOWN_MENU_CONTENT_SEARCH_SELECTOR,
MODEL_ICON,
MODELS_SHEET_QUICK_COUNT,
SETTINGS_KEYS
} from '#lib/constants/index.ts';
import { KeyboardKey, ServerModelStatus } from '#lib/enums/index.ts';
@ -26,9 +24,10 @@
modelsStore,
serverStore,
settingsStore,
uiStore
uiStore,
voiceStore
} from '#lib/stores/index.ts';
import { type ModelItem, modelLoadFraction } from '#lib/utils/index.ts';
import { modelLoadFraction, pickQuickModels } from '#lib/utils/index.ts';
import { untrack } from 'svelte';
interface Props {
@ -94,6 +93,20 @@
});
const selectedOption = $derived(ms.getDisplayOption());
// the models in reach on a phone: the chat's, the dictation's, the loaded ones, favorites,
// then the recently picked
let quickItems = $derived(
pickQuickModels({
activeId: ms.activeId,
dictationModel: voiceStore.dictationModel,
favoriteIds: modelsStore.favoriteModelIds,
limit: MODELS_SHEET_QUICK_COUNT,
loadedIds: new Set(ms.loadedItems.map((item) => item.option.id)),
options: ms.options.filter((option) => !modelsStore.isHidden(option.id)),
recentIds: modelsStore.recentModelIds
})
);
const triggerModel = $derived(selectedOption?.model ?? null);
let triggerStatus = $derived(
@ -256,74 +269,6 @@
{/if}
{/snippet}
{#snippet modelOption(item: ModelItem, hideOrgName: boolean)}
{@const { option } = item}
{@const isSelected = ms.activeId === option.id}
{@const isHighlighted = option.id === highlightedId}
{@const isFav = ms.isFavorite(option.model)}
<ModelsSelectorOption
{hideOrgName}
{isFav}
{isHighlighted}
{isSelected}
onKeyDown={(event) => {
if (event.key === KeyboardKey.ENTER || event.key === KeyboardKey.SPACE) {
event.preventDefault();
void handleModelKeyAction(option.id, event.altKey);
}
}}
onMouseEnter={() => (highlightedId = option.id)}
onSelect={ms.handleSelect}
{option}
/>
{/snippet}
{#snippet reasoningFooter()}
<ModelsSelectorReasoning variant="list" />
{/snippet}
{#snippet pickerList(listClass: string)}
<div class={['models-list', listClass]}>
{#if !ms.isCurrentModelInCache && displayModel}
<!-- Show unavailable model as first option (disabled) -->
<button
aria-disabled="true"
aria-selected="true"
class="flex w-full cursor-not-allowed items-center bg-surface-danger p-2 text-left text-body-sm text-fg-danger"
disabled
role="option"
type="button"
>
<ModelId
class="flex-1"
hideOrgName={!showOrgName}
hideQuantization
modelId={displayModel}
/>
<span class="ml-2 text-caption whitespace-nowrap opacity-70">(not available)</span>
</button>
{/if}
{#if ms.isEmpty}
<p class="px-4 py-3 text-body-sm text-muted-foreground">{ms.emptyMessage}</p>
{/if}
<ModelsSelectorList
activeId={ms.activeId}
currentModel={displayModel}
favorites={ms.favoriteItems}
groups={ms.groupedFilteredOptions}
loaded={ms.loadedItems}
onSelect={ms.handleSelect}
renderOption={modelOption}
sectionHeaderClass="[&:not(:first-child)]:mt-2 mb-1 px-2 py-2.5 text-body-sm font-semibold text-foreground/80 select-none"
{showOrgName}
/>
</div>
{/snippet}
{#if ms.loading && ms.options.length === 0 && ms.isMultiModel}
<div class="flex items-center gap-2 text-caption text-muted-foreground">
<Loader2 class="size-icon-sm animate-spin" />
@ -353,18 +298,25 @@
{@render selectorTriggerInner()}
</button>
<ModelsSelectorDrawer
<ModelsSelectorSheet
bind:open={isOpen}
activeId={ms.activeId}
emptyMessage={ms.emptyMessage}
footer={showReasoning ? reasoningFooter : undefined}
favoriteItems={ms.favoriteItems}
groups={ms.groupedFilteredOptions}
hideOrgName={!showOrgName}
{highlightedId}
isEmpty={ms.isEmpty && ms.isCurrentModelInCache}
loadedItems={ms.loadedItems}
onOpenChange={ms.handleOpenChange}
onSearchChange={(v) => ms.setSearchTerm(v)}
onSearchKeyDown={handleSearchKeyDown}
onSelect={ms.handleSelect}
{quickItems}
searchTerm={ms.searchTerm}
>
{@render pickerList('px-2.5')}
</ModelsSelectorDrawer>
{showReasoning}
unavailableModel={ms.isCurrentModelInCache ? null : displayModel}
/>
{:else}
<ModelsSelectorDropdown
bind:open={isOpen}
@ -392,18 +344,25 @@
{@render selectorTriggerInner()}
</button>
<ModelsSelectorDrawer
<ModelsSelectorSheet
bind:open={isOpen}
activeId={ms.activeId}
emptyMessage={ms.emptyMessage}
footer={showReasoning ? reasoningFooter : undefined}
favoriteItems={ms.favoriteItems}
groups={ms.groupedFilteredOptions}
hideOrgName={!showOrgName}
{highlightedId}
isEmpty={ms.isEmpty && ms.isCurrentModelInCache}
loadedItems={ms.loadedItems}
onOpenChange={ms.handleOpenChange}
onSearchChange={(v) => ms.setSearchTerm(v)}
onSearchKeyDown={handleSearchKeyDown}
onSelect={ms.handleSelect}
{quickItems}
searchTerm={ms.searchTerm}
>
{@render pickerList('px-2.5')}
</ModelsSelectorDrawer>
{showReasoning}
unavailableModel={ms.isCurrentModelInCache ? null : displayModel}
/>
{:else}
<!-- a lone llama.cpp server has nothing to choose from: the trigger opens the
manager instead, so the button is its own affordance. With the manager hidden

View file

@ -1,58 +0,0 @@
<script lang="ts">
import { Drawer, DrawerContent } from '@ggml-org/llama-ui/ui/drawer';
import { DropdownMenuSearchable } from '#lib/components/app/index.ts';
import { uiStore } from '#lib/stores/index.ts';
import type { Snippet } from 'svelte';
interface Props {
children: Snippet;
emptyMessage?: string;
/** Sticky picker footer: it sticks to the bottom of the drawer's scrollport. */
footer?: Snippet;
isEmpty?: boolean;
onOpenChange?: (open: boolean) => void;
onSearchChange?: (value: string) => void;
onSearchKeyDown?: (event: KeyboardEvent) => void;
open?: boolean;
placeholder?: string;
searchTerm?: string;
}
let {
children,
emptyMessage = 'No items found',
footer,
isEmpty = false,
onOpenChange,
onSearchChange,
onSearchKeyDown,
open = $bindable(false),
placeholder = 'Search models...',
searchTerm = ''
}: Props = $props();
</script>
<!-- the details drawer opens over the picker: the picker stays open under its backdrop -->
<Drawer bind:open {onOpenChange}>
<DrawerContent
class={['overflow-hidden', uiStore.isModelDetailsOpen && 'z-40']}
overlayClass={uiStore.isModelDetailsOpen ? 'z-40' : undefined}
>
<!-- the wrapper is the scrollport: the search header and the footer stick to it -->
<div class="max-h-[min(40rem,calc(100dvh-5rem))] min-h-0 overflow-y-auto">
<DropdownMenuSearchable
{emptyMessage}
{footer}
headerClass="p-2.5 pt-4"
{isEmpty}
{onSearchChange}
{onSearchKeyDown}
{placeholder}
searchClass="bg-transparent"
searchValue={searchTerm}
>
{@render children()}
</DropdownMenuSearchable>
</div>
</DrawerContent>
</Drawer>

View file

@ -1,7 +1,5 @@
<script lang="ts">
import ModelsSelectorDownloadItem from './ModelsSelectorDownloadItem.svelte';
import { Logo } from '@ggml-org/llama-ui/app/misc';
import { Heart, Power } from '@lucide/svelte';
import { DialogConfirmDownload } from '#lib/components/app/dialogs/index.ts';
import {
GroupedList,
@ -182,10 +180,6 @@
revealChevronOnHover
sticky
>
{#snippet icon()}
<Power class="size-icon-sm shrink-0" />
{/snippet}
{#each loadedForChat as item (item.option.id)}
{@render render(item, !showOrgName)}
{/each}
@ -211,10 +205,6 @@
{#if favorites.length > 0}
<!-- Favorites come first; the sections below skip them -->
<ModelsSection label="Favorites" persistKey="favorites" revealChevronOnHover sticky>
{#snippet icon()}
<Heart class="size-icon-sm shrink-0" />
{/snippet}
{#each favorites as item (`fav-${item.option.id}`)}
{@render render(item, !showOrgName)}
{/each}
@ -245,14 +235,17 @@
{/if}
{/snippet}
<!-- the server's own models are listed as they are, since there is no other provider yet to tell
them from; with favorites or loaded models above, they sit in a section of their own, as
those do -->
{#if groups.available.length > 0}
<ModelsSection label="Local models" persistKey={LOCAL_BACKEND_ID} revealChevronOnHover sticky>
{#snippet icon()}
<Logo class="shrink-0" style="--size: 0.875rem" />
{/snippet}
{#if favorites.length > 0 || loaded.length > 0}
<ModelsSection label="Other models" persistKey={LOCAL_BACKEND_ID} revealChevronOnHover sticky>
{@render localRows()}
</ModelsSection>
{:else}
{@render localRows()}
</ModelsSection>
{/if}
{/if}
<DialogConfirmDownload

View file

@ -0,0 +1,396 @@
<!--
A phone's model picker: a sheet in the settings sheet's patterns. It opens partway with the
few models in reach (loaded, favorite, recent), each marked when it is the chat's or the
dictation's, and a row that opens all models as a page, in groups of the
same rows. Tapping a model switches the chat to it, loading it if need be, as on a desktop;
holding it opens its menu, as a held chat row does: unload it, or open its details over the
sheet. A search shows its results in place; it stays at the sheet's foot, under the reasoning
effort as the desktop picker has it.
-->
<script lang="ts">
import ModelAvatar from '../ModelAvatar.svelte';
import ModelId from '../ModelId.svelte';
import ModelVoiceRole from '../ModelVoiceRole.svelte';
import ModelsSelectorReasoning from './ModelsSelectorReasoning.svelte';
import { SearchInput } from '@ggml-org/llama-ui/app/forms';
import {
InsetList,
InsetListRow,
SheetHeader,
SheetPages,
useSheetPages
} from '@ggml-org/llama-ui/app/sheets';
import { SHEET_CONTENT_CLASS } from '@ggml-org/llama-ui/constants';
import * as Drawer from '@ggml-org/llama-ui/ui/drawer';
import { Check, Info, Loader2, Mic, MoreHorizontal, PowerOff } from '@lucide/svelte';
import DropdownMenuActions from '#lib/components/app/navigation/DropdownMenuActions.svelte';
import {
MODELS_SHEET_GROUP_KEYS,
MODELS_SHEET_TEXT,
ROW_LONG_PRESS_MS,
SETTINGS_KEYS,
SHEET_AUTO_HEIGHT_CLASS,
SHEET_FULL_HEIGHT_CLASS
} from '#lib/constants/index.ts';
import { ModelsSheetPage } from '#lib/enums/index.ts';
import { useLongPress } from '#lib/hooks/use-long-press.svelte.ts';
import { useReasoningMenu } from '#lib/hooks/use-reasoning-menu.svelte.ts';
import {
modelsStore,
serverStore,
settingsStore,
uiStore,
voiceStore
} from '#lib/stores/index.ts';
import type { MenuAction } from '#lib/types/index.ts';
import {
type GroupedModelOptions,
groupModelFamilies,
type ModelItem
} from '#lib/utils/index.ts';
import { tick } from 'svelte';
interface Props {
/** The chat's model, marked among the rows. */
activeId?: string | null;
emptyMessage?: string;
/** Favorite models, after the loaded ones on the All models page. */
favoriteItems?: ModelItem[];
/** The other models: grouped by family on the All models page, as the setting asks. */
groups?: GroupedModelOptions;
/** Hide the organization in the rows' model ids. */
hideOrgName?: boolean;
/** The row the search's arrow keys are on, in the full list. */
highlightedId?: string | null;
isEmpty?: boolean;
/** Loaded models, leading the All models page. */
loadedItems?: ModelItem[];
onOpenChange?: (open: boolean) => void;
onSearchChange?: (value: string) => void;
onSearchKeyDown?: (event: KeyboardEvent) => void;
/** A tapped model: switches the chat to it, loading it if need be. */
onSelect?: (modelId: string) => void;
open?: boolean;
/** The few models the sheet opens with: the chat's, the dictation's, and those in reach. */
quickItems?: ModelItem[];
searchTerm?: string;
/** The chat's reasoning effort, as a row that opens its levels. */
showReasoning?: boolean;
/** The chat's model when the server no longer lists it, shown as not available. */
unavailableModel?: string | null;
}
let {
activeId = null,
emptyMessage = MODELS_SHEET_TEXT.EMPTY,
favoriteItems = [],
groups = { available: [] },
hideOrgName = false,
highlightedId = null,
isEmpty = false,
loadedItems = [],
onOpenChange,
onSearchChange,
onSearchKeyDown,
onSelect,
open = $bindable(false),
quickItems = [],
searchTerm = '',
showReasoning = false,
unavailableModel = null
}: Props = $props();
/** Marks a model's row, to bring the highlighted one into view. */
const MODEL_ID_ATTR = 'data-model-id';
const pages = useSheetPages({ id: ModelsSheetPage.ROOT });
const page = $derived(pages.page);
const reasoning = useReasoningMenu();
let scrollEl = $state<HTMLDivElement | null>(null);
let isSearching = $derived(searchTerm.trim().length > 0);
// the full list: its own page or a search's results; the sheet opens on the short view even
// when no model is in reach, with the way to all of them
let showFull = $derived(page.id === ModelsSheetPage.ALL || isSearching);
let hasEffort = $derived(showReasoning && reasoning.levels.length > 0);
// the models past the loaded and favorite ones: a group per family, or one for them all
let otherGroups = $derived.by(() => {
const items = groups.available.flatMap((group) => group.items);
if (items.length === 0) return [];
if (!settingsStore.config[SETTINGS_KEYS.GROUP_MODELS_BY_FAMILY]) {
return [{ items, key: MODELS_SHEET_GROUP_KEYS.LOCAL, title: MODELS_SHEET_TEXT.LOCAL_MODELS }];
}
return groupModelFamilies(items, (item) => item.option.model).map((family) => ({
items: family.entries,
key: `${MODELS_SHEET_GROUP_KEYS.FAMILY_PREFIX}${family.key}`,
title: family.label
}));
});
let fullGroups = $derived([
...(loadedItems.length > 0
? [
{
items: loadedItems,
key: MODELS_SHEET_GROUP_KEYS.LOADED,
title: MODELS_SHEET_TEXT.LOADED
}
]
: []),
...(favoriteItems.length > 0
? [
{
items: favoriteItems,
key: MODELS_SHEET_GROUP_KEYS.FAVORITES,
title: MODELS_SHEET_TEXT.FAVORITES
}
]
: []),
...otherGroups
]);
// a held row's menu, anchored to the row; raw, so a row's item still equals the one held
let menuItem = $state.raw<ModelItem | null>(null);
let menuAnchor = $state<HTMLElement | null>(null);
let menuOpen = $state(false);
// the row under the finger, for the hold to open its menu
let pressed = $state.raw<{ item: ModelItem; row: HTMLElement } | null>(null);
const longPress = useLongPress({
enabled: () => true,
onLongPress: () => {
if (!pressed) return;
menuItem = pressed.item;
menuAnchor = pressed.row;
menuOpen = true;
}
});
let menuActions = $derived.by((): MenuAction[] => {
const item = menuItem;
if (!item) return [];
const { id, model } = item.option;
const actions: MenuAction[] = [];
// a router unloads its models; a lone server keeps its one model loaded
if (serverStore.isRouterMode) {
if (modelsStore.isModelLoading(model)) {
actions.push({
icon: Loader2,
label: MODELS_SHEET_TEXT.CANCEL_LOADING,
onclick: () => void modelsStore.status.cancelLoad(model)
});
} else if (modelsStore.isModelLoaded(model)) {
actions.push({
icon: PowerOff,
label: MODELS_SHEET_TEXT.UNLOAD,
onclick: () => void modelsStore.status.unload(model)
});
}
}
actions.push({
icon: Info,
label: MODELS_SHEET_TEXT.MORE_DETAILS,
onclick: () => uiStore.openModelDetails(id)
});
return actions;
});
// each opening starts on the first page
$effect(() => {
if (open) pages.reset();
});
// the arrow keys can move the highlight to a row out of view
$effect(() => {
if (!highlightedId || !showFull) return;
scrollEl
?.querySelector(`[${MODEL_ID_ATTR}="${CSS.escape(highlightedId)}"]`)
?.scrollIntoView({ block: 'nearest' });
});
function openAllModels() {
pages.push({ id: ModelsSheetPage.ALL });
void tick().then(() => scrollEl?.scrollTo({ top: 0 }));
}
// the keys move a highlight through the full list, so they wait until it shows
function handleSearchKeyDown(event: KeyboardEvent) {
if (showFull) onSearchKeyDown?.(event);
}
</script>
{#snippet modelRow(item: ModelItem)}
{@const inChat = activeId === item.option.id}
{@const dictates = !inChat && voiceStore.isDictationModel(item.option.model)}
{@const isHeld = longPress.isPressing && pressed?.item === item}
{@const isLit = (menuOpen && menuItem === item) || (showFull && highlightedId === item.option.id)}
<!-- the row sinks while a finger holds it, and stays lit while its menu is open or the
search's arrow keys are on it -->
<InsetListRow
bodyClass="gap-3"
class={[
'select-none [-webkit-touch-callout:none] [content-visibility:auto] [contain-intrinsic-size:auto_3rem]',
isHeld && 'bg-(--surface-pressed) duration-(--row-hold-ms) ease-out',
isLit && 'bg-(--surface-pressed)'
]}
style="--row-hold-ms: {ROW_LONG_PRESS_MS}ms"
{...{ [MODEL_ID_ATTR]: item.option.id }}
onclick={() => onSelect?.(item.option.id)}
onclickcapture={longPress.handleClickCapture}
oncontextmenu={longPress.handleContextMenu}
onpointercancel={longPress.handlePointerEnd}
onpointerdown={(event) => {
pressed = { item, row: event.currentTarget };
longPress.handlePointerDown(event);
}}
onpointermove={longPress.handlePointerMove}
onpointerup={longPress.handlePointerEnd}
>
{#snippet leading()}
<ModelAvatar class="shrink-0" option={item.option} size="size-6" />
{/snippet}
<span class="flex min-w-0 flex-1 items-center gap-1.5">
<ModelId
class="min-w-0"
draftSidecars={item.option.draftSidecars}
hideCapabilities
hideModalities
{hideOrgName}
modelId={item.option.model}
tags={item.option.tags}
/>
<ModelVoiceRole model={item.option.model} />
</span>
<!-- what the model does now: the chat's, or the one that transcribes dictation -->
{#if inChat}
{@render role(MODELS_SHEET_TEXT.IN_CHAT, Check, 'text-(--action-primary)')}
{:else if dictates}
{@render role(MODELS_SHEET_TEXT.DICTATION, Mic, 'text-destructive')}
{/if}
</InsetListRow>
{/snippet}
{#snippet role(label: string, Icon: typeof Check, iconClass: string)}
<span class="flex shrink-0 items-center gap-1 text-caption text-muted-foreground">
{label}
<Icon class="size-4 {iconClass}" />
</span>
{/snippet}
<!-- the chat's model, when the server no longer lists it: shown, and not to be picked -->
{#snippet unavailableRow(model: string)}
<InsetList>
<InsetListRow aria-disabled="true" as="div" bodyClass="gap-3 text-fg-danger">
<ModelId class="min-w-0 flex-1" {hideOrgName} hideQuantization modelId={model} />
<span class="shrink-0 text-caption">{MODELS_SHEET_TEXT.NOT_AVAILABLE}</span>
</InsetListRow>
</InsetList>
{/snippet}
<!-- a held row's menu: it shows no trigger, anchored to the row as a held chat row's is -->
<div hidden>
<DropdownMenuActions
bind:open={menuOpen}
actions={menuActions}
align="center"
anchor={menuAnchor}
triggerIcon={MoreHorizontal}
triggerTooltip={MODELS_SHEET_TEXT.MODEL_ACTIONS}
/>
</div>
<!-- the details drawer opens over the picker: the picker stays open under its backdrop -->
<Drawer.Root bind:open {onOpenChange} shouldScaleBackground={false}>
<Drawer.Content
class={[
'gap-0 overflow-hidden',
showFull ? SHEET_FULL_HEIGHT_CLASS : SHEET_AUTO_HEIGHT_CLASS,
SHEET_CONTENT_CLASS,
uiStore.isModelDetailsOpen && 'z-40'
]}
onOpenAutoFocus={(event) => event.preventDefault()}
overlayClass={uiStore.isModelDetailsOpen ? 'z-40' : undefined}
>
<SheetHeader
canGoBack={pages.canGoBack}
onBack={pages.pop}
title={page.id === ModelsSheetPage.ALL
? MODELS_SHEET_TEXT.ALL_MODELS
: MODELS_SHEET_TEXT.SELECT_MODEL}
/>
<Drawer.Description class="sr-only">{MODELS_SHEET_TEXT.DESCRIPTION}</Drawer.Description>
<SheetPages bind:ref={scrollEl} class="gap-6 px-4 pb-4" pageKey={page.id} {pages}>
{#if unavailableModel}
{@render unavailableRow(unavailableModel)}
{/if}
{#if showFull}
{#if isEmpty}
<p class="px-4 py-3 text-body-sm text-muted-foreground">{emptyMessage}</p>
{:else}
{#each fullGroups as group (group.key)}
<InsetList title={group.title}>
{#each group.items as item (item.option.id)}
{@render modelRow(item)}
{/each}
</InsetList>
{/each}
{/if}
{:else}
<!-- plain rows in one rounded group, as the add sheet's -->
{#if quickItems.length > 0}
<InsetList>
{#each quickItems as item (item.option.id)}
{@render modelRow(item)}
{/each}
</InsetList>
{:else if isEmpty}
<p class="px-4 text-body-sm text-muted-foreground">{emptyMessage}</p>
{/if}
<InsetList>
<InsetListRow chevron onclick={openAllModels}>
<span class="flex-1">{MODELS_SHEET_TEXT.ALL_MODELS}</span>
</InsetListRow>
</InsetList>
{/if}
</SheetPages>
<!-- the reasoning effort, then the search at the sheet's foot, in the chat form's own
surface and shape -->
<div class="shrink-0 px-2 pt-2 pb-[max(0.5rem,var(--safe-area-bottom))]">
{#if hasEffort}
<ModelsSelectorReasoning variant="list" />
{/if}
<SearchInput
class="chat-form-surface overflow-hidden rounded-(--chat-form-single-row-radius)"
inputClass="h-12 max-md:h-12 border-0 bg-transparent shadow-none focus-visible:border-0 focus-visible:ring-0 dark:bg-transparent"
onInput={(value) => onSearchChange?.(value)}
onKeyDown={handleSearchKeyDown}
placeholder={MODELS_SHEET_TEXT.SEARCH_PLACEHOLDER}
value={searchTerm}
/>
</div>
</Drawer.Content>
</Drawer.Root>

View file

@ -3,7 +3,7 @@
export { default as ModelsSelector } from './ModelsSelector.svelte';
export { default as ModelsSelectorDropdown } from './ModelsSelectorDropdown.svelte';
export { default as ModelsSelectorDrawer } from './ModelsSelectorDrawer.svelte';
export { default as ModelsSelectorSheet } from './ModelsSelectorSheet.svelte';
export { default as ModelsSelectorList } from './ModelsSelectorList.svelte';
export { default as ModelsSelectorDownloadItem } from './ModelsSelectorDownloadItem.svelte';
export { default as ModelsSelectorOption } from './ModelsSelectorOption.svelte';

View file

@ -1,5 +1,6 @@
<script lang="ts">
import { PanelLeftClose, PanelLeftOpen, Search } from '@lucide/svelte';
import { Button } from '@ggml-org/llama-ui/ui/button';
import { PanelLeftClose, PanelLeftOpen, Search, Settings, SquarePen } from '@lucide/svelte';
import {
ActionIcon,
DialogConversationDelete,
@ -12,29 +13,28 @@
DialogSettingsChat,
Logo,
ModelsManagerModelDrawer,
SettingsSheet,
SidebarNavigationActions,
SidebarNavigationConversationList,
SidebarNavigationFooter
} from '#lib/components/app/index.ts';
import {
ROUTES,
SIDEBAR_ACTIONS_ITEMS,
SIDEBAR_COLLAPSE_WIDTH,
SIDEBAR_COLLAPSED_WIDTH,
SIDEBAR_CONTENT_FADE_MS,
SIDEBAR_KEYS_TEXT,
SIDEBAR_MAX_WIDTH,
SIDEBAR_MIN_WIDTH,
SIDEBAR_OVERSTRETCH_PX,
SIDEBAR_REVEAL_ACTION_DELAY_MS,
SIDEBAR_SETTLE_MS,
SIDEBAR_TOGGLE_MS,
sidebarFooterItems
SIDEBAR_TOGGLE_MS
} from '#lib/constants/index.ts';
import { SidebarAction, TooltipSide } from '#lib/enums/index.ts';
import { useKeyboardShortcuts } from '#lib/hooks/use-keyboard-shortcuts.svelte.ts';
import { useMarqueeSelection } from '#lib/hooks/use-marquee-selection.svelte.ts';
import { RouterService } from '#lib/services/router.service.ts';
import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts';
import {
chatStore,
conversationsStore,
@ -42,7 +42,7 @@
settingsStore,
uiStore
} from '#lib/stores/index.ts';
import { buildConversationTree, remToPx } from '#lib/utils/index.ts';
import { buildConversationTree, hapticTap, remToPx } from '#lib/utils/index.ts';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { tick } from 'svelte';
@ -174,7 +174,8 @@
let renameDialogOpen = $state(false);
let settingsDialogOpen = $state(false);
let mcpDialogOpen = $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('');
@ -543,14 +544,10 @@
openDialog(() => uiStore.openModelsManager());
break;
// dialogs on a desktop or tablet; on a phone, pages of their own
case SidebarAction.MCP:
if (isOnMobile) navigateBehind(() => goto(ROUTES.MCP_SERVERS));
else openDialog(() => (mcpDialogOpen = true));
break;
// a dialog on a desktop or tablet; on a phone, a sheet
case SidebarAction.SETTINGS:
if (isOnMobile) navigateBehind(() => goto(ROUTES.SETTINGS));
// the sheet rises over the sidebar, which stays open behind it
if (isOnMobile) settingsSheetOpen = true;
else openDialog(() => (settingsDialogOpen = true));
break;
@ -666,18 +663,18 @@
: ''}"
inert={isStripHidden}
>
<!-- a phone has no footer: its items join these -->
<SidebarNavigationActions
class="px-2 md:my-3"
items={isOnMobile
? [...SIDEBAR_ACTIONS_ITEMS, ...sidebarFooterItems(agenticMode.enabled)]
: undefined}
onAction={handleSidebarAction}
onNavigate={navigateBehind}
/>
<!-- a phone has New chat and Settings pinned under the conversations instead -->
{#if !isOnMobile}
<SidebarNavigationActions
class="px-2 md:my-3"
onAction={handleSidebarAction}
onNavigate={navigateBehind}
/>
{/if}
<!-- on a phone only the conversations scroll, fading out above the pinned keys -->
<div
class="flex min-h-0 flex-1 flex-col overflow-y-auto opacity-(--sidebar-fade) max-md:pb-safe-2"
class="flex min-h-0 flex-1 flex-col overflow-y-auto opacity-(--sidebar-fade) max-md:pb-6 max-md:mask-[linear-gradient(to_bottom,black_calc(100%-1.5rem),transparent)]"
>
<SidebarNavigationConversationList
{allSelectedArePinned}
@ -708,10 +705,38 @@
/>
</div>
<!-- the footer, at the bottom of the sidebar and of its collapsed strip alike (a
phone lists its items with the actions above) -->
<!-- the footer, at the bottom of the sidebar and of its collapsed strip alike; a
phone pins Settings to its left corner and New chat to its right -->
{#if !isOnMobile}
<SidebarNavigationFooter onAction={handleSidebarAction} />
{:else}
<div class="flex shrink-0 items-center justify-between px-2 pb-safe-3">
<ActionIcon
ariaLabel={SIDEBAR_KEYS_TEXT.SETTINGS}
class="matte-key size-12 rounded-full! bg-card! hover:bg-card! dark:bg-muted-foreground/15! dark:hover:bg-muted-foreground/15!"
icon={Settings}
iconSize="size-5"
onclick={() => {
hapticTap();
handleSidebarAction(SidebarAction.SETTINGS);
}}
size="lg"
/>
<!-- the sidebar's main action, so the one primary key on it -->
<Button
class="h-12 rounded-(--chat-form-single-row-radius) text-body"
onclick={() => {
hapticTap();
handleSidebarAction(SidebarAction.NEW_CHAT);
}}
size="lg"
>
<SquarePen class="size-icon-md" />
{SIDEBAR_KEYS_TEXT.NEW_CHAT}
</Button>
</div>
{/if}
</div>
</div>
@ -761,9 +786,13 @@
<DialogSettingsChat bind:open={settingsDialogOpen} />
{#if isOnMobile}
<SettingsSheet bind:open={settingsSheetOpen} />
{/if}
<DialogSearch bind:open={searchOpen} onAction={handleSidebarAction} />
<DialogMcpServers bind:open={mcpDialogOpen} />
<DialogMcpServers bind:open={uiStore.mcpServersOpen} />
<DialogDiscoverModels bind:open={uiStore.discoverModelsOpen} />

View file

@ -1,20 +1,26 @@
<script lang="ts">
import SidebarNavigationActions from './SidebarNavigationActions.svelte';
import { sidebarFooterItems } from '#lib/constants/index.ts';
import { SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts';
import type { SidebarAction } from '#lib/enums/index.ts';
import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts';
import { uiStore } from '#lib/stores/index.ts';
interface Props {
onAction?: (action: SidebarAction) => void;
}
let { onAction }: Props = $props();
// a lone row needs no group around it
let isGrouped = $derived(
SIDEBAR_FOOTER_ITEMS.filter((item) => uiStore.isSidebarActionShown(item.action)).length > 1
);
</script>
<!-- the footer: managing the app around the chats, a group inset in the sidebar, its rows
rounded concentric with it (see the nested surfaces in app.css) -->
<!-- the footer: managing the app around the chats. Two or more rows are a group inset in the
sidebar, rounded concentric with it (see the nested surfaces in app.css); a single row sits
on the sidebar as the top actions do -->
<SidebarNavigationActions
class="inset-group-surface mx-2 mb-2 p-(--surface-group-padding)"
items={sidebarFooterItems(agenticMode.enabled)}
class={isGrouped ? 'inset-group-surface mx-2 mb-2 p-(--surface-group-padding)' : 'mb-2 px-2'}
items={SIDEBAR_FOOTER_ITEMS}
{onAction}
/>

View file

@ -182,7 +182,7 @@ export { default as SidebarNavigationSelectionBar } from './SidebarNavigation/Si
export { default as SidebarNavigationConversationList } from './SidebarNavigation/SidebarNavigationConversationList.svelte';
export { default as SidebarNavigationActions } from './SidebarNavigation/SidebarNavigationActions.svelte';
/** The sidebar's footer: Models, MCP and Settings in a group inset in the sidebar. */
/** The sidebar's footer: Models and Settings in a group inset in the sidebar. */
export { default as SidebarNavigationFooter } from './SidebarNavigation/SidebarNavigationFooter.svelte';
/**

View file

@ -20,9 +20,11 @@
} from '#lib/constants/index.ts';
import { ColorMode } from '#lib/enums/ui.enums.ts';
import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts';
import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts';
import { deviceStore, modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts';
import type { SettingsSection, SettingsSectionTitle } from '#lib/types/index.ts';
import { isSettingShownOn } from '#lib/utils/index.ts';
import { setMode } from 'mode-watcher';
import { tick } from 'svelte';
import { fade } from 'svelte/transition';
interface Props {
initialSection?: string;
@ -36,13 +38,32 @@
const sections = $derived(settingsChatSections(agenticMode.enabled));
let activeSlug = $derived(initialSection ?? 'general');
let activeSlug = $derived(initialSection ?? SETTINGS_SECTION_SLUGS.GENERAL);
let contentEl = $state<HTMLDivElement>();
// a new section starts at its top, whether the dialog, the drawer or the page scrolls
function scrollToTop() {
let el: HTMLElement | null = contentEl ?? null;
while (el) {
const { overflowY } = getComputedStyle(el);
if ((overflowY === 'auto' || overflowY === 'scroll') && el.scrollHeight > el.clientHeight)
break;
el = el.parentElement;
}
(el ?? document.scrollingElement)?.scrollTo({ top: 0 });
}
function handleSectionChange(section: SettingsSectionTitle) {
const found = sections.find((s) => s.title === section);
if (found) {
if (found && found.slug !== activeSlug) {
activeSlug = found.slug;
void tick().then(scrollToTop);
}
onSectionChange?.(section);
@ -54,6 +75,11 @@
let localConfig: SettingsConfigType = $state({ ...settingsStore.config });
// a setting for another kind of device is left out
let sectionFields = $derived(
(currentSection.fields ?? []).filter((field) => isSettingShownOn(field, deviceStore.isMobile))
);
// inputs hand back strings for numeric fields, so compare stringified values
let hasChanges = $derived.by(() => {
const saved = settingsStore.config;
@ -176,7 +202,7 @@
{sections}
/>
<div class="mx-auto max-w-2xl px-4 flex-1 md:mt-4">
<div bind:this={contentEl} class="mx-auto max-w-2xl px-4 flex-1 md:mt-4">
<div class="space-y-6 pt-3">
<div class="grid">
{#if currentSection.slug === SETTINGS_SECTION_SLUGS.TOOLS}
@ -185,14 +211,14 @@
<SettingsChatImportExportTab />
{:else if currentSection.slug === SETTINGS_SECTION_SLUGS.VOICE && currentSection.fields}
<SettingsChatVoiceTab
fields={currentSection.fields}
fields={sectionFields}
{localConfig}
onConfigChange={handleConfigChange}
/>
{:else if currentSection.fields}
<div class="space-y-6">
<SettingsChatFields
fields={currentSection.fields}
fields={sectionFields}
{localConfig}
onConfigChange={handleConfigChange}
onThemeChange={handleThemeChange}

View file

@ -1,4 +1,5 @@
<script lang="ts">
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';
@ -6,15 +7,18 @@
import * as Select from '@ggml-org/llama-ui/ui/select';
import { Textarea } from '@ggml-org/llama-ui/ui/textarea';
import { FlaskConical, RotateCcw } from '@lucide/svelte';
import McpLogo from '#lib/components/app/mcp/McpLogo.svelte';
import { SettingsChatParameterSourceIndicator } from '#lib/components/app/settings/index.ts';
import {
ICON_CLASS_DEFAULT,
ICON_CLASS_SM,
MANAGE_MCP_SERVERS_LABEL,
SETTING_CONFIG_INFO,
SETTINGS_KEYS
} from '#lib/constants/index.ts';
import { SettingsFieldType } from '#lib/enums/settings.enums.ts';
import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts';
import { useSettingsFieldDefaults } from '#lib/hooks/use-settings-field-defaults.svelte.ts';
import { settingsStore, uiStore } from '#lib/stores/index.ts';
import { normalizeFloatingPoint } from '#lib/utils/precision.ts';
import type { Component } from 'svelte';
@ -27,35 +31,8 @@
let { fields, localConfig, onConfigChange, onThemeChange }: Props = $props();
// discover needs the hub metadata reads, and opens from the Models page, so both checkboxes
// are read-only while discover is on
let discoverOn = $derived(Boolean(localConfig[SETTINGS_KEYS.ENABLE_DISCOVER_MODELS]));
function isLockedField(key: string): boolean {
return (
discoverOn &&
(key === SETTINGS_KEYS.USE_HUGGING_FACE_HUB || key === SETTINGS_KEYS.SHOW_MODELS_MANAGER)
);
}
let currentModelParams = $derived.by(() => {
void modelsStore.props.cacheVersion;
if (serverStore.isRouterMode) {
const currentModelName = modelsStore.selectedModelName;
if (currentModelName) {
const currentModelProps = modelsStore.props.getModelProps(currentModelName);
return (currentModelProps?.default_generation_settings?.params ?? {}) as Record<
string,
unknown
>;
}
}
return (serverStore.defaultParams ?? {}) as Record<string, unknown>;
});
const fieldDefaults = useSettingsFieldDefaults(() => localConfig);
let currentModelParams = $derived(fieldDefaults.serverDefaults);
</script>
{#each fields as field (field.key)}
@ -63,23 +40,7 @@
<div class={field.dependsOn ? 'space-y-2 pl-6' : 'space-y-2'}>
{#if field.type === SettingsFieldType.INPUT}
{@const currentValue = String(localConfig[field.key] ?? '')}
{@const serverDefault = currentModelParams[field.key]}
{@const isCustomRealTime = (() => {
if (serverDefault == null) return false;
if (currentValue === '') return false;
const numericInput = parseFloat(currentValue);
const normalizedInput = !isNaN(numericInput)
? Math.round(numericInput * 1000000) / 1000000
: currentValue;
const normalizedDefault =
typeof serverDefault === 'number'
? Math.round(serverDefault * 1000000) / 1000000
: serverDefault;
return normalizedInput !== normalizedDefault;
})()}
{@const isCustomRealTime = fieldDefaults.isCustom(field)}
<div class="flex items-center gap-2">
<Label class="flex items-center gap-1.5 text-label" for={field.key}>
@ -97,7 +58,7 @@
<div class="relative w-full">
<Input
autocomplete={field.isPrivate ? 'new-password' : undefined}
autocomplete={field.isPrivate ? 'new-password' : 'off'}
id={field.key}
type={field.isPrivate ? 'password' : field.isPositiveInteger ? 'number' : 'text'}
{...field.isPositiveInteger
@ -151,7 +112,7 @@
class="min-h-40 w-full md:max-w-3xl"
id={field.key}
oninput={(e) => onConfigChange(field.key, e.currentTarget.value)}
placeholder=""
placeholder={field.placeholder ?? ''}
value={String(localConfig[field.key] ?? '')}
/>
@ -181,14 +142,7 @@
opt.value === localConfig[field.key]
)}
{@const currentValue = localConfig[field.key]}
{@const serverDefault = currentModelParams[field.key]}
{@const isCustomRealTime = (() => {
if (serverDefault == null) return false;
if (currentValue === '' || currentValue === undefined) return false;
return currentValue !== serverDefault;
})()}
{@const isCustomRealTime = fieldDefaults.isCustom(field)}
<div class="flex items-center gap-2">
<Label class="flex items-center gap-1.5 text-label" for={field.key}>
@ -317,14 +271,14 @@
<Checkbox
checked={Boolean(localConfig[field.key])}
class="mt-1"
disabled={isLockedField(field.key)}
disabled={fieldDefaults.isLocked(field.key)}
id={field.key}
onCheckedChange={(checked) => onConfigChange(field.key, checked)}
/>
<div class="space-y-1">
<label
class="flex items-center gap-1.5 pt-1 pb-0.5 text-label leading-none {isLockedField(
class="flex items-center gap-1.5 pt-1 pb-0.5 text-label leading-none {fieldDefaults.isLocked(
field.key
)
? 'cursor-default opacity-80'
@ -343,6 +297,19 @@
{field.help || SETTING_CONFIG_INFO[field.key]}
</p>
{/if}
{#if field.key === SETTINGS_KEYS.ENABLE_MCP && Boolean(localConfig[field.key])}
<Button
class="mt-2"
onclick={() => uiStore.openMcpServers()}
size="sm"
variant="outline"
>
<McpLogo class="size-icon-md" />
{MANAGE_MCP_SERVERS_LABEL}
</Button>
{/if}
</div>
</div>
{/if}

View file

@ -0,0 +1,338 @@
<!--
The settings fields as a phone's native inset list: switches, pickers and numbers as rows of
one group, prompts and choices of one as groups of their own, each help text under its label.
A change is handed on when it is made: a switch or a pick at once, typed text once it is left.
-->
<script lang="ts">
import { NativeSelect } from '@ggml-org/llama-ui/app/forms';
import { InsetList, InsetListRow } from '@ggml-org/llama-ui/app/sheets';
import { Switch } from '@ggml-org/llama-ui/ui/switch';
import { Textarea } from '@ggml-org/llama-ui/ui/textarea';
import { Check, FlaskConical, RotateCcw } from '@lucide/svelte';
import McpLogo from '#lib/components/app/mcp/McpLogo.svelte';
import {
MANAGE_MCP_SERVERS_LABEL,
NUMERIC_FIELDS,
SETTING_CONFIG_INFO,
SETTINGS_KEYS,
SETTINGS_SHEET_TEXT
} from '#lib/constants/index.ts';
import { SettingsFieldBlock, SettingsFieldType } from '#lib/enums/settings.enums.ts';
import { useSettingsFieldDefaults } from '#lib/hooks/use-settings-field-defaults.svelte.ts';
import { settingsStore, uiStore } from '#lib/stores/index.ts';
import { normalizeFloatingPoint } from '#lib/utils/precision.ts';
import { tick } from 'svelte';
interface Props {
/** The subgroup's title, shown above its first group of rows. */
title?: string;
fields: SettingsFieldConfig[];
localConfig: SettingsConfigType;
onConfigChange: (key: string, value: string | boolean) => void;
/** Opens the MCP servers as a page of the sheet; without it, they open in their dialog */
onManageMcpServers?: () => void;
onThemeChange?: (theme: string) => void;
}
let { fields, localConfig, onConfigChange, onManageMcpServers, onThemeChange, title }: Props =
$props();
/** Rows share a group; a prompt or a choice of one gets a group of its own. */
type Block =
| { fields: SettingsFieldConfig[]; kind: SettingsFieldBlock.ROWS }
| { field: SettingsFieldConfig; kind: SettingsFieldBlock.OWN };
const fieldDefaults = useSettingsFieldDefaults(() => localConfig);
let visibleFields = $derived(
fields.filter((field) => !field.dependsOn || Boolean(localConfig[field.dependsOn]))
);
let blocks = $derived.by(() => {
const result: Block[] = [];
for (const field of visibleFields) {
const ownGroup =
field.type === SettingsFieldType.TEXTAREA ||
field.type === SettingsFieldType.RADIO ||
(field.type === SettingsFieldType.INPUT && !isNumeric(field));
if (ownGroup) {
result.push({ field, kind: SettingsFieldBlock.OWN });
continue;
}
const last = result[result.length - 1];
if (last?.kind === SettingsFieldBlock.ROWS) last.fields.push(field);
else result.push({ fields: [field], kind: SettingsFieldBlock.ROWS });
}
return result;
});
function isNumeric(field: SettingsFieldConfig): boolean {
return field.isPositiveInteger || NUMERIC_FIELDS.includes(field.key);
}
// a prompt alone in a subgroup of its own name needs the name only once
function ownCaption(field: SettingsFieldConfig): string | null {
return title && field.label.toLowerCase() === title.toLowerCase() ? null : field.label;
}
function helpOf(field: SettingsFieldConfig): string | undefined {
return field.help || SETTING_CONFIG_INFO[field.key] || undefined;
}
function valueOf(key: string): string {
return String(localConfig[key] ?? '');
}
// typed text is handed on once the field is left; a value that was not taken (not a number,
// invalid JSON) or was adjusted gives way to the saved one
function handleTextChange(
event: Event & { currentTarget: HTMLInputElement | HTMLTextAreaElement }
) {
const input = event.currentTarget;
const key = input.name;
onConfigChange(key, input.value);
void tick().then(() => (input.value = valueOf(key)));
}
function resetToDefault(key: string) {
settingsStore.resetParameterToServerDefault(key);
onConfigChange(key, '');
}
</script>
{#if blocks.length > 0}
<div class="flex flex-col gap-1.5">
{#if title}
<h3 class="inset-list-title">{title}</h3>
{/if}
<div class="flex flex-col gap-6">
{#each blocks as block, index (block.kind === SettingsFieldBlock.OWN ? block.field.key : `${block.kind}-${index}`)}
{#if block.kind === SettingsFieldBlock.ROWS}
<InsetList>
{#each block.fields as field (field.key)}
{#if field.type === SettingsFieldType.CHECKBOX}
{@render switchRow(field)}
{:else if field.type === SettingsFieldType.SELECT}
{@render selectRow(field)}
{:else}
{@render numberRow(field)}
{/if}
{#if field.key === SETTINGS_KEYS.ENABLE_MCP && Boolean(localConfig[field.key])}
<InsetListRow
chevron
onclick={() =>
onManageMcpServers ? onManageMcpServers() : uiStore.openMcpServers()}
>
{#snippet leading()}
<McpLogo class="size-icon-md shrink-0" />
{/snippet}
<span class="flex-1">{MANAGE_MCP_SERVERS_LABEL}</span>
</InsetListRow>
{/if}
{/each}
</InsetList>
{:else}
{@const field = block.field}
{@const help = helpOf(field)}
{@const showCaption = index > 0 || ownCaption(field) !== null}
<div class="flex flex-col gap-1.5">
{#if showCaption}
<h3
class={[
title ? 'inset-list-caption' : 'inset-list-title',
'flex items-center gap-1.5'
]}
>
{field.label}
{#if field.isExperimental}
<FlaskConical class="size-icon-sm" />
{/if}
</h3>
{/if}
<InsetList>
{#if field.type === SettingsFieldType.TEXTAREA}
<Textarea
aria-label={field.label}
class="min-h-32 resize-none rounded-none border-0! bg-transparent! px-4 py-3 text-body shadow-none! focus-visible:ring-0 dark:bg-transparent!"
name={field.key}
onchange={handleTextChange}
placeholder={field.placeholder ?? ''}
value={valueOf(field.key)}
/>
{#if field.key === SETTINGS_KEYS.SYSTEM_MESSAGE}
<InsetListRow as="label" bodyClass="gap-4 py-3">
<span class="flex-1">{SETTINGS_SHEET_TEXT.SHOW_SYSTEM_MESSAGE}</span>
<Switch
checked={Boolean(localConfig[SETTINGS_KEYS.SHOW_SYSTEM_MESSAGE])}
onCheckedChange={(checked) =>
onConfigChange(SETTINGS_KEYS.SHOW_SYSTEM_MESSAGE, checked)}
size="lg"
/>
</InsetListRow>
{/if}
{:else if field.type === SettingsFieldType.RADIO && field.radioOptions}
{@const radioOptions = field.radioOptions}
{@const currentMode =
radioOptions.find((option: { key: string; value: string }) =>
Boolean(localConfig[option.key])
)?.value ?? radioOptions[0].value}
{#each radioOptions as option (option.value)}
<!-- an option's name can run to two lines, so the row grows with it -->
<InsetListRow
aria-pressed={option.value === currentMode}
bodyClass="gap-4 py-3"
onclick={() => {
for (const opt of radioOptions)
onConfigChange(opt.key, opt.value === option.value);
}}
>
<span class="flex flex-1 items-center gap-1.5 leading-snug">
{option.label}
{#if option.isExperimental}
<FlaskConical class="size-icon-sm text-muted-foreground" />
{/if}
</span>
{#if option.value === currentMode}
<Check class="size-4 text-(--action-primary)" />
{/if}
</InsetListRow>
{/each}
{:else}
<!-- text: a key, a name, a language; typed on a line of its own -->
<input
aria-label={field.label}
autocomplete={field.isPrivate ? 'new-password' : 'off'}
class="min-h-12 w-full border-0 bg-transparent px-4 text-body shadow-none outline-none placeholder:text-muted-foreground focus:ring-0"
name={field.key}
onchange={handleTextChange}
placeholder={field.placeholder ?? ''}
type={field.isPrivate ? 'password' : 'text'}
value={valueOf(field.key)}
/>
{/if}
</InsetList>
{#if help}
<!-- eslint-disable-next-line svelte/no-at-html-tags -- help text comes from the settings registry -->
<p class="inset-list-caption">{@html help}</p>
{/if}
</div>
{/if}
{/each}
</div>
</div>
{/if}
{#snippet rowLabel(field: SettingsFieldConfig)}
{@const help = helpOf(field)}
<span class="flex min-w-0 flex-1 flex-col gap-0.5 py-3">
<span class="flex items-center gap-1.5">
{field.label}
{#if field.isExperimental}
<FlaskConical class="size-icon-sm shrink-0 text-muted-foreground" />
{/if}
</span>
{#if help}
<!-- eslint-disable-next-line svelte/no-at-html-tags -- help text comes from the settings registry -->
<span class="text-caption text-muted-foreground">{@html help}</span>
{/if}
</span>
{/snippet}
{#snippet switchRow(field: SettingsFieldConfig)}
{@const locked = fieldDefaults.isLocked(field.key)}
<InsetListRow
as="label"
bodyClass={['gap-4', field.dependsOn && 'pl-4']}
class={locked ? 'cursor-default opacity-60' : undefined}
>
{@render rowLabel(field)}
<Switch
checked={Boolean(localConfig[field.key])}
disabled={locked}
onCheckedChange={(checked) => onConfigChange(field.key, checked)}
size="lg"
/>
</InsetListRow>
{/snippet}
{#snippet selectRow(field: SettingsFieldConfig)}
<InsetListRow as="div" bodyClass="gap-4">
{@render rowLabel(field)}
<NativeSelect
label={field.label}
onValueChange={(value) => {
if (field.key === SETTINGS_KEYS.THEME && value && onThemeChange) onThemeChange(value);
else onConfigChange(field.key, value);
}}
options={(field.options ?? []).map((option: { value: string; label: string }) => ({
label: option.label,
value: option.value
}))}
value={valueOf(field.key)}
variant="inset"
/>
</InsetListRow>
{/snippet}
{#snippet numberRow(field: SettingsFieldConfig)}
{@const custom = fieldDefaults.isCustom(field)}
{@const serverDefault = fieldDefaults.serverDefaults[field.key]}
<InsetListRow as="div" bodyClass="gap-3">
{@render rowLabel(field)}
{#if custom}
<button
aria-label={SETTINGS_SHEET_TEXT.RESET_FIELD(field.label)}
class="flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground active:bg-(--surface-pressed)"
onclick={() => resetToDefault(field.key)}
type="button"
>
<RotateCcw class="size-3.5" />
</button>
{/if}
<!-- 16px at least, or iOS zooms the page in on focus -->
<input
aria-label={field.label}
autocomplete="off"
class={[
'h-9 w-20 shrink-0 rounded-lg border-0 bg-(--surface-muted) px-2.5 text-right text-body tabular-nums shadow-none outline-none placeholder:text-muted-foreground focus:ring-1 focus:ring-(--line-focus)',
custom && 'text-foreground'
]}
inputmode="decimal"
name={field.key}
onchange={handleTextChange}
placeholder={serverDefault != null
? String(normalizeFloatingPoint(serverDefault))
: (field.placeholder ?? '')}
type="text"
value={valueOf(field.key)}
/>
</InsetListRow>
{/snippet}

View file

@ -1,4 +1,5 @@
<script lang="ts">
import { InsetListRow } from '@ggml-org/llama-ui/app/sheets';
import { Button, type ButtonVariant } from '@ggml-org/llama-ui/ui/button';
import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts';
import type { Component } from 'svelte';
@ -9,6 +10,7 @@
buttonVariant,
description,
IconComponent,
inset = false,
onclick,
summary,
title,
@ -18,6 +20,8 @@
title: string;
description: string;
IconComponent: Component;
/** Draw it as a row of a phone's inset list, its action as the row's name. */
inset?: boolean;
buttonText: string;
onclick: () => void;
titleClass?: string;
@ -29,35 +33,57 @@
let sectionButtonClass = $derived(buttonClass ?? 'justify-start justify-self-start md:w-auto');
let sectionButtonVariant = $derived(buttonVariant ?? 'outline');
let isDestructive = $derived(buttonVariant === 'destructive');
</script>
<div class="grid gap-1 {wrapperClass ?? ''}">
<h4 class="mt-0 mb-2 text-label {titleClass ?? ''}">{title}</h4>
{#snippet summaryList(summary: { verb: string; items: DatabaseConversation[] })}
<h5 class="mb-2 text-label">
{summary.verb}
{summary.items.length} conversation{summary.items.length === 1 ? '' : 's'}
</h5>
<p class="mb-4 text-body-sm text-muted-foreground">{description}</p>
<ul class="space-y-1 text-body-sm text-muted-foreground">
{#each summary.items.slice(0, 10) as conv (conv.id)}
<li class="truncate">• {conv.name || 'Untitled conversation'}</li>
{/each}
<Button class={sectionButtonClass} {onclick} variant={sectionButtonVariant}>
<IconComponent class="mr-2 {ICON_CLASS_DEFAULT}" />
{#if summary.items.length > 10}
<li class="italic">... and {summary.items.length - 10} more</li>
{/if}
</ul>
{/snippet}
{buttonText}
</Button>
{#if inset}
<InsetListRow
bodyClass="flex-col items-stretch gap-0.5 py-3"
icon={IconComponent}
iconClass={['mt-3.5 self-start', isDestructive && 'text-destructive']}
{onclick}
>
<span class={isDestructive ? 'text-destructive' : undefined}>{buttonText}</span>
{#if summary && summary.show && summary.items.length > 0}
<div class="mt-4 grid overflow-x-auto rounded-lg border border-border/50 bg-muted/30 p-4">
<h5 class="mb-2 text-label">
{summary.verb}
{summary.items.length} conversation{summary.items.length === 1 ? '' : 's'}
</h5>
<span class="text-caption text-muted-foreground">{description}</span>
<ul class="space-y-1 text-body-sm text-muted-foreground">
{#each summary.items.slice(0, 10) as conv (conv.id)}
<li class="truncate">• {conv.name || 'Untitled conversation'}</li>
{/each}
{#if summary && summary.show && summary.items.length > 0}
<span class="mt-2 block">{@render summaryList(summary)}</span>
{/if}
</InsetListRow>
{:else}
<div class="grid gap-1 {wrapperClass ?? ''}">
<h4 class="mt-0 mb-2 text-label {titleClass ?? ''}">{title}</h4>
{#if summary.items.length > 10}
<li class="italic">... and {summary.items.length - 10} more</li>
{/if}
</ul>
</div>
{/if}
</div>
<p class="mb-4 text-body-sm text-muted-foreground">{description}</p>
<Button class={sectionButtonClass} {onclick} variant={sectionButtonVariant}>
<IconComponent class="mr-2 {ICON_CLASS_DEFAULT}" />
{buttonText}
</Button>
{#if summary && summary.show && summary.items.length > 0}
<div class="mt-4 grid overflow-x-auto rounded-lg border border-border/50 bg-muted/30 p-4">
{@render summaryList(summary)}
</div>
{/if}
</div>
{/if}

View file

@ -1,11 +1,13 @@
<script lang="ts">
import SettingsChatImportDropZone from './SettingsChatImportDropZone.svelte';
import SettingsChatImportExportSection from './SettingsChatImportExportSection.svelte';
import { InsetList, InsetListRow } from '@ggml-org/llama-ui/app/sheets';
import { Button } from '@ggml-org/llama-ui/ui/button';
import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox';
import { Label } from '@ggml-org/llama-ui/ui/label';
import * as RadioGroup from '@ggml-org/llama-ui/ui/radio-group';
import { Download, Trash2 } from '@lucide/svelte';
import { Switch } from '@ggml-org/llama-ui/ui/switch';
import { Check, Download, Trash2 } from '@lucide/svelte';
import { DialogConfirmation, DialogConversationSelection } from '#lib/components/app/index.ts';
import SettingsGroup from '#lib/components/app/settings/SettingsGroup.svelte';
import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts';
@ -16,6 +18,33 @@
import { fade } from 'svelte/transition';
import { toast } from 'svelte-sonner';
interface Props {
/** Draw the actions as a phone's inset list, for the settings sheet. */
inset?: boolean;
}
let { inset = false }: Props = $props();
const FADE_MS = 150;
const TEXT = {
DELETE: 'Delete',
DELETE_ALL: 'Delete all conversations',
DELETE_ALL_NOTE:
'Permanently delete all conversations and their messages. This action cannot be undone. Consider exporting your conversations first if you want to keep a backup.',
DELETE_ALL_TITLE: 'Delete All',
EXPORT: 'Export',
IMPORT: 'Import',
IMPORT_NOTE:
'Bring in one or more conversations, your settings, or both at once. You see what each file holds before anything changes; conversations already in your library are left as they are.',
IMPORT_NOTE_SHORT:
'Conversations, your settings or both, from a .jsonl, a .zip or a .json. You see what each file holds before anything changes.',
INCLUDE_SENSITIVE: 'Include API keys and MCP server headers',
SENSITIVE_INCLUDED:
'The file will hold your credentials: share it with no one you do not trust.',
SENSITIVE_LEFT_OUT: 'Left out by default to keep your credentials safe.'
} as const;
const EXPORT_OPTIONS = [
{
description: 'Pick which ones: one is saved as a JSONL file, several as a ZIP.',
@ -138,77 +167,154 @@
}
</script>
<div in:fade={{ duration: 150 }} class="space-y-12">
<SettingsGroup title="Import">
<p class="text-body-sm text-muted-foreground">
Bring in one or more conversations, your settings, or both at once. You see what each file
holds before anything changes; conversations already in your library are left as they are.
</p>
{#snippet sensitiveNote()}
{includeSensitiveData ? TEXT.SENSITIVE_INCLUDED : TEXT.SENSITIVE_LEFT_OUT}
{/snippet}
<SettingsChatImportDropZone />
</SettingsGroup>
{#if inset}
<div in:fade={{ duration: FADE_MS }} class="flex flex-col gap-8">
<!-- the drop zone is its own surface, so it takes a group's title and caption, not its box -->
<div class="flex flex-col gap-1.5">
<h3 class="inset-list-title">{TEXT.IMPORT}</h3>
<SettingsGroup title="Export">
<RadioGroup.Root
class="gap-3"
onValueChange={(value) => (exportScope = value as DataExportScope)}
value={exportScope}
>
{#each EXPORT_OPTIONS as option (option.value)}
{@const id = `export-${option.value}`}
<SettingsChatImportDropZone />
<div class="flex items-start gap-3">
<RadioGroup.Item class="mt-0.5" {id} value={option.value} />
<p class="inset-list-caption">{TEXT.IMPORT_NOTE_SHORT}</p>
</div>
<Label class="grid cursor-pointer gap-0.5" for={id}>
<span class="text-label">{option.label}</span>
<div class="flex flex-col gap-6">
<InsetList title={TEXT.EXPORT}>
{#each EXPORT_OPTIONS as option (option.value)}
{@const selected = exportScope === option.value}
<span class="text-caption font-normal text-muted-foreground">{option.description}</span>
</Label>
<InsetListRow
aria-pressed={selected}
bodyClass="gap-3"
onclick={() => (exportScope = option.value)}
>
<span class="flex flex-1 flex-col gap-0.5 py-3">
<span>{option.label}</span>
<span class="text-caption text-muted-foreground">{option.description}</span>
</span>
{#if selected}
<Check class="size-4 shrink-0 text-(--action-primary)" />
{/if}
</InsetListRow>
{/each}
{#if exportsSettings}
<InsetListRow as="label" bodyClass="gap-3">
<span class="flex flex-1 flex-col gap-0.5 py-3">
<span>{TEXT.INCLUDE_SENSITIVE}</span>
<span
class={[
'text-caption',
includeSensitiveData ? 'text-destructive' : 'text-muted-foreground'
]}
>
{@render sensitiveNote()}
</span>
</span>
<Switch bind:checked={includeSensitiveData} size="lg" />
</InsetListRow>
{/if}
</InsetList>
<InsetList>
<InsetListRow icon={Download} onclick={handleExport}>{TEXT.EXPORT}</InsetListRow>
</InsetList>
</div>
<InsetList title={TEXT.DELETE}>
<SettingsChatImportExportSection
IconComponent={Trash2}
buttonText={TEXT.DELETE_ALL}
buttonVariant="destructive"
description={TEXT.DELETE_ALL_NOTE}
inset
onclick={handleDeleteAllClick}
title={TEXT.DELETE_ALL_TITLE}
/>
</InsetList>
</div>
{:else}
<div in:fade={{ duration: FADE_MS }} class="space-y-12">
<SettingsGroup title={TEXT.IMPORT}>
<p class="text-body-sm text-muted-foreground">
{TEXT.IMPORT_NOTE}
</p>
<SettingsChatImportDropZone />
</SettingsGroup>
<SettingsGroup title={TEXT.EXPORT}>
<RadioGroup.Root
class="gap-3"
onValueChange={(value) => (exportScope = value as DataExportScope)}
value={exportScope}
>
{#each EXPORT_OPTIONS as option (option.value)}
{@const id = `export-${option.value}`}
<div class="flex items-start gap-3">
<RadioGroup.Item class="mt-0.5" {id} value={option.value} />
<Label class="grid cursor-pointer gap-0.5" for={id}>
<span class="text-label">{option.label}</span>
<span class="text-caption font-normal text-muted-foreground"
>{option.description}</span
>
</Label>
</div>
{/each}
</RadioGroup.Root>
{#if exportsSettings}
<div transition:fade={{ duration: FADE_MS }} class="grid gap-1">
<div class="flex items-center gap-2">
<Checkbox bind:checked={includeSensitiveData} id="export-sensitive" />
<Label class="text-body-sm font-normal" for="export-sensitive">
{TEXT.INCLUDE_SENSITIVE}
</Label>
</div>
<p
class="text-caption {includeSensitiveData
? 'text-destructive'
: 'text-muted-foreground'}"
>
{@render sensitiveNote()}
</p>
</div>
{/each}
</RadioGroup.Root>
{/if}
{#if exportsSettings}
<div transition:fade={{ duration: 150 }} class="grid gap-1">
<div class="flex items-center gap-2">
<Checkbox bind:checked={includeSensitiveData} id="export-sensitive" />
<Button class="justify-self-start" onclick={handleExport} variant="outline">
<Download class="mr-2 {ICON_CLASS_DEFAULT}" />
<Label class="text-body-sm font-normal" for="export-sensitive">
Include API keys and MCP server headers
</Label>
</div>
{TEXT.EXPORT}
</Button>
</SettingsGroup>
<p
class="text-caption {includeSensitiveData ? 'text-destructive' : 'text-muted-foreground'}"
>
{includeSensitiveData
? 'The file will hold your credentials: share it with no one you do not trust.'
: 'Left out by default to keep your credentials safe.'}
</p>
</div>
{/if}
<Button class="justify-self-start" onclick={handleExport} variant="outline">
<Download class="mr-2 {ICON_CLASS_DEFAULT}" />
Export
</Button>
</SettingsGroup>
<SettingsGroup title="Delete">
<SettingsChatImportExportSection
IconComponent={Trash2}
buttonClass="justify-start justify-self-start md:w-auto"
buttonText="Delete all conversations"
buttonVariant="destructive"
description="Permanently delete all conversations and their messages. This action cannot be undone. Consider exporting your conversations first if you want to keep a backup."
onclick={handleDeleteAllClick}
title="Delete All"
titleClass="text-destructive"
/>
</SettingsGroup>
</div>
<SettingsGroup title={TEXT.DELETE}>
<SettingsChatImportExportSection
IconComponent={Trash2}
buttonClass="justify-start justify-self-start md:w-auto"
buttonText={TEXT.DELETE_ALL}
buttonVariant="destructive"
description={TEXT.DELETE_ALL_NOTE}
onclick={handleDeleteAllClick}
title={TEXT.DELETE_ALL_TITLE}
titleClass="text-destructive"
/>
</SettingsGroup>
</div>
{/if}
<DialogConversationSelection
bind:open={showExportDialog}
@ -227,6 +333,6 @@
icon={Trash2}
onCancel={handleDeleteAllCancel}
onConfirm={handleDeleteAllConfirm}
title="Delete all conversations"
title={TEXT.DELETE_ALL}
variant="destructive"
/>

View file

@ -6,68 +6,18 @@
import { McpServerIdentity, TruncatedText } from '#lib/components/app/index.ts';
import {
ICON_CLASS_DEFAULT,
SETTINGS_KEYS,
TOOL_CALL_SHOWN_ARG_NONE
TOOL_SETTINGS_TEXT,
TOOL_SHOWN_ARG_PICK
} from '#lib/constants/index.ts';
import { ToolSource } from '#lib/enums/tools.enums.ts';
import {
conversationsStore,
mcpStore,
permissionsStore,
settingsStore,
toolsStore
} from '#lib/stores/index.ts';
import type { OpenAIToolDefinition } from '#lib/types/index.ts';
import { getToolUi, parseToolCallShownArgOverrides } from '#lib/utils/index.ts';
import { useToolSettings } from '#lib/hooks/use-tool-settings.svelte.ts';
import { conversationsStore, mcpStore, permissionsStore, toolsStore } from '#lib/stores/index.ts';
import { getToolArgNames, getToolDisplay } from '#lib/utils/index.ts';
import { SvelteSet } from 'svelte/reactivity';
// the shown-argument picks: a tool follows the global setting until it gets one of its own
const SHOWN_ARG_DEFAULT = '__default__';
const SHOWN_ARG_NONE = '__none__';
const toolSettings = useToolSettings();
let expandedGroups = new SvelteSet<string>();
let groups = $derived(toolsStore.toolGroups);
let shownArgOverrides = $derived(
parseToolCallShownArgOverrides(
settingsStore.config[SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES]
)
);
let globalShownArg = $derived(
String(settingsStore.config[SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG] ?? '').trim()
);
function argNames(definition: OpenAIToolDefinition): string[] {
const properties = (definition.function.parameters as { properties?: object } | undefined)
?.properties;
return properties ? Object.keys(properties) : [];
}
function shownArgPick(toolName: string): string {
const own = shownArgOverrides[toolName];
if (own === undefined) return SHOWN_ARG_DEFAULT;
return own === TOOL_CALL_SHOWN_ARG_NONE ? SHOWN_ARG_NONE : own;
}
function shownArgLabel(pick: string): string {
if (pick === SHOWN_ARG_NONE) return 'None';
if (pick === SHOWN_ARG_DEFAULT)
return globalShownArg ? `Default (${globalShownArg})` : 'Default';
return pick;
}
function setShownArg(toolName: string, pick: string) {
const next = { ...shownArgOverrides };
if (pick === SHOWN_ARG_DEFAULT) delete next[toolName];
else next[toolName] = pick === SHOWN_ARG_NONE ? TOOL_CALL_SHOWN_ARG_NONE : pick;
settingsStore.updateConfig(SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES, JSON.stringify(next));
}
function toggleExpanded(key: string) {
if (expandedGroups.has(key)) {
@ -79,15 +29,13 @@
</script>
{#if groups.length === 0}
<div class="py-8 text-center text-body-sm text-muted-foreground">No tools available</div>
<div class="py-8 text-center text-body-sm text-muted-foreground">
{TOOL_SETTINGS_TEXT.NO_TOOLS}
</div>
{:else}
<div class="space-y-2">
<p class="text-body-sm text-muted-foreground">
{#if conversationsStore.activeConversation}
Applies to this conversation.
{:else}
Applies to new conversations. Tool picks inside a chat only affect that chat.
{/if}
{toolSettings.scopeNote}
</p>
{#each groups as group (group.key)}
@ -149,16 +97,13 @@
{#each group.tools as entry (entry.key)}
{@const toolName = entry.definition.function.name}
{@const toolUi =
entry.source === ToolSource.SERVER || entry.source === ToolSource.BROWSER
? getToolUi(toolName)
: null}
{@const displayLabel = toolUi?.label ?? toolName}
{@const IconComponent = toolUi?.icon ?? null}
{@const display = getToolDisplay(entry)}
{@const displayLabel = display.label}
{@const IconComponent = display.icon}
{@const isEnabled = conversationsStore.preferences.isToolEnabled(entry.key)}
{@const permissionKey = entry.key}
{@const isAlwaysAllowed = permissionsStore.hasTool(permissionKey)}
{@const shownArg = shownArgPick(toolName)}
{@const shownArg = toolSettings.shownArgPick(toolName)}
<div
class="flex items-center gap-2 rounded px-2 py-1.5 text-body-sm hover:bg-muted/50"
@ -196,7 +141,7 @@
<div class="w-32 shrink-0">
<Select.Root
onValueChange={(value) => setShownArg(toolName, value)}
onValueChange={(value) => toolSettings.setShownArg(toolName, value)}
type="single"
value={shownArg}
>
@ -206,21 +151,28 @@
size="sm"
>
<span class="truncate">
{shownArg === SHOWN_ARG_DEFAULT ? 'Default' : shownArgLabel(shownArg)}
{shownArg === TOOL_SHOWN_ARG_PICK.DEFAULT
? TOOL_SETTINGS_TEXT.SHOWN_ARG_DEFAULT
: toolSettings.shownArgLabel(shownArg)}
</span>
</Select.Trigger>
<Select.Content>
<Select.Item
label={shownArgLabel(SHOWN_ARG_DEFAULT)}
value={SHOWN_ARG_DEFAULT}
label={toolSettings.shownArgLabel(TOOL_SHOWN_ARG_PICK.DEFAULT)}
value={TOOL_SHOWN_ARG_PICK.DEFAULT}
>
{shownArgLabel(SHOWN_ARG_DEFAULT)}
{toolSettings.shownArgLabel(TOOL_SHOWN_ARG_PICK.DEFAULT)}
</Select.Item>
<Select.Item label="None" value={SHOWN_ARG_NONE}>None</Select.Item>
<Select.Item
label={TOOL_SETTINGS_TEXT.SHOWN_ARG_NONE}
value={TOOL_SHOWN_ARG_PICK.NONE}
>
{TOOL_SETTINGS_TEXT.SHOWN_ARG_NONE}
</Select.Item>
{#each argNames(entry.definition) as arg (arg)}
{#each getToolArgNames(entry.definition) as arg (arg)}
<Select.Item label={arg} value={arg}>
<span class="font-mono">{arg}</span>
</Select.Item>

View file

@ -4,6 +4,8 @@
are drawn here.
-->
<script lang="ts">
import { NativeSelect } from '@ggml-org/llama-ui/app/forms';
import { InsetList, InsetListRow } from '@ggml-org/llama-ui/app/sheets';
import { Label } from '@ggml-org/llama-ui/ui/label';
import * as Select from '@ggml-org/llama-ui/ui/select';
import {
@ -12,7 +14,10 @@
VOICE_MICROPHONE_AUTO,
VOICE_MICROPHONE_DEFAULT
} from '@ggml-org/llama-voice';
import { SettingsChatFields } from '#lib/components/app/settings/index.ts';
import {
SettingsChatFields,
SettingsChatFieldsInset
} from '#lib/components/app/settings/index.ts';
import {
SETTING_CONFIG_INFO,
SETTINGS_KEYS,
@ -22,19 +27,40 @@
} from '#lib/constants/index.ts';
import { modelsStore, serverStore } from '#lib/stores/index.ts';
import { isTranscriptionOnlyModel } from '#lib/utils/voice-mode.ts';
import { onMount } from 'svelte';
import { onMount, type Snippet } from 'svelte';
interface Props {
fields: SettingsFieldConfig[];
/** Draw the section as a phone's inset list, for the settings sheet. */
inset?: boolean;
localConfig: SettingsConfigType;
onConfigChange: (key: string, value: string | boolean) => void;
}
let { fields, localConfig, onConfigChange }: Props = $props();
let { fields, inset = false, localConfig, onConfigChange }: Props = $props();
/** Names the two pickers for the tests and demos that look for them. */
const VOICE_TAB_SLOTS = {
MICROPHONE: 'voice-microphone',
TRANSCRIPTION_MODEL: 'voice-transcription-model'
} as const;
const VOICE_TAB_TEXT = {
HAS_AUDIO: 'It has audio input, so it transcribes your voice.',
MIC_NAMES_HIDDEN:
'The browser names your microphones once you have allowed one, e.g. after your first recording.',
MICROPHONE: 'Microphone',
NO_AUDIO: 'It has no audio input, so voice input is not available on this server.',
ONE_MODEL: 'This server runs one model, which transcribes your voice when it has audio input.',
ONE_MODEL_NAMED: 'This server runs one model,',
TRANSCRIPTION_MODEL: 'Transcription model',
TRANSCRIPTION_NOTE:
"Only models with audio input are listed. A model you pick here is loaded on the server when you dictate, if it isn't loaded already."
} as const;
const KEY = SETTINGS_KEYS.VOICE_TRANSCRIPTION_MODEL;
// the picker sits right after the Voice input field
// the pickers sit right after the Voice input field
let splitAt = $derived(fields.findIndex((f) => f.key === SETTINGS_KEYS.VOICE_INPUT_MODE) + 1);
let isRouter = $derived(serverStore.isRouterMode);
let current = $derived(String(localConfig[KEY] ?? VOICE_TRANSCRIPTION_MODEL_AUTO));
@ -137,11 +163,19 @@
);
</script>
<div class="space-y-6">
<SettingsChatFields fields={fields.slice(0, splitAt)} {localConfig} {onConfigChange} />
{#snippet singleModelNote()}
{#if singleModel}
{VOICE_TAB_TEXT.ONE_MODEL_NAMED}
<span class="font-medium text-foreground">{singleModel}</span>.
{singleModelHasAudio ? VOICE_TAB_TEXT.HAS_AUDIO : VOICE_TAB_TEXT.NO_AUDIO}
{:else}
{VOICE_TAB_TEXT.ONE_MODEL}
{/if}
{/snippet}
<div class="space-y-2" data-slot="voice-microphone">
<Label class="text-label" for={MIC_KEY}>Microphone</Label>
{#snippet microphonePicker()}
<div class="space-y-2" data-slot={VOICE_TAB_SLOTS.MICROPHONE}>
<Label class="text-label" for={MIC_KEY}>{VOICE_TAB_TEXT.MICROPHONE}</Label>
<Select.Root
onValueChange={(value) => onConfigChange(MIC_KEY, value)}
@ -160,15 +194,14 @@
<p class="mt-1 text-caption text-muted-foreground">{SETTING_CONFIG_INFO[MIC_KEY]}</p>
{#if micNamesHidden}
<p class="text-caption text-muted-foreground">
The browser names your microphones once you have allowed one, e.g. after your first
recording.
</p>
<p class="text-caption text-muted-foreground">{VOICE_TAB_TEXT.MIC_NAMES_HIDDEN}</p>
{/if}
</div>
{/snippet}
<div class="space-y-2" data-slot="voice-transcription-model">
<Label class="text-label" for={KEY}>Transcription model</Label>
{#snippet transcriptionModelPicker()}
<div class="space-y-2" data-slot={VOICE_TAB_SLOTS.TRANSCRIPTION_MODEL}>
<Label class="text-label" for={KEY}>{VOICE_TAB_TEXT.TRANSCRIPTION_MODEL}</Label>
{#if isRouter}
<Select.Root
@ -208,19 +241,93 @@
>) unloads the chat model to do it.
</p>
{:else}
<p class="text-body-sm text-muted-foreground">
{#if singleModel}
This server runs one model, <span class="font-medium text-foreground">{singleModel}</span
>.
{singleModelHasAudio
? 'It has audio input, so it transcribes your voice.'
: 'It has no audio input, so voice input is not available on this server.'}
{:else}
This server runs one model, which transcribes your voice when it has audio input.
{/if}
</p>
<p class="text-body-sm text-muted-foreground">{@render singleModelNote()}</p>
{/if}
</div>
{/snippet}
<SettingsChatFields fields={fields.slice(splitAt)} {localConfig} {onConfigChange} />
</div>
{#snippet insetPicker(
label: string,
value: string,
valueLabel: string,
pick: (value: string) => void,
items: Array<{ label: string; value: string }>,
itemGroups: Array<{ heading: string; items: Array<{ label: string; value: string }> }>,
caption: Snippet,
slot: string
)}
<InsetList {caption} data-slot={slot}>
<InsetListRow as="div" bodyClass="gap-4">
<span class="flex-1 py-3">{label}</span>
<NativeSelect
displayLabel={valueLabel}
groups={itemGroups.map((group) => ({ heading: group.heading, options: group.items }))}
{label}
onValueChange={pick}
options={items}
{value}
variant="inset"
/>
</InsetListRow>
</InsetList>
{/snippet}
{#snippet microphoneNote()}
{SETTING_CONFIG_INFO[MIC_KEY]}
{#if micNamesHidden}
{VOICE_TAB_TEXT.MIC_NAMES_HIDDEN}
{/if}
{/snippet}
{#snippet transcriptionNote()}
{SETTING_CONFIG_INFO[KEY]}
{VOICE_TAB_TEXT.TRANSCRIPTION_NOTE}
{/snippet}
{#if inset}
<div class="flex flex-col gap-8">
<SettingsChatFieldsInset fields={fields.slice(0, splitAt)} {localConfig} {onConfigChange} />
{@render insetPicker(
VOICE_TAB_TEXT.MICROPHONE,
micCurrent,
micLabel,
(value) => onConfigChange(MIC_KEY, value),
micOptions,
[],
microphoneNote,
VOICE_TAB_SLOTS.MICROPHONE
)}
{#if isRouter}
{@render insetPicker(
VOICE_TAB_TEXT.TRANSCRIPTION_MODEL,
current,
selectedLabel,
(value) => onConfigChange(KEY, value),
[{ label: VOICE_SETTINGS_LABEL.automatic, value: VOICE_TRANSCRIPTION_MODEL_AUTO }],
optionGroups,
transcriptionNote,
VOICE_TAB_SLOTS.TRANSCRIPTION_MODEL
)}
{:else}
<p class="inset-list-caption" data-slot={VOICE_TAB_SLOTS.TRANSCRIPTION_MODEL}>
{@render singleModelNote()}
</p>
{/if}
<SettingsChatFieldsInset fields={fields.slice(splitAt)} {localConfig} {onConfigChange} />
</div>
{:else}
<div class="space-y-6">
<SettingsChatFields fields={fields.slice(0, splitAt)} {localConfig} {onConfigChange} />
{@render microphonePicker()}
{@render transcriptionModelPicker()}
<SettingsChatFields fields={fields.slice(splitAt)} {localConfig} {onConfigChange} />
</div>
{/if}

View file

@ -11,7 +11,7 @@
let { isActive, onSectionChange, sections }: Props = $props();
</script>
<div class="sticky top-12 hidden w-64 flex-col self-start bg-background md:flex gap-6">
<div class="sticky top-12 hidden w-64 flex-col gap-6 self-start md:flex">
<nav class="space-y-1">
{#each sections as section (section.title)}
<button

View file

@ -0,0 +1,377 @@
<!--
A phone's settings: a full-height sheet. Its first page has the theme and a row per section; a row
pushes the section's page, and the Tools row the tools. A change applies as it is made, the native
way, so there is nothing to save.
-->
<script lang="ts">
import SettingsSheetTools, { type SettingsToolsView } from './SettingsSheetTools.svelte';
import {
InsetList,
InsetListRow,
SheetHeader,
SheetPages,
useSheetPages
} from '@ggml-org/llama-ui/app/sheets';
import { SHEET_CONTENT_CLASS } from '@ggml-org/llama-ui/constants';
import * as AlertDialog from '@ggml-org/llama-ui/ui/alert-dialog';
import * as Drawer from '@ggml-org/llama-ui/ui/drawer';
import { RefreshCw, RotateCcw } from '@lucide/svelte';
import {
SettingsChatFieldsInset,
SettingsChatImportExportTab,
SettingsChatVoiceTab,
SettingsMcpServers
} from '#lib/components/app/settings/index.ts';
import {
NUMERIC_FIELDS,
POSITIVE_INTEGER_FIELDS,
SETTINGS_CHAT_SECTIONS,
SETTINGS_KEYS,
SETTINGS_SECTION_SLUGS,
SETTINGS_SHEET_TEXT,
SETTINGS_SHEET_THEMES,
settingsChatSections,
SHEET_FULL_HEIGHT_CLASS
} from '#lib/constants/index.ts';
import { SettingsSheetPage } from '#lib/enums/index.ts';
import { ColorMode } from '#lib/enums/ui.enums.ts';
import { useToolsPanel } from '#lib/hooks/use-tools-panel.svelte.ts';
import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts';
import {
deviceStore,
modelsStore,
serverStore,
settingsStore,
toolsStore
} from '#lib/stores/index.ts';
import { getToolDisplay, isSettingShownOn } from '#lib/utils/index.ts';
import { setMode } from 'mode-watcher';
import { tick } from 'svelte';
import { toast } from 'svelte-sonner';
interface Props {
open?: boolean;
}
let { open = $bindable(false) }: Props = $props();
type Page =
| { id: SettingsSheetPage.ROOT }
| { id: SettingsSheetPage.SECTION; slug: string }
| { id: SettingsSheetPage.MCP_SERVERS }
| SettingsToolsView;
/** The smallest value a positive whole number setting takes when its field names none. */
const POSITIVE_INTEGER_MIN = 1;
const pages = useSheetPages<Page>({ id: SettingsSheetPage.ROOT });
const page = $derived(pages.page);
const toolsPanel = useToolsPanel();
// a plain chat has no Agent section, as in the settings dialog
const sections = $derived(settingsChatSections(agenticMode.enabled));
const allFields = SETTINGS_CHAT_SECTIONS.flatMap((entry) => entry.fields ?? []);
let config = $derived(settingsStore.config);
let showResetDialog = $state(false);
let section = $derived(
page.id === SettingsSheetPage.SECTION
? SETTINGS_CHAT_SECTIONS.find((entry) => entry.slug === page.slug)
: undefined
);
// the theme has the first page's tiles, so a section does not list it again
let sectionFields = $derived(
(section?.fields ?? []).filter(
(field) => field.key !== SETTINGS_KEYS.THEME && isSettingShownOn(field, deviceStore.isMobile)
)
);
const title = $derived.by(() => {
switch (page.id) {
case SettingsSheetPage.SECTION:
return section?.title ?? SETTINGS_SHEET_TEXT.TITLE;
case SettingsSheetPage.MCP_SERVERS:
return SETTINGS_SHEET_TEXT.MCP_SERVERS;
case SettingsSheetPage.TOOLS:
return SETTINGS_SHEET_TEXT.TOOLS;
case SettingsSheetPage.TOOL_GROUP:
return (
toolsStore.toolGroups.find((group) => group.key === page.groupKey)?.label ??
SETTINGS_SHEET_TEXT.TOOLS
);
case SettingsSheetPage.TOOL: {
const entry = toolsStore.toolGroups
.flatMap((group) => group.tools)
.find((tool) => tool.key === page.toolKey);
return entry ? getToolDisplay(entry).label : SETTINGS_SHEET_TEXT.TOOL;
}
default:
return SETTINGS_SHEET_TEXT.TITLE;
}
});
// a section's number fields show the server's defaults, which a router reads off its models
let fetchInitiated = false;
$effect(() => {
if (open && serverStore.isRouterMode && section?.fields?.length && !fetchInitiated) {
fetchInitiated = true;
void modelsStore
.fetch()
.then(() => modelsStore.fetchRouterModels())
.then(() => modelsStore.props.fetchModalitiesForLoadedModels())
.then(() => modelsStore.ensureFirstModelSelected());
}
});
let scrollEl = $state<HTMLDivElement | null>(null);
// where each page below the top one was scrolled, to come back to it
let scrollStack: number[] = [];
// each opening starts on the first page
$effect(() => {
if (open) {
pages.reset();
scrollStack = [];
}
});
function scrollTo(top: number) {
void tick().then(() => scrollEl?.scrollTo({ top }));
}
// a pushed page starts at its top, and back returns to where the page below was left
function openPage(next: Page) {
if (next.id === SettingsSheetPage.TOOLS) toolsPanel.handleOpen();
scrollStack.push(scrollEl?.scrollTop ?? 0);
pages.push(next);
scrollTo(0);
}
function goBack() {
pages.pop();
scrollTo(scrollStack.pop() ?? 0);
}
/** Saves one change as it is made, checked and coupled as the desktop's Save does it. */
function commit(key: string, value: string | boolean) {
const updates: Record<string, string | number | boolean> = { [key]: value };
if (key === SETTINGS_KEYS.CUSTOM_JSON && typeof value === 'string' && value.trim()) {
try {
JSON.parse(value);
} catch {
toast.error(SETTINGS_SHEET_TEXT.CUSTOM_JSON_INVALID);
return;
}
}
if (NUMERIC_FIELDS.includes(key) && value !== '') {
const numeric = Number(value);
const field = allFields.find((entry) => entry.key === key);
if (isNaN(numeric)) {
toast.error(SETTINGS_SHEET_TEXT.NEEDS_NUMBER(field?.label ?? key));
return;
}
if (POSITIVE_INTEGER_FIELDS.includes(key)) {
updates[key] = Math.max(
field?.min ?? POSITIVE_INTEGER_MIN,
Math.min(field?.max ?? Number.POSITIVE_INFINITY, Math.round(numeric))
);
} else {
updates[key] = numeric;
}
}
// discover needs the hub metadata reads and opens from the Models page, as on the desktop
if (key === SETTINGS_KEYS.ENABLE_DISCOVER_MODELS) {
updates[SETTINGS_KEYS.USE_HUGGING_FACE_HUB] = value === true;
if (value === true) updates[SETTINGS_KEYS.SHOW_MODELS_MANAGER] = true;
}
settingsStore.updateMultipleConfig(updates);
}
function setTheme(theme: string) {
settingsStore.updateTheme(theme);
}
function handleConfirmReset() {
settingsStore.forceSyncWithServerDefaults();
setMode(settingsStore.config.theme as ColorMode);
showResetDialog = false;
toast.success(SETTINGS_SHEET_TEXT.RESET_DONE);
}
</script>
<!-- full width over the sidebar, so it does not read as part of the page slid aside; the drag
handle stays above the header, which lies over the page -->
<Drawer.Root bind:open shouldScaleBackground={false}>
<Drawer.Content
class="gap-0 overflow-hidden {SHEET_FULL_HEIGHT_CLASS} {SHEET_CONTENT_CLASS} [&>div:first-child]:relative [&>div:first-child]:z-20"
>
<SheetHeader canGoBack={pages.canGoBack} floating onBack={goBack} {title} />
<Drawer.Description class="sr-only">{SETTINGS_SHEET_TEXT.DESCRIPTION}</Drawer.Description>
<SheetPages
bind:ref={scrollEl}
class="gap-8 px-4 pt-16 pb-[max(1.5rem,var(--safe-area-bottom))]"
pageKey={JSON.stringify(page)}
{pages}
>
{#if page.id === SettingsSheetPage.ROOT}
{@render rootPage()}
{:else if page.id === SettingsSheetPage.SECTION}
{#if section}
{@render sectionPage(section.slug)}
{/if}
{:else if page.id === SettingsSheetPage.MCP_SERVERS}
<SettingsMcpServers />
{:else}
<SettingsSheetTools onOpen={openPage} view={page} />
{/if}
</SheetPages>
</Drawer.Content>
</Drawer.Root>
<AlertDialog.Root bind:open={showResetDialog}>
<AlertDialog.Content>
<AlertDialog.Header>
<AlertDialog.Title>{SETTINGS_SHEET_TEXT.RESET_TITLE}</AlertDialog.Title>
<AlertDialog.Description>{SETTINGS_SHEET_TEXT.RESET_DESCRIPTION}</AlertDialog.Description>
</AlertDialog.Header>
<AlertDialog.Footer>
<AlertDialog.Cancel>{SETTINGS_SHEET_TEXT.CANCEL}</AlertDialog.Cancel>
<AlertDialog.Action onclick={handleConfirmReset}>
{SETTINGS_SHEET_TEXT.RESET_CONFIRM}
</AlertDialog.Action>
</AlertDialog.Footer>
</AlertDialog.Content>
</AlertDialog.Root>
{#snippet themeTile(theme: ColorMode)}
{@const isDark = theme === ColorMode.DARK}
{#if theme === ColorMode.SYSTEM}
<span class="absolute inset-0 bg-neutral-50"></span>
<span class="absolute inset-0 bg-neutral-900 [clip-path:polygon(100%_0,100%_100%,0_100%)]"
></span>
{:else}
<span class={['absolute inset-0', isDark ? 'bg-neutral-900' : 'bg-neutral-50']}></span>
{/if}
<span
class={[
'absolute top-2.5 left-2.5 h-1 w-1/2 rounded-full',
isDark ? 'bg-neutral-600' : 'bg-neutral-300'
]}
></span>
<span
class={[
'absolute top-5 left-2.5 h-1 w-1/3 rounded-full',
isDark ? 'bg-neutral-700' : 'bg-neutral-200'
]}
></span>
{/snippet}
{#snippet rootPage()}
<InsetList class="grid grid-cols-3 gap-3 p-3" title={SETTINGS_SHEET_TEXT.APPEARANCE}>
{#each SETTINGS_SHEET_THEMES as theme (theme.value)}
{@const selected = config.theme === theme.value}
<button
aria-pressed={selected}
class="flex flex-col items-center gap-2"
onclick={() => setTheme(theme.value)}
type="button"
>
<span
class={[
'relative block aspect-[4/3] w-full overflow-hidden rounded-xl border border-border/60',
selected && 'ring-2 ring-(--action-primary) ring-offset-2 ring-offset-background'
]}
>
{@render themeTile(theme.value)}
</span>
<span class={['text-caption', selected ? 'text-foreground' : 'text-muted-foreground']}>
{theme.label}
</span>
</button>
{/each}
</InsetList>
<InsetList caption={SETTINGS_SHEET_TEXT.SAVED_NOTE}>
{#each sections as entry (entry.slug)}
<InsetListRow
chevron
icon={entry.icon}
onclick={() =>
openPage(
entry.slug === SETTINGS_SECTION_SLUGS.TOOLS
? { id: SettingsSheetPage.TOOLS }
: { id: SettingsSheetPage.SECTION, slug: entry.slug }
)}
>
<span class="flex-1">{entry.title}</span>
</InsetListRow>
{/each}
</InsetList>
{/snippet}
{#snippet sectionPage(slug: string)}
{#if slug === SETTINGS_SECTION_SLUGS.IMPORT_EXPORT}
<SettingsChatImportExportTab inset />
{:else if slug === SETTINGS_SECTION_SLUGS.VOICE}
<SettingsChatVoiceTab
fields={sectionFields}
inset
localConfig={config}
onConfigChange={commit}
/>
{:else}
<SettingsChatFieldsInset
fields={sectionFields}
localConfig={config}
onConfigChange={commit}
onManageMcpServers={() => openPage({ id: SettingsSheetPage.MCP_SERVERS })}
onThemeChange={setTheme}
/>
{#if slug === SETTINGS_SECTION_SLUGS.GENERAL}
<InsetList title={SETTINGS_SHEET_TEXT.APP}>
<InsetListRow icon={RefreshCw} onclick={() => window.location.reload()}>
{SETTINGS_SHEET_TEXT.RELOAD_APP}
</InsetListRow>
{#if settingsStore.hasCustomSettings}
<InsetListRow
bodyClass="text-destructive"
icon={RotateCcw}
iconClass="text-destructive"
onclick={() => (showResetDialog = true)}
>
{SETTINGS_SHEET_TEXT.RESET}
</InsetListRow>
{/if}
</InsetList>
{/if}
{/if}
{/snippet}

View file

@ -0,0 +1,188 @@
<!--
The Tools settings as the phone sheet's pages: the tool groups, one group's tools, and one tool's
switches and the argument its calls show. The desktop draws the same as one table.
-->
<script lang="ts" module>
import { SettingsSheetPage } from '#lib/enums/index.ts';
export type SettingsToolsView =
| { id: SettingsSheetPage.TOOLS }
| { groupKey: string; id: SettingsSheetPage.TOOL_GROUP }
| { id: SettingsSheetPage.TOOL; toolKey: string };
</script>
<script lang="ts">
import { InsetList, InsetListRow, InsetListSplitRow } from '@ggml-org/llama-ui/app/sheets';
import { Switch } from '@ggml-org/llama-ui/ui/switch';
import { Check, Server } from '@lucide/svelte';
import {
ICON_CLASS_DEFAULT,
TOOL_SETTINGS_TEXT,
TOOL_SHOWN_ARG_PICK
} from '#lib/constants/index.ts';
import { useToolSettings } from '#lib/hooks/use-tool-settings.svelte.ts';
import { conversationsStore, mcpStore, permissionsStore, toolsStore } from '#lib/stores/index.ts';
import type { ToolEntry, ToolGroup } from '#lib/types/index.ts';
import { getToolArgNames, getToolDisplay } from '#lib/utils/index.ts';
interface Props {
view: SettingsToolsView;
onOpen: (view: SettingsToolsView) => void;
}
let { onOpen, view }: Props = $props();
const toolSettings = useToolSettings();
const preferences = $derived(conversationsStore.preferences);
let groups = $derived(toolsStore.toolGroups);
let currentGroup = $derived(
view.id === SettingsSheetPage.TOOL_GROUP
? groups.find((group) => group.key === view.groupKey)
: undefined
);
let currentTool = $derived(
view.id === SettingsSheetPage.TOOL
? groups.flatMap((group) => group.tools).find((entry) => entry.key === view.toolKey)
: undefined
);
function enabledCount(group: ToolGroup): number {
return group.tools.filter((entry) => preferences.isToolEnabled(entry.key)).length;
}
</script>
{#snippet groupSwitch(group: ToolGroup, label?: string)}
<Switch
aria-label={label}
checked={preferences.isGroupChecked(group)}
onCheckedChange={() => void preferences.toggleGroup(group)}
size="lg"
/>
{/snippet}
{#snippet toolSwitch(entry: ToolEntry, label?: string)}
<Switch
aria-label={label}
checked={preferences.isToolEnabled(entry.key)}
onCheckedChange={() => void preferences.toggleTool(entry.key)}
size="lg"
/>
{/snippet}
{#if view.id === SettingsSheetPage.TOOLS}
{#if groups.length === 0}
<InsetList class="px-4 py-4 text-center text-body-sm text-muted-foreground">
{TOOL_SETTINGS_TEXT.NO_TOOLS}
</InsetList>
{:else}
<InsetList caption={toolSettings.scopeNote}>
{#each groups as group (group.key)}
{@const favicon = group.serverId ? mcpStore.getServerFavicon(group.serverId) : null}
<InsetListSplitRow
onclick={() => onOpen({ groupKey: group.key, id: SettingsSheetPage.TOOL_GROUP })}
>
{#snippet leading()}
{#if favicon}
<img alt="" class="{ICON_CLASS_DEFAULT} shrink-0 rounded-sm" src={favicon} />
{:else}
<Server class="{ICON_CLASS_DEFAULT} shrink-0" />
{/if}
{/snippet}
<span class="min-w-0 flex-1 truncate">{group.label}</span>
<span class="text-body-sm text-muted-foreground tabular-nums">
{enabledCount(group)}/{group.tools.length}
</span>
{#snippet trailing()}
{@render groupSwitch(group, TOOL_SETTINGS_TEXT.GROUP_TOOLS(group.label))}
{/snippet}
</InsetListSplitRow>
{/each}
</InsetList>
{/if}
{:else if view.id === SettingsSheetPage.TOOL_GROUP && currentGroup}
{@const group = currentGroup}
<InsetList>
<InsetListRow as="label">
<span class="flex-1">{TOOL_SETTINGS_TEXT.ALL_TOOLS}</span>
{@render groupSwitch(group)}
</InsetListRow>
</InsetList>
<InsetList caption={toolSettings.scopeNote}>
{#each group.tools as entry (entry.key)}
{@const display = getToolDisplay(entry)}
<InsetListSplitRow
icon={display.icon ?? undefined}
onclick={() => onOpen({ id: SettingsSheetPage.TOOL, toolKey: entry.key })}
>
<span class="min-w-0 flex-1 truncate">{display.label}</span>
{#if permissionsStore.hasTool(entry.key)}
<span class="text-body-sm text-muted-foreground">
{TOOL_SETTINGS_TEXT.ALWAYS_ALLOWED}
</span>
{/if}
{#snippet trailing()}
{@render toolSwitch(entry, display.label)}
{/snippet}
</InsetListSplitRow>
{/each}
</InsetList>
{:else if view.id === SettingsSheetPage.TOOL && currentTool}
{@const entry = currentTool}
{@const toolName = entry.definition.function.name}
{@const pick = toolSettings.shownArgPick(toolName)}
<InsetList>
<InsetListRow as="label">
<span class="flex-1">{TOOL_SETTINGS_TEXT.ENABLED}</span>
{@render toolSwitch(entry)}
</InsetListRow>
<InsetListRow as="label">
<span class="flex-1">{TOOL_SETTINGS_TEXT.ALWAYS_ALLOW}</span>
<Switch
checked={permissionsStore.hasTool(entry.key)}
onCheckedChange={(checked) =>
checked ? permissionsStore.allowTool(entry.key) : permissionsStore.revokeTool(entry.key)}
size="lg"
/>
</InsetListRow>
{#snippet caption()}
{TOOL_SETTINGS_TEXT.ALWAYS_ALLOW_NOTE} <span class="font-mono">{toolName}</span>
{/snippet}
</InsetList>
<InsetList caption={TOOL_SETTINGS_TEXT.SHOWN_ARG_NOTE} title={TOOL_SETTINGS_TEXT.SHOWN_ARG}>
{#each [TOOL_SHOWN_ARG_PICK.DEFAULT, TOOL_SHOWN_ARG_PICK.NONE, ...getToolArgNames(entry.definition)] as option (option)}
{@const isArgName =
option !== TOOL_SHOWN_ARG_PICK.DEFAULT && option !== TOOL_SHOWN_ARG_PICK.NONE}
<InsetListRow
aria-pressed={option === pick}
onclick={() => toolSettings.setShownArg(toolName, option)}
>
<span class={['min-w-0 flex-1 truncate', isArgName && 'font-mono text-body-sm']}>
{toolSettings.shownArgLabel(option)}
</span>
{#if option === pick}
<Check class="size-4 text-(--action-primary)" />
{/if}
</InsetListRow>
{/each}
</InsetList>
{/if}

View file

@ -80,6 +80,18 @@ export { default as SettingsMcpServers } from './SettingsMcpServers.svelte';
*/
export { default as SettingsChatFields } from './SettingsChat/SettingsChatFields.svelte';
/**
* The settings fields as a phone's native inset list: switch, picker and number rows grouped,
* prompts and single choices as groups of their own. Hands each change on as it is made.
*/
export { default as SettingsChatFieldsInset } from './SettingsChat/SettingsChatFieldsInset.svelte';
/**
* Phone settings: a full-height sheet whose rows push each section, its advanced settings and the
* tools onto a stack of pages. Changes apply as they are made.
*/
export { default as SettingsSheet } from './SettingsSheet/SettingsSheet.svelte';
/**
* **SettingsChatToolsTab** - Tools configuration tab for chat settings
*

View file

@ -65,9 +65,21 @@ export function attachmentTooltipText(agentic: boolean): string {
export const ATTACHMENT_MENU_TEXT = {
ADD_FILES: 'Add files',
ADD_TO_CHAT: 'Add to chat',
ALL_TOOLS: 'All tools',
BACK: 'Back',
CAMERA: 'Camera',
CLOSE: 'Close',
DESCRIPTION: 'Add files, system prompt or pick the tools the model may call',
DISABLE_GROUP: (group: string) => `Disable ${group}`,
ENABLE_GROUP: (group: string) => `Enable ${group}`,
LOADING_TOOLS: 'Loading tools...',
MCP_SERVERS: 'MCP Servers',
NO_TOOLS: 'No tools available',
NONE: 'None',
SYSTEM_MESSAGE: 'System Message',
TOOLS: 'Tools'
TOOLS: 'Tools',
TOOLS_FAILED: 'Failed to load tools',
WORKING_DIRECTORY: 'Working directory'
} as const;
/** Modality labels behind the file-upload row's enabled-when flags, both surfaces. */

View file

@ -43,12 +43,10 @@ export const DROPDOWN_MENU_CONTENT_SEARCH_SELECTOR = '[data-slot="dropdown-menu-
/**
* Sticky offset of a model-list group heading under the dropdown's search block:
* the search header exposes its height as `--dropdown-sticky-height`, and one
* section-header row (`py-2` over `text-body-sm` line height) minus the header's
* bottom border stacks the two sticky rows without a gap or an overlap.
* the search header exposes its height as `--dropdown-sticky-height`, and the
* heading overlaps the header's bottom border, so the two stack without a gap.
*/
export const SELECTOR_GROUP_STICKY_OFFSET =
'top: calc(var(--dropdown-sticky-height, 0px) + 2.25rem - 1px)';
export const SELECTOR_GROUP_STICKY_OFFSET = 'top: calc(var(--dropdown-sticky-height, 0px) - 1px)';
/** Column grid shared by every row of the models manager table. Below md the context,
* status and actions columns are dropped, so a phone gives the whole width to the

View file

@ -75,3 +75,4 @@ export * from './get-datetime';
export * from './browser-info';
export * from './search-chats';
export * from './voice.constants';
export * from './sheet.constants';

View file

@ -11,8 +11,6 @@ export const URL_PARAMS = {
export const ROUTES = {
/** Chat base — for dynamic chat URLs use RouterService. */
CHAT: '#/chat',
/** MCP servers - a page on a phone, a dialog elsewhere. */
MCP_SERVERS: '#/mcp-servers',
/** Models manager. */
MODELS: '#/models',
/** Search — mobile-only full-page conversation search. */
@ -26,8 +24,5 @@ export const ROUTES = {
/** SvelteKit route id of the models manager, as `page.route.id` reports it. */
export const MODELS_ROUTE_ID = '/models';
/** SvelteKit route id of the MCP servers page, as `page.route.id` reports it. */
export const MCP_SERVERS_ROUTE_ID = '/mcp-servers';
/** SvelteKit route id of the settings page, as `page.route.id` reports it. */
export const SETTINGS_ROUTE_ID = '/settings';

View file

@ -30,6 +30,7 @@ export const SETTINGS_KEYS = {
DYNATEMP_RANGE: 'dynatemp_range',
ENABLE_CONTINUE_GENERATION: 'enableContinueGeneration',
ENABLE_DISCOVER_MODELS: 'enableDiscoverModels',
ENABLE_MCP: 'enableMcp',
EXCLUDE_REASONING_FROM_CONTEXT: 'excludeReasoningFromContext',
FREQUENCY_PENALTY: 'frequency_penalty',
FULL_HEIGHT_CODE_BLOCKS: 'fullHeightCodeBlocks',
@ -58,7 +59,6 @@ export const SETTINGS_KEYS = {
SHOW_AGENTIC_TURN_STATS: 'showAgenticTurnStats',
SHOW_BUILD_VERSION: 'showBuildVersion',
SHOW_FULL_PATH_IN_MENTIONS: 'showFullPathInMentions',
SHOW_MCP: 'showMcp',
// Display
SHOW_MESSAGE_STATS: 'showMessageStats',
SHOW_MODEL_CAPABILITIES_IN_SELECTOR: 'showModelCapabilitiesInSelector',

View file

@ -20,7 +20,7 @@ import PencilRuler from '@lucide/svelte/icons/pencil-ruler';
import SlidersVertical from '@lucide/svelte/icons/sliders-vertical';
import Sun from '@lucide/svelte/icons/sun';
import TextCursorInput from '@lucide/svelte/icons/text-cursor-input';
import { SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts';
import { SettingsPlatform, SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts';
import { SettingsFieldType } from '#lib/enums/settings.enums.ts';
import { ColorMode } from '#lib/enums/ui.enums.ts';
import type {
@ -65,6 +65,9 @@ export const SETTINGS_SECTION_TITLES = {
VOICE: SETTINGS_SECTIONS.VOICE.title
} as const;
/** The action that opens the MCP servers, under the Enable MCP setting. */
export const MANAGE_MCP_SERVERS_LABEL = 'Manage MCP servers';
export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
// General
{
@ -95,6 +98,8 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
help: 'The starting message that defines how model should behave.',
key: SETTINGS_KEYS.SYSTEM_MESSAGE,
label: 'System Message',
placeholder:
'You are a helpful assistant. Answer briefly and ask when something is unclear.',
type: SettingsFieldType.TEXTAREA
},
{
@ -117,6 +122,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
help: 'Use Enter to send messages, and Shift + Enter or Ctrl/Cmd + Enter for new lines. When disabled, and always on a touch screen, Enter adds a line and Ctrl/Cmd + Enter sends.',
key: SETTINGS_KEYS.SEND_ON_ENTER,
label: 'Send message on Enter',
platform: SettingsPlatform.DESKTOP,
type: SettingsFieldType.CHECKBOX
},
{
@ -327,6 +333,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
help: 'On desktop, keep a one-line message on the same row as the + button, the model selector and the send button. A second line, or a line too long for the row, brings back the two-row form.',
key: SETTINGS_KEYS.SINGLE_ROW_CHAT_FORM,
label: 'Single-row chat form for short messages',
platform: SettingsPlatform.DESKTOP,
type: SettingsFieldType.CHECKBOX
},
{
@ -334,6 +341,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
help: 'Always keep the sidebar visible on desktop instead of auto-hiding it.',
key: SETTINGS_KEYS.ALWAYS_SHOW_SIDEBAR_ON_DESKTOP,
label: 'Always show sidebar on desktop',
platform: SettingsPlatform.DESKTOP,
type: SettingsFieldType.CHECKBOX
},
{
@ -341,6 +349,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
help: 'Show open chats as browser-style tabs above the conversation, one per open chat. When disabled, only one chat is shown at a time.',
key: SETTINGS_KEYS.CONVERSATION_TABS,
label: 'Conversation tabs',
platform: SettingsPlatform.DESKTOP,
type: SettingsFieldType.CHECKBOX
},
{
@ -383,6 +392,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
help: 'Keep the organization name on a phone too, where the model selector is narrow. Applies only while the organization name is shown.',
key: SETTINGS_KEYS.SHOW_MODEL_ORG_NAME_ON_MOBILE,
label: 'Show organization name on mobile',
platform: SettingsPlatform.MOBILE,
type: SettingsFieldType.CHECKBOX
},
{
@ -501,7 +511,7 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
settings: [
{
defaultValue: '[]',
help: 'Configure MCP servers as a JSON list. Use the form in the MCP Client settings section to edit.',
help: `Configure MCP servers as a JSON list. Edit them with ${MANAGE_MCP_SERVERS_LABEL}.`,
key: SETTINGS_KEYS.MCP_SERVERS,
label: 'MCP servers',
standaloneField: false,
@ -525,9 +535,9 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
settings: [
{
defaultValue: false,
help: 'Show MCP in the sidebar, to add and manage MCP servers. Servers already added keep working while it is hidden.',
key: SETTINGS_KEYS.SHOW_MCP,
label: 'Show MCP',
help: 'Let chats use the tools, prompts and resources of MCP servers. While it is off, no MCP server is connected.',
key: SETTINGS_KEYS.ENABLE_MCP,
label: 'Enable MCP',
type: SettingsFieldType.CHECKBOX
},
{
@ -870,6 +880,7 @@ function toSettingsSection(section: SettingsSectionEntry): SettingsSection {
min: s.min,
options: s.options as SettingsFieldConfig['options'],
placeholder: s.placeholder,
platform: s.platform,
radioOptions: s.radioOptions,
type: s.type
})),

View file

@ -0,0 +1,82 @@
/**
* The phone sheets (settings, add to chat, the model picker): their sizes and their text. They are
* built from @ggml-org/llama-ui/app/sheets.
*/
import { ColorMode } from '#lib/enums/ui.enums.ts';
/** A sheet as tall as the page under the status bar's corner controls. */
export const SHEET_FULL_HEIGHT_CLASS =
'data-[vaul-drawer-direction=bottom]:h-[calc(100dvh-var(--corner-control-top))] data-[vaul-drawer-direction=bottom]:max-h-none';
/** A sheet as tall as its content, up to the full height. */
export const SHEET_AUTO_HEIGHT_CLASS =
'data-[vaul-drawer-direction=bottom]:h-auto data-[vaul-drawer-direction=bottom]:max-h-[calc(100dvh-var(--corner-control-top))]';
/** A short sheet: as tall as its content, leaving the page visible above it. */
export const SHEET_SHORT_HEIGHT_CLASS = 'data-[vaul-drawer-direction=bottom]:max-h-[85dvh]';
/** How many models a phone's picker opens with, before its full list. */
export const MODELS_SHEET_QUICK_COUNT = 6;
/** Keys of the model picker's groups that are not a model family. */
export const MODELS_SHEET_GROUP_KEYS = {
FAMILY_PREFIX: 'family-',
FAVORITES: 'favorites',
LOADED: 'loaded',
LOCAL: 'local'
} as const;
export const MODELS_SHEET_TEXT = {
ALL_MODELS: 'All models',
CANCEL_LOADING: 'Cancel loading',
DESCRIPTION: 'Pick the model for this chat.',
DICTATION: 'Dictation',
EMPTY: 'No models found.',
FAVORITES: 'Favorites',
IN_CHAT: 'In chat',
LOADED: 'Loaded',
LOCAL_MODELS: 'Local models',
MODEL_ACTIONS: 'Model actions',
MORE_DETAILS: 'More details',
NOT_AVAILABLE: 'Not available',
SEARCH_PLACEHOLDER: 'Search models',
SELECT_MODEL: 'Select model',
UNLOAD: 'Unload'
} as const;
export const SETTINGS_SHEET_TEXT = {
APP: 'App',
APPEARANCE: 'Appearance',
CANCEL: 'Cancel',
CUSTOM_JSON_INVALID: 'Custom JSON is not valid JSON, so it was not saved',
DESCRIPTION: 'How the app looks, chats and talks to the server.',
MCP_SERVERS: 'MCP servers',
NEEDS_NUMBER: (label: string) => `${label} needs a number`,
RELOAD_APP: 'Reload app',
RESET: 'Reset settings to default',
RESET_CONFIRM: 'Reset to Default',
RESET_DESCRIPTION:
"All settings go back to their default values: the server's /props values where it has them. Your conversations are kept.",
RESET_DONE: 'Settings reset to their defaults',
RESET_FIELD: (label: string) => `Reset ${label} to default`,
RESET_TITLE: 'Reset Settings to Default',
SAVED_NOTE: 'Settings are saved in this browser.',
SHOW_SYSTEM_MESSAGE: 'Show system message in conversations',
TITLE: 'Settings',
TOOL: 'Tool',
TOOLS: 'Tools'
} as const;
/** The first page's theme tiles, in the order they are shown. */
export const SETTINGS_SHEET_THEMES = [
{ label: 'Light', value: ColorMode.LIGHT },
{ label: 'Dark', value: ColorMode.DARK },
{ label: 'System', value: ColorMode.SYSTEM }
] as const;
/** Labels of the phone sidebar's pinned keys. */
export const SIDEBAR_KEYS_TEXT = {
NEW_CHAT: 'New chat',
SETTINGS: 'Settings'
} as const;

View file

@ -78,3 +78,30 @@ export const WEB_SEARCH_PHRASING: ToolCallPhrasing = {
/** Per-tool choice that turns the shown arg off and keeps the sentence. */
export const TOOL_CALL_SHOWN_ARG_NONE = '';
/**
* Picks of a tool's shown argument that are not an argument's name: the tool follows the global
* setting, or shows none.
*/
export const TOOL_SHOWN_ARG_PICK = {
DEFAULT: '__default__',
NONE: '__none__'
} as const;
/** Text of the Tools settings, on the desktop's table and the phone sheet's pages. */
export const TOOL_SETTINGS_TEXT = {
ALL_TOOLS: 'All tools',
ALWAYS_ALLOW: 'Always allow',
ALWAYS_ALLOW_NOTE: 'An always allowed tool runs without asking first.',
ALWAYS_ALLOWED: 'Always allowed',
ENABLED: 'Enabled',
GROUP_TOOLS: (group: string) => `${group} tools`,
NO_TOOLS: 'No tools available',
SCOPE_CONVERSATION: 'Applies to this conversation.',
SCOPE_NEW: 'Applies to new conversations. Tool picks inside a chat only affect that chat.',
SHOWN_ARG: 'Shown argument',
SHOWN_ARG_DEFAULT: 'Default',
SHOWN_ARG_DEFAULT_OF: (arg: string) => `Default (${arg})`,
SHOWN_ARG_NONE: 'None',
SHOWN_ARG_NOTE: "The argument a call's line shows when the call has it."
} as const;

View file

@ -5,11 +5,10 @@ import {
SHORTCUT_SEARCH,
SHORTCUT_SETTINGS
} from './keyboard-shortcuts.constants';
import { MCP_SERVERS_ROUTE_ID, MODELS_ROUTE_ID, SETTINGS_ROUTE_ID } from './routes.constants';
import { MODELS_ROUTE_ID, SETTINGS_ROUTE_ID } from './routes.constants';
import Search from '@lucide/svelte/icons/search';
import Settings from '@lucide/svelte/icons/settings';
import SquarePen from '@lucide/svelte/icons/square-pen';
import McpLogo from '#lib/components/app/mcp/McpLogo.svelte';
import { SidebarAction, ToolSource } from '#lib/enums/index.ts';
import type { DesktopIconStripItem } from '#lib/types/index.ts';
@ -52,9 +51,12 @@ export const SIDEBAR_SECTION_PREVIEW_COUNT = 6;
/**
* The "Show less" row of an opened section stays at the bottom of the sidebar
* while the section scrolls under it, with room below it and a fade above
* (see app.css). "Show more" is a plain row.
* (see app.css). "Show more" is a plain row. A phone's list keeps 1.5rem clear at
* its end for the fade above the pinned keys, which a sticky row stops short of, so
* there the row sticks into it and its surface fills it to the edge.
*/
export const SIDEBAR_SHOW_MORE_ROW_CLASS = 'sidebar-show-more sticky bottom-0 z-10 pb-2';
export const SIDEBAR_SHOW_MORE_ROW_CLASS =
'sidebar-show-more sticky bottom-0 z-10 pb-2 max-md:-bottom-6 max-md:pb-6';
/** Ids of the sidebar's conversation sections, for their folded state. */
export const SIDEBAR_SECTION_IDS = {
@ -185,12 +187,6 @@ export const SIDEBAR_FOOTER_ITEMS: DesktopIconStripItem[] = [
keys: SHORTCUT_MODELS,
tooltip: 'Models'
},
{
action: SidebarAction.MCP,
activeRouteId: MCP_SERVERS_ROUTE_ID,
icon: McpLogo,
tooltip: 'MCP'
},
{
action: SidebarAction.SETTINGS,
activeRouteId: SETTINGS_ROUTE_ID,
@ -200,12 +196,5 @@ export const SIDEBAR_FOOTER_ITEMS: DesktopIconStripItem[] = [
}
];
/** The footer items to show: without the agentic features there is no MCP. */
export function sidebarFooterItems(agentic: boolean): DesktopIconStripItem[] {
return agentic
? SIDEBAR_FOOTER_ITEMS
: SIDEBAR_FOOTER_ITEMS.filter((item) => item.action !== SidebarAction.MCP);
}
/** A light haptic tap's length where the browser vibrates (Android): a click, not a buzz. */
export const HAPTIC_TAP_MS = 8;

View file

@ -94,7 +94,13 @@ export {
ServerModelsSseEventType
} from './llama-server.enums';
export { ParameterSource, SyncableParameterType, SettingsFieldType } from './settings.enums';
export {
ParameterSource,
SettingsFieldBlock,
SettingsFieldType,
SettingsPlatform,
SyncableParameterType
} from './settings.enums';
export {
ColorLevel,
@ -126,3 +132,5 @@ export {
export { SplashOrientation } from './splash.enums';
export { ChatFormVoiceState, VoiceInputMode, VoiceMode, VoiceModelRole } from './voice.enums';
export { AddSheetPage, ModelsSheetPage, SettingsSheetPage } from './sheet.enums';

View file

@ -15,6 +15,16 @@ export enum SyncableParameterType {
STRING = 'string'
}
/**
* Where a setting applies: every device, or only a desktop or tablet layout, or only a phone's.
* A setting is listed only where it applies.
*/
export enum SettingsPlatform {
ALL = 'all',
DESKTOP = 'desktop',
MOBILE = 'mobile'
}
/**
* Settings field type - defines the input type for settings fields
*/
@ -25,3 +35,12 @@ export enum SettingsFieldType {
SELECT = 'select',
TEXTAREA = 'textarea'
}
/**
* How a phone's settings list lays a field out: as a row of a group it shares with its
* neighbours, or as a group of its own (a prompt, a choice of one).
*/
export enum SettingsFieldBlock {
OWN = 'own',
ROWS = 'rows'
}

View file

@ -0,0 +1,22 @@
/** Pages of the phone's Add to chat sheet: its menu, the tool groups and one group's tools. */
export enum AddSheetPage {
ROOT = 'root',
TOOL_GROUP = 'tool-group',
TOOLS = 'tools'
}
/** Pages of the phone's model picker: the models in reach and all of them. */
export enum ModelsSheetPage {
ALL = 'all',
ROOT = 'root'
}
/** Pages of the phone's settings sheet. */
export enum SettingsSheetPage {
MCP_SERVERS = 'mcp-servers',
ROOT = 'root',
SECTION = 'section',
TOOL = 'tool',
TOOL_GROUP = 'tool-group',
TOOLS = 'tools'
}

View file

@ -13,7 +13,6 @@ export enum ScrollCarouselVariant {
*/
export enum SidebarAction {
MANAGE_MODELS = 'manage-models',
MCP = 'mcp',
NEW_CHAT = 'new-chat',
SEARCH = 'search',
SETTINGS = 'settings'

View file

@ -0,0 +1,56 @@
import { SETTINGS_KEYS } from '#lib/constants/index.ts';
import { SettingsFieldType } from '#lib/enums/settings.enums.ts';
import { modelsStore, serverStore } from '#lib/stores/index.ts';
import { normalizeFloatingPoint } from '#lib/utils/precision.ts';
/**
* What the settings fields share on a desktop and a phone: the server's defaults for the loaded
* model, whether a value differs from them, and which fields another setting locks.
*/
export function useSettingsFieldDefaults(getConfig: () => SettingsConfigType) {
const serverDefaults = $derived.by(() => {
void modelsStore.props.cacheVersion;
if (serverStore.isRouterMode) {
const modelName = modelsStore.selectedModelName;
if (modelName) {
const modelProps = modelsStore.props.getModelProps(modelName);
return (modelProps?.default_generation_settings?.params ?? {}) as Record<string, unknown>;
}
}
return (serverStore.defaultParams ?? {}) as Record<string, unknown>;
});
// discover needs the hub metadata reads, and opens from the Models page, so both are read-only while it is on
const discoverOn = $derived(Boolean(getConfig()[SETTINGS_KEYS.ENABLE_DISCOVER_MODELS]));
return {
/** A value set apart from the server's default for the loaded model. */
isCustom(field: Pick<SettingsFieldConfig, 'key' | 'type'>): boolean {
const serverDefault = serverDefaults[field.key];
const value = getConfig()[field.key];
if (serverDefault == null || value === '' || value === undefined) return false;
if (field.type === SettingsFieldType.SELECT) return value !== serverDefault;
const numeric = parseFloat(String(value));
return (
(isNaN(numeric) ? String(value) : normalizeFloatingPoint(numeric)) !==
normalizeFloatingPoint(serverDefault)
);
},
isLocked(key: string): boolean {
return (
discoverOn &&
(key === SETTINGS_KEYS.USE_HUGGING_FACE_HUB || key === SETTINGS_KEYS.SHOW_MODELS_MANAGER)
);
},
get serverDefaults() {
return serverDefaults;
}
};
}

View file

@ -0,0 +1,61 @@
import {
SETTINGS_KEYS,
TOOL_CALL_SHOWN_ARG_NONE,
TOOL_SETTINGS_TEXT,
TOOL_SHOWN_ARG_PICK
} from '#lib/constants/index.ts';
import { conversationsStore, settingsStore } from '#lib/stores/index.ts';
import { parseToolCallShownArgOverrides } from '#lib/utils/index.ts';
/**
* State of the Tools settings, for the desktop's table and the phone sheet's pages: which argument
* each tool's calls show, and what the tool switches apply to.
*/
export function useToolSettings() {
const shownArgOverrides = $derived(
parseToolCallShownArgOverrides(
settingsStore.config[SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES]
)
);
const globalShownArg = $derived(
String(settingsStore.config[SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG] ?? '').trim()
);
const scopeNote = $derived(
conversationsStore.activeConversation
? TOOL_SETTINGS_TEXT.SCOPE_CONVERSATION
: TOOL_SETTINGS_TEXT.SCOPE_NEW
);
return {
get scopeNote() {
return scopeNote;
},
setShownArg(toolName: string, pick: string) {
const next = { ...shownArgOverrides };
if (pick === TOOL_SHOWN_ARG_PICK.DEFAULT) delete next[toolName];
else next[toolName] = pick === TOOL_SHOWN_ARG_PICK.NONE ? TOOL_CALL_SHOWN_ARG_NONE : pick;
settingsStore.updateConfig(SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES, JSON.stringify(next));
},
shownArgLabel(pick: string): string {
if (pick === TOOL_SHOWN_ARG_PICK.NONE) return TOOL_SETTINGS_TEXT.SHOWN_ARG_NONE;
if (pick === TOOL_SHOWN_ARG_PICK.DEFAULT) {
return globalShownArg
? TOOL_SETTINGS_TEXT.SHOWN_ARG_DEFAULT_OF(globalShownArg)
: TOOL_SETTINGS_TEXT.SHOWN_ARG_DEFAULT;
}
return pick;
},
/** A tool follows the global setting until it gets a pick of its own. */
shownArgPick(toolName: string): string {
const own = shownArgOverrides[toolName];
if (own === undefined) return TOOL_SHOWN_ARG_PICK.DEFAULT;
return own === TOOL_CALL_SHOWN_ARG_NONE ? TOOL_SHOWN_ARG_PICK.NONE : own;
}
};
}

View file

@ -47,8 +47,8 @@ export function useToolsPanel(): UseToolsPanelReturn {
if (toolsStore.toolGroups.length > 0) return null;
// the MCP half only while MCP shows: with it hidden, there is nowhere to add a server
const mcpHint = uiStore.isMcpShown
// the MCP half only while MCP is on
const mcpHint = uiStore.isMcpEnabled
? ' To see MCP Tools you need to add / enable MCP Server(s).'
: '';

View file

@ -194,7 +194,7 @@ export class ConversationPreferences {
* MCP category on and the server-scoped key not disabled.
*/
policyEnabledServerIds(): string[] {
if (!this.isCategoryEnabled(ToolSource.MCP)) return [];
if (!mcpStore.isFeatureEnabled || !this.isCategoryEnabled(ToolSource.MCP)) return [];
return mcpStore
.getServers()

View file

@ -97,6 +97,11 @@ class MCPStore implements McpHealthHost {
);
}
/** Whether the Enable MCP setting is on. */
get isFeatureEnabled(): boolean {
return Boolean(settingsStore.config[SETTINGS_KEYS.ENABLE_MCP]);
}
get isInitialized(): boolean {
return this.connections.size > 0;
}
@ -815,6 +820,8 @@ class MCPStore implements McpHealthHost {
}
hasAvailableServers(): boolean {
if (!this.isFeatureEnabled) return false;
return parseMcpServerSettings(settingsStore.config.mcpServers).some(
(s) => s.enabled && s.url.trim()
);
@ -1097,6 +1104,8 @@ class MCPStore implements McpHealthHost {
* Builds MCP client configuration from settings.
*/
private buildMcpClientConfig(cfg: SettingsConfigType): MCPClientConfig | undefined {
if (!cfg[SETTINGS_KEYS.ENABLE_MCP]) return undefined;
const rawServers = parseMcpServerSettings(cfg.mcpServers);
if (!rawServers.length) {
@ -1274,6 +1283,8 @@ class MCPStore implements McpHealthHost {
/** Server ids that are usable right now: globally enabled ones. */
private globalEnabledServerIds(): Set<string> {
if (!this.isFeatureEnabled) return new Set();
return new Set(
this.getServers()
.filter((s) => s.enabled)

View file

@ -521,13 +521,13 @@ class SettingsStore {
}
}
// MCP shows by default for someone who already added a server, from before it moved
// behind its setting, so they keep the way to manage their servers
// MCP is on by default for someone who already added a server, from before it had
// its setting, so their servers keep working
if (
!(SETTINGS_KEYS.SHOW_MCP in savedVal) &&
!(SETTINGS_KEYS.ENABLE_MCP in savedVal) &&
parseMcpServerSettings(savedVal[SETTINGS_KEYS.MCP_SERVERS]).length > 0
) {
this.config[SETTINGS_KEYS.SHOW_MCP] = true;
this.config[SETTINGS_KEYS.ENABLE_MCP] = true;
}
// Load user overrides

View file

@ -80,7 +80,6 @@ class UiStore {
/** Open state of the Discover dialog. */
discoverModelsOpen = $state(false);
/** Sidebar sections showing all their chats past the preview, for this session. */
expandedSidebarSections = new SvelteSet<string>();
@ -96,6 +95,9 @@ class UiStore {
/** Set while the user drags the sidebar edge, so width transitions can step aside. */
isSidebarResizing = $state(false);
/** Open state of the MCP servers dialog. */
mcpServersOpen = $state(false);
/** Model the details drawer shows, a qualified id or a raw model name. */
modelDetailsFocus = $state<string | null>(null);
@ -115,13 +117,9 @@ class UiStore {
return Boolean(settingsStore.getConfig(SETTINGS_KEYS.ENABLE_DISCOVER_MODELS));
}
/**
* Whether MCP shows in the sidebar. Off by default: most people have never heard of MCP,
* so it waits behind its setting. Hiding it only hides the entry point: servers already
* added keep working.
*/
get isMcpShown(): boolean {
return Boolean(settingsStore.getConfig(SETTINGS_KEYS.SHOW_MCP));
/** Whether MCP is on. Off by default; while off, no MCP server is connected. */
get isMcpEnabled(): boolean {
return Boolean(settingsStore.getConfig(SETTINGS_KEYS.ENABLE_MCP));
}
/** Whether the model details drawer is open. */
@ -185,12 +183,10 @@ class UiStore {
if (this.collapsedSidebarSections.has(id)) this.toggleSidebarSection(id);
}
/** Whether a sidebar action shows: Models and MCP wait behind their settings. */
/** Whether a sidebar action shows: Models waits behind its setting. */
isSidebarActionShown(action: SidebarAction | undefined): boolean {
if (action === SidebarAction.MANAGE_MODELS) return this.isModelsManagerShown;
if (action === SidebarAction.MCP) return this.isMcpShown;
return true;
}
@ -212,6 +208,11 @@ class UiStore {
this.groupPicker = options;
}
/** Open the MCP servers dialog. */
openMcpServers(): void {
this.mcpServersOpen = true;
}
/** Open the model details drawer over the current page, without leaving it. */
openModelDetails(focus: string): void {
this.modelDetailsFocus = focus;

View file

@ -369,9 +369,13 @@ export interface ChatFormActionsContext {
readonly hasVideoModality: boolean;
readonly hasVisionModality: boolean;
onFileUpload?: () => void;
/** Adds files picked outside the form's own file input, such as the camera or photo library. */
onFilesSelect?: (files: File[]) => void;
onSystemPromptClick?: () => void;
/** Opens the working directory picker; set where the + menu offers it. */
onWorkingDirectoryClick?: () => void;
/** The working directory's name in the + menu, or what sets one. */
readonly workingDirectoryLabel: string;
/** The working directory's abbreviated path, or null when none is set. */
readonly workingDirectory: string | null;
}

View file

@ -7,6 +7,7 @@ import type {
ParameterSource,
ReasoningEffort,
SettingsFieldType,
SettingsPlatform,
StreamConnectionState,
SyncableParameterType
} from '#lib/enums/index.ts';
@ -24,6 +25,8 @@ export interface SettingsEntry {
label: string;
help: string;
defaultValue: SettingsConfigValue;
/** Where the setting applies, and so where it is listed; every device when not set. */
platform?: SettingsPlatform;
type: SettingsFieldType;
options?: Array<{ value: string; label: string; icon: Component }>;
/** Options rendered for RADIO fields. Each entry maps a `value` (the radio's selected value) to the underlying config `key` whose boolean state mirrors it. */
@ -63,6 +66,7 @@ export interface SettingsFieldConfig {
min?: number;
max?: number;
dependsOn?: string;
platform?: SettingsPlatform;
help?: string;
options?: Array<{ value: string; label: string; icon?: typeof Icon }>;
/** Options rendered for RADIO fields. Each entry maps a `value` (the radio's selected value) to the underlying config `key` whose boolean state mirrors it. */

View file

@ -5,6 +5,8 @@
* with dynamic keys while maintaining TypeScript type safety.
*/
import { SettingsPlatform } from '#lib/enums/settings.enums.ts';
/**
* Type-safe helper to access config properties dynamically
* Provides better type safety than direct casting to Record
@ -51,3 +53,18 @@ export function configToParameterRecord<T extends SettingsConfigType>(
return record;
}
/**
* Whether a setting is listed on this device: one for a desktop or tablet layout is left off a
* phone's settings, and one for a phone is left off the others
*/
export function isSettingShownOn(
field: { platform?: SettingsPlatform },
isMobile: boolean
): boolean {
if (field.platform === SettingsPlatform.DESKTOP) return !isMobile;
if (field.platform === SettingsPlatform.MOBILE) return isMobile;
return true;
}

View file

@ -51,7 +51,12 @@ export {
} from './code';
// Config helpers
export { setConfigValue, getConfigValue, configToParameterRecord } from './config-helpers';
export {
setConfigValue,
getConfigValue,
configToParameterRecord,
isSettingShownOn
} from './config-helpers';
// CORS Proxy
export { buildProxiedIconUrl, buildProxiedUrl, buildProxiedHeaders } from './cors-proxy';
@ -64,6 +69,7 @@ export {
filterModelOptions,
groupFavoriteOptions,
groupModelOptions,
pickQuickModels,
windowLocalGroups,
type GroupedModelOptions,
type ModelItem,
@ -355,7 +361,7 @@ export { tryParseToolResultObject } from './tool-call-meta';
// Per-tool UI metadata (label + icon) used by the tool-call chrome.
// Re-exported through $lib/utils so renderer components can read the
// label without depending on $lib/constants directly.
export { getToolUi } from './tool-ui';
export { getToolArgNames, getToolDisplay, getToolUi } from './tool-ui';
// Chat command picker

View file

@ -48,6 +48,36 @@ export function filterModelOptions(options: ModelOption[], searchTerm: string):
);
}
/**
* The few models a phone's picker opens with: the chat's model, the one that transcribes
* dictation, the loaded ones, then favorites, then the recently picked, each once and in that
* order, up to `limit`. The active and recent ids are option ids, the dictation model's a model.
*/
export function pickQuickModels(input: {
activeId?: string | null;
dictationModel?: string | null;
favoriteIds: Set<string>;
limit: number;
loadedIds: Set<string>;
options: ModelOption[];
recentIds: string[];
}): ModelItem[] {
const { activeId, dictationModel, favoriteIds, limit, loadedIds, options, recentIds } = input;
const picked: ModelOption[] = [];
const add = (option: ModelOption | undefined) => {
if (option && picked.length < limit && !picked.includes(option)) picked.push(option);
};
add(options.find((option) => option.id === activeId));
add(options.find((option) => option.model === dictationModel));
for (const option of options) if (loadedIds.has(option.id)) add(option);
for (const option of options) if (favoriteIds.has(option.model)) add(option);
for (const id of recentIds) add(options.find((option) => option.id === id));
return picked.map((option) => ({ option }));
}
/**
* Favorite models across every backend, in list order: the favorites tab spans
* all backends, so they come from the full option list.

View file

@ -1,5 +1,6 @@
import { TOOL_UI } from '#lib/constants/index.ts';
import type { ToolUiEntry } from '#lib/types/index.ts';
import { ToolSource } from '#lib/enums/tools.enums.ts';
import type { OpenAIToolDefinition, ToolEntry, ToolUiEntry } from '#lib/types/index.ts';
/**
* Resolve the UI metadata (label + icon) for a server or browser tool by its
@ -11,3 +12,28 @@ export function getToolUi(toolName: string | undefined): ToolUiEntry | null {
return (TOOL_UI as Record<string, ToolUiEntry>)[toolName] ?? null;
}
/**
* The name and icon a tool is listed with: built-in tools have friendlier ones than their
* function names, the others show the function name.
*/
export function getToolDisplay(entry: ToolEntry): {
icon: ToolUiEntry['icon'] | null;
label: string;
} {
const name = entry.definition.function.name;
const ui =
entry.source === ToolSource.SERVER || entry.source === ToolSource.BROWSER
? getToolUi(name)
: null;
return { icon: ui?.icon ?? null, label: ui?.label ?? name };
}
/** The names of the arguments a tool takes. */
export function getToolArgNames(definition: OpenAIToolDefinition): string[] {
const properties = (definition.function.parameters as { properties?: object } | undefined)
?.properties;
return properties ? Object.keys(properties) : [];
}

View file

@ -294,7 +294,7 @@
// Background MCP server health checks on app load.
// Health-check every configured server with a URL - including disabled ones -
// so the /mcp-servers page can display health metadata for servers that are
// so the MCP servers dialog can display health metadata for servers that are
// currently turned off. Disabled servers never get promoted to active
// connections (see runHealthCheck), so their tools/prompts/resources stay
// out of the chat-side stores.
@ -304,6 +304,13 @@
$effect(() => {
if (!browser) return;
// Enable MCP off: no server is checked or connected, open connections close
if (!mcpStore.isFeatureEnabled) {
untrack(() => void mcpStore.shutdown());
return;
}
const mcpServers = mcpStore.getServers();
const serversWithUrls = mcpServers.filter((s) => s.url.trim());

View file

@ -1,31 +0,0 @@
<script lang="ts">
import { SettingsMcpServers } from '#lib/components/app/settings/index.ts';
import { APP_NAME, ROUTES } from '#lib/constants/index.ts';
import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts';
import { goto } from '$app/navigation';
// a server without the agentic features has no MCP
$effect(() => {
if (agenticMode.settled && !agenticMode.enabled) void goto(ROUTES.START);
});
</script>
<svelte:head>
<title>MCP Servers - {APP_NAME}</title>
</svelte:head>
<!-- a phone's MCP servers: the page the sidebar opens there, where a desktop or tablet opens the
MCP servers dialog -->
<div
class="mx-auto flex w-full max-w-7xl flex-col gap-6 px-4 pt-(--page-top) pb-16 max-md:pb-safe-24 md:px-8 md:pt-6"
>
<div class="flex min-w-0 flex-col gap-1">
<h1 class="text-heading tracking-tight">MCP Servers</h1>
<p class="text-body-sm text-muted-foreground">
Connect the servers whose tools, prompts and resources your chats can use.
</p>
</div>
<SettingsMcpServers />
</div>

View file

@ -1,11 +0,0 @@
import type { PageLoad } from './$types';
import { redirect } from '@sveltejs/kit';
import { AGENTIC_ENABLED, ROUTES } from '#lib/constants/index.ts';
import { loadAppRoute } from '#lib/stores/init.ts';
export const load: PageLoad = ({ fetch }) => {
// a chat-only build has no MCP
if (!AGENTIC_ENABLED) redirect(307, ROUTES.START);
return loadAppRoute(fetch);
};

View file

@ -5,14 +5,22 @@
interface Props {
currentModel: string | null;
favorites?: ModelItem[];
groups: GroupedModelOptions;
loaded?: ModelItem[];
}
let { currentModel, groups, loaded = [] }: Props = $props();
let { currentModel, favorites = [], groups, loaded = [] }: Props = $props();
</script>
<!-- The rows mount tooltips, which need the provider +layout.svelte supplies. -->
<Tooltip.Provider>
<ModelsSelectorList activeId={null} {currentModel} {groups} {loaded} onSelect={() => {}} />
<ModelsSelectorList
activeId={null}
{currentModel}
{favorites}
{groups}
{loaded}
onSelect={() => {}}
/>
</Tooltip.Provider>

View file

@ -0,0 +1,34 @@
// Enable MCP is a real switch: while it is off, an added and enabled server is not usable.
import { SETTINGS_KEYS } from '#lib/constants/index.ts';
import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts';
import { mcpStore } from '#lib/stores/mcp/index.svelte.ts';
import { settingsStore } from '#lib/stores/settings/index.svelte.ts';
import { beforeEach, describe, expect, it } from 'vitest';
describe('Enable MCP setting', () => {
beforeEach(() => {
settingsStore.updateConfig(SETTINGS_KEYS.MCP_SERVERS, '[]');
settingsStore.updateConfig(SETTINGS_KEYS.ENABLE_MCP, false);
mcpStore.addServer({ enabled: true, url: 'https://mcp.example.com/a' });
});
it('keeps an enabled server out of use while it is off', () => {
expect(mcpStore.isFeatureEnabled).toBe(false);
expect(mcpStore.hasEnabledServers()).toBe(false);
expect(mcpStore.hasAvailableServers()).toBe(false);
expect(conversationsStore.preferences.policyEnabledServerIds()).toEqual([]);
});
it('makes the server usable once it is on', () => {
settingsStore.updateConfig(SETTINGS_KEYS.ENABLE_MCP, true);
expect(mcpStore.hasEnabledServers()).toBe(true);
expect(mcpStore.hasAvailableServers()).toBe(true);
expect(conversationsStore.preferences.policyEnabledServerIds()).toHaveLength(1);
});
it('keeps the server in the list either way, to manage it', () => {
expect(mcpStore.getServers()).toHaveLength(1);
});
});

View file

@ -1,5 +1,5 @@
// Guards the phone model picker: the selector serves a phone a bottom drawer
// with the same search and sections the desktop menu shows.
// Guards the phone model picker: the selector serves a phone a bottom sheet with the
// desktop menu's search and sections, opening on the models in reach when there are any.
import ModelsSelector from '#lib/components/app/models/ModelsSelector/ModelsSelector.svelte';
import { ServerRole } from '#lib/enums/index.ts';
@ -41,16 +41,36 @@ describe('model picker drawer on a phone', () => {
afterEach(async () => {
modelsStore.models = [];
modelsStore.recentModelIds = [];
vi.restoreAllMocks();
await page.viewport(DESKTOP.width, DESKTOP.height);
});
it('opens the picker in a drawer', async () => {
it("opens on the short view with the chat's model, even with no other in reach", async () => {
const screen = render(ModelsSelector);
await screen.getByRole('button').click();
await expect.element(screen.getByPlaceholder('Search models...')).toBeVisible();
await expect.element(screen.getByText('Local models')).toBeVisible();
await expect.element(screen.getByRole('button', { name: 'All models' })).toBeVisible();
await expect.element(screen.getByText('Q4_K_M')).toBeVisible();
await expect.element(screen.getByText('Q8_0')).not.toBeInTheDocument();
await expect.element(screen.getByPlaceholder('Search models')).toBeVisible();
});
it("lists the chat's model and a recent one, and all of them on their page", async () => {
modelsStore.recentModelIds = [other.id];
const screen = render(ModelsSelector);
await screen.getByRole('button').click();
await expect.element(screen.getByText('Q4_K_M')).toBeVisible();
await expect.element(screen.getByText('Q8_0')).toBeVisible();
await expect.element(screen.getByPlaceholder('Search models')).toBeVisible();
await screen.getByRole('button', { name: 'All models' }).click();
await expect.element(screen.getByRole('heading', { name: 'All models' })).toBeVisible();
await expect.element(screen.getByText('Q4_K_M')).toBeVisible();
});
});

View file

@ -0,0 +1,57 @@
// Guards the model selector's sections: the server's models are listed directly, and sit in an
// Other models section only beside favorites or loaded models, which are sections of their own.
import ModelsSelectorListWrapper from './components/ModelsSelectorListWrapper.svelte';
import { ServerRole } from '#lib/enums/index.ts';
import { serverStore } from '#lib/stores/llama-server.svelte.ts';
import { modelsStore } from '#lib/stores/models/index.svelte.ts';
import type { ModelOption } from '#lib/types/index.ts';
import { beforeEach, describe, expect, it } from 'vitest';
import { render } from 'vitest-browser-svelte';
const option = (name: string): ModelOption => ({
capabilities: [],
id: `org/${name}:Q4_K_M`,
model: `org/${name}:Q4_K_M`,
name
});
const ALPHA = option('Alpha-8B');
const BETA = option('Beta-8B');
beforeEach(() => {
serverStore.role = ServerRole.ROUTER;
modelsStore.models = [ALPHA, BETA];
});
function renderList(extra: { favorites?: ModelOption[]; loaded?: ModelOption[] } = {}) {
return render(ModelsSelectorListWrapper, {
currentModel: null,
favorites: (extra.favorites ?? []).map((entry) => ({ option: entry })),
groups: { available: [{ items: [{ option: BETA }], orgName: null }] },
loaded: (extra.loaded ?? []).map((entry) => ({ option: entry }))
});
}
describe('model selector sections', () => {
it('lists the models without a section when none is a favorite or loaded', async () => {
const screen = renderList();
await expect.element(screen.getByRole('option')).toBeVisible();
await expect.element(screen.getByText('Other models')).not.toBeInTheDocument();
await expect.element(screen.getByText('Local models')).not.toBeInTheDocument();
});
it('puts the other models in a section beside the favorites', async () => {
const screen = renderList({ favorites: [ALPHA] });
await expect.element(screen.getByText('Favorites')).toBeVisible();
await expect.element(screen.getByText('Other models')).toBeVisible();
});
it('puts the other models in a section beside the loaded ones', async () => {
const screen = renderList({ loaded: [ALPHA] });
await expect.element(screen.getByText('Loaded models')).toBeVisible();
await expect.element(screen.getByText('Other models')).toBeVisible();
});
});

View file

@ -40,7 +40,7 @@ describe('nested surfaces', () => {
// Models and MCP wait behind their settings: show them, so every footer row is measured
settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MODELS_MANAGER, true);
settingsStore.updateConfig(SETTINGS_KEYS.SHOW_MCP, true);
settingsStore.updateConfig(SETTINGS_KEYS.ENABLE_MCP, true);
});
it('round the footer group from its tokens', async () => {

View file

@ -0,0 +1,44 @@
<script lang="ts" module>
import ChatFormAddSheetStoryHost from './ChatFormAddSheetStoryHost.svelte';
import { resetPointerEvents } from './fixtures';
import { defineMeta } from '@storybook/addon-svelte-csf';
import { ATTACHMENT_MENU_TEXT } from '#lib/constants/index.ts';
import { screen } from 'storybook/test';
// a phone's + menu: a short sheet of grouped rows. Files and the camera open the phone's own
// pickers, the system message and working directory close the sheet, and Tools pushes pages:
// the tool groups, then one group's tools, each with a switch
const { Story } = defineMeta({
beforeEach: resetPointerEvents,
component: ChatFormAddSheetStoryHost,
globals: { viewport: { isRotated: false, value: 'mobile2' } },
parameters: {
layout: 'fullscreen'
},
title: 'Llama Chat/Chat/ChatForm/ChatFormActionAddDrawer'
});
const WORKING_DIRECTORY = '~/projects/llama.cpp';
async function openSheet({
canvas,
userEvent
}: {
canvas: { getByRole: (role: string, options: { name: string }) => Element };
userEvent: { click: (element: Element) => Promise<void> };
}) {
await userEvent.click(canvas.getByRole('button', { name: ATTACHMENT_MENU_TEXT.ADD_TO_CHAT }));
// the row's name gains the kinds of file the model takes
await screen.findByRole('button', { name: new RegExp(ATTACHMENT_MENU_TEXT.ADD_FILES) });
}
</script>
<Story name="Menu" play={openSheet} />
<Story args={{ hasVisionModality: true }} name="With the camera" play={openSheet} />
<Story
args={{ workingDirectory: WORKING_DIRECTORY }}
name="With a working directory"
play={openSheet}
/>

View file

@ -0,0 +1,57 @@
<!--
The phone's Add to chat sheet on its own: the chat form's actions as the sheet reads them, and a
+ key that opens it.
-->
<script lang="ts">
import { Button } from '@ggml-org/llama-ui/ui/button';
import { Plus } from '@lucide/svelte';
import ChatFormActionAddDrawer from '#lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte';
import { ATTACHMENT_MENU_TEXT } from '#lib/constants/index.ts';
import { setChatFormActionsContext } from '#lib/contexts/index.ts';
interface Props {
/** The model takes images, so the sheet offers the camera. */
hasVisionModality?: boolean;
/** The chat's working directory, abbreviated; null offers to set one. */
workingDirectory?: string | null;
}
let { hasVisionModality = false, workingDirectory = null }: Props = $props();
const noop = () => {};
setChatFormActionsContext({
disabled: false,
hasAudioModality: false,
hasVideoModality: false,
get hasVisionModality() {
return hasVisionModality;
},
onFilesSelect: noop,
onFileUpload: noop,
onSystemPromptClick: noop,
onWorkingDirectoryClick: noop,
get workingDirectory() {
return workingDirectory;
},
get workingDirectoryLabel() {
return workingDirectory ?? ATTACHMENT_MENU_TEXT.WORKING_DIRECTORY;
}
});
</script>
<div class="p-4">
<ChatFormActionAddDrawer>
{#snippet trigger({ disabled, onclick })}
<Button
aria-label={ATTACHMENT_MENU_TEXT.ADD_TO_CHAT}
{disabled}
{onclick}
size="icon"
variant="secondary"
>
<Plus />
</Button>
{/snippet}
</ChatFormActionAddDrawer>
</div>

View file

@ -32,6 +32,7 @@ export const STORYBOOK_SECTIONS: StorybookSection[] = [
name: 'Llama Chat',
pages: [
'Foundations',
'Mobile',
'Chat',
'Content',
'Models',

View file

@ -0,0 +1,20 @@
<script lang="ts" module>
import MobileFlows from './MobileFlows.svx';
import { defineMeta } from '@storybook/addon-svelte-csf';
import Editorial from '$llama-ui-stories/editorial/Editorial.svelte';
// how Llama Chat works on a phone: the sidebar's keys, the three sheets and the pages each pushes
const { Story } = defineMeta({
parameters: {
controls: { disable: true },
layout: 'fullscreen'
},
title: 'Llama Chat/Mobile/Flows'
});
</script>
<Story asChild name="Flows">
<Editorial>
<MobileFlows />
</Editorial>
</Story>

View file

@ -0,0 +1,77 @@
<!--
Mobile flows: how Llama Chat works on a phone. What the sidebar's keys open, the three sheets and the pages
each one pushes, and where their stories are. Written for people first and readable as plain Markdown by
agents too. Set in the Editorial.
-->
<script>
import Figure from '../editorial/Figure.svelte';
import SheetFlow from './SheetFlow.svelte';
import { ADD_FLOW, MODELS_FLOW, SETTINGS_FLOW, SETTINGS_TOOLS_FLOW } from './flows';
</script>
<p class="kicker">Llama Chat &middot; Mobile</p>
# Mobile flows
<p class="lead">On a phone, Llama Chat keeps the chat on screen and opens everything else as a <strong>sheet</strong>: a panel that rises from the bottom, with a round key in its corner and pages that slide in from the right. This page says what opens each sheet and where its pages lead.</p>
## The rules
- **One sheet at a time.** A sheet rises over the page and the sidebar. Its corner key closes it on the first page and goes back on the pages pushed over it. A swipe down closes it too.
- **Rows are a finger tall.** Every list is an inset list: rounded groups of 3rem rows, tappable as a whole, with a chevron when the row opens a page.
- **A change applies at once.** A switch or a pick is saved when it is made, and typed text when its field is left. There is no Save.
- **The phone's own pickers.** A select opens the system's wheel or sheet, files open the system file picker, and the camera row opens the camera.
- **Settings follow the device.** A setting that only matters on a desktop (the sidebar, tabs, Send on Enter) is not listed on a phone, and the other way round.
## The sidebar
The sidebar slides in from the left. Search is a round key across from the logo. Two keys stay pinned under the conversations: **Settings** on the left and **New chat**, the one primary button, on the right. The conversations scroll and fade out above them.
Story: `Llama Chat/Navigation/SidebarNavigation`.
## Settings
<Figure n={1} caption="Settings: the first page, a section, and the MCP servers from the Agentic section.">
<SheetFlow flow={SETTINGS_FLOW} />
</Figure>
The first page has the theme as three tiles, then one row per section. A section's page lists its fields in groups: switches, pickers and numbers as rows, a prompt or a choice of one as a group of its own, with the help text under the label. Back returns to where the page below was scrolled.
<Figure n={2} caption="The Tools section is three pages deep: the groups, one group's tools, one tool.">
<SheetFlow flow={SETTINGS_TOOLS_FLOW} />
</Figure>
A row with a switch at its end has two targets: the row opens the page, the switch turns the group or the tool on and off without opening it.
Stories: `Llama Chat/Settings/SettingsSheet`.
## Add to chat
<Figure n={3} caption="The + menu: a short sheet, with Tools as pages.">
<SheetFlow flow={ADD_FLOW} />
</Figure>
The sheet is as tall as its menu, and the pages pushed over it keep that height so it does not jump. Files and the camera keep the sheet open while the system picker is up and close it once files arrive. Tools show how many are on, as `4/9`.
Stories: `Llama Chat/Chat/ChatForm/ChatFormActionAddDrawer`.
## Model picker
<Figure n={4} caption="The model picker: the short view, then all models.">
<SheetFlow flow={MODELS_FLOW} />
</Figure>
The sheet opens short, with up to six models: the chat's, the one that transcribes dictation, then the loaded, favorite and recent ones. A tap switches the chat to a model and loads it if need be. Holding a row opens its menu: Unload, or More details over the sheet. The search stays at the sheet's foot, under the reasoning effort, and shows its results in place at full height.
Stories: `Llama Chat/Models/ModelsSelectorSheet`.
## Building a sheet
A sheet is made of Llama UI's pieces, from `@ggml-org/llama-ui/app/sheets`:
- `useSheetPages` holds the stack of pages; `SheetPages` shows the top one and slides between them.
- `SheetHeader` is the corner key and the title, inside a `Drawer` whose content takes `SHEET_CONTENT_CLASS`.
- `InsetList`, `InsetListRow` and `InsetListSplitRow` are the lists. `NativeSelect`, from `app/forms`, is the picker.
Their stories are under `Llama UI/App components`: Sheet, InsetList and NativeSelect.

View file

@ -0,0 +1,27 @@
<!-- One way through a phone sheet: what opens it, then its pages in the order a tap pushes them -->
<script lang="ts">
import type { Flow } from './flows';
import { ChevronRight } from '@lucide/svelte';
let { flow }: { flow: Flow } = $props();
</script>
<div class="flex flex-col gap-3">
<p class="text-caption text-muted-foreground">{flow.trigger}</p>
<ol class="flex flex-wrap items-stretch gap-2">
{#each flow.pages as page, index (page.title)}
{#if index > 0}
<li aria-hidden="true" class="flex items-center text-muted-foreground">
<ChevronRight class="size-4" />
</li>
{/if}
<li class="inset-group-surface flex w-40 flex-col gap-1 px-3 py-2.5">
<span class="text-label">{page.title}</span>
<span class="text-caption text-muted-foreground">{page.note}</span>
</li>
{/each}
</ol>
</div>

View file

@ -0,0 +1,49 @@
/** A page of a phone sheet, as the Mobile flows page draws it. */
export interface FlowPage {
/** What the page holds, in a few words. */
note: string;
title: string;
}
/** One way through a sheet: the pages a tap pushes, in order. */
export interface Flow {
pages: FlowPage[];
/** What opens the sheet. */
trigger: string;
}
export const SETTINGS_FLOW: Flow = {
pages: [
{ note: 'Theme tiles, then a row per section', title: 'Settings' },
{ note: 'Switches, pickers and numbers in groups', title: 'A section' },
{ note: 'From Enable MCP, in Agentic', title: 'MCP servers' }
],
trigger: 'Settings key, bottom left of the sidebar'
};
export const SETTINGS_TOOLS_FLOW: Flow = {
pages: [
{ note: 'The Tools row', title: 'Settings' },
{ note: 'A row and a switch per group', title: 'Tools' },
{ note: "The group's tools, each with a switch", title: 'A tool group' },
{ note: 'Enabled, Always allow, Shown argument', title: 'A tool' }
],
trigger: 'Settings key, then Tools'
};
export const ADD_FLOW: Flow = {
pages: [
{ note: 'Camera, files, system message, working directory', title: 'Add to chat' },
{ note: 'Built-in groups, then MCP servers', title: 'Tools' },
{ note: 'All tools, then a switch per tool', title: 'A tool group' }
],
trigger: '+ in the chat form'
};
export const MODELS_FLOW: Flow = {
pages: [
{ note: "The chat's model and those in reach", title: 'Select model' },
{ note: 'Loaded, Favorites, then the rest in groups', title: 'All models' }
],
trigger: 'The model name in the chat form'
};

View file

@ -0,0 +1,72 @@
<script lang="ts" module>
import { defineMeta } from '@storybook/addon-svelte-csf';
import ModelsSelectorSheet from '#lib/components/app/models/ModelsSelector/ModelsSelectorSheet.svelte';
import { MODELS_SHEET_TEXT } from '#lib/constants/index.ts';
import type { GroupedModelOptions, ModelItem } from '#lib/utils/index.ts';
import { screen } from 'storybook/test';
// a phone's model picker: a short sheet with the models in reach (the chat's, the loaded,
// favorite and recent ones) and a row to all of them, a page of groups. The search stays at
// the sheet's foot, and holding a row opens its menu
const { Story } = defineMeta({
component: ModelsSelectorSheet,
globals: { viewport: { isRotated: false, value: 'mobile2' } },
parameters: {
layout: 'fullscreen'
},
title: 'Llama Chat/Models/ModelsSelectorSheet'
});
const model = (name: string, orgName: string): ModelItem => ({
option: {
capabilities: [],
id: `${orgName}/${name}`,
model: `${orgName}/${name}`,
name
}
});
const QWEN = model('Qwen3-8B', 'Qwen');
const GEMMA = model('gemma-3n-E4B-it', 'google');
const LLAMA = model('Llama-3.2-3B-Instruct', 'meta');
const PHI = model('Phi-4-mini', 'microsoft');
const REMOVED_MODEL = 'acme/Removed-7B';
const groups: GroupedModelOptions = {
available: [
{ items: [LLAMA], orgName: 'meta' },
{ items: [PHI], orgName: 'microsoft' }
]
};
const args = {
activeId: QWEN.option.id,
favoriteItems: [GEMMA],
groups,
loadedItems: [QWEN],
open: true,
quickItems: [QWEN, GEMMA]
};
</script>
<Story {args} name="Models in reach" />
<Story
{args}
name="All models"
play={async ({ userEvent }) => {
await userEvent.click(
await screen.findByRole('button', { name: MODELS_SHEET_TEXT.ALL_MODELS })
);
await screen.findByRole('heading', { name: MODELS_SHEET_TEXT.LOADED });
}}
/>
<Story args={{ ...args, searchTerm: 'phi' }} name="Search results" />
<Story
args={{ ...args, activeId: null, quickItems: [GEMMA], unavailableModel: REMOVED_MODEL }}
name="Chat model not available"
/>
<Story args={{ isEmpty: true, open: true, searchTerm: 'nothing' }} name="No models found" />

View file

@ -0,0 +1,54 @@
<script lang="ts" module>
import { defineMeta } from '@storybook/addon-svelte-csf';
import { SettingsSheet } from '#lib/components/app/settings/index.ts';
import {
SETTINGS_CHAT_SECTIONS,
SETTINGS_SECTION_SLUGS,
SETTINGS_SHEET_TEXT
} from '#lib/constants/index.ts';
import { screen } from 'storybook/test';
// a phone's settings: a full-height sheet. Its first page has the theme tiles and a row per
// section; a row pushes that section's page, and every change applies as it is made
const { Story } = defineMeta({
component: SettingsSheet,
globals: { viewport: { isRotated: false, value: 'mobile2' } },
parameters: {
layout: 'fullscreen'
},
title: 'Llama Chat/Settings/SettingsSheet'
});
const titleOf = (slug: string) =>
SETTINGS_CHAT_SECTIONS.find((section) => section.slug === slug)?.title ?? slug;
/** Opens a section's page from the first page, as a tap on its row does. */
function openSection(slug: string) {
return async ({ userEvent }: { userEvent: { click: (element: Element) => Promise<void> } }) => {
await userEvent.click(await screen.findByRole('button', { name: titleOf(slug) }));
await screen.findByRole('button', { name: 'Back' });
};
}
</script>
<Story args={{ open: true }} name="First page" />
<Story args={{ open: true }} name="General" play={openSection(SETTINGS_SECTION_SLUGS.GENERAL)} />
<Story args={{ open: true }} name="Voice" play={openSection(SETTINGS_SECTION_SLUGS.VOICE)} />
<Story
args={{ open: true }}
name="Import and export"
play={openSection(SETTINGS_SECTION_SLUGS.IMPORT_EXPORT)}
/>
<Story
args={{ open: true }}
name="Back to the first page"
play={async (context) => {
await openSection(SETTINGS_SECTION_SLUGS.GENERAL)(context);
await context.userEvent.click(screen.getByRole('button', { name: 'Back' }));
await screen.findByText(SETTINGS_SHEET_TEXT.APPEARANCE);
}}
/>

View file

@ -2,7 +2,8 @@
// agentic settings, and a full build offers them only for a server that has
// them. The flag is read when the constants load, so each case loads them fresh.
import { SidebarAction } from '#lib/enums/index.ts';
// loaded once up front, so the first case's fresh load is not the cold one
import '#lib/constants/index.ts';
import { afterEach, describe, expect, it, vi } from 'vitest';
async function loadConstants(agentic?: string) {
@ -78,12 +79,11 @@ describe('agentic mode', () => {
expect(toolsStore.allTools.every((tool) => tool.source === ToolSource.BROWSER)).toBe(true);
});
it('leaves the Tools and Agentic settings and the MCP entry out when it is off', async () => {
it('leaves the Tools and Agentic settings, Enable MCP among them, out when it is off', async () => {
const c = await loadConstants();
const slugs = (agentic: boolean) => c.settingsChatSections(agentic).map((s) => s.slug);
const keys = (agentic: boolean) =>
c.settingsChatSections(agentic).flatMap((s) => (s.fields ?? []).map((field) => field.key));
const actions = (agentic: boolean) => c.sidebarFooterItems(agentic).map((item) => item.action);
const { AGENTIC, TOOLS } = c.SETTINGS_SECTION_SLUGS;
expect(slugs(true)).toEqual(expect.arrayContaining([TOOLS, AGENTIC]));
@ -91,11 +91,8 @@ describe('agentic mode', () => {
expect(slugs(false)).not.toContain(AGENTIC);
expect(slugs(false).length).toBeGreaterThan(0);
expect(keys(true)).toContain(c.SETTINGS_KEYS.SHOW_MCP);
expect(keys(false)).not.toContain(c.SETTINGS_KEYS.SHOW_MCP);
expect(actions(true)).toContain(SidebarAction.MCP);
expect(actions(false)).not.toContain(SidebarAction.MCP);
expect(keys(true)).toContain(c.SETTINGS_KEYS.ENABLE_MCP);
expect(keys(false)).not.toContain(c.SETTINGS_KEYS.ENABLE_MCP);
expect(c.attachmentTooltipText(false)).not.toMatch(/tools|MCP/i);
});

View file

@ -0,0 +1,65 @@
import type { ModelOption } from '#lib/types/models.js';
import { pickQuickModels } from '#lib/utils/index.ts';
import { describe, expect, it } from 'vitest';
const option = (id: string) => ({ id, model: id, name: id }) as ModelOption;
const options = ['a', 'b', 'c', 'd', 'e'].map(option);
const ids = (items: { option: ModelOption }[]) => items.map((item) => item.option.id);
describe('pickQuickModels', () => {
it('lists loaded, then favorite, then recent models, each once', () => {
expect(
ids(
pickQuickModels({
favoriteIds: new Set(['d', 'b']),
limit: 6,
loadedIds: new Set(['b']),
options,
recentIds: ['e', 'b', 'missing']
})
)
).toEqual(['b', 'd', 'e']);
});
it("leads with the chat's model and the dictation model", () => {
expect(
ids(
pickQuickModels({
activeId: 'c',
dictationModel: 'e',
favoriteIds: new Set(['d']),
limit: 6,
loadedIds: new Set(['b', 'c']),
options,
recentIds: ['a']
})
)
).toEqual(['c', 'e', 'b', 'd', 'a']);
});
it('is empty when nothing is in reach', () => {
expect(
pickQuickModels({
favoriteIds: new Set(),
limit: 6,
loadedIds: new Set(),
options,
recentIds: []
})
).toEqual([]);
});
it('stops at the limit', () => {
expect(
ids(
pickQuickModels({
favoriteIds: new Set(),
limit: 2,
loadedIds: new Set(),
options,
recentIds: ['c', 'a', 'b']
})
)
).toEqual(['c', 'a']);
});
});

View file

@ -0,0 +1,36 @@
import { SETTINGS_CHAT_SECTIONS, SETTINGS_KEYS } from '#lib/constants/index.ts';
import { SettingsPlatform } from '#lib/enums/index.ts';
import { isSettingShownOn } from '#lib/utils/index.ts';
import { describe, expect, it } from 'vitest';
const fields = SETTINGS_CHAT_SECTIONS.flatMap((section) => section.fields ?? []);
function shownKeys(isMobile: boolean): string[] {
return fields.filter((field) => isSettingShownOn(field, isMobile)).map((field) => field.key);
}
describe('settings platform', () => {
it('lists a setting without a platform everywhere', () => {
expect(isSettingShownOn({}, true)).toBe(true);
expect(isSettingShownOn({ platform: SettingsPlatform.ALL }, false)).toBe(true);
});
it('leaves desktop settings off a phone', () => {
const onPhone = shownKeys(true);
for (const key of [
SETTINGS_KEYS.ALWAYS_SHOW_SIDEBAR_ON_DESKTOP,
SETTINGS_KEYS.CONVERSATION_TABS,
SETTINGS_KEYS.SINGLE_ROW_CHAT_FORM,
SETTINGS_KEYS.SEND_ON_ENTER
]) {
expect(onPhone).not.toContain(key);
expect(shownKeys(false)).toContain(key);
}
});
it('leaves phone settings off a desktop', () => {
expect(shownKeys(false)).not.toContain(SETTINGS_KEYS.SHOW_MODEL_ORG_NAME_ON_MOBILE);
expect(shownKeys(true)).toContain(SETTINGS_KEYS.SHOW_MODEL_ORG_NAME_ON_MOBILE);
});
});

View file

@ -36,7 +36,7 @@ beside the apps built on it in `ui/apps`.
- **Components:** every base component of Llama Chat: Alert, AlertDialog, Badge, Button, ButtonGroup, Card, Checkbox,
Collapsible, ContextMenu, Dialog, Drawer, DropdownMenu, Empty, HoverCard, Input, Label, Popover, RadioGroup,
ScrollArea, Select, Separator, Skeleton, Switch, Table, Tabs, Textarea, Toggle, ToggleGroup and Tooltip. Each is
also its own entry point (`@ggml-org/llama-ui/ui/dialog`), with `cn` and `tv` at `@ggml-org/llama-ui/utils`. Then ActionIcon (an icon button with a tooltip), SearchInput (a search field with a clear button), SyntaxHighlightedCode (code as Llama Chat shows it, in highlight.js's GitHub themes; needs `mode-watcher`) and Logo (the brand mark, llama-brand's icon), at `@ggml-org/llama-ui/app/actions`, `app/forms`, `app/content` and `app/misc`. `FILTER_TRIGGER_CLASS` and `FILTER_TOGGLE_ITEM_CLASS` style a filters bar the way Llama Chat's Models Manager does.
also its own entry point (`@ggml-org/llama-ui/ui/dialog`), with `cn` and `tv` at `@ggml-org/llama-ui/utils`. Then ActionIcon (an icon button with a tooltip), SearchInput (a search field with a clear button), NativeSelect (the library's select trigger over the OS's own picker, for touch screens), SyntaxHighlightedCode (code as Llama Chat shows it, in highlight.js's GitHub themes; needs `mode-watcher`) and Logo (the brand mark, llama-brand's icon), at `@ggml-org/llama-ui/app/actions`, `app/forms`, `app/content` and `app/misc`. A phone's sheets are built from `app/sheets`: `SheetHeader` (the close or back key and the title) and `SheetPages` with `useSheetPages` (a stack of pages that slide) inside a Drawer whose content takes `SHEET_CONTENT_CLASS`, and `InsetList`, `InsetListRow` and `InsetListSplitRow` for their native-style lists. `FILTER_TRIGGER_CLASS` and `FILTER_TOGGLE_ITEM_CLASS` style a filters bar the way Llama Chat's Models Manager does.
- **App mockups:** MacMenu (Llama for Mac's menu) and WindowsTray (Llama for Windows' tray flyout), the native apps' UIs as the brand's communications draw them, with an `annotate` snippet to pin a page's numbered callouts to their edges.
- **Model UI:** how a model is shown in Llama Chat and on llama.app: `ModelCard`, `ModelFamilyCard` (a family as llama.app's catalog
shows it), `ModelId` (name, badges, capability,

View file

@ -1,12 +1,12 @@
{
"name": "@ggml-org/llama-ui",
"version": "0.6.0",
"version": "0.7.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@ggml-org/llama-ui",
"version": "0.6.0",
"version": "0.7.0",
"license": "MIT",
"dependencies": {
"@ggml-org/llama-brand": "0.1.0",

View file

@ -1,6 +1,6 @@
{
"name": "@ggml-org/llama-ui",
"version": "0.6.0",
"version": "0.7.0",
"description": "Shared UI library for llama.cpp frontend apps.",
"license": "MIT",
"repository": {

View file

@ -0,0 +1,96 @@
<!--
A select whose trigger looks like ours but opens the OS's own picker: a native <select> lies
invisible over the trigger and takes the tap, so a phone shows its wheel or sheet.
-->
<script lang="ts">
import { ChevronDown, ChevronsUpDown } from '@lucide/svelte';
import { NATIVE_SELECT_PLACEHOLDER } from '../../../constants';
interface NativeSelectOption {
label: string;
value: string;
}
interface Props {
/** Shown on the trigger in place of the selected option's label. */
displayLabel?: string;
disabled?: boolean;
/** Options under a heading of their own, after the ungrouped ones. */
groups?: Array<{ heading: string; options: NativeSelectOption[] }>;
id?: string;
label: string;
onValueChange: (value: string) => void;
options?: NativeSelectOption[];
placeholder?: string;
value: string;
/** `default` is the boxed select trigger; `inset` is a value and chevron at a row's end. */
variant?: 'default' | 'inset';
class?: string;
}
let {
class: className = '',
disabled = false,
displayLabel,
groups = [],
id,
label,
onValueChange,
options = [],
placeholder = NATIVE_SELECT_PLACEHOLDER,
value,
variant = 'default'
}: Props = $props();
let selected = $derived(
[...options, ...groups.flatMap((group) => group.options)].find(
(option) => option.value === value
)
);
let shown = $derived(displayLabel ?? selected?.label ?? placeholder);
</script>
<div
class={[
'relative flex min-w-0 items-center has-[select:focus-visible]:ring-3 has-[select:focus-visible]:ring-ring/50',
variant === 'inset'
? 'max-w-[60%] gap-1 rounded-md text-body-sm text-muted-foreground'
: 'h-9 w-full justify-between gap-2 rounded-md border border-border/30 bg-muted/60 px-3 text-body-sm matte-key dark:border-border/20 dark:bg-muted/75',
disabled && 'opacity-50',
className
]}
>
<span class={['truncate', !selected && !displayLabel && 'text-muted-foreground']}>{shown}</span>
{#if variant === 'inset'}
<ChevronsUpDown class="size-3.5 shrink-0" />
{:else}
<ChevronDown class="size-3.5 shrink-0 opacity-60" />
{/if}
<!-- 16px, or iOS zooms the page in when the picker opens -->
<select
aria-label={label}
class="absolute inset-0 size-full cursor-pointer appearance-none text-body opacity-0 disabled:cursor-not-allowed"
{disabled}
{id}
onchange={(event) => onValueChange(event.currentTarget.value)}
{value}
>
{#if !selected}
<option disabled {value}>{placeholder}</option>
{/if}
{#each options as option (option.value)}
<option value={option.value}>{option.label}</option>
{/each}
{#each groups as group (group.heading)}
<optgroup label={group.heading}>
{#each group.options as option (option.value)}
<option value={option.value}>{option.label}</option>
{/each}
</optgroup>
{/each}
</select>
</div>

View file

@ -11,6 +11,8 @@
onClose?: () => void;
onKeyDown?: (event: KeyboardEvent) => void;
class?: string;
/** Classes of the input itself, e.g. to drop its field look inside a surface of the wrapper's. */
inputClass?: string;
/** Input height, matching the small size of the other controls. */
size?: 'sm' | 'default';
id?: string;
@ -22,6 +24,7 @@
autofocus,
class: className,
id,
inputClass = '',
isCancelAlwaysVisible = false,
onClose,
onInput,
@ -63,7 +66,7 @@
{autofocus}
class="max-md:h-10 pl-9 {showClearButton ? 'pr-9' : ''} {size === 'sm'
? 'h-8'
: ''} [&::-webkit-search-cancel-button]:hidden"
: ''} [&::-webkit-search-cancel-button]:hidden {inputClass}"
{id}
oninput={handleInput}
onkeydown={onKeyDown}

View file

@ -1 +1,4 @@
export { default as SearchInput } from './SearchInput.svelte';
/** A select with the library's trigger that opens the OS's own picker, for touch screens. */
export { default as NativeSelect } from './NativeSelect.svelte';

View file

@ -0,0 +1,39 @@
<!--
An inset list: a rounded group of rows, as a phone's settings list them, with an optional title
above and caption below. Its rows are InsetListRow and InsetListSplitRow.
-->
<script lang="ts">
import type { Snippet } from 'svelte';
import type { HTMLAttributes } from 'svelte/elements';
import { cn } from '../../ui/utils';
interface Props extends Omit<HTMLAttributes<HTMLDivElement>, 'class' | 'title'> {
/** A note below the group. */
caption?: Snippet | string;
children: Snippet;
/** Classes of the group itself. */
class?: string;
/** The group's title above it. */
title?: Snippet | string;
}
let { caption, children, class: className, title, ...rest }: Props = $props();
</script>
<div class="flex flex-col gap-1.5" {...rest}>
{#if title}
<h3 class="inset-list-title">
{#if typeof title === 'string'}{title}{:else}{@render title()}{/if}
</h3>
{/if}
<section class={cn('inset-list', className)}>
{@render children()}
</section>
{#if caption}
<p class="inset-list-caption">
{#if typeof caption === 'string'}{caption}{:else}{@render caption()}{/if}
</p>
{/if}
</div>

View file

@ -0,0 +1,62 @@
<!--
A row of an InsetList, a finger tall and tappable as a whole: a button, a label around a switch,
or a plain row holding a control. Its content is the row's body, after an optional icon.
-->
<script lang="ts">
import { ChevronRight } from '@lucide/svelte';
import type { ClassValue } from 'clsx';
import type { Component, Snippet } from 'svelte';
import type { HTMLAttributes } from 'svelte/elements';
import { cn } from '../../ui/utils';
import { ICON_CLASS_DEFAULT } from '../../../constants';
interface Props extends Omit<HTMLAttributes<HTMLElement>, 'class'> {
/** `button` is tapped, `label` wraps a switch, `div` holds a control of its own. */
as?: 'button' | 'div' | 'label';
/** Classes of the body: the label and value, whose top border is the divider. */
bodyClass?: ClassValue;
children: Snippet;
/** Show a chevron at the row's end: the row opens a page. */
chevron?: boolean;
class?: ClassValue;
disabled?: boolean;
/** The icon before the body, outside the divider. */
icon?: Component<{ class?: string }>;
iconClass?: ClassValue;
/** Drawn in place of `icon`, for an avatar or an image. */
leading?: Snippet;
}
let {
as = 'button',
bodyClass,
children,
chevron = false,
class: className,
icon: Icon,
iconClass,
leading,
...rest
}: Props = $props();
</script>
<svelte:element
this={as}
class={cn('inset-list-row', as === 'label' && 'cursor-pointer', className)}
type={as === 'button' ? 'button' : undefined}
{...rest}
>
{#if leading}
{@render leading()}
{:else if Icon}
<Icon class={cn(ICON_CLASS_DEFAULT, 'shrink-0', iconClass)} />
{/if}
<span class={cn('inset-list-row-body', bodyClass)}>
{@render children()}
{#if chevron}
<ChevronRight class="size-4 shrink-0 text-muted-foreground" />
{/if}
</span>
</svelte:element>

View file

@ -0,0 +1,60 @@
<!--
A row of an InsetList with two targets: the row itself opens a page, and a control at its end
(a switch) acts on the row without opening it.
-->
<script lang="ts">
import { ChevronRight } from '@lucide/svelte';
import type { Component, Snippet } from 'svelte';
import { cn } from '../../ui/utils';
import { ICON_CLASS_DEFAULT } from '../../../constants';
interface Props {
children: Snippet;
class?: string;
/** Draw the row as unavailable. */
dimmed?: boolean;
icon?: Component<{ class?: string }>;
/** Drawn in place of `icon`, for an avatar or an image. */
leading?: Snippet;
onclick: () => void;
/** The control at the row's end. */
trailing: Snippet;
}
let {
children,
class: className,
dimmed = false,
icon: Icon,
leading,
onclick,
trailing
}: Props = $props();
</script>
<div class={cn('group/row flex min-h-12 items-center px-4', dimmed && 'opacity-50', className)}>
<button
class="flex min-h-12 min-w-0 flex-1 items-center gap-3 self-stretch text-left text-body"
{onclick}
type="button"
>
{#if leading}
{@render leading()}
{:else if Icon}
<Icon class={cn(ICON_CLASS_DEFAULT, 'shrink-0')} />
{/if}
<span class="inset-list-row-body">
{@render children()}
<ChevronRight class="size-4 shrink-0 text-muted-foreground" />
</span>
</button>
<!-- the divider runs on under the control -->
<span
class="flex items-center self-stretch border-t border-border/60 pl-3 group-first/row:border-t-0"
>
{@render trailing()}
</span>
</div>

View file

@ -0,0 +1,64 @@
<!--
A sheet's header: a round key in the top-left corner (close on the first page, back on the pages
pushed over it) and the title centered on that key. It goes inside a Drawer's content, which
takes SHEET_CONTENT_CLASS.
-->
<script lang="ts">
import { ChevronLeft, X } from '@lucide/svelte';
import * as Drawer from '../../ui/drawer';
import { cn } from '../../ui/utils';
import { ICON_CLASS_DEFAULT, SHEET_TEXT } from '../../../constants';
interface Props {
backLabel?: string;
/** Show back in place of close: a page sits over the first one. */
canGoBack?: boolean;
class?: string;
closeLabel?: string;
/** Lay the header over the content, which scrolls under its blurred, fading surface. */
floating?: boolean;
onBack?: () => void;
title: string;
}
let {
backLabel = SHEET_TEXT.BACK,
canGoBack = false,
class: className,
closeLabel = SHEET_TEXT.CLOSE,
floating = false,
onBack,
title
}: Props = $props();
</script>
<header
class={cn(
'grid grid-cols-[3rem_1fr_3rem] items-center px-3 pb-7',
floating
? 'pointer-events-none absolute inset-x-0 top-0 isolate z-10 pt-5.5 *:pointer-events-auto'
: 'shrink-0 pt-2.5',
className
)}
>
{#if floating}
<div
aria-hidden="true"
class="pointer-events-none! absolute inset-0 -z-10 bg-(--float-panel-background) backdrop-blur-xl mask-[linear-gradient(to_bottom,black_60%,transparent)]"
></div>
{/if}
{#if canGoBack}
<button aria-label={backLabel} class="sheet-key" onclick={onBack} type="button">
<ChevronLeft class="size-5" />
</button>
{:else}
<Drawer.Close aria-label={closeLabel} class="sheet-key">
<X class={ICON_CLASS_DEFAULT} />
</Drawer.Close>
{/if}
<Drawer.Title class="col-start-2 truncate text-center text-body font-semibold">
{title}
</Drawer.Title>
</header>

View file

@ -0,0 +1,68 @@
<!--
The scrolling body of a sheet with pages: it shows the page on top of a `useSheetPages` stack and
slides between pages as they are pushed and popped.
-->
<script generics="P" lang="ts">
import type { Snippet } from 'svelte';
import { cn } from '../../ui/utils';
import type { SheetPagesState } from './sheet-pages.svelte';
interface Props {
children: Snippet;
/** Classes of each page: its padding and the gap between its groups. */
class?: string;
/** Keep the first page's height as the floor of the pages pushed over it, so a short sheet does not jump. */
keepFirstPageHeight?: boolean;
/** Identifies the page shown; a change of it slides to the new page. */
pageKey: string;
pages: SheetPagesState<P>;
/** The scrolling element, to read or set its scroll position. */
ref?: HTMLDivElement | null;
scrollClass?: string;
}
let {
children,
class: className,
keepFirstPageHeight = false,
pageKey,
pages,
ref = $bindable(null),
scrollClass
}: Props = $props();
let firstPageHeight = $state(0);
let minHeight = $derived(
keepFirstPageHeight && pages.canGoBack && firstPageHeight ? `${firstPageHeight}px` : undefined
);
function slide(node: Element, params: { incoming: boolean }) {
return pages.transition(node, params);
}
</script>
<div
bind:this={ref}
style:min-height={minHeight}
class={cn(
'grid min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain',
scrollClass
)}
>
{#key pageKey}
<div
bind:clientHeight={
() => firstPageHeight,
(height) => {
if (!pages.canGoBack && height) firstPageHeight = height;
}
}
in:slide={{ incoming: true }}
out:slide={{ incoming: false }}
class={cn('col-start-1 row-start-1 flex min-w-0 flex-col', className)}
>
{@render children()}
</div>
{/key}
</div>

View file

@ -0,0 +1,16 @@
/** A rounded group of rows with an optional title and caption, as a phone's settings list them. */
export { default as InsetList } from './InsetList.svelte';
/** A row of an InsetList: a button, a label around a switch, or a row holding a control. */
export { default as InsetListRow } from './InsetListRow.svelte';
/** A row of an InsetList that opens a page and has a control of its own at its end. */
export { default as InsetListSplitRow } from './InsetListSplitRow.svelte';
/** A sheet's header: the close or back key in its corner and the centered title. */
export { default as SheetHeader } from './SheetHeader.svelte';
/** The scrolling body of a sheet, sliding between the pages of a `useSheetPages` stack. */
export { default as SheetPages } from './SheetPages.svelte';
export { type SheetPagesState, useSheetPages } from './sheet-pages.svelte';

View file

@ -0,0 +1,63 @@
import { prefersReducedMotion } from 'svelte/motion';
import { fly, type TransitionConfig } from 'svelte/transition';
import { SHEET_PAGE_SLIDE_MS, SHEET_PAGE_SLIDE_PX } from '../../../constants';
/** A slide to the next page, or back to the previous one. */
enum SlideDirection {
BACK = -1,
FORWARD = 1
}
export interface SheetPagesState<P> {
/** The page on top of the stack. */
readonly page: P;
/** Whether a page sits over the first one, so the header shows back instead of close. */
readonly canGoBack: boolean;
push(next: P): void;
/** Back to the page below; does nothing on the first page. */
pop(): void;
/** Back to the first page, for each time the sheet opens. */
reset(): void;
/** The slide between pages: the next one comes in from the right, the previous one from the left. */
transition(node: Element, params: { incoming: boolean }): TransitionConfig;
}
/**
* A stack of pages inside a sheet, the native way: tapping a row pushes its page, back pops it.
*/
export function useSheetPages<P>(root: P): SheetPagesState<P> {
let stack = $state<P[]>([root]);
let direction = SlideDirection.FORWARD;
return {
get canGoBack() {
return stack.length > 1;
},
get page() {
return stack[stack.length - 1];
},
pop() {
if (stack.length <= 1) return;
direction = SlideDirection.BACK;
stack = stack.slice(0, -1);
},
push(next: P) {
direction = SlideDirection.FORWARD;
stack = [...stack, next];
},
reset() {
stack = [root];
},
transition(node: Element, { incoming }: { incoming: boolean }) {
const offset = prefersReducedMotion.current ? 0 : SHEET_PAGE_SLIDE_PX;
const sign = incoming ? direction : -direction;
return fly(node, {
duration: SHEET_PAGE_SLIDE_MS,
opacity: 0,
x: sign * offset
});
}
};
}

View file

@ -19,13 +19,15 @@
} = $props();
</script>
<!-- a bottom sheet spans the screen's width and rounds its top corners as the screen's own are
(--sheet-radius); the inset groups inside it take the sheet's rounder group radius -->
<DrawerPortal {...portalProps}>
<DrawerOverlay class={overlayClass} />
<DrawerPrimitive.Content
bind:ref
class={cn(
'matte-float text-popover-foreground flex h-auto flex-col text-body-sm data-[vaul-drawer-direction=bottom]:rounded-t-xl data-[vaul-drawer-direction=bottom]:border-t data-[vaul-drawer-direction=left]:rounded-r-xl data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=right]:rounded-l-xl data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=top]:rounded-b-xl data-[vaul-drawer-direction=top]:border-b group/drawer-content fixed z-50 data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:start-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:end-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=left]:sm:max-w-sm data-[vaul-drawer-direction=right]:sm:max-w-sm',
'matte-float text-popover-foreground flex h-auto flex-col text-body-sm [--inset-group-radius:var(--sheet-group-radius)] [--sheet-radius:2.5rem] data-[vaul-drawer-direction=bottom]:rounded-t-(--sheet-radius) data-[vaul-drawer-direction=bottom]:border-t data-[vaul-drawer-direction=left]:rounded-r-xl data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=right]:rounded-l-xl data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=top]:rounded-b-xl data-[vaul-drawer-direction=top]:border-b group/drawer-content fixed z-50 data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:start-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:end-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=left]:sm:max-w-sm data-[vaul-drawer-direction=right]:sm:max-w-sm',
className
)}
data-slot="drawer-content"

View file

@ -6,23 +6,28 @@
checked = $bindable(false),
class: className,
ref = $bindable(null),
size = 'default',
...restProps
}: WithoutChildrenOrChild<SwitchPrimitive.RootProps> = $props();
}: WithoutChildrenOrChild<SwitchPrimitive.RootProps> & {
/** `lg` is sized for a finger, for touch screens' settings lists. */
size?: 'default' | 'lg';
} = $props();
</script>
<SwitchPrimitive.Root
bind:checked
bind:ref
class={cn(
'peer inline-flex h-[1.15rem] w-8 shrink-0 cursor-pointer items-center rounded-full border border-transparent bg-(--surface-muted) shadow-(--elevation-inset) transition-all outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-(--action-primary)',
'peer group/switch inline-flex h-[1.15rem] w-8 data-[size=lg]:h-7 data-[size=lg]:w-12 shrink-0 cursor-pointer items-center rounded-full border border-transparent bg-(--surface-muted) shadow-(--elevation-inset) transition-all outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-(--action-primary)',
className
)}
data-size={size}
data-slot="switch"
{...restProps}
>
<SwitchPrimitive.Thumb
class={cn(
'pointer-events-none block size-4 rounded-full bg-(--surface-lifted) shadow-(--elevation-control) ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=checked]:bg-(--switch-thumb-on) data-[state=unchecked]:translate-x-0'
'pointer-events-none block size-4 group-data-[size=lg]/switch:size-6 rounded-full bg-(--surface-lifted) shadow-(--elevation-control) ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=checked]:bg-(--switch-thumb-on) data-[state=unchecked]:translate-x-0'
)}
data-slot="switch-thumb"
/>

View file

@ -2,3 +2,4 @@ export * from './css-classes.constants';
export * from './code-block.constants';
export * from './ui.constants';
export * from './voice.constants';
export * from './sheet.constants';

View file

@ -0,0 +1,20 @@
/** How far (px) a sheet page slides as it comes in or leaves; nothing with reduced motion. */
export const SHEET_PAGE_SLIDE_PX = 32;
/** How long (ms) the slide between two sheet pages takes. */
export const SHEET_PAGE_SLIDE_MS = 220;
/** Labels of a sheet's corner key. */
export const SHEET_TEXT = {
BACK: 'Back',
CLOSE: 'Close'
} as const;
/**
* Classes of a drawer's content when it holds a SheetHeader: the drag handle sits 0.5rem from the
* top, clear of the corner key and of the title centered on that key.
*/
export const SHEET_CONTENT_CLASS = '[&>div:first-child]:mt-2';
/** Placeholder of a NativeSelect with no option picked. */
export const NATIVE_SELECT_PLACEHOLDER = 'Select';

View file

@ -3,9 +3,10 @@
export { cn, tv, type WithElementRef, type WithoutChild, type WithoutChildren, type WithoutChildrenOrChild } from './components/ui/utils.js';
export { ActionIcon } from './components/app/actions/index.js';
export { SyntaxHighlightedCode } from './components/app/content/index.js';
export { SearchInput } from './components/app/forms/index.js';
export { NativeSelect, SearchInput } from './components/app/forms/index.js';
export { Logo } from './components/app/misc/index.js';
export { FILTER_TOGGLE_ITEM_CLASS, FILTER_TRIGGER_CLASS, PANEL_CLOSE_MOBILE_CLASS } from './constants/index.js';
export { InsetList, InsetListRow, InsetListSplitRow, SheetHeader, SheetPages, type SheetPagesState, useSheetPages } from './components/app/sheets/index.js';
export { FILTER_TOGGLE_ITEM_CLASS, FILTER_TRIGGER_CLASS, PANEL_CLOSE_MOBILE_CLASS, SHEET_CONTENT_CLASS } from './constants/index.js';
export { ColorMode, TooltipSide } from './enums/index.js';
export { highlightCode, isHighlightLanguageLoaded, loadHighlightLanguages, resolveHighlightLanguage } from './utils/index.js';
export * as Alert from './components/ui/alert/index.js';

View file

@ -110,6 +110,92 @@
border-radius: var(--inset-group-radius);
}
/* Inset list: a phone sheet's native-style list. `inset-list` is an inset group of rows;
`inset-list-row` is a row, tappable as a whole, its icon outside the divider;
`inset-list-row-body` holds the label and value, and its top border is the divider, which
starts at the label and is dropped on the first row. `inset-list-title` sits above a group
and `inset-list-caption` below it. */
@utility inset-list {
@apply inset-group-surface;
display: flex;
flex-direction: column;
overflow: hidden;
}
@utility inset-list-row {
@apply text-body;
display: flex;
width: 100%;
min-height: 3rem;
align-items: center;
gap: 0.75rem;
padding-inline: 1rem;
text-align: left;
transition: background-color 150ms;
&:active {
background-color: var(--surface-pressed);
}
&:disabled {
pointer-events: none;
opacity: 0.5;
}
}
@utility inset-list-row-body {
display: flex;
min-width: 0;
min-height: 3rem;
flex: 1 1 0%;
align-items: center;
align-self: stretch;
gap: 0.5rem;
border-top: 1px solid color-mix(in oklab, var(--line-default) 60%, transparent);
/* the first row of a group has no divider, whether the row is an inset-list-row or built
by hand around one (a row split into two targets) */
.inset-list-row:first-child &,
.inset-list > :first-child & {
border-top-width: 0;
}
}
@utility inset-list-title {
@apply text-body;
padding-inline: 1rem;
font-weight: 500;
color: var(--fg-muted);
}
@utility inset-list-caption {
@apply text-caption;
padding-inline: 1rem;
color: var(--fg-muted);
}
/* A sheet's round corner key, close or back: 1rem from the top edge and from the side, outside
the header's flow, so a title row centered at 2.125rem lines up with its middle */
@utility sheet-key {
@apply matte-key;
position: absolute;
top: 1rem;
left: 1rem;
z-index: 10;
display: flex;
width: 2.25rem;
height: 2.25rem;
align-items: center;
justify-content: center;
border-radius: calc(infinity * 1px);
background-color: var(--surface-page);
box-shadow: var(--elevation-key);
&:where(.dark, .dark *) {
background-color: color-mix(in oklab, var(--fg-muted) 15%, transparent);
}
}
/* the row a sidebar list is on: the inset group's edge and shade around a tint. It keeps the
row's own radius, and hover or press fills (bg-*) still paint over it */
@utility selected-row-surface {

View file

@ -17,6 +17,10 @@
/* a step rounder than a card, so the rows inside it (its radius less its padding, see the
nested surfaces in Llama Chat's app.css) keep soft corners */
--inset-group-radius: 1rem;
/* a sheet's groups are rounder: they sit in a panel with the screen's own corner radius, and
their rows are a finger tall. A drawer sets --inset-group-radius to this, and a finger-tall
field or button shares it */
--sheet-group-radius: 1.25rem;
/* selected row: the page a sidebar row opens is on. A tint of the text colour, under hover's,
with the inset group's edge and shade so it reads as picked out rather than hovered */

View file

@ -0,0 +1,119 @@
<script lang="ts" module>
import StateGallery from '../helpers/StateGallery.svelte';
import StateGalleryItem from '../helpers/StateGalleryItem.svelte';
import { defineMeta } from '@storybook/addon-svelte-csf';
import { InsetList, InsetListRow, InsetListSplitRow } from '@ggml-org/llama-ui/app/sheets';
import { Switch } from '@ggml-org/llama-ui/ui/switch';
import { Check, Folder, Globe, Server, Trash2 } from '@lucide/svelte';
// the native-style list of a phone's sheets: rounded groups of finger-tall rows, the divider
// starting at the label. Shown in a float panel with the sheet's group radius, as a drawer sets it
const { Story } = defineMeta({
component: InsetList,
parameters: {
layout: 'centered'
},
title: 'Llama UI/App components/InsetList'
});
const PANEL_CLASS =
'matte-float flex w-80 flex-col gap-6 rounded-2xl border p-3 [--inset-group-radius:var(--sheet-group-radius)]';
</script>
<script lang="ts">
let webSearch = $state(true);
let server = $state(false);
let picked = $state('Light');
</script>
<Story asChild name="Default">
<StateGallery columns={2}>
<StateGalleryItem label="Rows that open a page" note="icon, value, chevron">
<div class={PANEL_CLASS}>
<InsetList caption="A caption sits under its group." title="Files">
<InsetListRow chevron icon={Folder}>
<span class="shrink-0">Working directory</span>
<span class="min-w-0 flex-1 truncate text-right text-body-sm text-muted-foreground">
~/projects/llama
</span>
</InsetListRow>
<InsetListRow chevron icon={Globe}>
<span class="flex-1">Web search</span>
</InsetListRow>
</InsetList>
</div>
</StateGalleryItem>
<StateGalleryItem label="Rows with a switch" note="the whole row is the label">
<div class={PANEL_CLASS}>
<InsetList>
<InsetListRow as="label">
<span class="flex-1">Web search</span>
<Switch bind:checked={webSearch} size="lg" />
</InsetListRow>
<InsetListRow as="label">
<span class="flex-1">Server tools</span>
<Switch bind:checked={server} size="lg" />
</InsetListRow>
</InsetList>
</div>
</StateGalleryItem>
<StateGalleryItem label="A choice of one" note="a check marks the pick">
<div class={PANEL_CLASS}>
<InsetList title="Appearance">
{#each ['Light', 'Dark', 'System'] as option (option)}
<InsetListRow aria-pressed={option === picked} onclick={() => (picked = option)}>
<span class="flex-1">{option}</span>
{#if option === picked}
<Check class="size-4 text-(--action-primary)" />
{/if}
</InsetListRow>
{/each}
</InsetList>
</div>
</StateGalleryItem>
<StateGalleryItem label="Split rows" note="the row opens a page, the switch acts on it">
<div class={PANEL_CLASS}>
<InsetList title="MCP servers">
<InsetListSplitRow icon={Server} onclick={() => {}}>
<span class="min-w-0 flex-1 truncate">Hugging Face</span>
<span class="text-body-sm text-muted-foreground tabular-nums">4/9</span>
{#snippet trailing()}
<Switch aria-label="Hugging Face tools" checked size="lg" />
{/snippet}
</InsetListSplitRow>
<InsetListSplitRow dimmed icon={Server} onclick={() => {}}>
<span class="min-w-0 flex-1 truncate">Filesystem</span>
<span class="text-body-sm text-muted-foreground tabular-nums">0/5</span>
{#snippet trailing()}
<Switch aria-label="Filesystem tools" disabled size="lg" />
{/snippet}
</InsetListSplitRow>
</InsetList>
</div>
</StateGalleryItem>
<StateGalleryItem label="A destructive row">
<div class={PANEL_CLASS}>
<InsetList>
<InsetListRow bodyClass="text-destructive" icon={Trash2} iconClass="text-destructive">
Delete all conversations
</InsetListRow>
</InsetList>
</div>
</StateGalleryItem>
</StateGallery>
</Story>

Some files were not shown because too many files have changed in this diff Show more