Add host and project filtering to worktree jump palette (#12638)

* Add host and project filtering to the worktree jump palette

Filter the search results by execution host (local, SSH, runtime) and project/repo, with a drill-down options menu, chips for active selections, and overflow hints for large result sets. Filters reset on open to prevent silently hiding results, and stale selections auto-prune. Caps rendered rows per section to prevent DOM bloat from single-character queries. Host badges appear when filtering to clarify which rows survived the cut.

* Add E2E test for worktree jump-palette host filtering

Tests filter interaction via keyboard, filter/project intersection, empty state when filters exclude all results, and ephemeral filter reset on modal close.

* Fix worktree jump-palette filter persistence and search UX

- Persist filter state when filter model changes to prevent dropped IDs from silently re-activating
- Fix result count to distinguish between query matches (all items) vs. empty list (capped sections)
- Improve filter field options: use state for scroller to handle unmount/remount, clamp highlight index to valid range, only reset on query/field change, not re-ranks
- Context-aware space key: allow toggle in listbox only, not in search input (preserves for typing)
- Replace generic "Clear field" translation with field-specific strings to preserve capitalization in non-English languages

* fix(cmd-j): reset filter highlight without prop-change effect

Derive the active option index from field/query identity instead of
resetting it in a useEffect so React Doctor and first-paint stay correct.

* fix static analysis issue

* fix(e2e): rename project entity in jump-palette filter seed

Filter options use project.displayName when a Project exists, so only
renaming the repo left the local option labeled with the path basename.
This commit is contained in:
Jinjing
2026-08-05 00:11:47 -07:00
committed by GitHub
parent e5f49e0e1d
commit 128a39f7f8
17 changed files with 2121 additions and 35 deletions
@@ -86,6 +86,19 @@ import {
import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel'
import { buildSidebarHostOptions } from '@/components/sidebar/sidebar-host-options'
import { getPaletteHostBadge, type PaletteHostBadge } from '@/components/cmd-j/palette-host-badge'
import PaletteFilterMenu from '@/components/cmd-j/PaletteFilterMenu'
import PaletteFilterChips from '@/components/cmd-j/PaletteFilterChips'
import { buildPaletteFilterModel } from '@/components/cmd-j/palette-filter-options'
import { getProjectGroupExecutionHostIdForRows } from '@/components/sidebar/worktree-list-host-filtering'
import {
buildPaletteFilterPredicate,
EMPTY_PALETTE_FILTER,
getPaletteFilterSelectionCount,
isPaletteFilterActive,
reconcilePaletteFilter,
type PaletteFilterState
} from '@/components/cmd-j/palette-filter'
import { capPaletteSection } from '@/components/cmd-j/palette-section-render-cap'
import { useSettingsNavigationMetadata } from '@/hooks/useSettingsNavigationMetadata'
import { runWorktreeDelete } from '@/components/sidebar/delete-worktree-flow'
import {
@@ -124,7 +137,10 @@ import {
import { lookupGitHubWorkItemForSource } from '@/lib/github-work-item-source-lookup'
import type { SettingsNavTarget } from '@/lib/settings-navigation-types'
import { getHostDisplayLabelOverrides } from '../../../shared/host-setting-overrides'
import { isRuntimeOwnedSshTargetId } from '../../../shared/execution-host'
import {
getSettingsFocusedExecutionHostId,
isRuntimeOwnedSshTargetId
} from '../../../shared/execution-host'
import type { BrowserPage, BrowserWorkspace, Worktree } from '../../../shared/types'
import { isGitRepoKind } from '../../../shared/repo-kind'
import { buildTaskSourceContextFromRepo } from '../../../shared/task-source-context'
@@ -420,6 +436,10 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
const [query, setQuery] = useState('')
const deferredQuery = useDeferredValue(query)
const [selectedItemId, setSelectedItemId] = useState('')
// Why: filters reset on close — a filter that survives reopen silently hides
// results in a surface people open reflexively.
const [rawFilter, setRawFilter] = useState<PaletteFilterState>(EMPTY_PALETTE_FILTER)
const [dialogElement, setDialogElement] = useState<HTMLElement | null>(null)
const previousWorktreeIdRef = useRef<string | null>(null)
const previousActiveTabTypeRef = useRef<'browser' | 'editor' | 'terminal' | 'simulator'>(
'terminal'
@@ -432,6 +452,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
const wasVisibleRef = useRef(false)
const skipRestoreFocusRef = useRef(false)
const listRef = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
const fallbackFocusOuterFrameRef = useRef<number | null>(null)
const fallbackFocusInnerFrameRef = useRef<number | null>(null)
const createLookupGuard = useMemo(() => createWorktreePaletteRequestGuard(), [])
@@ -467,6 +488,54 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
)
const canCreateWorktree = repos.length > 0
// Why: host-less repos and worktrees inherit the focused runtime host, exactly
// as the sidebar's host headers do — otherwise the two disagree on bucketing.
const defaultHostId = useMemo(() => getSettingsFocusedExecutionHostId(settings), [settings])
const filterModel = useMemo(
() =>
buildPaletteFilterModel({
repos,
worktrees: allWorktrees,
hostOptions,
projects,
projectHostSetups,
defaultHostId
}),
[allWorktrees, defaultHostId, hostOptions, projectHostSetups, projects, repos]
)
// Why: a selection whose repo or SSH target disappeared would otherwise keep
// the palette permanently empty with nothing on screen explaining it. Memoized
// because a prune allocates, and an unstable identity here would invalidate
// every downstream search memo on every render.
const filter = useMemo(
() => reconcilePaletteFilter(rawFilter, filterModel),
[rawFilter, filterModel]
)
// Why persist the prune: otherwise a dropped id lives on in rawFilter and
// silently re-activates — with no chip on screen — if its host or project
// comes back. Same-reference return on a no-op keeps this from re-rendering.
useEffect(() => {
setRawFilter((current) => reconcilePaletteFilter(current, filterModel))
}, [filterModel])
const filterActive = isPaletteFilterActive(filter)
const hostFilterActive = filter.hostIds.length > 0
const filterPredicate = useMemo(
() => buildPaletteFilterPredicate(filter, filterModel),
[filter, filterModel]
)
// Why: same resolver the sidebar's host filtering uses, so a group row lands on
// the host its header claims — including the host-less "inherit default" case.
const groupHostIdByGroupId = useMemo(
() =>
new Map(
projectGroups.map((group) => [
group.id,
getProjectGroupExecutionHostIdForRows(group, defaultHostId)
])
),
[defaultHostId, projectGroups]
)
const hasQuery = deferredQuery.trim().length > 0
const isLoading = repos.length > 0 && Object.keys(worktreesByRepo).length === 0
@@ -489,6 +558,11 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
if (worktree.isArchived) {
return false
}
// Why: filtering here (not after search) keeps the whole pipeline —
// smart-sort, search, tab indexing — working on the narrowed set.
if (filterPredicate && !filterPredicate.matchesWorktree(worktree)) {
return false
}
if (hideDefaultBranchWorkspace && isDefaultBranchWorkspace(worktree)) {
return false
}
@@ -522,6 +596,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
allWorktrees,
alwaysShowDefaultBranchWorkspace,
browserTabsByWorktree,
filterPredicate,
hideAutomationGeneratedWorkspaces,
hideCliCreatedWorkspaces,
hideDefaultBranchWorkspace,
@@ -544,15 +619,16 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
[emptyQueryVisibleWorktrees, activeWorktreeId, lastVisitedAtByWorktreeId]
)
const searchScopeWorktrees = useMemo(
() =>
getWorktreePaletteSearchScope({
hasQuery,
allWorktrees,
emptyQueryWorktrees: switchableWorktreesForRows
}),
[allWorktrees, hasQuery, switchableWorktreesForRows]
)
const searchScopeWorktrees = useMemo(() => {
const scope = getWorktreePaletteSearchScope({
hasQuery,
allWorktrees,
emptyQueryWorktrees: switchableWorktreesForRows
})
// Why: the typed-query branch widens back to allWorktrees, so the filter has
// to be re-applied there; the empty-query branch is already narrowed.
return hasQuery && filterPredicate ? scope.filter(filterPredicate.matchesWorktree) : scope
}, [allWorktrees, filterPredicate, hasQuery, switchableWorktreesForRows])
// Why: typed queries route through sortWorktreesSmart — ranking only diverges on the empty-query branch.
const sortedWorktrees = useMemo(
@@ -584,8 +660,12 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
const browserSortedWorktrees = useMemo(() => {
// Why: browser-tab search is cross-worktree, so keep indexing browser pages even when the owning worktree is archived/hidden.
// The filter still applies — narrowing before the sort also shrinks the open-tab index it feeds.
const scope = filterPredicate
? allWorktrees.filter(filterPredicate.matchesWorktree)
: allWorktrees
return sortWorktreesSmart(
allWorktrees,
scope,
tabsByWorktree,
repoMap,
agentStatusByPaneKey,
@@ -596,6 +676,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
)
}, [
allWorktrees,
filterPredicate,
tabsByWorktree,
repoMap,
agentStatusByPaneKey,
@@ -890,14 +971,29 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
projects,
projectHostSetups,
renderableRepoIds: renderableProjectRepoIds
}).map((result) => ({
id: result.id,
type: 'project-target' as const,
result
}))
})
.filter((result) => {
if (!filterPredicate) {
return true
}
return result.kind === 'project'
? filterPredicate.matchesProjectRowKey(result.rowKey)
: filterPredicate.matchesGroupHostId(
groupHostIdByGroupId.get(result.id.slice('project-group:'.length)) ??
defaultHostId
)
})
.map((result) => ({
id: result.id,
type: 'project-target' as const,
result
}))
: [],
[
deferredQuery,
defaultHostId,
filterPredicate,
groupHostIdByGroupId,
hasQuery,
projectGroups,
projectHostSetups,
@@ -984,19 +1080,27 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
const paletteSections = useMemo(() => {
// Why: the worktree cap only matters when open tabs need above-the-fold protection; uncap with zero open tabs.
const worktreeCap = !hasQuery && openTabItems.length > 0 ? EMPTY_QUERY_WORKTREE_CAP : Infinity
const visibleWorktreeItems = hasQuery ? worktreeItems : worktreeItems.slice(0, worktreeCap)
const visibleProjectTargetItems = hasQuery ? projectTargetItems : []
const visibleMiddleItems = hasQuery ? middleItems : []
const visibleOpenTabItems = hasQuery
? openTabItems
: openTabItems.slice(0, EMPTY_QUERY_OPEN_TAB_CAP)
// Why: a typed query can match hundreds of rows; capping the rendered slice
// is what keeps a one-character search from building an unbounded DOM.
const worktrees = hasQuery
? capPaletteSection(worktreeItems)
: { visible: worktreeItems.slice(0, worktreeCap), overflowCount: 0 }
const projectTargets = capPaletteSection(hasQuery ? projectTargetItems : [])
const middle = capPaletteSection(hasQuery ? middleItems : [])
const openTabs = hasQuery
? capPaletteSection(openTabItems)
: { visible: openTabItems.slice(0, EMPTY_QUERY_OPEN_TAB_CAP), overflowCount: 0 }
const showWorktreeHint = !hasQuery && worktreeItems.length > worktreeCap
return {
visibleWorktreeItems,
visibleProjectTargetItems,
visibleMiddleItems,
visibleOpenTabItems,
visibleWorktreeItems: worktrees.visible as PaletteItem[],
worktreeOverflowCount: worktrees.overflowCount,
visibleProjectTargetItems: projectTargets.visible as PaletteItem[],
projectTargetOverflowCount: projectTargets.overflowCount,
visibleMiddleItems: middle.visible as PaletteItem[],
middleOverflowCount: middle.overflowCount,
visibleOpenTabItems: openTabs.visible as PaletteItem[],
openTabOverflowCount: openTabs.overflowCount,
showWorktreeHint
}
}, [worktreeItems, projectTargetItems, middleItems, openTabItems, hasQuery])
@@ -1027,8 +1131,25 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
visibleProjectTargetItems,
visibleMiddleItems,
visibleOpenTabItems,
showWorktreeHint
showWorktreeHint,
worktreeOverflowCount,
projectTargetOverflowCount,
middleOverflowCount,
openTabOverflowCount
} = paletteSections
const pushOverflowHint = (id: string, overflowCount: number): void => {
if (overflowCount > 0) {
entries.push({
id,
type: 'hint',
label: translate(
'worktreeJumpPalette.renderCapOverflow',
'{{value0}} more - keep typing or add a filter to narrow',
{ value0: overflowCount }
)
})
}
}
const visibleWorkspaceItemCount = visibleWorktreeItems.length + (showCreateAction ? 1 : 0)
const populatedSectionCount = [
visibleWorkspaceItemCount,
@@ -1073,6 +1194,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
)
})
}
pushOverflowHint('__hint_worktree_overflow__', worktreeOverflowCount)
}
if (visibleProjectTargetItems.length > 0) {
if (showProjectTargetHeader) {
@@ -1086,6 +1208,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
})
}
appendPaletteListEntries(entries, visibleProjectTargetItems)
pushOverflowHint('__hint_project_overflow__', projectTargetOverflowCount)
}
if (showCreateAction) {
// Why: project/group jump targets are navigation results — keep them after worktree matches, before the creation fallback.
@@ -1100,6 +1223,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
})
}
appendPaletteListEntries(entries, visibleMiddleItems)
pushOverflowHint('__hint_middle_overflow__', middleOverflowCount)
}
if (visibleOpenTabItems.length > 0) {
if (showOpenTabsHeader) {
@@ -1110,6 +1234,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
})
}
appendPaletteListEntries(entries, visibleOpenTabItems)
pushOverflowHint('__hint_open_tab_overflow__', openTabOverflowCount)
}
return entries
}, [hasQuery, paletteSections, showCreateAction, worktreeItems.length])
@@ -1159,6 +1284,9 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
skipRestoreFocusRef.current = false
setQuery('')
setSelectedItemId('')
// Why: reset on open, not on close — closing races the fade-out, and a
// mid-animation reset would flash unfiltered rows behind the overlay.
setRawFilter(EMPTY_PALETTE_FILTER)
listRef.current?.scrollTo(0, 0)
}
@@ -1658,12 +1786,42 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
e.preventDefault()
}, [])
const focusPaletteInput = useCallback(() => {
inputRef.current?.focus()
}, [])
// Why: the filter popover portals into the dialog element so the Dialog focus
// trap treats it as inside; anchoring off the trailing slot finds it without
// threading a ref through CommandDialog.
const setDialogElementFromNode = useCallback((node: HTMLDivElement | null) => {
setDialogElement(node?.closest<HTMLElement>('[role="dialog"]') ?? null)
}, [])
const handleOpenAutoFocus = useCallback((_event: Event) => {
// No-op: focus handled in the visible effect before Radix; exists only to satisfy the prop API.
}, [])
const resultCount = selectableItems.length
// Why the split: on a query the render cap hides matches, so announcing the
// visible slice under-reports "results found". The empty-query list renders
// only its two capped sections, so there the visible count is the truth.
const resultCount = hasQuery
? worktreeItems.length + projectTargetItems.length + middleItems.length + openTabItems.length
: selectableItems.length
const emptyState = (() => {
// Why: a filter is the most likely reason a familiar query returns nothing,
// so name it before any other explanation and point at the way out.
if (filterActive) {
return {
title: translate(
'worktreeJumpPalette.filter.emptyTitle',
'No results match the active filter'
),
subtitle: translate(
'worktreeJumpPalette.filter.emptySubtitle',
'Clear the filter above, or widen it to more hosts and projects.'
)
}
}
if (
(hasAnySearchableWorktrees ||
hasAnyProjectSearchCandidates ||
@@ -1729,6 +1887,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
}}
>
<CommandInput
ref={inputRef}
placeholder={translate(
'auto.components.WorktreeJumpPalette.1ebe225fee',
'Search worktrees, settings, tabs, and actions...'
@@ -1738,7 +1897,19 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
wrapperClassName="mx-3 mt-3 rounded-lg border border-border/55 bg-muted/28 px-3.5 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]"
iconClassName="mr-2.5 h-4 w-4 text-muted-foreground/60"
className="h-12 text-[14px] placeholder:text-muted-foreground/75"
trailing={
<div ref={setDialogElementFromNode}>
<PaletteFilterMenu
model={filterModel}
filter={filter}
onFilterChange={setRawFilter}
onRequestInputFocus={focusPaletteInput}
portalContainer={dialogElement}
/>
</div>
}
/>
<PaletteFilterChips model={filterModel} filter={filter} onFilterChange={setRawFilter} />
<CommandList ref={listRef} className="max-h-[min(460px,62vh)] px-2.5 pb-2.5 pt-2">
{isLoading && selectableItems.length === 0 && !showCreateAction ? (
<PaletteState
@@ -1831,7 +2002,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
? (sshConnectionStates.get(sshConnectionId)?.status ?? 'disconnected')
: null
const isSshDisconnected = sshStatus != null && sshStatus !== 'connected'
const hostBadge = getPaletteHostBadge(repo, hostOptions)
const hostBadge = getPaletteHostBadge(repo, hostOptions, hostFilterActive)
return (
<CommandItem
@@ -1958,7 +2129,9 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
if (entry.type === 'project-target') {
const result = entry.result
const isProject = result.kind === 'project'
const hostBadge = isProject ? getPaletteHostBadge(result.repo, hostOptions) : null
const hostBadge = isProject
? getPaletteHostBadge(result.repo, hostOptions, hostFilterActive)
: null
const badgeLabel = isProject
? translate('auto.components.WorktreeJumpPalette.projectBadge', 'Project')
: translate('auto.components.WorktreeJumpPalette.repoGroupBadge', 'Repo group')
@@ -2046,7 +2219,11 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
? repoMap.get(workspaceTabWorktree.repoId)
: undefined
const workspaceTabRepoName = workspaceTabRepo?.displayName ?? result.repoName
const workspaceTabHostBadge = getPaletteHostBadge(workspaceTabRepo, hostOptions)
const workspaceTabHostBadge = getPaletteHostBadge(
workspaceTabRepo,
hostOptions,
hostFilterActive
)
const WorkspaceTabIcon =
result.contentType === 'terminal' ? SquareTerminal : FileText
@@ -2129,7 +2306,11 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
? repoMap.get(simulatorWorktree.repoId)
: undefined
const simulatorRepoName = simulatorRepo?.displayName ?? result.repoName
const simulatorHostBadge = getPaletteHostBadge(simulatorRepo, hostOptions)
const simulatorHostBadge = getPaletteHostBadge(
simulatorRepo,
hostOptions,
hostFilterActive
)
return (
<CommandItem
@@ -2207,7 +2388,11 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
const browserWorktree = worktreeMap.get(result.worktreeId)
const browserRepo = browserWorktree ? repoMap.get(browserWorktree.repoId) : undefined
const browserRepoName = browserRepo?.displayName ?? result.repoName
const browserHostBadge = getPaletteHostBadge(browserRepo, hostOptions)
const browserHostBadge = getPaletteHostBadge(
browserRepo,
hostOptions,
hostFilterActive
)
return (
<CommandItem
@@ -2295,9 +2480,16 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
<span>{translate('auto.components.WorktreeJumpPalette.75499e01d9', 'Close')}</span>
<FooterKey>↑↓</FooterKey>
<span>{translate('auto.components.WorktreeJumpPalette.ac037cfac2', 'Move')}</span>
<FooterKey>{translate('worktreeJumpPalette.filter.tabKey', 'Tab')}</FooterKey>
<span>{translate('worktreeJumpPalette.filter.label', 'Filter')}</span>
</div>
</div>
<div aria-live="polite" className="sr-only">
{filterActive
? `${translate('worktreeJumpPalette.filter.ariaActive', 'Filter: {{value0}} active.', {
value0: getPaletteFilterSelectionCount(filter)
})} `
: ''}
{deferredQuery.trim()
? translate(
'auto.components.WorktreeJumpPalette.bb72c08e63',
@@ -0,0 +1,77 @@
import React, { useMemo } from 'react'
import { X } from 'lucide-react'
import { translate } from '@/i18n/i18n'
import type { PaletteFilterModel } from './palette-filter-options'
import {
EMPTY_PALETTE_FILTER,
isPaletteFilterActive,
togglePaletteFilterValue,
type PaletteFilterField,
type PaletteFilterState
} from './palette-filter'
type Chip = { field: PaletteFilterField; id: string; label: string }
export default function PaletteFilterChips({
model,
filter,
onFilterChange
}: {
model: PaletteFilterModel
filter: PaletteFilterState
onFilterChange: (next: PaletteFilterState) => void
}): React.JSX.Element | null {
const chips = useMemo<Chip[]>(() => {
const hostLabels = new Map(model.hosts.map((host) => [host.id, host.label]))
const projectLabels = new Map(model.projects.map((project) => [project.id, project.label]))
return [
...filter.hostIds.map((id) => ({
field: 'host' as const,
id,
label: hostLabels.get(id) ?? id
})),
...filter.projectKeys.map((id) => ({
field: 'project' as const,
id,
label: projectLabels.get(id) ?? id
}))
]
}, [filter.hostIds, filter.projectKeys, model.hosts, model.projects])
if (!isPaletteFilterActive(filter) || chips.length === 0) {
return null
}
return (
<div className="mx-3 mt-2 flex items-center gap-1.5">
{/* Why: horizontal scroll keeps every chip reachable without a hard +N dead-end. */}
<div className="scrollbar-sleek flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto">
{chips.map((chip) => (
<button
key={`${chip.field}:${chip.id}`}
type="button"
onClick={() => onFilterChange(togglePaletteFilterValue(filter, chip.field, chip.id))}
aria-label={translate(
'worktreeJumpPalette.filter.removeChip',
'Remove filter {{value0}}',
{
value0: chip.label
}
)}
className="flex h-6 max-w-[140px] shrink-0 items-center gap-1 rounded-full border border-primary/35 bg-primary/12 px-2 text-[11px] text-foreground transition-colors hover:bg-primary/20"
>
<span className="truncate">{chip.label}</span>
<X className="size-3 shrink-0 text-muted-foreground" aria-hidden="true" />
</button>
))}
</div>
<button
type="button"
onClick={() => onFilterChange(EMPTY_PALETTE_FILTER)}
className="ml-1 shrink-0 rounded-md px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"
>
{translate('worktreeJumpPalette.filter.clearAll', 'Clear all')}
</button>
</div>
)
}
@@ -0,0 +1,321 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useVirtualizer } from '@tanstack/react-virtual'
import { Check, ChevronLeft, SearchIcon } from 'lucide-react'
import { cn } from '@/lib/utils'
import { translate } from '@/i18n/i18n'
import type { PaletteFilterOption } from './palette-filter-options'
import type { PaletteFilterField } from './palette-filter'
import {
FILTER_OPTION_LIST_MAX_HEIGHT,
FILTER_OPTION_ROW_HEIGHT,
rankPaletteFilterOptions,
type FilterOptionRankMode
} from './palette-filter-option-list'
export type PaletteFilterGroup = {
field: PaletteFilterField
heading: string
options: readonly PaletteFilterOption[]
selected: readonly string[]
}
function FilterOptionRow({
option,
isSelected,
isActive,
onToggle
}: {
option: PaletteFilterOption
isSelected: boolean
isActive: boolean
onToggle: () => void
}): React.JSX.Element {
return (
<button
type="button"
role="option"
aria-selected={isSelected}
data-active={isActive ? 'true' : undefined}
onClick={onToggle}
className={cn(
'flex w-full cursor-pointer items-center gap-2.5 px-2.5 text-left text-[13px] outline-none',
isActive ? 'bg-accent' : 'hover:bg-accent/70'
)}
style={{ height: FILTER_OPTION_ROW_HEIGHT }}
>
<span
className={cn(
'flex size-4 shrink-0 items-center justify-center rounded-[4px] border transition-colors',
isSelected ? 'border-primary bg-primary text-primary-foreground' : 'border-border/70'
)}
>
{isSelected ? <Check className="size-3" aria-hidden="true" /> : null}
</span>
<span className="min-w-0 flex-1 truncate text-foreground">{option.label}</span>
<span className="shrink-0 text-[11px] tabular-nums text-muted-foreground/70">
{option.count}
</span>
</button>
)
}
export function PaletteFilterFieldOptions({
group,
canGoBack,
optionQuery,
onOptionQueryChange,
onBack,
onToggle,
onClearField,
onSelectAllMatching
}: {
group: PaletteFilterGroup
canGoBack: boolean
optionQuery: string
onOptionQueryChange: (value: string) => void
onBack: () => void
onToggle: (id: string) => void
onClearField: () => void
onSelectAllMatching: (ids: readonly string[]) => void
}): React.JSX.Element {
const selected = useMemo(() => new Set(group.selected), [group.selected])
const normalizedQuery = optionQuery.trim().toLowerCase()
const rankMode: FilterOptionRankMode = group.field === 'host' ? 'registry' : 'popularity'
const ranked = useMemo(
() =>
rankPaletteFilterOptions({
options: group.options,
selectedIds: selected,
query: normalizedQuery,
rankMode
}),
[group.options, selected, normalizedQuery, rankMode]
)
// State, not a ref: the scroller unmounts on an empty list, and the wheel
// listener has to re-attach to the node that replaces it.
const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null)
const inputRef = useRef<HTMLInputElement>(null)
// Why the field/query are stored alongside the index instead of reset in an
// effect: a stale row would stay active for one paint. Why not key off the
// ranked list identity: a toggle re-ranks, so that would yank the cursor back
// to the top mid multi-select.
const [highlight, setHighlight] = useState(() => ({
field: group.field,
query: normalizedQuery,
index: 0
}))
const storedIndex =
highlight.field === group.field && highlight.query === normalizedQuery ? highlight.index : 0
// The stored index can outlive the rows it pointed at when the list shrinks.
const activeIndex = Math.min(storedIndex, Math.max(0, ranked.ordered.length - 1))
useEffect(() => {
inputRef.current?.focus()
}, [group.field])
const virtualizer = useVirtualizer({
count: ranked.ordered.length,
getScrollElement: () => scrollEl,
estimateSize: () => FILTER_OPTION_ROW_HEIGHT,
overscan: 8,
getItemKey: (index) => ranked.ordered[index]?.id ?? index
})
// Same wheel workaround as CommandList: Radix remove-scroll cancels wheel on portaled content.
useEffect(() => {
const el = scrollEl
if (!el) {
return
}
const onWheel = (event: WheelEvent): void => {
if (el.scrollHeight <= el.clientHeight) {
return
}
event.preventDefault()
el.scrollTop += event.deltaY
}
el.addEventListener('wheel', onWheel, { passive: false })
return () => el.removeEventListener('wheel', onWheel)
}, [scrollEl])
const moveActive = useCallback(
(delta: number) => {
if (ranked.ordered.length === 0) {
return
}
const next = Math.max(0, Math.min(ranked.ordered.length - 1, activeIndex + delta))
virtualizer.scrollToIndex(next, { align: 'auto' })
setHighlight({ field: group.field, query: normalizedQuery, index: next })
},
[activeIndex, group.field, normalizedQuery, ranked.ordered.length, virtualizer]
)
const handleListKeyDown = useCallback(
// Space toggles only from the listbox; in the search input it stays a
// typeable character, and labels like "Delta Host" need it.
(event: React.KeyboardEvent, allowSpaceToToggle = true) => {
if (event.key === 'ArrowDown') {
event.preventDefault()
moveActive(1)
return
}
if (event.key === 'ArrowUp') {
event.preventDefault()
moveActive(-1)
return
}
if (event.key === 'Enter' || (allowSpaceToToggle && event.key === ' ')) {
const option = ranked.ordered[activeIndex]
if (!option) {
return
}
event.preventDefault()
onToggle(option.id)
}
},
[activeIndex, moveActive, onToggle, ranked.ordered]
)
const searchPlaceholder =
group.field === 'host'
? translate('worktreeJumpPalette.filter.searchHosts', 'Filter hosts...')
: translate('worktreeJumpPalette.filter.searchProjects', 'Filter projects...')
const emptyLabel =
group.field === 'host'
? translate('worktreeJumpPalette.filter.noHosts', 'No matching hosts')
: translate('worktreeJumpPalette.filter.noProjects', 'No matching projects')
// Why a dedicated string per field: lowercasing a translated heading breaks in
// languages that capitalize nouns mid-sentence (German "Projekte").
const clearLabel =
group.field === 'host'
? translate('worktreeJumpPalette.filter.clearHosts', 'Clear hosts')
: translate('worktreeJumpPalette.filter.clearProjects', 'Clear projects')
const canSelectAll = ranked.unselectedCount > 0
const canClear = ranked.selectedCount > 0
return (
<>
{canGoBack ? (
<div className="flex items-center gap-1 border-b border-border/55 px-1.5 py-1">
<button
type="button"
onClick={onBack}
className="flex h-7 items-center gap-1 rounded-md px-1.5 text-[12px] text-muted-foreground hover:bg-accent hover:text-foreground"
>
<ChevronLeft className="size-3.5" aria-hidden="true" />
{translate('worktreeJumpPalette.filter.back', 'Back')}
</button>
<span className="min-w-0 flex-1 truncate pr-2 text-[12px] font-medium text-foreground">
{group.heading}
</span>
</div>
) : null}
<div
className="flex items-center border-b border-border/55 bg-muted/30 px-3"
data-cmdk-input-wrapper=""
>
<SearchIcon
className="mr-2 size-3.5 shrink-0 text-muted-foreground/60"
aria-hidden="true"
/>
<input
ref={inputRef}
value={optionQuery}
onChange={(event) => onOptionQueryChange(event.target.value)}
onKeyDown={(event) => handleListKeyDown(event, false)}
placeholder={searchPlaceholder}
className="h-9 w-full bg-transparent text-[13px] outline-none placeholder:text-muted-foreground"
aria-label={searchPlaceholder}
/>
</div>
{ranked.selectedCollapsed ? (
<div className="flex items-center justify-between gap-2 border-b border-border/55 px-2.5 py-1.5">
<span className="text-[11px] text-muted-foreground">
{translate(
'worktreeJumpPalette.filter.selectedCollapsed',
'{{value0}} selected — remove via chips or Clear',
{ value0: ranked.selectedCount }
)}
</span>
<button
type="button"
onClick={onClearField}
className="shrink-0 rounded-md px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"
>
{clearLabel}
</button>
</div>
) : null}
{ranked.ordered.length === 0 ? (
<div className="px-3 py-4 text-center text-[12px] text-muted-foreground">{emptyLabel}</div>
) : (
<div
ref={setScrollEl}
role="listbox"
aria-multiselectable="true"
aria-label={group.heading}
tabIndex={-1}
onKeyDown={handleListKeyDown}
className="popover-scroll-content scrollbar-sleek overflow-y-auto py-1"
style={{ maxHeight: FILTER_OPTION_LIST_MAX_HEIGHT }}
>
<div className="relative w-full" style={{ height: `${virtualizer.getTotalSize()}px` }}>
{virtualizer.getVirtualItems().map((virtualItem) => {
const option = ranked.ordered[virtualItem.index]
if (!option) {
return null
}
return (
<div
key={virtualItem.key}
className="absolute top-0 left-0 w-full"
style={{
height: `${virtualItem.size}px`,
transform: `translateY(${virtualItem.start}px)`
}}
>
<FilterOptionRow
option={option}
isSelected={selected.has(option.id)}
isActive={virtualItem.index === activeIndex}
onToggle={() => onToggle(option.id)}
/>
</div>
)
})}
</div>
</div>
)}
{canSelectAll || canClear ? (
<div className="flex items-center justify-between gap-2 border-t border-border/55 px-2 py-1.5">
{canSelectAll ? (
<button
type="button"
onClick={() => onSelectAllMatching(ranked.unselectedIds)}
className="rounded-md px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"
>
{translate(
'worktreeJumpPalette.filter.selectAllMatching',
'Select all matching ({{value0}})',
{ value0: ranked.unselectedCount }
)}
</button>
) : (
<span />
)}
{canClear ? (
<button
type="button"
onClick={onClearField}
className="rounded-md px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"
>
{clearLabel}
</button>
) : null}
</div>
) : null}
</>
)
}
@@ -0,0 +1,230 @@
import React, { useCallback, useMemo, useState } from 'react'
import { ChevronRight, ListFilter, X } from 'lucide-react'
import { Command, CommandGroup, CommandItem, CommandList } from '@/components/ui/command'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
import { translate } from '@/i18n/i18n'
import type { PaletteFilterModel } from './palette-filter-options'
import {
addPaletteFilterValues,
clearPaletteFilterField,
EMPTY_PALETTE_FILTER,
getPaletteFilterSelectionCount,
isPaletteFilterActive,
togglePaletteFilterValue,
type PaletteFilterField,
type PaletteFilterState
} from './palette-filter'
import { PaletteFilterFieldOptions, type PaletteFilterGroup } from './PaletteFilterFieldOptions'
function CategoryRoot({
groups,
onOpenField
}: {
groups: readonly PaletteFilterGroup[]
onOpenField: (field: PaletteFilterField) => void
}): React.JSX.Element {
return (
<CommandList className="popover-scroll-content scrollbar-sleek max-h-[280px] py-1">
<CommandGroup>
{groups.map((group) => {
const selectedCount = group.selected.length
return (
<CommandItem
key={group.field}
value={group.field}
onSelect={() => onOpenField(group.field)}
className="mx-0.5 flex cursor-pointer items-center gap-2.5 rounded-md px-2 py-2 text-[13px] data-[selected=true]:bg-accent"
>
<span className="min-w-0 flex-1 truncate text-foreground">{group.heading}</span>
{selectedCount > 0 ? (
<span className="rounded-full bg-primary/85 px-1.5 text-[10px] font-semibold tabular-nums text-primary-foreground">
{selectedCount}
</span>
) : (
<span className="shrink-0 text-[11px] tabular-nums text-muted-foreground/70">
{group.options.length}
</span>
)}
<ChevronRight
className="size-3.5 shrink-0 text-muted-foreground/60"
aria-hidden="true"
/>
</CommandItem>
)
})}
</CommandGroup>
</CommandList>
)
}
export default function PaletteFilterMenu({
model,
filter,
onFilterChange,
onRequestInputFocus,
portalContainer
}: {
model: PaletteFilterModel
filter: PaletteFilterState
onFilterChange: (next: PaletteFilterState) => void
onRequestInputFocus: () => void
portalContainer: HTMLElement | null
}): React.JSX.Element | null {
const [open, setOpen] = useState(false)
// null = category root; non-null = drill into that field's options
const [activeField, setActiveField] = useState<PaletteFilterField | null>(null)
const [optionQuery, setOptionQuery] = useState('')
const groups = useMemo<PaletteFilterGroup[]>(() => {
const entries: PaletteFilterGroup[] = []
// Why: a single host (or single project) is nothing to disambiguate between,
// so that axis stays hidden rather than offering a no-op checkbox.
if (model.hosts.length > 1) {
entries.push({
field: 'host',
heading: translate('worktreeJumpPalette.filter.hosts', 'Hosts'),
options: model.hosts,
selected: filter.hostIds
})
}
if (model.projects.length > 1) {
entries.push({
field: 'project',
heading: translate('worktreeJumpPalette.filter.projects', 'Projects'),
options: model.projects,
selected: filter.projectKeys
})
}
return entries
}, [filter.hostIds, filter.projectKeys, model.hosts, model.projects])
// Stale field falls back to root if its group disappeared mid-session.
const activeGroup =
activeField == null ? null : (groups.find((group) => group.field === activeField) ?? null)
const selectionCount = getPaletteFilterSelectionCount(filter)
const active = isPaletteFilterActive(filter)
const resetMenuState = useCallback(() => {
setActiveField(null)
setOptionQuery('')
}, [])
const handleOpenChange = useCallback(
(nextOpen: boolean) => {
setOpen(nextOpen)
if (!nextOpen) {
resetMenuState()
return
}
// Single axis: skip the category step and open straight into its options.
if (groups.length === 1) {
setActiveField(groups[0].field)
}
},
[groups, resetMenuState]
)
const goBackToRoot = useCallback(() => {
setActiveField(null)
setOptionQuery('')
}, [])
// Why: stopPropagation so the palette's ancestor cmdk doesn't steal keys;
// Escape on the options layer steps back instead of closing when both axes exist.
const handleKeyDown = useCallback(
(event: React.KeyboardEvent) => {
event.stopPropagation()
if (event.key === 'Escape' && activeGroup != null && groups.length > 1) {
event.preventDefault()
goBackToRoot()
}
},
[activeGroup, goBackToRoot, groups.length]
)
const handleCloseAutoFocus = useCallback(
(event: Event) => {
// Why: Radix would return focus to the trigger button, leaving typing dead.
event.preventDefault()
onRequestInputFocus()
},
[onRequestInputFocus]
)
if (groups.length === 0) {
return null
}
return (
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger
type="button"
aria-label={translate('worktreeJumpPalette.filter.trigger', 'Filter results')}
data-active={active ? 'true' : undefined}
className={cn(
'ml-2 flex h-7 shrink-0 items-center gap-1.5 rounded-md border border-border/55 px-2 text-[12px] text-muted-foreground transition-colors outline-none hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50',
active && 'border-primary/45 bg-primary/12 text-foreground'
)}
>
<ListFilter className="size-3.5" aria-hidden="true" />
<span>{translate('worktreeJumpPalette.filter.label', 'Filter')}</span>
{active ? (
<span className="rounded-full bg-primary/85 px-1.5 text-[10px] font-semibold tabular-nums text-primary-foreground">
{selectionCount}
</span>
) : null}
</PopoverTrigger>
<PopoverContent
align="end"
sideOffset={6}
portalContainer={portalContainer}
collisionBoundary={portalContainer ?? undefined}
onKeyDown={handleKeyDown}
onCloseAutoFocus={handleCloseAutoFocus}
className="w-[290px] p-0"
>
<Command shouldFilter={false} className="bg-transparent">
{activeGroup == null ? (
<CategoryRoot groups={groups} onOpenField={setActiveField} />
) : (
<PaletteFilterFieldOptions
group={activeGroup}
canGoBack={groups.length > 1}
optionQuery={optionQuery}
onOptionQueryChange={setOptionQuery}
onBack={goBackToRoot}
onToggle={(id) =>
onFilterChange(togglePaletteFilterValue(filter, activeGroup.field, id))
}
onClearField={() =>
onFilterChange(clearPaletteFilterField(filter, activeGroup.field))
}
onSelectAllMatching={(ids) =>
onFilterChange(addPaletteFilterValues(filter, activeGroup.field, ids))
}
/>
)}
</Command>
{active ? (
<div className="flex items-center justify-between border-t border-border/55 px-3 py-2">
<span className="text-[11px] text-muted-foreground">
{translate('worktreeJumpPalette.filter.activeCount', '{{value0}} active', {
value0: selectionCount
})}
</span>
<button
type="button"
onClick={() => onFilterChange(EMPTY_PALETTE_FILTER)}
className="flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"
>
<X className="size-3" aria-hidden="true" />
{translate('worktreeJumpPalette.filter.clearAll', 'Clear all')}
</button>
</div>
) : null}
</PopoverContent>
</Popover>
)
}
@@ -0,0 +1,97 @@
import { describe, expect, it } from 'vitest'
import {
buildPaletteFilterOptionSearchText,
FILTER_OPTION_MAX_PINNED_SELECTED,
rankPaletteFilterOptions
} from './palette-filter-option-list'
import type { PaletteFilterOption } from './palette-filter-options'
const option = (id: string, label: string, count: number, detail = ''): PaletteFilterOption => ({
id,
label,
detail,
count,
searchText: buildPaletteFilterOptionSearchText(label, detail)
})
describe('buildPaletteFilterOptionSearchText', () => {
it('lowercases label and detail once for cheap includes checks', () => {
expect(buildPaletteFilterOptionSearchText('Acme', 'SSH host')).toBe('acme ssh host')
expect(buildPaletteFilterOptionSearchText('Local', '')).toBe('local')
})
})
describe('rankPaletteFilterOptions', () => {
const options = [
option('a', 'Alpha', 1),
option('b', 'Beta', 5),
option('c', 'Gamma', 3),
option('d', 'Delta Host', 2, 'ssh')
]
it('pins selected matches first and ranks the rest by popularity', () => {
const ranked = rankPaletteFilterOptions({
options,
selectedIds: new Set(['a']),
query: '',
rankMode: 'popularity'
})
expect(ranked.ordered.map((row) => row.id)).toEqual(['a', 'b', 'c', 'd'])
expect(ranked.selectedCount).toBe(1)
expect(ranked.unselectedCount).toBe(3)
expect(ranked.unselectedIds).toEqual(['b', 'c', 'd'])
})
it('keeps registry order for hosts within each partition', () => {
const ranked = rankPaletteFilterOptions({
options,
selectedIds: new Set(['c']),
query: '',
rankMode: 'registry'
})
expect(ranked.ordered.map((row) => row.id)).toEqual(['c', 'a', 'b', 'd'])
})
it('filters with pre-normalized searchText without re-lowercasing options', () => {
const ranked = rankPaletteFilterOptions({
options,
selectedIds: new Set(),
query: 'ssh',
rankMode: 'popularity'
})
expect(ranked.ordered.map((row) => row.id)).toEqual(['d'])
})
it('keeps selected rows visible even when they miss the query text', () => {
// Selected rows must remain undoable after a search that would otherwise hide them.
const ranked = rankPaletteFilterOptions({
options,
selectedIds: new Set(['a']),
query: 'beta',
rankMode: 'popularity'
})
expect(ranked.ordered.map((row) => row.id)).toEqual(['a', 'b'])
expect(ranked.selectedCollapsed).toBe(false)
})
it('collapses pinned selected rows when they would crowd the list', () => {
const many = Array.from({ length: FILTER_OPTION_MAX_PINNED_SELECTED + 3 }, (_, i) =>
option(`s${i}`, `Selected ${i}`, 1)
)
const rest = [option('u1', 'Unselected', 9)]
const ranked = rankPaletteFilterOptions({
options: [...many, ...rest],
selectedIds: new Set(many.map((row) => row.id)),
query: '',
rankMode: 'popularity'
})
expect(ranked.selectedCollapsed).toBe(true)
expect(ranked.selectedCount).toBe(many.length)
expect(ranked.ordered.map((row) => row.id)).toEqual(['u1'])
})
})
@@ -0,0 +1,87 @@
import type { PaletteFilterOption } from './palette-filter-options'
/** Fixed row height for the virtualized options list. */
export const FILTER_OPTION_ROW_HEIGHT = 32
/** Viewport height of the options scroller. */
export const FILTER_OPTION_LIST_MAX_HEIGHT = 280
/**
* Beyond this, pinning every selected row would bury unselected options.
* The UI collapses them into a summary; chips still manage individual removals.
*/
export const FILTER_OPTION_MAX_PINNED_SELECTED = 12
export type FilterOptionRankMode = 'registry' | 'popularity'
export type RankedPaletteFilterOptions = {
/** Selected (when not collapsed) then unselected — full list; UI virtualizes. */
ordered: readonly PaletteFilterOption[]
selectedCount: number
unselectedCount: number
/** Unselected match ids in list order — used by "Select all matching". */
unselectedIds: readonly string[]
/** Selected rows omitted from ordered because there were too many to pin. */
selectedCollapsed: boolean
}
export function buildPaletteFilterOptionSearchText(label: string, detail: string): string {
return detail ? `${label} ${detail}`.toLowerCase() : label.toLowerCase()
}
function compareByPopularity(a: PaletteFilterOption, b: PaletteFilterOption): number {
const countDelta = b.count - a.count
if (countDelta !== 0) {
return countDelta
}
return a.label.localeCompare(b.label) || a.id.localeCompare(b.id)
}
/**
* Filters by pre-normalized searchText, pins selected matches first so they stay
* undoable, and ranks the rest for discovery (popularity) or stable registry order
* (hosts: local → SSH). No render cap — the list is virtualized.
*/
export function rankPaletteFilterOptions({
options,
selectedIds,
query,
rankMode
}: {
options: readonly PaletteFilterOption[]
selectedIds: ReadonlySet<string>
/** Already trimmed + lowercased. */
query: string
rankMode: FilterOptionRankMode
}): RankedPaletteFilterOptions {
const selected: PaletteFilterOption[] = []
const unselected: PaletteFilterOption[] = []
for (const option of options) {
const isSelected = selectedIds.has(option.id)
// Why: selected rows stay visible past a search mismatch so they can still
// be unchecked without clearing the whole field or hunting through chips.
if (!isSelected && query && !option.searchText.includes(query)) {
continue
}
if (isSelected) {
selected.push(option)
} else {
unselected.push(option)
}
}
if (rankMode === 'popularity') {
selected.sort(compareByPopularity)
unselected.sort(compareByPopularity)
}
// registry: keep input order within each partition (hosts stay local-first)
const selectedCollapsed = selected.length > FILTER_OPTION_MAX_PINNED_SELECTED
return {
ordered: selectedCollapsed || selected.length === 0 ? unselected : [...selected, ...unselected],
selectedCount: selected.length,
unselectedCount: unselected.length,
unselectedIds: unselected.map((option) => option.id),
selectedCollapsed
}
}
@@ -0,0 +1,191 @@
import path from 'node:path'
import { describe, expect, it } from 'vitest'
import { getWorktreeExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host'
import type { Project, ProjectHostSetup, Repo, Worktree } from '../../../../shared/types'
import { buildSidebarHostOptions } from '../sidebar/sidebar-host-options'
import {
buildPaletteFilterModel,
resolveRepoFilterHostId,
resolveWorktreeFilterHostId
} from './palette-filter-options'
function repo(id: string, displayName: string, connectionId: string | null = null): Repo {
return {
id,
path: path.join('/repos', id),
displayName,
badgeColor: '#999999',
addedAt: 1,
connectionId
} as Repo
}
function project(id: string, displayName: string): Project {
return {
id,
displayName,
badgeColor: '#999999',
sourceRepoIds: [],
createdAt: 1,
updatedAt: 1
}
}
function setup(id: string, projectId: string, hostId: string, repoId: string): ProjectHostSetup {
return {
id,
projectId,
hostId: hostId as ProjectHostSetup['hostId'],
repoId,
path: path.join('/repos', repoId),
displayName: repoId,
setupState: 'ready',
setupMethod: 'cloned',
createdAt: 1,
updatedAt: 1
}
}
function worktree(id: string, repoId: string, extra: Partial<Worktree> = {}): Worktree {
return { id, repoId, title: id, ...extra } as Worktree
}
// Two repos behind one project: one local checkout, one on the SSH host.
const repos = [repo('r1', 'Orca'), repo('r2', 'Orca (builder)', 'ssh-1'), repo('r3', 'Solo')]
const projects = [project('p1', 'Orca')]
const projectHostSetups = [setup('s1', 'p1', 'local', 'r1'), setup('s2', 'p1', 'ssh-1', 'r2')]
const hostOptions = buildSidebarHostOptions({
repos,
sshTargetLabels: new Map([['ssh-1', 'Builder']]),
settings: { activeRuntimeEnvironmentId: null }
})
const buildModel = (worktrees: readonly Worktree[]) =>
buildPaletteFilterModel({ repos, worktrees, hostOptions, projects, projectHostSetups })
describe('buildPaletteFilterModel', () => {
it('collapses the repos of one project into a single row', () => {
const model = buildModel([worktree('w1', 'r1'), worktree('w2', 'r2'), worktree('w3', 'r3')])
expect(model.repoIdsByProjectKey.get('project:p1')).toEqual(['r1', 'r2'])
expect(model.projects.map((option) => [option.id, option.label, option.count])).toEqual([
['project:p1', 'Orca', 2],
['repo:r3', 'Solo', 1]
])
expect(model.projects[0]?.searchText).toBe('orca')
})
it('counts a worktree against its own host stamp, not its repo host', () => {
const model = buildModel([
worktree('w1', 'r1'),
worktree('w2', 'r1', { hostId: 'ssh:ssh-1' }),
worktree('w3', 'r2')
])
expect(model.hosts.map((option) => [option.id, option.count])).toEqual([
['local', 1],
['ssh:ssh-1', 2]
])
// Host stamp does not move the workspace out of its project row.
expect(model.projects.find((option) => option.id === 'project:p1')?.count).toBe(3)
})
it('omits archived worktrees from every count', () => {
const model = buildModel([
worktree('w1', 'r1'),
worktree('w2', 'r1', { isArchived: true }),
worktree('w3', 'r3', { isArchived: true })
])
expect(model.hosts.map((option) => option.id)).toEqual(['local'])
expect(model.hosts[0]?.count).toBe(1)
expect(model.projects.map((option) => option.id)).toEqual(['project:p1'])
})
it('offers no options at all when there is nothing to narrow', () => {
const model = buildModel([])
expect(model.hosts).toEqual([])
expect(model.projects).toEqual([])
// The mapping still resolves so a lingering selection prunes cleanly.
expect(model.repoIdsByProjectKey.get('project:p1')).toEqual(['r1', 'r2'])
expect(model.hostIdByRepoId.get('r2')).toBe('ssh:ssh-1')
})
it('sorts project rows by workspace count then label', () => {
const model = buildModel([worktree('w1', 'r3'), worktree('w2', 'r1'), worktree('w3', 'r2')])
// Orca has 2 workspaces, Solo has 1 — popularity beats alpha.
expect(model.projects.map((option) => option.label)).toEqual(['Orca', 'Solo'])
})
it('prefers a busier project ahead of an alphabetically earlier quiet one', () => {
const model = buildModel([
worktree('w1', 'r3'),
worktree('w2', 'r3'),
worktree('w3', 'r3'),
worktree('w4', 'r1')
])
expect(model.projects.map((option) => [option.label, option.count])).toEqual([
['Solo', 3],
['Orca', 1]
])
})
})
describe('resolveWorktreeFilterHostId', () => {
const hostIdByRepoId = new Map<string, ExecutionHostId>([['r2', 'ssh:ssh-1']])
it('prefers the worktree stamp, then the repo host, then the default host', () => {
expect(
resolveWorktreeFilterHostId({ repoId: 'r2', hostId: 'local' }, hostIdByRepoId, 'local')
).toBe('local')
expect(resolveWorktreeFilterHostId({ repoId: 'r2' }, hostIdByRepoId, 'local')).toBe('ssh:ssh-1')
expect(resolveWorktreeFilterHostId({ repoId: 'unknown' }, hostIdByRepoId, 'local')).toBe(
'local'
)
expect(
resolveWorktreeFilterHostId({ repoId: 'unknown' }, hostIdByRepoId, 'runtime:env-1')
).toBe('runtime:env-1')
})
// Guards the bucketing contract: the palette must land a workspace on the same
// host the sidebar does, including the host-less "inherit the focused runtime" case.
it('agrees with getWorktreeExecutionHostId for every default host', () => {
const repoMap = new Map(repos.map((entry) => [entry.id, entry]))
const cases = [
worktree('w1', 'r1'),
worktree('w2', 'r2'),
worktree('w3', 'r3'),
worktree('w4', 'r1', { hostId: 'ssh:ssh-1' }),
worktree('w5', 'r2', { hostId: 'local' })
]
for (const defaultHostId of ['local', 'runtime:env-1'] as ExecutionHostId[]) {
const model = buildPaletteFilterModel({
repos,
worktrees: cases,
hostOptions,
projects,
projectHostSetups,
defaultHostId
})
for (const entry of cases) {
expect(resolveWorktreeFilterHostId(entry, model.hostIdByRepoId, model.defaultHostId)).toBe(
getWorktreeExecutionHostId(entry, repoMap.get(entry.repoId), defaultHostId)
)
}
}
})
})
describe('resolveRepoFilterHostId', () => {
it('falls back to the default host when the repo has no stamp', () => {
const hostIdByRepoId = new Map<string, ExecutionHostId>([['r2', 'ssh:ssh-1']])
expect(resolveRepoFilterHostId('r2', hostIdByRepoId, 'local')).toBe('ssh:ssh-1')
expect(resolveRepoFilterHostId('missing', hostIdByRepoId, 'runtime:env-1')).toBe(
'runtime:env-1'
)
})
})
@@ -0,0 +1,193 @@
import {
getRepoExecutionHostId,
LOCAL_EXECUTION_HOST_ID,
type ExecutionHostId
} from '../../../../shared/execution-host'
import type { Project, ProjectHostSetup, Repo, Worktree } from '../../../../shared/types'
import {
getProjectHeaderRevealTarget,
type ProjectGroupingModel
} from '../sidebar/worktree-list-groups'
import type { SidebarHostOption } from '../sidebar/sidebar-host-options'
import { buildPaletteFilterOptionSearchText } from './palette-filter-option-list'
export type PaletteFilterOption = {
id: string
label: string
detail: string
count: number
/** Pre-lowercased label+detail so keystroke filtering never re-lowercases. */
searchText: string
}
function toFilterOption({
id,
label,
detail,
count
}: {
id: string
label: string
detail: string
count: number
}): PaletteFilterOption {
return {
id,
label,
detail,
count,
searchText: buildPaletteFilterOptionSearchText(label, detail)
}
}
export type PaletteFilterModel = {
hosts: readonly PaletteFilterOption[]
projects: readonly PaletteFilterOption[]
/** A project row can span several repos (Project.sourceRepoIds), so selection resolves through this. */
repoIdsByProjectKey: ReadonlyMap<string, readonly string[]>
/** Only repos that carry a host stamp; absent means "inherit defaultHostId". */
hostIdByRepoId: ReadonlyMap<string, ExecutionHostId>
/** The focused runtime host, which host-less repos and worktrees inherit. */
defaultHostId: ExecutionHostId
}
export const EMPTY_PALETTE_FILTER_MODEL: PaletteFilterModel = {
hosts: [],
projects: [],
repoIdsByProjectKey: new Map(),
hostIdByRepoId: new Map(),
defaultHostId: LOCAL_EXECUTION_HOST_ID
}
/**
* Precomputes only the repos that actually carry a host stamp so the lookup miss
* below stays equivalent to getWorktreeExecutionHostId's `defaultHostId` branch.
* Collapsing host-less repos to `local` here would disagree with the sidebar
* whenever a runtime environment is focused.
*/
function buildRepoHostIndex(repos: readonly Repo[]): Map<string, ExecutionHostId> {
const hostIdByRepoId = new Map<string, ExecutionHostId>()
for (const repo of repos) {
if (repo.connectionId || repo.executionHostId) {
hostIdByRepoId.set(repo.id, getRepoExecutionHostId(repo))
}
}
return hostIdByRepoId
}
export function resolveWorktreeFilterHostId(
worktree: Pick<Worktree, 'repoId' | 'hostId'>,
hostIdByRepoId: ReadonlyMap<string, ExecutionHostId>,
defaultHostId: ExecutionHostId
): ExecutionHostId {
// Why: same precedence as getWorktreeExecutionHostId without re-resolving the
// repo per worktree — the repo host is precomputed once for the whole pass.
return worktree.hostId ?? hostIdByRepoId.get(worktree.repoId) ?? defaultHostId
}
/** Repo-derived host for a project row, which owns no worktree of its own. */
export function resolveRepoFilterHostId(
repoId: string,
hostIdByRepoId: ReadonlyMap<string, ExecutionHostId>,
defaultHostId: ExecutionHostId
): ExecutionHostId {
return hostIdByRepoId.get(repoId) ?? defaultHostId
}
type ProjectRow = { key: string; label: string; repoIds: string[] }
function buildProjectRows(
repos: readonly Repo[],
repoMap: Map<string, Repo>,
grouping: ProjectGroupingModel
): { rows: ProjectRow[]; keyByRepoId: Map<string, string> } {
const rows = new Map<string, ProjectRow>()
const keyByRepoId = new Map<string, string>()
for (const repo of repos) {
const target = getProjectHeaderRevealTarget(repo.id, repoMap, grouping)
if (!target.repo) {
continue
}
const existing = rows.get(target.key)
if (existing) {
existing.repoIds.push(repo.id)
} else {
rows.set(target.key, { key: target.key, label: target.label, repoIds: [repo.id] })
}
keyByRepoId.set(repo.id, target.key)
}
return { rows: [...rows.values()], keyByRepoId }
}
export function buildPaletteFilterModel({
repos,
worktrees,
hostOptions,
projects,
projectHostSetups,
defaultHostId = LOCAL_EXECUTION_HOST_ID
}: {
repos: readonly Repo[]
worktrees: readonly Worktree[]
hostOptions: readonly SidebarHostOption[]
projects: readonly Project[]
projectHostSetups: readonly ProjectHostSetup[]
defaultHostId?: ExecutionHostId
}): PaletteFilterModel {
const repoMap = new Map(repos.map((repo) => [repo.id, repo]))
const hostIdByRepoId = buildRepoHostIndex(repos)
const { rows, keyByRepoId } = buildProjectRows(repos, repoMap, { projects, projectHostSetups })
const worktreeCountByHostId = new Map<string, number>()
const worktreeCountByProjectKey = new Map<string, number>()
for (const worktree of worktrees) {
if (worktree.isArchived) {
continue
}
const hostId = resolveWorktreeFilterHostId(worktree, hostIdByRepoId, defaultHostId)
worktreeCountByHostId.set(hostId, (worktreeCountByHostId.get(hostId) ?? 0) + 1)
const projectKey = keyByRepoId.get(worktree.repoId)
if (projectKey) {
worktreeCountByProjectKey.set(
projectKey,
(worktreeCountByProjectKey.get(projectKey) ?? 0) + 1
)
}
}
// Why: options are gated on a live workspace count, not on configuration — an
// option that can only ever yield an empty list is a trap, and it also keeps
// stale selections self-healing through reconcilePaletteFilter.
// Registry order (local first, then SSH/runtime) matches the sidebar host headers.
const hosts = hostOptions
.filter((host) => (worktreeCountByHostId.get(host.id) ?? 0) > 0)
.map((host) =>
toFilterOption({
id: host.id,
label: host.label,
detail: host.detail,
count: worktreeCountByHostId.get(host.id) ?? 0
})
)
// Popularity first so a long project list surfaces busy workspaces without search.
const projectOptions = rows
.filter((row) => (worktreeCountByProjectKey.get(row.key) ?? 0) > 0)
.map((row) =>
toFilterOption({
id: row.key,
label: row.label,
detail: '',
count: worktreeCountByProjectKey.get(row.key) ?? 0
})
)
.sort((a, b) => b.count - a.count || a.label.localeCompare(b.label) || a.id.localeCompare(b.id))
return {
hosts,
projects: projectOptions,
repoIdsByProjectKey: new Map(rows.map((row) => [row.key, row.repoIds])),
hostIdByRepoId,
defaultHostId
}
}
@@ -0,0 +1,214 @@
import { describe, expect, it } from 'vitest'
import type { ExecutionHostId } from '../../../../shared/execution-host'
import {
addPaletteFilterValues,
buildPaletteFilterPredicate,
clearPaletteFilterField,
EMPTY_PALETTE_FILTER,
getPaletteFilterSelectionCount,
isPaletteFilterActive,
PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD,
reconcilePaletteFilter,
togglePaletteFilterValue,
type PaletteFilterState
} from './palette-filter'
import type { PaletteFilterModel } from './palette-filter-options'
import { buildPaletteFilterOptionSearchText } from './palette-filter-option-list'
import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host'
const option = (id: string, count = 1) => ({
id,
label: id,
detail: '',
count,
searchText: buildPaletteFilterOptionSearchText(id, '')
})
// r1 + r2 are two repos behind one project row; r3 is a standalone repo row.
const model: PaletteFilterModel = {
hosts: [option('local'), option('ssh:builder'), option('runtime:env-1')],
projects: [option('project:p1'), option('repo:r3')],
repoIdsByProjectKey: new Map([
['project:p1', ['r1', 'r2']],
['repo:r3', ['r3']]
]),
hostIdByRepoId: new Map<string, ExecutionHostId>([
['r1', 'local'],
['r2', 'ssh:builder'],
['r3', 'runtime:env-1']
]),
defaultHostId: LOCAL_EXECUTION_HOST_ID
}
const filterOf = (hostIds: string[], projectKeys: string[]): PaletteFilterState => ({
hostIds,
projectKeys
})
describe('palette filter state', () => {
it('reports activity and selection count across both fields', () => {
expect(isPaletteFilterActive(EMPTY_PALETTE_FILTER)).toBe(false)
expect(getPaletteFilterSelectionCount(EMPTY_PALETTE_FILTER)).toBe(0)
expect(isPaletteFilterActive(filterOf([], ['project:p1']))).toBe(true)
expect(getPaletteFilterSelectionCount(filterOf(['local'], ['project:p1']))).toBe(2)
})
it('toggles values on and off, keeping each field sorted', () => {
const withHost = togglePaletteFilterValue(EMPTY_PALETTE_FILTER, 'host', 'ssh:builder')
const withBothHosts = togglePaletteFilterValue(withHost, 'host', 'local')
expect(withBothHosts.hostIds).toEqual(['local', 'ssh:builder'])
expect(withBothHosts.projectKeys).toEqual([])
expect(togglePaletteFilterValue(withBothHosts, 'host', 'local').hostIds).toEqual([
'ssh:builder'
])
})
it('keeps the two fields independent', () => {
const filter = togglePaletteFilterValue(
togglePaletteFilterValue(EMPTY_PALETTE_FILTER, 'host', 'local'),
'project',
'project:p1'
)
expect(clearPaletteFilterField(filter, 'project')).toEqual(filterOf(['local'], []))
expect(clearPaletteFilterField(filter, 'host')).toEqual(filterOf([], ['project:p1']))
})
it('refuses selections past the per-field cap', () => {
const saturated = filterOf(
Array.from({ length: PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD }, (_, i) => `ssh:host-${i}`),
[]
)
const next = togglePaletteFilterValue(saturated, 'host', 'ssh:one-too-many')
expect(next.hostIds).toHaveLength(PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD)
expect(next.hostIds).not.toContain('ssh:one-too-many')
// Deselecting still works at the cap, so the user is never stuck.
expect(togglePaletteFilterValue(saturated, 'host', 'ssh:host-0').hostIds).toHaveLength(
PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD - 1
)
})
it('bulk-adds matching ids up to the per-field cap without duplicating', () => {
const withOne = addPaletteFilterValues(EMPTY_PALETTE_FILTER, 'project', [
'project:p1',
'repo:r3',
'project:p1'
])
expect(withOne.projectKeys).toEqual(['project:p1', 'repo:r3'])
const nearCap = filterOf(
Array.from(
{ length: PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD - 1 },
(_, i) => `ssh:host-${i}`
),
[]
)
const filled = addPaletteFilterValues(nearCap, 'host', ['ssh:a', 'ssh:b'])
expect(filled.hostIds).toHaveLength(PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD)
expect(filled.hostIds).toContain('ssh:a')
expect(filled.hostIds).not.toContain('ssh:b')
})
})
describe('reconcilePaletteFilter', () => {
it('returns the same reference when every selection still exists', () => {
const filter = filterOf(['local'], ['project:p1'])
expect(reconcilePaletteFilter(filter, model)).toBe(filter)
expect(reconcilePaletteFilter(EMPTY_PALETTE_FILTER, model)).toBe(EMPTY_PALETTE_FILTER)
})
it('drops selections whose host or project disappeared', () => {
const filter = filterOf(['local', 'ssh:deleted'], ['project:p1', 'repo:removed'])
expect(reconcilePaletteFilter(filter, model)).toEqual(filterOf(['local'], ['project:p1']))
})
it('empties a filter whose every selection is gone', () => {
const reconciled = reconcilePaletteFilter(filterOf(['ssh:deleted'], []), model)
expect(isPaletteFilterActive(reconciled)).toBe(false)
})
})
describe('buildPaletteFilterPredicate', () => {
it('returns null when no filter is active so callers can skip the pass', () => {
expect(buildPaletteFilterPredicate(EMPTY_PALETTE_FILTER, model)).toBeNull()
})
it('matches worktrees on the host axis, preferring the worktree stamp over the repo', () => {
const predicate = buildPaletteFilterPredicate(filterOf(['ssh:builder'], []), model)
expect(predicate?.matchesWorktree({ repoId: 'r2' })).toBe(true)
expect(predicate?.matchesWorktree({ repoId: 'r1' })).toBe(false)
// A workspace stamped onto another host follows its own stamp, not the repo's.
expect(predicate?.matchesWorktree({ repoId: 'r1', hostId: 'ssh:builder' })).toBe(true)
expect(predicate?.matchesWorktree({ repoId: 'r2', hostId: 'local' })).toBe(false)
})
it('treats an unknown repo as local', () => {
const local = buildPaletteFilterPredicate(filterOf(['local'], []), model)
expect(local?.matchesWorktree({ repoId: 'never-seen' })).toBe(true)
})
it('matches every repo behind a multi-repo project row', () => {
const predicate = buildPaletteFilterPredicate(filterOf([], ['project:p1']), model)
expect(predicate?.matchesWorktree({ repoId: 'r1' })).toBe(true)
expect(predicate?.matchesWorktree({ repoId: 'r2' })).toBe(true)
expect(predicate?.matchesWorktree({ repoId: 'r3' })).toBe(false)
expect(predicate?.matchesProjectRowKey('project:p1')).toBe(true)
expect(predicate?.matchesProjectRowKey('repo:r3')).toBe(false)
})
it('keeps a project row whose repos straddle hosts under either host filter', () => {
// project:p1 is checked out on local (r1) and ssh:builder (r2) — filtering to
// either host must keep the single row that represents both.
for (const hostId of ['local', 'ssh:builder']) {
const predicate = buildPaletteFilterPredicate(filterOf([hostId], []), model)
expect(predicate?.matchesProjectRowKey('project:p1')).toBe(true)
}
const runtimeOnly = buildPaletteFilterPredicate(filterOf(['runtime:env-1'], []), model)
expect(runtimeOnly?.matchesProjectRowKey('project:p1')).toBe(false)
expect(runtimeOnly?.matchesProjectRowKey('repo:r3')).toBe(true)
})
it('ORs within a field and ANDs across fields', () => {
const ored = buildPaletteFilterPredicate(filterOf([], ['project:p1', 'repo:r3']), model)
expect(ored?.matchesWorktree({ repoId: 'r1' })).toBe(true)
expect(ored?.matchesWorktree({ repoId: 'r3' })).toBe(true)
// Project p1 spans local (r1) and ssh:builder (r2); adding the host axis
// narrows to the intersection rather than widening the result set.
const anded = buildPaletteFilterPredicate(filterOf(['local'], ['project:p1']), model)
expect(anded?.matchesWorktree({ repoId: 'r1' })).toBe(true)
expect(anded?.matchesWorktree({ repoId: 'r2' })).toBe(false)
expect(anded?.matchesProjectRowKey('project:p1')).toBe(true)
expect(anded?.matchesProjectRowKey('repo:r3')).toBe(false)
})
it('never matches a stale project key that resolves to no repos', () => {
const predicate = buildPaletteFilterPredicate(filterOf([], ['project:gone']), model)
expect(predicate?.matchesWorktree({ repoId: 'r1' })).toBe(false)
expect(predicate?.matchesProjectRowKey('project:p1')).toBe(false)
})
it('keeps group rows on the host axis only', () => {
const hostOnly = buildPaletteFilterPredicate(filterOf(['ssh:builder'], []), model)
expect(hostOnly?.matchesGroupHostId('ssh:builder')).toBe(true)
expect(hostOnly?.matchesGroupHostId('local')).toBe(false)
// A group header belongs to no project, so any project selection excludes it.
const withProject = buildPaletteFilterPredicate(
filterOf(['ssh:builder'], ['project:p1']),
model
)
expect(withProject?.matchesGroupHostId('ssh:builder')).toBe(false)
})
})
@@ -0,0 +1,188 @@
import type { ExecutionHostId } from '../../../../shared/execution-host'
import type { Worktree } from '../../../../shared/types'
import {
resolveRepoFilterHostId,
resolveWorktreeFilterHostId,
type PaletteFilterModel
} from './palette-filter-options'
export type PaletteFilterField = 'host' | 'project'
/**
* Sorted arrays rather than Sets: identity is stable across renders and the
* serialized form is a cheap memo dependency for the palette's search passes.
*/
export type PaletteFilterState = {
hostIds: readonly string[]
projectKeys: readonly string[]
}
export const EMPTY_PALETTE_FILTER: PaletteFilterState = { hostIds: [], projectKeys: [] }
/** Guard against a pathological selection blowing up the predicate's Set build. */
export const PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD = 500
export function isPaletteFilterActive(filter: PaletteFilterState): boolean {
return filter.hostIds.length > 0 || filter.projectKeys.length > 0
}
export function getPaletteFilterSelectionCount(filter: PaletteFilterState): number {
return filter.hostIds.length + filter.projectKeys.length
}
function toggleValue(values: readonly string[], id: string): readonly string[] {
if (values.includes(id)) {
return values.filter((value) => value !== id)
}
// Why: same reference on the capped no-op — a fresh array would invalidate
// every downstream search memo for a click that changed nothing.
if (values.length >= PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD) {
return values
}
return [...values, id].sort()
}
export function togglePaletteFilterValue(
filter: PaletteFilterState,
field: PaletteFilterField,
id: string
): PaletteFilterState {
return field === 'host'
? { ...filter, hostIds: toggleValue(filter.hostIds, id) }
: { ...filter, projectKeys: toggleValue(filter.projectKeys, id) }
}
function addValues(values: readonly string[], ids: readonly string[]): readonly string[] {
if (ids.length === 0 || values.length >= PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD) {
return values
}
const merged = new Set(values)
const sizeBefore = merged.size
for (const id of ids) {
if (merged.size >= PALETTE_FILTER_MAX_SELECTIONS_PER_FIELD) {
break
}
merged.add(id)
}
// Why: same reference when nothing new fit — keeps search memos stable.
if (merged.size === sizeBefore) {
return values
}
return [...merged].sort()
}
/** Bulk-add for "Select all matching"; respects the per-field cap and de-dupes. */
export function addPaletteFilterValues(
filter: PaletteFilterState,
field: PaletteFilterField,
ids: readonly string[]
): PaletteFilterState {
return field === 'host'
? { ...filter, hostIds: addValues(filter.hostIds, ids) }
: { ...filter, projectKeys: addValues(filter.projectKeys, ids) }
}
export function clearPaletteFilterField(
filter: PaletteFilterState,
field: PaletteFilterField
): PaletteFilterState {
return field === 'host' ? { ...filter, hostIds: [] } : { ...filter, projectKeys: [] }
}
function pruneToAvailable(values: readonly string[], available: ReadonlySet<string>): string[] {
return values.filter((value) => available.has(value))
}
/**
* Drops selections whose host or project disappeared (repo removed, SSH target
* deleted). Without this a stale id would silently empty the palette forever.
* Returns the same reference when nothing changed so memo deps stay stable.
*/
export function reconcilePaletteFilter(
filter: PaletteFilterState,
model: PaletteFilterModel
): PaletteFilterState {
if (!isPaletteFilterActive(filter)) {
return filter
}
const hostIds = pruneToAvailable(filter.hostIds, new Set(model.hosts.map((host) => host.id)))
const projectKeys = pruneToAvailable(
filter.projectKeys,
new Set(model.projects.map((project) => project.id))
)
if (
hostIds.length === filter.hostIds.length &&
projectKeys.length === filter.projectKeys.length
) {
return filter
}
return { hostIds, projectKeys }
}
export type PaletteFilterPredicate = {
matchesWorktree: (worktree: Pick<Worktree, 'repoId' | 'hostId'>) => boolean
/** Keyed on the row, not a repo: one project row can span repos on several hosts. */
matchesProjectRowKey: (rowKey: string) => boolean
/** Project-group rows carry their own host stamp and belong to no single repo. */
matchesGroupHostId: (hostId: ExecutionHostId) => boolean
}
/**
* Returns null when no filter is active so callers can skip the pass entirely
* rather than paying an identity-predicate call per row.
*/
export function buildPaletteFilterPredicate(
filter: PaletteFilterState,
model: PaletteFilterModel
): PaletteFilterPredicate | null {
if (!isPaletteFilterActive(filter)) {
return null
}
const selectedHostIds = filter.hostIds.length > 0 ? new Set(filter.hostIds) : null
const selectedProjectKeys = filter.projectKeys.length > 0 ? new Set(filter.projectKeys) : null
let selectedRepoIds: Set<string> | null = null
if (selectedProjectKeys) {
selectedRepoIds = new Set<string>()
for (const projectKey of selectedProjectKeys) {
for (const repoId of model.repoIdsByProjectKey.get(projectKey) ?? []) {
selectedRepoIds.add(repoId)
}
}
}
return {
matchesProjectRowKey: (rowKey) => {
if (selectedProjectKeys && !selectedProjectKeys.has(rowKey)) {
return false
}
if (!selectedHostIds) {
return true
}
// Why: the row survives if *any* of its repos is on a selected host — a
// project checked out on both local and SSH is still reachable from either.
return (model.repoIdsByProjectKey.get(rowKey) ?? []).some((repoId) =>
selectedHostIds.has(
resolveRepoFilterHostId(repoId, model.hostIdByRepoId, model.defaultHostId)
)
)
},
matchesWorktree: (worktree) => {
if (selectedRepoIds && !selectedRepoIds.has(worktree.repoId)) {
return false
}
if (!selectedHostIds) {
return true
}
// Why: worktree.hostId wins over the repo fallback — a runtime-owned
// workspace can live on a different host than the repo it came from.
return selectedHostIds.has(
resolveWorktreeFilterHostId(worktree, model.hostIdByRepoId, model.defaultHostId)
)
},
// Why: a group header is not a project, so an explicit project selection
// excludes every group row; only the host axis can keep one.
matchesGroupHostId: (hostId) =>
selectedRepoIds === null && (!selectedHostIds || selectedHostIds.has(hostId))
}
}
@@ -35,6 +35,21 @@ describe('getPaletteHostBadge', () => {
expect(getPaletteHostBadge({ connectionId: null }, hosts)).toBeNull()
})
it('badges a disconnected host anyway when a host filter is applied', () => {
const hosts = buildSidebarHostOptions({
repos: [{ connectionId: 'ssh-1' }],
sshTargetLabels: new Map([['ssh-1', 'Builder']]),
settings: { activeRuntimeEnvironmentId: null }
})
// Why: with a host filter on, the badge is the only thing explaining which
// rows survived, so liveness must not suppress it.
expect(getPaletteHostBadge({ connectionId: 'ssh-1' }, hosts, true)).toEqual({
hostId: 'ssh:ssh-1',
label: 'Builder'
})
})
it('badges the local host when a connected remote host exists', () => {
const hosts = buildSidebarHostOptions({
repos: [{ connectionId: 'ssh-1' }],
@@ -23,9 +23,12 @@ function hasActiveRemoteHost(hostOptions: readonly SidebarHostOption[]): boolean
export function getPaletteHostBadge(
repo: Pick<Repo, 'connectionId' | 'executionHostId'> | null | undefined,
hostOptions: readonly SidebarHostOption[]
hostOptions: readonly SidebarHostOption[],
// Why: with a host filter applied the badge is the only thing explaining which
// rows survived, so it must show even when every remote is disconnected.
alwaysShowHostLabel = false
): PaletteHostBadge | null {
if (!repo || !hasActiveRemoteHost(hostOptions)) {
if (!repo || (!alwaysShowHostLabel && !hasActiveRemoteHost(hostOptions))) {
return null
}
const hostId = getRepoExecutionHostId(repo)
@@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest'
import { capPaletteSection, PALETTE_SECTION_RENDER_CAP } from './palette-section-render-cap'
const range = (count: number): number[] => Array.from({ length: count }, (_, index) => index)
describe('capPaletteSection', () => {
it('returns the original array reference when nothing overflows', () => {
const items = range(PALETTE_SECTION_RENDER_CAP)
const capped = capPaletteSection(items)
expect(capped.visible).toBe(items)
expect(capped.overflowCount).toBe(0)
})
it('keeps the top matches and reports the remainder', () => {
const capped = capPaletteSection(range(448))
expect(capped.visible).toHaveLength(PALETTE_SECTION_RENDER_CAP)
expect(capped.visible[0]).toBe(0)
expect(capped.visible.at(-1)).toBe(PALETTE_SECTION_RENDER_CAP - 1)
expect(capped.overflowCount).toBe(448 - PALETTE_SECTION_RENDER_CAP)
})
it('handles an empty section', () => {
expect(capPaletteSection([])).toEqual({ visible: [], overflowCount: 0 })
})
it('ignores a nonsensical cap rather than rendering nothing', () => {
const items = range(3)
expect(capPaletteSection(items, -1).visible).toBe(items)
expect(capPaletteSection(items, Number.NaN).visible).toBe(items)
})
it('supports an explicit cap of zero', () => {
expect(capPaletteSection(range(3), 0)).toEqual({ visible: [], overflowCount: 3 })
})
})
@@ -0,0 +1,24 @@
/**
* Typed queries used to render every match as a DOM row — a one-character query
* against a few hundred workspaces built hundreds of `CommandItem`s (each with
* status dots, badges and highlight spans) on every keystroke. Capping the
* rendered slice bounds worst-case DOM without changing ranking: the top matches
* are already the ones the user wants, and the overflow hint points at the two
* ways to reach the rest.
*/
export const PALETTE_SECTION_RENDER_CAP = 50
export type CappedPaletteSection<T> = {
visible: readonly T[]
overflowCount: number
}
export function capPaletteSection<T>(
items: readonly T[],
cap: number = PALETTE_SECTION_RENDER_CAP
): CappedPaletteSection<T> {
if (!Number.isFinite(cap) || cap < 0 || items.length <= cap) {
return { visible: items, overflowCount: 0 }
}
return { visible: items.slice(0, cap), overflowCount: items.length - cap }
}
@@ -92,10 +92,13 @@ function CommandInput({
className,
wrapperClassName,
iconClassName,
trailing,
...props
}: React.ComponentProps<typeof CommandPrimitive.Input> & {
wrapperClassName?: string
iconClassName?: string
/** Rendered after the field, inside the input frame (e.g. a filter control). */
trailing?: React.ReactNode
}) {
return (
<div
@@ -114,6 +117,7 @@ function CommandInput({
)}
{...props}
/>
{trailing}
</div>
)
}
+27
View File
@@ -109,6 +109,33 @@
"mr": "MR",
"port": "Port",
"pr": "PR"
},
"renderCapOverflow": "{{value0}} more - keep typing or add a filter to narrow",
"filter": {
"emptyTitle": "No results match the active filter",
"emptySubtitle": "Clear the filter above, or widen it to more hosts and projects.",
"tabKey": "Tab",
"label": "Filter",
"activeCount": "{{value0}} active",
"removeChip": "Remove filter {{value0}}",
"chipOverflow": "+{{value0}}",
"clearAll": "Clear all",
"hosts": "Hosts",
"projects": "Projects",
"trigger": "Filter results",
"search": "Filter by host or project...",
"searchHosts": "Filter hosts...",
"searchProjects": "Filter projects...",
"noOptions": "No matching hosts or projects",
"noHosts": "No matching hosts",
"noProjects": "No matching projects",
"moreOptions": "{{value0}} more - keep typing to narrow",
"selectAllMatching": "Select all matching ({{value0}})",
"selectedCollapsed": "{{value0}} selected — remove via chips or Clear",
"clearHosts": "Clear hosts",
"clearProjects": "Clear projects",
"back": "Back",
"ariaActive": "Filter: {{value0}} active."
}
},
"auto": {
@@ -0,0 +1,184 @@
import type { Page } from '@stablyai/playwright-test'
import { expect, test } from './helpers/orca-app'
import { waitForActiveWorktree, waitForSessionReady } from './helpers/store'
const LOCAL_PROJECT = 'E2E Palette Local Project'
const REMOTE_PROJECT = 'E2E Palette Remote Project'
const REMOTE_WORKSPACE = 'E2E Palette Remote Workspace'
const REMOTE_HOST = 'E2E Palette Builder'
type PaletteFilterFixture = { localWorktreeId: string; remoteWorktreeId: string }
async function seedPaletteFilterFixture(page: Page): Promise<PaletteFilterFixture> {
return page.evaluate(
({ localProject, remoteHost, remoteProject, remoteWorkspace }) => {
const store = window.__store
if (!store) {
throw new Error('window.__store is unavailable')
}
const state = store.getState()
const sourceRepo = state.repos[0]
const sourceWorktree = Object.values(state.worktreesByRepo)
.flat()
.find((worktree) => worktree.repoId === sourceRepo?.id && !worktree.isArchived)
if (!sourceRepo || !sourceWorktree) {
throw new Error('Palette filter E2E needs the seeded local repository')
}
const token = crypto.randomUUID()
const remoteConnectionId = `e2e-palette-host-${token}`
const remoteRepoId = `e2e-palette-remote-repo-${token}`
const remoteWorktreeId = `e2e-palette-remote-worktree-${token}`
const remoteRepo = {
...sourceRepo,
id: remoteRepoId,
path: `${sourceRepo.path}-e2e-palette-remote-${token}`,
displayName: remoteProject,
connectionId: remoteConnectionId,
executionHostId: `ssh:${remoteConnectionId}`
}
const remoteWorktree = {
...sourceWorktree,
id: remoteWorktreeId,
repoId: remoteRepoId,
path: `${sourceWorktree.path}-e2e-palette-remote-${token}`,
displayName: remoteWorkspace,
title: remoteWorkspace,
branch: 'refs/heads/e2e-palette-remote',
isMainWorktree: false,
isArchived: false,
hostId: `ssh:${remoteConnectionId}`
}
const sshTargetLabels = new Map(state.sshTargetLabels)
sshTargetLabels.set(remoteConnectionId, remoteHost)
// Filter options use project.displayName when a Project entity exists;
// renaming only the repo leaves the option labeled with the path basename.
const projects = state.projects.map((project) =>
project.sourceRepoIds.includes(sourceRepo.id)
? { ...project, displayName: localProject }
: project
)
store.setState({
repos: [
...state.repos.map((repo) =>
repo.id === sourceRepo.id ? { ...repo, displayName: localProject } : repo
),
remoteRepo
],
projects,
sshTargetLabels,
worktreesByRepo: {
...state.worktreesByRepo,
[sourceRepo.id]: (state.worktreesByRepo[sourceRepo.id] ?? []).map((worktree) =>
worktree.id === sourceWorktree.id ? { ...worktree, hostId: 'local' } : worktree
),
[remoteRepoId]: [remoteWorktree]
}
})
return { localWorktreeId: sourceWorktree.id, remoteWorktreeId }
},
{
localProject: LOCAL_PROJECT,
remoteHost: REMOTE_HOST,
remoteProject: REMOTE_PROJECT,
remoteWorkspace: REMOTE_WORKSPACE
}
)
}
function worktreeRow(page: Page, worktreeId: string) {
return palette(page).locator(`[cmdk-item][data-value="worktree:${worktreeId}"]`)
}
function palette(page: Page) {
return page.getByRole('dialog', { name: 'Jump to...' })
}
function filterTrigger(page: Page) {
return page.getByRole('button', { name: 'Filter results' })
}
async function openPalette(page: Page): Promise<void> {
await page.evaluate(() => window.__store?.getState().openModal('worktree-palette'))
await expect(palette(page)).toBeVisible()
}
async function searchFixtureWorkspaces(page: Page, fixture: PaletteFilterFixture): Promise<void> {
const input = palette(page).getByPlaceholder('Search worktrees, settings, tabs, and actions...')
await input.fill('E2E Palette')
await expect(worktreeRow(page, fixture.localWorktreeId)).toBeVisible()
await expect(worktreeRow(page, fixture.remoteWorktreeId)).toBeVisible()
}
async function selectRemoteHost(page: Page, useKeyboard = false): Promise<void> {
if (useKeyboard) {
const input = palette(page).getByPlaceholder('Search worktrees, settings, tabs, and actions...')
await input.press('Tab')
await expect(filterTrigger(page)).toBeFocused()
await filterTrigger(page).click()
} else {
await filterTrigger(page).click()
}
await expect(palette(page).getByText('Hosts', { exact: true })).toBeVisible()
await palette(page).getByText('Hosts', { exact: true }).click()
const hosts = palette(page).getByRole('listbox', { name: 'Hosts' })
await expect(hosts.getByRole('option', { name: REMOTE_HOST })).toBeVisible()
await hosts.getByRole('option', { name: REMOTE_HOST }).click()
await filterTrigger(page).click()
}
test.describe('Worktree jump-palette filters', () => {
test.beforeEach(async ({ orcaPage }) => {
await waitForSessionReady(orcaPage)
await waitForActiveWorktree(orcaPage)
})
test('filters workspace results by host, intersects project selection, and resets on close', async ({
orcaPage
}) => {
const fixture = await seedPaletteFilterFixture(orcaPage)
await openPalette(orcaPage)
await searchFixtureWorkspaces(orcaPage, fixture)
// P1: keyboard focus reaches the control; its rendered selection narrows rows.
await selectRemoteHost(orcaPage, true)
await expect(filterTrigger(orcaPage)).toContainText('1')
await expect(palette(orcaPage).getByLabel(`Remove filter ${REMOTE_HOST}`)).toBeVisible()
await expect(worktreeRow(orcaPage, fixture.remoteWorktreeId)).toBeVisible()
await expect(worktreeRow(orcaPage, fixture.localWorktreeId)).toHaveCount(0)
// P2: host and project fields intersect, with the filter-specific empty state.
await palette(orcaPage)
.getByPlaceholder('Search worktrees, settings, tabs, and actions...')
.fill('')
await filterTrigger(orcaPage).click()
await palette(orcaPage).getByText('Projects', { exact: true }).click()
const projects = palette(orcaPage).getByRole('listbox', { name: 'Projects' })
const localProject = projects.getByRole('option', { name: LOCAL_PROJECT })
await expect(localProject).toBeVisible()
await localProject.click()
await filterTrigger(orcaPage).click()
await expect(palette(orcaPage).getByText('No results match the active filter')).toBeVisible()
await expect(
palette(orcaPage).getByText('Clear the filter above, or widen it to more hosts and projects.')
).toBeVisible()
// P3: clear restores both rows; closing drops the ephemeral filter.
await filterTrigger(orcaPage).click()
await palette(orcaPage).getByRole('button', { name: 'Clear all' }).last().click()
await filterTrigger(orcaPage).click()
await expect(filterTrigger(orcaPage)).not.toContainText('1')
await searchFixtureWorkspaces(orcaPage, fixture)
await selectRemoteHost(orcaPage)
await orcaPage.evaluate(() => window.__store?.getState().closeModal())
await expect(palette(orcaPage)).toBeHidden()
await openPalette(orcaPage)
await searchFixtureWorkspaces(orcaPage, fixture)
await expect(filterTrigger(orcaPage)).not.toContainText('1')
})
})