Skip to content

Commit 54c3e1c

Browse files
authored
improvement(chat): defer resource-menu list queries until the menu opens (#5973)
* improvement(chat): defer resource-menu list queries until the menu opens The `+` resource menu and the `@`-mention menu both hydrate from `useAvailableResources`, which fired nine workspace-wide list queries and rebuilt ten item groups on mount — from two always-mounted call sites, for menus that were closed. Gate it on each menu's own open state. - add an `enabled` option to `useAvailableResources`; pass `open` from `AddResourceDropdown` and `PlusMenuDropdown` - add `options.enabled` to the six query hooks that lacked it, matching the convention already used by `useWorkspaceFiles` / `useKnowledgeBasesQuery` / `useLogsList` - skip the tab-name lookup's five list queries when there are no tabs to label - drop the `= []` destructuring defaults: a literal default allocates a fresh array every render while `data` is undefined, busting the group memo in exactly the disabled state - move the hook call into `PlusMenuDropdown`, which owns the open state, removing the `availableResources` pass-through from `usePromptEditor` - delete the `existingKeys`/`isOpen` plumbing — one consumer never read it; resolve it at the single call site instead * fix(chat): warm resource lists on editor focus so fast mentions resolve Deferring the lists to menu-open left a window where `selectActive()` saw an empty candidate list, and its `false` return falls through to submitting the message with the mention unresolved. Start hydrating on first focus — the earliest reliable signal a mention may be coming — which closes the window while keeping the lists off the page-load path. * fix(chat): never submit a mention while its candidate lists are loading Warming on focus shrank the race but gave no readiness guarantee: an empty candidate list still meant "no match" to the keydown handler, which falls through and submits the message with the mention as raw text. Make the distinction explicit. `useAvailableResources` now reports `isHydrating`, and `PlusMenuHandle.selectActive` returns `selected | empty | hydrating` instead of a boolean. The editor swallows Tab/Enter while hydrating and only lets them through once the lists have settled, where an empty result is a genuine no-match. `isHydrating` keys off `isPending`, not `data === undefined`, so a failed list settles instead of blocking the key forever.
1 parent 67ffdac commit 54c3e1c

17 files changed

Lines changed: 234 additions & 165 deletions

File tree

‎apps/sim/app/workspace/[workspaceId]/home/components/mothership-view/components/add-resource-dropdown/add-resource-dropdown.tsx‎

Lines changed: 119 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,51 @@ export interface AddResourceDropdownProps {
4242
existingKeys: Set<string>
4343
onAdd: (resource: MothershipResource) => void
4444
onSwitch?: (resourceId: string) => void
45-
/** Resource types to hide from the dropdown (e.g. `['folder', 'task']`). */
45+
/**
46+
* Resource types to hide from the dropdown. Must be referentially stable
47+
* (a module constant) — it keys the underlying group memo.
48+
*/
4649
excludeTypes?: readonly MothershipResourceType[]
4750
}
4851

49-
export type AvailableItem = { id: string; name: string; isOpen?: boolean; [key: string]: unknown }
52+
export type AvailableItem = { id: string; name: string; [key: string]: unknown }
5053

5154
interface AvailableItemsByType {
5255
type: MothershipResourceType
5356
items: AvailableItem[]
5457
}
5558

59+
interface AvailableResources {
60+
groups: AvailableItemsByType[]
61+
/**
62+
* True while enabled and at least one list has yet to produce data. Callers
63+
* that act on "no candidates" must check this first — an empty result during
64+
* hydration means "not known yet", not "no match".
65+
*/
66+
isHydrating: boolean
67+
}
68+
69+
interface UseAvailableResourcesOptions {
70+
/**
71+
* Skips the underlying list queries and the group construction they feed
72+
* while `false`, returning a stable empty result. Menus pass their own open
73+
* state so a closed one costs nothing; the lists fetch on first open.
74+
*
75+
* Note this only defers the lists nothing else on the surface already needs —
76+
* the mothership tab bar independently resolves tab names from the workflow,
77+
* table, file, knowledge-base, and folder lists, so those stay warm there.
78+
*/
79+
enabled?: boolean
80+
/**
81+
* Resource types to omit from the result. Must be referentially stable
82+
* (a module constant) — it keys the group memo.
83+
*/
84+
excludeTypes?: readonly MothershipResourceType[]
85+
}
86+
87+
/** Stable identity for the disabled result, so downstream memos never bust. */
88+
const NO_RESOURCE_GROUPS: AvailableItemsByType[] = []
89+
5690
const LOG_DROPDOWN_LIMIT = 50
5791

5892
const LOG_DROPDOWN_FILTERS = {
@@ -69,76 +103,99 @@ const LOG_DROPDOWN_FILTERS = {
69103

70104
export function useAvailableResources(
71105
workspaceId: string,
72-
existingKeys: Set<string>,
73-
excludeTypes?: readonly MothershipResourceType[]
74-
): AvailableItemsByType[] {
75-
const { data: workflows = [] } = useWorkflows(workspaceId)
76-
const { data: tables = [] } = useTablesList(workspaceId)
77-
const { data: files = [] } = useWorkspaceFiles(workspaceId)
78-
const { data: knowledgeBases } = useKnowledgeBasesQuery(workspaceId)
79-
const { data: folders = [] } = useFolders(workspaceId)
80-
const { data: fileFolders = [] } = useWorkspaceFileFolders(workspaceId)
81-
const { data: tasks = [] } = useMothershipChats(workspaceId)
82-
const { data: schedules = [] } = useWorkspaceSchedules(workspaceId)
83-
const { data: logsData } = useLogsList(workspaceId, LOG_DROPDOWN_FILTERS)
106+
options?: UseAvailableResourcesOptions
107+
): AvailableResources {
108+
const enabled = options?.enabled ?? true
109+
const excludeTypes = options?.excludeTypes
110+
// Destructured without `= []` defaults on purpose: a literal default allocates a
111+
// fresh array every render while `data` is undefined (exactly the disabled state),
112+
// which would bust the group memo below on every render. Undefined is stable.
113+
const { data: workflows, isPending: workflowsPending } = useWorkflows(workspaceId, { enabled })
114+
const { data: tables, isPending: tablesPending } = useTablesList(workspaceId, 'active', {
115+
enabled,
116+
})
117+
const { data: files, isPending: filesPending } = useWorkspaceFiles(workspaceId, 'active', {
118+
enabled,
119+
})
120+
const { data: knowledgeBases, isPending: knowledgeBasesPending } = useKnowledgeBasesQuery(
121+
workspaceId,
122+
{ enabled }
123+
)
124+
const { data: folders, isPending: foldersPending } = useFolders(workspaceId, { enabled })
125+
const { data: fileFolders, isPending: fileFoldersPending } = useWorkspaceFileFolders(
126+
workspaceId,
127+
'active',
128+
{ enabled }
129+
)
130+
const { data: tasks, isPending: tasksPending } = useMothershipChats(workspaceId, { enabled })
131+
const { data: schedules, isPending: schedulesPending } = useWorkspaceSchedules(workspaceId, {
132+
enabled,
133+
})
134+
const { data: logsData, isPending: logsPending } = useLogsList(
135+
workspaceId,
136+
LOG_DROPDOWN_FILTERS,
137+
{ enabled }
138+
)
84139
const logs = useMemo(() => (logsData?.pages ?? []).flatMap((page) => page.logs), [logsData])
85140

86-
return useMemo(() => {
141+
/**
142+
* Keyed off `isPending` rather than `data === undefined` so a failed list
143+
* settles to "not hydrating" — an errored query must not block the caller
144+
* forever.
145+
*/
146+
const isHydrating =
147+
enabled &&
148+
(workflowsPending ||
149+
tablesPending ||
150+
filesPending ||
151+
knowledgeBasesPending ||
152+
foldersPending ||
153+
fileFoldersPending ||
154+
tasksPending ||
155+
schedulesPending ||
156+
logsPending)
157+
158+
const groups = useMemo(() => {
159+
if (!enabled) return NO_RESOURCE_GROUPS
87160
const excluded = new Set<MothershipResourceType>(excludeTypes ?? [])
88161
const groups: AvailableItemsByType[] = [
89162
{
90163
type: 'workflow' as const,
91-
items: workflows.map((w) => ({
164+
items: (workflows ?? []).map((w) => ({
92165
id: w.id,
93166
name: w.name,
94167
folderId: w.folderId ?? null,
95168
sortOrder: w.sortOrder,
96-
isOpen: existingKeys.has(`workflow:${w.id}`),
97169
})),
98170
},
99171
{
100172
type: 'folder' as const,
101-
items: folders.map((f) => ({
173+
items: (folders ?? []).map((f) => ({
102174
id: f.id,
103175
name: f.name,
104176
parentId: f.parentId ?? null,
105177
sortOrder: f.sortOrder,
106-
isOpen: existingKeys.has(`folder:${f.id}`),
107178
})),
108179
},
109180
{
110181
type: 'table' as const,
111-
items: tables.map((t) => ({
112-
id: t.id,
113-
name: t.name,
114-
isOpen: existingKeys.has(`table:${t.id}`),
115-
})),
182+
items: (tables ?? []).map((t) => ({ id: t.id, name: t.name })),
116183
},
117184
{
118185
type: 'file' as const,
119-
items: files.map((f) => ({
120-
id: f.id,
121-
name: f.name,
122-
folderId: f.folderId ?? null,
123-
isOpen: existingKeys.has(`file:${f.id}`),
124-
})),
186+
items: (files ?? []).map((f) => ({ id: f.id, name: f.name, folderId: f.folderId ?? null })),
125187
},
126188
{
127189
type: 'filefolder' as const,
128-
items: fileFolders.map((f) => ({
190+
items: (fileFolders ?? []).map((f) => ({
129191
id: f.id,
130192
name: f.name,
131193
parentId: f.parentId ?? null,
132-
isOpen: existingKeys.has(`filefolder:${f.id}`),
133194
})),
134195
},
135196
{
136197
type: 'knowledgebase' as const,
137-
items: (knowledgeBases ?? []).map((kb) => ({
138-
id: kb.id,
139-
name: kb.name,
140-
isOpen: existingKeys.has(`knowledgebase:${kb.id}`),
141-
})),
198+
items: (knowledgeBases ?? []).map((kb) => ({ id: kb.id, name: kb.name })),
142199
},
143200
{
144201
type: 'integration' as const,
@@ -147,44 +204,33 @@ export function useAvailableResources(
147204
name: integration.name,
148205
iconComponent: integration.icon,
149206
bgColor: integration.bgColor,
150-
isOpen: existingKeys.has(`integration:${integration.blockType}`),
151207
})),
152208
},
153209
{
154210
type: 'task' as const,
155-
items: tasks.map((t) => ({
156-
id: t.id,
157-
name: t.name,
158-
isOpen: existingKeys.has(`task:${t.id}`),
159-
})),
211+
items: (tasks ?? []).map((t) => ({ id: t.id, name: t.name })),
160212
},
161213
{
162214
type: 'scheduledtask' as const,
163-
items: schedules
215+
items: (schedules ?? [])
164216
.filter((s) => s.sourceType === 'job')
165217
.map((s) => ({
166218
id: s.id,
167219
name: s.jobTitle || truncate(s.prompt ?? '', 40) || 'Scheduled Task',
168-
isOpen: existingKeys.has(`scheduledtask:${s.id}`),
169220
})),
170221
},
171222
{
172223
type: 'log' as const,
173224
items: logs.map((log) => {
174225
const workflowName = log.workflow?.name ?? log.workflowId ?? 'Unknown'
175226
const time = formatDate(log.createdAt).compact
176-
return {
177-
id: log.id,
178-
name: `${workflowName} · ${time}`,
179-
workflowName,
180-
time,
181-
isOpen: existingKeys.has(`log:${log.id}`),
182-
}
227+
return { id: log.id, name: `${workflowName} · ${time}`, workflowName, time }
183228
}),
184229
},
185230
]
186231
return groups.filter((g) => !excluded.has(g.type))
187232
}, [
233+
enabled,
188234
workflows,
189235
folders,
190236
fileFolders,
@@ -194,13 +240,16 @@ export function useAvailableResources(
194240
tasks,
195241
schedules,
196242
logs,
197-
existingKeys,
198243
excludeTypes,
199244
])
245+
246+
// `groups` keeps its own stable identity so the consumers' downstream memos
247+
// still key on it; only this wrapper changes when hydration settles.
248+
return useMemo(() => ({ groups, isHydrating }), [groups, isHydrating])
200249
}
201250

202251
export type WorkflowTreeNode =
203-
| { kind: 'workflow'; id: string; name: string; isOpen?: boolean }
252+
| { kind: 'workflow'; id: string; name: string }
204253
| { kind: 'folder'; id: string; name: string; children: WorkflowTreeNode[] }
205254

206255
export function buildWorkflowFolderTree(
@@ -222,7 +271,6 @@ export function buildWorkflowFolderTree(
222271
kind: 'workflow',
223272
id: w.id,
224273
name: w.name,
225-
isOpen: w.isOpen,
226274
})
227275

228276
const buildLevel = (parentId: string | null): WorkflowTreeNode[] => {
@@ -262,7 +310,7 @@ export function buildWorkflowFolderTree(
262310

263311
interface WorkflowFolderTreeItemsProps {
264312
nodes: WorkflowTreeNode[]
265-
onSelect: (resource: MothershipResource, isOpen?: boolean) => void
313+
onSelect: (resource: MothershipResource) => void
266314
}
267315

268316
export function WorkflowFolderTreeItems({ nodes, onSelect }: WorkflowFolderTreeItemsProps) {
@@ -272,9 +320,7 @@ export function WorkflowFolderTreeItems({ nodes, onSelect }: WorkflowFolderTreeI
272320
node.kind === 'workflow' ? (
273321
<DropdownMenuItem
274322
key={node.id}
275-
onClick={() =>
276-
onSelect({ type: 'workflow', id: node.id, title: node.name }, node.isOpen)
277-
}
323+
onClick={() => onSelect({ type: 'workflow', id: node.id, title: node.name })}
278324
>
279325
{getResourceConfig('workflow').renderDropdownItem({
280326
item: { id: node.id, name: node.name },
@@ -297,8 +343,8 @@ export function WorkflowFolderTreeItems({ nodes, onSelect }: WorkflowFolderTreeI
297343
}
298344

299345
export type FileFolderTreeNode =
300-
| { kind: 'file'; id: string; name: string; isOpen?: boolean }
301-
| { kind: 'folder'; id: string; name: string; isOpen?: boolean; children: FileFolderTreeNode[] }
346+
| { kind: 'file'; id: string; name: string }
347+
| { kind: 'folder'; id: string; name: string; children: FileFolderTreeNode[] }
302348

303349
export function buildFileFolderTree(
304350
fileItems: AvailableItem[],
@@ -319,17 +365,15 @@ export function buildFileFolderTree(
319365
const childFiles = byFolder.get(parentId) ?? []
320366
const nodes: FileFolderTreeNode[] = []
321367
for (const folder of childFolders) {
322-
const children = buildLevel(folder.id)
323368
nodes.push({
324369
kind: 'folder',
325370
id: folder.id,
326371
name: folder.name,
327-
isOpen: folder.isOpen,
328-
children,
372+
children: buildLevel(folder.id),
329373
})
330374
}
331375
for (const file of childFiles) {
332-
nodes.push({ kind: 'file', id: file.id, name: file.name, isOpen: file.isOpen })
376+
nodes.push({ kind: 'file', id: file.id, name: file.name })
333377
}
334378
return nodes
335379
}
@@ -339,7 +383,7 @@ export function buildFileFolderTree(
339383

340384
interface FileFolderTreeItemsProps {
341385
nodes: FileFolderTreeNode[]
342-
onSelect: (resource: MothershipResource, isOpen?: boolean) => void
386+
onSelect: (resource: MothershipResource) => void
343387
}
344388

345389
export function FileFolderTreeItems({ nodes, onSelect }: FileFolderTreeItemsProps) {
@@ -349,7 +393,7 @@ export function FileFolderTreeItems({ nodes, onSelect }: FileFolderTreeItemsProp
349393
node.kind === 'file' ? (
350394
<DropdownMenuItem
351395
key={node.id}
352-
onClick={() => onSelect({ type: 'file', id: node.id, title: node.name }, node.isOpen)}
396+
onClick={() => onSelect({ type: 'file', id: node.id, title: node.name })}
353397
>
354398
{getResourceConfig('file').renderDropdownItem({
355399
item: { id: node.id, name: node.name },
@@ -363,9 +407,7 @@ export function FileFolderTreeItems({ nodes, onSelect }: FileFolderTreeItemsProp
363407
</DropdownMenuSubTrigger>
364408
<DropdownMenuSubContent>
365409
<DropdownMenuItem
366-
onClick={() =>
367-
onSelect({ type: 'filefolder', id: node.id, title: node.name }, node.isOpen)
368-
}
410+
onClick={() => onSelect({ type: 'filefolder', id: node.id, title: node.name })}
369411
>
370412
<Folder className='size-[14px]' />
371413
<span>{node.name}</span>
@@ -391,10 +433,8 @@ export function AddResourceDropdown({
391433
const [open, setOpen] = useState(false)
392434
const [search, setSearch] = useState('')
393435
const [activeIndex, setActiveIndex] = useState(0)
394-
const available = useAvailableResources(workspaceId, existingKeys, [
395-
...(excludeTypes ?? []),
396-
'integration',
397-
])
436+
// Gated on `open` so an idle tab bar never fetches the workspace lists.
437+
const { groups: available } = useAvailableResources(workspaceId, { enabled: open, excludeTypes })
398438
const handleOpenChange = (next: boolean) => {
399439
setOpen(next)
400440
if (!next) {
@@ -403,8 +443,8 @@ export function AddResourceDropdown({
403443
}
404444
}
405445

406-
const select = (resource: MothershipResource, isOpen?: boolean) => {
407-
if (isOpen && onSwitch) {
446+
const select = (resource: MothershipResource) => {
447+
if (onSwitch && existingKeys.has(`${resource.type}:${resource.id}`)) {
408448
onSwitch(resource.id)
409449
} else {
410450
onAdd(resource)
@@ -446,7 +486,7 @@ export function AddResourceDropdown({
446486
if (filtered.length > 0 && filtered[activeIndex]) {
447487
e.preventDefault()
448488
const { type, item } = filtered[activeIndex]
449-
select({ type, id: item.id, title: item.name }, item.isOpen)
489+
select({ type, id: item.id, title: item.name })
450490
}
451491
}
452492
}
@@ -494,7 +534,7 @@ export function AddResourceDropdown({
494534
key={`${type}:${item.id}`}
495535
className={cn(index === activeIndex && 'bg-[var(--surface-active)]')}
496536
onMouseEnter={() => setActiveIndex(index)}
497-
onClick={() => select({ type, id: item.id, title: item.name }, item.isOpen)}
537+
onClick={() => select({ type, id: item.id, title: item.name })}
498538
>
499539
{config.renderDropdownItem({ item })}
500540
</DropdownMenuItem>
@@ -553,9 +593,7 @@ export function AddResourceDropdown({
553593
{items.map((item) => (
554594
<DropdownMenuItem
555595
key={item.id}
556-
onClick={() =>
557-
select({ type, id: item.id, title: item.name }, item.isOpen)
558-
}
596+
onClick={() => select({ type, id: item.id, title: item.name })}
559597
>
560598
{config.renderDropdownItem({ item })}
561599
</DropdownMenuItem>

0 commit comments

Comments
 (0)