feat(frontend): use unified drill picker for AI chat @-mention dropdown (#9159)

* feat(frontend): use unified drill picker for AI chat @-mention dropdown

* fix(frontend): chat picker review followups + overlay alignment

- AIChatDisplay: migrate @-badge popover to ChatContextPicker (was still
  importing the deleted AvailableContextList after the rebase onto #9034,
  causing a build break).
- DrillPicker: handle Tab as Enter so the inline @<word> mention completes
  without losing focus. Tweak leaf-row weight to font-normal; secondary
  text uses text-hint.
- ContextTextarea: drop px-0.5 from the highlight span — extra horizontal
  padding made every glyph typed after a mention drift right of the
  invisible textarea below. box-decoration-clone keeps the rounded corners.
- ContextElementBadge: explicit font-normal label, hoist label into a
  {@const} and pass to title= so the truncated badge shows the full title
  on hover.
- workspaceTree: drop orphaned doc-comment left dangling by the rebase.
- Add unit tests for drillPicker.ts and workspaceTree.ts (51 tests cover
  resolveScope/scopeChain/collectLeavesGrouped/leafHaystack, buildWorkspaceTree
  shape + loading + dir forest + leaf shape, withCurrent rename suppression,
  extraItemsByKind dedup, legacyScopeToPath, relativizeWorkspacePath).

* fix(flow-editor): ignore keyboard shortcuts when focus is outside the flow root

Menus, modals, drawers etc. live outside the flow root and capture focus
explicitly. Flow nodes aren't focusable, so the unfocused default
(activeElement === body) means "flow is the canvas" and we should react;
anything else means another surface has the user's attention and our
shortcuts would steal it.

* fix(frontend): inline @ mention picker + chat layout polish

- ContextTextarea: swap manual Portal+caret-math positioning for
  svelte-floating-ui anchored at the `@` character (virtual reference,
  middleware [offset, flip(crossAxis:false), shift]). Picker stays
  pinned to `@` while the user types the query, slides leftward when
  hitting the right edge instead of flipping alignment, and floating-ui
  handles above-vs-below + edge clamping automatically. Drops the
  60vh-worst-case reservation that left a big gap above the caret in
  sessions, and the now-unused isFirstMessage prop is marked deprecated.
- AIChatDisplay: the `@`-button Popover now opens with placement
  bottom-start (was the default `bottom`), aligning its left edge with
  the button instead of centering under it.
- ChatContextPicker: when no Diffs/Modules/Databases branches are
  present (e.g. global chat), return the Workspace tree's children at
  the root instead of wrapping them under a redundant "Workspace" row.
  handleScopeChange handles both the wrapped and unwrapped layouts and
  the single-kind `dir:` top segment.

* chore(frontend): address review suggestions on chat picker PR

- DrillPicker: clamp width to viewport on narrow screens —
  w-[420px] → w-[min(420px,calc(100vw-20px))].
- workspaceTree.buildWorkspaceTree: make loadingKind optional (defaults
  to {}). Chat picker still passes it; callers that don't track loading
  no longer need to thread an empty object.
- ChatContextPicker.handleScopeChange: name the WRAPPED vs UNWRAPPED
  layouts in a comment block so the dir:/kind: branches are obvious.
- ContextTextarea: drop deprecated isFirstMessage prop (floating-ui
  handles direction); drop defensive Math.max on the @ index now that
  the invariant is documented; comment the floatingRef(anchorRef) call
  as the supported virtual-reference path in svelte-floating-ui.
- AIChatInput: stop forwarding isFirstMessage to ContextTextarea.

* feat(frontend): sync selectedContext with @-mentions in textarea

Both picker entry points now insert a visible `@title` token in the
textarea, and deleting that token drops the matching entry from
selectedContext.

- AIChatInput: new insertMention(title) export. Appends `@title ` to
  instructions, prefixing a space only if the existing text doesn't
  already end in whitespace.
- AIChatDisplay: the `@`-button popover calls insertMention after
  addContextToSelection so its picks match the inline-mention path's
  textarea state.
- ContextTextarea: new onRemoveContext callback. A $effect compares the
  set of `@title` tokens in `value` (derived) against the previous
  snapshot; titles that disappeared trigger onRemoveContext for any
  selectedContext entry with `deletable !== false`. The diff lives in
  an effect (not handleInput) so it catches both keystroke deletions
  AND programmatic value updates from updateInstructionsWithContext.
- AIChatInput: passes onRemoveContext that filters selectedContext by
  type+title — mirrors the existing badge X-button handler.

* chore(frontend): narrow ChatContextPicker `inner` from `any` to `DrillPicker | undefined`

The previous `let inner: any` worked around svelte-check rejecting
`DrillPicker<ChatLeafData>` (the imported component is seen as the
non-generic `Comp`). Dropping the type parameter keeps the workaround
without `any`, so handleKeydown / pickHighlighted are at least typed
at the call site.

Addresses May-14 PR review.

* fix(frontend): address PR #9159 bot-review findings (eager preload, focus, dedup, icon types)

- [P1] ChatContextPicker.handleScopeChange: stop preloading workspace
  kinds at the wrapped picker root. New `isWorkspaceOnly` $derived (true
  when no Diffs/Modules/Databases branches are present) gates the at-
  root preload, so the chat root no longer fires two list requests
  before the user enters Workspace. Reported by Codex.
- [P2] AIChatDisplay @-button popover: call aiChatInput.focusInput()
  after close() so the textarea is focused for immediate typing — mirrors
  the inline-mention path's setTimeout(textarea.focus, 0). Reported by
  Claude.
- [P2] AIChatInput.insertMention: no-op when the `@title` token is
  already present in instructions, so re-picking a workspace item
  doesn't leave duplicate visible tokens for a single selectedContext
  entry. Reported by Codex.
- [P2] drillPicker.ts: introduce `DrillIcon = ComponentType |
  Component<any, {}, ''>` and replace `icon: any` on DrillLeaf,
  DrillBranch, and ChatContextPicker.buildContextBranch. Mirrors the
  ComponentType | Component pattern used in TriggersBadge.svelte for
  the same Svelte 4/5 compatibility window. Reported by Pi.

* fix(frontend): preserve workspace context on refresh + load all kinds for internal search

- [P1, Codex] ContextManager.updateAvailableContextForScript/Flow:
  preserve workspace_script and workspace_flow entries through the
  selectedContext filter on editor refresh. They're user-picked refs
  that don't appear in availableContext, so the previous filter was
  silently dropping them whenever the script/flow editor refreshed
  options (e.g. on any code change).
- [P2, cubic-dev-ai] WorkspaceItemDrillPicker: in internal-search mode
  (externalFilter === undefined, DrillPicker renders its own search
  box), preload all kinds on mount. Without this, typing in the
  picker's search before clicking a kind branch produced incomplete
  results since DrillPicker can't reach back through the adapter to
  trigger fetches on internalFilter change. Cached items keep the
  effective cost near-zero on warm sessions.

* fix(frontend): preserve workspace refs through script-mode context refresh

The script-mode updateAvailableContext overwrites newSelectedContext
with a fresh [code] entry, defeating the workspace_script /
workspace_flow preservation in the later filter — the entries are
already gone by the time the filter runs.

Seed newSelectedContext with the refreshed code block AND the user-
picked workspace_script / workspace_flow / code_piece entries from
currentlySelectedContext, so editor refreshes don't wipe @-mention
badges in script chat. The existing line-271 filter still validates
each entry against newAvailableContext + the per-type allowlist.

Reported by Codex on PR #9159 — completes the prior workspace-context-
on-refresh fix (b02d1f2d35) which only patched the filter, not the
rebuild step that runs before it.

* fix(frontend): preserve all previously-selected contexts on script refresh

The prior c2775fe0c5 fix only carried over workspace_script /
workspace_flow / code_piece entries from currentlySelectedContext.
That preserved the workspace P1 path but still dropped previously-
selected diff / error / db / runtime-context badges, which cubic
flagged in its 16:55 review.

Spread the full currentlySelectedContext (minus `code`, which we just
rebuilt). The downstream filter validates each entry against
newAvailableContext + the per-type allowlist, so auto-derived types
like diff / error / db survive when still applicable, and unrelated
items are dropped automatically.

Reported by cubic-dev-ai on PR #9159.

* fix(frontend): rehydrate auto-derived context + sync badge X with textarea

- [P2, cubic] ContextManager.updateAvailableContext: when the rebuild
  carries over previously-selected diff/error/db entries, swap each one
  for the matching freshly-built entry from newAvailableContext in the
  final .map() step. Preserves the user's `deletable` override on top
  of the fresh content/diff/schema, so refreshes don't keep stale
  payloads while still surviving the badge across edits.
- [P2, Pi/Codex] AIChatInput: new `removeMention(title)` export that
  strips `@title` tokens from `instructions` (whitespace-bounded so
  substring matches don't bleed). The badge X-button now calls it
  after filtering selectedContext, mirroring the inverse textarea-to-
  badge sync. No double-remove: ContextTextarea's $effect-driven
  onRemoveContext is a no-op once selectedContext no longer holds the
  entry.

* fix(frontend): retype ChatContextPicker.inner to DrillPicker<ChatLeafData>

`npm run check:fast` (TypeScript-only) and `npm run check` (svelte-check)
disagree on whether the imported DrillPicker is generic — `check:fast`
sees it as `Comp` and rejects the type parameter, while `svelte-check`
sees the real generic component and requires it. CI runs `check`, so
follow that: `DrillPicker<ChatLeafData> | undefined`.

This also fully replaces the prior `inner: any` workaround called out in
multiple bot reviews — handleKeydown / pickHighlighted now type-check at
the call site against the correct component instance.

* fix(frontend): scope removeMention's whitespace collapse to the mention site

The trailing `.replace(/  +/g, ' ')` in `removeMention` was global,
collapsing any pre-existing double-spaces in the prompt — e.g. a user
typing `"hello  world  @foo  bar"` lost their intentional formatting
when they deleted the `@foo` badge.

Rework the regex to match `(^|\s)@title(\s|$)` and decide per-match:
- Mention at a boundary (no lead or no trail): drop entirely.
- Mention in the middle: keep ONE bordering whitespace char (the
  leading one verbatim, so newlines/tabs aren't downgraded to spaces).

No global pass over `instructions`. Unrelated whitespace stays intact.

Reported by cubic-dev-ai on PR #9159 (07:27 review of 9e07eac4).

* fix(frontend): expose DrillPicker.onFilterChange + lazy-load workspace kinds

Both Codex P1s came from over-eager preload heuristics on my prior fixes:
the workspace picker cold-loaded every configured kind on mount in
internal-filter mode, and the chat badge popover never observed its own
internal filter so workspace results were missing from search until the
user drilled into Workspace.

Replace both ad-hoc effects with a single `onFilterChange` callback on
DrillPicker that fires whenever the EFFECTIVE filter (external or
internal) changes:

- [P1] WorkspaceItemDrillPicker: drop the "cold-load on mount when
  externalFilter === undefined" effect. Workspace kinds now load only
  once the user actually types something — closer to the pre-refactor
  behavior where the breadcrumb / "Open editor" pickers only fetched
  the drilled-into kind plus all kinds on search.
- [P1] ChatContextPicker: handleFilterChange replaces the prior
  externalFilter-only effect. Badge-popover search (internal filter)
  now triggers the same preload as inline-mention search (external
  filter), so workspace results appear without needing to drill first.

Both fixes reported by Codex on PR #9159.

* fix(frontend): skip mention-removal sync when textarea is programmatically cleared

sendRequest() sets `instructions = ''` immediately after dispatching to
AIChatManager. The mention-removal effect treated this as user-initiated
deletion and cleared selectedContext BEFORE AIChatManager.beforeSend
snapshotted it — selected `@` contexts disappeared from the outgoing
request. Skip the sync when value is empty; user-initiated mention
deletes happen in-place against non-empty content.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): scope post-send wipe protection to the send path only

Replace the blanket `if (value !== '')` guard on the mention-removal
effect with an explicit `clearForSend()` export. `sendRequest()` now
calls it instead of `instructions = ''`, so a user manually clearing
the whole textarea still drops the corresponding context badges while
the post-dispatch programmatic wipe is silent.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(frontend): extract useWorkspaceItemsLoader composable shared by both drill picker adapters

WorkspaceItemDrillPicker and ChatContextPicker each duplicated the same
machinery: loaded/loadingKind state seeded from the module cache, a
stale-while-revalidate ensureLoaded coroutine with an untrack guard, a
kind:/dir: scope-segment decoder, and the "load every kind once the user
starts searching" filter callback.

Move that to a single useWorkspaceItemsLoader() returning
{loaded, loadingKind, ensureLoaded, ensureAll, ensureForScopeSegment,
onFilterChange}. Adapters keep their own scope-walking policy (chat
collapses an optional 'workspace' wrapper, workspace handles single-kind
mode) but delegate kind decoding and lazy fetch to the composable.

Net: -135 +28 LOC in the two adapters; +109 LOC in the new composable.
The cache-version race, untrack discipline, and stale-while-revalidate
semantics now live in one place.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): address Codex P1+P2s — non-context clear, same-title cross-removal, single-kind cold load

P1: sendRequest() now clears `instructions` unconditionally after the
optional `clearForSend()` so APP/NAVIGATOR/ASK/API modes (which don't
mount ContextTextarea) still reset the input after send.

P2: removeMention() now calls a new `unsyncMention(title)` on the
textarea before stripping `@title` from `value`, so the mention-removal
effect doesn't fire a second onRemoveContext on a same-title sibling
(e.g. workspace_script + workspace_flow sharing a path).

P2: single-kind WorkspaceItemDrillPicker loads its kind at mount even
when scope is empty — buildWorkspaceTree collapses to the kind's
children, so there's no kind row to drill into to trigger the load.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Guilhem
2026-06-08 13:52:41 +02:00
committed by GitHub
parent 6156e2372a
commit 64b089cd23
15 changed files with 2154 additions and 1286 deletions
@@ -0,0 +1,532 @@
<!--
@component
Generic drill-through picker. Renders a tree of branches and leaves; one
level is shown at a time. The host supplies the tree shape — workspace
items, chat context elements, etc. all map to the same component.
- **Root** (no scope): the tree's top-level entries.
- **Branch** (scope = `[...keys]`): the children of the branch resolved
by walking the tree along the scope chain.
Clicking a row drills *down*; the chevron-left in the header walks one
level *up*. Filter (internal or `externalFilter`) is global across all
leaves and ignores the current scope.
-->
<script lang="ts" generics="L">
import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-svelte'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import SearchItems from '$lib/components/SearchItems.svelte'
import { generateRandomString } from '$lib/utils'
import { onMount, untrack, type Snippet } from 'svelte'
import {
collectLeavesGrouped,
leafHaystack,
resolveScope,
scopeChain,
type DrillBranch,
type DrillLeaf,
type DrillNode
} from './drillPicker'
interface Props {
tree: DrillNode<L>[]
onPick: (leaf: DrillLeaf<L>) => void
/** Drill path to land on initially. Empty = root. */
initialScope?: string[]
/** Composite key of the row to highlight initially. */
initialHighlight?: string
/** When set (any string, incl. ''), the host owns search input.
* The internal search field is hidden and the host is expected to
* forward keydown events via `handleKeydown`. */
externalFilter?: string
autoFocus?: boolean
/** Drop the outer fixed width / max height wrapper. */
flush?: boolean
/** Custom renderer for the icon column of a leaf. */
leafIcon?: Snippet<[DrillLeaf<L>]>
/** Custom renderer for the icon column of a branch (used inside
* the entry row AND as the leading icon in the breadcrumb header). */
branchIcon?: Snippet<[DrillBranch<L>]>
/** Override for a leaf row's secondary text in the **drilled view**
* (search results always show `leaf.secondary` to keep absolute
* paths visible globally). Returns `undefined` to defer to
* `leaf.secondary`. Used by the workspace adapter to render
* scope-relative paths once the user has drilled into a folder. */
leafSecondary?: (leaf: DrillLeaf<L>, scope: string[]) => string | undefined
/** Fires whenever the scope changes. Lets the host trigger lazy
* data loading for the branch the user drilled into. */
onScopeChange?: (scope: string[]) => void
/** Fires whenever the EFFECTIVE filter changes (internal OR external).
* Lets the host trigger global preloads when the user starts searching
* — needed in internal-filter mode where the host can't observe the
* picker's own search box otherwise. */
onFilterChange?: (filter: string) => void
}
let {
tree,
onPick,
initialScope,
initialHighlight,
externalFilter,
autoFocus = true,
flush = false,
leafIcon,
branchIcon,
leafSecondary,
onScopeChange,
onFilterChange
}: Props = $props()
let searchInput: TextInput | undefined = $state()
let pickerRoot: HTMLElement | undefined = $state()
const instanceId = generateRandomString(8)
const listboxId = `dpkr-list-${instanceId}`
const idFor = (key: string) => `dpkr-${instanceId}-${key.replace(/[^a-zA-Z0-9-]/g, '_')}`
export function focus() {
searchInput?.focus()
}
// Sibling-popover open: melt-ui's `openFocus` runs once during the
// close→open transition; the picker may not be mounted yet. Retry
// after settle. Skipped when `autoFocus` is false (host keeps focus)
// or when the search input is not rendered (external filter mode).
onMount(() => {
if (!autoFocus || externalFilter !== undefined) return
const t = setTimeout(focus, 50)
return () => clearTimeout(t)
})
let scope = $state<string[]>(untrack(() => initialScope ?? []))
let internalFilter = $state('')
const filter = $derived(externalFilter ?? internalFilter)
const isSearching = $derived(filter.trim() !== '')
$effect(() => {
void scope
onScopeChange?.(scope)
})
$effect(() => {
void filter
onFilterChange?.(filter)
})
/** Tracks whether the last user action was mouse movement (true) or
* keyboard nav (false). When false, row `mouseenter` events are
* ignored — prevents the cursor from stealing the keyboard-driven
* highlight as rows shift under it during scope changes. Re-enabled
* on `mousemove`. Starts `false` so the synthetic `mouseenter` fired
* when the popover mounts under a stationary cursor doesn't clobber
* `initialHighlight`. */
let mouseActive = $state(false)
const currentBranch = $derived(resolveScope(tree, scope))
const entries = $derived<DrillNode<L>[]>(
scope.length === 0 ? tree : (currentBranch?.children ?? [])
)
// Flat leaf pool for global search. Skips branches flagged
// `omitFromSearch` (e.g. workspace cross-kind 'all' branch).
const searchPool = $derived(collectLeavesGrouped(tree))
type SearchEntry = { leaf: DrillLeaf<L>; group: DrillBranch<L> | null; _key: string }
const searchItems = $derived<SearchEntry[]>(
searchPool.map(({ leaf, group }) => ({ leaf, group, _key: leaf.key }))
)
let searchedItems: (SearchEntry & { marked: string })[] | undefined = $state(undefined)
// Group filtered results by their nearest-branch ancestor for display.
const searchResultsByGroup = $derived.by(() => {
const groups = new Map<
string,
{ group: DrillBranch<L> | null; items: (SearchEntry & { marked: string })[] }
>()
if (!searchedItems) return [] as { group: DrillBranch<L> | null; items: SearchEntry[] }[]
for (const r of searchedItems) {
const gkey = r.group?.key ?? '__none'
const existing = groups.get(gkey)
if (existing) existing.items.push(r)
else groups.set(gkey, { group: r.group, items: [r] })
}
return Array.from(groups.values())
})
type Entry =
| { type: 'branch'; key: string; node: DrillBranch<L> }
| { type: 'leaf'; key: string; node: DrillLeaf<L> }
const entryList = $derived<Entry[]>(
entries.map((n) =>
n.type === 'branch'
? { type: 'branch' as const, key: n.key, node: n }
: { type: 'leaf' as const, key: n.key, node: n }
)
)
const navKeys = $derived(
isSearching
? (searchedItems ?? ([] as typeof searchItems)).map((r) => r.leaf.key)
: entryList.map((e) => e.key)
)
let highlightedKey = $state<string | undefined>(untrack(() => initialHighlight))
let highlightedId = $derived(highlightedKey ? idFor(highlightedKey) : undefined)
$effect(() => {
if (navKeys.length === 0) return
if (!highlightedKey || !navKeys.includes(highlightedKey)) {
highlightedKey = navKeys[0]
}
})
$effect(() => {
if (highlightedKey && navKeys.includes(highlightedKey)) {
requestAnimationFrame(scrollHighlightIntoView)
}
})
function scrollHighlightIntoView() {
if (!pickerRoot || !highlightedKey) return
const el = pickerRoot.querySelector<HTMLElement>(
`[data-nav-key="${CSS.escape(highlightedKey)}"]`
)
el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
}
function moveHighlight(delta: 1 | -1) {
if (navKeys.length === 0) return
const cur = navKeys.indexOf(highlightedKey ?? '')
const next = cur < 0 ? 0 : (cur + delta + navKeys.length) % navKeys.length
highlightedKey = navKeys[next]
mouseActive = false
requestAnimationFrame(scrollHighlightIntoView)
}
function setHoverHighlight(key: string) {
// Ignored until the user actually moves the mouse. Prevents the
// cursor (parked over a row) from clobbering keyboard-driven
// selection when the layout shifts beneath it.
if (mouseActive) highlightedKey = key
}
function pick(leaf: DrillLeaf<L>) {
if (leaf.current || leaf.disabled) return
onPick(leaf)
}
function activate(key: string | undefined) {
if (!key) return
if (isSearching) {
const found = (searchedItems ?? []).find((r) => r.leaf.key === key)
if (found) pick(found.leaf)
return
}
const entry = entryList.find((e) => e.key === key)
if (!entry) return
drill(entry)
}
function drill(entry: Entry) {
if (entry.type === 'branch') {
scope = [...scope, entry.key]
} else {
pick(entry.node)
}
}
function goUp() {
if (scope.length === 0) return
const leaving = scope[scope.length - 1]
scope = scope.slice(0, -1)
highlightedKey = leaving
}
function handleSearchKeydown(e: KeyboardEvent) {
if (e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
moveHighlight(1)
} else if (e.key === 'ArrowUp') {
e.preventDefault()
e.stopPropagation()
moveHighlight(-1)
} else if (e.key === 'Enter' || e.key === 'Tab') {
// Tab mirrors Enter so the inline `@<word>` mention completes
// without losing focus to the next form control (matches the
// previous `AvailableContextList` behavior). Guard on a
// highlighted row so an unrelated Tab in an empty picker still
// falls through to natural focus movement.
if (e.key === 'Tab' && !highlightedKey) return
e.preventDefault()
e.stopPropagation()
mouseActive = false
activate(highlightedKey)
} else if (
(e.key === 'ArrowLeft' || e.key === 'Backspace') &&
filter === '' &&
scope.length > 0
) {
// Walk up the tree. Only when search is empty — otherwise these
// keys would hijack cursor movement / character deletion.
e.preventDefault()
e.stopPropagation()
mouseActive = false
goUp()
} else if (e.key === 'ArrowRight' && filter === '' && !isSearching) {
// Drill into the highlighted branch. Leaves are reserved for
// Enter (more deliberate, since picking navigates away).
const entry = entryList.find((en) => en.key === highlightedKey)
if (entry && entry.type === 'branch') {
e.preventDefault()
e.stopPropagation()
mouseActive = false
drill(entry)
}
}
}
export function handleKeydown(e: KeyboardEvent) {
handleSearchKeydown(e)
}
export function pickHighlighted() {
activate(highlightedKey)
}
// Breadcrumb header — labels of branches along the scope chain.
const headerChain = $derived(scopeChain(tree, scope))
const headerSegments = $derived(headerChain.map((b) => b.label))
const headerLabel = $derived(headerSegments.join(' '))
/** Number of intermediate segments to hide behind a `…`. Always keep
* the first segment (kind / category) and the deepest. Bumped up by
* the measurement effect below. */
let hiddenCount = $state(0)
const headerLabelDisplay = $derived.by(() => {
if (headerSegments.length <= 2 || hiddenCount === 0) return headerLabel
return [headerSegments[0], '…', ...headerSegments.slice(1 + hiddenCount)].join(' ')
})
let breadcrumbSpan: HTMLElement | undefined = $state()
let lastSegmentsKey = ''
/** Measurement loop: each pass reads `scrollWidth > clientWidth` on
* the truncated span; if overflowing and there's still an intermediate
* segment to drop, increment `hiddenCount`. Mutating `hiddenCount`
* re-renders and re-fires this effect, so the loop self-terminates
* either when the text fits or when only [first, …, leaf] remain
* (`truncate-start` then polishes any final overflow). When the
* breadcrumb itself changes (new scope), reset to 0 first. */
$effect(() => {
const key = headerSegments.join('|')
const segmentsChanged = key !== lastSegmentsKey
if (segmentsChanged) {
lastSegmentsKey = key
if (hiddenCount !== 0) {
hiddenCount = 0
return
}
}
void hiddenCount
if (!breadcrumbSpan) return
const maxHide = Math.max(0, headerSegments.length - 2)
if (hiddenCount >= maxHide) return
queueMicrotask(() => {
if (!breadcrumbSpan) return
if (breadcrumbSpan.scrollWidth > breadcrumbSpan.clientWidth + 1) {
hiddenCount = hiddenCount + 1
}
})
})
const branchLoading = $derived(currentBranch?.loading ?? false)
</script>
<SearchItems
{filter}
items={isSearching ? searchItems : []}
bind:filteredItems={searchedItems}
f={(x: SearchEntry) => leafHaystack(x.leaf)}
opts={{}}
/>
{#snippet defaultLeafIcon(leaf: DrillLeaf<L>)}
{#if leafIcon}
{@render leafIcon(leaf)}
{:else if leaf.icon}
{@const Icon = leaf.icon}
<Icon size={12} class="shrink-0" />
{/if}
{/snippet}
{#snippet defaultBranchIcon(branch: DrillBranch<L>)}
{#if branchIcon}
{@render branchIcon(branch)}
{:else if branch.icon}
{@const Icon = branch.icon}
<Icon size={12} class="shrink-0 text-tertiary" />
{/if}
{/snippet}
{#snippet leafRow(leaf: DrillLeaf<L>, secondary: string | undefined, baseClass: string)}
{@const key = leaf.key}
{@const isHl = key === highlightedKey}
{@const isCur = !!leaf.current}
<button
type="button"
id={idFor(key)}
role="option"
aria-selected={isHl}
data-nav-key={key}
aria-current={isCur ? 'true' : undefined}
class="w-full text-left flex items-center gap-2 px-3 transition-colors {baseClass} {isHl
? 'bg-surface-hover'
: ''} {isCur ? 'cursor-default text-emphasis font-medium' : ''} {leaf.disabled
? 'opacity-50 cursor-not-allowed'
: ''}"
disabled={leaf.disabled}
onmousedown={(e) => e.preventDefault()}
onclick={() => pick(leaf)}
onmouseenter={() => setHoverHighlight(key)}
>
{@render defaultLeafIcon(leaf)}
<div class="min-w-0 flex-1">
{#if leaf.secondary}
<div class="text-xs text-primary font-normal truncate">{leaf.label}</div>
<div class="text-2xs text-hint font-normal font-mono truncate">
{secondary ?? leaf.secondary}
</div>
{:else}
<div class="text-xs text-primary font-normal font-mono truncate">
{secondary ?? leaf.label}
</div>
{/if}
</div>
</button>
{/snippet}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={pickerRoot}
class={flush
? 'flex flex-col w-full h-full'
: 'flex flex-col w-[min(420px,calc(100vw-20px))] max-h-[60vh]'}
onkeydown={handleSearchKeydown}
onmousemove={() => (mouseActive = true)}
>
{#if externalFilter === undefined}
<div class="px-3 py-2 border-b border-gray-200 dark:border-gray-700">
<TextInput
bind:this={searchInput}
bind:value={internalFilter}
size="sm"
inputProps={{
placeholder: 'Search by name or summary...',
'data-workspace-picker-search': '',
role: 'combobox',
'aria-controls': listboxId,
'aria-expanded': 'true',
'aria-autocomplete': 'list',
'aria-activedescendant': highlightedId
}}
/>
</div>
{/if}
{#if scope.length > 0 && !isSearching}
<button
type="button"
class="flex items-center gap-1.5 w-full text-left px-3 py-1 text-xs font-medium font-mono text-secondary bg-surface-secondary/20 hover:bg-surface-hover transition-colors"
onmousedown={(e) => e.preventDefault()}
onclick={goUp}
title={headerLabel}
>
<ChevronLeft size={12} class="shrink-0 text-secondary" />
{#if headerChain[0]}
{@render defaultBranchIcon(headerChain[0])}
{/if}
<span bind:this={breadcrumbSpan} class="flex-1 min-w-0 truncate truncate-start">
{headerLabelDisplay}
</span>
</button>
{/if}
<div class="flex-1 overflow-y-auto" role="listbox" id={listboxId}>
{#if isSearching}
{@const total = (searchedItems ?? []).length}
{#if !searchedItems}
<div role="status" class="px-3 py-2 text-xs text-tertiary flex items-center gap-2">
<Loader2 size={14} class="animate-spin" /> Searching…
</div>
{:else if total === 0}
<div role="status" class="px-3 py-2 text-xs text-tertiary">No matches</div>
{:else}
{#each searchResultsByGroup as { group, items } (group?.key ?? '__none')}
{#if group}
<div class="px-3 pt-3 pb-1 text-2xs uppercase tracking-wide text-tertiary font-medium">
{group.label}
</div>
{/if}
<ul class="pb-1">
{#each items as r (r.leaf.key)}
<li>{@render leafRow(r.leaf, r.leaf.secondary ?? r.leaf.label, 'py-1.5')}</li>
{/each}
</ul>
{/each}
{/if}
{:else if branchLoading && entryList.length === 0}
<div role="status" class="px-3 py-2 text-xs text-tertiary flex items-center gap-2">
<Loader2 size={14} class="animate-spin" /> Loading…
</div>
{:else if entryList.length === 0}
<div role="status" class="px-3 py-2 text-xs text-tertiary">Empty</div>
{:else}
<div class="flex flex-col py-1">
{#each entryList as entry (entry.key)}
{@const isHl = entry.key === highlightedKey}
{#if entry.type === 'leaf'}
{@render leafRow(
entry.node,
leafSecondary?.(entry.node, scope) ?? entry.node.secondary,
'py-1.5'
)}
{:else}
<button
type="button"
id={idFor(entry.key)}
role="option"
aria-selected={isHl}
data-nav-key={entry.key}
class="flex items-center gap-1.5 w-full text-left px-3 py-1.5 text-xs font-medium font-mono text-emphasis transition-colors {isHl
? 'bg-surface-hover'
: ''}"
onmousedown={(e) => e.preventDefault()}
onclick={() => drill(entry)}
onmouseenter={() => setHoverHighlight(entry.key)}
>
{@render defaultBranchIcon(entry.node)}
<span class="flex-1 truncate">{entry.node.label}</span>
{#if entry.node.loading}
<Loader2 size={12} class="animate-spin text-tertiary" />
{/if}
<ChevronRight size={10} class="shrink-0 text-secondary" />
</button>
{/if}
{/each}
</div>
{/if}
</div>
</div>
<style>
/* Path truncates from the start (left ellipsis) so the deepest
* (rightmost) folder stays visible. `unicode-bidi: plaintext` keeps
* each path segment laid out per its own direction. */
.truncate-start {
direction: rtl;
text-align: left;
unicode-bidi: plaintext;
}
</style>
+12 -1
View File
@@ -735,7 +735,18 @@
flowStore.val = redo(history)
}
let flowBuilderRoot: HTMLDivElement | undefined = $state()
function onKeyDown(event: KeyboardEvent) {
// Defer to anything that has explicitly grabbed focus — menus, modals,
// drawers etc. live outside the flow root. Flow nodes aren't focusable,
// so the unfocused default (activeElement === body) means "flow is the
// canvas" and we should react.
const active = document.activeElement
if (active && active !== document.body && !flowBuilderRoot?.contains(active)) {
return
}
let classes = event.target?.['className']
if (
(typeof classes === 'string' && classes.includes('inputarea')) ||
@@ -1175,7 +1186,7 @@
<ScriptEditorDrawer bind:this={$scriptEditorDrawer} />
<FlowEditorDrawer bind:this={$flowEditorDrawer} />
<div class="flex flex-col flex-1 h-screen">
<div bind:this={flowBuilderRoot} class="flex flex-col flex-1 h-screen">
<!-- Nav between steps-->
<div
bind:clientWidth={topbarWidth}
@@ -1,44 +1,30 @@
<!--
@component
Drill-through workspace item picker. One level is shown at a time:
Workspace drill picker — adapter over the generic `DrillPicker`. Preserves
the workspace-specific public API (kinds, scope = `{ kind, dir? }`,
currentItem, leaf/branch icons) so callers (BreadcrumbSegment, EditorHeader)
don't need to know about the generic tree model underneath.
- **Root** (no scope): All + kinds (Flows / Scripts / Apps). "All" is a
cross-kind row — drilling in shows folders/items merged across every kind.
- **Kind** (`{ kind }`): top-level scopes for that kind (e.g. `f/demo`, `u/alice`).
`kind: 'all'` is the cross-kind variant — folders contain items from
every kind, leaves still belong to a real kind.
- **Dir** (`{ kind, dir }`): immediate children of `dir` — subdirs + leaves.
Clicking a row drills *down*; the chevron-left in the header walks one level
*up*. Search is global across all kinds and ignores the current scope.
Surfaces AI-created localStorage drafts (via `listGlobalDrafts`) as extra
items alongside the backend-loaded list, so chat-scaffolded scripts/flows/
apps that haven't been deployed yet are still navigable. Gated on
`isGlobalAiEnabled()` — without sessions, the only UserDrafts present are
standalone editor autosaves and surfacing those in the breadcrumb picker
would be surprising.
-->
<script lang="ts">
import { workspaceStore } from '$lib/stores'
import { ChevronLeft, ChevronRight, Folder, Layers, Loader2, User } from 'lucide-svelte'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import RowIcon from '$lib/components/common/table/RowIcon.svelte'
import WorkspaceItemRow from '$lib/components/WorkspaceItemRow.svelte'
import SearchItems from '$lib/components/SearchItems.svelte'
import { onMount, untrack } from 'svelte'
import { generateRandomString } from '$lib/utils'
import {
dirKey,
getCachedItems,
KIND_LABEL,
KIND_LABEL_LOWER,
kindKey,
leafKeyFor,
loadKind,
type WorkspaceItem,
type WorkspaceItemKind
} from './workspacePicker'
import { untrack } from 'svelte'
import { type WorkspaceItem, type WorkspaceItemKind } from './workspacePicker'
import { useWorkspaceItemsLoader } from './workspaceItemsLoader.svelte'
import DrillPicker from './DrillPicker.svelte'
import type { DrillBranch, DrillLeaf } from './drillPicker'
import { buildWorkspaceTree, legacyScopeToPath, relativizeWorkspacePath } from './workspaceTree'
import { listGlobalDrafts } from '$lib/components/copilot/chat/global/userDraftAdapter'
import { isGlobalAiEnabled } from '$lib/components/copilot/chat/global/gate'
type Kind = WorkspaceItemKind
type Item = WorkspaceItem
/** `'all'` is a virtual cross-kind scope — items still belong to a real
* kind, but folders and the root row group items from every kind. */
type ScopeKind = Kind | 'all'
export type Scope = { kind: ScopeKind; dir?: string } | undefined
@@ -46,14 +32,12 @@ Clicking a row drills *down*; the chevron-left in the header walks one level
interface Props {
onPick: (item: WorkspaceItem) => void
kinds?: Kind[]
/** Where the picker lands when first opened. `undefined` = root (kinds list). */
initialScope?: Scope
/** Composite key of the row to highlight (e.g. `dir:flow:f/demo`). */
initialHighlight?: string
/** Currently-edited item — gets `aria-current` and a no-op click. If
* `savedPath` differs from `path` (draft rename), the saved entry is
* suppressed so only the live one shows. */
currentItem?: WorkspaceItem & { savedPath?: string }
externalFilter?: string
autoFocus?: boolean
flush?: boolean
}
let {
@@ -61,112 +45,39 @@ Clicking a row drills *down*; the chevron-left in the header walks one level
kinds = ['flow', 'script', 'app'],
initialScope,
initialHighlight,
currentItem
currentItem,
externalFilter,
autoFocus = true,
flush = false
}: Props = $props()
let searchInput: TextInput | undefined = $state()
let pickerRoot: HTMLElement | undefined = $state()
const instanceId = generateRandomString(8)
const listboxId = `pkr-list-${instanceId}`
const idFor = (key: string) => `pkr-${instanceId}-${key.replace(/[^a-zA-Z0-9-]/g, '_')}`
let inner = $state<DrillPicker<WorkspaceItem> | undefined>(undefined)
export function focus() {
searchInput?.focus()
inner?.focus()
}
export function handleKeydown(e: KeyboardEvent) {
inner?.handleKeydown(e)
}
export function pickHighlighted() {
inner?.pickHighlighted()
}
// Sibling-popover open: melt-ui's `openFocus` runs once during the close→open
// transition; the picker may not be mounted yet. Retry after settle.
// Also kicks off the initial scope's fetch — drill/goUp do the same from
// their respective branches, so `ensureLoaded` is always a callback
// reaction to user navigation, never a reactive consequence.
onMount(() => {
const t = setTimeout(focus, 50)
const initial = untrack(() => scope)
if (initial) {
if (initial.kind === 'all') for (const k of kinds) ensureLoaded(k)
else ensureLoaded(initial.kind)
}
return () => clearTimeout(t)
})
const leafKey = (it: Item) => leafKeyFor(it.kind, it.path)
let scope = $state<Scope>(untrack(() => initialScope))
let filter = $state('')
/**
* Canonical entry point for changing the picker's scope. Triggers the
* fetch for the kind(s) the new scope needs at the same point in time.
* Replaces the older "react to `scope` change via `$effect`" wiring,
* which had a subtle bug: `ensureLoaded` reads `loaded[kind]`, so the
* effect ended up subscribed to the signal it fills — every fetch
* result re-fired it. With explicit callbacks the fetch is tied to
* the user's action, never to a reactive consequence of that action.
*/
function setScope(next: Scope) {
scope = next
if (!next) return
if (next.kind === 'all') for (const k of kinds) ensureLoaded(k)
else ensureLoaded(next.kind)
}
/** Tracks whether the last user action was mouse movement (true) or
* keyboard nav (false). When false, row `mouseenter` events are ignored
* — prevents the cursor from stealing the keyboard-driven highlight as
* rows shift under it during scope changes. Re-enabled on `mousemove`.
* Starts `false` so the synthetic `mouseenter` fired when the popover
* mounts under a stationary cursor doesn't clobber `initialHighlight`. */
let mouseActive = $state(false)
// Seed from the last fetched snapshot so kinds already fetched in this
// session render on the first frame. Each entry is replaced once
// `loadKind` returns fresh data — stale-while-revalidate, so deploys and
// AI-created drafts surface on the next open without explicit cache
// busting.
let loaded = $state<Partial<Record<Kind, Item[]>>>(
(() => {
if (!$workspaceStore) return {}
const out: Partial<Record<Kind, Item[]>> = {}
for (const k of kinds) {
const cached = getCachedItems($workspaceStore, k)
if (cached) out[k] = cached
}
return out
})()
const loader = useWorkspaceItemsLoader(
() => $workspaceStore,
() => kinds
)
let loadingKind = $state<Partial<Record<Kind, boolean>>>({})
async function ensureLoaded(kind: Kind) {
if (!$workspaceStore) return
// Always re-fetch. If we have nothing cached, show a spinner; if we do,
// keep displaying it and quietly swap to fresh data when it lands.
// `loaded[kind]` is read inside `untrack(...)` because this function is
// reachable from the search `$effect` below — without the untrack,
// that effect would subscribe to the signal `ensureLoaded` fills, and
// each `loaded[kind] = items` (proxy `set` notifies even when the ref
// is unchanged from cache) would refire it → runaway loop. Drill
// navigation goes through `setScope` directly so it isn't affected.
if (!untrack(() => loaded[kind])) loadingKind[kind] = true
try {
const items = await loadKind($workspaceStore, kind)
loaded[kind] = items
} finally {
loadingKind[kind] = false
}
}
// Chat tools and session editor previews write drafts through
// `UserDraft` (workspace-scoped, localStorage-backed). Merge those into
// the picker so users can navigate to in-flight items that haven't been
// deployed yet. Filter to kinds the picker actually displays.
//
// Gated on the same dev flag as the rest of the sessions feature: without
// it there are no sessions, so the only UserDrafts present are the
// standalone editors' autosaves — surfacing those in the breadcrumb picker
// would be surprising (they'd appear as navigable items that 404 on the
// backend draft fetch). When the flag is off this is a no-op.
// Chat tools and session editor previews write drafts through `UserDraft`
// (workspace-scoped, localStorage-backed). Merge those into the picker so
// users can navigate to in-flight items that haven't been deployed yet.
// Filter to kinds the picker actually displays. Gated on the global-AI
// flag — without sessions, the only UserDrafts present are the standalone
// editors' autosaves and surfacing those in the breadcrumb picker would
// be surprising (they'd appear as navigable items that 404 on the backend
// draft fetch).
const KIND_TO_DRAFT_TYPE = { flow: 'flow', script: 'script', app: 'app' } as const
function aiDraftsForKind(k: Kind): Item[] {
function aiDraftsForKind(k: Kind): WorkspaceItem[] {
if (!isGlobalAiEnabled()) return []
if (!$workspaceStore) return []
const targetType = KIND_TO_DRAFT_TYPE[k]
@@ -181,573 +92,58 @@ Clicking a row drills *down*; the chevron-left in the header walks one level
}))
}
// Searching is global → load every kind.
$effect(() => {
if (filter.trim() !== '') for (const k of kinds) ensureLoaded(k)
})
type DirNode = {
fullPath: string
name: string
isScope: boolean
children: DirNode[]
leaves: Item[]
}
/** Merge AI-created in-memory drafts into a kind's list. The AI may have
* scaffolded a script/flow/app via chat tools without the user saving
* yet — those drafts should be navigable from the picker. Existing items
* (same path) win to keep the backend's metadata (summary etc.). */
function withAiDrafts(items: Item[], k: Kind): Item[] {
const ai = aiDraftsForKind(k)
if (ai.length === 0) return items
const known = new Set(items.map((it) => it.path))
return items.concat(ai.filter((d) => !known.has(d.path)))
}
/** Inject the currently-edited item into a kind's list at its live path,
* dropping the saved entry when a draft rename is in progress. Other kinds
* pass through untouched. */
function withCurrent(items: Item[], k: Kind): Item[] {
if (!currentItem || currentItem.kind !== k) return items
const drafted =
currentItem.savedPath && currentItem.savedPath !== currentItem.path
? items.filter((it) => it.path !== currentItem.savedPath)
: items
if (drafted.some((it) => it.path === currentItem.path)) return drafted
return [
...drafted,
{
path: currentItem.path,
summary: currentItem.summary,
kind: k,
raw_app: currentItem.raw_app
}
]
}
function buildTreeFromItems(items: Item[]): DirNode[] {
const scopeRoots = new Map<string, DirNode>()
for (const it of items) {
const parts = it.path.split('/')
if (parts.length < 3) continue
const scopeFp = parts.slice(0, 2).join('/')
let node = scopeRoots.get(scopeFp)
if (!node) {
node = { fullPath: scopeFp, name: scopeFp, isScope: true, children: [], leaves: [] }
scopeRoots.set(scopeFp, node)
}
const slug = parts.slice(2)
let cur = node
for (let i = 0; i < slug.length - 1; i++) {
const seg = slug[i]
const fullPath = cur.fullPath + '/' + seg
let next = cur.children.find((c) => c.name === seg)
if (!next) {
next = { fullPath, name: seg, isScope: false, children: [], leaves: [] }
cur.children.push(next)
}
cur = next
}
cur.leaves.push(it)
}
const scopes = Array.from(scopeRoots.values()).sort((a, b) => {
const af = a.fullPath.startsWith('f/') ? 0 : 1
const bf = b.fullPath.startsWith('f/') ? 0 : 1
if (af !== bf) return af - bf
return a.fullPath.localeCompare(b.fullPath)
})
const sortNode = (n: DirNode) => {
n.children.sort((a, b) => a.name.localeCompare(b.name))
n.leaves.sort((a, b) => a.path.localeCompare(b.path))
n.children.forEach(sortNode)
}
scopes.forEach(sortNode)
return scopes
}
/** Per-kind tree deriveds. Each only re-evaluates `buildTreeFromItems`
* when its own `loaded[k]` changes or when the user is mid-rename on
* that kind — typing in a flow's path edit leaves script/app trees
* cached. */
function buildIfActive(k: Kind, list: Item[] | undefined): DirNode[] {
if (!kinds.includes(k)) return []
const items = withAiDrafts(withCurrent(list ?? [], k), k)
if (items.length === 0) return []
return buildTreeFromItems(items)
}
const flowTree = $derived(buildIfActive('flow', loaded.flow))
const scriptTree = $derived(buildIfActive('script', loaded.script))
const appTree = $derived(buildIfActive('app', loaded.app))
/** Cross-kind tree: every loaded item from every active kind, merged into
* one folder hierarchy. Each leaf still carries its real kind, so the row
* icon and `editPathFor` routing still work; folders contain a mix. */
const allTree = $derived.by(() => {
const merged = kinds.flatMap((k) => withAiDrafts(withCurrent(loaded[k] ?? [], k), k))
return merged.length === 0 ? [] : buildTreeFromItems(merged)
})
function treeFor(k: ScopeKind): DirNode[] {
if (k === 'all') return allTree
if (k === 'flow') return flowTree
if (k === 'script') return scriptTree
return appTree
}
function findDirInList(list: DirNode[], fullPath: string): DirNode | undefined {
for (const n of list) {
if (n.fullPath === fullPath) return n
const sub = findDirInList(n.children, fullPath)
if (sub) return sub
}
return undefined
}
function parentDirPath(p: string): string | undefined {
const parts = p.split('/')
if (parts.length <= 2) return undefined
return parts.slice(0, -1).join('/')
}
type Entry =
| { type: 'kind'; key: string; kind: ScopeKind }
| { type: 'dir'; key: string; kind: ScopeKind; node: DirNode }
| { type: 'leaf'; key: string; item: Item }
type DisplayItem = Item & { marked?: string }
type SearchInput = Item & { _key: string }
let allItems = $derived<SearchInput[]>(
kinds.flatMap((k) =>
withAiDrafts(withCurrent(loaded[k] ?? [], k), k).map((it) => ({
...it,
_key: `${k}:${it.path}`
}))
)
const extraItemsByKind = $derived<Partial<Record<Kind, WorkspaceItem[]>>>(
Object.fromEntries(kinds.map((k) => [k, aiDraftsForKind(k)]))
)
let searchedItems: DisplayItem[] | undefined = $state(undefined)
let isSearching = $derived(filter.trim() !== '')
let searchResultsByKind = $derived.by(() => {
const out: Record<Kind, DisplayItem[]> = { flow: [], script: [], app: [] }
if (!searchedItems) return out
for (const it of searchedItems) out[it.kind].push(it)
return out
})
/** Rows currently shown — drives both rendering and keyboard nav. Not used
* while `isSearching` (search renders its own grouped layout). */
let entries = $derived.by<Entry[]>(() => {
const s = scope
if (!s) {
const kindEntries = kinds.map((k) => ({
type: 'kind' as const,
key: kindKey(k),
kind: k
}))
// "All" only makes sense across multiple kinds — with a single kind
// it would duplicate that kind's own root row.
if (kinds.length <= 1) return kindEntries
return [
{ type: 'kind' as const, key: kindKey('all'), kind: 'all' as ScopeKind },
...kindEntries
]
}
const tree = treeFor(s.kind)
if (!s.dir) {
return tree.map((node) => ({
type: 'dir',
key: dirKey(s.kind, node.fullPath),
kind: s.kind,
node
}))
}
const node = findDirInList(tree, s.dir)
if (!node) return []
return [
...node.children.map(
(c): Entry => ({
type: 'dir',
key: dirKey(s.kind, c.fullPath),
kind: s.kind,
node: c
})
),
...node.leaves.map((l): Entry => ({ type: 'leaf', key: leafKey(l), item: l }))
]
})
let navKeys = $derived.by(() => {
if (isSearching) {
return kinds.flatMap((k) => searchResultsByKind[k].map((it) => leafKey(it)))
}
return entries.map((e) => e.key)
})
let highlightedKey = $state<string | undefined>(untrack(() => initialHighlight))
let highlightedId = $derived(highlightedKey ? idFor(highlightedKey) : undefined)
$effect(() => {
if (navKeys.length === 0) return
if (!highlightedKey || !navKeys.includes(highlightedKey)) {
highlightedKey = navKeys[0]
}
})
$effect(() => {
if (highlightedKey && navKeys.includes(highlightedKey)) {
requestAnimationFrame(scrollHighlightIntoView)
}
})
function scrollHighlightIntoView() {
if (!pickerRoot || !highlightedKey) return
const el = pickerRoot.querySelector<HTMLElement>(
`[data-nav-key="${CSS.escape(highlightedKey)}"]`
)
el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
}
function moveHighlight(delta: 1 | -1) {
if (navKeys.length === 0) return
const cur = navKeys.indexOf(highlightedKey ?? '')
const next = cur < 0 ? 0 : (cur + delta + navKeys.length) % navKeys.length
highlightedKey = navKeys[next]
mouseActive = false
requestAnimationFrame(scrollHighlightIntoView)
}
function setHoverHighlight(key: string) {
// Ignored until the user actually moves the mouse. Prevents the cursor
// (parked over a row) from clobbering keyboard-driven selection when
// the layout shifts beneath it.
if (mouseActive) highlightedKey = key
}
function isCurrent(it: Item): boolean {
return !!currentItem && currentItem.kind === it.kind && currentItem.path === it.path
}
function pick(it: Item) {
if (isCurrent(it)) return
onPick({ path: it.path, summary: it.summary, kind: it.kind, raw_app: it.raw_app })
}
function activate(key: string | undefined) {
if (!key) return
if (isSearching) {
const flat = kinds.flatMap((k) => searchResultsByKind[k])
const it = flat.find((x) => leafKey(x) === key)
if (it) pick(it)
return
}
const entry = entries.find((e) => e.key === key)
if (!entry) return
drill(entry)
}
function drill(entry: Entry) {
if (entry.type === 'kind') {
setScope({ kind: entry.kind })
} else if (entry.type === 'dir') {
setScope({ kind: entry.kind, dir: entry.node.fullPath })
} else {
pick(entry.item)
}
}
function goUp() {
if (!scope) return
// Highlight the row in the parent view that represents the scope we
// just left, so the user sees where they came from.
if (!scope.dir) {
const leaving = kindKey(scope.kind)
setScope(undefined)
highlightedKey = leaving
return
}
const leaving = dirKey(scope.kind, scope.dir)
const parent = parentDirPath(scope.dir)
setScope(parent ? { kind: scope.kind, dir: parent } : { kind: scope.kind })
highlightedKey = leaving
}
function handleSearchKeydown(e: KeyboardEvent) {
if (e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
moveHighlight(1)
} else if (e.key === 'ArrowUp') {
e.preventDefault()
e.stopPropagation()
moveHighlight(-1)
} else if (e.key === 'Enter') {
e.preventDefault()
e.stopPropagation()
mouseActive = false
activate(highlightedKey)
} else if ((e.key === 'ArrowLeft' || e.key === 'Backspace') && filter === '' && scope) {
// Walk up the tree. Only when search is empty — otherwise these
// keys would hijack cursor movement / character deletion.
e.preventDefault()
e.stopPropagation()
mouseActive = false
goUp()
} else if (e.key === 'ArrowRight' && filter === '' && !isSearching) {
// Drill into the highlighted folder/kind. Leaves are reserved for
// Enter (more deliberate, since picking navigates away).
const entry = entries.find((en) => en.key === highlightedKey)
if (entry && entry.type !== 'leaf') {
e.preventDefault()
e.stopPropagation()
mouseActive = false
drill(entry)
}
}
}
/** Breadcrumb segments for the header — kind name first, then the scope
* (`f/<folder>` or `u/<user>`) as one chunk, then any nested subdirs. */
let headerSegments = $derived.by<string[]>(() => {
if (!scope) return []
const out = [scope.kind === 'all' ? 'all' : KIND_LABEL_LOWER[scope.kind]]
if (scope.dir) {
const parts = scope.dir.split('/')
out.push(parts.slice(0, 2).join('/'))
for (let i = 2; i < parts.length; i++) out.push(parts[i])
}
return out
})
/** Full breadcrumb (used for the hover tooltip). */
let headerLabel = $derived(headerSegments.join(' '))
/** Number of intermediate segments to hide behind a `…`. The collapsed
* window is segments[2 .. 2 + hiddenCount); we always keep the first
* two (kind, top-level scope) and the deepest segment. Bumped up by an
* effect that measures actual overflow — see below. */
let hiddenCount = $state(0)
/** Breadcrumb shown to the user. Hides intermediate segments first, then
* relies on `truncate-start` for any remaining overflow on the deepest
* segment. Hover reveals the full path via `title`. */
let headerLabelDisplay = $derived.by(() => {
if (headerSegments.length <= 3 || hiddenCount === 0) return headerLabel
return [
headerSegments[0],
headerSegments[1],
'…',
...headerSegments.slice(2 + hiddenCount)
].join(' ')
})
let breadcrumbSpan: HTMLElement | undefined = $state()
let lastSegmentsKey = ''
/** Measurement loop: each pass reads `scrollWidth > clientWidth` on the
* truncated span; if overflowing and there's still an intermediate segment
* to drop, increment `hiddenCount`. Mutating `hiddenCount` re-renders and
* re-fires this effect, so the loop self-terminates either when the text
* fits or when only [kind, scope, …, leaf] remain (`truncate-start` then
* polishes any final overflow). When the breadcrumb itself changes (new
* scope), reset to 0 first so a shorter path can re-expand. */
$effect(() => {
const key = headerSegments.join('|')
const segmentsChanged = key !== lastSegmentsKey
if (segmentsChanged) {
lastSegmentsKey = key
if (hiddenCount !== 0) {
hiddenCount = 0
return
}
}
// Track hiddenCount so each collapse step re-measures.
void hiddenCount
if (!breadcrumbSpan) return
const maxHide = Math.max(0, headerSegments.length - 3)
if (hiddenCount >= maxHide) return
queueMicrotask(() => {
if (!breadcrumbSpan) return
if (breadcrumbSpan.scrollWidth > breadcrumbSpan.clientWidth + 1) {
hiddenCount = hiddenCount + 1
}
const tree = $derived(
buildWorkspaceTree({
loaded: loader.loaded,
kinds,
currentItem,
loadingKind: loader.loadingKind,
extraItemsByKind
})
})
)
let scopeLoading = $derived.by(() => {
if (!scope) return false
if (scope.kind === 'all') {
return kinds.some((k) => !loaded[k] && !!loadingKind[k])
}
return !loaded[scope.kind] && !!loadingKind[scope.kind]
})
// Mount-time only: callers (BreadcrumbSegment, EditorHeader) snapshot the
// scope when the popover opens, so re-evaluating on prop changes would
// fight the user's drilling.
const computedInitialScope = untrack(() => legacyScopeToPath(initialScope, kinds))
</script>
<SearchItems
{filter}
items={isSearching ? allItems : []}
bind:filteredItems={searchedItems}
f={(x: SearchInput) => (x.summary ? `${x.summary} (${x.path})` : x.path)}
opts={{}}
/>
{#snippet leafRow(it: Item, secondary: string, baseClass: string)}
{@const key = leafKey(it)}
<WorkspaceItemRow
kind={it.kind}
summary={it.summary}
{secondary}
highlighted={key === highlightedKey}
current={isCurrent(it)}
id={idFor(key)}
navKey={key}
{baseClass}
onclick={() => pick(it)}
onmouseenter={() => setHoverHighlight(key)}
/>
{#snippet leafIcon(leaf: DrillLeaf<WorkspaceItem>)}
<RowIcon kind={leaf.data.kind} size={12} />
{/snippet}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={pickerRoot}
class="flex flex-col w-[420px] max-h-[60vh]"
onkeydown={handleSearchKeydown}
onmousemove={() => (mouseActive = true)}
>
<div class="px-3 py-2 border-b border-gray-200 dark:border-gray-700">
<TextInput
bind:this={searchInput}
bind:value={filter}
size="sm"
inputProps={{
placeholder: 'Search by name or summary...',
'data-workspace-picker-search': '',
role: 'combobox',
'aria-controls': listboxId,
'aria-expanded': 'true',
'aria-autocomplete': 'list',
'aria-activedescendant': highlightedId
}}
/>
</div>
{#if scope}
{@const s = scope}
<button
type="button"
class="flex items-center gap-1.5 w-full text-left px-3 py-1 text-xs font-medium font-mono text-secondary bg-surface-secondary/20 hover:bg-surface-hover transition-colors"
onmousedown={(e) => e.preventDefault()}
onclick={goUp}
title={headerLabel}
>
<ChevronLeft size={12} class="shrink-0 text-secondary" />
{#if s.kind === 'all'}
<Layers size={12} class="shrink-0 text-tertiary" />
{:else}
<RowIcon kind={s.kind} size={12} />
{/if}
<span bind:this={breadcrumbSpan} class="flex-1 min-w-0 truncate truncate-start"
>{headerLabelDisplay}</span
>
</button>
{#snippet branchIcon(branch: DrillBranch<WorkspaceItem>)}
{#if branch.key === 'kind:flow' || branch.key === 'kind:script' || branch.key === 'kind:app'}
{@const k = branch.key.slice(5) as Kind}
<RowIcon kind={k} size={12} />
{:else if branch.icon}
{@const Icon = branch.icon}
<Icon size={12} class="shrink-0 text-tertiary" />
{/if}
{/snippet}
<div class="flex-1 overflow-y-auto" role="listbox" id={listboxId}>
{#if isSearching}
{@const total = (searchedItems ?? []).length}
{@const anyKindLoading = kinds.some((k) => loadingKind[k])}
{#if !searchedItems || anyKindLoading}
<!-- "Searching…" while any active kind is still loading, otherwise
`SearchItems` would briefly write `filteredItems=[]` from the
partial set and flash "No matches" before results trickle in. -->
<div role="status" class="px-3 py-2 text-xs text-tertiary flex items-center gap-2">
<Loader2 size={14} class="animate-spin" /> Searching…
</div>
{:else if total === 0}
<div role="status" class="px-3 py-2 text-xs text-tertiary">No matches</div>
{:else}
{#each kinds as k (k)}
{@const results = searchResultsByKind[k]}
{#if results.length > 0}
<div class="px-3 pt-3 pb-1 text-2xs uppercase tracking-wide text-tertiary font-medium">
{KIND_LABEL[k]}
</div>
<ul class="pb-1">
{#each results as it (leafKey(it))}
<li>{@render leafRow(it, it.path, 'py-1.5')}</li>
{/each}
</ul>
{/if}
{/each}
{/if}
{:else if scopeLoading && entries.length === 0}
<div role="status" class="px-3 py-2 text-xs text-tertiary flex items-center gap-2">
<Loader2 size={14} class="animate-spin" /> Loading…
</div>
{:else if entries.length === 0}
<div role="status" class="px-3 py-2 text-xs text-tertiary">Empty</div>
{:else}
<div class="flex flex-col py-1">
{#each entries as entry (entry.key)}
{@const isHl = entry.key === highlightedKey}
{#if entry.type === 'leaf'}
{@render leafRow(
entry.item,
scope?.dir ? entry.item.path.slice(scope.dir.length + 1) : entry.item.path,
'py-1.5'
)}
{:else}
<button
type="button"
id={idFor(entry.key)}
role="option"
aria-selected={isHl}
data-nav-key={entry.key}
class="flex items-center gap-1.5 w-full text-left px-3 py-1.5 text-xs font-medium font-mono text-emphasis transition-colors {isHl
? 'bg-surface-hover'
: ''}"
onmousedown={(e) => e.preventDefault()}
onclick={() => drill(entry)}
onmouseenter={() => setHoverHighlight(entry.key)}
>
{#if entry.type === 'kind'}
{#if entry.kind === 'all'}
<Layers size={12} class="shrink-0 text-tertiary" />
<span class="flex-1">All</span>
{:else}
<RowIcon kind={entry.kind} size={12} />
<span class="flex-1">{KIND_LABEL[entry.kind]}</span>
{/if}
{:else if entry.node.isScope && entry.node.fullPath.startsWith('u/')}
<User size={12} class="shrink-0 text-tertiary" />
<span class="flex-1 truncate">{entry.node.name}</span>
{:else}
<Folder size={12} class="shrink-0 text-tertiary" />
<span class="flex-1 truncate">{entry.node.name}</span>
{/if}
{#if entry.type === 'kind' && entry.kind !== 'all' && loadingKind[entry.kind]}
<Loader2 size={12} class="animate-spin text-tertiary" />
{/if}
<ChevronRight size={10} class="shrink-0 text-secondary" />
</button>
{/if}
{/each}
</div>
{/if}
</div>
</div>
<style>
/* Path truncates from the start (left ellipsis) so the deepest (rightmost)
* folder stays visible. `unicode-bidi: plaintext` keeps each path segment
* laid out per its own direction — defends against any future RTL char
* appearing in a workspace path. */
.truncate-start {
direction: rtl;
text-align: left;
unicode-bidi: plaintext;
}
</style>
<DrillPicker
bind:this={inner}
{tree}
onPick={(leaf) => onPick(leaf.data)}
initialScope={computedInitialScope}
{initialHighlight}
{externalFilter}
{autoFocus}
{flush}
{leafIcon}
{branchIcon}
leafSecondary={(leaf, scope) => relativizeWorkspacePath(leaf.data.path, scope)}
onScopeChange={(scope) => {
if (scope.length > 0) loader.ensureForScopeSegment(scope[0])
// Single-kind layout has no kind branch at root — `buildWorkspaceTree`
// collapses to the kind's children. The picker mounts with scope=[],
// so without this fallback nothing fires until the user searches.
else if (kinds.length === 1) loader.ensureLoaded(kinds[0])
}}
onFilterChange={loader.onFilterChange}
/>
@@ -1,7 +1,7 @@
<script lang="ts">
import AIChatMessage from './AIChatMessage.svelte'
import AppAvailableContextList from './AppAvailableContextList.svelte'
import AvailableContextList from './AvailableContextList.svelte'
import ChatContextPicker from './ChatContextPicker.svelte'
import { type Snippet } from 'svelte'
import {
AlertTriangle,
@@ -518,7 +518,7 @@
{#if showFooterLeftControls}
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap">
{#if showContextPicker && !disabled}
<Popover>
<Popover placement="bottom-start">
{#snippet trigger()}
<Button
nonCaptureEvent
@@ -540,16 +540,23 @@
}}
/>
{:else}
<AvailableContextList
<ChatContextPicker
{availableContext}
{selectedContext}
onSelect={(element) => {
void aiChatInput?.addContextToSelection(element)
aiChatInput?.insertMention(element.title)
close()
aiChatInput?.focusInput()
}}
onSelectWorkspaceItem={(element) => {
void aiChatInput?.addContextToSelection(element)
aiChatInput?.insertMention(element.title)
close()
aiChatInput?.focusInput()
}}
setShowing={(showing) => {
if (!showing) close()
}}
/>
{/if}
@@ -129,6 +129,42 @@
aiChatManager.mode === AIMode.GLOBAL
)
/** Append `@title` to the textarea so the button-picker path stays in
* sync with the inline `@<word>` mention path — both leave a visible
* token tied to the selectedContext entry, which the textarea diffs on
* to auto-remove items when the user deletes them. No-op when the
* mention is already present so re-picking the same item doesn't
* leave duplicate tokens. */
export function insertMention(title: string) {
const target = `@${title}`
if (instructions.split(/\s+/).includes(target)) return
const sep = instructions.length === 0 || /\s$/.test(instructions) ? '' : ' '
instructions = `${instructions}${sep}${target} `
}
/** Strip every `@title` token from the textarea — used when the user
* deletes the corresponding badge so the badge X-button mirrors the
* inverse (text-delete-to-badge-remove) sync. Only matches `@title` as a
* standalone token (boundary on both sides) so substring matches don't
* bleed into other words; only the whitespace adjacent to the removed
* mention is collapsed so unrelated double-spaces stay intact. */
export function removeMention(title: string) {
// Pre-zap the textarea's mention diff snapshot so the upcoming strip
// doesn't refire the removal effect on a same-title sibling — the host
// has already mutated `selectedContext` to drop the targeted entry.
contextTextareaComponent?.unsyncMention(title)
const escaped = title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const re = new RegExp(`(^|\\s)@${escaped}(\\s|$)`, 'g')
instructions = instructions.replace(re, (_m, lead, trail) => {
// Boundary on at least one side → drop the mention entirely.
if (!lead || !trail) return ''
// Middle of text: keep ONE of the bracketing whitespace chars so
// the surviving tokens are still separated; preserve the leading
// one verbatim so newlines/tabs aren't downgraded to spaces.
return lead
})
}
export function focusInput() {
if (isContextEnabledMode) {
contextTextareaComponent?.focus()
@@ -226,6 +262,12 @@
onEditEnd()
} else {
aiChatManager.sendRequest({ instructions })
// clearForSend() pre-zaps the textarea's mention-sync so the wipe
// doesn't drop `selectedContext` before `AIChatManager.beforeSend`
// snapshots it. Only mounted in SCRIPT/FLOW/GLOBAL — APP and the
// fallback textarea still rely on the plain `instructions = ''`
// reset (no `@`-mention state to coordinate).
contextTextareaComponent?.clearForSend()
instructions = ''
}
}
@@ -460,6 +502,7 @@
selectedContext = selectedContext?.filter(
(c) => c.type !== element.type || c.title !== element.title
)
removeMention(element.title)
}}
/>
{/each}
@@ -488,9 +531,13 @@
bind:value={instructions}
{availableContext}
{selectedContext}
{isFirstMessage}
placeholder={modePlaceholder}
onAddContext={(contextElement) => void addContextToSelection(contextElement)}
onRemoveContext={(element) => {
selectedContext = selectedContext?.filter(
(c) => c.type !== element.type || c.title !== element.title
)
}}
onSendRequest={() => {
if (disabled) {
return
@@ -1,482 +0,0 @@
<script lang="ts">
import FlowModuleIcon from '$lib/components/flows/FlowModuleIcon.svelte'
import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte'
import type { FlowModule } from '$lib/gen/types.gen'
import { workspaceStore } from '$lib/stores'
import { workspaceRunnablesSearch } from './shared'
import {
ContextIconMap,
type ContextElement,
type WorkspaceScriptElement,
type WorkspaceFlowElement
} from './context'
import {
ArrowLeft,
Diff,
Database,
ChevronRight,
Code2,
Loader2
} from 'lucide-svelte'
interface Props {
availableContext: ContextElement[]
selectedContext: ContextElement[]
onSelect: (element: ContextElement) => void
onSelectWorkspaceItem?: (element: ContextElement) => void
setShowing?: (showing: boolean) => void
showAllAvailable?: boolean
stringSearch?: string
onViewChange?: (newNumber: number) => void
}
const {
availableContext,
selectedContext,
onSelect,
onSelectWorkspaceItem,
setShowing,
showAllAvailable = false,
stringSearch = '',
onViewChange
}: Props = $props()
// Current view state: 'categories' or specific category type
let currentView = $state<
'categories' | 'diffs' | 'modules' | 'databases' | 'scripts' | 'flows'
>('categories')
// Selected index for keyboard navigation
let itemSelectedIndex = $state(0)
let categorySelectedIndex = $state(0)
// Workspace search state
let workspaceSearchQuery = $state('')
let workspaceSearchResults = $state<{ path: string; summary: string }[]>([])
let workspaceSearchLoading = $state(false)
let searchInputElement = $state<HTMLInputElement | undefined>(undefined)
let searchDebounceTimer: ReturnType<typeof setTimeout> | undefined = undefined
// Category definitions
const categories = [
{ id: 'diffs' as const, label: 'Diffs', icon: Diff, searchable: false },
{ id: 'modules' as const, label: 'Modules', icon: BarsStaggered, searchable: false },
{ id: 'databases' as const, label: 'Databases', icon: Database, searchable: false },
{ id: 'scripts' as const, label: 'Scripts', icon: Code2, searchable: true },
{ id: 'flows' as const, label: 'Flows', icon: BarsStaggered, searchable: true }
]
const isSearchableView = $derived(
currentView === 'scripts' || currentView === 'flows'
)
const filteredAvailableContext = $derived(
availableContext.filter((context) => {
const filtered =
(showAllAvailable ||
!selectedContext.some((sc) => sc.type === context.type && sc.title === context.title)) &&
(!stringSearch || context.title.toLowerCase().includes(stringSearch.toLowerCase()))
return filtered
})
)
// Group context by category
const contextByCategory = $derived.by(() => {
const grouped: Record<string, ContextElement[]> = {
diffs: [],
modules: [],
databases: []
}
filteredAvailableContext.forEach((context) => {
if (context.type === 'diff') grouped.diffs.push(context)
else if (context.type === 'flow_module') grouped.modules.push(context)
else if (context.type === 'db') grouped.databases.push(context)
})
return grouped
})
const currentCategoryItems = $derived(
currentView !== 'categories' && !isSearchableView ? contextByCategory[currentView] : []
)
// Filter to only show categories with items (non-searchable) or always show (searchable)
const availableCategories = $derived(
categories.filter(
(cat) => cat.searchable || contextByCategory[cat.id]?.length > 0
)
)
// Report view changes
$effect(() => {
if (onViewChange) {
if (currentView === 'categories') {
onViewChange(availableCategories.length)
} else if (isSearchableView) {
onViewChange(workspaceSearchResults.length + 2) // +2 for back button and search input
} else {
onViewChange(currentCategoryItems.length + 1)
}
}
})
function handleCategoryClick(categoryId: string) {
currentView = categoryId as typeof currentView
itemSelectedIndex = 0
if (categoryId === 'scripts' || categoryId === 'flows') {
workspaceSearchQuery = ''
workspaceSearchResults = []
searchWorkspaceItems('')
setTimeout(() => searchInputElement?.focus(), 0)
}
}
function handleBackClick() {
currentView = 'categories'
itemSelectedIndex = 0
workspaceSearchQuery = ''
workspaceSearchResults = []
}
async function searchWorkspaceItems(query: string) {
const workspace = $workspaceStore
if (!workspace) return
workspaceSearchLoading = true
try {
const type = currentView === 'scripts' ? 'scripts' : 'flows'
const results = await workspaceRunnablesSearch.search(query, workspace, type)
workspaceSearchResults = results.map((r) => ({
path: r.path,
summary: r.summary
}))
} catch (err) {
console.error('Error searching workspace items', err)
workspaceSearchResults = []
} finally {
workspaceSearchLoading = false
}
}
function handleSearchInput() {
if (searchDebounceTimer) clearTimeout(searchDebounceTimer)
searchDebounceTimer = setTimeout(() => {
searchWorkspaceItems(workspaceSearchQuery)
}, 300)
}
function handleWorkspaceItemSelect(item: { path: string; summary?: string }) {
if (!onSelectWorkspaceItem) return
if (currentView === 'scripts') {
const element: WorkspaceScriptElement & { deletable: boolean } = {
type: 'workspace_script',
path: item.path,
title: item.path,
summary: item.summary,
deletable: true
}
onSelectWorkspaceItem(element)
} else if (currentView === 'flows') {
const element: WorkspaceFlowElement & { deletable: boolean } = {
type: 'workspace_flow',
path: item.path,
title: item.path,
summary: item.summary,
deletable: true
}
onSelectWorkspaceItem(element)
}
currentView = 'categories'
workspaceSearchQuery = ''
workspaceSearchResults = []
}
function handleKeyDown(e: KeyboardEvent) {
if (isSearchableView) {
// Navigation in workspace search view
if (e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
if (workspaceSearchResults.length > 0) {
itemSelectedIndex = (itemSelectedIndex + 1) % workspaceSearchResults.length
}
} else if (e.key === 'ArrowUp') {
e.preventDefault()
e.stopPropagation()
if (workspaceSearchResults.length > 0) {
itemSelectedIndex =
(itemSelectedIndex - 1 + workspaceSearchResults.length) %
workspaceSearchResults.length
}
} else if (e.key === 'Enter') {
// Only select if not typing in the search input, or if results exist
if (workspaceSearchResults.length > 0) {
e.preventDefault()
e.stopPropagation()
const selectedItem = workspaceSearchResults[itemSelectedIndex]
if (selectedItem) {
handleWorkspaceItemSelect(selectedItem)
}
}
} else if (e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
handleBackClick()
}
} else if (stringSearch.length > 0) {
// Navigation in search view (flat list)
if (e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
if (filteredAvailableContext.length > 0) {
itemSelectedIndex = (itemSelectedIndex + 1) % filteredAvailableContext.length
}
} else if (e.key === 'ArrowUp') {
e.preventDefault()
e.stopPropagation()
if (filteredAvailableContext.length > 0) {
itemSelectedIndex =
(itemSelectedIndex - 1 + filteredAvailableContext.length) %
filteredAvailableContext.length
}
} else if (e.key === 'Enter' || e.key === 'Tab') {
if (e.key === 'Tab') e.preventDefault()
e.stopPropagation()
const selectedItem = filteredAvailableContext[itemSelectedIndex]
if (selectedItem) {
onSelect(selectedItem)
}
}
} else if (currentView === 'categories') {
// Navigation in categories view
if (e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
categorySelectedIndex = (categorySelectedIndex + 1) % availableCategories.length
} else if (e.key === 'ArrowUp') {
e.preventDefault()
e.stopPropagation()
categorySelectedIndex =
(categorySelectedIndex - 1 + availableCategories.length) % availableCategories.length
} else if (e.key === 'Enter' || e.key === 'ArrowRight' || e.key === 'Tab') {
e.preventDefault()
e.stopPropagation()
const selectedCategory = availableCategories[categorySelectedIndex]
if (selectedCategory) {
handleCategoryClick(selectedCategory.id)
}
} else if (e.key === 'Escape' || e.key === 'ArrowLeft') {
e.preventDefault()
e.stopPropagation()
setShowing?.(false)
}
} else {
// Navigation in category items view
if (e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
if (currentCategoryItems.length > 0) {
itemSelectedIndex = (itemSelectedIndex + 1) % currentCategoryItems.length
}
} else if (e.key === 'ArrowUp') {
e.preventDefault()
e.stopPropagation()
if (currentCategoryItems.length > 0) {
itemSelectedIndex =
(itemSelectedIndex - 1 + currentCategoryItems.length) % currentCategoryItems.length
}
} else if (e.key === 'Enter' || e.key === 'Tab') {
if (e.key === 'Tab') e.preventDefault()
e.stopPropagation()
const selectedItem = currentCategoryItems[itemSelectedIndex]
if (selectedItem) {
onSelect(selectedItem)
currentView = 'categories' // Go back to categories after selection
}
} else if (e.key === 'ArrowLeft' || e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
handleBackClick()
}
}
}
// Listen for keyboard events + clean up debounce timer
$effect(() => {
document.addEventListener('keydown', handleKeyDown)
return () => {
document.removeEventListener('keydown', handleKeyDown)
if (searchDebounceTimer) clearTimeout(searchDebounceTimer)
}
})
$effect(() => {
if (stringSearch.length > 0) {
itemSelectedIndex = 0
}
})
</script>
<div
class="flex flex-col gap-1 text-primary text-xs p-1 pr-0 min-w-24 max-h-48 overflow-y-scroll"
onmousedown={(e) => {
// avoids triggering onblur on the textinput and closing the tooltip
// but allow input elements to receive focus for the search input
if (!(e.target instanceof HTMLInputElement)) {
e.preventDefault()
}
}}
role="listbox"
tabindex={0}
>
{#if stringSearch.length > 0}
<!-- Search view - show flat list -->
{#each filteredAvailableContext as element, i (element.type + '-' + element.title)}
{@const Icon = ContextIconMap[element.type]}
<button
class="hover:bg-surface-hover rounded-md p-1 text-left flex flex-row gap-1 items-center font-normal transition-colors {i ===
itemSelectedIndex
? 'bg-surface-hover'
: ''}"
onclick={() => {
onSelect(element)
}}
>
{#if element.type === 'flow_module'}
<FlowModuleIcon module={element as FlowModule} size={16} />
{:else if Icon}
<Icon size={16} />
{/if}
<span class="truncate">
{element.type === 'diff' || element.type === 'flow_module'
? element.title.replace(/_/g, ' ')
: element.title}
</span>
</button>
{/each}
{#if filteredAvailableContext.length === 0}
<div class="text-center text-primary text-xs py-2">No matching context</div>
{/if}
{:else if currentView === 'categories'}
<!-- Categories view -->
{#each availableCategories as category, i (category.id)}
{@const Icon = category.icon}
<button
class="hover:bg-surface-hover rounded-md p-1 pr-0 text-left flex flex-row gap-1 items-center font-normal transition-colors {i ===
categorySelectedIndex
? 'bg-surface-hover'
: ''}"
onclick={() => handleCategoryClick(category.id)}
>
<Icon size={16} />
<span class="flex-1">{category.label}</span>
<ChevronRight size={16} />
</button>
{/each}
{#if availableCategories.length === 0}
<div class="text-center text-primary text-xs py-2">No available context</div>
{/if}
{:else if isSearchableView}
<!-- Workspace search view (scripts/flows) -->
<button
class="hover:bg-surface-hover rounded-md text-left flex flex-row gap-1 items-center font-normal transition-colors mb-1"
onclick={handleBackClick}
>
<ArrowLeft size={12} />
<span class="text-xs">Go back</span>
</button>
<input
bind:this={searchInputElement}
bind:value={workspaceSearchQuery}
oninput={handleSearchInput}
type="text"
placeholder="Search {currentView}..."
class="w-full text-xs px-2 py-1 rounded-md border border-gray-200 dark:border-gray-700 bg-surface mb-1 outline-none focus:border-blue-500"
/>
{#if workspaceSearchLoading}
<div class="flex items-center justify-center py-2 gap-1">
<Loader2 size={14} class="animate-spin" />
<span class="text-xs text-secondary">Searching...</span>
</div>
{:else if workspaceSearchResults.length === 0}
<div class="text-center text-secondary text-xs py-2">
No results found
</div>
{:else}
{#each workspaceSearchResults as item, i (currentView + '-' + item.path)}
{@const isAlreadySelected = selectedContext.some(
(c) =>
((c.type === 'workspace_script' && currentView === 'scripts') ||
(c.type === 'workspace_flow' && currentView === 'flows')) &&
c.title === item.path
)}
<button
class="hover:bg-surface-hover rounded-md p-1 text-left flex flex-col font-normal transition-colors {i ===
itemSelectedIndex
? 'bg-surface-hover'
: ''} {isAlreadySelected ? 'opacity-50' : ''}"
onclick={() => {
if (!isAlreadySelected) {
handleWorkspaceItemSelect(item)
}
}}
disabled={isAlreadySelected}
>
<div class="flex flex-row gap-1 items-center">
{#if currentView === 'scripts'}
<Code2 size={14} class="shrink-0" />
{:else}
<BarsStaggered size={14} class="shrink-0" />
{/if}
<span class="truncate">{item.path}</span>
</div>
{#if item.summary}
<span class="truncate text-secondary pl-5">{item.summary}</span>
{/if}
</button>
{/each}
{/if}
{:else}
<!-- Category items view -->
<button
class="hover:bg-surface-hover rounded-md text-left flex flex-row gap-1 items-center font-normal transition-colors mb-1"
onclick={handleBackClick}
>
<ArrowLeft size={12} />
<span class="text-xs">Go back</span>
</button>
{#if currentCategoryItems.length === 0}
<div class="text-center text-primary text-xs py-2">No items in this category</div>
{:else}
{#each currentCategoryItems as element, i (element.type + '-' + element.title)}
{@const Icon = ContextIconMap[element.type]}
<button
class="hover:bg-surface-hover rounded-md p-1 text-left flex flex-row gap-1 items-center font-normal transition-colors {i ===
itemSelectedIndex
? 'bg-surface-hover'
: ''}"
onclick={() => {
onSelect(element)
currentView = 'categories' // Go back to categories after selection
}}
>
{#if element.type === 'flow_module'}
<FlowModuleIcon module={element as FlowModule} size={16} />
{:else if Icon}
<Icon size={16} />
{/if}
<span class="truncate">
{element.type === 'diff' ? element.title.replace(/_/g, ' ') : element.title}
</span>
</button>
{/each}
{/if}
{/if}
</div>
@@ -0,0 +1,273 @@
<!--
@component
AI chat `@`-mention dropdown. Mounts the generic `DrillPicker` with a
unified tree:
Diffs / Modules / Databases / Workspace
├── All / Flows / Scripts
│ └── f/scope/sub/leaf …
The Diffs / Modules / Databases branches are synthesized from the chat's
in-memory `availableContext`. The Workspace branch delegates to
`buildWorkspaceTree` so the picker shares the workspace caching machinery
with the standalone picker used by `EditorHeader`.
On a workspace-leaf pick, emits a reference-only `WorkspaceScriptElement` /
`WorkspaceFlowElement` (path + title + summary). Content is materialized
at message-prep time by `AIChatManager` — see PR #9216.
-->
<script lang="ts">
import { workspaceStore } from '$lib/stores'
import { Database, Diff, Layers } from 'lucide-svelte'
import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte'
import FlowModuleIcon from '$lib/components/flows/FlowModuleIcon.svelte'
import RowIcon from '$lib/components/common/table/RowIcon.svelte'
import type { FlowModule } from '$lib/gen/types.gen'
import DrillPicker from '$lib/components/DrillPicker.svelte'
import type { DrillBranch, DrillIcon, DrillLeaf, DrillNode } from '$lib/components/drillPicker'
import { type WorkspaceItem, type WorkspaceItemKind } from '$lib/components/workspacePicker'
import { useWorkspaceItemsLoader } from '$lib/components/workspaceItemsLoader.svelte'
import { buildWorkspaceTree, relativizeWorkspacePath } from '$lib/components/workspaceTree'
import {
ContextIconMap,
type ContextElement,
type WorkspaceFlowElement,
type WorkspaceScriptElement
} from './context'
interface Props {
availableContext: ContextElement[]
selectedContext: ContextElement[]
onSelect: (element: ContextElement) => void
onSelectWorkspaceItem?: (element: ContextElement) => void
setShowing?: (showing: boolean) => void
externalFilter?: string
autoFocus?: boolean
}
let {
availableContext,
selectedContext,
onSelect,
onSelectWorkspaceItem,
setShowing,
externalFilter,
autoFocus = true
}: Props = $props()
// Chat tree leaves carry either a workspace path (resolved to content
// at pick time) or a runtime ContextElement (added directly).
type ChatLeafData = WorkspaceItem | ContextElement
let inner = $state<DrillPicker<ChatLeafData> | undefined>(undefined)
export function handleKeydown(e: KeyboardEvent) {
inner?.handleKeydown(e)
}
// Hide already-selected runtime context in the badge popover (no
// external filter). Keep them in the inline-search view so a re-match
// isn't suppressed (matches the prior `showAllAvailable={true}` path).
const hideSelected = $derived(externalFilter === undefined)
function isSelected(c: ContextElement): boolean {
return selectedContext.some((s) => s.type === c.type && s.title === c.title)
}
// Workspace state shared with WorkspaceItemDrillPicker via the loader.
// Chat surfaces flows and scripts only — apps aren't useful as @-mention
// context because they're frontends, not callable units.
const WORKSPACE_KINDS: WorkspaceItemKind[] = ['flow', 'script']
const loader = useWorkspaceItemsLoader(
() => $workspaceStore,
() => WORKSPACE_KINDS
)
function contextLeaf(c: ContextElement): DrillLeaf<ChatLeafData> {
const displayLabel =
c.type === 'diff' || c.type === 'flow_module' ? c.title.replace(/_/g, ' ') : c.title
return {
type: 'leaf',
key: `${c.type}:${c.title}`,
label: displayLabel,
// Keep the raw title (with underscores) in the search haystack so
// `@my_module` matches as well as the display form `my module`.
// Skip the join when the display form is the raw title itself
// (e.g. `db` elements) to avoid `"x x"` haystacks.
searchableText: displayLabel === c.title ? c.title : `${displayLabel} ${c.title}`,
data: c
}
}
function buildContextBranch(
id: 'diffs' | 'modules' | 'databases',
label: string,
icon: DrillIcon,
type: 'diff' | 'flow_module' | 'db'
): DrillBranch<ChatLeafData> | null {
const filtered = availableContext.filter(
(c) => c.type === type && (!hideSelected || !isSelected(c))
)
if (filtered.length === 0) return null
return {
type: 'branch',
key: id,
label,
icon,
searchGroup: true,
children: filtered.map(contextLeaf)
}
}
// True when the chat root collapses to the workspace subtree (no Diffs /
// Modules / Databases branches present). Drives handleScopeChange's
// at-root preload — only fires when scope `[]` literally IS the workspace
// root; otherwise we wait until the user enters the Workspace branch.
const isWorkspaceOnly = $derived(
!availableContext.some(
(c) =>
(c.type === 'diff' || c.type === 'flow_module' || c.type === 'db') &&
(!hideSelected || !isSelected(c))
)
)
const tree = $derived<DrillNode<ChatLeafData>[]>(
(() => {
const branches: DrillNode<ChatLeafData>[] = []
const diffs = buildContextBranch('diffs', 'Diffs', Diff, 'diff')
const modules = buildContextBranch('modules', 'Modules', BarsStaggered, 'flow_module')
const dbs = buildContextBranch('databases', 'Databases', Database, 'db')
if (diffs) branches.push(diffs)
if (modules) branches.push(modules)
if (dbs) branches.push(dbs)
const wsChildren = buildWorkspaceTree({
loaded: loader.loaded,
kinds: WORKSPACE_KINDS,
loadingKind: loader.loadingKind
}) as DrillNode<ChatLeafData>[]
// Workspace-only (e.g. global chat with no diffs/modules/dbs): skip
// the redundant 'Workspace' row and surface its children at the root.
if (branches.length === 0) return wsChildren
branches.push({
type: 'branch',
key: 'workspace',
label: 'Workspace',
icon: Layers,
children: wsChildren
})
return branches
})()
)
function handlePick(leaf: DrillLeaf<ChatLeafData>) {
const d = leaf.data
if ('kind' in d) {
// Workspace item — emit a reference-only workspace_* element.
// Content is fetched at message-prep time by the chat manager
// (see PR #9216 which switched workspace context to references).
if (!onSelectWorkspaceItem) return
if (d.kind === 'script') {
const element: WorkspaceScriptElement & { deletable: boolean } = {
type: 'workspace_script',
path: d.path,
title: d.path,
summary: d.summary,
deletable: true
}
onSelectWorkspaceItem(element)
} else if (d.kind === 'flow') {
const element: WorkspaceFlowElement & { deletable: boolean } = {
type: 'workspace_flow',
path: d.path,
title: d.path,
summary: d.summary,
deletable: true
}
onSelectWorkspaceItem(element)
}
// Apps are filtered out via kinds=['flow','script']; ignore.
} else {
// Runtime context element — added directly.
onSelect(d)
}
}
function handleScopeChange(scope: string[]) {
// Two possible layouts:
// (a) WRAPPED — `['workspace', 'kind:all', ...]` — chat with Diffs /
// Modules / Databases branches alongside Workspace.
// (b) UNWRAPPED — `['kind:all', ...]` or `['dir:flow:...']` — chat
// with only the workspace branch (global chat). The redundant
// 'workspace' wrapper is collapsed in the tree builder.
// Empty scope `[]` is the picker root: in (a) it's the chat root
// (don't preload — user hasn't entered Workspace yet), in (b) it's
// the workspace root itself (preload so kind branches don't render
// empty-without-spinner).
if (scope.length === 0) {
if (isWorkspaceOnly) loader.ensureAll()
return
}
const inWorkspace = scope[0] === 'workspace' || isWorkspaceOnly
if (!inWorkspace) return // diffs / modules / databases — synthesised, no fetch
const path = scope[0] === 'workspace' ? scope.slice(1) : scope
// Entering Workspace (wrapped: scope=['workspace']) or its 'All' sub-
// branch: preload every kind so the kind branches each show their
// spinner/items without a per-drill delay.
if (path.length === 0 || path[0] === 'kind:all') {
loader.ensureAll()
return
}
loader.ensureForScopeSegment(path[0])
}
// Close the picker on Escape. The badge popover's melt-ui handles Esc
// itself; for the inline-mention case (Portal-rendered, no melt) we
// listen at the document level. Skip when an upstream handler already
// claimed the event (defensive — melt-ui doesn't currently
// preventDefault on Esc, but a future host might).
function onDocumentKeydown(e: KeyboardEvent) {
if (e.key === 'Escape' && !e.defaultPrevented) {
setShowing?.(false)
}
}
$effect(() => {
document.addEventListener('keydown', onDocumentKeydown)
return () => document.removeEventListener('keydown', onDocumentKeydown)
})
</script>
{#snippet leafIcon(leaf: DrillLeaf<ChatLeafData>)}
{@const d = leaf.data}
{#if 'kind' in d}
<RowIcon kind={d.kind} size={12} />
{:else if d.type === 'flow_module'}
<FlowModuleIcon module={d as unknown as FlowModule} size={14} />
{:else}
{@const Icon = ContextIconMap[d.type]}
{#if Icon}<Icon size={12} class="shrink-0" />{/if}
{/if}
{/snippet}
{#snippet branchIcon(branch: DrillBranch<ChatLeafData>)}
{#if branch.key === 'kind:flow' || branch.key === 'kind:script' || branch.key === 'kind:app'}
{@const k = branch.key.slice(5) as WorkspaceItemKind}
<RowIcon kind={k} size={12} />
{:else if branch.icon}
{@const Icon = branch.icon}
<Icon size={12} class="shrink-0 text-tertiary" />
{/if}
{/snippet}
<DrillPicker
bind:this={inner}
{tree}
onPick={handlePick}
{externalFilter}
{autoFocus}
{leafIcon}
{branchIcon}
leafSecondary={(leaf, scope) =>
'kind' in leaf.data ? relativizeWorkspacePath(leaf.data.path, scope) : undefined}
onScopeChange={handleScopeChange}
onFilterChange={loader.onFilterChange}
/>
@@ -30,9 +30,13 @@
<Popover>
{#snippet trigger()}
{@const label =
contextElement.type === 'diff'
? contextElement.title.replace(/_/g, ' ')
: contextElement.title}
<div
class={twMerge(
'border rounded-md px-1 py-0.5 flex flex-row items-center gap-1 text-primary text-xs cursor-default hover:bg-surface-hover hover:cursor-pointer max-w-48 bg-surface'
'border rounded-md px-1 py-0.5 flex flex-row items-center gap-1 text-primary text-xs font-normal cursor-default hover:bg-surface-hover hover:cursor-pointer max-w-48 bg-surface'
)}
onmouseenter={() => (showDelete = true)}
onmouseleave={() => (showDelete = false)}
@@ -50,11 +54,7 @@
<SvelteComponent size={16} />
{/if}
</button>
<span class="truncate">
{contextElement.type === 'diff'
? contextElement.title.replace(/_/g, ' ')
: contextElement.title}
</span>
<span class="truncate" title={label}>{label}</span>
</div>
{/snippet}
{#snippet content()}
@@ -127,11 +127,7 @@
<div class="text-tertiary text-xs mb-1 px-2 pt-1">
{contextElement.source} (L{contextElement.startLine}-L{contextElement.endLine})
</div>
<HighlightCode
language="bun"
code={contextElement.content}
className="w-full p-2"
/>
<HighlightCode language="bun" code={contextElement.content} className="w-full p-2" />
</div>
{:else if contextElement.type === 'app_datatable'}
<div class="p-2 max-w-96 max-h-[300px] text-xs overflow-auto">
@@ -149,9 +149,17 @@ export default class ContextManager {
let newSelectedContext: ContextElement[] = [...currentlySelectedContext]
// Filter selected context to only include available items
// Filter selected context to only include available items. Workspace
// references (workspace_script / workspace_flow) are user-picked via
// the @-mention picker and intentionally aren't in availableContext —
// preserve them unconditionally so the badge survives editor refreshes.
newSelectedContext = newSelectedContext
.filter((c) => newAvailableContext.some((ac) => ac.type === c.type && ac.title === c.title))
.filter(
(c) =>
c.type === 'workspace_script' ||
c.type === 'workspace_flow' ||
newAvailableContext.some((ac) => ac.type === c.type && ac.title === c.title)
)
.map((c) =>
c.type === 'db' && dbSchemas[c.title]
? {
@@ -232,16 +240,22 @@ export default class ContextManager {
]
}
let newSelectedContext: ContextElement[] = [...currentlySelectedContext]
newSelectedContext = [
// Seed with the (refreshed) code block + everything else previously
// selected. The filter further down validates each entry against
// newAvailableContext (and the per-type allowlist for code_piece /
// workspace_*); types that are auto-derived (diff/error/db) survive
// when they're still in availableContext, user-picked workspace refs
// survive unconditionally, and `code` is excluded from the carryover
// because we just rebuilt it.
let newSelectedContext: ContextElement[] = [
{
type: 'code',
title: this.getContextCodePath(scriptOptions) ?? '',
content: scriptOptions.code,
lang: scriptOptions.lang,
deletable: false
}
},
...currentlySelectedContext.filter((c) => c.type !== 'code')
]
const db = this.getSelectedDBSchema(scriptOptions, dbSchemas)
@@ -265,22 +279,33 @@ export default class ContextManager {
(c) =>
(c.type === 'code_piece' && scriptOptions.code.includes(c.content)) ||
c.type === 'code' ||
// Workspace references are user-picked via @-mention and not in
// availableContext; preserve so badges survive editor refreshes.
c.type === 'workspace_script' ||
c.type === 'workspace_flow' ||
newAvailableContext.some((ac) => ac.type === c.type && ac.title === c.title)
)
.map((c) =>
c.type === 'code'
? {
...c,
content: scriptOptions.code,
title: this.getContextCodePath(scriptOptions)
}
: c.type === 'db' && dbSchemas[c.title]
? {
...c,
schema: dbSchemas[c.title]
}
: c
)
.map((c) => {
if (c.type === 'code') {
return {
...c,
content: scriptOptions.code,
title: this.getContextCodePath(scriptOptions)
}
}
if (c.type === 'db' && dbSchemas[c.title]) {
return { ...c, schema: dbSchemas[c.title] }
}
// For other auto-derived types (diff, error), rehydrate from the
// freshly-built newAvailableContext so the carryover doesn't keep
// stale `content` / `diff` payloads — preserve the user-set
// `deletable` flag on top of the fresh entry.
const fresh = newAvailableContext.find((ac) => ac.type === c.type && ac.title === c.title)
if (fresh && 'deletable' in c) {
return { ...fresh, deletable: c.deletable } as ContextElement
}
return fresh ?? c
})
this.availableContext = newAvailableContext
this.selectedContext = newSelectedContext
@@ -1,22 +1,26 @@
<script lang="ts">
import autosize from '$lib/autosize'
import { tick } from 'svelte'
import type { ContextElement } from './context'
import AvailableContextList from './AvailableContextList.svelte'
import ChatContextPicker from './ChatContextPicker.svelte'
import Portal from '$lib/components/Portal.svelte'
import { zIndexes } from '$lib/zIndexes'
import { twMerge } from 'tailwind-merge'
import { CHAT_INPUT_PADDING } from './aiChatManagerContext'
import { createFloatingActions, createVirtualElement } from 'svelte-floating-ui'
import { flip, offset, shift } from 'svelte-floating-ui/dom'
interface Props {
value: string
availableContext: ContextElement[]
selectedContext: ContextElement[]
isFirstMessage: boolean
placeholder: string
disabled: boolean
onSendRequest: () => void
onAddContext: (contextElement: ContextElement) => void
/** Called when the user deletes a previously-inserted `@title` mention
* from the textarea. The host should drop the matching entry from
* selectedContext (only items with `deletable !== false` are reported). */
onRemoveContext?: (contextElement: ContextElement) => void
className?: string
onKeyDown?: (e: KeyboardEvent) => void
}
@@ -25,21 +29,58 @@
value = $bindable(''),
availableContext,
selectedContext,
isFirstMessage,
placeholder,
disabled,
onSendRequest,
onAddContext,
onRemoveContext,
className = '',
onKeyDown = undefined
}: Props = $props()
const MENTION_RE = /@[\w/.\-\[\]]+/g
function extractMentions(text: string): Set<string> {
const out = new Set<string>()
for (const m of text.matchAll(MENTION_RE)) out.add(m[0].slice(1))
return out
}
// Titles currently appearing as `@title` mentions in the textarea. Compared
// against the previous snapshot in a $effect (NOT inside handleInput —
// the picker mutates `value` programmatically via `updateInstructionsWithContext`,
// which doesn't fire `oninput`, so a handleInput-only diff goes stale).
const mentionedTitles = $derived(extractMentions(value))
let prevMentionedTitles = $state<Set<string>>(new Set())
let showContextTooltip = $state(false)
let contextTooltipWord = $state('')
let tooltipPosition = $state({ x: 0, y: 0 })
let textarea = $state<HTMLTextAreaElement | undefined>(undefined)
let tooltipElement = $state<HTMLDivElement | undefined>(undefined)
let tooltipCurrentViewNumber = $state(0)
let chatContextPicker: ChatContextPicker | undefined = $state()
// Virtual reference anchored at the `@` that opened the mention (not the
// caret), so the picker stays put while the user types the query.
// svelte-floating-ui's `createVirtualElement` takes a raw ClientRect and
// wraps it in a function internally — re-`update()` on each anchor move.
let anchorRect: DOMRect = new DOMRect(0, 0, 1, 16)
const anchorRef = createVirtualElement({ getBoundingClientRect: anchorRect })
const [floatingRef, floatingContent, updateFloating] = createFloatingActions({
strategy: 'fixed',
placement: 'bottom-start',
// flip handles above/below only; horizontal overflow is solved by shift
// (picker slides left to fit) instead of flipping to `bottom-end` which
// would re-anchor the picker's right edge to the `@`.
middleware: [offset(6), flip({ crossAxis: false }), shift({ padding: 10 })],
autoUpdate: true
})
// Calling the reference action as a function (instead of `use:floatingRef`
// on a DOM node): svelte-floating-ui's `referenceAction` detects
// `'subscribe' in node` and subscribes to the virtual-element store. This
// is the supported path for virtual references — see the library's
// `referenceAction` / `setupVirtualElementObserver` in dist/index.js.
floatingRef(anchorRef)
// Properties to copy for caret position calculation
const properties = [
@@ -162,7 +203,7 @@
availableContext.find((c) => c.title === title) ||
selectedContext.find((c) => c.title === title)
if (inContext) {
return `<span class="bg-black dark:bg-white text-white dark:text-black z-10">${match}</span>`
return `<span class="bg-surface-accent-selected text-primary rounded box-decoration-clone z-10">${match}</span>`
}
return match
})
@@ -186,73 +227,30 @@
showContextTooltip = false
}
async function updateTooltipPosition(currentViewItemsNumber: number) {
function updateAnchorRect() {
if (!textarea) return
try {
const coords = getCaretCoordinates(textarea, textarea.selectionEnd)
// Index of the `@` that started the current mention. handleInput
// only opens the picker when `contextTooltipWord` (= `@xxx`) is the
// LAST whitespace-separated word in `value`, so the `@` always sits
// at `value.length - contextTooltipWord.length`.
const atIndex = value.length - contextTooltipWord.length
const coords = getCaretCoordinates(textarea, atIndex)
const rect = textarea.getBoundingClientRect()
const itemHeight = 28 // Estimated height of one item + gap (Button: p-1(8px) + text-xs(16px) = 24px; Parent: gap-1(4px) = 28px)
const containerPadding = 8 // p-1 top + p-1 bottom = 4px + 4px = 8px
const maxHeight = 192 + containerPadding // max-h-48 (192px) + containerPadding (8px)
// Calculate uncapped height, subtract gap from last item as it's not needed
const numItems = currentViewItemsNumber
let uncappedHeight =
numItems > 0 ? numItems * itemHeight - 4 + containerPadding : containerPadding
// Ensure height is at least containerPadding even if no items
uncappedHeight = Math.max(uncappedHeight, containerPadding)
const estimatedTooltipHeight = Math.min(uncappedHeight, maxHeight)
const margin = 6 // Small margin between caret and tooltip
// Initial position calculation
let finalX = rect.left + coords.left - 70
let finalY: number
if (isFirstMessage) {
// Position below the caret line
finalY = rect.top + coords.top + coords.height - 3
} else {
// Position above the caret line
finalY = rect.top + coords.top - estimatedTooltipHeight - margin
}
// Set initial position
tooltipPosition = {
x: finalX,
y: finalY
}
// Wait for tooltip to render with initial position
await tick()
// Get actual tooltip width if tooltip is rendered
if (tooltipElement) {
const tooltipRect = tooltipElement.getBoundingClientRect()
const tooltipWidth = tooltipRect.width
// Adjust position if tooltip would overflow right edge
if (finalX + tooltipWidth > window.innerWidth) {
finalX = Math.max(10, window.innerWidth - tooltipWidth - 10)
// Update position after measuring actual width
tooltipPosition = {
x: finalX,
y: finalY
}
}
}
anchorRect = new DOMRect(rect.left + coords.left, rect.top + coords.top, 1, coords.height)
// Re-prime the virtual ref then kick floating-ui (autoUpdate only fires
// on scroll/resize, not on text changes inside the textarea).
anchorRef.update({ getBoundingClientRect: anchorRect })
updateFloating()
} catch (error) {
// Hide tooltip on any error related to position calculation
console.error('Error updating tooltip position', error)
console.error('Error computing anchor rect', error)
showContextTooltip = false
}
}
function handleInput(e: Event) {
textarea = e.target as HTMLTextAreaElement
const words = value.split(/\s+/)
const lastWord = words[words.length - 1]
@@ -276,7 +274,24 @@
}
if (showContextTooltip) {
// avoid new line after Enter in the tooltip
// Forward navigation keys to the picker so the textarea-focused
// user can drive it. The picker preventDefault/stopPropagation's
// the ones it handles; we still preventDefault Enter so it never
// inserts a newline even if no item is highlighted. ArrowLeft /
// ArrowRight forward too but the picker only consumes them when
// the search query is empty — so cursor movement within `@xxx`
// still works once the user has typed past the `@`.
if (
e.key === 'ArrowDown' ||
e.key === 'ArrowUp' ||
e.key === 'ArrowLeft' ||
e.key === 'ArrowRight' ||
e.key === 'Enter' ||
e.key === 'Tab' ||
e.key === 'Escape'
) {
chatContextPicker?.handleKeydown(e)
}
if (e.key === 'Enter') {
e.preventDefault()
}
@@ -290,14 +305,54 @@
}
$effect(() => {
if (showContextTooltip) {
updateTooltipPosition(tooltipCurrentViewNumber)
// Re-track on every value change. The `@` position can shift when the
// user adds/deletes text BEFORE it (line wrap, etc.); the picker should
// follow. floating-ui's autoUpdate only fires on scroll/resize.
void value
if (showContextTooltip) updateAnchorRect()
})
$effect(() => {
// Mention-removal sync: any title that was a `@mention` last frame and
// is gone now → drop the matching selectedContext entry. Reactive (not
// inside handleInput) so it catches both keystroke deletions AND any
// programmatic value changes from the picker insertion path.
const prev = prevMentionedTitles
const cur = mentionedTitles
for (const title of prev) {
if (cur.has(title)) continue
const entry = selectedContext.find((c) => c.title === title && c.deletable !== false)
if (entry) onRemoveContext?.(entry)
}
prevMentionedTitles = cur
})
export function focus() {
textarea?.focus()
}
// Wipe after dispatching a send: pre-zero `prevMentionedTitles` so the
// effect above sees no diff when `value` clears, leaving `selectedContext`
// untouched until `AIChatManager.beforeSend` snapshots it. A manual
// textarea clear by the user keeps the old behaviour (badges drop).
export function clearForSend() {
prevMentionedTitles = new Set()
value = ''
}
// Called by the host BEFORE it strips a mention token from `value`
// (badge-delete path). Drops the title from `prevMentionedTitles` so when
// the strip lands, the effect sees no diff and doesn't dispatch another
// `onRemoveContext` — the host has already mutated `selectedContext`.
// Critical when two `selectedContext` entries share a title (workspace
// script + flow with same path): without this, the effect would find the
// surviving sibling by title and remove it too.
export function unsyncMention(title: string) {
if (!prevMentionedTitles.has(title)) return
const next = new Set(prevMentionedTitles)
next.delete(title)
prevMentionedTitles = next
}
</script>
<div class="relative w-full scroll-pb-2 bg-surface">
@@ -343,10 +398,12 @@
<Portal target="body">
<div
bind:this={tooltipElement}
class="absolute bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg"
style="left: {tooltipPosition.x}px; top: {tooltipPosition.y}px; z-index: {zIndexes.tooltip};"
use:floatingContent
class="bg-surface border border-gray-200 dark:border-gray-700 rounded-md shadow-lg overflow-hidden"
style="z-index: {zIndexes.tooltip};"
>
<AvailableContextList
<ChatContextPicker
bind:this={chatContextPicker}
{availableContext}
{selectedContext}
onSelect={(element) => {
@@ -356,14 +413,10 @@
onAddContext(element)
updateInstructionsWithContext(element)
showContextTooltip = false
// Refocus the textarea since focus may have been on the search input
setTimeout(() => textarea?.focus(), 0)
}}
showAllAvailable={true}
stringSearch={contextTooltipWord.slice(1)}
onViewChange={(newNumber) => {
tooltipCurrentViewNumber = newNumber
}}
externalFilter={contextTooltipWord.slice(1)}
autoFocus={false}
setShowing={(showing) => {
showContextTooltip = showing
}}
@@ -0,0 +1,183 @@
import { describe, it, expect } from 'vitest'
import {
collectLeavesGrouped,
leafHaystack,
resolveScope,
scopeChain,
type DrillBranch,
type DrillLeaf,
type DrillNode
} from './drillPicker'
const leaf = (key: string, label = key, secondary?: string): DrillLeaf<string> => ({
type: 'leaf',
key,
label,
secondary,
data: key
})
const branch = (
key: string,
children: DrillNode<string>[],
opts: { label?: string; omitFromSearch?: boolean; searchGroup?: boolean } = {}
): DrillBranch<string> => ({
type: 'branch',
key,
label: opts.label ?? key,
children,
omitFromSearch: opts.omitFromSearch,
searchGroup: opts.searchGroup
})
describe('resolveScope', () => {
const tree: DrillNode<string>[] = [
branch('a', [branch('a.x', [leaf('a.x.1')]), leaf('a.2')]),
branch('b', [leaf('b.1')]),
leaf('top')
]
it('returns null at the root (empty scope)', () => {
expect(resolveScope(tree, [])).toBeNull()
})
it('returns the branch at a one-level scope', () => {
expect(resolveScope(tree, ['a'])?.key).toBe('a')
})
it('returns the branch at a nested scope', () => {
expect(resolveScope(tree, ['a', 'a.x'])?.key).toBe('a.x')
})
it('returns null when any segment is missing', () => {
expect(resolveScope(tree, ['a', 'missing'])).toBeNull()
expect(resolveScope(tree, ['nope'])).toBeNull()
})
it('returns null when a segment resolves to a leaf (not a branch)', () => {
expect(resolveScope(tree, ['top'])).toBeNull()
expect(resolveScope(tree, ['a', 'a.2'])).toBeNull()
})
})
describe('scopeChain', () => {
const tree: DrillNode<string>[] = [
branch('a', [branch('a.x', [leaf('a.x.1')]), leaf('a.2')]),
branch('b', [leaf('b.1')])
]
it('returns [] at the root', () => {
expect(scopeChain(tree, [])).toEqual([])
})
it('returns one branch for a one-level scope', () => {
const chain = scopeChain(tree, ['a'])
expect(chain.map((b) => b.key)).toEqual(['a'])
})
it('returns each branch along the path for a nested scope', () => {
const chain = scopeChain(tree, ['a', 'a.x'])
expect(chain.map((b) => b.key)).toEqual(['a', 'a.x'])
})
it('stops at the first missing/non-branch segment', () => {
const chain = scopeChain(tree, ['a', 'a.2', 'never-reached'])
expect(chain.map((b) => b.key)).toEqual(['a'])
})
})
describe('collectLeavesGrouped', () => {
it('flattens all leaves with null group when no branch has searchGroup', () => {
const tree: DrillNode<string>[] = [branch('a', [leaf('a.1')]), leaf('top')]
const result = collectLeavesGrouped(tree)
expect(result.map((r) => [r.leaf.key, r.group?.key])).toEqual([
['a.1', undefined],
['top', undefined]
])
})
it('groups leaves under their nearest searchGroup ancestor', () => {
const tree: DrillNode<string>[] = [
branch('flows', [branch('flows-folder', [leaf('flows-folder.1')]), leaf('flows.root')], {
searchGroup: true
})
]
const result = collectLeavesGrouped(tree)
expect(result.map((r) => [r.leaf.key, r.group?.key])).toEqual([
['flows-folder.1', 'flows'],
['flows.root', 'flows']
])
})
it('the DEEPEST searchGroup wins when nested', () => {
const tree: DrillNode<string>[] = [
branch('outer', [branch('inner', [leaf('deep')], { searchGroup: true })], {
searchGroup: true
})
]
const result = collectLeavesGrouped(tree)
expect(result[0].group?.key).toBe('inner')
})
it('skips branches marked omitFromSearch entirely', () => {
const tree: DrillNode<string>[] = [
branch('all', [leaf('shared')], { omitFromSearch: true }),
branch('flows', [leaf('shared'), leaf('uniq')], { searchGroup: true })
]
const result = collectLeavesGrouped(tree)
// `all` branch is skipped, so `shared` is only seen once and grouped under `flows`.
expect(result.map((r) => [r.leaf.key, r.group?.key])).toEqual([
['shared', 'flows'],
['uniq', 'flows']
])
})
it('deduplicates leaves by key (first occurrence wins)', () => {
// Simulate the workspace 'All' branch (omitFromSearch=true) plus per-kind
// branches having the same leaf — even without omitFromSearch the dedup
// would still guarantee no double-counting if the search tree changes.
const tree: DrillNode<string>[] = [
branch('flows', [leaf('a')], { searchGroup: true }),
branch('scripts', [leaf('a')], { searchGroup: true })
]
const result = collectLeavesGrouped(tree)
expect(result.length).toBe(1)
expect(result[0].group?.key).toBe('flows')
})
it('handles a mix of top-level leaves and branches', () => {
const tree: DrillNode<string>[] = [
leaf('root-leaf'),
branch('b', [leaf('b.1')], { searchGroup: true })
]
const result = collectLeavesGrouped(tree)
expect(result.map((r) => [r.leaf.key, r.group?.key])).toEqual([
['root-leaf', undefined],
['b.1', 'b']
])
})
})
describe('leafHaystack', () => {
it('uses searchableText when present (overrides label/secondary)', () => {
expect(leafHaystack({ ...leaf('k', 'Label'), searchableText: 'custom' })).toBe('custom')
})
it('joins label and secondary with parens when both are present', () => {
expect(leafHaystack(leaf('k', 'My Flow', 'f/demo/my_flow'))).toBe('My Flow (f/demo/my_flow)')
})
it('uses just label when secondary is absent', () => {
expect(leafHaystack(leaf('k', 'just label'))).toBe('just label')
})
it('falls back to secondary when label is empty', () => {
expect(leafHaystack({ type: 'leaf', key: 'k', label: '', secondary: 'sec', data: 'd' })).toBe(
'sec'
)
})
it('returns the empty string when nothing is set', () => {
expect(leafHaystack({ type: 'leaf', key: 'k', label: '', data: 'd' })).toBe('')
})
})
+116
View File
@@ -0,0 +1,116 @@
import type { Component, ComponentType } from 'svelte'
/** Icon constructor accepted by the picker — covers Svelte-5 `Component` and
* legacy `ComponentType` (lucide icons resolve to the former, but other
* callers in the repo still hand in the latter, see `TriggersBadge.svelte`). */
export type DrillIcon = ComponentType | Component<any, {}, ''>
/** Leaf node — terminal entry the user picks. The picker emits the leaf
* back via `onPick` so callers can react with the original `data` payload. */
export type DrillLeaf<L> = {
type: 'leaf'
key: string
/** Primary line. */
label: string
/** Optional secondary line (e.g. full path). */
secondary?: string
/** Lucide-style component rendered with `size={12}`. The picker also
* accepts a `leafIcon` snippet override that gets the whole leaf. */
icon?: DrillIcon
data: L
/** Optional override for the fuzzy-search haystack. Defaults to
* `label` (or `secondary` when label is empty). */
searchableText?: string
/** Marks this leaf as the user's current location — gets `aria-current`
* and a styled, no-op click. */
current?: boolean
/** When true, leaf is rendered but disabled (greyed + no-op click). */
disabled?: boolean
}
/** Branch node — interior entry the user drills into. */
export type DrillBranch<L> = {
type: 'branch'
key: string
label: string
icon?: DrillIcon
children: DrillNode<L>[]
/** Show a spinner alongside the branch (async loading in progress). */
loading?: boolean
/** Hide from search index traversal. Used by the workspace adapter to
* keep the cross-kind 'all' branch out of search (its leaves are
* duplicates of the per-kind branches' leaves). */
omitFromSearch?: boolean
/** When true, leaves under this branch are grouped under its label in
* the search-results display. The DEEPEST such ancestor wins. Used to
* collapse folder hierarchies into kind/section headers — e.g. a leaf
* at `Workspace > Flows > f/demo > foo` groups under "Flows" (not
* "f/demo"). */
searchGroup?: boolean
}
export type DrillNode<L> = DrillBranch<L> | DrillLeaf<L>
/** Walk the tree to the branch at the given scope path. Returns null at
* root (empty scope) or when any segment doesn't resolve to a branch. */
export function resolveScope<L>(tree: DrillNode<L>[], scope: string[]): DrillBranch<L> | null {
if (scope.length === 0) return null
let level: DrillNode<L>[] = tree
let current: DrillBranch<L> | null = null
for (const key of scope) {
const node = level.find((n) => n.key === key)
if (!node || node.type !== 'branch') return null
current = node
level = node.children
}
return current
}
/** Walk the tree to the branch at scope, returning ALL branches along the
* path (for breadcrumb rendering). The root is implicit and not returned. */
export function scopeChain<L>(tree: DrillNode<L>[], scope: string[]): DrillBranch<L>[] {
const chain: DrillBranch<L>[] = []
let level: DrillNode<L>[] = tree
for (const key of scope) {
const node = level.find((n) => n.key === key)
if (!node || node.type !== 'branch') break
chain.push(node)
level = node.children
}
return chain
}
/** Flatten the tree into a leaf list with each leaf's deepest
* `searchGroup`-anchor ancestor (or null if none). Skips branches marked
* `omitFromSearch`. Deduplicates leaves by `key` (first occurrence wins). */
export function collectLeavesGrouped<L>(
tree: DrillNode<L>[]
): { leaf: DrillLeaf<L>; group: DrillBranch<L> | null }[] {
const out: { leaf: DrillLeaf<L>; group: DrillBranch<L> | null }[] = []
const seen = new Set<string>()
function walk(nodes: DrillNode<L>[], group: DrillBranch<L> | null) {
for (const n of nodes) {
if (n.type === 'leaf') {
if (!seen.has(n.key)) {
seen.add(n.key)
out.push({ leaf: n, group })
}
} else {
if (n.omitFromSearch) continue
// Deeper `searchGroup` anchors override shallower ones.
const nextGroup = n.searchGroup ? n : group
walk(n.children, nextGroup)
}
}
}
walk(tree, null)
return out
}
/** Fuzzy-search haystack string for a leaf. */
export function leafHaystack<L>(leaf: DrillLeaf<L>): string {
if (leaf.searchableText) return leaf.searchableText
if (leaf.label && leaf.secondary) return `${leaf.label} (${leaf.secondary})`
return leaf.label || leaf.secondary || ''
}
@@ -0,0 +1,109 @@
import { untrack } from 'svelte'
import {
getCachedItems,
loadKind,
type WorkspaceItem,
type WorkspaceItemKind
} from './workspacePicker'
/**
* Shared loader for workspace items in drill pickers. Owns the
* `loaded` / `loadingKind` state, the stale-while-revalidate `ensureLoaded`
* coroutine, the `kind:` / `dir:` scope-segment decoder, and the
* "load every kind on first search" filter callback.
*
* Both `WorkspaceItemDrillPicker` and `ChatContextPicker` mount a
* `DrillPicker` over a workspace tree built from these maps. They each
* keep their own scope-walking policy (chat collapses an optional
* `'workspace'` wrapper segment; workspace handles single-kind mode at
* the top), but the kind decoding and lazy fetch live here.
*
* Both getters are read inside the returned closures so changing
* workspace or kinds after mount Just Works.
*/
export function useWorkspaceItemsLoader(
workspace: () => string | undefined,
kinds: () => readonly WorkspaceItemKind[]
) {
// Seed from the module-level cache so kinds already fetched in this
// session render on the first frame. Re-fetching `ensureLoaded` later
// quietly swaps in fresh data (stale-while-revalidate).
let loaded = $state<Partial<Record<WorkspaceItemKind, WorkspaceItem[]>>>(
(() => {
const ws = untrack(workspace)
if (!ws) return {}
const out: Partial<Record<WorkspaceItemKind, WorkspaceItem[]>> = {}
for (const k of untrack(kinds)) {
const cached = getCachedItems(ws, k)
if (cached) out[k] = cached
}
return out
})()
)
let loadingKind = $state<Partial<Record<WorkspaceItemKind, boolean>>>({})
async function ensureLoaded(kind: WorkspaceItemKind) {
const ws = workspace()
if (!ws) return
// `loaded[kind]` read inside `untrack` so callers wiring this into
// a reactive context (DrillPicker's onFilterChange effect) don't
// subscribe to a signal `ensureLoaded` itself writes — that would
// re-fire the effect on every assignment and busy-loop.
if (!untrack(() => loaded[kind])) loadingKind[kind] = true
try {
const items = await loadKind(ws, kind)
loaded[kind] = items
} finally {
loadingKind[kind] = false
}
}
function ensureAll() {
for (const k of kinds()) ensureLoaded(k)
}
/** Decode one scope segment and trigger loads for the kind(s) it refers to.
* Accepts:
* - `kind:<k>` (or `kind:all` — loads everything)
* - `dir:<k>:<path>` (the single-kind layout where there's no `kind:`
* wrapper at the top of the path)
* Unknown segments and kinds outside the current `kinds()` set are
* ignored — the caller has already filtered scope chains it cares about.
*/
function ensureForScopeSegment(segment: string) {
const ks = kinds()
const triggerKind = (k: string) => {
if (k === 'all') return ensureAll()
if ((ks as readonly string[]).includes(k)) ensureLoaded(k as WorkspaceItemKind)
}
if (segment.startsWith('kind:')) {
triggerKind(segment.slice(5))
return
}
if (segment.startsWith('dir:')) {
const rest = segment.slice(4)
const colon = rest.indexOf(':')
if (colon > 0) triggerKind(rest.slice(0, colon))
}
}
/** Global search → load every kind so results appear across the tree.
* Skip on the empty filter so a bare mount doesn't cold-load anything. */
function onFilterChange(filter: string) {
if (filter.trim() === '') return
ensureAll()
}
return {
get loaded() {
return loaded
},
get loadingKind() {
return loadingKind
},
ensureLoaded,
ensureAll,
ensureForScopeSegment,
onFilterChange
}
}
@@ -0,0 +1,358 @@
import { describe, it, expect } from 'vitest'
import { buildWorkspaceTree, legacyScopeToPath, relativizeWorkspacePath } from './workspaceTree'
import {
dirKey,
kindKey,
leafKeyFor,
type WorkspaceItem,
type WorkspaceItemKind
} from './workspacePicker'
import type { DrillBranch, DrillLeaf, DrillNode } from './drillPicker'
const item = (
kind: WorkspaceItemKind,
path: string,
summary?: string,
raw_app?: boolean
): WorkspaceItem => ({ kind, path, summary: summary ?? '', raw_app })
const isBranch = <L>(n: DrillNode<L> | undefined): n is DrillBranch<L> => !!n && n.type === 'branch'
const isLeaf = <L>(n: DrillNode<L> | undefined): n is DrillLeaf<L> => !!n && n.type === 'leaf'
const childKeys = <L>(b: DrillBranch<L>) => b.children.map((c) => c.key)
const findBranch = <L>(nodes: DrillNode<L>[], key: string): DrillBranch<L> => {
const n = nodes.find((x) => x.key === key)
if (!isBranch(n)) throw new Error(`expected branch ${key} in [${nodes.map((x) => x.key)}]`)
return n
}
describe('buildWorkspaceTree', () => {
describe('shape', () => {
it('returns an empty tree when kinds is empty', () => {
expect(buildWorkspaceTree({ loaded: {}, kinds: [], loadingKind: {} })).toEqual([])
})
it('multi-kind: prepends an All branch then per-kind branches', () => {
const tree = buildWorkspaceTree({
loaded: {
flow: [item('flow', 'f/demo/a')],
script: [item('script', 'f/demo/b')]
},
kinds: ['flow', 'script'],
loadingKind: {}
})
expect(tree.map((n) => n.key)).toEqual([kindKey('all'), kindKey('flow'), kindKey('script')])
})
it('All branch is omitFromSearch and labeled "All"', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a')], script: [] },
kinds: ['flow', 'script'],
loadingKind: {}
})
const all = findBranch(tree, kindKey('all'))
expect(all.omitFromSearch).toBe(true)
expect(all.label).toBe('All')
})
it('per-kind branches are searchGroup anchors', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a')], script: [] },
kinds: ['flow', 'script'],
loadingKind: {}
})
const flow = findBranch(tree, kindKey('flow'))
expect(flow.searchGroup).toBe(true)
})
it("single-kind: returns that kind branch's children directly (no kind-level)", () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a'), item('flow', 'u/alice/b')] },
kinds: ['flow'],
loadingKind: {}
})
// At the top we should see the scope dirs (f/demo, u/alice) directly,
// not a single 'kind:flow' branch wrapping them.
expect(tree.every((n) => isBranch(n) && n.key.startsWith('dir:flow:'))).toBe(true)
// f-scopes come before u-scopes
expect(tree.map((n) => n.key)).toEqual([dirKey('flow', 'f/demo'), dirKey('flow', 'u/alice')])
})
})
describe('loading state', () => {
it('per-kind branch is loading=true when loaded[k] is undefined and loadingKind[k] is true', () => {
const tree = buildWorkspaceTree({
loaded: {},
kinds: ['flow', 'script'],
loadingKind: { flow: true }
})
const flow = findBranch(tree, kindKey('flow'))
expect(flow.loading).toBe(true)
})
it('per-kind branch is not loading once loaded[k] is set, even mid-refetch', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [] },
kinds: ['flow', 'script'],
loadingKind: { flow: true }
})
const flow = findBranch(tree, kindKey('flow'))
expect(flow.loading).toBeFalsy()
})
it('All branch is loading when any kind is loading', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [] },
kinds: ['flow', 'script'],
loadingKind: { script: true }
})
const all = findBranch(tree, kindKey('all'))
expect(all.loading).toBe(true)
})
})
describe('dir forest', () => {
it('groups leaves under their scope, then nested folders', () => {
const tree = buildWorkspaceTree({
loaded: {
flow: [
item('flow', 'f/demo/a'),
item('flow', 'f/demo/sub/b'),
item('flow', 'f/demo/sub/c'),
item('flow', 'u/alice/d')
]
},
kinds: ['flow'],
loadingKind: {}
})
// Top-level: f/demo (folder scope), u/alice (user scope)
expect(tree.map((n) => n.key)).toEqual([dirKey('flow', 'f/demo'), dirKey('flow', 'u/alice')])
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
// Children: nested folder `sub` first, then leaf `a`
expect(childKeys(demo)).toEqual([
dirKey('flow', 'f/demo/sub'),
leafKeyFor('flow', 'f/demo/a')
])
const sub = findBranch(demo.children, dirKey('flow', 'f/demo/sub'))
expect(childKeys(sub)).toEqual([
leafKeyFor('flow', 'f/demo/sub/b'),
leafKeyFor('flow', 'f/demo/sub/c')
])
})
it('skips items with paths shorter than 3 segments', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo'), item('flow', 'f/demo/a')] },
kinds: ['flow'],
loadingKind: {}
})
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
expect(childKeys(demo)).toEqual([leafKeyFor('flow', 'f/demo/a')])
})
})
describe('leaf shape', () => {
it('uses summary as label and path as secondary when summary is present', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a', 'Hello')] },
kinds: ['flow'],
loadingKind: {}
})
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
const leaf = demo.children[0]
if (!isLeaf(leaf)) throw new Error('expected leaf')
expect(leaf.label).toBe('Hello')
expect(leaf.secondary).toBe('f/demo/a')
})
it('falls back to path as label when summary is empty', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a')] },
kinds: ['flow'],
loadingKind: {}
})
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
const leaf = demo.children[0]
if (!isLeaf(leaf)) throw new Error('expected leaf')
expect(leaf.label).toBe('f/demo/a')
expect(leaf.secondary).toBeUndefined()
})
it('marks the currentItem leaf with current=true', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a'), item('flow', 'f/demo/b')] },
kinds: ['flow'],
loadingKind: {},
currentItem: item('flow', 'f/demo/a')
})
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
const [a, b] = demo.children
if (!isLeaf(a) || !isLeaf(b)) throw new Error('expected leaves')
expect(a.current).toBe(true)
expect(b.current).toBeFalsy()
})
})
describe('withCurrent: rename suppression', () => {
it('injects currentItem at its live path when not already in the list', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [] },
kinds: ['flow'],
loadingKind: {},
currentItem: { ...item('flow', 'f/demo/new'), summary: 'My Flow' }
})
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
expect(demo.children.map((c) => c.key)).toEqual([leafKeyFor('flow', 'f/demo/new')])
})
it('drops the savedPath entry during a mid-rename so only the live one shows', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/old', 'My Flow')] },
kinds: ['flow'],
loadingKind: {},
currentItem: { ...item('flow', 'f/demo/new', 'My Flow'), savedPath: 'f/demo/old' }
})
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
const paths = demo.children.map((c) => c.key)
expect(paths).toContain(leafKeyFor('flow', 'f/demo/new'))
expect(paths).not.toContain(leafKeyFor('flow', 'f/demo/old'))
})
it('does not re-inject when the live entry already exists in loaded', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a', 'Original')] },
kinds: ['flow'],
loadingKind: {},
currentItem: item('flow', 'f/demo/a', 'Original')
})
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
expect(demo.children.length).toBe(1)
})
it('passes other-kind items through untouched', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a')], script: [item('script', 'f/demo/b')] },
kinds: ['flow', 'script'],
loadingKind: {},
currentItem: { ...item('flow', 'f/demo/new'), savedPath: 'f/demo/old' }
})
const script = findBranch(tree, kindKey('script'))
const demo = findBranch(script.children, dirKey('script', 'f/demo'))
expect(demo.children.map((c) => c.key)).toEqual([leafKeyFor('script', 'f/demo/b')])
})
})
describe('extraItemsByKind (drafts)', () => {
it('merges extras alongside loaded items', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a')] },
kinds: ['flow'],
loadingKind: {},
extraItemsByKind: { flow: [item('flow', 'f/demo/draft')] }
})
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
expect(demo.children.map((c) => c.key).sort()).toEqual(
[leafKeyFor('flow', 'f/demo/a'), leafKeyFor('flow', 'f/demo/draft')].sort()
)
})
it('drops extras whose path collides with a loaded item (loaded wins)', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a', 'Backend summary')] },
kinds: ['flow'],
loadingKind: {},
extraItemsByKind: { flow: [item('flow', 'f/demo/a', 'Draft summary')] }
})
const demo = findBranch(tree, dirKey('flow', 'f/demo'))
expect(demo.children.length).toBe(1)
const leaf = demo.children[0]
if (!isLeaf(leaf)) throw new Error('expected leaf')
expect(leaf.label).toBe('Backend summary')
})
it('extras flow into the cross-kind All branch too', () => {
const tree = buildWorkspaceTree({
loaded: { flow: [], script: [item('script', 'f/demo/b')] },
kinds: ['flow', 'script'],
loadingKind: {},
extraItemsByKind: { flow: [item('flow', 'f/demo/draft')] }
})
const all = findBranch(tree, kindKey('all'))
const demo = findBranch(all.children, dirKey('all', 'f/demo'))
const keys = demo.children.map((c) => c.key)
expect(keys).toContain(leafKeyFor('flow', 'f/demo/draft'))
expect(keys).toContain(leafKeyFor('script', 'f/demo/b'))
})
it('is a no-op when extras are absent or empty', () => {
const noOpts = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a')] },
kinds: ['flow'],
loadingKind: {}
})
const emptyExtras = buildWorkspaceTree({
loaded: { flow: [item('flow', 'f/demo/a')] },
kinds: ['flow'],
loadingKind: {},
extraItemsByKind: { flow: [] }
})
expect(JSON.stringify(noOpts)).toEqual(JSON.stringify(emptyExtras))
})
})
})
describe('legacyScopeToPath', () => {
it('returns [] for undefined scope', () => {
expect(legacyScopeToPath(undefined, ['flow', 'script'])).toEqual([])
})
it('multi-kind: returns [kindKey] for a kind-only scope', () => {
expect(legacyScopeToPath({ kind: 'flow' }, ['flow', 'script'])).toEqual([kindKey('flow')])
})
it('multi-kind: returns [kindKey, dirKey] for a kind+dir scope', () => {
expect(legacyScopeToPath({ kind: 'flow', dir: 'f/demo' }, ['flow', 'script'])).toEqual([
kindKey('flow'),
dirKey('flow', 'f/demo')
])
})
it('multi-kind: handles `all` as a kind', () => {
expect(legacyScopeToPath({ kind: 'all', dir: 'f/demo' }, ['flow', 'script'])).toEqual([
kindKey('all'),
dirKey('all', 'f/demo')
])
})
it('single-kind: returns [] for a kind-only scope (no kind level in tree)', () => {
expect(legacyScopeToPath({ kind: 'flow' }, ['flow'])).toEqual([])
})
it('single-kind: returns [dirKey] for a kind+dir scope', () => {
expect(legacyScopeToPath({ kind: 'flow', dir: 'f/demo' }, ['flow'])).toEqual([
dirKey('flow', 'f/demo')
])
})
})
describe('relativizeWorkspacePath', () => {
it('returns the absolute path when scope has no dir segment', () => {
expect(relativizeWorkspacePath('f/demo/a', [])).toBe('f/demo/a')
expect(relativizeWorkspacePath('f/demo/a', [kindKey('flow')])).toBe('f/demo/a')
})
it('shortens to the path relative to the deepest dir scope', () => {
const scope = [kindKey('flow'), dirKey('flow', 'f/demo')]
expect(relativizeWorkspacePath('f/demo/a', scope)).toBe('a')
})
it('uses the DEEPEST dir scope when there are nested ones', () => {
const scope = [kindKey('flow'), dirKey('flow', 'f/demo'), dirKey('flow', 'f/demo/sub')]
expect(relativizeWorkspacePath('f/demo/sub/b', scope)).toBe('b')
})
it('falls back to absolute path when the leaf is not under the dir scope', () => {
const scope = [kindKey('flow'), dirKey('flow', 'f/demo')]
expect(relativizeWorkspacePath('f/other/a', scope)).toBe('f/other/a')
})
})
@@ -0,0 +1,244 @@
import { Folder, Layers, User } from 'lucide-svelte'
import {
dirKey,
KIND_LABEL,
kindKey,
leafKeyFor,
type WorkspaceItem,
type WorkspaceItemKind
} from './workspacePicker'
import type { DrillBranch, DrillLeaf, DrillNode } from './drillPicker'
/** Intermediate path-hierarchy node — same shape as the previous
* `buildTreeFromItems` output, kept internal because the DrillPicker
* consumes `DrillNode`s instead. */
type DirNode = {
fullPath: string
name: string
/** True for the top-level `f/<folder>` or `u/<user>` directories. */
isScope: boolean
children: DirNode[]
leaves: WorkspaceItem[]
}
/** Build the path-hierarchy from a flat list of workspace items. */
function buildDirForest(items: WorkspaceItem[]): DirNode[] {
const scopeRoots = new Map<string, DirNode>()
for (const it of items) {
const parts = it.path.split('/')
if (parts.length < 3) continue
const scopeFp = parts.slice(0, 2).join('/')
let node = scopeRoots.get(scopeFp)
if (!node) {
node = { fullPath: scopeFp, name: scopeFp, isScope: true, children: [], leaves: [] }
scopeRoots.set(scopeFp, node)
}
const slug = parts.slice(2)
let cur = node
for (let i = 0; i < slug.length - 1; i++) {
const seg = slug[i]
const fullPath = cur.fullPath + '/' + seg
let next = cur.children.find((c) => c.name === seg)
if (!next) {
next = { fullPath, name: seg, isScope: false, children: [], leaves: [] }
cur.children.push(next)
}
cur = next
}
cur.leaves.push(it)
}
const scopes = Array.from(scopeRoots.values()).sort((a, b) => {
// `f/` (folder) scopes before `u/` (user) scopes; alphabetical within.
const af = a.fullPath.startsWith('f/') ? 0 : 1
const bf = b.fullPath.startsWith('f/') ? 0 : 1
if (af !== bf) return af - bf
return a.fullPath.localeCompare(b.fullPath)
})
const sortNode = (n: DirNode) => {
n.children.sort((a, b) => a.name.localeCompare(b.name))
n.leaves.sort((a, b) => a.path.localeCompare(b.path))
n.children.forEach(sortNode)
}
scopes.forEach(sortNode)
return scopes
}
/** Inject the currently-edited item at its live path, dropping the saved
* entry when a draft rename is mid-flight. Only applies to items of the
* same kind. */
function withCurrent(
items: WorkspaceItem[],
k: WorkspaceItemKind,
currentItem: (WorkspaceItem & { savedPath?: string }) | undefined
): WorkspaceItem[] {
if (!currentItem || currentItem.kind !== k) return items
const drafted =
currentItem.savedPath && currentItem.savedPath !== currentItem.path
? items.filter((it) => it.path !== currentItem.savedPath)
: items
if (drafted.some((it) => it.path === currentItem.path)) return drafted
return [
...drafted,
{
path: currentItem.path,
summary: currentItem.summary,
kind: k,
raw_app: currentItem.raw_app
}
]
}
function itemToLeaf(
it: WorkspaceItem,
currentItem: (WorkspaceItem & { savedPath?: string }) | undefined
): DrillLeaf<WorkspaceItem> {
const isCurrent = !!currentItem && currentItem.kind === it.kind && currentItem.path === it.path
return {
type: 'leaf',
key: leafKeyFor(it.kind, it.path),
label: it.summary || it.path,
secondary: it.summary ? it.path : undefined,
data: it,
current: isCurrent
}
}
function dirToBranch(
d: DirNode,
scopeKind: WorkspaceItemKind | 'all',
currentItem: (WorkspaceItem & { savedPath?: string }) | undefined
): DrillBranch<WorkspaceItem> {
// Top-level user scope (`u/<user>`) gets a person icon. Everything
// else (top-level `f/<folder>` or any deeper folder) is a folder.
const isUserScope = d.isScope && d.fullPath.startsWith('u/')
return {
type: 'branch',
key: dirKey(scopeKind, d.fullPath),
label: d.name,
icon: isUserScope ? User : Folder,
children: [
...d.children.map((c) => dirToBranch(c, scopeKind, currentItem)),
...d.leaves.map((l) => itemToLeaf(l, currentItem))
]
}
}
/** Merge AI-created in-memory drafts (or any caller-provided extras) into a
* kind's loaded list. The chat tools / session previews scaffold items via
* `UserDraft` before the user deploys; those should be navigable from the
* picker. Existing items (same path) win so backend metadata (summary etc.)
* isn't clobbered. */
function withExtras(
items: WorkspaceItem[],
k: WorkspaceItemKind,
extraItemsByKind: Partial<Record<WorkspaceItemKind, WorkspaceItem[]>> | undefined
): WorkspaceItem[] {
const extras = extraItemsByKind?.[k]
if (!extras || extras.length === 0) return items
const known = new Set(items.map((it) => it.path))
return items.concat(extras.filter((d) => !known.has(d.path)))
}
/** Build the workspace drill tree.
*
* - One branch per kind in `kinds` (`Flows` / `Scripts` / `Apps`),
* each containing the kind's path hierarchy.
* - When `kinds.length > 1`, prepend an `All` branch that merges items
* across kinds. The `All` branch is flagged `omitFromSearch` so its
* leaves don't appear twice in global-search results.
* - When `kinds.length === 1`, return the single kind branch's children
* directly so the user lands on folders without a redundant level.
*/
export function buildWorkspaceTree(opts: {
loaded: Partial<Record<WorkspaceItemKind, WorkspaceItem[]>>
kinds: WorkspaceItemKind[]
currentItem?: WorkspaceItem & { savedPath?: string }
/** Per-kind spinner flag. Defaults to `{}` — callers that don't track
* loading state (e.g. chat picker, which preloads eagerly) can omit it. */
loadingKind?: Partial<Record<WorkspaceItemKind, boolean>>
/** Per-kind extras to merge into the loaded list before tree-building
* (e.g. AI-created localStorage drafts surfaced by the workspace adapter).
* Extras whose path matches an already-loaded item are dropped. */
extraItemsByKind?: Partial<Record<WorkspaceItemKind, WorkspaceItem[]>>
}): DrillNode<WorkspaceItem>[] {
const { loaded, kinds, currentItem, extraItemsByKind } = opts
const loadingKind = opts.loadingKind ?? {}
function kindBranch(k: WorkspaceItemKind): DrillBranch<WorkspaceItem> {
const raw = withExtras(loaded[k] ?? [], k, extraItemsByKind)
const items = withCurrent(raw, k, currentItem)
const dirs = items.length > 0 ? buildDirForest(items) : []
return {
type: 'branch',
key: kindKey(k),
label: KIND_LABEL[k],
children: dirs.map((d) => dirToBranch(d, k, currentItem)),
loading: !loaded[k] && !!loadingKind[k],
// Search results from this kind group under its label (collapses
// the folder hierarchy in the search view).
searchGroup: true
}
}
if (kinds.length === 0) return []
if (kinds.length === 1) {
return kindBranch(kinds[0]).children
}
// Cross-kind 'all' branch — flagged so search doesn't double-count leaves.
const allItems = kinds.flatMap((k) =>
withCurrent(withExtras(loaded[k] ?? [], k, extraItemsByKind), k, currentItem)
)
const allDirs = allItems.length > 0 ? buildDirForest(allItems) : []
const allBranch: DrillBranch<WorkspaceItem> = {
type: 'branch',
key: kindKey('all'),
label: 'All',
icon: Layers,
children: allDirs.map((d) => dirToBranch(d, 'all', currentItem)),
omitFromSearch: true,
loading: kinds.some((k) => !loaded[k] && !!loadingKind[k])
}
return [allBranch, ...kinds.map((k) => kindBranch(k))]
}
/** Map the legacy `{ kind, dir? }` initial-scope shape used by callers
* (BreadcrumbSegment / EditorHeader) onto the new generic `string[]` path. */
export function legacyScopeToPath(
scope: { kind: WorkspaceItemKind | 'all'; dir?: string } | undefined,
kinds: WorkspaceItemKind[]
): string[] {
if (!scope) return []
// Single-kind mode: there's no kind branch at root; scope's `kind` is
// implicit. Only the dir (if any) makes it to the path.
if (kinds.length === 1) {
return scope.dir ? [dirKey(scope.kind, scope.dir)] : []
}
const path: string[] = [kindKey(scope.kind)]
if (scope.dir) path.push(dirKey(scope.kind, scope.dir))
return path
}
/** Return `absolutePath` shortened to its segment relative to the deepest
* `dir:<kind>:<path>` segment in `scope`. Used to render leaf rows like
* `parquet_etl` instead of `f/examples/parquet_etl` once the user has
* drilled into `f/examples`. Falls back to the absolute path when no dir
* scope matches (e.g. at the kind level, or when the leaf isn't actually
* under the scoped dir). */
export function relativizeWorkspacePath(absolutePath: string, scope: string[]): string {
for (let i = scope.length - 1; i >= 0; i--) {
const k = scope[i]
if (!k.startsWith('dir:')) continue
const rest = k.slice(4) // '<kind>:<path>'
const colon = rest.indexOf(':')
if (colon < 0) continue
const dirPath = rest.slice(colon + 1)
if (absolutePath.startsWith(dirPath + '/')) {
return absolutePath.slice(dirPath.length + 1)
}
return absolutePath
}
return absolutePath
}