ui: type /cwd and other slash commands anywhere in the chat input (#33070)

* ui: type the working directory on a /cwd line in the chat input

On a desktop, choosing the working directory from the + menu or the chip
puts `/cwd <path>` above the message being written, with the caret after
the path, instead of opening a separate search field. The suggestions
follow what is typed there, Enter picks only from them, and closing the
picker gives the message back as it was.

The chat form's pickers float above the line being written, also in the
collapsed form, and fit their suggestions between a min and a max width.
A directory under home always shows from `~/`.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: find working directories by a partial name, allowing for a typo

A plain name on the /cwd line is now looked up anywhere under home, not
only among its direct children, with the nearest folders listed first.
A search that finds nothing is retried allowing for one wrong, missing,
extra or swapped character.

Assisted-by: Claude (Fable 5.2)

* ui: keep the path pickers at one width and list hidden folders last

The @ mention and /cwd pickers no longer resize with their results, and
folders that are hidden or sit inside a hidden folder rank below regular
ones unless the query itself starts with a dot.

Assisted-by: Claude (Fable 5.2)

* ui: list a relative path's own folder before its deeper namesakes

A query with a path in it (ui/lib/voi) was matched only below some other
folder, never at the top of the scope, so hidden copies were the only
results. The path is now also followed from the scope itself and listed
first.

Assisted-by: Claude (Fable 5.2)

* ui: fix the folder pickers' review findings

- Read a backslash as a path separator under a Windows home or working
  directory, in the /cwd and @ pickers.
- Leave Enter to an IME composition, and to the message when the caret is
  below the /cwd line.
- Close the /cwd line before sending, so it is not sent as text.
- Keep the highlighted folder when the deeper results arrive, and do not
  leave the deep search's failure unhandled.
- Walk the typo search nearest depth first and stop once it finds something.
- Surface the deep search's error when a relative path finds nothing.

Assisted-by: Claude (Fable 5.2)

* ui: highlight the first suggestion of every new round in the pickers

A list that renders under a resting pointer no longer counts as a hover, and the
folder picker starts each round of results on its first folder.

Assisted-by: Claude (Fable 5.2)

* ui: keep the new chat's form in place as chips appear under it

Assisted-by: Claude (Fable 5.2)

* ui: drop the command picker's icons and shorten /compact's description

Assisted-by: Claude (Fable 5.2)

* ui: always edit the system message in the chat form, without a model selector

The + menu turns the form into the system message editor whether or not the
conversation shows its system message, and the editor offers no model selector.

Assisted-by: Claude (Fable 5.2)

* ui: add /system-message and keep the form's size in system message mode

The command turns the chat form into the system message editor. The editor's
dashed edge is an inset outline in place of the card's own edge, so the card
keeps its size.

Assisted-by: Claude (Fable 5.2)

* ui: find a rooted path's name further down, and retry a failed home lookup

`@~/llama.cpp` and `/cwd ~/llama.cpp` list `~/git/llama.cpp` when home itself
holds no such name. A failed lookup of the server's home directory is no longer
kept for the session, so the working directory can show from `~/` once it works.

Assisted-by: Claude (Fable 5.2)

* ui: type slash commands anywhere in the message

A command is found at the caret, after other words or on another line, not only
at the start of the input. Picking one takes just the command out and leaves the
words around it, and /cwd stays where it was typed (the + menu writes it at the
caret), so the path no longer jumps to a line of its own above the message.

Assisted-by: Claude (Opus 5.5)

* ui: keep the words after an argless command, and track /cwd by its edits

- only /prompt and /cwd read the words after them: Enter after
  `use /m the small one` no longer picks /model and deletes the sentence
- the open /cwd picker follows its own command after an edit, never
  another /cwd the message names, and closes when its command is deleted
- a blocked send leaves the /cwd command and its picker alone
- callers of the server home share one request
- a typo-tolerant folder search whose every glob fails shows the error
- hidden folders sort last behind backslash separators too

Assisted-by: Claude (Opus 5.5 Medium)
This commit is contained in:
Aleksander Grygier 2026-11-26 21:25:36 +01:00 • committed by GitHub
parent 2a335259ca
commit e8d7128fea
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
31 changed files with 1774 additions and 297 deletions

View file

@ -64,7 +64,6 @@
} from '#lib/types/index.ts';
import {
buildMentionInsertion,
findCommandToken,
findMentionToken,
getConversationModel,
isIMEComposing,
@ -140,6 +139,7 @@
let pickersRef: { handleKeydown: (event: KeyboardEvent) => boolean } | undefined =
$state(undefined);
let inputRef: ChatFormInput | undefined = $state(undefined);
let workingDirectoryRef: ChatFormCurrentWorkingDirectory | undefined = $state(undefined);
// Voice input
const recorder: VoiceRecorderLike = untrack(() => voiceRecorder) ?? new VoiceRecorder();
@ -148,8 +148,8 @@
/** Why the last start failed (denied, no microphone, busy); the next tap tries again. */
let micError = $state<string | null>(null);
// Invisible anchor the pickers' popovers float above: the form's top edge, or in the
// expanded editor the line being written
// Invisible anchor the pickers' popovers float above: the line being written, or on a
// phone the form's top edge
let pickerAnchor: HTMLDivElement | null = $state(null);
let pickerAnchorBox = $state({ height: 1, top: 0 });
@ -174,6 +174,8 @@
conversationsStore.activeConversation ? systemMessage?.content : undefined
);
// a system message is the same whichever model answers: its editor offers no selector
let isModelSelectorShown = $derived(showModelSelector && !systemMode);
let showWorkingDirectory = $derived(conversationsStore.preferences.hasEnabledCwdTools());
// On a desktop the chip under the form shows a directory once one is set, and the + menu
// sets one until then. A phone has no chip: a chat shows it in its header (see
@ -185,12 +187,16 @@
const pickers = useChatFormPickers({
canCompact: () => chatStore.canCompact(conversationsStore.activeMessages),
canEditSystemMessage: () => !!onSystemPromptClick && !systemMode,
// a phone picks in a drawer with its own search field, and a touch screen opens no
// typed pickers (see opensOnInput)
editsCwdInline: () => !deviceStore.isMobile && !deviceStore.isTouch,
focusInput: refocusInput,
getCaretOffset: () => inputRef?.getCaretOffset(),
getCwd: () => cwd,
getPickersRef: () => pickersRef,
getServerHome: () => toolsStore.serverHome ?? null,
getShowModelSelector: () => showModelSelector,
getShowModelSelector: () => isModelSelectorShown,
getValue: () => value,
hasCwdTools: () => conversationsStore.preferences.hasEnabledCwdTools(),
// policy-aware, same rule as the agentic flow: MCP category on and at
@ -205,12 +211,17 @@
.some((s) => s.enabled && prefs.isServerToolsEnabled(s.id) && s.url.trim());
},
onCompact: () => chatStore.compactConversation(),
onSystemMessage: () => onSystemPromptClick?.({ files: uploadedFiles, message: value }),
openModelSelector: () => chatFormActionsRef?.openModelSelector(),
// TODO: no typed pickers with an on-screen keyboard for now: each mobile browser moves
// the page its own way as it opens, so a list by the form can not stay clear of the
// text. A drawer with its own search field (as the directory picker is) could.
opensOnInput: () => !deviceStore.isTouch,
setCaretOffset: (offset) => inputRef?.setCaretOffset(offset),
setCaretOffset: (offset) => {
inputRef?.setCaretOffset(offset);
// the caret moved without typing, e.g. onto the `/cwd` line the + menu just added
measurePickerAnchor();
},
setValue: (v) => {
value = v;
onValueChange?.(v);
@ -237,14 +248,9 @@
});
async function handleWorkingDirectoryChange(newDir: string | null) {
// Committing a directory consumes the `/cwd` token; the chip's
// clear-X path has no token to consume.
const token = findCommandToken(value);
if (token && token.name === 'cwd') {
value = '';
onValueChange?.('');
}
// Committing a directory consumes the `/cwd` line and keeps the message below it; the
// chip's clear-X path has no line to consume.
pickers.consumeCwdCommand();
await conversationsStore.preferences.setCwd(newDir);
@ -365,18 +371,30 @@
isExpanded && deviceStore.isMobile ? (actionsEl ?? null) : pickerAnchor
);
// The anchor covers the caret's line, kept within the form when the line is scrolled out
// of the editor's view; on a phone the form's top edge
function measurePickerAnchor() {
const line = deviceStore.isMobile ? null : inputRef?.getCaretRect();
const form = pickerAnchor?.parentElement?.getBoundingClientRect();
if (!line || !form) {
pickerAnchorBox = { height: 1, top: 0 };
return;
}
const top = Math.min(Math.max(line.top - form.top, 0), form.height);
pickerAnchorBox = { height: Math.max(line.bottom - line.top, 1), top };
}
// before the popover is drawn, and again as the query is typed and the line moves
$effect.pre(() => {
if (!isPickerOpen) return;
void value;
const line = isExpanded && !deviceStore.isMobile ? inputRef?.getCaretRect() : null;
const formTop = pickerAnchor?.parentElement?.getBoundingClientRect().top ?? 0;
pickerAnchorBox = line
? { height: line.bottom - line.top, top: line.top - formTop }
: { height: 1, top: 0 };
measurePickerAnchor();
});
// shown on hover (always on touch screens) while collapsed, always while expanded: on
// the phone sheet it keeps the collapsed card's place, below the status bar
@ -447,7 +465,14 @@
function handleKeydown(event: KeyboardEvent) {
// Pickers consume navigation/escape keys first; when consumed, skip
// the enter-to-submit logic below and keep the key from the editor.
if (pickers.handleKeydown(event)) {
// The directory picker takes the keys typed on its `/cwd` line; in the message below
// it only Escape, so Enter and the arrows there stay the message's
const isDirectoryKey = pickers.isCaretInCwdCommand() || event.key === KeyboardKey.ESCAPE;
if (
(isDirectoryKey && workingDirectoryRef?.handleKeydown(event)) ||
pickers.handleKeydown(event)
) {
event.preventDefault();
return;
@ -678,6 +703,13 @@
async function submit() {
if (!canSubmit || disabled || hasLoadingAttachments || isSendWaiting) return;
// sending closes the directory picker first, so its `/cwd` command is not sent as text
if (pickers.isWorkingDirectoryPickerOpen) {
pickers.handleWorkingDirectoryClose();
if (!canSubmit) return;
}
if (voice.isRefining) {
isSendWaiting = true;
@ -809,7 +841,9 @@
'max-md:border-transparent max-md:focus-within:border-transparent max-md:dark:border-transparent max-md:dark:focus-within:border-transparent',
EXPANDED_SHEET_FILL
],
systemMode && '!border-2 !border-dashed !border-border/50 !bg-muted',
// a dashed outline stands in for the card's edge, drawn inside it: the card keeps its size
systemMode &&
'!bg-muted !outline-2 -outline-offset-2 !outline-dashed !outline-border/50 [--glass-edge-focus:transparent] [--glass-edge:transparent]',
disabled && 'cursor-not-allowed opacity-60'
]}
data-single-row={isSingleRow || undefined}
@ -920,7 +954,7 @@
? pickers.handleWorkingDirectoryOpen
: undefined}
{showAddButton}
{showModelSelector}
showModelSelector={isModelSelectorShown}
voice={{
action: voice.label,
hint: voice.hint,
@ -952,15 +986,21 @@
></div>
{/if}
<div class="flex flex-wrap items-center gap-x-1 self-start">
<!-- The chips sit under the card. On a new chat, where the page centres the form, they
hang below it and take no room: the card stays where it is as they come and go -->
<div
class="flex flex-wrap items-center gap-x-1 self-start md:group-data-[chat-form-lifted]/chat-form-host:absolute md:group-data-[chat-form-lifted]/chat-form-host:top-full"
>
{#if showWorkingDirectory}
<!-- opened from the chip, the + menu, a phone chat's header or `/cwd` -->
<ChatFormCurrentWorkingDirectory
bind:query={pickers.workingDirectoryQuery}
bind:this={workingDirectoryRef}
class="self-start"
customAnchor={activePickerAnchor}
directory={cwd}
{disabled}
inline={pickers.isWorkingDirectoryInline}
isOpen={pickers.isWorkingDirectoryPickerOpen}
onChange={handleWorkingDirectoryChange}
onClose={pickers.handleWorkingDirectoryClose}

View file

@ -8,20 +8,23 @@
import {
CHAT_FORM_CHIP_SPLIT,
CHAT_FORM_CHIP_TRANSITION_MS,
CHAT_FORM_PATH_PICKER_WIDTH_CLASS,
DEFAULT_MOBILE_BREAKPOINT,
HOME_TILDE,
SEARCH,
UI_DATA_ATTRS
} from '#lib/constants/index.ts';
import { BuiltInTool, GlobSearchType, KeyboardKey, ToolSource } from '#lib/enums/index.ts';
import { BuiltInTool, KeyboardKey, ToolSource } from '#lib/enums/index.ts';
import { useDebouncedSearch } from '#lib/hooks/use-debounced-search.svelte.ts';
import { usePickerNavigation } from '#lib/hooks/use-picker-navigation.svelte.ts';
import { useScrollActiveRow } from '#lib/hooks/use-scroll-active-row.svelte.ts';
import { ToolsService } from '#lib/services/tools.service.ts';
import { conversationsStore, deviceStore, toolsStore } from '#lib/stores/index.ts';
import type { GlobSearchChildResult } from '#lib/types/glob.js';
import {
abbreviateHome,
runGlobSearchWithChildren,
isIMEComposing,
runFolderSearch,
toHomeRelativeQuery
} from '#lib/utils/index.ts';
import { page } from '$app/state';
@ -37,6 +40,9 @@
/** Controlled open state; the host owns it so the chip, the + menu and the
* `/cwd` slash command open the picker through the same path. */
isOpen: boolean;
/** The path is typed on the chat input's `/cwd` line: no search field of its own, and
* the host forwards the input's keys through `handleKeydown`. */
inline?: boolean;
/** Two-way bound query, kept in sync with the text after `/cwd `. */
query: string;
/** Anchor at the form's top edge so the popover floats above the box. */
@ -55,6 +61,7 @@
customAnchor = null,
directory = null,
disabled = false,
inline = false,
isOpen,
onChange,
onClose,
@ -109,7 +116,7 @@
// HTML `autofocus` is unreliable on dynamically shown elements.
$effect(() => {
if (!isOpen) return;
if (!isOpen || inline) return;
setTimeout(() => searchInputRef?.focus(), FOCUS_DELAY_MS);
});
@ -160,32 +167,14 @@
return;
}
try {
// Generous limit: ranking is client-side, only the top
// MAX_RESULTS_SHOWN are shown.
// A plain query navigates home as if typed after `~/`; a query
// starting from a root or `~` navigates the absolute tree.
const res = await runGlobSearchWithChildren(
toHomeRelativeQuery(trimmed, homeBase),
homeBase ?? HOME_TILDE,
SEARCH.MAX_DEPTH,
SEARCH.LIMIT,
signal,
{ type: GlobSearchType.DIR }
);
// Every round of results starts with its first folder highlighted. A stale
// search must not touch the list: the next one is already running.
const show = (res: GlobSearchChildResult) => {
if (!isCurrent()) return;
if (res.error) {
queryResults = [];
nav.reset(-1);
searchError = res.error;
return;
}
searchScope = res.exactDir ?? res.args.path;
queryResults = res.entries.map((e) => e.path).slice(0, SEARCH.MAX_RESULTS_SHOWN);
searchError = res.error ?? null;
if (queryResults.length > 0) {
nav.reset(0);
@ -193,8 +182,10 @@
} else {
nav.reset(-1);
}
};
searchError = null;
try {
show(await runFolderSearch(trimmed, homeBase, signal, show));
} catch (err) {
if (!isCurrent() || signal.aborted) return;
@ -261,25 +252,60 @@
closePicker();
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === KeyboardKey.ENTER) {
/** True when the key was the picker's: the chat input then leaves it alone. */
function handlePickerKeydown(event: KeyboardEvent): boolean {
// a key that confirms or moves within an IME composition belongs to the text
if (isIMEComposing(event)) return false;
// Enter picks a suggestion, never the typed text: before the results arrive it does
// nothing. Only without file search, where nothing is suggested, does it take the path
// as typed
if (event.key === KeyboardKey.ENTER && !event.shiftKey) {
event.preventDefault();
if (nav.hoveredIndex >= 0 && queryResults[nav.hoveredIndex]) {
commit(queryResults[nav.hoveredIndex]);
} else if (queryResults.length === 0) {
} else if (!fileSearchEnabled) {
handleSubmit();
}
} else if (event.key === KeyboardKey.ARROW_DOWN) {
if (queryResults.length > 0) {
event.preventDefault();
nav.move(1);
}
} else if (event.key === KeyboardKey.ARROW_UP) {
if (queryResults.length > 0) {
event.preventDefault();
nav.move(-1);
}
return true;
}
if (
(event.key === KeyboardKey.ARROW_DOWN || event.key === KeyboardKey.ARROW_UP) &&
queryResults.length > 0
) {
event.preventDefault();
nav.move(event.key === KeyboardKey.ARROW_DOWN ? 1 : -1);
return true;
}
if (inline && event.key === KeyboardKey.ESCAPE) {
event.preventDefault();
closePicker();
return true;
}
return false;
}
/** The chat input's keys while the path is typed on its `/cwd` line. */
export function handleKeydown(event: KeyboardEvent): boolean {
if (!isOpen || !inline) return false;
return handlePickerKeydown(event);
}
// Inline, the chat input is the picker's field: pressing in the form (to move the caret,
// say) keeps the picker open
function handleInteractOutside(event: PointerEvent) {
const target = event.target;
if (inline && target instanceof Node && customAnchor?.closest('form')?.contains(target)) {
event.preventDefault();
}
}
@ -380,14 +406,27 @@
<!-- the drawer's version is roomier: the header's inset, rows spaced for a finger and
lined up with the search results, and text sized for a phone -->
{#snippet picker(inDrawer: boolean)}
<div class={inDrawer ? 'flex flex-col gap-1 px-4' : 'p-2 min-h-22 flex flex-col justify-between'}>
<SearchInput
bind:ref={searchInputRef}
bind:value={query}
class="w-full"
onClose={closePicker}
placeholder="Choose working directory"
/>
<!-- inline there is no search field to keep room for, only the rows below the line -->
<div
class={inDrawer
? 'flex flex-col gap-1 px-4'
: ['flex flex-col justify-between p-2', !inline && 'min-h-22']}
>
{#if inline}
{#if fileSearchEnabled && !query.trim()}
<div class="px-2 py-1.5 text-body-sm text-muted-foreground">
Type a folder name or path after <span class="font-mono">/cwd</span>
</div>
{/if}
{:else}
<SearchInput
bind:ref={searchInputRef}
bind:value={query}
class="w-full"
onClose={closePicker}
placeholder="Choose working directory"
/>
{/if}
{#if !fileSearchEnabled}
<div class="px-2 py-1.5 text-body-sm text-muted-foreground">{searchUnavailableMessage}</div>
@ -460,7 +499,7 @@
<!-- a phone picks in a drawer from the screen's bottom; elsewhere a popover above the form -->
{#if deviceStore.isMobile}
<Drawer.Root onOpenChange={handleOpenChange} open={isOpen}>
<Drawer.Content class="gap-0" onkeydown={handleKeydown}>
<Drawer.Content class="gap-0" onkeydown={handlePickerKeydown}>
<Drawer.Header>
<Drawer.Title>Working directory</Drawer.Title>
@ -484,16 +523,20 @@
<span class="sr-only">Open working directory picker</span>
</Popover.Trigger>
<!-- inline, the focus stays in the chat input, where the path is typed: a trap would
pull it into the list as the + menu closes -->
<Popover.Content
align="start"
class="w-[var(--bits-popover-anchor-width)] max-w-none rounded-xl p-0"
class={[CHAT_FORM_PATH_PICKER_WIDTH_CLASS, 'rounded-xl p-0']}
{customAnchor}
onCloseAutoFocus={(event) => event.preventDefault()}
onInteractOutside={handleInteractOutside}
onOpenAutoFocus={(event) => event.preventDefault()}
onkeydown={handleKeydown}
onkeydown={handlePickerKeydown}
preventScroll={false}
side="top"
sideOffset={12}
trapFocus={!inline}
>
{@render picker(false)}
</Popover.Content>

View file

@ -2,7 +2,7 @@
import { cn } from '@ggml-org/llama-ui/utils';
import { Folder } from '@lucide/svelte';
import { UI_DATA_ATTRS } from '#lib/constants/index.ts';
import { highlightMatch } from '#lib/utils/index.ts';
import { hasPointerMoved, highlightMatch } from '#lib/utils/index.ts';
import { fly } from 'svelte/transition';
// Fly-in transition for the results list.
@ -53,7 +53,9 @@
)}
data-highlighted={index === hoveredIndex ? '' : undefined}
onclick={() => onCommit?.(path)}
onmouseenter={() => onHover?.(index)}
onmousemove={(event) => {
if (hasPointerMoved(event)) onHover?.(index);
}}
>
<Folder class="size-4 shrink-0 text-muted-foreground" />

View file

@ -1,12 +1,14 @@
<script lang="ts">
import { UI_DATA_ATTRS } from '#lib/constants/index.ts';
import { hasPointerMoved } from '#lib/utils/index.ts';
import type { Snippet } from 'svelte';
interface Props {
isSelected?: boolean;
disabled?: boolean;
onclick: () => void;
onmouseenter?: () => void;
/** Called when the user moves the pointer over the row, not when the row renders under it. */
onhover?: () => void;
dataIndex?: number;
children: Snippet;
class?: string;
@ -19,14 +21,16 @@
disabled = false,
isSelected = false,
onclick,
onmouseenter
onhover
}: Props = $props();
</script>
<button
{disabled}
{onclick}
{onmouseenter}
onmousemove={(event) => {
if (hasPointerMoved(event)) onhover?.();
}}
type="button"
{...{ [UI_DATA_ATTRS.PICKER_INDEX]: dataIndex }}
class="flex w-full cursor-pointer items-start gap-3 rounded-lg px-3 py-2 text-left hover:bg-accent/50 {isSelected

View file

@ -1,5 +1,6 @@
<script lang="ts">
import * as Popover from '@ggml-org/llama-ui/ui/popover';
import { CHAT_FORM_PICKER_WIDTH_CLASS } from '#lib/constants/index.ts';
import type { Snippet } from 'svelte';
interface Props {
@ -42,7 +43,7 @@
<Popover.Content
align="start"
class="w-[var(--bits-popover-anchor-width)] max-w-none rounded-xl p-0 {className}"
class={[CHAT_FORM_PICKER_WIDTH_CLASS, 'rounded-xl p-0', className]}
{customAnchor}
onOpenAutoFocus={(event) => event.preventDefault()}
onkeydown={onKeydown}

View file

@ -4,7 +4,6 @@
ChatFormPickerListItem,
ChatFormPickerPopover
} from '#lib/components/app/chat/index.ts';
import { CHAT_FORM_COMMAND_ICONS } from '#lib/constants/index.ts';
import { usePickerNavigation } from '#lib/hooks/use-picker-navigation.svelte.ts';
import type { ChatFormCommand } from '#lib/types/index.ts';
@ -121,18 +120,15 @@
showSearchInput={false}
>
{#snippet item(command, index, isSelected)}
{@const Icon = CHAT_FORM_COMMAND_ICONS[command.action]}
<ChatFormPickerListItem
dataIndex={index}
disabled={command.disabled}
{isSelected}
onclick={() => handleSelect(command)}
onmouseenter={() => {
onhover={() => {
if (!command.disabled) nav.setHover(index);
}}
>
<Icon class="mt-0.5 size-icon-md shrink-0 text-muted-foreground" />
<div class="flex min-w-0 flex-1 flex-col">
<span class="font-mono text-label">/{command.name}</span>

View file

@ -4,7 +4,12 @@
import { File, Folder } from '@lucide/svelte';
import { ChatFormPickerList, ChatFormPickerListItem } from '#lib/components/app/chat/index.ts';
import HighlightedMatch from '#lib/components/app/forms/HighlightedMatch.svelte';
import { FILE_GLOB_SEARCH_PICKERS, HOME_TILDE, SEARCH } from '#lib/constants/index.ts';
import {
CHAT_FORM_PATH_PICKER_WIDTH_CLASS,
FILE_GLOB_SEARCH_PICKERS,
HOME_TILDE,
SEARCH
} from '#lib/constants/index.ts';
import {
BuiltInTool,
FileMentionEntryType,
@ -216,7 +221,7 @@
<Popover.Content
align="start"
class={['w-[var(--bits-popover-anchor-width)] max-w-none rounded-xl p-0', className]}
class={[CHAT_FORM_PATH_PICKER_WIDTH_CLASS, 'rounded-xl p-0', className]}
{customAnchor}
onCloseAutoFocus={(event) => event.preventDefault()}
onOpenAutoFocus={(event) => event.preventDefault()}
@ -240,7 +245,7 @@
dataIndex={index}
{isSelected}
onclick={() => handleSelect(entry)}
onmouseenter={() => nav.setHover(index)}
onhover={() => nav.setHover(index)}
>
{@const Icon = entry.type === FileMentionEntryType.DIRECTORY ? Folder : File}
<Icon

View file

@ -258,10 +258,6 @@
}
}
async function handleSystemPromptAdd(draft: { message: string; files: ChatUploadedFile[] }) {
await chatStore.addSystemPrompt(draft);
}
$effect(() => {
stick.setEnabled(!settingsStore.config.disableAutoScroll);
});
@ -337,7 +333,7 @@
class={[
// moves between the centered and bottom positions with a fade (see moveForm), at
// the same height in the page, so the messages never shift
'pointer-events-none md:sticky fixed mt-auto max-md:z-10',
'group/chat-form-host pointer-events-none md:sticky fixed mt-auto max-md:z-10',
// a phone holds it in place on screen while the page is slid aside
deviceStore.isMobile && 'sidebar-reveal-pin-bottom',
// on a phone the expanded form is a sheet: flush with the screen's sides and bottom
@ -358,6 +354,7 @@
!isFormMoving &&
'transition-[left,right,bottom] duration-400 ease-[var(--chat-form-resize-ease,cubic-bezier(0.3,1.12,0.5,1))] max-md:transition-none motion-reduce:transition-none'
]}
data-chat-form-lifted={isFormLifted || undefined}
>
<ChatScreenGreeting
faded={uiStore.isComposerExpanded}
@ -387,7 +384,6 @@
onFileUpload={fileUpload.handleFileUpload}
onSend={handleSendMessage}
onStop={() => chatStore.stopGeneration()}
onSystemPromptAdd={handleSystemPromptAdd}
/>
</div>
</div>

View file

@ -17,7 +17,6 @@
onFileUpload?: (files: File[]) => void;
onSend?: (message: string, files?: ChatUploadedFile[]) => Promise<boolean>;
onStop?: () => void;
onSystemPromptAdd?: (draft: { message: string; files: ChatUploadedFile[] }) => void;
uploadedFiles?: ChatUploadedFile[];
}
@ -29,7 +28,6 @@
onFileUpload,
onSend,
onStop,
onSystemPromptAdd,
uploadedFiles = $bindable([])
}: Props = $props();
@ -111,16 +109,10 @@
}
}
// With system messages hidden in the conversation there is nothing to edit in place, so the
// form itself turns into the system message editor
// The form itself turns into the system message editor, whether or not the conversation
// shows its system message
function handleSystemPromptClick() {
if (settingsStore.config[SETTINGS_KEYS.SHOW_SYSTEM_MESSAGE] ?? true) {
onSystemPromptAdd?.({ files: uploadedFiles, message });
return;
}
const existing = conversationsStore.activeMessages.find((m) => m.role === MessageRole.SYSTEM);
stashedDraft = { files: uploadedFiles, message };

View file

@ -2,6 +2,23 @@ export const INITIAL_FILE_SIZE = 0;
export const PROMPT_CONTENT_SEPARATOR = '\n\n';
export const CLIPBOARD_CONTENT_QUOTE_PREFIX = '"';
export const PROMPT_TRIGGER_PREFIX = '/';
/** The slash command that sets the working directory, typed as `/cwd <path>`. */
export const CWD_COMMAND_NAME = 'cwd';
/** A command's name after the `/`: letters, digits and dashes (`system-message`). */
export const COMMAND_NAME_REGEX = /^[\w-]*$/;
/** Where a working directory is typed, anywhere in the input: `/cwd <path>`. */
export const CWD_COMMAND_PREFIX = `${PROMPT_TRIGGER_PREFIX}${CWD_COMMAND_NAME} `;
/**
* The command picker fits its suggestions: as wide as the longest one, between a floor
* that keeps short lists readable and a cap no wider than the form.
*/
export const CHAT_FORM_PICKER_WIDTH_CLASS =
'w-max min-w-64 max-w-[min(36rem,var(--bits-popover-anchor-width))]';
/**
* The pickers that list paths (`@` mentions, `/cwd`) keep one width, so the list does not
* resize as the results change with every keystroke.
*/
export const CHAT_FORM_PATH_PICKER_WIDTH_CLASS = 'w-[min(36rem,var(--bits-popover-anchor-width))]';
export const NEW_CHAT_DRAFT_KEY = '__new_chat__';
/** Lines of text from which the main chat form expands into its large editor. */
export const CHAT_FORM_EXPAND_MIN_LINES = 4;

View file

@ -11,8 +11,6 @@ import FileIcon from '@lucide/svelte/icons/file';
// not a microphone: that one is for recording and dictation
import AudioIcon from '@lucide/svelte/icons/file-headphone';
import FileTextIcon from '@lucide/svelte/icons/file-text';
import CompactCommandIcon from '@lucide/svelte/icons/fold-vertical';
import CwdCommandIcon from '@lucide/svelte/icons/folder-open';
import ImageIcon from '@lucide/svelte/icons/image';
import LoadingIcon from '@lucide/svelte/icons/loader-2';
import ModelIcon from '@lucide/svelte/icons/package';
@ -20,12 +18,10 @@ import PauseDownloadIcon from '@lucide/svelte/icons/pause';
import ResumeDownloadIcon from '@lucide/svelte/icons/play';
import LoadIcon from '@lucide/svelte/icons/power';
import RetryIcon from '@lucide/svelte/icons/rotate-cw';
import PromptCommandIcon from '@lucide/svelte/icons/sparkles';
import VideoIcon from '@lucide/svelte/icons/video';
import CancelLoadIcon from '@lucide/svelte/icons/x';
import { ChatFormCommandAction, FileTypeCategory, ModelCapability } from '#lib/enums/index.ts';
import { FileTypeCategory, ModelCapability } from '#lib/enums/index.ts';
import type { ModelCapabilities } from '#lib/types/models.js';
import type { Component } from 'svelte';
export {
CAPABILITY_ICONS,
CAPABILITY_LABELS,
@ -65,14 +61,6 @@ export const CAPABILITY_FLAG_KEYS: Record<ModelCapability, keyof ModelCapabiliti
[ModelCapability.TOOL_USE]: 'tools'
};
/** Icons of the slash-command picker, one per chat-form command. */
export const CHAT_FORM_COMMAND_ICONS: Record<ChatFormCommandAction, Component> = {
[ChatFormCommandAction.COMPACT]: CompactCommandIcon,
[ChatFormCommandAction.CWD]: CwdCommandIcon,
[ChatFormCommandAction.MODEL]: MODEL_ICON,
[ChatFormCommandAction.PROMPT]: PromptCommandIcon
};
/** Icons of the download control a manager row shows while it downloads. */
export const MODEL_DOWNLOAD_ICONS = {
pause: PauseDownloadIcon,

View file

@ -9,6 +9,9 @@
/** Label shown for the working-directory picker / `/cwd` slash command. */
export const SET_WORKING_DIRECTORY_LABEL = 'Set working directory';
/** Prefix of a hidden file or folder name (`.git`, `.config`). */
export const HIDDEN_NAME_PREFIX = '.';
export const GLOB = {
/** `C:`, the drive part of a Windows absolute path. */
DRIVE_PREFIX_REGEX: /^[A-Za-z]:/,
@ -31,15 +34,28 @@ export const GLOB = {
export const SEARCH = {
// Search tuning for the picker's file_glob_search calls.
DEBOUNCE_MS: 180,
// A typo-tolerant search runs only when the exact one finds nothing. Past
// the shallow walk it goes less deep than the exact search, as it sends one
// glob per pair of neighbouring query characters.
FUZZY_MAX_DEPTH: 3,
// One wrong, missing, extra or swapped character still matches.
FUZZY_MAX_EDITS: 1,
// Longer queries would send too many globs for the typo-tolerant search.
FUZZY_MAX_QUERY_LENGTH: 16,
// Shorter queries are too loose to tell a typo from another name.
FUZZY_MIN_QUERY_LENGTH: 4,
LIMIT: 100,
// Home-relative globs descend deeper than path navigation, which only
// needs the direct children of the parent.
MAX_DEPTH: 6,
// A plain name is searched anywhere under home down to this depth; path
// navigation only needs the direct children of the parent.
MAX_DEPTH: 4,
MAX_RESULTS_SHOWN: 20,
NATIVE_LIMIT: 20,
// Native folder-picker resolution searches a shallow, bounded window.
NATIVE_MAX_DEPTH: 4,
PATH_NAV_MAX_DEPTH: 1
PATH_NAV_MAX_DEPTH: 1,
// A plain name is searched this deep first: the walk is fast, and the
// server's result cap cannot crowd the nearest folders out of it.
SHALLOW_DEPTH: 2
} as const;
export const FILE_GLOB_SEARCH_PICKERS = {

View file

@ -84,7 +84,8 @@ export enum ChatFormCommandAction {
COMPACT = 'compact',
CWD = 'cwd',
MODEL = 'model',
PROMPT = 'prompt'
PROMPT = 'prompt',
SYSTEM_MESSAGE = 'system-message'
}
export enum FileMentionEntryType {

View file

@ -1,12 +1,19 @@
import { PROMPT_TRIGGER_PREFIX } from '#lib/constants/index.ts';
import { CWD_COMMAND_NAME } from '#lib/constants/index.ts';
import { ChatFormCommandAction, KeyboardKey } from '#lib/enums/index.ts';
import type { ChatFormCommand } from '#lib/types/index.ts';
import { getChatCommands } from '#lib/utils/index.ts';
import {
abbreviateHome,
type CommandDismissSnapshot,
type CommandToken,
findCommandToken,
findMentionToken,
getChatCommands,
insertCwdCommand,
isCommandDismissed,
locateCwdCommand,
type MentionDismissSnapshot,
removeCommandToken,
replaceWithCwdCommand,
takeCommandDismissSnapshot,
takeMentionDismissSnapshot
} from '#lib/utils/index.ts';
@ -22,6 +29,11 @@ export interface UseChatFormPickersOptions {
focusInput: () => void;
/** Whether typing `/` or `@` opens a picker at all. */
opensOnInput: () => boolean;
/**
* Whether the working directory is typed in the chat input, after a `/cwd` command
* wherever it is in the message, instead of in the picker's own search field.
*/
editsCwdInline: () => boolean;
/** Gates `/model`. */
getShowModelSelector: () => boolean;
/** Gates `/prompt`. */
@ -32,6 +44,10 @@ export interface UseChatFormPickersOptions {
canCompact: () => boolean;
/** Runs `/compact`. */
onCompact: () => void;
/** Gates `/system-message`. */
canEditSystemMessage: () => boolean;
/** Runs `/system-message`: the form turns into the system message editor. */
onSystemMessage: () => void;
getCwd: () => string | null;
/** Mention search fallback scope. */
getServerHome: () => string | null;
@ -54,11 +70,18 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
let mentionQuery = $state('');
let isWorkingDirectoryPickerOpen = $state(false);
let workingDirectoryQuery = $state('');
// The open picker searches the `/cwd` command in the chat input, not a field of its own.
// Set on every open and kept after a close, so the picker fades out the way it looked
let isWorkingDirectoryInline = $state(false);
// Last dismissed `@`-mention token; while intact, the picker does not
// reopen, so an escaped `@<query>` stays literal until edited.
let mentionDismissedSnapshot: MentionDismissSnapshot | null = null;
// Same dismissal contract for the `/`-command token.
let commandDismissedSnapshot: CommandDismissSnapshot | null = null;
// Where the open working directory picker's `/cwd` command is, its path as last typed,
// and the input's length then: an edit elsewhere in the message moves it by the
// change in length if it was made before it
let cwdCommand: { start: number; query: string; length: number } | null = null;
// Fall back to the server home so the picker still finds matches
// before a cwd is set.
@ -66,55 +89,93 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
const availableCommands = $derived(
getChatCommands({
canCompact: opts.canCompact,
canEditSystemMessage: opts.canEditSystemMessage,
hasCwdTools: opts.hasCwdTools,
hasPrompts: opts.hasPrompts,
showModelSelector: opts.getShowModelSelector()
})
);
// only the commands that take an argument read the words after them
const commandNames = $derived(
availableCommands.filter((command) => command.takesArgument).map((command) => command.name)
);
const caretOf = (value: string) => opts.getCaretOffset() ?? value.length;
const commandAt = (value: string) => findCommandToken(value, caretOf(value), commandNames);
// Dispatch a slash command picked from the list: consume the token and
// open the target picker, seeding its search with `args`. Runs only on
// explicit selection (Enter/click), so the buffer is never cleared
// mid-typing.
function dispatchCommand(command: ChatFormCommand, args: string) {
/** The open picker's `/cwd` command where it now is, or null when it was edited away. */
function currentCwdCommand(value = opts.getValue()) {
if (!cwdCommand) return null;
const { length, query, start } = cwdCommand;
const shift = value.length - length;
const caret = opts.getCaretOffset();
// an edit made before the command leaves the caret before it too
const isEditBefore = caret === undefined || caret <= start + shift;
return locateCwdCommand(value, start, query, isEditBefore ? shift : 0);
}
function trackCwdCommand(start: number, query: string, value: string) {
cwdCommand = { length: value.length, query, start };
}
function setValueAndCaret(value: string, caret: number) {
if (opts.getValue() !== value) opts.setValue(value);
queueMicrotask(() => opts.setCaretOffset(caret));
}
/** Takes the command out of the message, leaving the words around it. */
function consumeCommand(token: { start: number; end: number }) {
const next = removeCommandToken(opts.getValue(), token);
setValueAndCaret(next.value, next.caret);
}
// Dispatch a slash command picked from the list, wherever it is in the message: take the
// token out and open the target picker, seeding its search with `args`. Runs only on
// explicit selection (Enter/click), so nothing is cleared mid-typing.
function dispatchCommand(command: ChatFormCommand, token: CommandToken) {
isCommandPickerOpen = false;
commandQuery = '';
if (command.action !== ChatFormCommandAction.CWD) {
isWorkingDirectoryPickerOpen = false;
cwdCommand = null;
consumeCommand(token);
}
switch (command.action) {
case ChatFormCommandAction.COMPACT:
isWorkingDirectoryPickerOpen = false;
opts.setValue('');
opts.onCompact();
break;
case ChatFormCommandAction.PROMPT:
isWorkingDirectoryPickerOpen = false;
opts.setValue('');
isPromptPickerOpen = true;
promptSearchQuery = args.trim();
promptSearchQuery = token.args.trim();
break;
case ChatFormCommandAction.CWD: {
// Keep `/cwd <args>` in the input so the search field and the
// token stay two-way bound; normalize partial tokens (`/cw foo`).
const trimmed = args.trim();
const newValue = `/cwd ${trimmed}`;
// `/cwd <path>` stays where it was typed, the path two-way bound to the picker's
// search; a partial token (`/cw foo`) is completed
const query = token.args.trim();
const next = replaceWithCwdCommand(opts.getValue(), token, query);
if (opts.getValue() !== newValue) {
opts.setValue(newValue);
queueMicrotask(() => opts.setCaretOffset(newValue.length));
}
workingDirectoryQuery = trimmed;
isWorkingDirectoryInline = opts.editsCwdInline();
trackCwdCommand(next.start, query, next.value);
setValueAndCaret(next.value, next.caret);
workingDirectoryQuery = query;
isWorkingDirectoryPickerOpen = true;
break;
}
case ChatFormCommandAction.MODEL:
isWorkingDirectoryPickerOpen = false;
opts.setValue('');
opts.openModelSelector();
break;
case ChatFormCommandAction.SYSTEM_MESSAGE:
opts.onSystemMessage();
break;
}
}
@ -123,44 +184,43 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
if (!opts.opensOnInput()) return;
const value = opts.getValue();
const cursor = opts.getCaretOffset() ?? value.length;
const cursor = caretOf(value);
const command = commandAt(value);
if (value.startsWith(PROMPT_TRIGGER_PREFIX)) {
// While the `/cwd` picker is open the command doubles as its search field: keep the two
// in sync instead of re-dispatching. An edit elsewhere in the message leaves it open
if (isWorkingDirectoryPickerOpen && cwdCommand) {
isCommandPickerOpen = false;
commandQuery = '';
// the path as typed when the caret is in the command, not in another `/cwd` the
// message names
const tracked = currentCwdCommand(value);
const located =
tracked && command?.name === CWD_COMMAND_NAME && command.start === tracked.start
? { query: command.args, start: command.start }
: tracked;
if (located) {
trackCwdCommand(located.start, located.query, value);
workingDirectoryQuery = located.query.trim();
} else {
isWorkingDirectoryPickerOpen = false;
workingDirectoryQuery = '';
cwdCommand = null;
}
return;
}
if (command) {
isMentionPickerOpen = false;
mentionQuery = '';
isPromptPickerOpen = false;
promptSearchQuery = '';
const token = findCommandToken(value);
if (!token) {
isCommandPickerOpen = false;
commandQuery = '';
return;
}
// While the `/cwd` picker is open the token doubles as its search
// field: keep the two in sync instead of re-dispatching.
if (isWorkingDirectoryPickerOpen) {
isCommandPickerOpen = false;
commandQuery = '';
if (token.name === 'cwd') {
workingDirectoryQuery = token.args.trim();
} else {
isWorkingDirectoryPickerOpen = false;
workingDirectoryQuery = '';
}
return;
}
// Dismissed token stays literal until it changes.
const isDismissedSticky =
commandDismissedSnapshot !== null &&
commandDismissedSnapshot.name === token.name &&
commandDismissedSnapshot.args === token.args;
const isDismissedSticky = isCommandDismissed(commandDismissedSnapshot, command);
if (isDismissedSticky) {
isCommandPickerOpen = false;
@ -174,7 +234,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
// picks the command from the list.
if (availableCommands.length > 0) {
isCommandPickerOpen = true;
commandQuery = token.name;
commandQuery = command.name;
} else {
isCommandPickerOpen = false;
commandQuery = '';
@ -190,10 +250,6 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
commandDismissedSnapshot = null;
}
if (isWorkingDirectoryPickerOpen) {
isWorkingDirectoryPickerOpen = false;
}
const token = findMentionToken(value, cursor);
if (token) {
@ -246,16 +302,20 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
function handleCommandSelect(command: ChatFormCommand) {
// Dispatch on the live token so typed args seed the target picker.
const token = findCommandToken(opts.getValue());
const value = opts.getValue();
const caret = caretOf(value);
const token = commandAt(value) ?? { args: '', end: caret, name: '', start: caret };
dispatchCommand(command, token?.args ?? '');
dispatchCommand(command, token);
}
// Picker dismissed: snapshot the live token so it stays literal until
// deleted or retyped.
function handleCommandPickerClose() {
if (isCommandPickerOpen) {
commandDismissedSnapshot = takeCommandDismissSnapshot(opts.getValue());
const value = opts.getValue();
commandDismissedSnapshot = takeCommandDismissSnapshot(value, caretOf(value), commandNames);
}
isCommandPickerOpen = false;
@ -286,33 +346,77 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
opts.focusInput();
}
/** True while the caret is in the `/cwd` command, not in the message around it. */
function isCaretInCwdCommand(): boolean {
const located = currentCwdCommand();
const caret = opts.getCaretOffset();
return !located || caret === undefined || (caret >= located.start && caret <= located.end);
}
/** Takes the `/cwd` command out, leaving the message written around it. */
function consumeCwdCommand() {
const located = currentCwdCommand();
cwdCommand = null;
if (located) consumeCommand(located);
}
// Opened from the + menu or the chip. Inline, the current directory (or the path already
// after a `/cwd` command) goes on a `/cwd` command at the caret, to be edited there
function handleWorkingDirectoryOpen() {
workingDirectoryQuery = opts.getCwd() ?? '';
const cwd = opts.getCwd();
const seed = cwd ? abbreviateHome(cwd, opts.getServerHome()) : '';
isWorkingDirectoryInline = opts.editsCwdInline();
if (isWorkingDirectoryInline) {
const value = opts.getValue();
const located = currentCwdCommand(value);
if (located) {
trackCwdCommand(located.start, located.query, value);
workingDirectoryQuery = located.query.trim();
queueMicrotask(() => opts.setCaretOffset(located.end));
} else {
const next = insertCwdCommand(value, caretOf(value), seed);
trackCwdCommand(next.start, seed, next.value);
workingDirectoryQuery = seed;
setValueAndCaret(next.value, next.caret);
}
} else {
workingDirectoryQuery = seed;
}
isWorkingDirectoryPickerOpen = true;
}
// A closed picker leaves no `/cwd` command behind: committing a directory or dismissing
// the picker gives the message back as it was
function handleWorkingDirectoryClose() {
isWorkingDirectoryPickerOpen = false;
workingDirectoryQuery = '';
consumeCwdCommand();
opts.focusInput();
}
// Two-way bind the text after `/cwd ` and the picker search input; the
// reverse direction is handled by handleInput.
// Two-way bind the text after `/cwd ` and the picker's own search field; the reverse
// direction is handled by handleInput. Inline, the `/cwd` command is the only field
$effect(() => {
if (!isWorkingDirectoryPickerOpen) return;
const query = workingDirectoryQuery;
const value = opts.getValue();
const token = findCommandToken(value);
if (!isWorkingDirectoryPickerOpen || isWorkingDirectoryInline) return;
if (!token || token.name !== 'cwd') return;
const located = currentCwdCommand();
const newValue = `/cwd ${workingDirectoryQuery}`;
if (!located || located.query === query) return;
if (newValue === value) return;
const next = replaceWithCwdCommand(opts.getValue(), located, query);
opts.setValue(newValue);
queueMicrotask(() => opts.setCaretOffset(newValue.length));
trackCwdCommand(next.start, query, next.value);
opts.setValue(next.value);
});
return {
@ -329,6 +433,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
set commandQuery(v: string) {
commandQuery = v;
},
consumeCwdCommand,
dispatchCommand,
handleCommandPickerClose,
handleCommandSelect,
@ -339,6 +444,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
handlePromptPickerClose,
handleWorkingDirectoryClose,
handleWorkingDirectoryOpen,
isCaretInCwdCommand,
get isCommandPickerOpen() {
return isCommandPickerOpen;
},
@ -357,6 +463,9 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
set isPromptPickerOpen(v: boolean) {
isPromptPickerOpen = v;
},
get isWorkingDirectoryInline() {
return isWorkingDirectoryInline;
},
get isWorkingDirectoryPickerOpen() {
return isWorkingDirectoryPickerOpen;
},

View file

@ -48,6 +48,7 @@ class ToolsStore {
private _error = $state<string | null>(null);
private _loading = $state(false);
private _serverHome = $state<string | null | undefined>(undefined);
private _serverHomeRequest: Promise<string | null> | null = null;
private _serverTools = $state<OpenAIToolDefinition[]>([]);
private _toolsEndpointUnreachable = $state(false);
// server tools that resolve their paths against the working directory,
@ -434,27 +435,18 @@ class ToolsStore {
* directory picker's search scope and the `~` abbreviation of cwd
* displays. Returns null when tools are unavailable.
*/
async resolveServerHome(): Promise<string | null> {
if (this._serverHome !== undefined) return this._serverHome;
resolveServerHome(): Promise<string | null> {
if (this._serverHome !== undefined) return Promise.resolve(this._serverHome);
// a plain chat never calls the server's tools
if (!agenticMode.enabled) return null;
if (!agenticMode.enabled) return Promise.resolve(null);
try {
const res = await ToolsService.executeToolRaw(BuiltInTool.SERVER_FILE_GLOB_SEARCH, {
limit: 1,
max_depth: 1,
path: HOME_TILDE,
type: GlobSearchType.DIR
});
// callers at the same time (a send, the pickers) share one request
this._serverHomeRequest ??= this.requestServerHome().finally(() => {
this._serverHomeRequest = null;
});
this._serverHome = typeof res.base === 'string' ? res.base : null;
} catch {
// searches still work via a literal `~`, only `~` abbreviation degrades
this._serverHome = null;
}
return this._serverHome;
return this._serverHomeRequest;
}
setCategoryEnabled(source: ToolSource, enabled: boolean): void {
@ -707,6 +699,25 @@ class ToolsStore {
return buildReadMediaToolDefinition(vision, audio);
}
private async requestServerHome(): Promise<string | null> {
try {
const res = await ToolsService.executeToolRaw(BuiltInTool.SERVER_FILE_GLOB_SEARCH, {
limit: 1,
max_depth: 1,
path: HOME_TILDE,
type: GlobSearchType.DIR
});
this._serverHome = typeof res.base === 'string' ? res.base : null;
} catch {
// searches still work via a literal `~`, only `~` abbreviation degrades. Left
// unresolved, so the next caller asks again instead of keeping the failure
return null;
}
return this._serverHome;
}
private toolKey(source: ToolSource, name: string, serverId?: string): string {
switch (source) {
case ToolSource.MCP:

View file

@ -251,6 +251,8 @@ export interface ChatCommandsOptions {
hasPrompts: () => boolean;
/** Gates `/cwd`. */
hasCwdTools: () => boolean;
/** Gates `/system-message`. */
canEditSystemMessage: () => boolean;
}
/** Protocol-level verbs accepted by the realtime inference control endpoint. Mirrors `CONTROL_ACTION`. */
@ -263,6 +265,8 @@ export interface ChatFormCommand {
keywords?: string[];
action: ChatFormCommandAction;
disabled: boolean;
/** Takes an argument after a space (`/cwd ~/git`); the others end at their name. */
takesArgument?: boolean;
}
/**

View file

@ -1,4 +1,4 @@
import { SET_WORKING_DIRECTORY_LABEL } from '#lib/constants/index.ts';
import { CWD_COMMAND_NAME, SET_WORKING_DIRECTORY_LABEL } from '#lib/constants/index.ts';
import { ChatFormCommandAction } from '#lib/enums/index.ts';
import type { ChatCommandsOptions, ChatFormCommand } from '#lib/types/index.ts';
@ -16,14 +16,16 @@ export function getChatCommands(options: ChatCommandsOptions): ChatFormCommand[]
action: ChatFormCommandAction.PROMPT,
description: 'Insert an MCP prompt',
disabled: !options.hasPrompts(),
name: 'prompt'
name: 'prompt',
takesArgument: true
},
{
action: ChatFormCommandAction.CWD,
description: SET_WORKING_DIRECTORY_LABEL,
disabled: !options.hasCwdTools(),
keywords: ['current working directory'],
name: 'cwd'
name: CWD_COMMAND_NAME,
takesArgument: true
},
{
action: ChatFormCommandAction.MODEL,
@ -33,10 +35,17 @@ export function getChatCommands(options: ChatCommandsOptions): ChatFormCommand[]
},
{
action: ChatFormCommandAction.COMPACT,
description: 'Summarize the conversation to free up context',
description: 'Summarize to free up context',
disabled: !options.canCompact(),
keywords: ['summarize', 'context'],
name: 'compact'
},
{
action: ChatFormCommandAction.SYSTEM_MESSAGE,
description: 'Edit the system message',
disabled: !options.canEditSystemMessage(),
keywords: ['system prompt', 'instructions'],
name: 'system-message'
}
];
}

View file

@ -1,17 +1,118 @@
import {
COMMAND_NAME_REGEX,
CWD_COMMAND_PREFIX,
PROMPT_TRIGGER_PREFIX
} from '#lib/constants/index.ts';
const SPACE = ' ';
const WHITESPACE_REGEX = /\s/;
const COMMAND_NAME_PREFIX_REGEX = /^([\w-]+)/;
/** A slash command typed in the chat input: `/name`, and the argument after it. */
export interface CommandToken {
/** Offset of the `/`. */
start: number;
/** Offset just past the token. */
end: number;
name: string;
/** What follows the name and its space, e.g. the path of `/cwd ~/git`. */
args: string;
}
const isWhitespace = (char: string | undefined) => !!char && WHITESPACE_REGEX.test(char);
/** True when a command can start at `index`: the input's start, or right after whitespace. */
function startsCommand(value: string, index: number): boolean {
return value[index] === PROMPT_TRIGGER_PREFIX && (index === 0 || isWhitespace(value[index - 1]));
}
/** Where the text the caret is in begins: after a new line or two spaces in a row. */
function runStart(value: string, cursor: number): number {
let i = cursor;
while (i > 0) {
const char = value[i - 1];
if (isWhitespace(char) && char !== SPACE) break;
if (char === SPACE && value[i - 2] === SPACE) break;
i--;
}
return i;
}
/** Past the word the caret is in: the token never takes the text after it. */
function wordEnd(value: string, cursor: number): number {
let end = cursor;
while (end < value.length && !isWhitespace(value[end])) end++;
return end;
}
/**
* Slash-command token detection for the chat form. Valid only at offset 0.
* The slash command the caret is in, anywhere in the input: a `/` at the input's start or
* after whitespace, then the command's name, as in `fix this /cwd ~/git`.
*
* A command that takes an argument (one of `commands`, or the start of one's name) takes
* it after a space, single spaces included (`/cwd ~/My Documents`); like an `@` mention,
* two spaces or a new line end it. So a path in the argument (`/cwd /usr/lo`) is not taken
* for a command of its own, unless it names one. Any other command ends at its name: the
* words after `/model` are the message's. After the caret the token runs to the end of the
* word.
*/
export function findCommandToken(
value: string
): { name: string; args: string; end: number } | null {
if (!value.startsWith('/')) return null;
value: string,
cursor: number,
commands: readonly string[] = []
): CommandToken | null {
if (cursor < 0 || cursor > value.length) return null;
const rest = value.slice(1);
const spaceIdx = rest.search(/\s/);
const name = spaceIdx === -1 ? rest : rest.slice(0, spaceIdx);
const args = spaceIdx === -1 ? '' : rest.slice(spaceIdx + 1);
const end = wordEnd(value, cursor);
const from = runStart(value, cursor);
return { args, end: value.length, name };
// the word the caret is in, when it is a `/name`
let word: CommandToken | null = null;
for (let i = cursor - 1; i >= from && !isWhitespace(value[i]); i--) {
if (!startsCommand(value, i)) continue;
const name = value.slice(i + 1, end);
if (COMMAND_NAME_REGEX.test(name)) word = { args: '', end, name, start: i };
break;
}
// a command that takes an argument further back on the run, with the caret in it
let withArgs: CommandToken | null = null;
for (let i = cursor - 1; i >= from; i--) {
if (!startsCommand(value, i)) continue;
// a known command, or the start of one (`/cw docs` completes to `/cwd docs`)
const name = COMMAND_NAME_PREFIX_REGEX.exec(value.slice(i + PROMPT_TRIGGER_PREFIX.length))?.[1];
if (!name || value[i + PROMPT_TRIGGER_PREFIX.length + name.length] !== SPACE) continue;
if (!commands.some((command) => command.startsWith(name))) continue;
const argsStart = i + PROMPT_TRIGGER_PREFIX.length + name.length + SPACE.length;
if (argsStart > cursor) continue;
withArgs = { args: value.slice(argsStart, end), end, name, start: i };
break;
}
if (word && (!withArgs || commands.some((command) => command.startsWith(word.name)))) {
return word;
}
return withArgs ?? word;
}
/**
@ -20,14 +121,121 @@ export function findCommandToken(
* the picker does not re-open on in-token edits.
*/
export interface CommandDismissSnapshot {
start: number;
name: string;
args: string;
}
export function takeCommandDismissSnapshot(value: string): CommandDismissSnapshot | null {
const token = findCommandToken(value);
export function takeCommandDismissSnapshot(
value: string,
cursor: number,
commands: readonly string[] = []
): CommandDismissSnapshot | null {
const token = findCommandToken(value, cursor, commands);
if (!token) return null;
return { args: token.args, name: token.name };
return { args: token.args, name: token.name, start: token.start };
}
export function isCommandDismissed(
snapshot: CommandDismissSnapshot | null,
token: CommandToken
): boolean {
return (
!!snapshot &&
snapshot.start === token.start &&
snapshot.name === token.name &&
snapshot.args === token.args
);
}
/** The input with `[start, end)` taken out, and where the caret goes: where it was. */
export function removeCommandToken(
value: string,
token: { start: number; end: number }
): { value: string; caret: number } {
let before = value.slice(0, token.start);
let after = value.slice(token.end);
// one space is left where the token was, none at the start or end of a line
if ((!before || isWhitespace(before.at(-1))) && after.startsWith(SPACE)) {
after = after.slice(SPACE.length);
} else if (before.endsWith(SPACE) && (!after || isWhitespace(after[0]))) {
before = before.slice(0, -SPACE.length);
}
return { caret: before.length, value: before + after };
}
/** The input with `/cwd <query>` in `[start, end)`, and the offset past the query. */
export function replaceWithCwdCommand(
value: string,
token: { start: number; end: number },
query: string
): { value: string; start: number; caret: number } {
const text = `${CWD_COMMAND_PREFIX}${query}`;
return {
caret: token.start + text.length,
start: token.start,
value: value.slice(0, token.start) + text + value.slice(token.end)
};
}
/**
* The input with `/cwd <query>` written at `caret`, set apart from the words around it by
* a space, and where the command starts and the query ends.
*/
export function insertCwdCommand(
value: string,
caret: number,
query: string
): { value: string; start: number; caret: number } {
const before = value.slice(0, caret);
const after = value.slice(caret);
const lead = before && !isWhitespace(before.at(-1)) ? SPACE : '';
const trail = after && !isWhitespace(after[0]) ? SPACE : '';
const start = before.length + lead.length;
return replaceWithCwdCommand(before + lead + trail + after, { end: start, start }, query);
}
/**
* Finds the `/cwd` command again after an edit somewhere else: at `start` if the edit was
* after it, or moved by `shift` (the change in the input's length) if it was before. Its
* argument is `query` when the text still reads so, or else runs to two spaces or the end
* of the line. Null when the command is gone, even if the message names `/cwd` elsewhere.
*/
export function locateCwdCommand(
value: string,
start: number,
query: string,
shift = 0
): { start: number; end: number; query: string } | null {
const isCwdAt = (index: number) =>
startsCommand(value, index) &&
value.startsWith(CWD_COMMAND_PREFIX.trimEnd(), index) &&
(index + CWD_COMMAND_PREFIX.length - 1 === value.length ||
isWhitespace(value[index + CWD_COMMAND_PREFIX.length - 1]));
const found = [start, start + shift].find(isCwdAt);
if (found === undefined) return null;
const argsStart = Math.min(found + CWD_COMMAND_PREFIX.length, value.length);
if (value.startsWith(query, argsStart)) {
return { end: argsStart + query.length, query, start: found };
}
let end = argsStart;
while (
end < value.length &&
(!isWhitespace(value[end]) || (value[end] === SPACE && value[end + 1] !== SPACE))
) {
end++;
}
return { end, query: value.slice(argsStart, end).trimEnd(), start: found };
}

View file

@ -5,8 +5,24 @@
*/
import { lastPathSegment } from './path-display';
import { buildGlobSearchArgs, joinPath, rankEntries } from './working-directory';
import { GLOB, PATH_SEPARATOR, SEARCH } from '#lib/constants/index.ts';
import {
buildFuzzyGlobs,
buildGlobSearchArgs,
fuzzyDistance,
isHiddenPath,
joinPath,
rankEntries,
splitPathQuery,
toHomeRelativeQuery,
toScopeSeparators
} from './working-directory';
import {
GLOB,
HIDDEN_NAME_PREFIX,
HOME_TILDE,
PATH_SEPARATOR,
SEARCH
} from '#lib/constants/index.ts';
import { BuiltInTool, GlobSearchType } from '#lib/enums/index.ts';
import { ToolsService } from '#lib/services/tools.service.ts';
import type {
@ -78,6 +94,57 @@ export async function runGlobSearchWithChildren(
limit: number,
signal: AbortSignal,
options: GlobSearchChildOptions = {}
): Promise<GlobSearchChildResult> {
const search = (q: string) =>
searchWithChildren(q, scopePath, searchDepth, limit, signal, options);
query = toScopeSeparators(query, scopePath);
const pathQuery = splitPathQuery(query);
if (pathQuery) {
const direct = await search(query);
const canLookDeeper = !!pathQuery.last && searchDepth > SEARCH.PATH_NAV_MAX_DEPTH;
if (direct.error || direct.entries.length > 0 || !canLookDeeper) return direct;
// no such name in that folder (`~/llama.cpp`): look for it further down (`~/git/llama.cpp`)
const deep = await runGlobSearch(
{ ...direct.args, maxDepth: searchDepth },
options.type ?? GlobSearchType.ALL,
limit,
signal
);
if (deep.error) return direct;
const ranked = rankEntries(deep.entries, direct.args.rankQuery);
return { ...direct, base: deep.base, entries: ranked.map((e) => toEntryResult(e, deep.base)) };
}
if (!query.includes(PATH_SEPARATOR)) return search(query);
// A relative path (`ui/lib/voi`) is also followed from the scope itself: the
// server's glob matches it only below some other folder, never at the top.
const [direct, deep] = await Promise.all([search(joinPath(scopePath, query)), search(query)]);
// nothing found directly: the deep search speaks, its error included
if (direct.error || (direct.entries.length === 0 && deep.error)) return deep;
const directPaths = new Set(direct.entries.map((entry) => entry.path));
const below = deep.entries.filter((entry) => !directPaths.has(entry.path));
return { ...direct, entries: [...direct.entries, ...below] };
}
async function searchWithChildren(
query: string,
scopePath: string,
searchDepth: number,
limit: number,
signal: AbortSignal,
options: GlobSearchChildOptions
): Promise<GlobSearchChildResult> {
const {
childMaxDepth = SEARCH.PATH_NAV_MAX_DEPTH,
@ -90,35 +157,182 @@ export async function runGlobSearchWithChildren(
if (res.error) return { args, base: res.base, entries: [], error: res.error };
const ranked = rankEntries(res.entries, args.rankQuery);
const entries = ranked.map((e) => toEntryResult(e, res.base));
const last = args.last;
const result = { args, base: res.base, entries: ranked.map((e) => toEntryResult(e, res.base)) };
const wantsDescend = descendOnTrailingSeparator
? query.endsWith(PATH_SEPARATOR) || query.endsWith(GLOB.WINDOWS_SEPARATOR)
: true;
if (last) {
const wantsDescend = descendOnTrailingSeparator
? query.endsWith(PATH_SEPARATOR) || query.endsWith(GLOB.WINDOWS_SEPARATOR)
: true;
const exact = ranked.find(
(e) => e.type === 'dir' && lastPathSegment(e.path).toLowerCase() === last.toLowerCase()
if (!args.last || !wantsDescend) return result;
return withExactDirChildren(result, ranked, args.last, type, limit, childMaxDepth, signal);
}
/** Append the children of the directory named exactly `name`, when the results hold one. */
async function withExactDirChildren(
result: GlobSearchChildResult,
ranked: GlobEntry[],
name: string,
type: GlobSearchType,
limit: number,
childMaxDepth: number,
signal: AbortSignal
): Promise<GlobSearchChildResult> {
const exact = ranked.find(
(e) => e.type === 'dir' && lastPathSegment(e.path).toLowerCase() === name.toLowerCase()
);
if (!exact) return result;
const exactDir = joinPath(result.base, exact.path);
const childRes = await runGlobSearch(
{ include: GLOB.WILDCARD, maxDepth: childMaxDepth, path: exactDir, rankQuery: '' },
type,
limit,
signal
);
if (childRes.error) return result;
// alphabetical, with hidden entries after the regular ones
const children = childRes.entries
.map((e) => toEntryResult(e, childRes.base))
.sort(
(a, b) =>
Number(isHiddenPath(a.name)) - Number(isHiddenPath(b.name)) || a.path.localeCompare(b.path)
);
if (wantsDescend && exact) {
const exactDir = joinPath(res.base, exact.path);
const childRes = await runGlobSearch(
{ include: GLOB.WILDCARD, maxDepth: childMaxDepth, path: exactDir, rankQuery: '' },
type,
limit,
signal
);
return { ...result, entries: [...result.entries, ...children], exactDir };
}
if (!childRes.error) {
const children = childRes.entries
.map((e) => toEntryResult(e, childRes.base))
.sort((a, b) => a.path.localeCompare(b.path));
/**
* Folders within a typo of the query's name, for when the exact search finds
* nothing. The depths are walked in turn, nearest first, and the walk stops at
* the first one that finds something: every glob is a walk of its own on the
* server, and its result cap could crowd the nearest folders out of a deeper one.
*/
async function runFuzzyFolderSearch(
args: GlobSearchArgs,
depths: number[],
signal: AbortSignal
): Promise<GlobSearchChildResult> {
const globs = buildFuzzyGlobs(args.rankQuery);
const close = new Map<string, GlobEntry>();
return { args, base: res.base, entries: [...entries, ...children], exactDir };
let base = '';
let error: string | undefined;
for (const maxDepth of depths) {
const results = await Promise.all(
globs.map((include) =>
runGlobSearch({ ...args, include, maxDepth }, GlobSearchType.DIR, SEARCH.LIMIT, signal)
)
);
base = results.find((res) => !res.error)?.base ?? base;
// a walk whose every glob failed reports why, rather than finding nothing
error = results.every((res) => res.error) ? results[0]?.error : undefined;
if (error) break;
for (const entry of results.flatMap((res) => res.entries)) {
if (fuzzyDistance(lastPathSegment(entry.path), args.rankQuery) <= SEARCH.FUZZY_MAX_EDITS) {
close.set(entry.path, entry);
}
}
if (close.size > 0) break;
}
return { args, base: res.base, entries };
if (error && close.size === 0) return { args, base, entries: [], error };
const entries = rankEntries([...close.values()], args.rankQuery);
return { args, base, entries: entries.map((e) => toEntryResult(e, base)) };
}
/**
* The working-directory picker's search. A query with a path in it (`git/llama`,
* `~/git`, `/usr/lo`) navigates: it matches the last segment among the parent's
* children. A plain name (`llama`) is looked up anywhere under home, nearest
* folders first: `onPartial` gets the shallow results while the deeper walk
* runs. Either way a search that finds nothing is retried allowing for a typo.
*/
export async function runFolderSearch(
query: string,
home: string | null,
signal: AbortSignal,
onPartial?: (result: GlobSearchChildResult) => void
): Promise<GlobSearchChildResult> {
const scope = home ?? HOME_TILDE;
const type = GlobSearchType.DIR;
query = toScopeSeparators(query, scope);
if (splitPathQuery(query) || query.includes(PATH_SEPARATOR)) {
const res = await runGlobSearchWithChildren(
toHomeRelativeQuery(query, home),
scope,
SEARCH.MAX_DEPTH,
SEARCH.LIMIT,
signal,
{ type }
);
if (res.error || res.entries.length > 0) return res;
return runFuzzyFolderSearch(res.args, [SEARCH.PATH_NAV_MAX_DEPTH], signal);
}
const args = buildGlobSearchArgs(query, scope, SEARCH.SHALLOW_DEPTH);
// started alongside the shallow search and read after it: a failure here (the search
// being cancelled, say) must not go unhandled, and costs only the deeper results
const deepSearch = runGlobSearch(
{ ...args, maxDepth: SEARCH.MAX_DEPTH },
type,
SEARCH.LIMIT,
signal
).catch((): GlobSearchResult => ({ base: '', entries: [] }));
const shallow = await runGlobSearch(args, type, SEARCH.LIMIT, signal);
if (shallow.error) return { args, base: shallow.base, entries: [], error: shallow.error };
const near = rankEntries(shallow.entries, query);
// only a near folder is entered on an exact name: a deeper namesake is just a result
const collect = (ranked: GlobEntry[], base: string) => {
const result = { args, base, entries: ranked.map((e) => toEntryResult(e, base)) };
return withExactDirChildren(
result,
near,
query,
type,
SEARCH.LIMIT,
SEARCH.PATH_NAV_MAX_DEPTH,
signal
);
};
if (near.length > 0) onPartial?.(await collect(near, shallow.base));
const deep = await deepSearch;
const nearPaths = new Set(near.map((entry) => entry.path));
// deeper folders go below the near ones, so the list does not reshuffle when they arrive
const far = rankEntries(
deep.entries.filter((entry) => !nearPaths.has(entry.path)),
query
);
if (near.length + far.length === 0) {
return runFuzzyFolderSearch(args, [SEARCH.SHALLOW_DEPTH, SEARCH.FUZZY_MAX_DEPTH], signal);
}
// hidden folders go last, below even the deeper regular ones
const isRegular = (entry: GlobEntry) =>
query.startsWith(HIDDEN_NAME_PREFIX) || !isHiddenPath(entry.path);
const found = [...near, ...far];
return collect(
[...found.filter(isRegular), ...found.filter((entry) => !isRegular(entry))],
shallow.base
);
}

View file

@ -0,0 +1,7 @@
/**
* True for a mouse move the user made. A list that renders under a resting
* pointer fires hover events too, and those must not move a picker's highlight.
*/
export function hasPointerMoved(event: MouseEvent) {
return event.movementX !== 0 || event.movementY !== 0;
}

View file

@ -125,6 +125,7 @@ export {
} from './formatters';
// IME utilities
export { hasPointerMoved } from './has-pointer-moved';
export { isIMEComposing } from './is-ime-composing';
export { shouldTypeToFocus } from './type-to-focus';
@ -235,9 +236,13 @@ export {
export {
splitPathQuery,
toHomeRelativeQuery,
toScopeSeparators,
buildCaseInsensitiveGlob,
buildFuzzyGlobs,
fuzzyDistance,
buildGlobSearchArgs,
rankEntries,
isHiddenPath,
joinPath,
highlightMatch,
type PathQuery
@ -246,7 +251,7 @@ export {
export { resolveTabTarget, resolveTabView, type TabView } from './chat-tabs';
// Shared `file_glob_search` runner with a short-lived result cache
export { runGlobSearch, runGlobSearchWithChildren } from './glob-search';
export { runFolderSearch, runGlobSearch, runGlobSearchWithChildren } from './glob-search';
// Mention-token detection (for the `@`-triggered file/folder mention picker)
export {
@ -257,7 +262,13 @@ export {
// Slash-command token detection (for the `/`-triggered command picker)
export {
type CommandToken,
findCommandToken,
insertCwdCommand,
isCommandDismissed,
locateCwdCommand,
removeCommandToken,
replaceWithCwdCommand,
takeCommandDismissSnapshot,
type CommandDismissSnapshot
} from './command-token';

View file

@ -9,6 +9,11 @@ import {
TRAILING_SLASHES_REGEX
} from '#lib/constants/index.ts';
/** `~` or a path under it, as typed or as a search from `~` returns it. */
function isTildePath(path: string): boolean {
return path === HOME_TILDE || path.startsWith(HOME_TILDE_PREFIX);
}
export function lastPathSegment(p: string): string {
const trimmed = p.replace(TRAILING_SLASHES_REGEX, '');
const idx = trimmed.lastIndexOf(PATH_SEPARATOR);
@ -16,14 +21,16 @@ export function lastPathSegment(p: string): string {
return idx === -1 ? trimmed : trimmed.slice(idx + 1);
}
// `~/...` under `home`; falls back to the basename when home is unknown
// or the path is outside it.
// `~/...` under `home` (a path already written from `~` stays as it is); falls back to the
// basename when home is unknown or the path is outside it.
export function abbreviateWorkingDir(
path: string | null | undefined,
home: string | null | undefined
): string {
if (!path) return '';
if (isTildePath(path)) return path;
if (!home) return lastPathSegment(path);
if (path === home) return HOME_TILDE;
@ -37,6 +44,8 @@ export function abbreviateWorkingDir(
// Unlike abbreviateWorkingDir, paths outside `home` are returned
// unchanged - used where the full path matters.
export function abbreviateHome(path: string, home: string | null | undefined): string {
if (isTildePath(path)) return path;
if (!home) return path;
if (path === home) return HOME_TILDE;

View file

@ -9,6 +9,7 @@
import { lastPathSegment } from './path-display';
import {
GLOB,
HIDDEN_NAME_PREFIX,
HOME_TILDE,
HOME_TILDE_PREFIX,
LEADING_SLASHES_REGEX,
@ -34,6 +35,19 @@ function toPosixSeparators(query: string): string {
return query.split(GLOB.WINDOWS_SEPARATOR).join(PATH_SEPARATOR);
}
/**
* The query with `\\` rewritten into `/` when the scope it is searched in is a
* Windows path (`C:/Users/al`, `//host/share`), so `git\\llama` is a path there
* too. Under a POSIX scope the backslash stays: it is a legal filename character.
*/
export function toScopeSeparators(query: string, scope: string): string {
const isWindowsScope = GLOB.DRIVE_PREFIX_REGEX.test(scope) || GLOB.UNC_ROOT_REGEX.test(scope);
if (!isWindowsScope) return query;
return query.split(GLOB.WINDOWS_SEPARATOR).join(PATH_SEPARATOR);
}
export function rootPrefixLength(path: string): number {
const unc = path.match(GLOB.UNC_ROOT_REGEX);
@ -86,10 +100,11 @@ export function toHomeRelativeQuery(query: string, home?: string | null): string
return home ? joinPath(home, query) : HOME_TILDE_PREFIX + query;
}
export function buildCaseInsensitiveGlob(query: string): string {
let out = GLOB.WILDCARD;
/** Glob fragment matching `text` in any letter case, with glob metacharacters taken literally. */
function toCaseInsensitiveFragment(text: string): string {
let out = '';
for (const c of query) {
for (const c of text) {
const lo = c.toLowerCase();
const up = c.toUpperCase();
@ -100,7 +115,70 @@ export function buildCaseInsensitiveGlob(query: string): string {
else out += c;
}
return out + GLOB.WILDCARD;
return out;
}
export function buildCaseInsensitiveGlob(query: string): string {
return GLOB.WILDCARD + toCaseInsensitiveFragment(query) + GLOB.WILDCARD;
}
/**
* Globs that together match every name within one typo of `query`: each one
* swaps a pair of neighbouring characters for a wildcard, which covers a
* wrong, missing, extra or swapped character there. They match far more than
* that, so the results are filtered with `fuzzyDistance`.
*/
export function buildFuzzyGlobs(query: string): string[] {
const chars = [...query];
if (chars.length < SEARCH.FUZZY_MIN_QUERY_LENGTH || chars.length > SEARCH.FUZZY_MAX_QUERY_LENGTH)
return [];
const globs = new Set<string>();
for (let i = 0; i + 1 < chars.length; i++) {
const kept = [chars.slice(0, i), chars.slice(i + 2)]
.filter((part) => part.length > 0)
.map((part) => toCaseInsensitiveFragment(part.join('')));
globs.add(GLOB.WILDCARD + kept.join(GLOB.WILDCARD) + GLOB.WILDCARD);
}
return [...globs];
}
/**
* Fewest single-character edits (a wrong, missing, extra or swapped
* character) that turn `query` into some part of `text`, ignoring case.
*/
export function fuzzyDistance(text: string, query: string): number {
const t = [...text.toLowerCase()];
const q = [...query.toLowerCase()];
// a match may start anywhere in the text, so the first row costs nothing
let previous: number[] = new Array(t.length + 1).fill(0);
let beforePrevious: number[] = [];
for (let i = 1; i <= q.length; i++) {
const row = [i];
for (let j = 1; j <= t.length; j++) {
const substitution = previous[j - 1] + (q[i - 1] === t[j - 1] ? 0 : 1);
let best = Math.min(previous[j] + 1, row[j - 1] + 1, substitution);
if (i > 1 && j > 1 && q[i - 1] === t[j - 2] && q[i - 2] === t[j - 1]) {
best = Math.min(best, beforePrevious[j - 2] + 1);
}
row.push(best);
}
beforePrevious = previous;
previous = row;
}
return Math.min(...previous);
}
export function buildGlobSearchArgs(
@ -138,9 +216,24 @@ function rankScore(path: string, query: string): number {
return RANK_OTHER;
}
/** True when the path is, or sits inside, a hidden folder (`.config/llama`, `git\\.cache`). */
export function isHiddenPath(path: string): boolean {
return toPosixSeparators(path)
.split(PATH_SEPARATOR)
.some((segment) => segment.startsWith(HIDDEN_NAME_PREFIX));
}
/**
* Regular entries come before hidden ones, unless the query itself asks for a
* hidden name (`.config`). Within each group the best name match wins.
*/
export function rankEntries(entries: GlobEntry[], query: string): GlobEntry[] {
const hiddenRank = (path: string) =>
!query.startsWith(HIDDEN_NAME_PREFIX) && isHiddenPath(path) ? 1 : 0;
return [...entries].sort(
(a, b) =>
hiddenRank(a.path) - hiddenRank(b.path) ||
rankScore(a.path, query) - rankScore(b.path, query) ||
a.path.length - b.path.length ||
a.path.localeCompare(b.path)

View file

@ -1,7 +1,8 @@
// Guards the slash-command dispatch contract: commands dispatch only on
// explicit selection (Enter/click in the picker), never mid-typing.
// Typing `/model is broken` is prose until the command is picked - the
// buffer must survive; only an actual selection consumes the token.
// Typing `/model is broken` is prose: `/model` takes no argument, so the
// words after it close the picker and the buffer survives; only an actual
// selection consumes the token.
import ChatFormPickersHarness from './components/ChatFormPickersHarness.svelte';
import { tick } from 'svelte';
@ -22,8 +23,7 @@ describe('slash command dispatch', () => {
expect(screen.component.getValue()).toBe('/model is broken');
expect(screen.component.getCalls()).not.toContain('openModelSelector');
expect(screen.component.getCalls().some((c) => c.startsWith('setValue:'))).toBe(false);
expect(pickers.isCommandPickerOpen).toBe(true);
expect(pickers.commandQuery).toBe('model');
expect(pickers.isCommandPickerOpen).toBe(false);
});
it('dispatches /model on explicit selection and consumes the token', async () => {
@ -31,7 +31,7 @@ describe('slash command dispatch', () => {
await tick();
screen.component.type('/model is broken');
screen.component.type('/model');
await tick();
const pickers = screen.component.getPickers();
@ -47,6 +47,27 @@ describe('slash command dispatch', () => {
expect(pickers.isCommandPickerOpen).toBe(false);
});
it('opens the system message editor on /system-message and consumes the token', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.type('/system');
await tick();
const pickers = screen.component.getPickers();
const command = pickers.availableCommands.find((c) => c.name === 'system-message');
if (!command) throw new Error('system-message command missing');
pickers.handleCommandSelect(command);
await tick();
expect(screen.component.getValue()).toBe('');
expect(screen.component.getCalls()).toContain('onSystemMessage');
expect(pickers.isCommandPickerOpen).toBe(false);
});
it('seeds the prompt picker search from the token args on selection', async () => {
const screen = render(ChatFormPickersHarness);
@ -137,3 +158,186 @@ describe('slash command dispatch', () => {
expect(pickers.isWorkingDirectoryPickerOpen).toBe(false);
});
});
describe('commands anywhere in the message', () => {
it('opens the command picker for a command typed after other words', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix the build /mod|');
await tick();
const pickers = screen.component.getPickers();
expect(pickers.isCommandPickerOpen).toBe(true);
expect(pickers.commandQuery).toBe('mod');
});
it('takes only the command out of the message on selection', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix /model| the build');
await tick();
const pickers = screen.component.getPickers();
const model = pickers.availableCommands.find((c) => c.name === 'model');
if (!model) throw new Error('model command missing');
pickers.handleCommandSelect(model);
await tick();
await Promise.resolve();
expect(screen.component.getValue()).toBe('fix the build');
expect(screen.component.getCaretOffset()).toBe('fix '.length);
expect(screen.component.getCalls()).toContain('openModelSelector');
});
it('leaves a path in the message alone', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('look in src/lib|');
await tick();
expect(screen.component.getPickers().isCommandPickerOpen).toBe(false);
});
});
describe('/cwd command in the chat input', () => {
it('writes the current directory on a /cwd command at the caret', async () => {
const screen = render(ChatFormPickersHarness, {
cwd: '/home/me/projects/app',
serverHome: '/home/me'
});
await tick();
screen.component.typeAt('fix| the build');
const pickers = screen.component.getPickers();
pickers.handleWorkingDirectoryOpen();
await tick();
await Promise.resolve();
expect(screen.component.getValue()).toBe('fix /cwd ~/projects/app the build');
expect(screen.component.getCaretOffset()).toBe('fix /cwd ~/projects/app'.length);
expect(pickers.isWorkingDirectoryPickerOpen).toBe(true);
expect(pickers.isWorkingDirectoryInline).toBe(true);
expect(pickers.workingDirectoryQuery).toBe('~/projects/app');
});
it('searches the path after /cwd, not the words around it', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix the build|');
const pickers = screen.component.getPickers();
pickers.handleWorkingDirectoryOpen();
await tick();
expect(screen.component.getValue()).toBe('fix the build /cwd ');
screen.component.typeAt('fix the build /cwd docs|');
await tick();
expect(pickers.workingDirectoryQuery).toBe('docs');
expect(pickers.isWorkingDirectoryPickerOpen).toBe(true);
// an edit elsewhere in the message keeps the picker and its path
screen.component.typeAt('so,| fix the build /cwd docs');
await tick();
expect(pickers.workingDirectoryQuery).toBe('docs');
expect(pickers.isWorkingDirectoryPickerOpen).toBe(true);
});
it('gives the message back when the picker closes', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix| the build');
const pickers = screen.component.getPickers();
pickers.handleWorkingDirectoryOpen();
await tick();
screen.component.typeAt('fix /cwd docs| the build');
pickers.handleWorkingDirectoryClose();
await tick();
expect(screen.component.getValue()).toBe('fix the build');
expect(pickers.isWorkingDirectoryPickerOpen).toBe(false);
});
it('closes when its command is deleted, whatever else the message says', async () => {
const screen = render(ChatFormPickersHarness, {
cwd: '/home/me/git',
serverHome: '/home/me'
});
await tick();
const pickers = screen.component.getPickers();
screen.component.typeAt('why does /cwd break|');
pickers.handleWorkingDirectoryOpen();
await tick();
expect(screen.component.getValue()).toBe('why does /cwd break /cwd ~/git');
// deleting ` /cwd ~/git` shifts the text by as much as the other `/cwd` is away
screen.component.typeAt('why does /cwd break|');
await tick();
expect(pickers.isWorkingDirectoryPickerOpen).toBe(false);
expect(screen.component.getValue()).toBe('why does /cwd break');
});
it('completes a typed /cw command where it is, on selection', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix the build /cw docs|');
await tick();
const pickers = screen.component.getPickers();
const cwd = pickers.availableCommands.find((c) => c.name === 'cwd');
if (!cwd) throw new Error('cwd command missing');
pickers.handleCommandSelect(cwd);
await tick();
expect(screen.component.getValue()).toBe('fix the build /cwd docs');
expect(pickers.workingDirectoryQuery).toBe('docs');
});
it('tells the /cwd command from the message around it by the caret', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
const pickers = screen.component.getPickers();
screen.component.typeAt('fix the build|');
pickers.handleWorkingDirectoryOpen();
await tick();
screen.component.typeAt('fix the build /cwd docs|');
expect(pickers.isCaretInCwdCommand()).toBe(true);
screen.component.typeAt('fix| the build /cwd docs');
expect(pickers.isCaretInCwdCommand()).toBe(false);
});
});

View file

@ -4,17 +4,26 @@
type UseChatFormPickersReturn
} from '#lib/hooks/use-chat-form-pickers.svelte.ts';
interface Props {
cwd?: string | null;
serverHome?: string | null;
}
let { cwd = null, serverHome = null }: Props = $props();
let value = $state('');
let caretOffset = $state(0);
const calls: string[] = [];
const pickers = useChatFormPickers({
canCompact: () => true,
canEditSystemMessage: () => true,
editsCwdInline: () => true,
focusInput: () => {},
getCaretOffset: () => caretOffset,
getCwd: () => null,
getCwd: () => cwd,
getPickersRef: () => undefined,
getServerHome: () => null,
getServerHome: () => serverHome,
getShowModelSelector: () => true,
getValue: () => value,
hasCwdTools: () => true,
@ -22,6 +31,9 @@
onCompact: () => {
calls.push('onCompact');
},
onSystemMessage: () => {
calls.push('onSystemMessage');
},
openModelSelector: () => {
calls.push('openModelSelector');
},
@ -42,6 +54,17 @@
pickers.handleInput();
}
// The same, with the caret at `|` in `text`: an edit somewhere in the middle.
export function typeAt(text: string) {
value = text.replace('|', '');
caretOffset = text.indexOf('|');
pickers.handleInput();
}
export function getCaretOffset() {
return caretOffset;
}
export function getValue() {
return value;
}

View file

@ -168,7 +168,7 @@ export const chatCommands: ChatFormCommand[] = [
},
{
action: ChatFormCommandAction.COMPACT,
description: 'Summarize the conversation to free up context',
description: 'Summarize to free up context',
disabled: true,
keywords: ['summarize', 'context'],
name: 'compact'

View file

@ -1,51 +1,151 @@
import { findCommandToken, takeCommandDismissSnapshot } from '#lib/utils/index.ts';
import {
findCommandToken,
insertCwdCommand,
isCommandDismissed,
locateCwdCommand,
removeCommandToken,
replaceWithCwdCommand,
takeCommandDismissSnapshot
} from '#lib/utils/index.ts';
import { describe, expect, it } from 'vitest';
// the commands that take an argument
const COMMANDS = ['prompt', 'cwd'];
/** The token with the caret at `|` in `text`. */
function tokenAt(text: string, commands: readonly string[] = COMMANDS) {
const cursor = text.indexOf('|');
return findCommandToken(text.replace('|', ''), cursor, commands);
}
describe('findCommandToken', () => {
it('returns null when the value does not start with a slash', () => {
expect(findCommandToken('hello /prompt')).toBeNull();
expect(findCommandToken('')).toBeNull();
expect(findCommandToken('prompt')).toBeNull();
it('returns null where no command is typed', () => {
expect(tokenAt('|')).toBeNull();
expect(tokenAt('prompt|')).toBeNull();
expect(tokenAt('and/or|')).toBeNull();
expect(tokenAt('see ~/git|')).toBeNull();
});
it('parses a bare slash', () => {
expect(findCommandToken('/')).toEqual({ args: '', end: 1, name: '' });
it('finds a command at the start of the input', () => {
expect(tokenAt('/|')).toEqual({ args: '', end: 1, name: '', start: 0 });
expect(tokenAt('/prompt|')).toEqual({ args: '', end: 7, name: 'prompt', start: 0 });
});
it('parses a command name with no args', () => {
expect(findCommandToken('/prompt')).toEqual({ args: '', end: 7, name: 'prompt' });
it('finds a command anywhere in the message', () => {
expect(tokenAt('fix the build /cw|')).toEqual({ args: '', end: 17, name: 'cw', start: 14 });
expect(tokenAt('first line\n/mod|')).toEqual({ args: '', end: 15, name: 'mod', start: 11 });
expect(tokenAt('fix /cw| the build')).toEqual({ args: '', end: 7, name: 'cw', start: 4 });
});
it('parses a command name followed by a space', () => {
expect(findCommandToken('/prompt ')).toEqual({ args: '', end: 8, name: 'prompt' });
it('runs to the end of the word the caret is in', () => {
expect(tokenAt('/pro|mpt and more')).toEqual({ args: '', end: 7, name: 'prompt', start: 0 });
});
it('parses args after the command name', () => {
expect(findCommandToken('/prompt rev')).toEqual({ args: 'rev', end: 11, name: 'prompt' });
});
it('parses multi-word args', () => {
expect(findCommandToken('/prompt review code ')).toEqual({
args: ' review code ',
end: 22,
name: 'prompt'
it('takes the argument of a known command, single spaces included', () => {
expect(tokenAt('/prompt rev|')).toEqual({ args: 'rev', end: 11, name: 'prompt', start: 0 });
expect(tokenAt('fix /cwd ~/My Docs|')).toEqual({
args: '~/My Docs',
end: 18,
name: 'cwd',
start: 4
});
});
it('treats the whole run as the name when there is no space', () => {
expect(findCommandToken('/promptx')).toEqual({ args: '', end: 8, name: 'promptx' });
it('reads a path in the argument as the argument, not a command of its own', () => {
expect(tokenAt('/cwd /usr/lo|')?.name).toBe('cwd');
expect(tokenAt('/cwd /usr|')?.name).toBe('cwd');
});
it('ends the argument at two spaces or a new line', () => {
expect(tokenAt('/cwd docs more|')).toBeNull();
expect(tokenAt('/cwd docs\nmore|')).toBeNull();
});
it('leaves the words after a command without an argument to the message', () => {
expect(tokenAt('/model is broken|')).toBeNull();
expect(tokenAt('please use /m the small one|')).toBeNull();
expect(tokenAt('please use /m|')).toEqual({ args: '', end: 13, name: 'm', start: 11 });
});
it('takes no argument for an unknown name', () => {
expect(tokenAt('/promptx|')).toEqual({ args: '', end: 8, name: 'promptx', start: 0 });
expect(tokenAt('/foo bar|')).toBeNull();
expect(tokenAt('/cw docs|')).toEqual({ args: 'docs', end: 8, name: 'cw', start: 0 });
});
});
describe('takeCommandDismissSnapshot', () => {
it('returns null when there is no command token', () => {
expect(takeCommandDismissSnapshot('hello')).toBeNull();
describe('command dismissal', () => {
it('holds for the same token only', () => {
const snapshot = takeCommandDismissSnapshot('hi /prompt rev', 14, COMMANDS);
expect(snapshot).toEqual({ args: 'rev', name: 'prompt', start: 3 });
expect(isCommandDismissed(snapshot, { args: 'rev', end: 14, name: 'prompt', start: 3 })).toBe(
true
);
expect(isCommandDismissed(snapshot, { args: 'revi', end: 15, name: 'prompt', start: 3 })).toBe(
false
);
expect(takeCommandDismissSnapshot('hello', 5, COMMANDS)).toBeNull();
});
});
describe('removeCommandToken', () => {
it('leaves one space between the words around it', () => {
expect(removeCommandToken('fix /model the build', { end: 10, start: 4 })).toEqual({
caret: 4,
value: 'fix the build'
});
expect(removeCommandToken('fix the build /model', { end: 20, start: 14 })).toEqual({
caret: 13,
value: 'fix the build'
});
expect(removeCommandToken('/model fix it', { end: 6, start: 0 })).toEqual({
caret: 0,
value: 'fix it'
});
expect(removeCommandToken('/model', { end: 6, start: 0 })).toEqual({ caret: 0, value: '' });
});
});
describe('the /cwd command', () => {
it('is written at the caret, set apart by spaces', () => {
expect(insertCwdCommand('fix the build', 3, '~/git')).toEqual({
caret: 14,
start: 4,
value: 'fix /cwd ~/git the build'
});
expect(insertCwdCommand('', 0, '')).toEqual({ caret: 5, start: 0, value: '/cwd ' });
});
it('captures the name and args', () => {
expect(takeCommandDismissSnapshot('/prompt rev')).toEqual({
args: 'rev',
name: 'prompt'
it('completes a partial token in place', () => {
expect(replaceWithCwdCommand('fix /cw docs now', { end: 12, start: 4 }, 'docs')).toEqual({
caret: 13,
start: 4,
value: 'fix /cwd docs now'
});
});
it('is found again after an edit elsewhere', () => {
expect(locateCwdCommand('so, fix /cwd docs now', 4, 'docs', 4)).toEqual({
end: 17,
query: 'docs',
start: 8
});
expect(locateCwdCommand('fix the build', 4, 'docs')).toBeNull();
});
it('is looked for only where it was or where the edit moved it', () => {
expect(locateCwdCommand('why does /cwd break', 20, '~/git', -6)).toBeNull();
});
it('reads its path to two spaces or the end of the line when it changed', () => {
expect(locateCwdCommand('/cwd ~/My Docs more', 0, 'x')).toEqual({
end: 14,
query: '~/My Docs',
start: 0
});
expect(locateCwdCommand('/cwd', 0, '')).toEqual({ end: 4, query: '', start: 0 });
});
});

View file

@ -0,0 +1,142 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('#lib/services/tools.service.ts', () => ({
ToolsService: { executeToolRaw: vi.fn() }
}));
import { SEARCH } from '#lib/constants/index.ts';
import { ToolsService } from '#lib/services/tools.service.ts';
import { runFolderSearch } from '#lib/utils/index.ts';
const mockExecute = vi.mocked(ToolsService.executeToolRaw);
interface Folders {
[depth: number]: string[];
}
/** Serve `folders[max_depth]` for the globs that carry `needle`, and nothing for the rest. */
function serve(home: string, needle: string, folders: Folders) {
mockExecute.mockImplementation(async (_tool, params) => {
const { include, max_depth: depth, path } = params as Record<string, string | number>;
const paths = path === home && String(include).includes(needle) ? (folders[+depth] ?? []) : [];
return { base: String(path), entries: paths.map((p) => ({ path: p, type: 'dir' })) };
});
}
const signal = () => new AbortController().signal;
// Distinct homes per test so the module-level search cache never serves a
// prior test's result under the same (type, path, glob, depth) key.
beforeEach(() => {
mockExecute.mockReset();
});
describe('runFolderSearch', () => {
it('finds a plain name below home, nearest folders first', async () => {
const home = '/Users/deep';
serve(home, '[lL][lL][aA][mM][aA]', {
[SEARCH.MAX_DEPTH]: ['git/llama.cpp', 'git/work/tools/llama-bench'],
[SEARCH.SHALLOW_DEPTH]: ['git/llama.cpp']
});
const partial = vi.fn();
const res = await runFolderSearch('llama', home, signal(), partial);
expect(partial.mock.calls[0][0].entries.map((e: { path: string }) => e.path)).toEqual([
`${home}/git/llama.cpp`
]);
expect(res.entries.map((e) => e.path)).toEqual([
`${home}/git/llama.cpp`,
`${home}/git/work/tools/llama-bench`
]);
});
it('navigates a query with a path in it', async () => {
const home = '/Users/nav';
mockExecute.mockResolvedValueOnce({
base: `${home}/git`,
entries: [{ path: 'llama-ui', type: 'dir' }]
});
const res = await runFolderSearch('git/llama', home, signal());
expect(mockExecute.mock.calls[0][1]).toMatchObject({
max_depth: SEARCH.PATH_NAV_MAX_DEPTH,
path: `${home}/git`
});
expect(res.entries.map((e) => e.path)).toEqual([`${home}/git/llama-ui`]);
});
it('allows for a typo when nothing matches exactly', async () => {
const home = '/Users/typo';
// only the looser typo globs carry this fragment
serve(home, '[lL][lL]*[aA]', {
[SEARCH.FUZZY_MAX_DEPTH]: ['git/llama.cpp', 'git/all-data']
});
const res = await runFolderSearch('llana', home, signal());
expect(res.entries.map((e) => e.path)).toEqual([`${home}/git/llama.cpp`]);
});
it('finds nothing for a name that is more than a typo away', async () => {
const home = '/Users/none';
serve(home, 'never', {});
const res = await runFolderSearch('zzzzz', home, signal());
expect(res.entries).toEqual([]);
expect(res.error).toBeUndefined();
});
});
describe('runFolderSearch across platforms', () => {
it('navigates a backslash path under a Windows home', async () => {
const home = 'C:/Users/win';
mockExecute.mockResolvedValueOnce({
base: `${home}/git`,
entries: [{ path: 'llama.cpp', type: 'dir' }]
});
const res = await runFolderSearch('git\\llama', home, signal());
expect(mockExecute.mock.calls[0][1]).toMatchObject({ path: `${home}/git` });
expect(res.entries.map((e) => e.path)).toEqual([`${home}/git/llama.cpp`]);
});
it('keeps the near results when the deeper search fails', async () => {
const home = '/Users/flaky';
mockExecute.mockImplementation(async (_tool, params) => {
const { max_depth: depth, path } = params as Record<string, string | number>;
if (depth === SEARCH.MAX_DEPTH) throw new Error('network');
return { base: String(path), entries: [{ path: 'git/llama.cpp', type: 'dir' }] };
});
const res = await runFolderSearch('llama', home, signal());
expect(res.entries.map((e) => e.path)).toEqual([`${home}/git/llama.cpp`]);
});
it('stops the typo search at the nearest depth that finds something', async () => {
const home = '/Users/near';
serve(home, '[lL][lL]*[aA]', { [SEARCH.SHALLOW_DEPTH]: ['git/llama.cpp'] });
await runFolderSearch('llana', home, signal());
const depths = mockExecute.mock.calls.map(
([, params]) => (params as { max_depth: number }).max_depth
);
expect(depths).not.toContain(SEARCH.FUZZY_MAX_DEPTH);
});
});

View file

@ -122,3 +122,149 @@ describe('runGlobSearchWithChildren', () => {
expect(mockExecute).toHaveBeenCalledTimes(1);
});
});
describe('runGlobSearchWithChildren with a relative path', () => {
it('lists the folder at the top of the scope before its deeper namesakes', async () => {
const scope = '/Users/rootF';
mockExecute.mockImplementation(async (_tool, params) => {
const { path } = params as { path: string };
// the direct lookup navigates to the parent; the glob only sees deeper copies
return path === `${scope}/ui/lib`
? { base: path, entries: [{ path: 'voice', type: 'dir' }] }
: { base: scope, entries: [{ path: '.worktrees/a/ui/lib/voice', type: 'dir' }] };
});
const res = await runGlobSearchWithChildren(
'ui/lib/voi',
scope,
3,
50,
new AbortController().signal,
{ descendOnTrailingSeparator: true, type: GlobSearchType.ALL }
);
expect(res.entries.map((e) => e.path)).toEqual([
`${scope}/ui/lib/voice`,
`${scope}/.worktrees/a/ui/lib/voice`
]);
});
it('keeps the deeper matches when the path does not exist at the top', async () => {
const scope = '/Users/rootG';
mockExecute.mockImplementation(async (_tool, params) => {
const { path } = params as { path: string };
return path === scope
? { base: scope, entries: [{ path: 'apps/ui/lib/voice', type: 'dir' }] }
: { error: 'path does not exist or is not a directory' };
});
const res = await runGlobSearchWithChildren(
'ui/lib/voi',
scope,
3,
50,
new AbortController().signal
);
expect(res.error).toBeUndefined();
expect(res.entries.map((e) => e.path)).toEqual([`${scope}/apps/ui/lib/voice`]);
});
});
describe('runGlobSearchWithChildren with a rooted path', () => {
it('looks further down when the folder itself holds no such name', async () => {
mockExecute
.mockResolvedValueOnce({ base: '/Users/rootDeep', entries: [] })
.mockResolvedValueOnce({
base: '/Users/rootDeep',
entries: [
{ path: '.cache/llama.cpp', type: 'dir' },
{ path: 'git/llama.cpp', type: 'dir' }
]
});
const res = await runGlobSearchWithChildren(
'~/llama.cpp',
'/Users/rootDeep/Desktop',
3,
50,
new AbortController().signal
);
expect(mockExecute.mock.calls.map((call) => call[1])).toMatchObject([
{ max_depth: 1, path: '~' },
{ max_depth: 3, path: '~' }
]);
expect(res.entries.map((e) => e.path)).toEqual([
'/Users/rootDeep/git/llama.cpp',
'/Users/rootDeep/.cache/llama.cpp'
]);
});
it('stays in the folder when it holds a match', async () => {
mockExecute.mockResolvedValueOnce({
base: '/Users/rootNear',
entries: [{ path: 'whisper.cpp', type: 'dir' }]
});
const res = await runGlobSearchWithChildren(
'~/whisper.cpp',
'/Users/rootNear/Desktop',
3,
50,
new AbortController().signal,
{ descendOnTrailingSeparator: true }
);
expect(mockExecute).toHaveBeenCalledTimes(1);
expect(res.entries.map((e) => e.path)).toEqual(['/Users/rootNear/whisper.cpp']);
});
});
describe('runGlobSearchWithChildren edge cases', () => {
it('follows a backslash path from a Windows scope', async () => {
const scope = 'C:/rootH';
mockExecute.mockImplementation(async (_tool, params) => {
const { path } = params as { path: string };
return path === `${scope}/ui/lib`
? { base: path, entries: [{ path: 'voice', type: 'dir' }] }
: { base: scope, entries: [] };
});
const res = await runGlobSearchWithChildren(
'ui\\lib\\voi',
scope,
3,
50,
new AbortController().signal
);
expect(res.entries.map((e) => e.path)).toEqual([`${scope}/ui/lib/voice`]);
});
it('surfaces the deep search error when the direct lookup finds nothing', async () => {
const scope = '/Users/rootI';
mockExecute.mockImplementation(async (_tool, params) => {
const { path } = params as { path: string };
return path === scope ? { error: 'boom' } : { base: path, entries: [] };
});
const res = await runGlobSearchWithChildren(
'ui/lib/zzz',
scope,
3,
50,
new AbortController().signal
);
expect(res.error).toBe('boom');
});
});

View file

@ -20,6 +20,7 @@ import { AgenticSectionType, BuiltInTool } from '#lib/enums/index.ts';
import type { AgenticSection, WriteFileMeta } from '#lib/types/index.ts';
import {
abbreviateHome,
abbreviateWorkingDir,
formatCwdMessage,
lastPathSegment,
parseCwdMessage
@ -88,6 +89,21 @@ describe('abbreviateHome', () => {
});
});
describe('abbreviateWorkingDir', () => {
it('shows a directory under home from ~/', () => {
expect(abbreviateWorkingDir('/Users/al/git/llama.cpp', '/Users/al')).toBe('~/git/llama.cpp');
});
it('keeps a directory already written from ~', () => {
expect(abbreviateWorkingDir('~/git/llama.cpp', '/Users/al')).toBe('~/git/llama.cpp');
expect(abbreviateWorkingDir('~/git/llama.cpp', null)).toBe('~/git/llama.cpp');
});
it('shows the last segment of a directory outside home', () => {
expect(abbreviateWorkingDir('/opt/project', '/Users/al')).toBe('project');
});
});
describe('formatCwdMessage / parseCwdMessage', () => {
it('formats a cwd change matching the UI text, with a file link', () => {
expect(formatCwdMessage('/Users/al/Documents', '/Users/al')).toBe(

View file

@ -1,12 +1,16 @@
import { GLOB, SEARCH } from '#lib/constants/index.ts';
import {
buildCaseInsensitiveGlob,
buildFuzzyGlobs,
buildGlobSearchArgs,
fuzzyDistance,
highlightMatch,
isHiddenPath,
joinPath,
rankEntries,
splitPathQuery,
toHomeRelativeQuery
toHomeRelativeQuery,
toScopeSeparators
} from '#lib/utils/index.ts';
import { describe, expect, it } from 'vitest';
@ -211,3 +215,69 @@ describe('toHomeRelativeQuery', () => {
expect(args.last).toBe('proj');
});
});
describe('buildFuzzyGlobs', () => {
it('swaps each pair of neighbouring characters for a wildcard', () => {
expect(buildFuzzyGlobs('lama')).toEqual(['*[mM][aA]*', '*[lL]*[aA]*', '*[lL][aA]*']);
});
it('skips queries too short or too long to match loosely', () => {
expect(buildFuzzyGlobs('abc')).toEqual([]);
expect(buildFuzzyGlobs('a'.repeat(SEARCH.FUZZY_MAX_QUERY_LENGTH + 1))).toEqual([]);
});
});
describe('fuzzyDistance', () => {
it('is zero when the text holds the query, in any case', () => {
expect(fuzzyDistance('Llama.cpp', 'llama')).toBe(0);
});
it('counts a wrong, missing, extra or swapped character as one edit', () => {
expect(fuzzyDistance('llama.cpp', 'llana')).toBe(1);
expect(fuzzyDistance('llama.cpp', 'lama.')).toBe(0);
expect(fuzzyDistance('llama.cpp', 'llma.')).toBe(1);
expect(fuzzyDistance('llama.cpp', 'llamma')).toBe(1);
expect(fuzzyDistance('llama.cpp', 'lalma')).toBe(1);
});
it('grows with every further edit', () => {
expect(fuzzyDistance('documents', 'llama')).toBeGreaterThan(SEARCH.FUZZY_MAX_EDITS);
});
});
describe('rankEntries with hidden folders', () => {
const entries = [
{ path: '.config/llama', type: 'dir' },
{ path: '.llama-app', type: 'dir' },
{ path: 'git/llama.cpp', type: 'dir' }
];
it('ranks regular folders above hidden ones, even an exact hidden match', () => {
expect(rankEntries(entries, 'llama').map((e) => e.path)).toEqual([
'git/llama.cpp',
'.config/llama',
'.llama-app'
]);
});
it('ranks by name alone when the query asks for a hidden name', () => {
expect(rankEntries(entries, '.llama')[0].path).toBe('.llama-app');
});
it('tells a hidden path by any of its segments', () => {
expect(isHiddenPath('git/.cache/x')).toBe(true);
expect(isHiddenPath('git/llama.cpp')).toBe(false);
});
});
describe('toScopeSeparators', () => {
it('reads a backslash as a separator under a Windows scope', () => {
expect(toScopeSeparators('git\\llama', 'C:/Users/al')).toBe('git/llama');
expect(toScopeSeparators('git\\llama', '//host/share/al')).toBe('git/llama');
});
it('leaves the backslash alone under a POSIX scope, where it is a filename character', () => {
expect(toScopeSeparators('git\\llama', '/home/al')).toBe('git\\llama');
expect(toScopeSeparators('git\\llama', '~')).toBe('git\\llama');
});
});