Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
'use client'

import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react'
import {
startTransition,
useCallback,
useDeferredValue,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import { Button, cn } from '@sim/emcn'
import { X } from '@sim/emcn/icons'
import { WorkflowBlockBorder, type WorkflowBorderPort } from '@sim/workflow-renderer'
Expand Down Expand Up @@ -45,6 +53,8 @@ const SELECTOR_ACTION_MENU_RIGHT_INSET = 24
const SELECTOR_ACTION_MENU_AMPLITUDE = 7
const RECENT_SELECTION_LIMIT = 3
const RECENT_SELECTION_STORAGE_PREFIX = 'sim:connection-block-selector:recent'
const BROWSE_PREFETCH_MARGIN_PX = 640
const BROWSE_PAGE_SIZE = 50
const POPULAR_BLOCK_TYPES = [
'agent',
'function',
Expand All @@ -54,6 +64,11 @@ const POPULAR_BLOCK_TYPES = [
'memory',
] as const

/** Ordered prefix that reuses the source array once `count` covers all of it. */
function takePrefix<T>(items: T[], count: number): T[] {
return count >= items.length ? items : items.slice(0, Math.max(0, count))
}

const SELECTOR_PORTS: WorkflowBorderPort[] = [
{
id: 'target',
Expand Down Expand Up @@ -136,9 +151,11 @@ export function ConnectionBlockSelector({ id, data }: NodeProps<ConnectionBlockS
const posthog = usePostHog()
const inputRef = useRef<HTMLInputElement>(null)
const listRef = useRef<HTMLDivElement>(null)
const browseSentinelRef = useRef<HTMLDivElement>(null)
const [search, setSearch] = useState('')
const [selectedValue, setSelectedValue] = useState('')
const [recentSelections, setRecentSelections] = useState<RecentSelection[]>([])
const [browseLimit, setBrowseLimit] = useState(BROWSE_PAGE_SIZE)
const deferredSearch = useDeferredValue(search)
const isSearching = deferredSearch.trim().length > 0
const recentStorageKey = `${RECENT_SELECTION_STORAGE_PREFIX}:${workspaceId}`
Expand Down Expand Up @@ -260,6 +277,42 @@ export function ConnectionBlockSelector({ id, data }: NodeProps<ConnectionBlockS
() => availableTools.filter((tool) => !recentSelectionKeys.has(`tool:${tool.id}`)),
[availableTools, recentSelectionKeys]
)
const visibleBrowseBlocks = useMemo(
() => takePrefix(browseBlocks, browseLimit),
[browseBlocks, browseLimit]
)
const visibleBrowseTools = useMemo(
() => takePrefix(browseTools, browseLimit - browseBlocks.length),
[browseBlocks.length, browseLimit, browseTools]
)
const hasMoreBrowseResults = browseLimit < browseBlocks.length + browseTools.length

/**
* Mounting every cmdk item up front caused the frame spike; a manual "show
* more" control would leak that constraint into the UI. Prefetching near the
* viewport keeps scrolling continuous and cmdk's keyboard navigation intact.
*/
useEffect(() => {
const list = listRef.current
const sentinel = browseSentinelRef.current
if (isSearching || !hasMoreBrowseResults || !list || !sentinel) return

const observer = new IntersectionObserver(
([entry]) => {
if (!entry.isIntersecting) return
startTransition(() => {
setBrowseLimit((current) => current + BROWSE_PAGE_SIZE)
})
},
{
root: list,
rootMargin: `0px 0px ${BROWSE_PREFETCH_MARGIN_PX}px 0px`,
}
)

observer.observe(sentinel)
return () => observer.disconnect()
}, [hasMoreBrowseResults, isSearching])

const dispatchSelection = useCallback(
(type: string, resultType: 'block' | 'tool' | 'tool_operation', presetOperation?: string) => {
Expand Down Expand Up @@ -480,11 +533,14 @@ export function ConnectionBlockSelector({ id, data }: NodeProps<ConnectionBlockS
)}
<BlocksGroup items={popularBlocks} onSelect={handleBlockSelect} heading='Popular' />
<BlocksGroup
items={browseBlocks}
items={visibleBrowseBlocks}
onSelect={handleBlockSelect}
heading='All blocks'
/>
<ToolsGroup items={browseTools} onSelect={handleToolSelect} />
<ToolsGroup items={visibleBrowseTools} onSelect={handleToolSelect} />
{hasMoreBrowseResults && (
<div ref={browseSentinelRef} aria-hidden='true' className='h-px' />
)}
</>
)}
</CommandFadedList>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,9 @@ function UnsupportedToolBadge({ message }: { message: string }) {
)
}

const EMPTY_COMBOBOX_GROUPS: ComboboxOptionGroup[] = []
const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = []

export const ToolInput = memo(function ToolInput({
blockId,
subBlockId,
Expand Down Expand Up @@ -1403,6 +1406,7 @@ export const ToolInput = memo(function ToolInput({
* @returns Array of option groups for the combobox component
*/
const toolGroups = useMemo((): ComboboxOptionGroup[] => {
if (!open) return EMPTY_COMBOBOX_GROUPS
const groups: ComboboxOptionGroup[] = []

// MCP Server drill-down: when navigated into a server, show only its tools
Expand Down Expand Up @@ -1681,6 +1685,7 @@ export const ToolInput = memo(function ToolInput({

return groups
}, [
open,
mcpServerDrilldown,
customTools,
availableMcpTools,
Expand All @@ -1705,7 +1710,7 @@ export const ToolInput = memo(function ToolInput({
return (
<div className='w-full space-y-2'>
<Combobox
options={[]}
options={EMPTY_COMBOBOX_OPTIONS}
groups={toolGroups}
placeholder='Add tool...'
/* Every list this picker offers — blocks, operations, MCP and custom
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client'

import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Button, cn, Input, toast } from '@sim/emcn'
import { ChevronDown, ChevronRight, ChevronUp, X } from '@sim/emcn/icons'
import { useParams } from 'next/navigation'
Expand Down Expand Up @@ -110,6 +110,30 @@ function createActiveSearchTarget(
}

export function WorkflowSearchReplace() {
const { isOpen, open } = useWorkflowSearchReplaceStore(
useShallow((state) => ({ isOpen: state.isOpen, open: state.open }))
)
const focusSearchInputRef = useRef<(() => void) | null>(null)

useRegisterGlobalCommands([
createCommand({
id: 'open-workflow-search-replace',
handler: () => {
open()
focusSearchInputRef.current?.()
},
}),
])
Comment thread
cursor[bot] marked this conversation as resolved.

return isOpen ? <WorkflowSearchReplacePanel focusRef={focusSearchInputRef} /> : null
}

interface WorkflowSearchReplacePanelProps {
/** Lets the shortcut re-select the query while the panel is already open. */
focusRef: RefObject<(() => void) | null>
}

function WorkflowSearchReplacePanel({ focusRef }: WorkflowSearchReplacePanelProps) {
const params = useParams()
const workspaceId = params.workspaceId as string | undefined
const routeWorkflowId = params.workflowId as string | undefined
Expand Down Expand Up @@ -143,38 +167,33 @@ export function WorkflowSearchReplace() {
>({})

const {
isOpen,
query,
replacement: textReplacement,
activeMatchId,
position,
close,
open,
setPosition,
setQuery,
setReplacement,
setActiveMatchId,
} = useWorkflowSearchReplaceStore(
useShallow((state) => ({
isOpen: state.isOpen,
query: state.query,
replacement: state.replacement,
activeMatchId: state.activeMatchId,
position: state.position,
close: state.close,
open: state.open,
setPosition: state.setPosition,
setQuery: state.setQuery,
setReplacement: state.setReplacement,
setActiveMatchId: state.setActiveMatchId,
}))
)
const prevQueryRef = useRef(query)
const prevIsOpenRef = useRef(false)
const prevQueryRef = useRef<string | null>(null)
const afterReplaceIndexRef = useRef<number | null>(null)
const { data: workspaceCredentials } = useWorkspaceCredentials({ workspaceId, enabled: isOpen })
const { data: customTools = [] } = useCustomTools(isOpen && workspaceId ? workspaceId : '')
const { mcpTools } = useMcpTools(isOpen && workspaceId ? workspaceId : '')
const { data: workspaceCredentials } = useWorkspaceCredentials({ workspaceId })
const { data: customTools = [] } = useCustomTools(workspaceId ?? '')
const { mcpTools } = useMcpTools(workspaceId ?? '')
const mcpToolNamesById = useMemo(() => {
const names = new Map<string, string>()
for (const t of mcpTools) {
Expand All @@ -183,19 +202,6 @@ export function WorkflowSearchReplace() {
return names
}, [mcpTools])

useRegisterGlobalCommands([
createCommand({
id: 'open-workflow-search-replace',
handler: () => {
open()
requestAnimationFrame(() => {
searchInputRef.current?.focus()
searchInputRef.current?.select()
})
},
}),
])

const searchBlocks = useMemo(
() =>
getWorkflowSearchBlocks({
Expand Down Expand Up @@ -267,10 +273,17 @@ export function WorkflowSearchReplace() {
)

useEffect(() => {
if (!isOpen) return
searchInputRef.current?.focus()
searchInputRef.current?.select()
}, [isOpen])
const focusSearchInput = () => {
searchInputRef.current?.focus()
searchInputRef.current?.select()
}
focusSearchInput()
focusRef.current = focusSearchInput
return () => {
focusRef.current = null
usePanelEditorSearchStore.getState().setActiveSearchTarget(null)
}
}, [focusRef])

const panelHeight = isReplaceExpanded
? SEARCH_PANEL_EXPANDED_HEIGHT
Expand All @@ -288,7 +301,7 @@ export function WorkflowSearchReplace() {
})

useFloatBoundarySync({
isOpen,
isOpen: true,
position: actualPosition,
width: SEARCH_PANEL_WIDTH,
height: panelHeight,
Expand Down Expand Up @@ -384,14 +397,6 @@ export function WorkflowSearchReplace() {
}

useEffect(() => {
if (!isOpen) {
prevIsOpenRef.current = false
usePanelEditorSearchStore.getState().setActiveSearchTarget(null)
return
}

const justOpened = !prevIsOpenRef.current
prevIsOpenRef.current = true
const queryChanged = prevQueryRef.current !== query
prevQueryRef.current = query

Expand All @@ -406,7 +411,7 @@ export function WorkflowSearchReplace() {
const replaceIndex = afterReplaceIndexRef.current
afterReplaceIndexRef.current = null

if (queryChanged || justOpened) {
if (queryChanged) {
handleSelectMatch(hydratedMatches[0].id)
} else if (replaceIndex !== null) {
handleSelectMatch(hydratedMatches[Math.min(replaceIndex, hydratedMatches.length - 1)].id)
Expand All @@ -422,9 +427,7 @@ export function WorkflowSearchReplace() {
usePanelEditorSearchStore
.getState()
.setActiveSearchTarget(createActiveSearchTarget(activeHydratedMatch, query))
}, [activeMatchId, handleSelectMatch, hydratedMatches, isOpen, query, setActiveMatchId])

if (!isOpen) return null
}, [activeMatchId, handleSelectMatch, hydratedMatches, query, setActiveMatchId])

const handleMoveActiveMatch = (delta: number) => {
if (hydratedMatches.length === 0) return
Expand Down
Loading
Loading