The open-source agent harness - the runtime layer that turns an LLM into a working agent.
chore: allow search in sessions agent filter (#864)
harshil-209672a116843cc3
diff --git a/.changeset/searchable-session-agent-filter.md b/.changeset/searchable-session-agent-filter.mdnew file mode 100644index 000000000..1e9b35c5b--- /dev/null+++ b/.changeset/searchable-session-agent-filter.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Use the shared searchable agent picker in the sessions filter.diff --git a/packages/trueforge-ui/src/atoms/AgentSearchPicker.tsx b/packages/trueforge-ui/src/atoms/AgentSearchPicker.tsxindex f16930d00..2da88301e 100644--- a/packages/trueforge-ui/src/atoms/AgentSearchPicker.tsx+++ b/packages/trueforge-ui/src/atoms/AgentSearchPicker.tsx@@ -7,7 +7,12 @@ import { Icon } from '../icons/Icon.js';import { libraryAgentId } from '../server/ShellModeContext.js';import type { AgentLibraryEntry } from '../server/types.js';import { cn } from './lib/cn.js';-import { auiSelectMenuClass, auiSelectOptionClass, auiSelectTriggerClass } from './lib/selectClasses.js';+import {+ auiSelectMenuClass,+ auiSelectOptionClass,+ auiSelectPrefixTriggerClass,+ auiSelectTriggerClass,+} from './lib/selectClasses.js';import { themePortalRoot } from './lib/themePortalRoot.js';import { useSearchAgentsList } from './lib/useSearchAgentsList.js';import { Button } from './primitives/Button.js';@@ -21,6 +26,7 @@ export type AgentSearchPickerProps = {onBuildAgent?: () => void;/** When set, shows this option above results while the query is empty (e.g. filter "All agents"). */allOption?: { value: string; label: string };+ prefix?: string;'aria-label'?: string;placeholder?: string;className?: string;@@ -37,6 +43,7 @@ export function AgentSearchPicker({disabled = false,onBuildAgent,allOption,+ prefix,'aria-label': ariaLabel = 'Agent',placeholder = 'Search agent',className,@@ -225,46 +232,77 @@ export function AgentSearchPicker({): null;+ const input = (+ <input+ ref={inputRef}+ type="text"+ role="combobox"+ aria-label={ariaLabel}+ aria-expanded={open}+ aria-controls={open ? listboxId : undefined}+ aria-autocomplete="list"+ disabled={disabled}+ placeholder={placeholder}+ value={inputValue}+ className={cn(+ 'min-w-0 bg-transparent outline-none placeholder:text-text-secondary/70 disabled:cursor-not-allowed',+ prefix == null ? 'flex-1' : 'absolute inset-0 w-full px-2',+ )}+ onFocus={() => {+ if (!disabled) setOpen(true);+ }}+ onChange={event => {+ if (disabled) return;+ setQuery(event.target.value);+ setOpen(true);+ }}+ onKeyDown={event => {+ if (event.key === 'Escape') {+ event.preventDefault();+ setOpen(false);+ inputRef.current?.blur();+ return;+ }+ if (event.key === 'ArrowDown' && !open && !disabled) {+ event.preventDefault();+ setOpen(true);+ }+ }}+ />+ );+return (<div ref={rootRef} className={cn('relative', className)}><divref={triggerRef}- className={auiSelectTriggerClass(disabled ? 'cursor-not-allowed opacity-50' : 'cursor-text')}+ className={+ prefix == null+ ? auiSelectTriggerClass(disabled ? 'cursor-not-allowed opacity-50' : 'cursor-text')+ : auiSelectPrefixTriggerClass(+ cn('w-fit min-w-full', disabled ? 'cursor-not-allowed opacity-50' : 'cursor-text'),+ )+ }+ onClick={() => {+ if (!disabled) inputRef.current?.focus();+ }}>- <input- ref={inputRef}- type="text"- role="combobox"- aria-label={ariaLabel}- aria-expanded={open}- aria-controls={open ? listboxId : undefined}- aria-autocomplete="list"- disabled={disabled}- placeholder={placeholder}- value={inputValue}- className="min-w-0 flex-1 bg-transparent outline-none placeholder:text-text-secondary/70 disabled:cursor-not-allowed"- onFocus={() => {- if (!disabled) setOpen(true);- }}- onChange={event => {- if (disabled) return;- setQuery(event.target.value);- setOpen(true);- }}- onKeyDown={event => {- if (event.key === 'Escape') {- event.preventDefault();- setOpen(false);- inputRef.current?.blur();- return;- }- if (event.key === 'ArrowDown' && !open && !disabled) {- event.preventDefault();- setOpen(true);- }- }}+ {prefix == null ? null : (+ <span className="text-text-primary shrink-0 border-r border-border px-3 font-semibold">{prefix}</span>+ )}+ {prefix == null ? (+ input+ ) : (+ <div className="relative mx-2 max-w-48 min-w-24 flex-none overflow-hidden px-2 py-0.5 text-sm">+ <span aria-hidden className="invisible block truncate whitespace-pre">+ {selectedLabel || placeholder}+ </span>+ {input}+ </div>+ )}+ <Icon+ name="chevron-down"+ className={cn('size-4 shrink-0 text-text-secondary', prefix == null ? null : 'mr-2')}/>- <Icon name="chevron-down" className="size-4 shrink-0 text-text-secondary" /></div>{menu}</div>diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionsFilters.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionsFilters.tsxindex aa2a15ef0..af45ae9c6 100644--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionsFilters.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionsFilters.tsx@@ -4,8 +4,7 @@ import { useEffect, useRef, useState } from 'react';import { Icon } from '../../icons/Icon.js';import { useOptionalServer } from '../../server/ServerContext.js';-import { useOptionalShellMode } from '../../server/ShellModeContext.js';-import type { AgentLibraryEntry } from '../../server/types.js';+import { libraryAgentId } from '../../server/ShellModeContext.js';import { SESSION_CUSTOM_RANGE_MAX_DAYS, type SessionTimeRange } from '../../utils/sessionShareUrl.js';import {formatSessionTimePresetLabel,@@ -14,12 +13,12 @@ import {SESSION_TIME_PRESETS,toDateTimeLocalValue,} from '../../utils/sessionTimePresets.js';+import { AgentSearchPicker } from '../AgentSearchPicker.js';import { cn } from '../lib/cn.js';import { auiInputClass } from '../lib/inputClasses.js';import { auiSelectMenuClass, auiSelectOptionClass, auiSelectTriggerClass } from '../lib/selectClasses.js';-import { searchAllAgents } from '../lib/useSearchAgentsList.js';+import { findLibraryAgent } from '../lib/useSearchAgentsList.js';import { Button } from '../primitives/Button.js';-import { PopoverSelect } from '../primitives/PopoverSelect.js';export type AgentSessionsFiltersProps = {agentId: string | null;@@ -39,27 +38,29 @@ export function AgentSessionsFilters({showCustomTimeRange = true,}: AgentSessionsFiltersProps) {const server = useOptionalServer();- const shell = useOptionalShellMode();- const [agents, setAgents] = useState<AgentLibraryEntry[]>([]);+ const [agentLabelById, setAgentLabelById] = useState<Record<string, string>>({});const [menuOpen, setMenuOpen] = useState(false);const [customPickerOpen, setCustomPickerOpen] = useState(false);const [fromValue, setFromValue] = useState(() => toDateTimeLocalValue(timeRange.startTs));const [toValue, setToValue] = useState(() => toDateTimeLocalValue(timeRange.endTs));const popoverRef = useRef<HTMLDivElement>(null);+ const selectedAgentLabel = agentId == null ? undefined : agentLabelById[agentId];+ // On refresh get the agent name from the server if we have agent id in url but no agent name in optionsuseEffect(() => {- if (!showAgentFilter || server == null) return undefined;+ if (server == null || agentId == null || selectedAgentLabel != null) return undefined;let cancelled = false;- void searchAllAgents(server).then(- rows => {- if (!cancelled) setAgents(rows);+ void findLibraryAgent({ server, agentKey: agentId }).then(+ agent => {+ if (cancelled || agent == null) return;+ setAgentLabelById(current => ({ ...current, [agentId]: agent.name }));},() => undefined,);return () => {cancelled = true;};- }, [server, shell?.agentsListEpoch, showAgentFilter]);+ }, [agentId, selectedAgentLabel, server]);useEffect(() => {setFromValue(toDateTimeLocalValue(timeRange.startTs));@@ -107,16 +108,20 @@ export function AgentSessionsFilters({return (<div className="flex min-w-0 items-center gap-2">{showAgentFilter ? (- <PopoverSelect+ <AgentSearchPickeraria-label="Filter sessions by agent"prefix="Agents"- className="min-w-[12rem]"+ className="min-w-40"value={agentId ?? ''}- options={[- { value: '', label: 'All' },- ...agents.map(agent => ({ value: agent.agentId ?? agent.name, label: agent.name })),- ]}+ selectedLabel={agentId == null ? 'All' : (selectedAgentLabel ?? agentId)}+ allOption={{ value: '', label: 'All' }}onValueChange={value => onAgentChange(value.length === 0 ? null : value)}+ onAgentPicked={agent => {+ setAgentLabelById(current => ({+ ...current,+ [libraryAgentId(agent)]: agent.name,+ }));+ }}/>) : null}<div className="relative" ref={popoverRef}>diff --git a/packages/trueforge-ui/test/atoms/AgentSearchPicker.test.tsx b/packages/trueforge-ui/test/atoms/AgentSearchPicker.test.tsxindex bd348b248..fcbb399dc 100644--- a/packages/trueforge-ui/test/atoms/AgentSearchPicker.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentSearchPicker.test.tsx@@ -115,4 +115,39 @@ describe('AgentSearchPicker', () => {expect(screen.getByRole('option', { name: 'beta-bot' })).toBeInTheDocument();});});++ it('keeps a prefixed picker width stable and opens from its chrome', async () => {+ render(+ <AgentSearchPicker+ value="alpha-bot"+ selectedLabel="A long selected agent"+ onValueChange={() => undefined}+ prefix="Agents"+ />,+ {+ wrapper: wrap(+ createMockAgentUIServer({+ searchAgents: vi.fn(async () => [{ name: 'alpha-bot', agentId: 'alpha-bot' }]),+ }),+ ),+ },+ );++ const input = screen.getByRole('combobox', { name: 'Agent' });+ const trigger = screen.getByText('Agents').parentElement;+ if (trigger == null) throw new Error('expected prefixed picker trigger');++ fireEvent.click(screen.getByText('Agents'));+ expect(input).toHaveFocus();+ expect(input).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByText('A long selected agent')).toBeInTheDocument();+ await screen.findByRole('option', { name: 'alpha-bot' });++ fireEvent.keyDown(input, { key: 'Escape' });+ const chevron = trigger.querySelector('svg');+ if (chevron == null) throw new Error('expected picker chevron');+ fireEvent.click(chevron);+ expect(input).toHaveFocus();+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });});diff --git a/packages/trueforge-ui/test/atoms/AgentSessionsFilters.test.tsx b/packages/trueforge-ui/test/atoms/AgentSessionsFilters.test.tsxindex 0b9612f13..203dd6551 100644--- a/packages/trueforge-ui/test/atoms/AgentSessionsFilters.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentSessionsFilters.test.tsx@@ -1,36 +1,73 @@// @vitest-environment jsdom-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';import { AgentSessionsFilters } from '@/atoms/agent-details/AgentSessionsFilters.js';import { ServerProvider } from '@/server/ServerContext.js';-import type { AgentLibraryEntry } from '@/server/types.js';import { createMockAgentUIServer } from '../server/mockServer.js';describe('AgentSessionsFilters', () => {- it('loads every page of agents', async () => {- const agents: AgentLibraryEntry[] = Array.from({ length: 51 }, (_, index) => ({- agentId: `agent-${String(index + 1)}`,- name: `Agent ${String(index + 1)}`,- }));- const searchAgents = vi.fn(async ({ limit = 50, offset = 0 } = {}) => agents.slice(offset, offset + limit));+ afterEach(() => {+ vi.useRealTimers();+ });++ it('searches agents and applies the selected agent filter', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const searchAgents = vi.fn(async ({ query }: { query?: string } = {}) => {+ const agents = [+ { agentId: 'alpha-agent', name: 'Alpha agent' },+ { agentId: 'beta-agent', name: 'Beta agent' },+ ];+ return query == null ? agents : agents.filter(agent => agent.name.toLowerCase().includes(query.toLowerCase()));+ });+ const onAgentChange = vi.fn();render(<ServerProvider server={createMockAgentUIServer({ searchAgents })}><AgentSessionsFiltersagentId={null}timeRange={{ startTs: 1, endTs: 2 }}- onAgentChange={() => undefined}+ onAgentChange={onAgentChange}onTimeRangeChange={() => undefined}/></ServerProvider>,);- fireEvent.click(await screen.findByRole('button', { name: 'Filter sessions by agent' }));+ expect(searchAgents).not.toHaveBeenCalled();+ const filter = screen.getByRole('combobox', { name: 'Filter sessions by agent' });+ fireEvent.focus(filter);+ expect(await screen.findByRole('option', { name: 'Alpha agent' })).toBeInTheDocument();++ fireEvent.change(filter, { target: { value: 'beta' } });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300);+ });++ await waitFor(() => {+ expect(searchAgents).toHaveBeenCalledWith(expect.objectContaining({ query: 'beta' }));+ expect(screen.getByRole('option', { name: 'Beta agent' })).toBeInTheDocument();+ });+ fireEvent.click(screen.getByRole('option', { name: 'Beta agent' }));+ expect(onAgentChange).toHaveBeenCalledWith('beta-agent');+ });++ it('resolves the selected agent name after a refresh', async () => {+ const searchAgents = vi.fn(async () => [{ agentId: 'agent-id', name: 'Agent name' }]);++ render(+ <ServerProvider server={createMockAgentUIServer({ searchAgents })}>+ <AgentSessionsFilters+ agentId="agent-id"+ timeRange={{ startTs: 1, endTs: 2 }}+ onAgentChange={() => undefined}+ onTimeRangeChange={() => undefined}+ />+ </ServerProvider>,+ );- await waitFor(() => expect(screen.getByRole('option', { name: 'Agent 51' })).toBeInTheDocument());- expect(searchAgents).toHaveBeenNthCalledWith(1, { limit: 50, offset: 0 });- expect(searchAgents).toHaveBeenNthCalledWith(2, { limit: 50, offset: 50 });+ await waitFor(() => {+ expect(screen.getByRole('combobox', { name: 'Filter sessions by agent' })).toHaveValue('Agent name');+ });});it('can hide the custom time range option', () => {