The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: add pagination and server side search to list agents (#684)
Srajan Asthanadc2151f9a645
diff --git a/.changeset/paginate-list-agents.md b/.changeset/paginate-list-agents.mdnew file mode 100644index 000000000..b806f1750--- /dev/null+++ b/.changeset/paginate-list-agents.md@@ -0,0 +1,7 @@+---+"@truefoundry/trueforge": patch+"@truefoundry/trueforge-ui": patch+"@truefoundry/trueforge-sdk": patch+---++Paginate `GET /api/v1/agents` with `limit` / `page_token` and a `pagination` envelope; optional `agent_name` filters by case-insensitive substring. Agents library uses rows-per-page and prev/next against the token-paginated API. Schedule create and the schedules listing agent filter use a searchable agent combobox backed by the same filtered list API.diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex c494b6827..9b076745f 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -2128,10 +2128,14 @@"$ref": "#/components/schemas/Agent"},"type": "array"+ },+ "pagination": {+ "$ref": "#/components/schemas/TokenPagination"}},"required": [- "data"+ "data",+ "pagination"],"type": "object"},@@ -5569,7 +5573,7 @@"info": {"description": "HTTP API for the TrueForge agent server (`/api/v1`). Interactive docs are served at `/api/v1/docs` (OpenAPI JSON at `/api/v1/openapi.json`).\n\n**Authentication:** Standalone auth accepts requests without credentials — middleware stamps a local default user. When OIDC or TrueFoundry auth is configured, protected routes require a valid cookie or `Authorization: Bearer` token. There is no built-in API-key scheme; pass custom headers only if your reverse proxy or IdP layer requires them.\n\nCovers DB-backed sessions, the agent registry, settings catalogs, and model/MCP/skill/sandbox providers.","title": "TrueForge API",- "version": "0.2.0-rc.4"+ "version": "0.2.0-rc.5"},"openapi": "3.1.0","paths": {@@ -6113,7 +6117,43 @@},"/api/v1/agents": {"get": {- "description": "All configured agents for the tenant.",+ "description": "List configured agents for the tenant, ordered by name. Optional `agent_name` filters by substring.",+ "parameters": [+ {+ "description": "Page size. Defaults to 50, max 100.",+ "in": "query",+ "name": "limit",+ "required": false,+ "schema": {+ "default": 50,+ "description": "Page size. Defaults to 50, max 100.",+ "maximum": 100,+ "minimum": 1,+ "type": "integer"+ }+ },+ {+ "description": "Opaque token from a previous response `next_page_token`.",+ "in": "query",+ "name": "page_token",+ "required": false,+ "schema": {+ "description": "Opaque token from a previous response `next_page_token`.",+ "type": "string"+ }+ },+ {+ "description": "Case-insensitive substring match on agent name.",+ "in": "query",+ "name": "agent_name",+ "required": false,+ "schema": {+ "description": "Case-insensitive substring match on agent name.",+ "minLength": 1,+ "type": "string"+ }+ }+ ],"responses": {"200": {"content": {@@ -6123,7 +6163,17 @@}}},- "description": "All configured agents."+ "description": "Paginated matching agents."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid query parameters or page token."},"401": {"content": {@@ -6140,6 +6190,11 @@"tags": ["Agents"],+ "x-fern-pagination": {+ "cursor": "$request.page_token",+ "next_cursor": "$response.pagination.next_page_token",+ "results": "$response.data"+ },"x-fern-sdk-group-name": ["agents"],diff --git a/docs/openapi.json b/docs/openapi.jsonindex c494b6827..9b076745f 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -2128,10 +2128,14 @@"$ref": "#/components/schemas/Agent"},"type": "array"+ },+ "pagination": {+ "$ref": "#/components/schemas/TokenPagination"}},"required": [- "data"+ "data",+ "pagination"],"type": "object"},@@ -5569,7 +5573,7 @@"info": {"description": "HTTP API for the TrueForge agent server (`/api/v1`). Interactive docs are served at `/api/v1/docs` (OpenAPI JSON at `/api/v1/openapi.json`).\n\n**Authentication:** Standalone auth accepts requests without credentials — middleware stamps a local default user. When OIDC or TrueFoundry auth is configured, protected routes require a valid cookie or `Authorization: Bearer` token. There is no built-in API-key scheme; pass custom headers only if your reverse proxy or IdP layer requires them.\n\nCovers DB-backed sessions, the agent registry, settings catalogs, and model/MCP/skill/sandbox providers.","title": "TrueForge API",- "version": "0.2.0-rc.4"+ "version": "0.2.0-rc.5"},"openapi": "3.1.0","paths": {@@ -6113,7 +6117,43 @@},"/api/v1/agents": {"get": {- "description": "All configured agents for the tenant.",+ "description": "List configured agents for the tenant, ordered by name. Optional `agent_name` filters by substring.",+ "parameters": [+ {+ "description": "Page size. Defaults to 50, max 100.",+ "in": "query",+ "name": "limit",+ "required": false,+ "schema": {+ "default": 50,+ "description": "Page size. Defaults to 50, max 100.",+ "maximum": 100,+ "minimum": 1,+ "type": "integer"+ }+ },+ {+ "description": "Opaque token from a previous response `next_page_token`.",+ "in": "query",+ "name": "page_token",+ "required": false,+ "schema": {+ "description": "Opaque token from a previous response `next_page_token`.",+ "type": "string"+ }+ },+ {+ "description": "Case-insensitive substring match on agent name.",+ "in": "query",+ "name": "agent_name",+ "required": false,+ "schema": {+ "description": "Case-insensitive substring match on agent name.",+ "minLength": 1,+ "type": "string"+ }+ }+ ],"responses": {"200": {"content": {@@ -6123,7 +6163,17 @@}}},- "description": "All configured agents."+ "description": "Paginated matching agents."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid query parameters or page token."},"401": {"content": {@@ -6140,6 +6190,11 @@"tags": ["Agents"],+ "x-fern-pagination": {+ "cursor": "$request.page_token",+ "next_cursor": "$response.pagination.next_page_token",+ "results": "$response.data"+ },"x-fern-sdk-group-name": ["agents"],diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.mdindex 31ba5882c..fe932a62d 100644--- a/packages/trueforge-sdk/reference.md+++ b/packages/trueforge-sdk/reference.md@@ -67,7 +67,7 @@ await client.internal.listPermissions({</details>## Agents-<details><summary><code>client.agents.<a href="/src/api/resources/agents/client/Client.ts">list</a>() -> TrueForge.ListAgentsResponse</code></summary>+<details><summary><code>client.agents.<a href="/src/api/resources/agents/client/Client.ts">list</a>({ ...params }) -> core.Page<TrueForge.Agent, TrueForge.ListAgentsResponse></code></summary><dl><dd>@@ -79,7 +79,7 @@ await client.internal.listPermissions({<dl><dd>-All configured agents for the tenant.+List configured agents for the tenant, ordered by name. Optional `agent_name` filters by substring.</dd></dl></dd>@@ -110,6 +110,14 @@ await client.agents.list();<dl><dd>+**request:** `TrueForge.ListAgentsRequest`++</dd>+</dl>++<dl>+<dd>+**requestOptions:** `AgentsClient.RequestOptions`</dd>diff --git a/packages/trueforge-sdk/src/api/resources/agents/client/Client.ts b/packages/trueforge-sdk/src/api/resources/agents/client/Client.tsindex fbf595c8c..c2aece33d 100644--- a/packages/trueforge-sdk/src/api/resources/agents/client/Client.ts+++ b/packages/trueforge-sdk/src/api/resources/agents/client/Client.ts@@ -24,10 +24,12 @@ export class AgentsClient {}/**- * All configured agents for the tenant.+ * List configured agents for the tenant, ordered by name. Optional `agent_name` filters by substring.*+ * @param {TrueForge.ListAgentsRequest} request* @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.*+ * @throws {@link TrueForge.BadRequestError}* @throws {@link TrueForge.UnauthorizedError}* @throws {@link errors.TrueForgeError}* @throws {@link errors.TrueForgeTimeoutError}@@ -35,70 +37,104 @@ export class AgentsClient {* @example* await client.agents.list()*/- public list(requestOptions?: AgentsClient.RequestOptions): core.HttpResponsePromise<TrueForge.ListAgentsResponse> {- return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));- }-- private async __list(+ public async list(+ request: TrueForge.ListAgentsRequest = {},requestOptions?: AgentsClient.RequestOptions,- ): Promise<core.WithRawResponse<TrueForge.ListAgentsResponse>> {- const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();- const _headers: core.Fetcher.Args["headers"] = mergeHeaders(- _authRequest.headers,- this._options?.headers,- requestOptions?.headers,- );- const _response = await (this._options.fetcher ?? core.fetcher)({- url: core.url.join(- (await core.Supplier.get(this._options.baseUrl)) ??- (await core.Supplier.get(this._options.environment)),- "api/v1/agents",- ),- method: "GET",- headers: _headers,- queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),- timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,- maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,- abortSignal: requestOptions?.abortSignal,- fetchFn: this._options?.fetch,- logging: this._options.logging,- });- if (_response.ok) {- return {- data: serializers.ListAgentsResponse.parseOrThrow(_response.body, {- unrecognizedObjectKeys: "passthrough",- allowUnrecognizedUnionMembers: true,- allowUnrecognizedEnumValues: true,- skipValidation: true,- breadcrumbsPrefix: ["response"],- }),- rawResponse: _response.rawResponse,- };- }-- if (_response.error.reason === "status-code") {- switch (_response.error.statusCode) {- case 401:- throw new TrueForge.UnauthorizedError(- serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ ): Promise<core.Page<TrueForge.Agent, TrueForge.ListAgentsResponse>> {+ const list = core.HttpResponsePromise.interceptFunction(+ async (+ request: TrueForge.ListAgentsRequest,+ ): Promise<core.WithRawResponse<TrueForge.ListAgentsResponse>> => {+ const { limit = 50, pageToken, agentName } = request;+ const _queryParams: Record<string, unknown> = {+ limit,+ page_token: pageToken,+ agent_name: agentName,+ };+ const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(+ _authRequest.headers,+ this._options?.headers,+ requestOptions?.headers,+ );+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ "api/v1/agents",+ ),+ method: "GET",+ headers: _headers,+ queryString: core.url+ .queryBuilder()+ .addMany(_queryParams)+ .mergeAdditional(requestOptions?.queryParams)+ .build(),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return {+ data: serializers.ListAgentsResponse.parseOrThrow(_response.body, {unrecognizedObjectKeys: "passthrough",allowUnrecognizedUnionMembers: true,allowUnrecognizedEnumValues: true,skipValidation: true,breadcrumbsPrefix: ["response"],}),- _response.rawResponse,- );- default:- throw new errors.TrueForgeError({- statusCode: _response.error.statusCode,- body: _response.error.body,rawResponse: _response.rawResponse,- });- }- }-- return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/agents");+ };+ }+ if (_response.error.reason === "status-code") {+ switch (_response.error.statusCode) {+ case 400:+ throw new TrueForge.BadRequestError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 401:+ throw new TrueForge.UnauthorizedError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ default:+ throw new errors.TrueForgeError({+ statusCode: _response.error.statusCode,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }+ }+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/agents");+ },+ );+ const dataWithRawResponse = await list(request).withRawResponse();+ return new core.Page<TrueForge.Agent, TrueForge.ListAgentsResponse>({+ response: dataWithRawResponse.data,+ rawResponse: dataWithRawResponse.rawResponse,+ hasNextPage: (response) =>+ response?.pagination.nextPageToken != null &&+ !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""),+ getItems: (response) => response?.data ?? [],+ loadPage: (response) => {+ return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken));+ },+ });}/**diff --git a/packages/trueforge-sdk/src/api/resources/agents/client/requests/ListAgentsRequest.ts b/packages/trueforge-sdk/src/api/resources/agents/client/requests/ListAgentsRequest.tsnew file mode 100644index 000000000..568abed61--- /dev/null+++ b/packages/trueforge-sdk/src/api/resources/agents/client/requests/ListAgentsRequest.ts@@ -0,0 +1,14 @@+// This file was auto-generated by Fern from our API Definition.++/**+ * @example+ * {}+ */+export interface ListAgentsRequest {+ /** Page size. Defaults to 50, max 100. */+ limit?: number;+ /** Opaque token from a previous response `next_page_token`. */+ pageToken?: string;+ /** Case-insensitive substring match on agent name. */+ agentName?: string;+}diff --git a/packages/trueforge-sdk/src/api/resources/agents/client/requests/index.ts b/packages/trueforge-sdk/src/api/resources/agents/client/requests/index.tsindex ed75949c6..cde69b4a4 100644--- a/packages/trueforge-sdk/src/api/resources/agents/client/requests/index.ts+++ b/packages/trueforge-sdk/src/api/resources/agents/client/requests/index.ts@@ -1,2 +1,3 @@export type { CreateAgentRequest } from "./CreateAgentRequest.js";+export type { ListAgentsRequest } from "./ListAgentsRequest.js";export type { UpdateAgentRequest } from "./UpdateAgentRequest.js";diff --git a/packages/trueforge-sdk/src/api/types/ListAgentsResponse.ts b/packages/trueforge-sdk/src/api/types/ListAgentsResponse.tsindex 31819069c..c74cbca29 100644--- a/packages/trueforge-sdk/src/api/types/ListAgentsResponse.ts+++ b/packages/trueforge-sdk/src/api/types/ListAgentsResponse.ts@@ -4,4 +4,5 @@ import type * as TrueForge from "../index.js";export interface ListAgentsResponse {data: TrueForge.Agent[];+ pagination: TrueForge.TokenPagination;}diff --git a/packages/trueforge-sdk/src/serialization/types/ListAgentsResponse.ts b/packages/trueforge-sdk/src/serialization/types/ListAgentsResponse.tsindex 15018a96a..1c20a1ac8 100644--- a/packages/trueforge-sdk/src/serialization/types/ListAgentsResponse.ts+++ b/packages/trueforge-sdk/src/serialization/types/ListAgentsResponse.ts@@ -4,16 +4,19 @@ import type * as TrueForge from "../../api/index.js";import * as core from "../../core/index.js";import type * as serializers from "../index.js";import { Agent } from "./Agent.js";+import { TokenPagination } from "./TokenPagination.js";export const ListAgentsResponse: core.serialization.ObjectSchema<serializers.ListAgentsResponse.Raw,TrueForge.ListAgentsResponse> = core.serialization.object({data: core.serialization.list(Agent),+ pagination: TokenPagination,});export declare namespace ListAgentsResponse {export interface Raw {data: Agent.Raw[];+ pagination: TokenPagination.Raw;}}diff --git a/packages/trueforge-sdk/tests/wire/agents.test.ts b/packages/trueforge-sdk/tests/wire/agents.test.tsindex c4b00174b..0bdd448a3 100644--- a/packages/trueforge-sdk/tests/wire/agents.test.ts+++ b/packages/trueforge-sdk/tests/wire/agents.test.ts@@ -22,12 +22,18 @@ describe("AgentsClient", () => {name: "name",},],+ pagination: { limit: 1, next_page_token: "next_page_token", previous_page_token: "previous_page_token" },};- server.mockEndpoint().get("/api/v1/agents").respondWith().statusCode(200).jsonBody(rawResponseBody).build();+ server+ .mockEndpoint({ once: false })+ .get("/api/v1/agents")+ .respondWith()+ .statusCode(200)+ .jsonBody(rawResponseBody)+ .build();- const response = await client.agents.list();- expect(response).toEqual({+ const expected = {data: [{createdBySubject: {@@ -44,7 +50,18 @@ describe("AgentsClient", () => {name: "name",},],- });+ pagination: {+ limit: 1,+ nextPageToken: "next_page_token",+ previousPageToken: "previous_page_token",+ },+ };+ const page = await client.agents.list();++ expect(expected.data).toEqual(page.data);+ expect(page.hasNextPage()).toBe(true);+ const nextPage = await page.getNextPage();+ expect(expected.data).toEqual(nextPage.data);});test("list (2)", async () => {@@ -53,6 +70,19 @@ describe("AgentsClient", () => {const rawResponseBody = { error: { message: "message" } };+ server.mockEndpoint().get("/api/v1/agents").respondWith().statusCode(400).jsonBody(rawResponseBody).build();++ await expect(async () => {+ return await client.agents.list();+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);+ });++ test("list (3)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });++ const rawResponseBody = { error: { message: "message" } };+server.mockEndpoint().get("/api/v1/agents").respondWith().statusCode(401).jsonBody(rawResponseBody).build();await expect(async () => {diff --git a/packages/trueforge-ui/src/atoms/AgentSearchPicker.tsx b/packages/trueforge-ui/src/atoms/AgentSearchPicker.tsxnew file mode 100644index 000000000..f16930d00--- /dev/null+++ b/packages/trueforge-ui/src/atoms/AgentSearchPicker.tsx@@ -0,0 +1,272 @@+'use client';++import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';++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 { themePortalRoot } from './lib/themePortalRoot.js';+import { useSearchAgentsList } from './lib/useSearchAgentsList.js';+import { Button } from './primitives/Button.js';++export type AgentSearchPickerProps = {+ value: string;+ selectedLabel: string;+ onValueChange: (agentId: string) => void;+ onAgentPicked?: (agent: AgentLibraryEntry) => void;+ disabled?: boolean;+ onBuildAgent?: () => void;+ /** When set, shows this option above results while the query is empty (e.g. filter "All agents"). */+ allOption?: { value: string; label: string };+ 'aria-label'?: string;+ placeholder?: string;+ className?: string;+};++/**+ * Combobox agent picker: type in the field to filter via debounced `searchAgents`.+ */+export function AgentSearchPicker({+ value,+ selectedLabel,+ onValueChange,+ onAgentPicked,+ disabled = false,+ onBuildAgent,+ allOption,+ 'aria-label': ariaLabel = 'Agent',+ placeholder = 'Search agent',+ className,+}: AgentSearchPickerProps) {+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState('');+ const [pos, setPos] = useState<{ top: number; left: number; width: number } | null>(null);+ const rootRef = useRef<HTMLDivElement>(null);+ const triggerRef = useRef<HTMLDivElement>(null);+ const inputRef = useRef<HTMLInputElement>(null);+ const menuRef = useRef<HTMLDivElement>(null);+ const listboxId = useId();++ const { agents, isInitialLoading, isSearching, loadingMore, hasMore, error, listRef, sentinelRef } =+ useSearchAgentsList({+ enabled: open && !disabled,+ query,+ });++ useEffect(() => {+ if (!open) setQuery('');+ }, [open]);++ useLayoutEffect(() => {+ if (!open) {+ setPos(null);+ return;+ }++ const update = () => {+ const el = triggerRef.current;+ if (!el) return;+ const rect = el.getBoundingClientRect();+ setPos({+ top: rect.bottom + 4,+ left: rect.left,+ width: rect.width,+ });+ };++ update();+ window.addEventListener('scroll', update, true);+ window.addEventListener('resize', update);+ return () => {+ window.removeEventListener('scroll', update, true);+ window.removeEventListener('resize', update);+ };+ }, [open]);++ useEffect(() => {+ if (!open) return;++ const handlePointerDown = (event: MouseEvent) => {+ if (!(event.target instanceof Node)) return;+ if (rootRef.current?.contains(event.target)) return;+ if (menuRef.current?.contains(event.target)) return;+ setOpen(false);+ };+ document.addEventListener('mousedown', handlePointerDown);+ return () => document.removeEventListener('mousedown', handlePointerDown);+ }, [open]);++ const close = () => {+ setOpen(false);+ setQuery('');+ inputRef.current?.blur();+ };++ const pick = (agent: AgentLibraryEntry) => {+ const id = libraryAgentId(agent);+ onValueChange(id);+ onAgentPicked?.(agent);+ close();+ };++ const pickAll = () => {+ if (allOption == null) return;+ onValueChange(allOption.value);+ close();+ };++ const inputValue = open ? query : selectedLabel;+ const queryTrimmed = query.trim();+ const showError = !isInitialLoading && error != null;+ const showEmptyCatalog = !isInitialLoading && error == null && agents.length === 0 && queryTrimmed === '';+ const showNoMatch = !isInitialLoading && error == null && agents.length === 0 && queryTrimmed !== '';++ const menu =+ open && pos != null && !disabled+ ? createPortal(+ <div+ ref={menuRef}+ className={auiSelectMenuClass('fixed z-[200] flex max-h-64 flex-col overflow-hidden')}+ style={{+ top: pos.top,+ left: pos.left,+ width: pos.width,+ }}+ onMouseDown={event => event.stopPropagation()}+ >+ <div+ ref={listRef}+ id={listboxId}+ role="listbox"+ aria-label={ariaLabel}+ className="min-h-0 flex-1 overflow-y-auto p-1"+ >+ {allOption != null && queryTrimmed === '' ? (+ <button+ type="button"+ role="option"+ aria-selected={value === allOption.value}+ className={auiSelectOptionClass()}+ onClick={pickAll}+ >+ <span className="min-w-0 flex-1 truncate">{allOption.label}</span>+ <Icon+ name="check"+ className={cn('ml-auto size-4 shrink-0', value === allOption.value ? 'opacity-100' : 'opacity-0')}+ />+ </button>+ ) : null}+ {isInitialLoading ? (+ <p className="text-text-secondary px-3 py-5 text-center text-sm" role="status">+ Loading…+ </p>+ ) : showError ? (+ <p className="text-failure-bg px-3 py-5 text-center text-sm" role="alert">+ {error}+ </p>+ ) : showEmptyCatalog ? (+ <p className="text-text-secondary px-3 py-5 text-center text-sm">No Agents created yet</p>+ ) : showNoMatch ? (+ <p className="text-text-secondary px-3 py-5 text-center text-sm" role="status">+ No agents match "{queryTrimmed}".+ </p>+ ) : (+ <>+ {isSearching ? (+ <p className="sr-only" role="status">+ Searching…+ </p>+ ) : null}+ {agents.map(agent => {+ const id = libraryAgentId(agent);+ const selected = value === id;+ return (+ <button+ key={id}+ type="button"+ role="option"+ aria-selected={selected}+ className={auiSelectOptionClass()}+ onClick={() => pick(agent)}+ >+ <span className="min-w-0 flex-1 truncate">{agent.name}</span>+ <Icon+ name="check"+ className={cn('ml-auto size-4 shrink-0', selected ? 'opacity-100' : 'opacity-0')}+ />+ </button>+ );+ })}+ {hasMore ? (+ <div ref={sentinelRef} className="flex h-6 shrink-0 items-center justify-center" aria-hidden>+ {loadingMore ? (+ <span className="text-text-secondary text-[11px]" role="status">+ Loading more…+ </span>+ ) : null}+ </div>+ ) : null}+ </>+ )}+ </div>+ {showEmptyCatalog && onBuildAgent != null ? (+ <div className="flex justify-end border-t border-border px-2 pt-2">+ <Button.Ghost type="button" onClick={onBuildAgent}>+ <Icon name="plus" className="size-3.5" />+ Build Agent+ </Button.Ghost>+ </div>+ ) : null}+ </div>,+ themePortalRoot(rootRef.current),+ )+ : null;++ return (+ <div ref={rootRef} className={cn('relative', className)}>+ <div+ ref={triggerRef}+ className={auiSelectTriggerClass(disabled ? 'cursor-not-allowed opacity-50' : 'cursor-text')}+ >+ <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);+ }+ }}+ />+ <Icon name="chevron-down" className="size-4 shrink-0 text-text-secondary" />+ </div>+ {menu}+ </div>+ );+}diff --git a/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx b/packages/trueforge-ui/src/atoms/AgentsLibrary.tsxindex 086b103cf..df8b4ce1c 100644--- a/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx+++ b/packages/trueforge-ui/src/atoms/AgentsLibrary.tsx@@ -21,9 +21,21 @@ import { PageHeader } from './PageHeader.js';import { Button } from './primitives/Button.js';import SearchInput from './primitives/SearchInput.js';import { Skeleton } from './primitives/Skeleton.js';-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './primitives/Table.js';+import {+ DEFAULT_TABLE_PAGE_SIZE,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ TableTokenPagination,+} from './primitives/Table.js';import { Tooltip } from './primitives/Tooltip.js';+/** API max page size for agents list. */+const AGENTS_PAGE_SIZE_OPTIONS = [10, 25] as const;+export type AgentsLibraryProps = {onSelectAgent?: (agentName: string) => void;};@@ -357,12 +369,15 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {return () => window.removeEventListener('keydown', onKeyDown, true);}, [closeLibrary, open]);- const { agents, isInitialLoading, isSearching, loadingMore, error, hasMore, listRef, sentinelRef } =+ const { agents, isInitialLoading, isSearching, error, pageSize, setPageSize, canPrev, canNext, goPrev, goNext } =useSearchAgentsList({enabled: open,query,refreshKey: agentsListEpoch,+ mode: 'paged',+ limit: DEFAULT_TABLE_PAGE_SIZE,});+ const hasPageNav = canPrev || canNext;const showCreatedByColumn = hasCreatedBySubject(agents);const permissionAgentIds = open ? agents.map(libraryAgentId) : [];const { allows } = useResourcePermissions({@@ -449,7 +464,7 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {<div className="bg-secondary-bg/40 flex min-h-0 flex-1 flex-col">{/* Not flex-col: overflow-hidden table chrome would clip instead of letting this scroll. */}- <div ref={listRef} className="min-h-0 flex-1 overflow-y-auto p-4" aria-label="Agents">+ <div className="min-h-0 flex-1 overflow-y-auto p-4" aria-label="Agents">{isInitialLoading ? (<div className="flex flex-col gap-2 p-1" role="status" aria-label="Loading agents">{Array.from({ length: 6 }, (_, i) => (@@ -458,7 +473,7 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {</div>) : error ? (<p className="text-failure-bg px-3 py-8 text-center text-sm">{error}</p>- ) : agents.length === 0 ? (+ ) : agents.length === 0 && !hasPageNav ? (<EmptyScreentitle="No Agents Found"description={@@ -471,87 +486,114 @@ export function AgentsLibrary({ onSelectAgent }: AgentsLibraryProps) {)}/>- ) : (- <>+ ) : agents.length === 0 ? (+ <div className="flex min-h-full flex-col">+ <EmptyScreen+ title="No Agents Found"+ description={+ query.trim() ? (+ <>+ No search results found for <EmptyScreenQueryHighlight>{query.trim()}</EmptyScreenQueryHighlight>+ </>+ ) : (+ 'Build one in a chat, then save it as an agent.'+ )+ }+ className="flex-1"+ /><div className="overflow-hidden rounded-lg border border-border">- <Table>- <TableHeader>- <TableRow className="hover:bg-transparent">- <TableHead>Agent name</TableHead>- <TableHead>Configuration</TableHead>- {showCreatedByColumn ? <TableHead>Created by</TableHead> : null}- {showSchedulesColumn ? <TableHead className="w-[14rem]">Schedules</TableHead> : null}- <TableHead className="w-px">- <span className="sr-only">Actions</span>- </TableHead>- </TableRow>- </TableHeader>- <TableBody>- {agents.map(agent => {- const agentSpec = agent.agentSpec;- const agentId = agent.agentId;- const id = libraryAgentId(agent);- const summary = showSchedulesColumn- ? (scheduleByAgent?.get(id) ??- scheduleByAgent?.get(agent.name) ??- (scheduleByAgent == null- ? null- : { count: 0, pausedCount: 0, activeNames: [], pausedNames: [] }))- : undefined;- return (- <SlottedAgentLibraryRow- key={id}- agent={agent}- canMutate={canMutate}- canUseAgent={allows(id, 'USE')}- canManageAgent={allows(id, 'MANAGE')}- canDeleteAgent={allows(id, 'DELETE')}- canManageSchedules={canOpenAgentSchedules}- showCreatedBy={showCreatedByColumn}- {...(summary !== undefined ? { scheduleSummary: summary } : {})}- {...(canOpenAgentSchedules && agentId != null- ? {- onOpenSchedules: () => openSchedulesForAgent({ agentId }),- onCreateSchedule: () => openSchedulesForAgent({ agentId, isNew: true }),- onManageSchedules: () => openSchedulesForAgent({ agentId }),- }- : {})}- {...(canOpenAgentDetails && agentId != null- ? {- onOpen: () => {- updateShareSearch({- agentId,- tab: 'overview',- sessionId: null,- view: null,- timeRange: null,- });- shell.openLibraryAgent(agentId);- },- }- : {})}- onTry={() => {- if (allows(id, 'USE')) handleTry(agent);- }}- onEdit={() => {- if (agentSpec != null && allows(id, 'MANAGE')) handleEdit(agent, agentSpec);- }}- />- );- })}- </TableBody>- </Table>+ <TableTokenPagination+ pageSize={pageSize}+ rowCount={0}+ canPrev={canPrev}+ canNext={canNext}+ onPrev={goPrev}+ onNext={goNext}+ pageSizeOptions={AGENTS_PAGE_SIZE_OPTIONS}+ onPageSizeChange={setPageSize}+ /></div>- {hasMore ? (- <div ref={sentinelRef} className="flex h-8 shrink-0 items-center justify-center" aria-hidden>- {loadingMore ? (- <span className="text-text-secondary text-xs" role="status">- Loading more…- </span>- ) : null}- </div>- ) : null}- </>+ </div>+ ) : (+ <div className="overflow-hidden rounded-lg border border-border">+ <Table>+ <TableHeader>+ <TableRow className="hover:bg-transparent">+ <TableHead>Agent name</TableHead>+ <TableHead>Configuration</TableHead>+ {showCreatedByColumn ? <TableHead>Created by</TableHead> : null}+ {showSchedulesColumn ? <TableHead className="w-[14rem]">Schedules</TableHead> : null}+ <TableHead className="w-px">+ <span className="sr-only">Actions</span>+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {agents.map(agent => {+ const agentSpec = agent.agentSpec;+ const agentId = agent.agentId;+ const id = libraryAgentId(agent);+ const summary = showSchedulesColumn+ ? (scheduleByAgent?.get(id) ??+ scheduleByAgent?.get(agent.name) ??+ (scheduleByAgent == null+ ? null+ : { count: 0, pausedCount: 0, activeNames: [], pausedNames: [] }))+ : undefined;+ return (+ <SlottedAgentLibraryRow+ key={id}+ agent={agent}+ canMutate={canMutate}+ canUseAgent={allows(id, 'USE')}+ canManageAgent={allows(id, 'MANAGE')}+ canDeleteAgent={allows(id, 'DELETE')}+ canManageSchedules={canOpenAgentSchedules}+ showCreatedBy={showCreatedByColumn}+ {...(summary !== undefined ? { scheduleSummary: summary } : {})}+ {...(canOpenAgentSchedules && agentId != null+ ? {+ onOpenSchedules: () => openSchedulesForAgent({ agentId }),+ onCreateSchedule: () => openSchedulesForAgent({ agentId, isNew: true }),+ onManageSchedules: () => openSchedulesForAgent({ agentId }),+ }+ : {})}+ {...(canOpenAgentDetails && agentId != null+ ? {+ onOpen: () => {+ updateShareSearch({+ agentId,+ tab: 'overview',+ sessionId: null,+ view: null,+ timeRange: null,+ });+ shell.openLibraryAgent(agentId);+ },+ }+ : {})}+ onTry={() => {+ if (allows(id, 'USE')) handleTry(agent);+ }}+ onEdit={() => {+ if (agentSpec != null && allows(id, 'MANAGE')) handleEdit(agent, agentSpec);+ }}+ />+ );+ })}+ </TableBody>+ </Table>+ <TableTokenPagination+ pageSize={pageSize}+ rowCount={agents.length}+ canPrev={canPrev}+ canNext={canNext}+ onPrev={goPrev}+ onNext={goNext}+ pageSizeOptions={AGENTS_PAGE_SIZE_OPTIONS}+ onPageSizeChange={setPageSize}+ />+ </div>)}</div></div>diff --git a/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts b/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.tsindex 89f8498a6..e9370fd88 100644--- a/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts+++ b/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts@@ -7,10 +7,16 @@ import type { AgentBuilderServer, AgentLibraryEntry } from '../../server/types.jimport { getErrorMessage } from '../../utils/getErrorMessage.js';import { useDebouncedValue } from './useDebouncedValue.js';+/** Matches API AGENTS_PAGE_DEFAULT / AGENTS_PAGE_LIMIT. */export const SEARCH_AGENTS_PAGE_SIZE = 50;+export const SEARCH_AGENTS_PAGE_MAX = 100;const DEFAULT_DEBOUNCE_MS = 300;const LOAD_MORE_ROOT_MARGIN = '48px';+function clampPageSize(size: number): number {+ return Math.min(Math.max(size, 1), SEARCH_AGENTS_PAGE_MAX);+}+/** Drain every `searchAgents` page (offset pagination). */export async function searchAllAgents(server: Pick<AgentBuilderServer, 'searchAgents'>,@@ -21,7 +27,7 @@ export async function searchAllAgents(return [...rows, ...(await searchAllAgents(server, offset + rows.length))];}-/** Exact-name queries can still span multiple server-filtered pages. */+/** Exact-name lookup walks server-filtered pages until a precise match is found. */export async function findAgentByName({server,agentName,@@ -37,14 +43,36 @@ export async function findAgentByName({return findAgentByName({ server, agentName, offset: offset + rows.length });}+/** Resolve by agent id or exact name by walking unfiltered pages (ids are not name-searchable). */+export async function findLibraryAgent({+ server,+ agentKey,+ offset = 0,+}: {+ server: Pick<AgentBuilderServer, 'searchAgents'>;+ agentKey: string;+ offset?: number;+}): Promise<AgentLibraryEntry | undefined> {+ const rows = await server.searchAgents({ limit: SEARCH_AGENTS_PAGE_SIZE, offset });+ const match = rows.find(agent => agent.name === agentKey || agent.agentId === agentKey);+ if (match != null || rows.length < SEARCH_AGENTS_PAGE_SIZE) return match;+ return findLibraryAgent({ server, agentKey, offset: offset + rows.length });+}+export type UseSearchAgentsListOptions = {/** When false, no fetches run. */enabled: boolean;query: string;/** Bump to force a replace fetch (e.g. agentsListEpoch). */refreshKey?: number;+ /** Page size for infinite mode, or initial size for paged mode. Capped at 100. */limit?: number;debounceMs?: number;+ /**+ * `infinite` — append via IntersectionObserver sentinel (default).+ * `paged` — replace rows; navigate with goPrev / goNext.+ */+ mode?: 'infinite' | 'paged';};export type UseSearchAgentsListResult = {@@ -58,18 +86,26 @@ export type UseSearchAgentsListResult = {hasMore: boolean;listRef: (node: HTMLElement | null) => void;sentinelRef: (node: HTMLElement | null) => void;+ pageSize: number;+ setPageSize: (pageSize: number) => void;+ canPrev: boolean;+ canNext: boolean;+ goPrev: () => void;+ goNext: () => void;};/**- * Debounced `searchAgents` with offset pagination and an IntersectionObserver sentinel.- * Attach `listRef` to the scroll container and `sentinelRef` to a footer element.+ * Debounced `searchAgents` with offset pagination.+ * Infinite mode: attach `listRef` / `sentinelRef` for IntersectionObserver load-more.+ * Paged mode: use `goPrev` / `goNext` / `setPageSize` (rows replaced each fetch).*/export function useSearchAgentsList({enabled,query,refreshKey = 0,- limit = SEARCH_AGENTS_PAGE_SIZE,+ limit: limitOption = SEARCH_AGENTS_PAGE_SIZE,debounceMs = DEFAULT_DEBOUNCE_MS,+ mode = 'infinite',}: UseSearchAgentsListOptions): UseSearchAgentsListResult {const server = useOptionalServer();// While closed, sync immediately so reopen never fetches a stale query.@@ -80,6 +116,8 @@ export function useSearchAgentsList({const [loadingMore, setLoadingMore] = useState(false);const [error, setError] = useState<string | null>(null);const [hasMore, setHasMore] = useState(false);+ const [pageSize, setPageSizeState] = useState(() => clampPageSize(limitOption));+ const [offset, setOffset] = useState(0);const genRef = useRef(0);const loadMoreInflightRef = useRef(false);@@ -90,6 +128,8 @@ export function useSearchAgentsList({const [listEl, setListEl] = useState<HTMLElement | null>(null);const [sentinelEl, setSentinelEl] = useState<HTMLElement | null>(null);+ const limit = mode === 'paged' ? pageSize : clampPageSize(limitOption);+hasMoreRef.current = hasMore;agentsLenRef.current = agents.length;@@ -105,6 +145,12 @@ export function useSearchAgentsList({const searchQuery = debouncedQuery.trim() || undefined;+ // Reset to first page when the query or catalog epoch changes.+ useEffect(() => {+ if (mode !== 'paged') return;+ setOffset(0);+ }, [mode, searchQuery, refreshKey]);+useEffect(() => {if (!enabled || server == null) return;@@ -113,8 +159,10 @@ export function useSearchAgentsList({setLoading(true);setError(null);+ const fetchOffset = mode === 'paged' ? offset : 0;+void server- .searchAgents({ query: searchQuery, limit, offset: 0 })+ .searchAgents({ query: searchQuery, limit, offset: fetchOffset }).then(rows => {if (gen !== genRef.current) return;setAgents(rows);@@ -133,20 +181,21 @@ export function useSearchAgentsList({return () => {genRef.current += 1;};- }, [enabled, server, searchQuery, limit, refreshKey]);+ }, [enabled, server, searchQuery, limit, refreshKey, mode, offset]);const loadMore = useCallback(() => {+ if (mode !== 'infinite') return;if (!enabled || server == null || !hasMoreRef.current || loadMoreInflightRef.current || loading) {return;}const gen = genRef.current;- const offset = agentsLenRef.current;+ const nextOffset = agentsLenRef.current;loadMoreInflightRef.current = true;setLoadingMore(true);void server- .searchAgents({ query: searchQuery, limit, offset })+ .searchAgents({ query: searchQuery, limit, offset: nextOffset }).then(rows => {if (gen !== genRef.current) return;setAgents(prev => [...prev, ...rows]);@@ -160,10 +209,10 @@ export function useSearchAgentsList({loadMoreInflightRef.current = false;if (gen === genRef.current) setLoadingMore(false);});- }, [enabled, server, searchQuery, limit, loading]);+ }, [enabled, server, searchQuery, limit, loading, mode]);useEffect(() => {- if (!enabled || !hasMore || listEl == null || sentinelEl == null) return;+ if (mode !== 'infinite' || !enabled || !hasMore || listEl == null || sentinelEl == null) return;const observer = new IntersectionObserver(entries => {@@ -175,7 +224,22 @@ export function useSearchAgentsList({);observer.observe(sentinelEl);return () => observer.disconnect();- }, [enabled, hasMore, listEl, sentinelEl, loadMore, agents.length]);+ }, [mode, enabled, hasMore, listEl, sentinelEl, loadMore, agents.length]);++ const setPageSize = useCallback((size: number) => {+ setPageSizeState(clampPageSize(size));+ setOffset(0);+ }, []);++ const goNext = useCallback(() => {+ if (mode !== 'paged' || !hasMoreRef.current || loading) return;+ setOffset(current => current + pageSize);+ }, [mode, loading, pageSize]);++ const goPrev = useCallback(() => {+ if (mode !== 'paged' || loading) return;+ setOffset(current => Math.max(0, current - pageSize));+ }, [mode, loading, pageSize]);return {agents,@@ -186,5 +250,11 @@ export function useSearchAgentsList({hasMore,listRef,sentinelRef,+ pageSize,+ setPageSize,+ canPrev: mode === 'paged' && offset > 0,+ canNext: mode === 'paged' && hasMore,+ goPrev,+ goNext,};}diff --git a/packages/trueforge-ui/src/atoms/schedules/ScheduleFormDrawer.tsx b/packages/trueforge-ui/src/atoms/schedules/ScheduleFormDrawer.tsxindex aebff6962..ca9a1c835 100644--- a/packages/trueforge-ui/src/atoms/schedules/ScheduleFormDrawer.tsx+++ b/packages/trueforge-ui/src/atoms/schedules/ScheduleFormDrawer.tsx@@ -1,6 +1,6 @@'use client';-import { useEffect, useMemo, useState, type FormEvent, type ReactNode } from 'react';+import { useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react';import { useToasterOptional } from '../../containers/ToasterContainer.js';import { useResourcePermissions } from '../../hooks/useResourcePermissions.js';@@ -10,7 +10,7 @@ import { libraryAgentId, useOptionalShellMode } from '../../server/ShellModeContimport type { AgentLibraryEntry, Schedule } from '../../server/types.js';import { DraftCatalogProvider } from '../draft/DraftCatalogProvider.js';import { mountName } from '../lib/mountName.js';-import { searchAllAgents } from '../lib/useSearchAgentsList.js';+import { findLibraryAgent } from '../lib/useSearchAgentsList.js';import { Button } from '../primitives/Button.js';import { SideDrawer } from '../primitives/SideDrawer.js';import {@@ -48,12 +48,13 @@ function ScheduleFormDrawerBody({const toaster = useToasterOptional();const [form, setForm] = useState<ScheduleFormValues>(defaultScheduleFormValues);const [agentId, setAgentId] = useState(initialAgentId);- const [agents, setAgents] = useState<AgentLibraryEntry[]>([]);- const [agentsLoaded, setAgentsLoaded] = useState(false);+ const [selectedAgent, setSelectedAgent] = useState<AgentLibraryEntry | null>(null);const [view, setView] = useState<DrawerView>({ kind: 'form' });const [saving, setSaving] = useState(false);const [activating, setActivating] = useState(false);const [error, setError] = useState<string | null>(null);+ const agentIdRef = useRef(agentId);+ agentIdRef.current = agentId;const savedFromCreate = view.kind === 'form' ? view.saved : view.schedule;const isExternalEdit = mode === 'edit' && view.kind === 'form' && view.saved == null && schedule != null;@@ -64,26 +65,11 @@ function ScheduleFormDrawerBody({resourceIds: agentId.length === 0 ? [] : [agentId],});- useEffect(() => {- if (!open) return;- let cancelled = false;- setAgentsLoaded(false);- void searchAllAgents(server)- .then(rows => {- if (cancelled) return;- setAgents(rows);- setAgentsLoaded(true);- })- .catch(() => undefined);- return () => {- cancelled = true;- };- }, [open, server]);-useEffect(() => {if (!open) {setForm(defaultScheduleFormValues());setAgentId(initialAgentId);+ setSelectedAgent(null);setError(null);setView({ kind: 'form' });setActivating(false);@@ -99,30 +85,37 @@ function ScheduleFormDrawerBody({}),);setAgentId(schedule.agentId);+ setSelectedAgent(null);setView({ kind: 'form' });return;}setForm(defaultScheduleFormValues());setAgentId(initialAgentId);+ setSelectedAgent(null);setView({ kind: 'form' });}, [open, mode, schedule, initialAgentId]);- const agentOptions = useMemo(- () => agents.map(agent => ({ agentId: libraryAgentId(agent), name: agent.name })),- [agents],- );-- const selectedAgent = useMemo(- () => agents.find(agent => libraryAgentId(agent) === agentId) ?? null,- [agents, agentId],- );+ // Prefill create with a known agent id or exact name.+ useEffect(() => {+ if (!open || mode !== 'create' || initialAgentId.length === 0) return;+ let cancelled = false;+ const requestedId = initialAgentId;+ void findLibraryAgent({ server, agentKey: requestedId })+ .then(agent => {+ if (cancelled || agent == null) return;+ // Skip if the user already picked a different agent while this was in flight.+ if (agentIdRef.current !== requestedId) return;+ setSelectedAgent(agent);+ setAgentId(libraryAgentId(agent));+ })+ .catch(() => undefined);+ return () => {+ cancelled = true;+ };+ }, [open, mode, initialAgentId, server]);const agentLabel =- selectedAgent?.name ??- savedFromCreate?.agentName ??- schedule?.agentName ??- agentOptions.find(option => option.agentId === agentId)?.name ??- agentId;+ selectedAgent?.name ?? savedFromCreate?.agentName ?? schedule?.agentName ?? (agentId.length > 0 ? agentId : '');const mcpMounts = useMemo(() => {const mounts = selectedAgent?.agentSpec?.mcpServers ?? [];@@ -311,9 +304,16 @@ function ScheduleFormDrawerBody({values={form}onChange={setForm}agentId={agentId}- onAgentIdChange={isExternalEdit || isCreatedEdit ? undefined : setAgentId}- agentOptions={agentOptions}- agentOptionsLoaded={agentsLoaded}+ agentLabel={agentLabel}+ onAgentIdChange={+ isExternalEdit || isCreatedEdit+ ? undefined+ : nextId => {+ setAgentId(nextId);+ if (nextId.length === 0) setSelectedAgent(null);+ }+ }+ onAgentPicked={setSelectedAgent}agentPickerDisabled={isExternalEdit || isCreatedEdit}onBuildAgent={mode === 'create' && shell?.isComposerEnabled === truediff --git a/packages/trueforge-ui/src/atoms/schedules/ScheduleFormFields.tsx b/packages/trueforge-ui/src/atoms/schedules/ScheduleFormFields.tsxindex 1614f883e..9ac1ebfea 100644--- a/packages/trueforge-ui/src/atoms/schedules/ScheduleFormFields.tsx+++ b/packages/trueforge-ui/src/atoms/schedules/ScheduleFormFields.tsx@@ -1,9 +1,10 @@'use client';import { Icon } from '../../icons/Icon.js';+import type { AgentLibraryEntry } from '../../server/types.js';+import { AgentSearchPicker } from '../AgentSearchPicker.js';import { cn } from '../lib/cn.js';import { auiInputClass } from '../lib/inputClasses.js';-import { Button } from '../primitives/Button.js';import { PopoverSelect } from '../primitives/PopoverSelect.js';import {WEEKDAY_OPTIONS,@@ -33,9 +34,9 @@ export type ScheduleFormFieldsProps = {values: ScheduleFormValues;onChange: (next: ScheduleFormValues) => void;agentId: string;+ agentLabel: string;onAgentIdChange?: (agentId: string) => void;- agentOptions: Array<{ agentId: string; name: string }>;- agentOptionsLoaded?: boolean;+ onAgentPicked?: (agent: AgentLibraryEntry) => void;agentPickerDisabled?: boolean;onBuildAgent?: () => void;};@@ -44,9 +45,9 @@ export function ScheduleFormFields({values,onChange,agentId,+ agentLabel,onAgentIdChange,- agentOptions,- agentOptionsLoaded = true,+ onAgentPicked,agentPickerDisabled = false,onBuildAgent,}: ScheduleFormFieldsProps) {@@ -68,28 +69,15 @@ export function ScheduleFormFields({<div className="flex flex-col gap-4 px-5 py-4"><div className="block"><span className="mb-1.5 block text-sm font-medium">Agent</span>- <PopoverSelect+ <AgentSearchPickeraria-label="Agent"- placeholder="Select an agent"+ placeholder="Search agent"value={agentId}- options={agentOptions.map(agent => ({ value: agent.agentId, label: agent.name }))}+ selectedLabel={agentLabel}onValueChange={value => onAgentIdChange?.(value)}+ onAgentPicked={onAgentPicked}disabled={agentPickerDisabled || onAgentIdChange == null}- emptyContent={- agentOptionsLoaded ? (- <p className="text-text-secondary px-3 py-5 text-center text-sm">No Agents created yet</p>- ) : null- }- footer={- agentOptionsLoaded && agentOptions.length === 0 && onBuildAgent != null ? (- <div className="flex justify-end border-t border-border px-2 pt-2">- <Button.Ghost type="button" onClick={onBuildAgent}>- <Icon name="plus" className="size-3.5" />- Build Agent- </Button.Ghost>- </div>- ) : null- }+ onBuildAgent={onBuildAgent}/></div>diff --git a/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsx b/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsxindex a37157945..99d490c43 100644--- a/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsx+++ b/packages/trueforge-ui/src/atoms/schedules/SchedulesPage.tsx@@ -11,6 +11,7 @@ import type { Schedule, ScheduleRun, ScheduleStatus } from '../../server/types.jimport { useSlot } from '../../theme/SlotsProvider.js';import { hasCreatedBySubject } from '../../utils/createdBySubject.js';import { readScheduleShareSearch, replaceScheduleShareSearch } from '../../utils/scheduleShareUrl.js';+import { AgentSearchPicker } from '../AgentSearchPicker.js';import { CreatedByCell } from '../CreatedByCell.js';import { EmptyScreen } from '../EmptyScreen.js';import { auiButtonClass } from '../lib/buttonClasses.js';@@ -424,19 +425,18 @@ export function SchedulesPage({ agentId }: SchedulesPageProps) {aria-label="Filter by status"/>{agentId === undefined ? (- <PopoverSelect+ <AgentSearchPickervalue={agentFilter}+ selectedLabel={agentFilter === 'all' ? 'All agents' : (agentNameById.get(agentFilter) ?? agentFilter)}onValueChange={value => {setAgentFilter(value);setPageToken(undefined);setPrevTokenStack([]);}}- options={[- { value: 'all', label: 'All agents' },- ...agentOptions.map(agent => ({ value: agent.agentId, label: agent.name })),- ]}- className="sm:w-40"+ allOption={{ value: 'all', label: 'All agents' }}+ className="sm:w-48"aria-label="Filter by agent"+ placeholder="Search agent"/>) : null}<Button.Primarydiff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/agentsList.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/agentsList.tsnew file mode 100644index 000000000..eea191667--- /dev/null+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/agentsList.ts@@ -0,0 +1,54 @@+/**+ * Paginated helpers for `client.agents.list` (API default 50, max 100).+ */+import type { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk';++/** Matches API AGENTS_PAGE_DEFAULT / AGENTS_PAGE_LIMIT. */+export const AGENTS_PAGE_DEFAULT = 50;+export const AGENTS_PAGE_LIMIT = 100;++export function clampAgentsPageSize(size: number): number {+ return Math.min(Math.max(size, 1), AGENTS_PAGE_LIMIT);+}++/**+ * One page of agents. `offset` must be a multiple of `limit` (page-aligned);+ * advances via SDK `getNextPage` so we never invent page tokens.+ */+export async function listAgentsPage({+ client,+ limit,+ offset = 0,+ agentName,+}: {+ client: TrueForge;+ limit: number;+ offset?: number;+ agentName?: string;+}): Promise<TrueForgeApi.Agent[]> {+ const pageSize = clampAgentsPageSize(limit);+ const start = Math.max(0, offset);+ const page = await client.agents.list({+ limit: pageSize,+ ...(agentName === undefined ? {} : { agentName }),+ });+ let at = 0;+ while (at < start) {+ if (!page.hasNextPage()) return [];+ await page.getNextPage();+ at += pageSize;+ }+ return [...page.data];+}++/** Drain every agents page into one array (name lookups, indexes). */+export async function drainAgentsList(client: TrueForge): Promise<TrueForgeApi.Agent[]> {+ const items: TrueForgeApi.Agent[] = [];+ const page = await client.agents.list({ limit: AGENTS_PAGE_DEFAULT });+ for (;;) {+ items.push(...page.data);+ if (!page.hasNextPage()) break;+ await page.getNextPage();+ }+ return items;+}diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/builderServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/builderServer.tsindex c3a3d0ee9..bdeeb1435 100644--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/builderServer.ts+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/builderServer.ts@@ -4,6 +4,7 @@*/import type { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk';import type { AgentBuilderServer, AgentLibraryEntry, ModelSelection, SearchAgentsParams } from '../../server/types.js';+import { AGENTS_PAGE_DEFAULT, clampAgentsPageSize, drainAgentsList, listAgentsPage } from './agentsList.js';import { toUiConnectorFromReadEntry, toUiTool } from './catalogs/connectorCatalog.js';import { toHarnessAgentSpec, toUiAgentSpec } from './chatServer.js';import { createTrueForgeClient, type CreateTrueForgeClientOptions } from './client.js';@@ -120,21 +121,24 @@ export function createHarnessBuilderServer(},async searchAgents(req?: SearchAgentsParams) {- const { data } = await client.agents.list();- const query = req?.query?.trim().toLowerCase();- const filtered =- query === undefined || query === '' ? data : data.filter(agent => agent.name.toLowerCase().includes(query));+ const limit = clampAgentsPageSize(req?.limit ?? AGENTS_PAGE_DEFAULT);const offset = req?.offset ?? 0;- const limit = req?.limit ?? 50;- return filtered.slice(offset, offset + limit).map(toLibraryEntry);+ const query = req?.query?.trim();+ const rows = await listAgentsPage({+ client,+ limit,+ offset,+ ...(query === undefined || query === '' ? {} : { agentName: query }),+ });+ return rows.map(toLibraryEntry);},async saveAgent({ agentName, agentSpec, intent }) {// TODO: TrueForge currently drops AgentSpec.description until its schema supports it.const manifest = toHarnessAgentSpec(agentSpec);if (intent === 'update') {- const { data } = await client.agents.list();- const existing = data.find(agent => agent.name === agentName);+ const agents = await drainAgentsList(client);+ const existing = agents.find(agent => agent.name === agentName);if (!existing) {return {};}@@ -146,8 +150,8 @@ export function createHarnessBuilderServer(},async deleteAgent({ agentName }) {- const { data } = await client.agents.list();- const existing = data.find(agent => agent.name === agentName);+ const agents = await drainAgentsList(client);+ const existing = agents.find(agent => agent.name === agentName);if (!existing) return;await client.agents.delete(existing.id);},diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/schedules/scheduleServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/schedules/scheduleServer.tsindex d80d9ad49..5e38d2370 100644--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/schedules/scheduleServer.ts+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/schedules/scheduleServer.ts@@ -13,6 +13,7 @@ import type {ScheduleStatus,UpdateScheduleRequest,} from '../../../server/types.js';+import { drainAgentsList } from '../agentsList.js';import { toListResult } from '../chatServer.js';/** Matches API PAGE_LIMIT for schedules list. */@@ -24,10 +25,10 @@ type AgentIndex = {};async function loadAgentIndex(client: TrueForge): Promise<AgentIndex> {- const { data } = await client.agents.list();+ const agents = await drainAgentsList(client);const idToName = new Map<string, string>();const nameToId = new Map<string, string>();- for (const agent of data) {+ for (const agent of agents) {idToName.set(agent.id, agent.name);nameToId.set(agent.name, agent.id);}diff --git a/packages/trueforge-ui/test/atoms/AgentSearchPicker.test.tsx b/packages/trueforge-ui/test/atoms/AgentSearchPicker.test.tsxnew file mode 100644index 000000000..bd348b248--- /dev/null+++ b/packages/trueforge-ui/test/atoms/AgentSearchPicker.test.tsx@@ -0,0 +1,118 @@+// @vitest-environment jsdom+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { AgentSearchPicker } from '@/atoms/AgentSearchPicker.js';+import { ServerProvider } from '@/server/ServerContext.js';+import type { AgentUIServer } from '@/server/types.js';+import { SlotsProvider } from '@/theme/SlotsProvider.js';+import { createMockAgentUIServer } from '../server/mockServer.js';++function wrap(server: AgentUIServer) {+ return function Wrapper({ children }: { children: ReactNode }) {+ return (+ <SlotsProvider>+ <ServerProvider server={server}>{children}</ServerProvider>+ </SlotsProvider>+ );+ };+}++describe('AgentSearchPicker', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('searches on type and selects an agent', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const searchAgents = vi.fn(async ({ query }: { query?: string } = {}) => {+ const agents = [+ { name: 'alpha-bot', agentId: 'alpha-bot' },+ { name: 'beta-bot', agentId: 'beta-bot' },+ ];+ if (query == null || query === '') return agents;+ return agents.filter(agent => agent.name.includes(query));+ });+ const onValueChange = vi.fn();+ const onAgentPicked = vi.fn();++ render(+ <AgentSearchPicker value="" selectedLabel="" onValueChange={onValueChange} onAgentPicked={onAgentPicked} />,+ { wrapper: wrap(createMockAgentUIServer({ searchAgents })) },+ );++ const input = screen.getByRole('combobox', { name: 'Agent' });+ fireEvent.focus(input);+ await waitFor(() => expect(screen.getByRole('option', { name: 'alpha-bot' })).toBeInTheDocument());++ fireEvent.change(input, { 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-bot' })).toBeInTheDocument();+ });++ fireEvent.click(screen.getByRole('option', { name: 'beta-bot' }));+ expect(onValueChange).toHaveBeenCalledWith('beta-bot');+ expect(onAgentPicked).toHaveBeenCalledWith(expect.objectContaining({ name: 'beta-bot', agentId: 'beta-bot' }));+ });++ it('shows a load error instead of an empty catalog', async () => {+ const searchAgents = vi.fn(async () => {+ throw new Error('catalog unavailable');+ });++ render(<AgentSearchPicker value="" selectedLabel="" onValueChange={() => undefined} />, {+ wrapper: wrap(createMockAgentUIServer({ searchAgents })),+ });++ fireEvent.focus(screen.getByRole('combobox', { name: 'Agent' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('catalog unavailable');+ expect(screen.queryByText('No Agents created yet')).not.toBeInTheDocument();+ });++ it('offers an All option for filter use and clears it while searching', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const searchAgents = vi.fn(async ({ query }: { query?: string } = {}) => {+ const agents = [+ { name: 'alpha-bot', agentId: 'alpha-bot' },+ { name: 'beta-bot', agentId: 'beta-bot' },+ ];+ if (query == null || query === '') return agents;+ return agents.filter(agent => agent.name.includes(query));+ });+ const onValueChange = vi.fn();++ render(+ <AgentSearchPicker+ value="all"+ selectedLabel="All agents"+ onValueChange={onValueChange}+ allOption={{ value: 'all', label: 'All agents' }}+ aria-label="Filter by agent"+ />,+ { wrapper: wrap(createMockAgentUIServer({ searchAgents })) },+ );++ const input = screen.getByRole('combobox', { name: 'Filter by agent' });+ fireEvent.focus(input);+ expect(await screen.findByRole('option', { name: 'All agents' })).toBeInTheDocument();++ fireEvent.click(screen.getByRole('option', { name: 'alpha-bot' }));+ expect(onValueChange).toHaveBeenCalledWith('alpha-bot');++ fireEvent.focus(input);+ fireEvent.change(input, { target: { value: 'beta' } });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300);+ });+ await waitFor(() => {+ expect(screen.queryByRole('option', { name: 'All agents' })).not.toBeInTheDocument();+ expect(screen.getByRole('option', { name: 'beta-bot' })).toBeInTheDocument();+ });+ });+});diff --git a/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx b/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsxindex 3c28edcd6..7e9439da6 100644--- a/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentsLibrary.test.tsx@@ -604,6 +604,60 @@ describe('AgentsLibraryButton', () => {expect(await screen.findByRole('button', { name: 'Add schedule for alpha-agent' })).toBeInTheDocument();});+ it('disables next page when the current page is short', async () => {+ renderLibrary(<LibraryHarness />, { server: mockServer([{ name: 'alpha-agent', agentId: 'alpha-agent' }]) });+ fireEvent.click(screen.getByRole('button', { name: 'Open library' }));++ await screen.findByRole('button', { name: 'Try agent alpha-agent' });+ expect(screen.getByRole('button', { name: 'Next page' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Previous page' })).toBeDisabled();+ });++ it('paginates with next and previous and resets offset when page size changes', async () => {+ const all = Array.from({ length: 15 }, (_, i) => ({+ name: `agent-${String(i).padStart(2, '0')}`,+ agentId: `agent-${i}`,+ }));+ const searchAgents = vi.fn(async ({ limit = 10, offset = 0 }: { limit?: number; offset?: number } = {}) =>+ all.slice(offset, offset + limit),+ );+ const server = createMockAgentUIServer({ searchAgents });++ renderLibrary(<LibraryHarness />, { server });+ fireEvent.click(screen.getByRole('button', { name: 'Open library' }));++ await screen.findByRole('button', { name: 'Try agent agent-00' });+ expect(searchAgents).toHaveBeenLastCalledWith({ query: undefined, limit: 10, offset: 0 });+ expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled();+ expect(screen.getByRole('button', { name: 'Previous page' })).toBeDisabled();++ fireEvent.click(screen.getByRole('button', { name: 'Next page' }));+ await waitFor(() => {+ expect(searchAgents).toHaveBeenLastCalledWith({ query: undefined, limit: 10, offset: 10 });+ });+ await screen.findByRole('button', { name: 'Try agent agent-10' });+ expect(screen.getByRole('button', { name: 'Previous page' })).toBeEnabled();+ expect(screen.getByRole('button', { name: 'Next page' })).toBeDisabled();++ fireEvent.click(screen.getByRole('button', { name: 'Previous page' }));+ await waitFor(() => {+ expect(searchAgents).toHaveBeenLastCalledWith({ query: undefined, limit: 10, offset: 0 });+ });+ await screen.findByRole('button', { name: 'Try agent agent-00' });++ fireEvent.click(screen.getByRole('button', { name: 'Next page' }));+ await waitFor(() => {+ expect(searchAgents).toHaveBeenLastCalledWith({ query: undefined, limit: 10, offset: 10 });+ });++ // PopoverSelect: open rows-per-page and pick 25+ fireEvent.click(screen.getByRole('button', { name: 'Rows per page' }));+ fireEvent.click(await screen.findByRole('option', { name: '25' }));+ await waitFor(() => {+ expect(searchAgents).toHaveBeenLastCalledWith({ query: undefined, limit: 25, offset: 0 });+ });+ });+it('shows Created by when agents include createdBySubject', async () => {const server = mockServer([{diff --git a/packages/trueforge-ui/test/atoms/lib/useSearchAgentsList.test.tsx b/packages/trueforge-ui/test/atoms/lib/useSearchAgentsList.test.tsxindex 4d5ca0e96..5895aa8e3 100644--- a/packages/trueforge-ui/test/atoms/lib/useSearchAgentsList.test.tsx+++ b/packages/trueforge-ui/test/atoms/lib/useSearchAgentsList.test.tsx@@ -3,7 +3,12 @@ import { act, renderHook, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, describe, expect, it, vi } from 'vitest';-import { findAgentByName, SEARCH_AGENTS_PAGE_SIZE, useSearchAgentsList } from '@/atoms/lib/useSearchAgentsList.js';+import {+ findAgentByName,+ findLibraryAgent,+ SEARCH_AGENTS_PAGE_SIZE,+ useSearchAgentsList,+} from '@/atoms/lib/useSearchAgentsList.js';import { ServerProvider } from '@/server/ServerContext.js';import type { AgentLibraryEntry, AgentUIServer } from '@/server/types.js';import { createMockAgentUIServer } from '../../server/mockServer.js';@@ -42,6 +47,28 @@ describe('useSearchAgentsList', () => {});});+ it('finds an agent by id when name search would miss', async () => {+ const firstPage = Array.from({ length: SEARCH_AGENTS_PAGE_SIZE }, (_, index) => ({+ name: `other-${index}`,+ agentId: `id-${index}`,+ }));+ const searchAgents = vi+ .fn()+ .mockResolvedValueOnce(firstPage)+ .mockResolvedValueOnce([{ name: 'Demo Bot', agentId: 'agt_demo' }]);++ await expect(+ findLibraryAgent({+ server: createMockAgentUIServer({ searchAgents }),+ agentKey: 'agt_demo',+ }),+ ).resolves.toEqual({ name: 'Demo Bot', agentId: 'agt_demo' });+ expect(searchAgents).toHaveBeenLastCalledWith({+ limit: SEARCH_AGENTS_PAGE_SIZE,+ offset: SEARCH_AGENTS_PAGE_SIZE,+ });+ });+it('fetches the first page when enabled and paginates via loadMore sentinel', async () => {const page1 = Array.from({ length: SEARCH_AGENTS_PAGE_SIZE }, (_, i) => ({name: `agent-${i}`,@@ -135,4 +162,37 @@ describe('useSearchAgentsList', () => {expect(searchAgents).toHaveBeenLastCalledWith({ query: 'alpha', limit: SEARCH_AGENTS_PAGE_SIZE, offset: 0 });expect(result.current.agents).toEqual([{ name: 'alpha', agentId: 'alpha' } satisfies AgentLibraryEntry]);});++ it('paged mode replaces rows and navigates by offset', async () => {+ const page1 = Array.from({ length: 10 }, (_, i) => ({+ name: `agent-${i}`,+ agentId: `agent-${i}`,+ }));+ const page2 = [{ name: 'agent-10', agentId: 'agent-10' }];+ const searchAgents = vi.fn().mockResolvedValueOnce(page1).mockResolvedValueOnce(page2).mockResolvedValueOnce(page1);++ const server = createMockAgentUIServer({ searchAgents });+ const { result } = renderHook(() => useSearchAgentsList({ enabled: true, query: '', mode: 'paged', limit: 10 }), {+ wrapper: wrapperFor(server),+ });++ await waitFor(() => expect(result.current.agents).toHaveLength(10));+ expect(result.current.canNext).toBe(true);+ expect(result.current.canPrev).toBe(false);+ expect(searchAgents).toHaveBeenCalledWith({ query: undefined, limit: 10, offset: 0 });++ act(() => {+ result.current.goNext();+ });+ await waitFor(() => expect(result.current.agents).toEqual(page2));+ expect(searchAgents).toHaveBeenCalledWith({ query: undefined, limit: 10, offset: 10 });+ expect(result.current.canPrev).toBe(true);+ expect(result.current.canNext).toBe(false);++ act(() => {+ result.current.goPrev();+ });+ await waitFor(() => expect(result.current.agents).toHaveLength(10));+ expect(searchAgents).toHaveBeenLastCalledWith({ query: undefined, limit: 10, offset: 0 });+ });});diff --git a/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsx b/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsxindex 27480e681..8cca05502 100644--- a/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsx+++ b/packages/trueforge-ui/test/atoms/schedules/ScheduleFormDrawer.test.tsx@@ -154,12 +154,39 @@ describe('ScheduleFormDrawer', () => {const picker = await screen.findByLabelText('Agent');expect(picker).toBeInTheDocument();- fireEvent.click(picker);+ fireEvent.focus(picker);await waitFor(() => {expect(screen.getByRole('option', { name: 'demo-agent' })).toBeInTheDocument();});});+ it('filters agents when typing in the agent picker', async () => {+ const searchAgents = vi.fn(async ({ query }: { query?: string } = {}) => {+ const agents = [+ {+ name: 'demo-agent',+ agentId: 'demo-agent',+ agentSpec: { model: { name: 'openai/gpt-4.1' }, mcpServers: [{ name: 'Slack 1234' }] },+ },+ { name: 'other-agent', agentId: 'other-agent' },+ ];+ if (query == null || query === '') return agents;+ return agents.filter(agent => agent.name.toLowerCase().includes(query.toLowerCase()));+ });+ renderDrawer({ server: createMockAgentUIServer({ searchAgents }) });++ const picker = await screen.findByLabelText('Agent');+ fireEvent.focus(picker);+ await waitFor(() => expect(screen.getByRole('option', { name: 'demo-agent' })).toBeInTheDocument());++ fireEvent.change(picker, { target: { value: 'other' } });+ await waitFor(() => {+ expect(searchAgents).toHaveBeenCalledWith(expect.objectContaining({ query: 'other' }));+ expect(screen.getByRole('option', { name: 'other-agent' })).toBeInTheDocument();+ expect(screen.queryByRole('option', { name: 'demo-agent' })).not.toBeInTheDocument();+ });+ });+it('offers to build an agent when none have been created', async () => {const onOpenChange = vi.fn();renderDrawer({@@ -168,7 +195,7 @@ describe('ScheduleFormDrawer', () => {withShell: true,});- fireEvent.click(await screen.findByLabelText('Agent'));+ fireEvent.focus(await screen.findByLabelText('Agent'));expect(await screen.findByText('No Agents created yet')).toBeInTheDocument();fireEvent.click(screen.getByRole('button', { name: 'Build Agent' }));@@ -423,4 +450,84 @@ describe('ScheduleFormDrawer', () => {expect(onOpenChange).toHaveBeenCalledWith(false);expect(screen.queryByRole('heading', { name: 'Test Schedule' })).not.toBeInTheDocument();});++ it('prefills create from an agent id that differs from the name', async () => {+ const searchAgents = vi.fn(async (_opts: { query?: string; limit?: number; offset?: number } = {}) => [+ {+ name: 'Demo Bot',+ agentId: 'agt_demo',+ agentSpec: {+ model: { name: 'openai/gpt-4.1' },+ mcpServers: [{ name: 'Slack 1234' }],+ },+ },+ ]);+ renderDrawer({+ server: createMockAgentUIServer({+ searchAgents,+ getMcp: vi.fn(async () => [slackMcp]),+ catalog: createMockCatalog({+ connectorCatalog: {+ getConnectorCatalog: async () => [],+ listConnectors: async () => [slackCatalogConnector],+ getConnector: async () => slackCatalogConnector,+ getToolsByConnectorId: async () => [],+ createConnector: vi.fn(),+ updateConnector: vi.fn(),+ authenticateConnector: vi.fn(async () => ({ status: 'AUTHENTICATED' })),+ disconnectConnector: vi.fn(),+ },+ }),+ }),+ initialAgentId: 'agt_demo',+ });++ await waitFor(() => {+ expect(screen.getByRole('combobox', { name: 'Agent' })).toHaveValue('Demo Bot');+ });+ expect(searchAgents).toHaveBeenCalledWith(expect.objectContaining({ limit: expect.any(Number), offset: 0 }));+ expect(searchAgents.mock.calls.some(call => call[0]?.query != null)).toBe(false);+ });++ it('does not let a slow prefill overwrite a later agent pick', async () => {+ let resolvePrefill: (value: unknown) => void = () => undefined;+ const prefillPromise = new Promise(resolve => {+ resolvePrefill = resolve;+ });+ const searchAgents = vi.fn(async ({ query }: { query?: string } = {}) => {+ if (query == null || query === '') {+ await prefillPromise;+ return [+ {+ name: 'Prefill Bot',+ agentId: 'agt_prefill',+ agentSpec: { model: { name: 'openai/gpt-4.1' }, mcpServers: [] },+ },+ ];+ }+ return [+ {+ name: 'Picked Bot',+ agentId: 'agt_picked',+ agentSpec: { model: { name: 'openai/gpt-4.1' }, mcpServers: [] },+ },+ ];+ });++ renderDrawer({+ server: createMockAgentUIServer({ searchAgents }),+ initialAgentId: 'agt_prefill',+ });++ const picker = await screen.findByRole('combobox', { name: 'Agent' });+ fireEvent.focus(picker);+ fireEvent.change(picker, { target: { value: 'Picked' } });+ await waitFor(() => expect(screen.getByRole('option', { name: 'Picked Bot' })).toBeInTheDocument());+ fireEvent.click(screen.getByRole('option', { name: 'Picked Bot' }));+ expect(picker).toHaveValue('Picked Bot');++ resolvePrefill(undefined);+ await waitFor(() => expect(searchAgents).toHaveBeenCalled());+ expect(picker).toHaveValue('Picked Bot');+ });});diff --git a/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx b/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsxindex 12638af10..4daf4b537 100644--- a/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx+++ b/packages/trueforge-ui/test/atoms/schedules/SchedulesPage.test.tsx@@ -173,7 +173,7 @@ describe('SchedulesPage', () => {);});expect(screen.queryByRole('heading', { name: 'Scheduled Agents' })).not.toBeInTheDocument();- expect(screen.queryByRole('button', { name: 'Filter by agent' })).not.toBeInTheDocument();+ expect(screen.queryByRole('combobox', { name: 'Filter by agent' })).not.toBeInTheDocument();});it('shows empty state when there are no schedules', async () => {@@ -246,8 +246,8 @@ describe('SchedulesPage', () => {const { scheduleServer } = renderPage();await screen.findByText('daily-digest');- fireEvent.click(screen.getByRole('button', { name: 'Filter by agent' }));- fireEvent.click(screen.getByRole('option', { name: 'demo-agent' }));+ fireEvent.focus(screen.getByRole('combobox', { name: 'Filter by agent' }));+ fireEvent.click(await screen.findByRole('option', { name: 'demo-agent' }));await waitFor(() => {expect(scheduleServer.listSchedules).toHaveBeenCalledWith(@@ -426,19 +426,41 @@ describe('SchedulesPage', () => {expect(screen.getByRole('button', { name: 'Next page' })).toBeEnabled();});- it('loads every page of agents for the filter', async () => {- const agents = 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));+ it('searches agents in the filter', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const agents = [+ { agentId: 'alpha-agent', name: 'alpha-agent' },+ { agentId: 'beta-agent', name: 'beta-agent' },+ ];+ const searchAgents = vi.fn(+ async ({ query, limit = 50, offset = 0 }: { query?: string; limit?: number; offset?: number } = {}) => {+ const matched =+ query == null || query === ''+ ? agents+ : agents.filter(agent => agent.name.toLowerCase().includes(query.toLowerCase()));+ return matched.slice(offset, offset + limit);+ },+ );renderPage(sampleSchedules, {}, undefined, searchAgents);+ await screen.findByText('daily-digest');++ const filter = screen.getByRole('combobox', { name: 'Filter by agent' });+ fireEvent.focus(filter);+ expect(await screen.findByRole('option', { name: 'All agents' })).toBeInTheDocument();+ expect(screen.getByRole('option', { name: 'alpha-agent' })).toBeInTheDocument();++ fireEvent.change(filter, { target: { value: 'beta' } });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300);+ });await waitFor(() => {- expect(searchAgents).toHaveBeenCalledTimes(2);+ expect(searchAgents).toHaveBeenCalledWith(expect.objectContaining({ query: 'beta' }));+ expect(screen.getByRole('option', { name: 'beta-agent' })).toBeInTheDocument();+ expect(screen.queryByRole('option', { name: 'All agents' })).not.toBeInTheDocument();+ expect(screen.queryByRole('option', { name: 'alpha-agent' })).not.toBeInTheDocument();});- fireEvent.click(await screen.findByRole('button', { name: 'Filter by agent' }));- expect(screen.getByRole('option', { name: 'Agent 51' })).toBeInTheDocument();+ vi.useRealTimers();});it('opens the create drawer from isNew=true then clears the flag', async () => {diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessBuilderServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessBuilderServer.test.tsindex ce1a8d630..39875b156 100644--- a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessBuilderServer.test.ts+++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/harnessBuilderServer.test.ts@@ -7,6 +7,10 @@ import {toModelSelection,} from '@/plugins/trueforge-agent-server-adapter/builderServer.js';+function isAgentsCollectionUrl(url: string): boolean {+ return new URL(url).pathname.endsWith('/api/v1/agents');+}+describe('harnessBuilderServer', () => {it('modelProviderLogosByName maps well-known catalog logos by type', () => {const logos = modelProviderLogosByName([@@ -292,28 +296,35 @@ describe('harnessBuilderServer', () => {});it('searchAgents maps registry rows to library entries with agentId + agentSpec', async () => {+ const requestedAgentNames: Array<string | null> = [];const fetchMock: typeof fetch = async input => {const url = input instanceof Request ? input.url : String(input);- if (url.endsWith('/api/v1/agents')) {+ if (isAgentsCollectionUrl(url)) {+ const agentName = new URL(url).searchParams.get('agent_name');+ requestedAgentNames.push(agentName);return Response.json({- data: [- {- id: 'agt_1',- name: 'reviewer',- created_by_subject: {- subject_id: 'user-1',- subject_type: 'user',- subject_display_name: 'Alice',- },- manifest: {- model: { name: 'test/model' },- instructions: 'Review carefully.',- skills: [{ name: 'review' }],- mcp_servers: [{ name: 'github', enable_tools: ['@all'] }],- },- },- { id: 'agt_2', name: 'writer', manifest: { model: { name: 'test/model' } } },- ],+ data:+ agentName === 'write'+ ? [{ id: 'agt_2', name: 'writer', manifest: { model: { name: 'test/model' } } }]+ : [+ {+ id: 'agt_1',+ name: 'reviewer',+ created_by_subject: {+ subject_id: 'user-1',+ subject_type: 'user',+ subject_display_name: 'Alice',+ },+ manifest: {+ model: { name: 'test/model' },+ instructions: 'Review carefully.',+ skills: [{ name: 'review' }],+ mcp_servers: [{ name: 'github', enable_tools: ['@all'] }],+ },+ },+ { id: 'agt_2', name: 'writer', manifest: { model: { name: 'test/model' } } },+ ],+ pagination: { limit: 25 },});}return new Response(`Unexpected request: ${url}`, { status: 500 });@@ -338,11 +349,64 @@ describe('harnessBuilderServer', () => {},});- const filtered = await builder.searchAgents({ query: 'write' });+ const filtered = await builder.searchAgents({ query: ' write ' });assert.deepEqual(filtered.map(row => row.name),['writer'],);+ assert.deepEqual(requestedAgentNames, [null, 'write']);+ });++ it('searchAgents advances offset via page_token on a later API page', async () => {+ const fetchMock: typeof fetch = async input => {+ const url = String(input instanceof Request ? input.url : input);+ const parsed = new URL(url);+ if (!parsed.pathname.endsWith('/api/v1/agents')) {+ return new Response(`Unexpected request: ${url}`, { status: 500 });+ }+ const agentName = parsed.searchParams.get('agent_name');+ if (agentName !== 'a') {+ return new Response(`Unexpected agent_name: ${String(agentName)}`, { status: 500 });+ }+ const pageToken = parsed.searchParams.get('page_token');+ if (pageToken == null || pageToken === '') {+ return Response.json({+ data: [{ id: 'agt_1', name: 'alpha', manifest: { model: { name: 'test/model' } } }],+ pagination: { limit: 1, next_page_token: 'tok_2' },+ });+ }+ if (pageToken === 'tok_2') {+ return Response.json({+ data: [{ id: 'agt_2', name: 'beta', manifest: { model: { name: 'test/model' } } }],+ pagination: { limit: 1 },+ });+ }+ return new Response(`Unexpected page_token: ${pageToken}`, { status: 500 });+ };++ const builder = createHarnessBuilderServer({ fetch: fetchMock });+ const page = await builder.searchAgents({ query: 'a', limit: 1, offset: 1 });+ assert.deepEqual(+ page.map(row => row.name),+ ['beta'],+ );+ });++ it('searchAgents caps limit at 100', async () => {+ const urls: string[] = [];+ const fetchMock: typeof fetch = async input => {+ const url = String(input instanceof Request ? input.url : input);+ urls.push(url);+ if (isAgentsCollectionUrl(url)) {+ return Response.json({ data: [], pagination: { limit: 100 } });+ }+ return new Response(`Unexpected request: ${url}`, { status: 500 });+ };++ const builder = createHarnessBuilderServer({ fetch: fetchMock });+ await builder.searchAgents({ limit: 200 });+ const parsed = new URL(urls[0] ?? '');+ assert.equal(parsed.searchParams.get('limit'), '100');});it('saveAgent creates when the name is new', async () => {@@ -388,9 +452,10 @@ describe('harnessBuilderServer', () => {const fetchMock: typeof fetch = async (input, init) => {const url = input instanceof Request ? input.url : String(input);const method = init?.method ?? 'GET';- if (url.endsWith('/api/v1/agents') && method === 'GET') {+ if (isAgentsCollectionUrl(url) && method === 'GET') {return Response.json({data: [{ id: 'agt_1', name: 'writer', manifest: { model: { name: 'test/model' } } }],+ pagination: { limit: 25 },});}if (url.endsWith('/api/v1/agents/agt_1') && method === 'PUT' && typeof init?.body === 'string') {@@ -435,9 +500,10 @@ describe('harnessBuilderServer', () => {const url = input instanceof Request ? input.url : String(input);const method = init?.method ?? 'GET';requests.push({ method, url });- if (url.endsWith('/api/v1/agents') && method === 'GET') {+ if (isAgentsCollectionUrl(url) && method === 'GET') {return Response.json({data: [{ id: 'agt_1', name: 'writer', manifest: { model: { name: 'test/model' } } }],+ pagination: { limit: 25 },});}if (url.endsWith('/api/v1/agents/agt_1') && method === 'DELETE') {@@ -461,8 +527,8 @@ describe('harnessBuilderServer', () => {const url = input instanceof Request ? input.url : String(input);const method = init?.method ?? 'GET';requests.push({ method, url });- if (url.endsWith('/api/v1/agents') && method === 'GET') {- return Response.json({ data: [] });+ if (isAgentsCollectionUrl(url) && method === 'GET') {+ return Response.json({ data: [], pagination: { limit: 25 } });}return new Response(`Unexpected request: ${method} ${url}`, { status: 500 });};diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/scheduleServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/scheduleServer.test.tsindex a04a45bb5..fc2d0e884 100644--- a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/scheduleServer.test.ts+++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/scheduleServer.test.ts@@ -45,7 +45,12 @@ function mockClient(return {agents: {- list: vi.fn(async () => ({ data: agents })),+ list: vi.fn(async () => ({+ data: agents,+ response: { pagination: { limit: 25 } },+ hasNextPage: () => false,+ getNextPage: async () => undefined,+ })),},schedules: {list,diff --git a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsxindex 14ebacf7f..a17b601ca 100644--- a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx+++ b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx@@ -76,7 +76,8 @@ function SettingsCatalogProvider({createdAt: '2026-01-01T00:00:00Z',updatedAt: '2026-01-01T00:00:00Z',}),- searchAgents: async req => (req?.query === 'helper' ? [{ name: 'helper', agentId: 'helper-id' }] : []),+ // findAgentByName walks unfiltered pages and matches by exact name client-side.+ searchAgents: async () => [{ name: 'helper', agentId: 'helper-id' }],});return <ServerProvider server={server}>{children}</ServerProvider>;}diff --git a/packages/trueforge/src/apis/agentAccess.ts b/packages/trueforge/src/apis/agentAccess.tsindex 22a94311f..84e7adba2 100644--- a/packages/trueforge/src/apis/agentAccess.ts+++ b/packages/trueforge/src/apis/agentAccess.ts@@ -3,6 +3,7 @@* and schedule handlers. Lives in the API layer because stores must stay free* of request identity.*/+import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';import type { AgentAction, Authorizer } from '../auth/authorizer';import type { RequestContext } from '../auth/identity';import type { AgentRecord, IAgentStore } from '../db/agentStore';@@ -31,14 +32,25 @@ export async function listAccessibleAgents<TTransaction>(input: {context: RequestContext;authorizer: Authorizer;action: AgentAction;-}): Promise<AgentRecord[]> {+ agent_name: string | undefined;+ limit: number | undefined;+ page_token: string | undefined;+}): Promise<{ data: AgentRecord[]; pagination: TokenPagination }> {const access = await input.authorizer.listAgentAccess({ context: input.context, action: input.action });if (access.kind === 'all') {- return input.store.listAgents({ tenant_id: input.context.tenant_id });+ return input.store.listAgents({+ tenant_id: input.context.tenant_id,+ agent_name: input.agent_name,+ limit: input.limit,+ page_token: input.page_token,+ });}return input.store.listAgents({tenant_id: input.context.tenant_id,external_ids: access.agent_external_ids,+ agent_name: input.agent_name,+ limit: input.limit,+ page_token: input.page_token,});}@@ -56,11 +68,14 @@ export async function resolveManagedAgentIds<TTransaction>(input: {if (access.kind === 'all') {return [];}- const agents = await store.listAgents({+ const { data } = await store.listAgents({tenant_id: context.tenant_id,external_ids: access.agent_external_ids,+ agent_name: undefined,+ limit: undefined,+ page_token: undefined,});- return agents.map(agent => agent.id);+ return data.map(agent => agent.id);}/** Related rows are readable by their creator or a manager of the bound named agent. */diff --git a/packages/trueforge/src/apis/agents.ts b/packages/trueforge/src/apis/agents.tsindex 80f3a5bcb..836ac021b 100644--- a/packages/trueforge/src/apis/agents.ts+++ b/packages/trueforge/src/apis/agents.ts@@ -2,7 +2,7 @@* DB-backed agent registry API (mounted at /api/v1/agents).*/import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';-import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';+import { InvalidPageTokenError, type AgentSpec } from '@truefoundry/trueforge-core/agent-session';import type { Context } from 'hono';import type { Authorizer } from '../auth/authorizer';import { createdBySubjectFromRequestContext, type ResolveRequestContext } from '../auth/identity';@@ -81,14 +81,25 @@ async function validateManifest<TTransaction>({export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransaction>) {const listHandler: RouteHandler<typeof listAgentsRoute> = async c => {+ const { limit, page_token: pageToken, agent_name: agentName } = c.req.valid('query');const requestContext = deps.resolveRequestContext(c);- const records = await listAccessibleAgents({- store: deps.resolveAgentStore(c),- context: requestContext,- authorizer: deps.authorizer,- action: 'read',- });- return c.json({ data: records.map(toWireAgent) }, 200);+ try {+ const { data, pagination } = await listAccessibleAgents({+ store: deps.resolveAgentStore(c),+ context: requestContext,+ authorizer: deps.authorizer,+ action: 'read',+ agent_name: agentName,+ limit,+ page_token: pageToken,+ });+ return c.json({ data: data.map(toWireAgent), pagination }, 200);+ } catch (error) {+ if (error instanceof InvalidPageTokenError) {+ return c.json({ error: { message: error.message } }, 400);+ }+ throw error;+ }};const createHandler: RouteHandler<typeof createAgentRoute> = async c => {diff --git a/packages/trueforge/src/db/agentStore.ts b/packages/trueforge/src/db/agentStore.tsindex 51f81d8af..c796fc9bc 100644--- a/packages/trueforge/src/db/agentStore.ts+++ b/packages/trueforge/src/db/agentStore.ts@@ -4,7 +4,12 @@* `AgentSpec` jsonb document.* Implementations: PostgresAgentStore and SqliteAgentStore.*/-import { AgentSpecSchema, type AgentSpec, type CreatedBySubject } from '@truefoundry/trueforge-core/agent-session';+import {+ AgentSpecSchema,+ type AgentSpec,+ type CreatedBySubject,+ type TokenPagination,+} from '@truefoundry/trueforge-core/agent-session';import type { ResourceName } from '../schemas/common';export interface AgentRecord {@@ -35,6 +40,11 @@ export interface ListAgentsInput {tenant_id: string;/** When set, only agents whose `external_id` is in this list. */external_ids?: readonly string[];+ /** Case-insensitive substring match on `name`. */+ agent_name: string | undefined;+ /** When undefined, return the full matching set (no SQL LIMIT). */+ limit: number | undefined;+ page_token: string | undefined;}export interface GetOwnedIdsInput {@@ -104,7 +114,10 @@ export class AgentExternalIdConflictError extends Error {}export interface IAgentStore<TTransaction = never> {- listAgents(input: ListAgentsInput, transaction?: TTransaction): Promise<AgentRecord[]>;+ listAgents(+ input: ListAgentsInput,+ transaction?: TTransaction,+ ): Promise<{ data: AgentRecord[]; pagination: TokenPagination }>;/** Ids among `ids` owned by `subject_id`. Empty `ids` → `[]`. */getOwnedIds(input: GetOwnedIdsInput, transaction?: TTransaction): Promise<readonly string[]>;/** Agents with a non-null `external_id` among `ids`. Empty `ids` → `[]`. */diff --git a/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts b/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.tsindex 6f0ab7056..02faf8ff9 100644--- a/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts+++ b/packages/trueforge/src/db/postgres/agent-store/PostgresAgentStore.ts@@ -1,4 +1,8 @@-import { CreatedBySubjectSchema } from '@truefoundry/trueforge-core/agent-session';+import { CreatedBySubjectSchema, type TokenPagination } from '@truefoundry/trueforge-core/agent-session';+import {+ decodeOffsetPageToken,+ paginateOffsetRows,+} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';import { sql, type Kysely, type Selectable, type Transaction } from 'kysely';import { newId } from '../../../utils/id';import {@@ -59,17 +63,34 @@ export class PostgresAgentStore implements IAgentStore<Transaction<Database>> {this.#db = db;}- async listAgents(input: ListAgentsInput, transaction?: Transaction<Database>): Promise<AgentRecord[]> {+ async listAgents(+ input: ListAgentsInput,+ transaction?: Transaction<Database>,+ ): Promise<{ data: AgentRecord[]; pagination: TokenPagination }> {if (input.external_ids?.length === 0) {- return [];+ return { data: [], pagination: { limit: input.limit ?? 0 } };}const db = transaction ?? this.#db;let query = db.selectFrom('agent').selectAll().where('tenant_id', '=', input.tenant_id);if (input.external_ids !== undefined) {query = query.where('external_id', 'in', [...input.external_ids]);}- const rows = await query.orderBy('name').execute();- return rows.map(toRecord);+ if (input.agent_name !== undefined) {+ query = query.where(sql<boolean>`position(lower(${input.agent_name}) in lower(name)) > 0`);+ }+ query = query.orderBy('name');+ if (input.limit === undefined) {+ const rows = await query.execute();+ const data = rows.map(toRecord);+ return { data, pagination: { limit: data.length } };+ }+ const offset = decodeOffsetPageToken(input.page_token);+ const rows = await query+ .limit(input.limit + 1)+ .offset(offset)+ .execute();+ const { data, pagination } = paginateOffsetRows(rows, input.limit, offset);+ return { data: data.map(toRecord), pagination };}async getOwnedIds(input: GetOwnedIdsInput, transaction?: Transaction<Database>): Promise<readonly string[]> {diff --git a/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts b/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.tsindex 80487cf54..bfbad492a 100644--- a/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts+++ b/packages/trueforge/src/db/sqlite/agent-store/SqliteAgentStore.ts@@ -2,7 +2,12 @@ import {CreatedBySubjectSchema,type AgentSpec,type CreatedBySubject,+ type TokenPagination,} from '@truefoundry/trueforge-core/agent-session';+import {+ decodeOffsetPageToken,+ paginateOffsetRows,+} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';import { sql, type ExpressionBuilder, type Kysely, type Transaction } from 'kysely';import { newId } from '../../../utils/id';import {@@ -62,17 +67,34 @@ export class SqliteAgentStore implements IAgentStore<Transaction<Database>> {this.#db = db;}- async listAgents(input: ListAgentsInput, transaction?: Transaction<Database>): Promise<AgentRecord[]> {+ async listAgents(+ input: ListAgentsInput,+ transaction?: Transaction<Database>,+ ): Promise<{ data: AgentRecord[]; pagination: TokenPagination }> {if (input.external_ids?.length === 0) {- return [];+ return { data: [], pagination: { limit: input.limit ?? 0 } };}const db = transaction ?? this.#db;let query = db.selectFrom('agent').select(recordColumns).where('tenant_id', '=', input.tenant_id);if (input.external_ids !== undefined) {query = query.where('external_id', 'in', [...input.external_ids]);}- const rows = await query.orderBy('name').execute();- return rows.map(toRecord);+ if (input.agent_name !== undefined) {+ query = query.where(sql<boolean>`instr(lower(name), lower(${input.agent_name})) > 0`);+ }+ query = query.orderBy('name');+ if (input.limit === undefined) {+ const rows = await query.execute();+ const data = rows.map(toRecord);+ return { data, pagination: { limit: data.length } };+ }+ const offset = decodeOffsetPageToken(input.page_token);+ const rows = await query+ .limit(input.limit + 1)+ .offset(offset)+ .execute();+ const { data, pagination } = paginateOffsetRows(rows, input.limit, offset);+ return { data: data.map(toRecord), pagination };}async getOwnedIds(input: GetOwnedIdsInput, transaction?: Transaction<Database>): Promise<readonly string[]> {diff --git a/packages/trueforge/src/routes/agentRoutes.ts b/packages/trueforge/src/routes/agentRoutes.tsindex 998b88b58..cac16e525 100644--- a/packages/trueforge/src/routes/agentRoutes.ts+++ b/packages/trueforge/src/routes/agentRoutes.ts@@ -12,25 +12,50 @@ import {ListAgentsResponseSchema,UpdateAgentRequestSchema,} from '../schemas/agent';+import { AGENTS_PAGE_DEFAULT, AGENTS_PAGE_LIMIT } from '../schemas/common';import { RequestErrorResponseSchema } from '../schemas/errors';+import { TOKEN_PAGINATION } from './fernExtensions';import { OpenApiTag } from './openapiTags';export const AgentIdParamsSchema = z.object({agent_id: z.string().min(1).max(64).describe('Immutable agent identifier.'),});+export const ListAgentsQuerySchema = z+ .object({+ limit: z.coerce+ .number()+ .int()+ .min(1)+ .max(AGENTS_PAGE_LIMIT)+ .optional()+ .default(AGENTS_PAGE_DEFAULT)+ .describe(`Page size. Defaults to ${String(AGENTS_PAGE_DEFAULT)}, max ${String(AGENTS_PAGE_LIMIT)}.`),+ page_token: z.string().optional().describe('Opaque token from a previous response `next_page_token`.'),+ agent_name: z.string().trim().min(1).optional().describe('Case-insensitive substring match on agent name.'),+ })+ .openapi('ListAgentsQuery');+export const listAgentsRoute = createRoute({method: 'get',path: '/',tags: [OpenApiTag.AGENTS],summary: 'List agents',- description: 'All configured agents for the tenant.',+ description: 'List configured agents for the tenant, ordered by name. Optional `agent_name` filters by substring.','x-fern-sdk-group-name': ['agents'],'x-fern-sdk-method-name': 'list',+ 'x-fern-pagination': TOKEN_PAGINATION,+ request: {+ query: ListAgentsQuerySchema,+ },responses: {200: {content: { 'application/json': { schema: ListAgentsResponseSchema } },- description: 'All configured agents.',+ description: 'Paginated matching agents.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid query parameters or page token.',},401: {content: { 'application/json': { schema: RequestErrorResponseSchema } },diff --git a/packages/trueforge/src/schemas/agent.ts b/packages/trueforge/src/schemas/agent.tsindex 84ba3be7c..122e65fa4 100644--- a/packages/trueforge/src/schemas/agent.ts+++ b/packages/trueforge/src/schemas/agent.ts@@ -3,7 +3,11 @@* AgentSpec document (JSON key `manifest`).*/import { z } from '@hono/zod-openapi';-import { AgentSpecSchema, CreatedBySubjectSchema } from '@truefoundry/trueforge-core/agent-session';+import {+ AgentSpecSchema,+ CreatedBySubjectSchema,+ TokenPaginationSchema,+} from '@truefoundry/trueforge-core/agent-session';import { NameSchema } from './common';const RESERVED_AGENT_NAMES = new Set(['tfg', 'trueforge']);@@ -39,7 +43,12 @@ export const AgentSchema = z.openapi('Agent');export const GetAgentResponseSchema = z.object({ data: AgentSchema }).openapi('GetAgentResponse');-export const ListAgentsResponseSchema = z.object({ data: z.array(AgentSchema) }).openapi('ListAgentsResponse');+export const ListAgentsResponseSchema = z+ .object({+ data: z.array(AgentSchema),+ pagination: TokenPaginationSchema,+ })+ .openapi('ListAgentsResponse');export const DeleteAgentResponseSchema = z.object({}).openapi('DeleteAgentResponse');export const AgentCodeSnippetSampleCodeSchema = zdiff --git a/packages/trueforge/src/schemas/common.ts b/packages/trueforge/src/schemas/common.tsindex d96e14a65..0c78868d8 100644--- a/packages/trueforge/src/schemas/common.ts+++ b/packages/trueforge/src/schemas/common.ts@@ -22,6 +22,9 @@ export type ResourceName = z.infer<typeof NameSchema>;export const PAGE_LIMIT = 25;/** Session/turn event list page size (default = max). */export const EVENTS_PAGE_LIMIT = 100;+/** List-agents page size. */+export const AGENTS_PAGE_DEFAULT = 50;+export const AGENTS_PAGE_LIMIT = 100;/** Adds a validation issue if two entries share a name. */export function uniqueNames(entries: { name: string }[], ctx: z.RefinementCtx): void {diff --git a/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.tsindex d237ee568..4c9bfe819 100644--- a/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundryAgentStore.ts@@ -1,4 +1,4 @@-import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';+import type { AgentSpec, TokenPagination } from '@truefoundry/trueforge-core/agent-session';import { sql, type Kysely, type Transaction } from 'kysely';import type { RequestContext } from '../auth/identity';import {@@ -86,7 +86,10 @@ export class TrueFoundryAgentStore implements IAgentStore<Transaction<Database>>this.#db = input.db;}- listAgents(input: ListAgentsInput, transaction?: Transaction<Database>): Promise<AgentRecord[]> {+ listAgents(+ input: ListAgentsInput,+ transaction?: Transaction<Database>,+ ): Promise<{ data: AgentRecord[]; pagination: TokenPagination }> {return this.#inner.listAgents(input, transaction);}diff --git a/packages/trueforge/tests/db/agentStoreContractSuite.ts b/packages/trueforge/tests/db/agentStoreContractSuite.tsindex 2d26f7693..e123b80f1 100644--- a/packages/trueforge/tests/db/agentStoreContractSuite.ts+++ b/packages/trueforge/tests/db/agentStoreContractSuite.ts@@ -146,9 +146,14 @@ export function runAgentStoreContractSuite(getStore: () => IAgentStore): void {external_id: null,});- const agents = await store.listAgents({ tenant_id: TENANT });- expect(agents.map(agent => agent.name)).toEqual(['alpha', 'zeta']);- expect(agents.every(agent => agent.tenant_id === TENANT)).toBe(true);+ const agents = await store.listAgents({+ tenant_id: TENANT,+ agent_name: undefined,+ limit: undefined,+ page_token: undefined,+ });+ expect(agents.data.map(agent => agent.name)).toEqual(['alpha', 'zeta']);+ expect(agents.data.every(agent => agent.tenant_id === TENANT)).toBe(true);});it('listAgents can filter by external_ids', async () => {@@ -175,14 +180,130 @@ export function runAgentStoreContractSuite(getStore: () => IAgentStore): void {external_id: 'sf-agent-2',});- expect(await store.listAgents({ tenant_id: TENANT, external_ids: ['sf-agent-1'] })).toEqual([linked]);expect(- (await store.listAgents({ tenant_id: TENANT, external_ids: ['sf-agent-1', 'sf-agent-2'] })).map(- agent => agent.name,- ),+ await store.listAgents({+ tenant_id: TENANT,+ external_ids: ['sf-agent-1'],+ agent_name: undefined,+ limit: undefined,+ page_token: undefined,+ }),+ ).toEqual({ data: [linked], pagination: { limit: 1 } });+ expect(+ (+ await store.listAgents({+ tenant_id: TENANT,+ external_ids: ['sf-agent-1', 'sf-agent-2'],+ agent_name: undefined,+ limit: undefined,+ page_token: undefined,+ })+ ).data.map(agent => agent.name),).toEqual(['linked', 'other-linked']);- expect(await store.listAgents({ tenant_id: TENANT, external_ids: ['missing'] })).toEqual([]);- expect(await store.listAgents({ tenant_id: TENANT, external_ids: [] })).toEqual([]);+ expect(+ await store.listAgents({+ tenant_id: TENANT,+ external_ids: ['missing'],+ agent_name: undefined,+ limit: undefined,+ page_token: undefined,+ }),+ ).toEqual({ data: [], pagination: { limit: 0 } });+ expect(+ await store.listAgents({+ tenant_id: TENANT,+ external_ids: [],+ agent_name: undefined,+ limit: undefined,+ page_token: undefined,+ }),+ ).toEqual({ data: [], pagination: { limit: 0 } });+ });++ it('listAgents filters by agent_name substring case-insensitively', async () => {+ const store = getStore();+ await store.createAgent({+ tenant_id: TENANT,+ created_by_subject: CREATED_BY_SUBJECT,+ name: 'alpha-bot',+ manifest: manifest(),+ external_id: null,+ });+ await store.createAgent({+ tenant_id: TENANT,+ created_by_subject: CREATED_BY_SUBJECT,+ name: 'bravo-bot',+ manifest: manifest(),+ external_id: null,+ });+ await store.createAgent({+ tenant_id: TENANT,+ created_by_subject: CREATED_BY_SUBJECT,+ name: 'unrelated',+ manifest: manifest(),+ external_id: null,+ });++ const matched = await store.listAgents({+ tenant_id: TENANT,+ agent_name: 'BOT',+ limit: undefined,+ page_token: undefined,+ });+ expect(matched.data.map(agent => agent.name)).toEqual(['alpha-bot', 'bravo-bot']);++ const none = await store.listAgents({+ tenant_id: TENANT,+ agent_name: 'missing',+ limit: undefined,+ page_token: undefined,+ });+ expect(none.data).toEqual([]);+ });++ it('listAgents paginates with limit and page_token in name order', async () => {+ const store = getStore();+ await store.createAgent({+ tenant_id: TENANT,+ created_by_subject: CREATED_BY_SUBJECT,+ name: 'charlie',+ manifest: manifest(),+ external_id: null,+ });+ await store.createAgent({+ tenant_id: TENANT,+ created_by_subject: CREATED_BY_SUBJECT,+ name: 'alpha',+ manifest: manifest(),+ external_id: null,+ });+ await store.createAgent({+ tenant_id: TENANT,+ created_by_subject: CREATED_BY_SUBJECT,+ name: 'bravo',+ manifest: manifest(),+ external_id: null,+ });++ const page1 = await store.listAgents({+ tenant_id: TENANT,+ agent_name: undefined,+ limit: 2,+ page_token: undefined,+ });+ expect(page1.data.map(agent => agent.name)).toEqual(['alpha', 'bravo']);+ expect(page1.pagination.limit).toBe(2);+ expect(page1.pagination.next_page_token).toEqual(expect.any(String));++ const page2 = await store.listAgents({+ tenant_id: TENANT,+ agent_name: undefined,+ limit: 2,+ page_token: page1.pagination.next_page_token,+ });+ expect(page2.data.map(agent => agent.name)).toEqual(['charlie']);+ expect(page2.pagination.previous_page_token).toEqual(expect.any(String));+ expect(page2.pagination.next_page_token).toBeUndefined();});it('getAgent by id is tenant-scoped', async () => {diff --git a/packages/trueforge/tests/unit/apis/agents.test.ts b/packages/trueforge/tests/unit/apis/agents.test.tsindex d527d4ca3..edf2ca0f7 100644--- a/packages/trueforge/tests/unit/apis/agents.test.ts+++ b/packages/trueforge/tests/unit/apis/agents.test.ts@@ -9,6 +9,7 @@ import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/Sqimport { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';+import { ListAgentsResponseSchema } from '../../../src/schemas/agent';const modelProvider = {type: 'anthropic' as const,@@ -243,7 +244,10 @@ describe('agents router', () => {const listed = await deniedRouter.request('/');expect(listed.status).toBe(200);- expect(((await listed.json()) as { data: WireAgent[] }).data).toEqual([]);+ expect(ListAgentsResponseSchema.parse(await listed.json())).toEqual({+ data: [],+ pagination: { limit: 50 },+ });expect((await deniedRouter.request(`/${data.id}`)).status).toBe(404);expect((await deniedRouter.request(`/${data.id}/code-snippets`)).status).toBe(404);@@ -258,4 +262,54 @@ describe('agents router', () => {'delete',]);});++ it('lists agents with pagination envelope and rejects an invalid page_token', async () => {+ const charlie = await router.request('/', jsonInit('POST', { ...writeBody, name: 'aaa-list-charlie' }));+ const alpha = await router.request('/', jsonInit('POST', { ...writeBody, name: 'aaa-list-alpha' }));+ const bravo = await router.request('/', jsonInit('POST', { ...writeBody, name: 'aaa-list-bravo' }));+ expect(charlie.status).toBe(201);+ expect(alpha.status).toBe(201);+ expect(bravo.status).toBe(201);++ const first = await router.request('/?limit=2');+ expect(first.status).toBe(200);+ const firstBody = ListAgentsResponseSchema.parse(await first.json());+ expect(firstBody.data.map(agent => agent.name)).toEqual(['aaa-list-alpha', 'aaa-list-bravo']);+ expect(firstBody.pagination.limit).toBe(2);+ expect(firstBody.pagination.next_page_token).toEqual(expect.any(String));++ const second = await router.request(+ `/?limit=2&page_token=${encodeURIComponent(firstBody.pagination.next_page_token ?? '')}`,+ );+ expect(second.status).toBe(200);+ const secondBody = ListAgentsResponseSchema.parse(await second.json());+ expect(secondBody.data[0]?.name).toBe('aaa-list-charlie');+ expect(secondBody.pagination.previous_page_token).toEqual(expect.any(String));++ const badToken = await router.request('/?page_token=not-a-token');+ expect(badToken.status).toBe(400);+ });++ it('lists agents filtered by agent_name substring case-insensitively', async () => {+ const alpha = await router.request('/', jsonInit('POST', { ...writeBody, name: 'zzz-filter-alpha-bot' }));+ const bravo = await router.request('/', jsonInit('POST', { ...writeBody, name: 'zzz-filter-bravo-bot' }));+ const other = await router.request('/', jsonInit('POST', { ...writeBody, name: 'zzz-filter-unrelated' }));+ expect(alpha.status).toBe(201);+ expect(bravo.status).toBe(201);+ expect(other.status).toBe(201);++ const matched = await router.request('/?agent_name=FILTER-ALPHA');+ expect(matched.status).toBe(200);+ const matchedBody = ListAgentsResponseSchema.parse(await matched.json());+ expect(matchedBody.data.map(agent => agent.name)).toEqual(['zzz-filter-alpha-bot']);++ const both = await router.request('/?agent_name=zzz-filter');+ expect(both.status).toBe(200);+ const bothBody = ListAgentsResponseSchema.parse(await both.json());+ expect(bothBody.data.map(agent => agent.name)).toEqual([+ 'zzz-filter-alpha-bot',+ 'zzz-filter-bravo-bot',+ 'zzz-filter-unrelated',+ ]);+ });});diff --git a/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts b/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.tsindex 431517368..12c1b1e97 100644--- a/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts+++ b/packages/trueforge/tests/unit/truefoundry/TrueFoundryAgentStore.test.ts@@ -138,17 +138,22 @@ function firstInvocationOrder(mock: jest.Mock): number {describe('TrueFoundryAgentStore', () => {it('listAgents and getAgent pass through to the inner store', async () => {- const agents = [record()];- const listAgents = jest.fn(async () => agents);- const getAgent = jest.fn(async () => agents[0]);+ const listed = { data: [record()], pagination: { limit: 1 } };+ const listAgents = jest.fn(async () => listed);+ const getAgent = jest.fn(async () => listed.data[0]);const store = tfStore({inner: mockInner({ listAgents, getAgent }),client: mockClient(),});- await expect(store.listAgents({ tenant_id: TENANT }, TXN)).resolves.toBe(agents);- await expect(store.getAgent({ tenant_id: TENANT, id: 'agent-1' }, TXN)).resolves.toBe(agents[0]);- expect(listAgents).toHaveBeenCalledWith({ tenant_id: TENANT }, TXN);+ await expect(+ store.listAgents({ tenant_id: TENANT, agent_name: undefined, limit: undefined, page_token: undefined }, TXN),+ ).resolves.toBe(listed);+ await expect(store.getAgent({ tenant_id: TENANT, id: 'agent-1' }, TXN)).resolves.toBe(listed.data[0]);+ expect(listAgents).toHaveBeenCalledWith(+ { tenant_id: TENANT, agent_name: undefined, limit: undefined, page_token: undefined },+ TXN,+ );expect(getAgent).toHaveBeenCalledWith({ tenant_id: TENANT, id: 'agent-1' }, TXN);});